Title:
There are n items, from which 2*k items are selected, so that the sum of the squares of the difference between the weights of the two items in each group of these k groups is the smallest
answer:
Sort n items first, and try to select an item adjacent to it to pair it.
dp[i][j] means to select i pair from the first j items
Then for the jth item, there are two choices: choose or not, that is, dp[i][j-1] or dp[i-1][j-2]+(a[j]-a[j- 1])^2#include<cstdio> #include<cstring> #include<string> #include<iostream> #include<sstream> #include<algorithm> #include<utility> #include<vector> #include<set> #include<map> #include<queue> #include<cmath> #include<iterator> #include<stack> using namespace std; const int INF=0x3f3f3f3f; const double eps=1e-7; const int mod=1000007; const int maxn=2005; int dp[maxn][maxn]; int a[maxn]; intmain() { int n,k; while(cin>>n>>k) { for(int i=1;i<=n;i++) cin>>a[i]; sort(a+1,a+1+n); memset(dp,INF,sizeof dp);//Indicates that it cannot be reached for(int i=0;i<=n;i++) dp[0][i]=0;//No need to select any items for(int i=1;i<=k;i++) { for(int j=2;j<=n;j++) dp[i][j]=min(dp[i][j-1],dp[i-1][j-2]+(a[j]-a[j-1])*(a[j]-a[j-1])); } cout<<dp[k][n]<<endl; } }