AcWing 848.Directly graph's topology sequence (BFS) Described by Java

Cause of this semester we will do the single chip microcomputer, It’s very very difficult, using C to program. I hope I will pass the Exam and Project! And maybe have not a long time to practice, but I will try my best to come on.

This module, said problem is more suitable…
is about the Topology, is just allowed from after going list in graph.
Okey, we can pay attention on the problem.
Problem in AcWing

Thinking is to use the knowledge in Data Structure : Indegree and Outdegree(if u donot know what the damn is, then can google it, very simple. or I can tell u)
Indegree : the number of lines will go to a point.
Outdegree : same , the number of lines will leave from a point.

Use an array to sum the points’ Indegree.To sum all the ways that is topology.
We can see the code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 100010, n, m, idx;
    static int h[] = new int[N], e[] = new int[N], ne[] = new int[N], q[] = new int[N], d[] = new int[N];

    public static void main(String[] args) throws Exception {
        String nm[] = br.readLine().split(" ");
        n = Integer.parseInt(nm[0]);
        m = Integer.parseInt(nm[1]);
        Arrays.fill(h, -1);
        for (int i = 0; i < m; i++) {
            String ss[] = br.readLine().split(" ");
            int a = Integer.parseInt(ss[0]);
            int b = Integer.parseInt(ss[1]);
            add(a, b);
            d[b]++;
        }

        if (topology()) {
            for (int i = 0; i < n; i++) pw.print(q[i] + " ");
        } else pw.println(-1);
        pw.flush();
        br.close();
    }

    private static boolean topology() {
        int hh = 0, tt = -1;
        for (int i = 1; i <= n; i++)
            if (d[i] == 0)
                q[++tt] = i;
        while (hh <= tt) {
            int t = q[hh++];
            for (int i = h[t]; i != -1; i = ne[i]) {
                int j = e[i];
                d[j] --;
                if (d[j] == 0) q[++tt] = j;
            }
        }
        return tt == n - 1;
    }

    private static void add(int a, int b) {
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx++;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值