牛客网 2018校招真题 美团点评 重要节点

Description

牛客网 2018校招真题 重要节点

Solving Ideas

BFS
创建一个标记数组arrivearrive[i][j]true表示从i可以到达j, false则不能

Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;

/**
 * @author wylu
 */
public class Main {
    //arrive[i][j]为true表示从i可以到达j, false则不能
    static boolean[][] arrive;
    static int[] sv;
    static int[] tv;
    static ArrayList<Integer>[] graph;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] strs = br.readLine().split(" ");
        int n = Integer.parseInt(strs[0]), m = Integer.parseInt(strs[1]);
        arrive = new boolean[n + 1][n + 1];
        sv = new int[n + 1];
        tv = new int[n + 1];
        graph = new ArrayList[n + 1];
        for (int i = 1; i <= n; i++) graph[i] = new ArrayList<>();

        for (int i = 0; i < m; i++) {
            strs = br.readLine().split(" ");
            int u = Integer.parseInt(strs[0]), v = Integer.parseInt(strs[1]);
            graph[u].add(v);
        }

        for (int i = 1; i <= n; i++) bfs(i);

        //根据arrive数组计算每个点能达到的点数和能达到每个点的点数
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (arrive[i][j]) {
                    sv[i]++;
                    tv[j]++;
                }
            }
        }

        int res = 0;
        for (int i = 1; i <= n; i++) {
            if (tv[i] > sv[i]) res++;
        }
        System.out.println(res);
    }

    //找出i这个点所能到达的所有点并在arrive数组中进行标记
    private static void bfs(int i) {
        LinkedList<Integer> queue = new LinkedList<>();
        queue.offer(i);
        arrive[i][i] = true;
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            for (Integer e : graph[cur]) {
                if (!arrive[i][e]) {
                    arrive[i][e] = true;
                    queue.offer(e);
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值