1073.选课

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

vector<int> nt[501];
char s[501][41];
int d[501];
int a[500];
int n;

void topological() {
    int i, u, k = 0;
    queue<int> que;
    for (i = 1; i <= n; i++)
        if (d[i] == 0)
            que.push(i);
    while (!que.empty()) {
        u = que.front();
        que.pop();
        a[k++] = u;
        for (vector<int>::iterator it = nt[u].begin(); it != nt[u].end(); it++) {
            d[*it]--;
            if (d[*it] == 0)
                que.push(*it);
        }
    }
    if (k != n) {
        printf("Impossible!\n");
        return;
    }
    printf("%s", s[a[0]]);
    for (i = 1; i < n; i++)
        printf(" %s", s[a[i]]);
    printf("\n");
}

int main(int argc, char* argv[]) {
    int m, i, u;

    scanf("%d", &n);
    for (i = 1; i <= n; i++)
        scanf("%s", s[i]);
    for (i = 1; i <= n; i++) {
        scanf("%d", &m);
        while (m--) {
            scanf("%d", &u);
            nt[u].push_back(i);
            d[i]++;
        }
    }

    topological();

    return 0;
}


作者: gzzcracker   发布时间: 2010-11-11