Thereare V tasks to do. Some task(s) can begin only after a particular task ends,which we will call precedence relation. A graph indicating precedence relationof tasks is given. In this graph, each task is denoted as vertex, and the precedencerelation as directed edge. Note there is no cycle with this graph (cycle refers to a path that starts from one vertex and returns to the same vertex). The graph below is one example of such graph.
In this graph, task 1 can start after task 4 ends and task 6can when task 5 and task 7 end; there is no cycle with this graph.
Manager Kim is going to finish a set of tasks having precedencerelation by taking care of one task at a time. If he is going to do this withthe set of tasks illustrated above, the tasks can be handled with the followingorder.
8, 9, 4, 1, 5, 2, 3, 7, 6
And the order below is also possible.
4, 1, 2, 3, 8, 5, 7, 6, 9
But, the order below is not possible.
4, 1, 5, 2, 3, 7, 6, 8, 9
[Input/output example]
Input
9 9 ← Test case 1 starts 4 1 1 2 2 3 2 7 5 6 7 6 1 5 8 5 8 9 5 4 ← Test case 2 starts 1 2 2 3 4 1 1 5 ... |
Output(consisting of 10 lines in total)
#1 8 9 4 1 5 2 3 7 6 #2 4 1 2 3 5 ... |
public class Solution {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int T;
T = sc.nextInt();
for (int t = 1; t <= T; t++) {
sc.nextLine();
String line1 = sc.nextLine();
String line2 = sc.nextLine();
String ans = orderTask(line1, line2);
StringBuilder sb = new StringBuilder();
sb.append("#").append(t).append(" ").append(ans);
System.out.println(sb);
}
sc.close();
}
private static String orderTask(String line1, String line2) {
String[] parts1 = line1.split(" ");
int v = Integer.parseInt(parts1[0]); // 节点数量
int e = Integer.parseInt(parts1[1]); // 边数量
String[] edges = line2.split(" ");
boolean[] visited = new boolean[v + 1]; // 访问标记数组
Arrays.fill(visited, false);
LinkedList<Integer>[] arr = new LinkedList[v + 1]; // 邻接表
// 初始化数组中的每个链表
for (int i = 0; i <= v; i++) {
arr[i] = new LinkedList<>();
}
int[] in_degree = new int[v + 1]; // 入度
Arrays.fill(in_degree, 0);
for (int i = 0; i < edges.length; i += 2) {
int x = Integer.parseInt(edges[i]); // 边的第一个端点
int y = Integer.parseInt(edges[i + 1]); // 边的第二个端点
arr[y].add(x);
// 增加目标顶点的入度
in_degree[y]++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < v; i++) {
int index = 0;
for (int j = 1; j <= v; j++) { // 找到一个入度为0的点
if (in_degree[j] == 0 && visited[j] == false) {
visited[j] = true;
index = j;
sb.append(j).append(" ");
break;
}
}
// 遍历找到父节点为index的节点,入度 -1
for (int k = 1; k <= v; k++) {
if (arr[k].contains(index) && visited[k] == false) {
in_degree[k]--;
}
}
}
return sb.toString().trim();
}
}
标签:task,int,graph,vertex,tasks,new,机试,Order
From: https://blog.csdn.net/Mr__________xiao/article/details/140425711