题面
核心思想
建立一个有向图
从c
作为起点dfs 同时做访问标记 时间复杂度o(n)
然后所有访问过的 都是能推导的 时间复杂度o(n)
最终复杂度o(n)
代码
import java.util.*;
public class Main {
static final int MAXN = (int) (1e4 + 10);
static List<Integer>[] next;
static int[] v;
public static void main(String[] args) {
final long MOD = (long) (1e9 + 7);
next = new ArrayList[MAXN];
v = new int[MAXN];
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int c = in.nextInt();
for(int i = 1; i < MAXN; i++){
next[i] = new ArrayList<>();
next[i].add(i);
}
for(int i = 0; i < n; i++){
int x = in.nextInt();
int y = in.nextInt();
next[x].add(y);
}
helper(c);
int cnt = 0;
for(int i = 1; i < MAXN; i++){
if(v[i] == 1)
cnt++;
}
System.out.println(cnt);
}
static void helper(int cur){
v[cur] = 1;
for(int nxt: next[cur]){
if(v[nxt] == 1)
continue;
helper(nxt);
}
}
}
标签:OPPO23,届秋招,int,真题,next,++,MAXN,new,static
From: https://www.cnblogs.com/ganyq/p/18129957