1133 non-overlapping segments (greedy algorithm, maximum interval not coincident problem)

Source: Internet
Author: User

There are n segments on the x-axis, and each segment has 1 start s and end E. The maximum number of lines that can be selected for each non-overlapping segment. (Note: The start or end point overlaps, not overlapping). For example: [1 5][2 3][3 6], you can choose [2 3][3 6], these 2 line segments do not overlap. Input
Line 1th: 1 number N, number of segments (2 <= n <= 10000) 2-n + 1 lines: 2 numbers per line, start and end of line segments ( -10^9 <= s,e <= 10^9)
Output
Outputs the maximum number of segments that can be selected.
Input example
31 52 33 6
Output example
2 


Code as follows:
#include <cstdio>
#include <algorithm>
# Define MAXN 100010
using namespace std;
struct node
{
 int L, R;
};
BOOL CMP (Node A, Node B)
{
 return A.R < B.R;
}
Node NUM[MAXN];
Int main ()
{
 int n;
 while (scanf ("%d", &n)! = EOF)
 {
  for (int i = 0; i < n; i++)
   sca NF ("%d%d", &NUM[I].L, &NUM[I].R);
  sort (num, num + N, CMP);
  int ans = 0;
  if (n>0)
  {
   ans = 1;
   int temp = NUM[0].R;
   for (int i = 0; i < n;i++)
   if (num[i].l >= temp)
   {
    temp = NUM[I].R;
    ans++;
   }
  }
  printf ("%d\n", ans);
 }
 return 0;
}

1133 non-overlapping segments (greedy algorithm, maximum interval not coincident problem)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.