【题解】NOIp模拟:混合图

【题目描述】

Hzwer神犇最近又征服了一个国家,然后接下来却也遇见了一个难题。

Hzwer的国家有n个点,m条边,而作为国王,他十分喜欢游览自己的国家。他一般会从任意一个点出发,随便找边走,沿途欣赏路上的美景。但是我们的Hzwer是一个奇怪的人,他不喜欢走到自己以前走过的地方,他的国家本来有p1条有向边,p2条无向边,由于国王奇怪的爱好,他觉得整改所有无向边,使得他们变成有向边,要求整改完以后保证他的国家不可能出现从某个地点出发顺着路走一圈又回来的情况。(注:m=p1+p2.)

概述:给你一张混合图,要求你为无向图定向,使得图上没有环。

【输入格式】 dizzy.in

  第一行3个整数 n,p1,p2,分别表示点数,有向边的数量,无向边的数量。

  第二行起输入p1行,每行2个整数 a,b 表示a到b有一条有向边。

  接下来输入p2行,每行2个整数 a,b 表示a和b中间有一条无向边。

【输出格式】 dizzy.out

对于每条无向边,我们要求按输入顺序输出你定向的结果,也就是如果你输出a b,那表示你将a和b中间的无向边定向为a->b。

注意,也许存在很多可行的解。你只要输出其中任意一个就好。

【样例输入】

4 2 3

1 2

4 3

1 3

4 2

3 2

【样例输出】

1 3

4 2

2 3

数据范围

对于20%的数据 n<=10 p1<=10 p2<=5

对于30%的数据 n<=10 p1<=30 p2<=20

对于100%的数据 n<=100000 p1<=100000 p2<=100000

数据保证至少有一种可行解。

先进行拓扑排序,对于一条无向边, i d id 小的连向大的就好了

Code:

#include <bits/stdc++.h>
#define maxn 100010
using namespace std;
struct Edge{
	int to, next;
}edge[maxn << 1];
int num, head[maxn], d[maxn], id[maxn], n, p1, p2, Index;
queue <int> q;

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = 1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

void addedge(int x, int y){ edge[++num] = (Edge){y, head[x]}, head[x] = num; }

int main(){
	freopen("dizzy.in", "r", stdin);
	freopen("dizzy.out", "w", stdout);
	n = read(), p1 = read(), p2 = read();
	for (int i = 1; i <= p1; ++i){
		int x = read(), y = read();
		addedge(x, y);
		++d[y];
	}
	for (int i = 1; i <= n; ++i)
		if (!d[i]) q.push(i);
	while (!q.empty()){
		int u = q.front(); q.pop();
		id[u] = ++Index;
		for (int i = head[u]; i; i = edge[i].next){
			int v = edge[i].to;
			if ((--d[v]) == 0) q.push(v);
		}
	}
	while (p2--){
		int x = read(), y = read();
		if (id[x] < id[y]) printf("%d %d\n", x, y); else printf("%d %d\n", y, x);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ModestCoder_/article/details/108278047