Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
【majuncheng】 AC 码//poj 1015 相当经典的DP题。题意其实就是给一个n个整数的序列(可负),要求取出m个,使得这m个的整数和 //绝对值最小,而且Sum(di)+Sum(pi)最大。而且要求记录最优解的路径。 #include <iostream> #include <algorithm> using namespace std; int n,m; int d[205],p[205]; //本题的整数就是用d[i]-p[i]表示 //dp[i][j][k]记录算到第i个值,已经选j个值,和为k-20*m的最大Sum(di)+Sum(pi)。 //f[i][j][k]记录路径,表示相应的最后一个选的值。 int dp[205][25][40*20+1],f[205][25][40*20+1]; int ans[25]; int main() { int t=0; while (scanf("%d%d",&n,&m) && n+m) { printf("Jury #%d\n",++t); for (int i=1;i<=n;i++) scanf("%d%d",&d[i],&p[i]); memset(dp,-1,sizeof(dp)); memset(f,-1,sizeof(-1)); int zero=20*m,top=40*m; for (int i=0;i<=n;i++) dp[i][0][zero]=0; for (int i=1;i<=n;i++) for (int j=1;j<=m && j<=i;j++) for (int k=0;k<=top;k++) { dp[i][j][k]=dp[i-1][j][k];f[i][j][k]=f[i-1][j][k]; //决策一,不取d[i]-p[i] if ( k>=d[i]-p[i] && k-(d[i]-p[i])<=top && dp[i-1][j-1][k-(d[i]-p[i])]!=-1 && dp[i-1][j-1][k-(d[i]-p[i])]+d[i]+p[i]>=dp[i][j][k]) //决策二,取d[i]-p[i] dp[i][j][k]=dp[i-1][j-1][k-(d[i]-p[i])]+d[i]+p[i],f[i][j][k]=i; } //找到绝对值最小的可行解 int i,j; for (i=zero;i<=top;i++) if (dp[n][m][i]!=-1) break; for (j=zero-1;j>=0;j--) if (dp[n][m][j]!=-1) break; //printf("%d %d\n%d %d\n",i,dp[n][m][i],j,dp[n][m][j]); if (j>=0) if (i>top || i-zero > zero-j || i-zero==zero-j && dp[n][m][i]<dp[n][m][j]) i=j; //按记录的路径往回找,并放入ans中 int c=f[n][m][i],l=0,r=0; for (int k=m;k>=1;k--) { l+=d[c],r+=p[c]; ans[k]=c; i-=(d[c]-p[c]); c=f[c-1][k-1][i]; } printf("Best jury has value %d for prosecution and value %d for defence:\n",l,r); //sort(ans+1,ans+1+m); for (int i=1;i<=m;i++) printf(" %d",ans[i]); printf("\n\n"); } // system("pause"); return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator