Minimal coverage (贪心,最小覆盖)
生活随笔
收集整理的這篇文章主要介紹了
Minimal coverage (贪心,最小覆盖)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
題目大意:先確定一個(gè)M, 然后輸入多組線段的左端和右端的端點(diǎn)坐標(biāo),然后讓你求出來在所給的線段中能夠
把[0, M]?區(qū)域完全覆蓋完的最少需要的線段數(shù),并輸出這些線段的左右端點(diǎn)坐標(biāo)。
?
思路分析:
? ? ? ?線段區(qū)間的起點(diǎn)是0,那么找出所有區(qū)間起點(diǎn)小于0中的最合適的區(qū)間。
? ? ? ?因?yàn)樾枰M量少的區(qū)間,所以選擇右端點(diǎn)更大的區(qū)間,它包含所選線段更大。
? ? ? ?如果在所有區(qū)間中找到了解,且右端點(diǎn)小于M,則把找到的區(qū)間的右端點(diǎn)定為新的線段區(qū)間的起點(diǎn)。
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; // 起始邊界點(diǎn)為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提交將會(huì)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; // 更新邊界點(diǎn) 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 }?
轉(zhuǎn)載于:https://www.cnblogs.com/FengZeng666/p/11120095.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Minimal coverage (贪心,最小覆盖)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python初学者必须了解的星号(*)9
- 下一篇: Kafka2.0生产者客户端使用