1. 程式人生 > >hdu-6301-貪心

hdu-6301-貪心

arch xtra ret sin title elements php continue earch

Distinct Values

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2822 Accepted Submission(s): 904


Problem Description Chiaki has an array of n positive integers. You are told some facts about the array: for every two elements ai and aj in the subarray al..r
(li<jr), aiajholds.
Chiaki would like to find a lexicographically minimal array which meets the facts.

Input There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first line contains two integers n and m (1n,m105
) -- the length of the array and the number of facts. Each of the next m lines contains two integers li and ri (1lirin).

It is guaranteed that neither the sum of all n nor the sum of all m exceeds 106.

Output For each test case, output n integers denoting the lexicographically minimal array. Integers should be separated by a single space, and no extra spaces are allowed at the end of lines.

Sample Input 3 2 1 1 2 4 2 1 2 3 4 5 2 1 3 2 4

Sample Output 1 2 1 2 1 2 1 2 3 1 1

Source 2018 Multi-University Training Contest 1

  比賽時候想到了用set找,又感覺復雜度爆炸,下來想想的話,每個點最多進出一次所以O(N*log(N))還是ok的。

就是排序區間然後枚舉所有區間,一段一段的填充,要維護一個set表示當前區間段內所有能寫入的數。還要記錄下上一個區間。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 struct node{
 4     int l,r;
 5 }A[100010];
 6 int a[100010];
 7 bool cmp(node A,node B){
 8     if(A.l!=B.l) return A.l<B.l;
 9     return A.r>B.r;
10 }
11 set<int>S;
12 set<int>::iterator it;
13 int main(){
14     int t,n,m,i,j,k;
15     cin>>t;
16     while(t--){
17         S.clear();
18         memset(a,0,sizeof(a));
19         scanf("%d%d",&n,&m);
20         for(i=1;i<=n;++i) S.insert(i);
21         for(i=1;i<=m;++i) scanf("%d%d",&A[i].l,&A[i].r);
22         sort(A+1,A+1+m,cmp);
23         int l=A[1].l,r=A[1].r;
24         for(i=l,j=1;i<=r;++i,++j) a[i]=j,S.erase(j);
25         for(i=2;i<=m;++i){
26             if(A[i].r<=r) continue;
27             if(A[i].l>r){
28                 for(j=l;j<=r;++j) S.insert(a[j]);
29                 for(j=A[i].l;j<=A[i].r;++j){
30                     a[j]=*S.begin();
31                     S.erase(a[j]);
32                 }
33                 l=A[i].l,r=A[i].r;
34             }
35             else{
36                 for(j=l;j<A[i].l;++j) S.insert(a[j]);
37                 for(j=r+1;j<=A[i].r;++j){
38                     a[j]=*S.begin();
39                     S.erase(a[j]);
40                 }
41                 l=A[i].l,r=A[i].r;
42             }
43         }
44         for(i=1;i<=n;++i) printf("%d%c",a[i]==0?1:a[i],i==n?\n: );
45     }
46     return 0;
47 }

hdu-6301-貪心