组队选拔赛三——E - 链条 HRBUST - 2080 【贪心】

链条
Time Limit: 1000 MS Memory Limit: 32768 K
Total Submit: 161(49 users) Total Accepted: 63(44 users) Rating:  Special Judge: No
Description

给出n对数字,每个对数字由两个数ab构成,其中a<b,现在用一些对拼成最长的链,要使得 b1 < a2, b2 < a3 ... 求最长链的长度。

Input

有多组测试数据。

每组测试数据的第一行有一个数字N(1<=N<=10^5)

接下来有n对数字aibi,数据保证保证ai<bi0<=ai,bi<=10^9

处理到文件结束。

Output

对于每组测试数据输出一行,为最长长度。

Sample Input
5
2 3
0 9
2 8
1 6
0 1
7
5 8
30 93
66 69
17 32
47 72
68 80
23 49
Sample Output
2
3

题目链接:点击打开链接

比赛的时候,我和两个队友碰到这道题当时都是自信满满举得这道题分分钟钟就能过,谁知道这道题从一开始我们的思路就错了,在错误的道路上越行越远,我们当初的思路是:对a排序,然后遍历每个a和a后面的每一个元素,在用一个数组计数然后就TLE了,后来下来仔细一想发现,我们已经保证每一组a<b,然后只要对每一个b有小到大排序,让每一步的b尽量小就可以使其最长了。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
	int a,b;
}temp[1000010];
bool cmp(node x,node y){
	return x.b<y.b;
}
int main(){
	int n;
	while(~scanf("%d",&n)){
		for(int i=0;i<n;i++){
			scanf("%d %d",&temp[i].a,&temp[i].b); 
		}
		sort(temp,temp+n,cmp);
		int ans=temp[0].b;
		int count=1;
		for(int i=1;i<n;i++){
			if(temp[i].a>ans){
				count++;
				ans=temp[i].b;
			}
		}
		printf("%d\n",count);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/xiang_hehe/article/details/80151895
今日推荐