题解:AT_abc304_h [ABC304Ex] Constrained Topological Sort
蒟蒻今天刷老师给的图论题单的时候意外自己切了一道紫题,于是来写题解。
我们先观察一下两个限制。
限制一,对于所有
所以限制一就是在告诉我们
限制二,对于所有
code
#include<bits/stdc++.h>
using namespace std;
#define N 200005
int n, m, cnt, l[N], r[N], ind1[N], ind2[N], ans[N];
vector<int> g2[N], g1[N];
struct node{ int x, y; };
inline bool operator <(const node &x, const node &y) { return x.y ^ y.y ? x.y > y.y : x.x > y.x; }
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for(int i = m; i; --i) {
int s, t;
cin >> s >> t;
g1[s].push_back(t), g2[t].push_back(s);
++ind1[t], ++ind2[s];
}
for(int i = 1; i <= n; ++i)
cin >> l[i] >> r[i];
queue<int> q;
for(int i = n; i; --i)
if(!ind2[i]) q.push(i);
while(!q.empty()) {
++cnt;
int aa = q.front();
q.pop();
for(int i = g2[aa].size() - 1; ~i; --i) {
int to = g2[aa][i];
--ind2[to], r[to] = min(r[to], r[aa]);
if(!ind2[to]) q.push(to);
}
}
if(cnt < n) {
puts("No");
return 0;
}
priority_queue<node> q1, q2;
for(int i = n; i; --i)
if(!ind1[i]) q2.push({i, l[i]});
int now = 1;
while(!q1.empty() || !q2.empty()) {
while(!q2.empty()) {
node aa = q2.top();
if(aa.y <= now) {
q2.pop();
q1.push({aa.x, r[aa.x]});
} else break;
}
if(!q1.empty()) {
node aa = q1.top();
q1.pop();
if(r[aa.x] < now) {
cnt = 0;
break;
}
ans[aa.x] = now;
//cout << aa.x << " " << now << endl;
for(int i = g1[aa.x].size() - 1; ~i; --i) {
int to = g1[aa.x][i];
--ind1[to];
if(!ind1[to]) q2.push({to, l[to]});
}
}
++now;
}
if(cnt) {
puts("Yes");
for(int i = 1; i <= n; ++i) printf("%d ", ans[i]);
} else puts("No");
return 0;
}