洛谷 P3916 图的遍历

洛谷 P3916 图的遍历

Description

  • 给出N个点,M条边的有向图,对于每个点v,求A(v)表示从点v出发,能到达的编号最大的点。

Input

  • 第1 行,2 个整数N,M。

    接下来M行,每行2个整数Ui,Vi,表示边(Ui,Vi)。点用1,2,⋯,N编号。

Output

  • N 个整数A(1),A(2),⋯,A(N)

Sample Input

4 3
1 2
2 4
4 3

Sample Output

4 4 3 4

题解:

  • 写这题时没有看出反向建边,而是一眼秒出是缩点。
  • 想着练练手,打了一个缩点的模版上去切了这道题。
  • 思路就是缩完点后跑一遍DAG。用dfs的跑法比拓扑好写
#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;
}

猜你喜欢

转载自www.cnblogs.com/BigYellowDog/p/11229349.html