题意
传送门 Codeforces 118E Bertown roads
题解
给定一个无向连通图,将各条无向边变为有向边,求是否能构造得到 S C C SCC SCC。
若图中存在割边,则不存在这样的构造。反之,求图的 D F S DFS DFS 树,树边 p a r e n t → c h i l d parent\rightarrow child parent→child,容易证明祖先节点可达任意其子孙节点;非树边 d e s c e n d a n t → a n c e s t o r descendant\rightarrow ancestor descendant→ancestor,容易证明任意子孙节点可达其祖先节点。即,根节点与图中任意节点间都存在有向环,那么构造得到 S C C SCC SCC。
关于 D F S DFS DFS 树的分析可见 [Tutorial] The DFS tree and its applications。
#include <bits/stdc++.h>
using namespace std;
#define rep(i, l, r) for (int i = l, _ = r; i < _; ++i)
#define pb push_back
const int MAXN = 1E5 + 5;
bool has_bridge;
int N, M;
int dfn[MAXN], low[MAXN];
vector<int> G[MAXN];
vector<pair<int, int>> res;
void tarjan(int u, int p, int &k)
{
dfn[u] = low[u] = k++;
for (auto &v : G[u])
{
if (dfn[v] == -1)
{
tarjan(v, u, k);
low[u] = min(low[u], low[v]);
if (low[v] > dfn[u])
has_bridge = 1;
res.pb({u, v});
}
else if (v != p)
{
low[u] = min(low[u], dfn[v]);
if (dfn[v] < dfn[u])
res.pb({u, v});
}
}
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> N >> M;
rep(i, 0, M)
{
int u, v;
cin >> u >> v;
--u, --v;
G[u].pb(v), G[v].pb(u);
}
has_bridge = 0;
int k = 0;
memset(dfn, -1, sizeof(dfn));
tarjan(0, -1, k);
if (has_bridge)
cout << 0 << '\n';
else
for (auto &e : res)
cout << e.first + 1 << ' ' << e.second + 1 << '\n';
return 0;
}