题解:dp求出(sum(a[i]) - V)%K的方案,那么剩下的数就能凑成V%K的方案数。但是只有合并没有分离dp是求不出方案数的,但是答案却是有方案的。这个特殊判断(先全部合并然后再分开)
例子:
6 11 3
6 6 6 6 6 6
#include"bits/stdc++.h"
using namespace std;
int n,K,V;
const int MX = 5e3+7;
int a[MX],dp[MX][MX];
short int last[MX][MX];
bool vis[MX][MX],sign[MX];
vector<int>ans;
struct node{
int x,y,num;
node(){}
node(int x, int y, int num) : x(x), y(y), num(num) {}
}res[MX];
int main(){
scanf("%d%d%d",&n,&K,&V);
int sum = 0;
for(int i = 1; i <= n; i++){
scanf("%d",&a[i]);
sum += a[i];
}
int tmpv = (sum-V)%K;
if(sum < V){
printf("NO");
return 0;
}
int x = 0, y = tmpv;
memset(dp,-1,sizeof(dp));
dp[0][0] = 0;
for(int i = 1; i <= n; i++){
for(int j = 0; j < K; j++) if(dp[i-1][j] >= 0){
int nxt = (j+a[i])%K;
if(dp[i-1][j] + a[i] > dp[i][nxt]){
dp[i][nxt] = dp[i-1][j] + a[i];
last[i][nxt] = j;
vis[i][nxt] = 1;
}
if(dp[i-1][j] > dp[i][j]) {
dp[i][j] = dp[i-1][j];
last[i][j] = j;
vis[i][j] = 0;
}
}
if(dp[i][y] > 0) x = i;
}
int num = V-sum;
for(; x >= 1; x--){
if(vis[x][y] && a[x] > 0) num += a[x], ans.push_back(x), sign[x] = 1;
y = last[x][y];
}
if(ans.empty()){
int cnt = 0, cc = -1;
for(int i = 2; i <= n; i++)
if(a[i] > 0) res[++cnt] = node(i,1,a[i]/K + (a[i]%K? 1 : 0));
if(V%K == 0) cc = V/K;
if((sum-V)%K == 0) cc = (sum-V)/K;
if(cc >= 0) {
if(cc > 0 && a[1] > 0) res[++cnt] = node(1,n,cc);
printf("YES\n");
for(int i = 1; i <= cnt; i++)
printf("%d %d %d\n",res[i].num, res[i].x, res[i].y);
return 0;
}
printf("NO");
return 0;
}
int cnt = 0, id = 0;
for(int i = 1; i < ans.size(); i++) {
int y = ans[i];
id = y;
res[++cnt] = node(y, ans[0], a[y]/K + ((a[y]%K)? 1 : 0) );
}
for(int i = 1; i <= n; i++) if(!sign[i]){
if(id == 0) id = i;
if(id == i) continue;
if(a[i] > 0) res[++cnt] = node(i, id, a[i]/K + (a[i]%K? 1 : 0));
}
if(num > 0) res[++cnt] = node(ans[0],id,num/K);
else if(num < 0) res[++cnt] = node(id,ans[0],-num/K);
printf("YES\n");
for(int i = 1; i <= cnt; i++)
printf("%d %d %d\n",res[i].num, res[i].x, res[i].y);
return 0;
}