Minimal coverage (greedy, minimum coverage)

 

Subject to the effect: first determine a M, then enter the coordinates of endpoints of left and right ends of the multiple sets of segments, and then you can find out in a given line segments

The [0, M] requires a minimum number of line segments a region completely covered finished, and outputs the coordinates of the left and right segment endpoints.

 

Analysis of ideas:

       The starting point of the line segment is 0, then the starting point to identify all sections of less than optimum interval of 0.

       Because of the need to minimize the interval, the interval select the right end of a larger, more comprising the selected segment.

       If you find understanding in all sections, and the right point less than M, put the right end of the range to find the point as a new starting point of the line segment.

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 
 7 
 8 using namespace std;
 9 
10 struct node
11 {
12     int L, R;
13 }a[100010], b[100010];
14 
15 bool cmp(node a, node b)
16 {
17     return a.R > b.R;
18 }
19 
20 int main() 
21 {
22     int M;
23     while(scanf("%d", &M) != EOF)
24     {
25         int Index = 0;
26         while(1)
27         {
28             scanf("%d%d", &a[Index].L, &a[Index].R);
29             if(a[Index].L == 0 && a[Index].R == 0)
30                 break;
31             ++Index;
32         }
33         
34         sort(a, a+Index, cmp);
35         
36         int border = 0;        // 起始边界点为0 
37         int cnt = 0;
38         while(border < M)
39         {
40             int i = 0;
41             for(; i < Index; ++i)
42             {
43                 // a[i].R >= border提交将会Runtime error 
44                 if(a[i].L <= border && a[i].R > border)
45                 {
46                     b[cnt] = a[i];
47                     cnt++;
48                     border = a[i].R;    // 更新边界点 
49                     break;
50                 }
51             }
52             if(i == Index)
53                 break;
54         }
55         
56         
57         if(border < M)
58             cout << "No solution" << endl;
59         else
60         {
61             cout << cnt << endl;
62             for(int i = 0; i < cnt; ++i)
63                 cout << b[i].L << " " << b[i].R << endl;
64         }
65     }
66             
67     return 0;
68 }

 

Guess you like

Origin www.cnblogs.com/FengZeng666/p/11120095.html
Recommended