吃在工大
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;
}