Solution to a problem P2661 [messaging]

This problem because each person can only tell one person, so that each point is 1 degree. Find the smallest ring.

Pit:

FIG communication drawings are not necessarily

Therefore, not only over bfs / dfs.

The following talk about my ideas

三个数组next,vis,dep;
next[i]记录第i位同学传递的人
vis[i]记录当前点是否访问和是哪一次访问
dep[i]记录第i个点在它的访问里的深度
当dfs时出现点已被访问,判断
  • Dfs is currently visited update point then answer
  • else does not consider
#include <cstdio>
using namespace std;
int n,ans;
int vis[200005],dep[200005],next[200005];

int main(){
    ans=1<<17;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&next[i]);
    for(int i=1;i<=n;i++)
        if(vis[i]==0){
            int dfs=0,j;
            for(j=i;vis[j]==0;j=next[j])vis[j]=i,dep[j]=++dfs;
            if(vis[j]==i && dfs-dep[j]<ans)ans=dfs-dep[j];
        }
    printf("%d\n",ans+1);
    return 0;
}

Like it a point

Guess you like

Origin www.cnblogs.com/lzxzy-blog/p/11118363.html