http://blog.csdn.net/acm_cxlove/article/details/7964594
http://www.tuicool.com/articles/jyaQ7n
http://blog.csdn.net/woshi250hua/article/details/7973824
记忆化搜索(15MS):
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <cctype> #include <vector> #include <iterator> #include <set> #include <map> #include <sstream> using namespace std; #define mem(a,b) memset(a,b,sizeof(a)) #define pf printf #define sf scanf #define spf sprintf #define pb push_back #define debug printf("!\n") #define INF 10000 #define MAX(a,b) a>b?a:b #define blank pf("\n") #define LL long long #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) #define pqueue priority_queue const int MAXN = 1000 + 5; int n,m; int dp[110][110]; int a[110],sum[110]; int solve(int i,int j) { int& ans = dp[i][j]; if(ans!=-1) return ans; if(i>=j) return 0; ans = 1<<30; for(int k = 1;k<=j-i+1;k++) { ans = min(ans,solve(i+1,i+k-1)+solve(i+k,j) + (k-1)*a[i] + (sum[j]-sum[i+k-1])*k); } return ans; } int main() { int i,j; int t; cin>>t; while(t--) { cin>>n; sum[0]=0; for(i=1;i<=n;i++) { sf("%d",&a[i]); sum[i]=sum[i-1]+a[i]; } mem(dp,-1); pf("%d\n",solve(1,n)); } return 0; }
递推:
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <cctype> #include <vector> #include <iterator> #include <set> #include <map> #include <sstream> using namespace std; #define mem(a,b) memset(a,b,sizeof(a)) #define pf printf #define sf scanf #define spf sprintf #define pb push_back #define debug printf("!\n") #define INF 10000 #define MAX(a,b) a>b?a:b #define blank pf("\n") #define LL long long #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) #define pqueue priority_queue const int MAXN = 1000 + 5; int n,m; int dp[110][110]; int a[110],sum[110]; int main() { int i,j; int t; cin>>t; while(t--) { cin>>n; sum[0]=0; for(i=1;i<=n;i++) { sf("%d",&a[i]); sum[i]=sum[i-1]+a[i]; } mem(dp,0); for(int l = 1;l<=n;l++) { for(i=1;i<=n-l+1;i++) { j = i+l-1; dp[i][j] = 1<<30; for(int k = 1;k<=l;k++) { dp[i][j] = min(dp[i][j],dp[i+1][i+k-1] + dp[i+k][j] + (k-1)*a[i] + (sum[j]-sum[i+k-1])*k); } } } pf("%d\n",dp[1][n]); } return 0; }
时间: 2024-10-30 08:49:52