標籤:des style blog http color strong
1089:Intervals
總時間限制: 1000ms 記憶體限制: 65536kB描述There is given the series of n closed intervals [ai; b i], where i=1,2,...,n. The sum of those intervals may berepresented as a sum of closed pairwise non−intersecting intervals. The task is to find such representation with the minimal number of intervals. The intervals of this representation should be written in the output file in acceding order. We say that the intervals [a; b] and [c; d] are in ascending order if, and only if a <= b < c <= d.TaskWrite a program which:.reads from the std input the description of the series of intervals,.computes pairwise non−intersecting intervals satisfying the conditions given above, .writes the computed intervals in ascending order into std output輸入In the first line of input there is one integer n, 3 <= n <= 50000. This is the number of intervals. In the (i+1)−st line, 1 <= i <= n, there is a description of the interval [ai; bi] in the form of two integers ai and bi separated by a single space, which are respectively the beginning and the end of the interval,1 <= ai <= bi <= 1000000.輸出The output should contain descriptions of all computed pairwise non−intersecting intervals. In each line should be written a description of one interval. It should be composed of two integers, separated by a single space, the beginning and the end of the interval respectively. The intervals should be written into the output in ascending order.範例輸入55 61 410 106 98 10範例輸出1 45 10
這道題做的時候真是無語了。。。。
這幾天做的線段樹的題太多了,導致特麼一看到線段區間什麼的,第一時間就想到線段樹來解。。。結果寫了一個小時,覺得不對勁,1000000個葉子節點的樹的資料大小。。。光是建樹估計花的時間就逾時了。。。最開始想的方法是建樹,再用consult來查詢是否被覆蓋,並根據左端點來排序,用二分來找出剛好被覆蓋到的滿足條件的最大的右端點。。。
快寫哭了。。。實在沒信心寫不下去了,百度了一下諸位大俠的寫法,才發現自己簡直蠢到家了。。。
最後解法:
直接簡單地根據左端點由小到大排好序,然後遍曆過去就OK了,並把重疊的合在一起,直到發現並沒有交叉的區間,然後輸出之前的區間,最後把最後一次的區間輸出就好了。
代碼:
1 #include <iostream> 2 #include <stdio.h> 3 #include <algorithm> 4 5 using namespace std; 6 7 struct P 8 { 9 int l;10 int r;11 }p[50001];12 13 bool cmp(const P& a,const P& b)14 {15 return a.l < b.l;16 }17 18 int main()19 {20 int n;21 scanf("%d",&n);22 for (int i = 0; i < n; ++i)23 {24 scanf("%d%d",&p[i].l,&p[i].r);25 }26 sort(p,p+n,cmp);27 int x = p[0].l,y = p[0].r;28 for(int i = 0; i < n; ++i)29 {30 if(p[i].l >= x && p[i].l <=y)31 {32 if(p[i].r > y)33 y = p[i].r;34 }35 else36 {37 printf("%d %d\n",x,y);38 x = p[i].l;39 y = p[i].r;40 }41 }42 printf("%d %d\n",x,y);43 return 0;44 }View Code