题意
给出有m1条有向边和m2条无向边的图,求出我们每条无向边的方向使得这个图是一个有向无环图。
思路
先用拓扑排序求出每一个点的拓扑序,然后读入无向边是判断拓扑序,让顺序小的连大的就好了。
代码
#include<cstdio>
#include<queue>
using namespace std;
int cnt,tot,n,m1,m2,a,b,rd[100001],head[100001],ans[100001];
struct node{
int to,next;
}e[100001];
void add(int x,int y)
{
e[++tot].to=y;e[tot].next=head[x];head[x]=tot;rd[y]++;
}
void topsort()
{
queue<int> q;
int x,y;
for (int i=1;i<=n;i++)
if (!rd[i]) q.push(i);
while (q.size())
{
x=q.front();q.pop();
ans[x]=++cnt;
for (int i=head[x];i;i=e[i].next)
{
y=e[i].to;
if (--rd[y]==0) q.push(y);
}
}
}
int main()
{
scanf("%d%d%d",&n,&m1,&m2);
for (int i=1;i<=m1;i++)
{
scanf("%d%d",&a,&b);
add(a,b);
}
topsort();//拓扑排序
while (m2--)
{
scanf("%d%d",&a,&b);
if (ans[a]<ans[b]) printf("%d %d\n",a,b);//把小的连向大的
else printf("%d %d\n",b,a);
}
}