吃在工大
Time Limit: 1000 MS | Memory Limit: 65536 KB |
Total Submissions: 51 | Accepted: 15 |
Description
于是YZ为了帮助他解决这个问题,也顺便考考他,给他出了一个问题:“黄焖鸡必须在干锅花菜前面吃,干锅牛肉必须在干锅鱿鱼前面吃….你按这个要求下,就知道吃的顺序啦”。JH抓抓头,分分钟写了个程序搞定,现在,让你来写写看?输出一组JH符合条件下吃的食物的序列。
假设JH每顿只吃一种食物,且每顿吃的都不同,食物编号1到N。
Input
每组数据第一行输出一个整数,N,M,分别表示有N种食物,总共有M个约束条件,接下来M行每行输入两个正整数a,b(n>=a>0,n>=b>0),表示食物a必须在食物b之前吃。
Output
Sample Input
4 3
1 2
2 3
4 3
Sample Output
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 10000 + 5;
vector<int> g[maxn];
int du[maxn], n, m, 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> Q;
for (int i=0; i<n; i++)
if (!du[i]) Q.push(i);//入度为0的点存入优先队列
while (!Q.empty()) {
int x = Q.top(); Q.pop();
L[tot++] = x;//取出入度为0的点,并存入数组
for (int j=0; j<g[x].size(); j++){
int t = g[x][j];
du[t]--;//相连的点入度依次减一
if (!du[t])
Q.push(t);//把入度为0的点放入优先队列
}
}
if (tot == n)
return 1;
return 0;
}
int main(int argc, char const *argv[])
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &m);
for(int i=0;i<n;i++)
g[i].clear();
while (m--)
{
int N, M;
scanf("%d%d", &N, &M);
g[N-1].push_back(M-1);
}
int first = 0;
if (toposort()) {
for (int i=0; i<n; i++) {
if (first)
printf(" ");
first = 1;
printf("%d", L[i]+1);
}
printf("\n");
}
else
printf("-1\n");
}
return 0;
}