L3-001 Collect change (30 points): 0-1 backpack, find the smallest sequence that meets the conditions

Han Meimei likes shopping around the universe. Now she wandered to a Mars shop and found that this shop has a special rule: You can pay with coins from any planet, but you never get change, and of course you can't owe debts. Han Meimei has 104 coins from various planets in hand. I need to ask you to help her figure out whether it is possible to make up the exact amount to be paid.

Input format:
Enter two positive integers in the first line: N (≤10​4​​) is the total number of coins, and M (≤10​2​​) is the amount to be paid by Han Meimei. The second line gives the positive integer denominations of N coins. The numbers are separated by spaces.

Output format:
output the face value of the coin V​1​​ ≤V​2​​ ≤...≤V​k​​ in one line, meeting the condition V​1​​ +V​2​​ +…+V​k​ =M. The numbers are separated by 1 space, and there must be no extra spaces at the beginning and end of the line. If the solution is not unique, the smallest sequence is output. If there is no solution, output No Solution.

Note: We say that the sequence {A[1],A[2],...} is "smaller" than {B[1],B[2],... }, which means that there is k≥1 such that A[i]=B[ i] holds for all i<k, and A[k]<B[k].

Input example 1:
8 9
5 9 8 7 2 3 4 1
Output example 1:
1 3 5
Input example 2:
4 8
7 2 4 3
Output example 2:
No Solution

#include <bits/stdc++.h>
using namespace std;
#define ll long long
int a[10010],b[11000],vis[10010][11000],n,m;
void cou()
{
    
    
	int bo=0,tip=1,ans=m;
	while(ans)
	{
    
    
		if(vis[tip][ans])
		{
    
    
			if(bo) cout<<" ";
			cout<<a[tip];bo=1;
			ans-=a[tip],tip++;
		}
		while(vis[tip][ans]==0&&tip<=n)
		 tip++;
	}
}
int main()
{
    
    
    ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
     cin>>a[i];
    sort(a+1,a+n+1);
	for(int i=n;i>=1;i--)
	{
    
    
	 for(int j=m;j>=a[i];j--)
	  if(b[j]<=b[j-a[i]]+a[i])
	  {
    
    
	  	b[j]=b[j-a[i]]+a[i];
	  	vis[i][j]=1;
	  }
	} 
	if(b[m]==m) cou();
	else cout<<"No Solution";
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43540515/article/details/110219739