推导式(OPPO23届秋招-后端真题)

题面

核心思想

建立一个有向图
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);
        }
        //dfs
        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);
        }
    }
}
posted @ 2024-04-11 20:06  Shie1d  阅读(47)  评论(0)    收藏  举报