【NOIP2015】信息传递

【NOIP2015】信息传递_第1张图片

 数据规模与约定

测试点编号 nn 的规模
1 n200n≤200
2
3
4 n2500n≤2500
5
6
7 n200000n≤200000
8
9
10

时间限制:1s

空间限制:128MB

 

#include 
using namespace std;
#define ll long long
using namespace std;
const int mod = 1e9+7;/// 998244353;
const int mxn = 2e5 +7;
int _,m,n,t,k,ans,cnt,lg;
vector<int>e[mxn];
stack<int>s;
int vis[mxn] , dfn[mxn] , low[mxn] ;
void tarjan(int x)
{
    vis[x] = 1 ; s.push(x);
    low[x] = dfn[x] = cnt++;
    for(int i=0 , v ;i){
        v = e[x][i] ;
        if(!dfn[v]){
            tarjan(v);
            low[x] = min( low[x] , low[v] );
        } else {
            low[x] = min( low[x] , dfn[v] );
        }
    }
    if(dfn[x]==low[x]){
        int res = 0 ;
        while(1){
            int now = s.top(); s.pop();
            vis[now] = 0 ;
            res++;
            if(now==x) break;
        }
        if(res>1) ans = min(res , ans ) ;
    }
}
void solve()
{
    while(cin>>n)
    {
        cnt = 1 ; ans = mod ;
        for(int i=1;i<=n;i++){
            cin>>k;
            e[i].push_back(k);
        }
        for(int i=1;i<=n;i++){
            if(!vis[i]){
                tarjan(i);
            }
        }
        cout<< ans <<endl;
    }
}
int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    solve();
}
View Code

 

你可能感兴趣的:(【NOIP2015】信息传递)