CodeForces

题意:给出一个n个点有向图,问是否存在三个点,这三个点构成一个回路。n<=5000

模拟即可。

注意是必须三个点 多了居然不行。

 1 import java.util.*;
 2 public class Main {
 3 
 4     public static final int maxn = 5000;
 5     public static int [] v = new int [maxn+10];
 6     public static int [] f = new int [maxn+10];
 7     
 8     public static int DFS(int x, int t) {
 9         if (v[x]>0) return t - v[x];
10         v[x] = t;
11         int k = DFS(f[x], t+1);
12         v[x] = 0;
13         return k;
14     }
15     public static void main(String[] args) {
16         Scanner input = new Scanner(System.in);
17         int n = input.nextInt();
18         
19         
20         for (int i = 1; i<=n; i++) f[i] = input.nextInt();
21         boolean flag = true;
22         for (int i = 1; i<=n; i++) {
23             if (3 == DFS(i, 1)) {
24                 System.out.println("YES");
25                 flag = false;
26                 break;
27             }
28         }
29         if(flag) System.out.println("NO");
30         input.close();
31     }
32 
33 }
原文地址:https://www.cnblogs.com/NeoLCX/p/8762444.html