题意:给你n个点,m条边的有向无环图,要求给n个点赋值1至n,每条边u->v要求val[u]<val[v]。
思路:跟HDU 4857一样点击打开链接需要反向建图。
正向建图不能保证把把前面的位置尽可能小。
样例:
3 1
3 1
正向建图答案会是:3 1 2,因为一开始2 3点入度为0,把序号1给了2, 把2给了3,1只能是3,所以序列成了3 1 2.
正解应该是:2 1 3
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5+5;
int du[maxn], n, m;
vector<int> g[maxn];
queue<int> qid;
struct node
{
int id, val;
bool operator < (const node &a) const
{
return id < a.id;
}
}a[maxn];
void topSort()
{
priority_queue<int, vector<int>, less<int> > pq;
for(int i = 1; i <= n; i++)
if(!du[i]) pq.push(i);
while(!pq.empty())
{
int u = pq.top(); pq.pop();
qid.push(u);
for(int i = 0; i < g[u].size(); i++)
{
int v = g[u][i];
du[v]--;
if(!du[v])
pq.push(v);
}
}
}
int main(void)
{
while(cin >> n >> m)
{
qid.empty();
memset(du, 0, sizeof(du));
for(int i = 0; i < maxn; i++)
g[i].clear();
while(m--)
{
int x, y;
scanf("%d%d", &x, &y);
swap(x, y);
g[x].push_back(y);
du[y]++;
}
for(int i = 0; i < maxn; i++)
sort(g[i].begin(), g[i].end());
topSort();
int cnt = 0;
while(!qid.empty())
{
int u = qid.front(); qid.pop();
a[cnt].id = u;
a[cnt].val = n-cnt;
cnt++;
}
sort(a, a+cnt);
for(int i = 0; i < cnt; i++)
printf("%d%c", a[i].val, i==cnt-1 ? '\n' : ' ');
}
return 0;
}