原题链接
- 题意:很多链,然后让每条链中各个元素都要挨在一起,然后给他们每个元素分配层数,层数相同的要以元素大小从左往右。
- 题解:就是两个栈模拟一下贪心即可。
- 代码:
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int N = 1e5 + 9;
int id[N];
int ans[N];
int stk[N];
int Color[N];
int vis[N];
int l[N], r[N];
vector<int> G[N];
signed main() {
int n, m;cin >> n >> m;
int u, v;
for (int i = 1; i <= m; i ++) {
cin >> u >> v;
G[u].push_back(v);
}
int nn = 0;
for (int i = 1; i <= n; i ++) {
if (!vis[i]) {
nn++;
vis[i] = 1;
int u = i;
l[u] = r[u] = 1;
id[u] = nn;
if (G[u].size()) {
while (G[u].size() != 0) {
r[u] = 0;
u = G[u][0];
id[u] = nn;
vis[u] = 1;
r[u] = 1;
}
}
}
}
int top =nn;
for (int i = top, j = 1; i >= 0; i--,j++) {stk[i] = j;}
for (int i = 1; i <= n; i ++) {
if (l[i]) {
//cout << i << "L
";
Color[id[i]] = stk[top--];
}
if (r[i]){
top++;
//cout << i << "R
";
stk[top] = Color[id[i]];
}
ans[i] = Color[id[i]];
}
for (int i = 1; i <= n; i ++) {
cout << ans[i] << " ";
}
}