关于贪心中的结构体排序:
世界杯来了,球迷的节日也来了,估计很多ACMer也会抛开电脑,奔向电视了。
作为球迷,一定想看尽量多的完整的比赛,当然,作为新时代的好青年,你一定还会看一些其它的节目,比如新闻联播(永远不要忘记关心国家大事)、非常6+7、超级女生,以及王小丫的《开心辞典》等等,假设你已经知道了所有你喜欢看的电视节目的转播时间表,你会合理安排吗?(目标是能看尽量多的完整节目)
输入
输入数据包含多个测试实例,每个测试实例的第一行只有一个整数n(n < = 100),表示你喜欢看的节目的总数,然后是n行数据,每行包括两个数据Ti_s,Ti_e (1 < = i < = n),分别表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。n=0 表示输入结束,不做处理。
输出
对于每个测试实例,输出能完整看到的电视节目的个数,每个测试实例的输出占一行。
样例输入
12
1 3
3 4
0 7
3 8
15 19
15 20
10 15
8 18
6 12
5 10
4 14
2 9
0
样例输出
5
AC代码:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string.h>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#define max1 1000
using namespace std;
struct movie
{
int begin;
int end;
}m[1000];
bool cmp(movie a,movie b)
{
return a.end < b.end;
}
int main()
{
int n;
while(cin >> n && n)
{
for(int k = 0;k < n;k++)
{
cin >> m[k].begin >> m[k].end;
}
sort(m,m + n,cmp);
int i = 1;
int h = m[0].end;
for(int k = 1;k < n;k++)
{
if(h <= m[k].begin)
{
i++;
h = m[k].end;
}
}
cout << i << endl;
}
}
好不容易做出了陶陶抢苹果!
关于结构体小应用还是挺有用的;
举个栗子!
Problem 1228
Description
输入n(n <= 100)个整数,按照绝对值从大到小的顺序输出。
Input
输入数据有多组,每组占一行,每行的第一个数字为n,接着是n个整数。n=0表示输入数据的结束,不做处理。输入的数据保证对于每一个测试实例,所有的数的绝对值都不相等。
Output
对于每个测试实例,输出排序后的结果,两个数之间用一个空格隔开。每个测试实例占一行。
Sample Input
3 3 -4 2
4 0 1 2 -3
0
Sample Output
-4 3 2
-3 2 1 0
此时就需要吧原来的数表示出来而不是绝对值之后的数字!
源代码:
#include <iostream>
#include <algorithm>
#include <math.h>
#include <cmath>
using namespace std;
struct ju
{
int who[15];
}juedui[1000];
bool cmp(ju a,ju b)
{
return fabs(a.who[1]) > fabs(b.who[1]);
}
int main()
{
int n;
while(cin >> n && n)
{
for(int k = 0;k < n;k++)
{
cin >> juedui[k].who[1];
}
sort(juedui, juedui + n, cmp);
for(int k = 0;k < n;k++)
{
cout << juedui[k].who[1] << " ";
}
cout << endl;
}
}
而此时sort排序结构体需要构造它的思想;用bool来实现;
举第二个栗子:
陶陶抢苹果!
Description
又到了收获的季节,树上结了许多陶陶,错了,是许多苹果,有很多个小陶陶都来摘苹果。每个陶陶都想要最大的苹果,所以发生了争执,为了解决他们的矛盾,出题人定了一项特殊的规则,按体重的大小来定顺序,每一轮都是先由胖的先摘(照顾胖子),每个陶陶都是很聪明的,不会错过眼前最大的苹果。现在问题来了,一共有n个苹果,m个陶陶,要你按原顺序输出每个陶陶可以抢到的苹果的总大小。
Input
第一行两个数n、m(n,m < = 100000)。
第二行n个数,分别为每个苹果的大小。
第三行m个数,分别为每个陶陶的体重。
Output
每行m个数,分别是每个陶陶抢到的苹果的大小。
Sample Input
5 3
1 2 3 4 5
1 2 3
Sample Output
3 5 7
代码:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string.h>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#define max1 1000
using namespace std;
int apple[100000 + 5];
struct dd
{
int start;//记录刚开始的人的顺序
int people;//记录体重
int eat = 0;//抢的苹果
}taotao[100000 + 5];
bool cmp(dd a,dd b)
{
return a.people > b.people;
}
bool cmp1(dd a,dd b)
{
return a.start < b.start;
}
int main()
{
int n, m;
cin >> n >> m;
for(int k = 0;k < n;k++)
{
cin >> apple[k];
}
for(int k = 0;k < m;k++)
{
cin >> taotao[k].people;
taotao[k].start = k;//这段是为了标记刚开始的人顺序
}
sort(apple,apple + n,greater<int>());
sort(taotao,taotao + m,cmp);
int i = 0;
for(int k = 0;k < n;k++)
{
taotao[i].eat += apple[k];
i++;
if(i == m)
{
i = 0;
}
}
sort(taotao,taotao + m,cmp1);//恢复刚开始人的顺序
for(int k = 0;k < m;k++)
{
cout << taotao[k].eat << " ";
}
}
还有两个星期选拔赛了!!冲鸭!!!