-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSTRINGRA_AUG17.cpp
More file actions
70 lines (66 loc) · 1.97 KB
/
STRINGRA_AUG17.cpp
File metadata and controls
70 lines (66 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// https://www.codechef.com/AUG17/problems/STRINGRA
#include <bits/stdc++.h>
using namespace std;
int main(){
int t,a,b,n,m;
cin>>t;
while(t--){
cin>>n>>m;
vector<int> adj[n+1];
while(m--){
cin>>a>>b;
if(a<b)
adj[a].push_back(b);
}
int s[n+1]={-1,0}, MaxE = adj[0].size();
int firstoccur[MaxE+1];
for(int i=1;i<=MaxE;++i)
firstoccur[i] = INT_MAX;
// for(int i=0 ; i<=n; ++i)
sort(adj[0].begin(),adj[0].end());
for(int i=0; i < adj[0].size(); ++i){
s[adj[0][i]] = i+1;
firstoccur[i+1] = adj[0][i];
}
bool available[MaxE+1];
memset(available, 1 , MaxE+1);
// Main algo starts
for(int i=1;i<n;++i){
int emptyi = -1, toIndex;
if(adj[i].size() > MaxE || adj[i].size() == 0)goto g;
for(int j=0;j<adj[i].size();++j){
toIndex = adj[i][j];
if(s[toIndex] == 0)
if(emptyi == -1)
emptyi = toIndex;
else
goto g;
}
if(emptyi != -1){
for(int k=1;k<=MaxE;++k){
if(available[k] && firstoccur[k]<=i){
s[emptyi] = k;
firstoccur[k] = emptyi;
break;
}
}
}
memset(available, 0 , MaxE+1);
for(int j=0;j<adj[i].size();++j)
available[s[adj[i][j]]]=1;
}
// recheck
for(int i=0;i<=n;++i){
int count = 0;
for(int j = 1; j<=MaxE;++j)
if(firstoccur[j] > i)
++count;
if(count != adj[i].size())
goto g;
}
for(int i=1;i<=n;++i)cout<<s[i]<<' ';cout<<endl;
continue;
g:;
cout<<-1<<endl;
}
}