http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=234 http://acm.hdu.edu.cn/showproblem.php?pid=1500
#include<iostream> using namespace std; long dp[5001][1009];//dp[i][j]表示从第i个筷子到第n个筷子中取j对的最优值 int main() { long t,k,n,i,j; scanf("%ld",&t); while(t--) { long chopsticks[5001],num[5001]; //cin>>k>>n; scanf("%ld%ld",&k,&n); k += 8; for(i=1;i<=n;i++) scanf("%ld",&chopsticks[i]);
for(i=1;i<n;i++) num[i] = (chopsticks[i+1] - chopsticks[i]) * (chopsticks[i+1] - chopsticks[i]);
for(i=0;i<=n;i++) for(j=0;j<=k;j++) dp[i][j] = 1024000000;//初值一定要足够大
for(i=0;i<=n;i++)//取0对筷子 dp[i][0] = 0; for(i=n-2;i>=1;i--)//从后往前 { for(j=1;3*j<=(n-i+1);j++) { dp[i][j] = dp[i+1][j]; if(dp[i][j] > dp[i+2][j-1] + num[i]) dp[i][j] = dp[i+2][j-1] + num[i]; } } //cout<<dp[1][k]<<endl; printf("%ld\n",dp[1][k]); } return 0; }
|