小Y上学记——修学分(拓扑排序)

来源:互联网 发布:c语言标识符命名规则 编辑:程序博客网 时间:2024/04/27 21:54

A - 小Y上学记——修学分

Time Limit: 2000/1000MS (Java/Others)    Memory Limit: 128000/64000KB (Java/Others)
Submit Status

Problem Description

小Y终于如愿以偿地通过高考来到了魂牵梦萦的大学校园——ACdream大学。来到校园的第一件事就是选课。

由于每一门课都有1个学分~而且有一些课需要先学完别的课程(例如必须先学会高等数学,才能学会量子力学,必须先学会走,才能学会跑)

ACdream大学需要学生修够若干学分才允许毕业。

请按顺序输出小Y的一种方案(若不止一种答案,请输出字典序最小的一种方案)

Input

多组数据,每组数据首先是两个整数n,m,k,分别表示学科总数,学科之间的关系数,以及毕业所需的最少学分。

(2<=n<=100, 0<=m<=500,1<=k<=n)

接下来是m行,每行是两个整数a,b表示学科a是学科b的前置学科。

Output

对于每组数据,若小Y不存在任何方案选课,请输出-1.

否则在一行输出m个整数,表示小Y按顺序修的学科编号。

Sample Input

2 1 20 12 2 21 00 13 2 11 00 13 0 3

Sample Output

0 1-120 1 2

Hint

对于第一组数据,先修完第0学科,获得1学分,再修以第0学科为前置学科的第1学科,获得1学分,即可满足毕业条件:2学分。

对于第二组数据,由于第0学科的前置学科为第1学科,而第1学科的前置学科为第2学科,因此小Y无论如何也无法满足毕业条件。

对于第三组数据,由于多了第2学科,而且第2学科不需要前置学科,因此只需要修完第2学科即可满足毕业条件了。

对于第四组数据,没有任何的先后限制,因此6种全排列方案均符合题意,字典序最小的方案为0,1,2



题目大意:小Y要选课来使自己能够毕业。有的课必须要先修完其他课才能修。求出字典序最小的一种方案。


分析:拓扑排序稍微变形下。


代码:

#include <cstdio>#include <vector>#include <queue>#include <cstring>#include <algorithm>using namespace std;const int maxn = 110;vector <int> g[maxn];int du[maxn], n, m, k, L[maxn];bool toposort() {    memset(du, 0, sizeof(du));    for(int i = 0; i < n; i++)        for(int j = 0; j < g[i].size(); j++)            du[g[i][j]]++;    int tot = 0;    priority_queue <int, vector<int>, greater<int> > Q;    for(int i = 0; i < n; i++)        if(!du[i]) Q.push(i);    while(!Q.empty()) {        int x = Q.top();        Q.pop();        L[tot++] = x;        for(int j = 0; j < g[x].size(); j++) {            int t = g[x][j];            du[t]--;            if(!du[t])                Q.push(t);        }    }    if(tot >= k) return 1;    return 0;}int main() {    while(~scanf("%d%d%d", &n, &m, &k)) {        for(int i = 0; i < n; i++)            g[i].clear();        for(int i = 0; i < m; i++) {            int a, b;            scanf("%d%d", &a, &b);            g[a].push_back(b);        }        if(toposort()) {            printf("%d", L[0]);            for(int i = 1; i < k; i++)                printf(" %d", L[i]);            printf("\n");        }        else printf("-1\n");    }    return 0;}






0 0
原创粉丝点击