java | 拓扑排序模版

  • 用队列 + 链式前向星存边,每次删除入度为零的节点,并且更新它的边指向顶点的入度,直到队列为空。
    import java.util.*;
    
    public class model {
        public static int n, count, cnt;
        public static class Edge {
            int to;
            int next;
        }
        public static Edge[] edges;
        public static int[] head, into, sort;
        public static void toposort() {
            cnt = 0;
            Queue<Integer> queue = new ArrayDeque<>();
            //初始化:寻找入度为0的点
            for (int i = 1; i <= n; i += 1) {
                if (into[i] == 0) {
                    queue.offer(i);
                }
            }
            //循环,出队的点删掉边
            while (!queue.isEmpty()) {
                int cur = queue.poll();
                sort[cnt] = cur;
                cnt += 1;
                int index = head[cur];
                while (index != -1) {
                    into[edges[index].to] -= 1;
                    if (into[edges[index].to] == 0) {
                        queue.offer(edges[index].to);
                    }
                    index = edges[index].next;
                }
    
            }
        }
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            n = in.nextInt();
            count = 0;
            edges = new Edge[10000];
            head = new int[n + 1];
            Arrays.fill(head, -1);
            into = new int[n + 1];
            sort = new int[n + 1];
            for (int i = 1; i <= n; i += 1) {
                int to;
                while (true) {
                    to = in.nextInt();
                    if (to == 0) {
                        break;
                    }
                    edges[count] = new Edge();
                    edges[count].to = to;
                    into[to] += 1;
                    edges[count].next = head[i];
                    head[i] = count;
                    count += 1;
                }
            }
            toposort();
            for (int i = 0; i < n; i += 1) {
                System.out.print(sort[i] + " ");
            }
        }
    }
    

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值