DAG图与拓扑排序 (士兵排队问题)
【问题描述】
有N个士兵,编号依次为1,2,3,…,N, 队列训练时,指挥官要把一些士兵从高到矮依次排成一行。但现在指挥官不能直接获得每个人的身高信息,只能获得“p1比p2高”这样的比较结果:记为p1>p2。例如 1>2, 2>4,3>4。士兵的身高关系如图所示:
【输入格式】
第一行:包含两个整数N、M,第二至第M+1行:每行两个整数x,y,代表士兵x比士兵y高。
【输出格式】
一个1..N的排列,表示排队方案(字典序最小),如果没有可行方案则输出-1。
【输入样例】
【样例1】
4 3
1 2
2 4
3 4
【样例2】
4 4
1 2
2 4
2 3
3 1
【输出样例】
【样例1】
1 2 3 4
【样例2】
-1
【数据范围】
1<=N<10000
1<=M<=100000
普通的拓补排序,注意判断无解,输出字典序最小的拓补序列用优先队列(按编号最小队)即可
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn=10005;
vector<int>g[maxn];
int n,m;
int rd[maxn];
vector<int>topo;
struct cmp
{
bool operator()(int a,int b)
{
return a>b;
}
};
void init()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
g[x].push_back(y);
rd[y]++;
}
}
bool BFS()
{
priority_queue<int,vector<int>,cmp>q;
for(int i=1;i<=n;i++)
if(rd[i]==0)
{
q.push(i);
}
while(!q.empty())
{
int i=q.top();q.pop();
topo.push_back(i);
for(int k=0;k<g[i].size();k++)
{
int j=g[i][k];
if(rd[j]>0)rd[j]--;
if(rd[j]==0)q.push(j);
}
}
return topo.size()==n;
}
int main()
{
//freopen("my.in","r",stdin);
//freopen("my.out","w",stdout);
init();
int flag=BFS();
if(flag)
{
for(int k=0;k<topo.size();k++)
printf("%d ",topo[k]);
}
else printf("-1");
return 0;
}