51Nod non-overlapping segments (greedy)

There are N line segments on the X-axis, and each line segment has a start point S and an end point E. The maximum number of non-overlapping line segments that can be selected. (Note: The starting point or the ending point overlaps, and it is not counted as overlapping).

For example: [1 5][2 3][3 6], you can choose [2 3][3 6], these two line segments do not overlap each other.
Input
Line 1: 1 number N, number of line segments (2 <= N <= 10000)
Lines 2 - N + 1: 2 numbers per line, start and end of the line segment (-10^9 <= S, E <= 10^9)
Output
Output the maximum number of line segments that can be selected.
Input example
3
1 5
2 3
3 6
Output example
2 
After sorting the line segments, the maximum number is that the coordinates of the end point of each line segment are as far to the left as possible, so the greedy solution
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <cassert>
#include <ctime>
#include <map>
#include <set>
using namespace std;
#pragma comment(linker, "/stck:1024000000,1024000000")
#define lowbit(x) (x&(-x))
#define max(x,y) (x>=y?x:y)
#define min(x,y) (x<=y?x:y)
#define MAX 100000000000000000
#define MOD 1000000007
#define pi acos(-1.0)
#define ei exp(1)
#define PI 3.1415926535897932384626433832
#define ios() ios::sync_with_stdio(true)
#define INF 0x3f3f3f3f
#define mem(a) ((a,0,sizeof(a)))
struct node
{
    int u,v;
    bool operator<(const node a)
    {
        return a.u==u?a.v>v:a.u>u;
    }
}e[10006];
int n;
int main()
{
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d%d",&e[i].u,&e[i].v);
    sort(e,e+n);
    int ans=1,mark=e[0].v;
    for(int i=1;i<n;i++)
    {
        if(e[i].u>=mark){ans++,mark=e[i].v;}
        else if(e[i].u<mark && e[i].v<mark) mark=e[i].v;
    }
    printf("%d\n",ans);
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324972865&siteId=291194637