[ACM]积木分发
Time Limit: 1000MS Memory Limit: 65535KB
Total Submissions: 539 Accepted: 52
Description:
歌手Pancakes到幼儿园跟小朋友玩,她到达的时候小朋友们正在争积木,小朋友都想要更多的积木砌一个自己喜欢的图形,砌完就可以和Pancakes合照。
同时,Pancakes手上还有一些积木,她可以把手上的这些积木全部给一个小朋友,然后等该小朋友砌完后就可以收回所发的积木和该小朋友原先手上的积木。
但她不知道能否让所有的小朋友都和她合照,聪明的你可以帮助她么?
Input:
输入包括多个数据。
每个数据的第1行是两个正整数n和s,n的范围是[1,10000], s的范围是[1,10000],表示一共有n位小朋友,Pancakes手上有s块积木。以下有n行,每行有2个正整数,a和b,a和b的范围是[1,10^9],表示第i个小朋友手上有a块积木,还需要b块积木才能够砌完。
输入n=0时表示结束。
Output:
如果可以让所有小朋友都合照,就输出"YES",否则,输出"NO"。
Sample Input:
2 2
1 4
2 1
2 2
1 4
1 1
0 0
Sample Output:
YES
NO
Hint:
Source:
GDCPC
解答:
此题相对来说比较简单,只要找大一个小孩需要积木数少于歌手手里的积木数就可以给他,然后就可以收回给的积木数,并获得小孩手里的积木。此题并不需要去贪心,否则可能造成超时。代码如下:
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
struct child
{
int own;
int less;
};
int child_cmp(const child& a, const child& b)
{
return a.less < b.less;
}
int main()
{
int n, s, i, can;
vector<child>::iterator it;
while(1)
{
scanf("%d%d", &n, &s);
if(n == 0)
break;
vector<child> cls;
for(i = 0; i < n; i ++)
{
child x;
scanf("%d%d", &x.own, &x.less);
cls.push_back(x);
}
can = true;
make_heap(cls.begin(), cls.end(), child_cmp);
sort_heap(cls.begin(), cls.end(), child_cmp);
for(it = cls.begin(); it != cls.end(); it ++)
{
if(it->less <= s)
s += it->own;
else
{
can = false;
break;
}
}
if(can)
printf("YES ");
else
printf("NO ");
}
return 0;
}
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
struct child
{
int own;
int less;
};
int child_cmp(const child& a, const child& b)
{
return a.less < b.less;
}
int main()
{
int n, s, i, can;
vector<child>::iterator it;
while(1)
{
scanf("%d%d", &n, &s);
if(n == 0)
break;
vector<child> cls;
for(i = 0; i < n; i ++)
{
child x;
scanf("%d%d", &x.own, &x.less);
cls.push_back(x);
}
can = true;
make_heap(cls.begin(), cls.end(), child_cmp);
sort_heap(cls.begin(), cls.end(), child_cmp);
for(it = cls.begin(); it != cls.end(); it ++)
{
if(it->less <= s)
s += it->own;
else
{
can = false;
break;
}
}
if(can)
printf("YES ");
else
printf("NO ");
}
return 0;
}
代码中用到了结构体,可能影响速度,可以改成两个数组来提高速度。排序算法用的也是系统的堆排序。
本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名小橋流水(包含链接)。如您有任何疑问或者授权方面的协商,请给我发邮件。