【算法设计与分析】The Dragon of Loowater
来源:互联网 发布:minecraft mac 启动器 编辑:程序博客网 时间:2024/05/17 17:17
【题目】
【输入输出要求】
【输出样例】
【程序代码】
<span style="font-family:Microsoft YaHei;font-size:18px;">#include<stdio.h>#include<algorithm>#define N 2000#define M 2000int main(){ int n,m; int a[N];//怪兽头的半径 int b[M];//骑士的能力值 while(scanf("%d%d",&n,&m)==2&&(n+m!=0)) { for(int i=0;i<n;i++)//输入怪兽头的半径 scanf("%d",&a[i]); for(int j=0;j<m;j++)//输入骑士的能力值 scanf("%d",&b[j]); if(n>m)//如果怪兽头的半径数量大于骑士的个数,则无解 printf("Loowater is doomed!\n"); else { std::sort(b,b+m);//将怪兽头的半径和骑士能力分别从小到大排列 std::sort(a,a+n); int s=0;//最终金币数 int head=0;//记录可以被其实解决的怪兽头的数目 for(int i=0,j=0;i<n&&j<m;) if(a[i]<=b[i])//如果怪兽头的半径小于骑士能力 { s+=b[i]; i++; j++; head++; } else j++; if(head<n)//最终还剩下怪兽头不能被砍掉 printf("Loowater is doomed!\n"); else printf("%d\n",s); } } return 0;}</span>
【简要分析】
首先需要注意一个问题,我们需要求得是总金币数量最少,那么就需要在满足条件的前提下,每一次使用的金币数都尽量的少,每一步最优,最后结果才最优,这就是贪婪算法的一个问题了。
这里骑士和怪兽头的数量上首先应该满足骑士的人数多于怪兽,其次是能力值和怪兽头的半径的配对,要满足能力值大于半径,又要满足金币值最小,那么我们将怪兽头的半径和骑士能力值按照从小到大的顺序sort一遍就可以,按照顺序为每一个怪兽头寻找能力值匹配的骑士即可,不相匹配就相下寻找,直到找不到为止。
这个问题很简单,只要明白是贪婪问题,每一步最优,学会使用sort即可。
0 0
- 【算法设计与分析】The Dragon of Loowater
- The Dragon of Loowater
- The Dragon of Loowater
- The Dragon of Loowater
- The Dragon of Loowater
- The Dragon of Loowater
- The Dragon of Loowater
- UVA11292 The Dragon of Loowater
- UVA11292-The Dragon of Loowater
- HDU The Dragon of Loowater
- poj3646 The Dragon of Loowater
- The Dragon of Loowater(poj3646)
- ZOJ3646 The Dragon of Loowater
- Uva11292 The Dragon of Loowater
- uva11292 The Dragon of Loowater
- UVA11292 The Dragon of Loowater
- HOJ 2620 The Dragon of Loowater
- UVa 11292 - The Dragon of Loowater
- PhpStorm/IDEA/clion/pycharm 的破解与激活
- Android综合项目乐学成语
- Android学习笔记--基础知识
- solr和lucene历史版本地址
- 用R语言进行中文分词
- 【算法设计与分析】The Dragon of Loowater
- codeforces 656b Scrambled
- LeetCode总结,位运算总结(该)
- WebView详解
- leetcode 209. Minimum Size Subarray Sum-子序列最小长度|双指针|二分查找
- python参数规则
- 递归复制文件
- MongoDB学习
- python递归目录子目录列出目录和文件