hdu 2660 Accepted Necklace(简单DFS)
Problem Description
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.
Input
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, 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.
Output
For each case, output the highest possible value of the necklace.
Sample Input
1
2 1
1 1
1 1
3
Sample Output
1
刚开始就隐隐约约是贪心了,读完题目觉得可能是个复杂的dp,可是数据N小于等于20,呵呵,用暴力之王DFS就搞定了!
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 #define N 25 6 int v[N],w[N]; 7 int n,m; 8 int lim; 9 int sum; 10 void DFS(int a,int b,int c,int d)//a 当前价值 b当前重量 c已经采用的宝石 遍历到的宝石下标 11 { 12 if(b>lim)//如果重量超过了限制 13 return ; 14 if(c>m)//如果采用的宝石超过了限制返回 15 return ; 16 int rest=0; 17 for(int i=d;i<n;i++) 18 rest+=v[i]; 19 if(a+rest<sum)//优化一下 15ms变0ms 20 return ; 21 if(sum<a) 22 { 23 sum=a; 24 } 25 int j; 26 for(j=d;j<n;j++) 27 { 28 DFS(a+v[j],b+w[j],c+1,j+1); 29 } 30 } 31 int main() 32 { 33 int t; 34 scanf("%d",&t); 35 while(t--) 36 { 37 memset(v,0,sizeof(v)); 38 memset(w,0,sizeof(w)); 39 scanf("%d%d",&n,&m); 40 int i; 41 for(i=0;i<n;i++) 42 scanf("%d%d",&v[i],&w[i]); 43 scanf("%d",&lim); 44 sum=0; 45 DFS(0,0,0,0); 46 printf("%d\n",sum); 47 } 48 return 0; 49 }
标签:
DFS
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?