本来只是想刷一下题,没想到提交了三遍才过。0 0的情景应该放到while里去做,分而治之,高度自治,软件工程的东西代码里也是一样的,这样才能有条理,才能更高效。
sort方法捡一下。
本题是典型的贪心,每次找能满足需要的最少花费的勇士来杀,则最终的结果肯定是最优的!
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int MAX_SIZE=20000;
int main()
{
int n,m;
int heads[MAX_SIZE],soldiers[MAX_SIZE];
while(scanf("%d%d",&n,&m)==2)
{
if(n==0 && m==0)break;
for(int i = 0; i < n; i++)cin>>heads[i];
for(int i = 0; i < m; i++)cin >> soldiers[i];
sort(heads,heads+n);
sort(soldiers,soldiers+m);
int h_pos = 0,s_pos = 0;//heads和soldiers的数组当前位置
int count = 0;
while(h_pos < n && s_pos < m )
{
if(heads[h_pos] <= soldiers[s_pos])
{
count += soldiers[s_pos];
h_pos++;
s_pos++;
}
else
{
s_pos++;
}
}
if(h_pos == n)cout << count<<"\n";
else cout<<"Loowater is doomed!\n";
}
return 0;
}