I have N precious stones, and plan to use K of them to make a necklace for my mother, but she won't accept a necklace which is too heavy. Given the value and the weight of each precious stone, please help me find out the most valuable necklace my mother will accept.
The first line of input is the number of cases. For each case, the first line contains two integers N (N <= 20), the total number of stones, and K (K <= N), the exact number of stones to make a necklace. Then N lines follow, each containing two integers: a (a<=1000), representing the value of each precious stone, and b (b<=1000), its weight. The last line of each case contains an integer W, the maximum weight my mother will accept, W <= 1000.
For each case, output the highest possible value of the necklace.
1 2 1 1 1 1 1 3
1
for(int i=cur;i<n;i++){
if(!vis[i]){
vis[i]=1;
dfs(i,num+1,weight+w[i],value+v[i]);
vis[i]=0;
}
}
这里一开写的是for(int i=cur+1;i<n;i++)就错了,改成for(int i=cur;i<n;i++)就莫名其妙地A了。
1 #pragma comment(linker, "/STACK:1024000000,1024000000") 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 #include<cmath> 6 #include<math.h> 7 #include<algorithm> 8 #include<queue> 9 #include<set> 10 #include<bitset> 11 #include<map> 12 #include<vector> 13 #include<stdlib.h> 14 #include <stack> 15 using namespace std; 16 #define PI acos(-1.0) 17 #define max(a,b) (a) > (b) ? (a) : (b) 18 #define min(a,b) (a) < (b) ? (a) : (b) 19 #define ll long long 20 #define eps 1e-10 21 #define MOD 1000000007 22 #define N 26 23 #define inf 1<<26 24 int n,k,total; 25 int ans; 26 int v[N]; 27 int w[N]; 28 int vis[N]; 29 void dfs(int cur,int num,int weight,int value){ 30 if(weight>total){ 31 return; 32 } 33 int sum=0; 34 for(int i=cur+1;i<n;i++){ 35 sum+=v[i]; 36 } 37 if(value+sum<ans){ 38 return; 39 } 40 if(num==k){ 41 ans=max(ans,value); 42 return; 43 } 44 for(int i=cur;i<n;i++){ 45 if(!vis[i]){ 46 vis[i]=1; 47 dfs(i,num+1,weight+w[i],value+v[i]); 48 vis[i]=0; 49 } 50 } 51 } 52 int main() 53 { 54 int t; 55 scanf("%d",&t); 56 while(t--){ 57 scanf("%d%d",&n,&k); 58 for(int i=0;i<n;i++){ 59 scanf("%d%d",&v[i],&w[i]); 60 } 61 scanf("%d",&total); 62 memset(vis,0,sizeof(vis)); 63 ans=-inf; 64 dfs(0,0,0,0); 65 printf("%d\n",ans); 66 } 67 return 0; 68 }