zoukankan      html  css  js  c++  java
  • Codeforces Round #595 (Div. 3)B2 简单的dfs

    原题

    https://codeforces.com/contest/1249/problem/B2

    这道题一开始给的数组相当于地图的路标,我们只需对每个没走过的点进行dfs即可

    #include <bits/stdc++.h>

    using namespace std;
    const int maxn=2e5+20;
    int a[maxn],b[maxn],c[maxn];
    int dfs(int pos,int step){//传递坐标与步数
    if(b[pos]==1){//再次遇到b[pos],返回步数+1
    return step+1;
    }
    else{//若没b[pos]==0,则说明没回原位
    b[pos]=1;//标记b[pos]已走过
    c[pos]=dfs(a[pos],step+1);
    return c[pos];
    }
    }
    int main()
    {
    int n,m;
    cin>>n;
    while(n--){
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    memset(c,0,sizeof(c));
    scanf("%d",&m);
    for(int i=1;i<=m;i++){
    cin>>a[i];
    }
    for(int i=1;i<=m;i++){
    if(!b[i]){//若走过b[i],则跳过
    b[i]=1;
    c[i]=dfs(a[i],0);
    }
    }
    for(int i=1;i<=m;i++){
    cout<<c[i]<<" ";
    }
    cout<<endl;
    }
    return 0;
    }

  • 相关阅读:
    POJ 2486
    奇怪的电梯
    穿越泥地(mud)
    救援行动(save)
    As Fast As Possible
    Connecting Universities
    They Are Everywhere
    Cells Not Under Attack
    吃饭
    花店橱窗(flower)
  • 原文地址:https://www.cnblogs.com/ilikeeatfish/p/11760780.html
Copyright © 2011-2022 走看看