POJ传送门
洛谷传送门
UVA传送门
题意翻译
给定一个无向图(默认联通),保证无重边, 请给尽可能多的无向边定向,使得定向后新图中所有点可以互相到达。并输出所有的边,已定向的输出i j
的形式,不能定向的同时输出i j
和j i
(本题有SPJ)。 另外提示一下,输出时在case编号后是有一个空行的。
输入输出格式
输入格式
输入包含多组数据。
对于每组数据, 第一行两个正整数 n , m n, m n,m表示点和边的数量。 如果 n = m = 0 n=m=0 n=m=0则表示输入结束, 你不需要对这组数据回答。
以下 m m m行, 每行两个正整数 i , j i,j i,j, 表示编号为 i i i和编号为 j j j的节点之间有一条无向边。
输出格式
对于每组数据, 首先输出一行为组号(从1开始编号)。
接下来一行为空行。
以下若干行, 表示每条无向边处理后的结果。 输出顺序随意。
输入输出样例
输入样例#1:
7 10
1 2
1 3
2 4
3 4
4 5
4 6
5 7
6 7
2 5
3 6
7 9
1 2
1 3
1 4
2 4
3 4
4 5
5 6
5 7
7 6
0 0
输出样例#1:
1
1 2
2 4
3 1
3 6
4 3
5 2
5 4
6 4
6 7
7 5
#
2
1 2
2 4
3 1
4 1
4 3
4 5
5 4
5 6
6 7
7 5
#
解题分析
首先一个边双联通分量里面的点在定向后可以形成环, 都可以互相到达, 只有桥边需要保持无向。
那么直接缩边双联通分量后判桥边, 然后一遍 D F S DFS DFS输出就好了。
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <algorithm>
#define R register
#define IN inline
#define W while
#define gc getchar()
#define MX 1050
template <class T>
IN void in(T &x)
{
x = 0; R char c = gc;
for (; !isdigit(c); c = gc);
for (; isdigit(c); c = gc)
x = (x << 1) + (x << 3) + c - 48;
}
template <class T> IN T max(T a, T b) {return a > b ? a : b;}
template <class T> IN T min(T a, T b) {return a < b ? a : b;}
int n, m, cnt, col, top, arr;
int head[MX], bel[MX], sta[MX], dfn[MX], low[MX];
struct Edge {int to, nex; bool vis;} edge[MX * MX << 1];
IN void add(R int from, R int to) {edge[++cnt] = {to, head[from], false}, head[from] = cnt;}
void tarjan(R int now, R int fa)
{
dfn[now] = low[now] = ++arr;
sta[++top] = now;
for (R int i = head[now]; ~i; i = edge[i].nex)
{
if (edge[i].to == fa) continue;
if (!dfn[edge[i].to])
{
tarjan(edge[i].to, now);
low[now] = min(low[now], low[edge[i].to]);
}
else low[now] = min(low[now], dfn[edge[i].to]);
}
if (low[now] == dfn[now])
{
bel[now] = ++col;
W (sta[top] ^ now) bel[sta[top--]] = col;
--top;
}
}
void out(R int now)
{
dfn[now] = 0;
for (R int i = head[now]; ~i; i = edge[i].nex)
{
if (!edge[i].vis)
{
if (bel[edge[i].to] ^ bel[now]) printf("%d %d\n%d %d\n", now, edge[i].to, edge[i].to, now);
else printf("%d %d\n", now, edge[i].to);
edge[i].vis = edge[i ^ 1].vis = true;
}
if (dfn[edge[i].to]) out(edge[i].to);
}
}
int main(void)
{
freopen("1.out", "w", stdout);
int T = 0, foo, bar;
W (~scanf("%d%d", &n, &m))
{
cnt = -1; arr = col = 0;
std::memset(head, -1, sizeof(head));
if (n == m && n == 0) break;
printf("%d\n\n", ++T);
for (R int i = 1; i <= m; ++i)
in(foo), in(bar), add(foo, bar), add(bar, foo);
tarjan(1, 0);
out(1);
puts("#");
}
}