java有向图_AcWing 848. 有向图的拓扑序列-java

import java.util.*;

import java.io.*;

class Main {

static int n,m;

//稀疏图,邻接表存储

static int idx;

static int[] h = new int[100010];

static int[] e = new int[200010];

static int[] ne = new int[200010];

static {

Arrays.fill(h,-1);

Arrays.fill(e,-1);

Arrays.fill(ne,-1);

}

//存储点的入度

static int[] v = new int[100010];

//队列

static int[] queue = new int[100010];

static int head, tail;

static void insert(int x, int y) {

e[idx] = y;

ne[idx] = h[x];

v[y]++;

h[x] = idx++;

}

static boolean topSort() {

//入度为0全部加入队列

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

if (v[i] == 0) queue[tail++] = i;

while (tail > head) {

int x = queue[head++];

for (int i = h[x]; i!=-1; i=ne[i]) {

int y = e[i];

v[y]--;

if (v[y] == 0) queue[tail++] = y;

}

if (tail == n) return true;

}

return false;

}

public static void main(String[] args) throws IOException {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader in = new BufferedReader(isr);

String[] strs = in.readLine().split(" ");

n = Integer.parseInt(strs[0]);

m = Integer.parseInt(strs[1]);

for (int i = 0; i < m; i++) {

strs = in.readLine().split(" ");

int a = Integer.parseInt(strs[0]);

int b = Integer.parseInt(strs[1]);

insert(a,b);

}

in.close();

isr.close();

OutputStreamWriter osw = new OutputStreamWriter(System.out);

BufferedWriter out = new BufferedWriter(osw);

if (topSort())

for (int i = 0; i < n; i++) out.write(queue[i]+" ");

else

out.write("-1");

out.flush();

out.close();

osw.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值