2013-01-03 22:03:00Morris

[UVA][拓樸排序] 1119 - Project File Dependencies

Project managers, such as the UNIX utility make,are used to maintain large software projects made up frommany components.Users write a project file specifying which components(called tasks) dependon others and the project manager canautomatically update the components in the correct order.

Write a program that reads a project fileand outputs the order in which the tasks should be performed.

Input 

The input begins with a single positive integer on a line by itself indicatingthe number of the cases following, each of them as described below.This line is followed by a blank line, and there is also a blank line betweentwo consecutive inputs.

For simplicity we represent each task by an integer numberfrom 1,2,...,N (where N is the total number of tasks).The first line of input specifies the number N of tasksand the number M of rules,such that N ≤ 100, M ≤ 100.

The rest of the input consists of M rules, one in each line,specifying dependencies using the following syntax:

T0      k      T1     T2      ...     Tk

This rule means that task number T0 depends onk tasks T1, T2, ..., Tk(we say that task T0 is the targetand T1,...,Tk are dependents).

Note that tasks numbers are separated by single spacesand that rules end with a newline.Rules can appear in any order, but each task can appear as targetonly once.

Your program can assume that there are no circular dependencies in therules, i.e. no task depends directly or indirectly on itself.

Output 

For each test case, the output must follow the description below.The outputs of two consecutive cases will be separated by a blank line.

The output should be a single linewith the permutation of the tasks 1 ... N to be performed,ordered by dependencies (i.e. no task should appear before othersthat it depends on).

To avoid ambiguity in the output, tasks that do not depend on eachother should be ordered by their number (lower numbers first).

Sample Input 

15 43 2 1 52 2 5 34 1 35 1 1

Sample Output 

1 5 3 2 4



題目要求一個字典順序的拓樸排序,將 queue 改成 priority_queue 即可。


#include <stdio.h>
#include <queue>
#include <functional>
#include <vector>
using namespace std;

int main() {
priority_queue<int, vector<int>, greater<int> > pQ;
vector<int> g[105];
int t, M, N, indeg[105];
int i, j, x, y, z;
scanf("%d", &t);
while(t--) {
scanf("%d %d", &N, &M);
for(i = 0; i <= N; i++)
g[i].clear(), indeg[i] = 0;
while(M--) {
scanf("%d %d", &x, &z);
while(z--) {
scanf("%d", &y);
g[y].push_back(x);
indeg[x]++;
}
}
for(i = 1; i <= N; i++)
if(indeg[i] == 0)
pQ.push(i);
int tn, flag = 0;
while(!pQ.empty()) {
if(flag) putchar(' ');
flag = 1;
tn = pQ.top(), pQ.pop();
printf("%d", tn);
for(vector<int>::iterator it = g[tn].begin();
it != g[tn].end(); it++)
if(--indeg[*it] == 0)
pQ.push(*it);
}
puts("");
if(t)
puts("");
}
return 0;
}