这道题只要状态一想出来,这题就做完了。
另 dp[i][j] 表示 i 首歌音量 j 能否达到,则如果dp[i - 1][j] = 1,那么dp[i][j + c[i]] = dp[i][j - c[i]] = 1.然后最后从Max到0反向遍历dp[n][i]即可。
注意这题数组要开2e3,否则因为j + c[i]数组越界造成了一些诡异的错误,导致我第一次交WA了三个点。
1 #include<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #include<cstdlib> 7 #include<cctype> 8 #include<vector> 9 #include<stack> 10 #include<queue> 11 using namespace std; 12 #define enter printf("\n") 13 #define space printf(" ") 14 #define Mem(a) memset(a, 0, sizeof(a)) 15 typedef long long ll; 16 typedef double db; 17 const int INF = 0x3f3f3f3f; 18 const int eps = 1e-8; 19 const int maxn = 55; 20 const int max_size = 2e3 + 5; 21 inline ll read() 22 { 23 ll ans = 0; 24 char ch = getchar(), last = ' '; 25 while(!isdigit(ch)) {last = ch; ch = getchar();} 26 while(isdigit(ch)) {ans = ans * 10 + ch - '0'; ch = getchar();} 27 if(last == '-') ans = -ans; 28 return ans; 29 } 30 inline void write(ll x) 31 { 32 if(x < 0) x = -x, putchar('-'); 33 if(x >= 10) write(x / 10); 34 putchar(x % 10 + '0'); 35 } 36 37 int n, Beg, Max, a[maxn]; 38 bool dp[maxn][max_size]; 39 40 int main() 41 { 42 n = read(); Beg = read(), Max = read(); 43 for(int i = 1; i <= n; ++i) a[i] = read(); 44 dp[0][Beg] = 1; 45 for(int i = 1; i <= n; ++i) 46 for(int j = 0; j <= Max; ++j) 47 if(dp[i - 1][j]) dp[i][j + a[i]] = dp[i][j - a[i]] = 1; 48 for(int i = Max; i >= 0; --i) if(dp[n][i]) {write(i); enter; return 0;} 49 write(-1); enter; 50 return 0; 51 }