Los traverse the valley P3916 map
Description
- N points are given, directed edges of the map M, for each point v, seeking A (v) represents from the point of v, the maximum number of points can be reached.
Input
Line 1, two integers N, M.
Next M rows, each row two integers Ui, Vi, expressed edge (Ui, Vi). Point with 1,2, ⋯, N number.
Output
- N integers A (1), A (2), ⋯, A (N)
Sample Input
4 3
1 2
2 4
4 3
Sample Output
4 4 3 4
answer:
- We did not see the reverse side of the construction time of writing this question, but one second a point is shrinking.
- Thinking practice your hand, I hit a template shrink up point cut this question.
- The idea is to shrink after the completion point run again DAG. With dfs run method is better than writing topology
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#define N 100005
using namespace std;
struct E {int next, to;} e[N];
int n, m, num;
int h[N], dp[N], u[N], v[N];
int dex, tot;
int low[N], dfn[N], obj[N], bel[N];
bool vis[N];
stack<int> stk;
int read()
{
int x = 0; char c = getchar();
while(c < '0' || c > '9') c = getchar();
while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
return x;
}
void add(int u, int v)
{
e[++num].next = h[u];
e[num].to = v;
h[u] = num;
}
void tarjan(int x)
{
low[x] = dfn[x] = ++dex;
stk.push(x), vis[x] = 1;
for(int i = h[x]; i != 0; i = e[i].next)
{
int now = e[i].to;
if(!dfn[now])
tarjan(now),
low[x] = min(low[x], low[now]);
else if(vis[now])
low[x] = min(low[x], dfn[now]);
}
if(low[x] == dfn[x])
{
tot++;
while(1)
{
int now = stk.top();
stk.pop(), vis[now] = 0;
obj[tot] = max(obj[tot], now);
bel[now] = tot;
if(now == x) break;
}
}
}
void dfs(int x)
{
if(dp[x]) return;
dp[x] = obj[x];
for(int i = h[x]; i != 0; i = e[i].next)
{
dfs(e[i].to);
dp[x] = max(dp[x], dp[e[i].to]);
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i++)
{
u[i] = read(), v[i] = read();
add(u[i], v[i]);
}
for(int i = 1; i <= n; i++)
if(!dfn[i]) tarjan(i);
num = 0;
memset(h, 0, sizeof(h));
for(int i = 1; i <= m; i++)
if(bel[u[i]] != bel[v[i]])
add(bel[u[i]], bel[v[i]]);
for(int i = 1; i <= tot; i++)
if(!dp[i]) dfs(i);
for(int i = 1; i <= n; i++) printf("%d ", dp[bel[i]]);
return 0;
}