ZOJ-3197(最小区间覆盖)

Google Book

Time Limit: 1 Second      Memory Limit: 32768 KB

You, the best hacker in the world, want to download the books published on Google Book. After some investigation, you found that the address of each page consists of two parts. The first part is the page number, the second part is the signature which is unique for each page. To get the signature, you can send the query to the server. The query has one parameter, which indicates the page number. The server will return the signature of the required page, and it may also return the signature of some adjacent pages.

To minimize the bytes downloaded from the internet, and also make the server adminstrator hard to notice your "hack", you'd like to minimize the number of queries

Input

The input has multiple cases.
The first line of the input is a single integer T which is the number of test cases. Then T consecutive test cases follow. In each test case, the first line is a number N (1<=N<=5000), indicating the number of pages of the book. Then n lines follows. On the i-th line, there will be two integers ai and bi (ai<=i<=bi). They indicate that the query for the i-th page will return the signatures from page ai to page bi (inclusive)

Output

Results should be directed to standard output. The output of each test case should be a single integer, which is the minimum number of queries to get all the signatures.

Sample Input

2
3
1 1
2 2
3 3
3
1 1
1 3
3 3

Sample Output

3
1

题意:有n页书,有n个区间,问最少选几个区间能把这本书从1到n页都覆盖。
思路:最小区间覆盖。
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 
 5 using namespace std;
 6 
 7 #define maxn 5010
 8 
 9 int t, n;
10 //区间结点
11 struct node{
12     int a, b;
13 }no[maxn];
14 
15 //将区间节点左端点按从小到大顺序排列
16 bool cmp(const node& no1, const node& no2){
17     return no1.a < no2.a;
18 }
19 
20 //将区间节点左端点按从小到大顺序排序,相同左端点时,按右端点从大到小排列
21 bool cmp2(const node& no1, const node& no2){
22     if(no1.a != no2.a) return no1.a < no2.a;
23     return no1.b > no2.b;
24 }
25 
26 //最小区间覆盖
27 int least_cover(){
28     sort(no, no+n, cmp);
29 
30     int result = 0;
31     //初始化,保证r比所有区间右端点小
32     int l = no[0].a, r = -1;
33     //计算所选区间个数的循环,一旦所选区间右端点超过覆盖区域右端点则停止
34     for (int i = 0; i < n && r < n; ){
35         //找出能够覆盖未被覆盖的点的最长区间
36         while(no[i].a <= l && i < n){
37             if(no[i].b > r) r = no[i].b;
38             i++;
39         }
40         //计数
41         result++;
42         //下一个未被覆盖的点
43         l = r + 1;
44     }
45     return result;
46 }
47 
48 int main()
49 {
50     scanf("%d", &t);
51     while(t--){
52         scanf("%d", &n);
53         for (int i = 0; i <n; i++){
54             scanf("%d%d", &no[i].a, &no[i].b);
55         }
56         printf("%d\n", least_cover());
57     }
58     return 0;
59 }

 

posted @ 2016-02-23 12:42  喷水小火龙  阅读(110)  评论(0)    收藏  举报