1244. GentlemenTime limit: 0.5 second
Memory limit: 64 MB Let's remember one old joke:
Once a gentleman said to another gentleman:
— What if we play cards? — You know, I haven't played cards for ten years… — And I haven't played for fifteen years… So, little by little, they decided to resurrect their youth. The first gentleman asked a servant to bring a pack of cards, and before starting playing out weighed in his hand the pack. — It seems to me, one card is missing from the pack… — he said and gave the pack to the other gentleman. — Yes, the nine of spades, — the man agreed. An incomplete pack of cards is given. The program should determine which cards are missing.
InputThe first line contains a positive integer, which is the weight in milligrams of the given incomplete pack. The second line contains an integer N, 2 ≤ N ≤ 100 — the number of cards in the complete pack. In the next N lines there are integers from 1 to 1000, which are the weights of the cards in milligrams. It's guaranteed that the total weight of all cards in the complete pack is strictly greater than the weight of the incomplete pack.
OutputIf there is no solution, then output the single number 0. If there are more than one solutions, then you should write −1. Finally, if it is possible to determine unambiguously which cards are missing in the incomplete pack as compared to the complete one, then output the numbers of the missing cards separated with a space in ascending order.
Samples
|
感觉URAL上的题目都很好。
题意:给你一些背包的体积,问能不能拿一些背包,使得总容量为m
若不能,输出0
若有多种拿的组合,输出-1
若只有一种方式,按升序输出哪些背包是不需要拿的,输出编号。
刚开始用DFS,tle了。
用DP时,这种记录路径的方式我是看了网上的题解的,真的是很漂亮。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 5 using namespace std; 6 7 const int maxn=105; 8 const int inf=0x3f3f3f3f; 9 10 int dp[100010]; //存储体积为j时拿到的背包体积 11 int a[maxn]; //存储每一个背包的容量 12 int flag[100010]; //flag[j]表示体积从0到j有多少条路径 13 int pre[100010]; //用于记录路径 14 int ans[100010]; //记录路径时要用到 15 16 int main() 17 { 18 int m,n; 19 while(scanf("%d%d",&m,&n)!=EOF) 20 { 21 for(int i=1;i<=n;i++) 22 scanf("%d",&a[i]); 23 for(int i=1;i<=m;i++) 24 dp[i]=inf; //初始化 25 memset(flag,0,sizeof(flag)); 26 flag[0]=1; //从0到0有1条路径 27 for(int i=1;i<=n;i++) 28 { 29 for(int j=m;j>=a[i];j--) 30 { 31 if(dp[j]>dp[j-a[i]]+a[i]) 32 { 33 dp[j]=dp[j-a[i]]+a[i]; 34 pre[j]=i; 35 } 36 if(dp[j]==dp[j-a[i]]+a[i]) 37 { 38 flag[j]+=flag[j-a[i]]; //看这里 39 } 40 } 41 } 42 if(dp[m]!=m) 43 printf("0 "); 44 else if(flag[m]>1) 45 printf("-1 "); 46 else 47 { 48 memset(ans,0,sizeof(ans)); 49 while(m) 50 { 51 ans[pre[m]]=1; 52 m-=a[pre[m]]; 53 } 54 int first=0; 55 for(int i=1;i<=n;i++) 56 { 57 if(!ans[i]) 58 { 59 if(first) 60 printf(" "); 61 first++; 62 printf("%d",i); 63 } 64 } 65 printf(" "); 66 } 67 } 68 return 0; 69 }