标签:des style blog http color io os java ar
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17687 Accepted Submission(s): 6000
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<iostream> 5 using namespace std; 6 const int maxn=2002; 7 const int inf=0x3f3f3f3f; 8 int aa[maxn],dp[maxn][maxn]; 9 int n,k; 10 int main() 11 { 12 while(scanf("%d%d",&n,&k)!=EOF) 13 { 14 for(int i=1;i<=n;i++) 15 scanf("%d",aa+i); 16 sort(aa+1,aa+n+1); 17 for(int i=1;i<=n;i++) 18 { 19 for(int j=1;j<=k;j++) 20 dp[i][j]=inf; 21 } 22 dp[0][0]=0; 23 for(int i=2;i<=n;i++) 24 { 25 for(int j=1;2*j<=i;j++){ 26 dp[i][j]=min(dp[i-1][j],dp[i-2][j-1]+(aa[i]-aa[i-1])*(aa[i]-aa[i-1])); 27 } 28 } 29 printf("%d\n",dp[n][k]); 30 } 31 return 0; 32 }
对其进行优化,压缩空间由于只涉及到dp[i-1],dp[i-2],dp[i];所以舍去其他空间
代码:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<iostream> 5 using namespace std; 6 const int maxn=2002; 7 const int inf=0x3f3f3f3f; 8 int aa[maxn],dp[3][maxn]; 9 int n,k; 10 int main() 11 { 12 while(scanf("%d%d",&n,&k)!=EOF) 13 { 14 for(int i=1;i<=n;i++) 15 scanf("%d",aa+i); 16 sort(aa+1,aa+n+1); 17 for(int i=0;i<=2;i++) 18 { 19 for(int j=1;j<=k;j++) 20 dp[i][j]=inf; 21 } 22 dp[0][0]=0; 23 for(int i=2;i<=n;i++) 24 { 25 for(int j=1;2*j<=i;j++){ 26 dp[i%3][j]=min(dp[(i-1)%3][j],dp[(i-2)%3][j-1]+(aa[i]-aa[i-1])*(aa[i]-aa[i-1])); 27 } 28 } 29 printf("%d\n",dp[n%3][k]); 30 } 31 return 0; 32 }
标签:des style blog http color io os java ar
原文地址:http://www.cnblogs.com/gongxijun/p/3993559.html