PAT.A1068 Find More Coins

Back to ContentsInsert picture description here

Title

There are N coins, and the value of each coin is given. Now it is necessary to use these coins to pay for the value of M. Ask if such a solution can be found so that the sum of the values ​​of the coins selected for payment is exactly M. If it does not exist, output No Solution; if it exists, select the value of the coins used for payment from small to large. If there are multiple solutions, output the one with the smallest lexicographic order. The so-called lexicographical order refers to: there are two schemes: {A [1], A [2], ...} and {B [1], B [2], ... If k≥1, for any i <k has A []-B [question, and A [k] <B [k] holds, then the lexicographic order of scheme A is smaller than that of scheme B.

Sample (can be copied)

8 9
5 9 8 7 2 3 4 1
//output
1 3 5
4 8
7 2 4 3
//output
No Solution

important point

  1. This problem uses dynamic programming, the problem is 0-1 backpack problem
#include <bits/stdc++.h>
using namespace std;

int w[10010],dp[110]={0};
bool cho[10011][110],flag[10011];//cho[i][v]用来记录dp[i][v]时选择的策略,flag[i]用来存放第i号物品是否选择
bool cmp(int a,int b){
	return a>b;
}
int main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)scanf("%d",&w[i]);
    sort(w+1,w+n+1,cmp);
    for(int i=1;i<=n;i++){
    	for(int v=m;v>=w[i];v--){
    		if(dp[v]<=dp[v-w[i]]+w[i]){//放入
    			dp[v]=dp[v-w[i]]+w[i];
    			cho[i][v]=1;
			}else{//不放入
				cho[i][v]=0;
			}
		}
	}
	if(dp[m]!=m)cout<<"No Solution";
	else{
		int k=n,num=0;//num记录选择的总数
		while(k>=0){
			if(cho[k][v]==1){
				flag[k]=true;
				m-=w[k];
				num++;
			}else{
				flag[k]=false;
			}
			k--;
		}
		for(int i=n;i>=1;i--){
			if(flag[i]){
				printf("%d",w[i]);
				num--;
				if(num>0)printf(" ");
			}
		}
	}
	return 0;
}
Published 177 original articles · won praise 5 · Views 6645

Guess you like

Origin blog.csdn.net/a1920993165/article/details/105595058