1. 程式人生 > >luogu P1063 能量項鍊 區間dp

luogu P1063 能量項鍊 區間dp

傳送門

我才不會說我這個題D了好久

區間dp可是一大騙分利器

要寫熟練

如果第一層迴圈要列舉長度真的不如記搜

Time cost: 25min

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<queue>
 6 #include<vector>
 7 #define ms(a,b) memset(a,b,sizeof a)
 8 #define rep(i,a,n) for(int i = a;i <= n;i++)
 9
#define per(i,n,a) for(int i = n;i >= a;i--) 10 #define inf 2147483647 11 using namespace std; 12 typedef long long ll; 13 ll read() { 14 ll as = 0,fu = 1; 15 char c = getchar(); 16 while(c < '0' || c > '9') { 17 if(c == '-') fu = -1; 18 c = getchar(); 19 } 20 while
(c >= '0' && c <= '9') { 21 as = as * 10 + c - '0'; 22 c = getchar(); 23 } 24 return as * fu; 25 } 26 const int N = 105; 27 //head 28 29 int n; 30 int a[N<<1]; 31 int dp[N<<1][N<<1],maxx; 32 //[l,r) 33 int dfs(int l,int r) { 34 if(r - l < 2) return
0; 35 if(dp[l][r]) return dp[l][r]; 36 rep(i,l+1,r-1) { 37 dp[l][r] = max(dp[l][r],dfs(l,i) + dfs(i,r) + a[l] * a[i] * a[r]); 38 } 39 return dp[l][r]; 40 } 41 42 int main() { 43 n = read(); 44 rep(i,1,n) a[i] = read(); 45 rep(i,1,n) a[i+n] = a[i]; 46 dfs(1,n<<1); 47 rep(i,1,n) maxx = max(maxx,dp[i][i+n]); 48 printf("%d\n",maxx); 49 return 0; 50 }
View Code

迴圈

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<queue>
 6 #include<vector>
 7 #define ms(a,b) memset(a,b,sizeof a)
 8 #define rep(i,a,n) for(int i = a;i <= n;i++)
 9 #define per(i,n,a) for(int i = n;i >= a;i--)
10 #define inf 2147483647
11 using namespace std;
12 typedef long long ll;
13 ll read() {
14     ll as = 0,fu = 1;
15     char c = getchar();
16     while(c < '0' || c > '9') {
17         if(c == '-') fu = -1;
18         c = getchar();
19     }
20     while(c >= '0' && c <= '9') {
21         as = as * 10 + c - '0';
22         c = getchar();
23     }
24     return as * fu;
25 }
26 const int N = 1005;
27 //head
28 int n,maxx;
29 int a[N];
30 int dp[N][N];
31 int main() {
32     n = read();
33     rep(i,1,n) a[i] = a[i+n] = read();
34 //    rep(i,1,n<<1) printf("%d ",a[i]);puts("");
35     rep(i,2,n+1) {
36         rep(l,1,n*2-i+1) {
37             int r = l+i-1;
38             rep(k,l+1,r-1)
39                  dp[l][r] = max(dp[l][r],dp[l][k] + dp[k][r] + a[l]*a[k]*a[r]);
40 //            printf("%d %d %d\n",l,r,dp[l][r]);
41         }
42     }
43     maxx = 0;
44     rep(i,1,n) maxx = max(maxx,dp[i][n+i]);
45     printf("%d\n",maxx);
46 }
View Code

 

不得不說這種簡單題樣例真的良心