hdoj5124lines【贪心 or 离散化】

来源:互联网 发布:药品网络经营许可证 编辑:程序博客网 时间:2024/06/05 00:28



lines

Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1364    Accepted Submission(s): 567


Problem Description
John has several lines. The lines are covered on the X axis. Let A is a point which is covered by the most lines. John wants to know how many lines cover A.
 

Input
The first line contains a single integer T(1T100)(the data for N>100 less than 11 cases),indicating the number of test cases.
Each test case begins with an integer N(1N105),indicating the number of lines.
Next N lines contains two integers Xi and Yi(1XiYi109),describing a line.
 

Output
For each case, output an integer means how many lines cover A.
 

Sample Input
251 2 2 22 43 45 100051 12 23 34 45 5
 

Sample Output
31
 

Source
BestCoder Round #20
 

题意:给出一些线段求一个被线段覆盖最多的点的覆盖线段数

可以用离散化做但离散化还不知道怎么做此题也可以用贪心做

贪心思路是把一条线段拆成两个点后排序,那么此时当前位置如果遇到一个起点,那么被覆盖的线段数要+1,遇到终点就是一条线段完结了被覆盖的数量-1,找出过程中的最大值即可。

#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>using namespace std;const int maxn=100010;int s[maxn];int e[maxn];bool cmp(int a,int b){    return a<b;}int MAX(int a,int b){    return a>b?a:b;}int main(){    int t,i,j,k,n;    scanf("%d",&t);    while(t--){        scanf("%d",&n);        for(i=0;i<n;++i){            scanf("%d%d",&s[i],&e[i]);        }        sort(s,s+n,cmp);        sort(e,e+n,cmp);        int ans=0,temp=0,x=0,y=0;        while(x<n){            if(s[x]<=e[y]){                temp++;x++;            }            else {                temp--;y++;            }            ans=MAX(ans,temp);        }        printf("%d\n",ans);    }    return 0;} 
0 0
原创粉丝点击