3 solutions

  • 1
    @ 2025-10-9 15:44:20
    #include <iostream>
    #include <vector>
    #include <cstring>
    using namespace std;
    
    const int MAX = 200050;
    int c[MAX], p[MAX], n, m, q, x;
    bool vis[MAX];
    
    int dfs(int u) {
        if (vis[c[u]]) return 1;
        vis[c[u]] = true;
        return 1 + dfs(p[u]);
    }
    
    int main() {
        ios::sync_with_stdio(0);
        cin.tie(0);
        
        cin >> n >> m;
        for (int i = 1; i <= n; i++) cin >> c[i];
        for (int i = 1; i <= n; i++) cin >> p[i];
        
        cin >> q;
        while (q--) {
            cin >> x;
            memset(vis, 0, sizeof(vis));
            cout << dfs(x) << '\n';
        }
    }
    
    
    • 0
      @ 2025-7-25 14:54:54
      #include <bits/stdc++.h>
      using namespace std;
      int n,m,c[200050],p[200050],q,x,ans;
      bool tong[200050];
      void dfs(int t){
          ans++;
          if(tong[c[t]]){
              return ;
          }
          tong[c[t]]=1;
          dfs(p[t]);
      }
      int main(){
          cin>>n>>m;
          for(int i=1;i<=n;i++){
              cin>>c[i];
          }
          for(int i=1;i<=n;i++){
              cin>>p[i];
          }
          cin>>q;
          for(int i=1;i<=q;i++){
              cin>>x;
              for(int j=1;j<=m;j++){
                  tong[j]=0;
              }
              ans=0;
              dfs(x);
              cout<<ans<<endl;
          }
          return 0;
      }
      
      • 0
        @ 2024-10-11 10:48:55

        image

        • 1

        Information

        ID
        573
        Time
        2000ms
        Memory
        512MiB
        Difficulty
        10
        Tags
        (None)
        # Submissions
        8
        Accepted
        3
        Uploaded By