【Codeforces 350B】Resort

【链接】 我是链接,点我呀:)
【题意】

【题解】

我们可以把原图的边都反向一下. 然后以每个休息点作为起点,进行dfs. 每次在扩展节点y的时候,要求这个点y必须只有一个出度,然后就能走多远就走多远就ok了。 会发现每个休息点占据的那些链都是唯一的,所以其他的休息点在进行dfs的时候,不会重复走到其他休息点dfs过的点。 因此这样dfs的复杂度是O(N)的。 随便搞搞,更新一下最大值就ok了。

【代码】

#include <bits/stdc++.h>
#define rep1(i,a,b) for (int i = a;i <= b;i++)
using namespace std;

const int N = 1e5;

int n,m;
int a[N+10],ans = 0,s;
vector<int> g1[N+10],g2[N+10];

void dfs(int x,int dep){
    if (dep>ans){
        ans = dep;
        s = x;
    }
    for (int y:g2[x]){
        if (a[y]==1) continue;
        if ((int)g1[y].size()>1) continue;
        dfs(y,dep+1);
    }
}

int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin >> n;
    rep1(i,1,n) cin >> a[i];
    rep1(i,1,n){
        int x,y;
        cin >> x;
        y = i;
        if(x==0) continue;
        g1[x].push_back(y);
        g2[y].push_back(x);
    }
    rep1(i,1,n)
        if(a[i]==1) dfs(i,1);
    cout<<ans<<endl;
    int x = s;
    while(1){
        cout<<x<<' ';
        if (a[x]==1) break;
        x = g1[x][0];
    }
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/9742213.html