题意:找无向图的桥。很长时间没敲过图论代码了,这个算法居然忘了。
解法:pre[x]记录顶点x的访问时间,anc[x]记录通过顶点x的dfs子树所能访问到的pre最小的祖先结点的访问时间。如果 anc[x]==pre[x] 说明到达顶点x的树边是桥。
#include <stdio.h>
#include <memory.h>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 10005;
const int maxm = 100005 * 2;
struct Graph {
int hed[maxn], pnt[maxm], nxt[maxm], id[maxm], cnt;
void init(int n) {
memset(hed + 1, -1, 4 * n);
cnt = 0;
}
void addedge(int x, int y, int i) {
pnt[cnt] = y; id[cnt] = i; nxt[cnt] = hed[x]; hed[x] = cnt++;
pnt[cnt] = x; id[cnt] = i; nxt[cnt] = hed[y]; hed[y] = cnt++;
}
} G;
vector<int> V;
int anc[maxn], pre[maxn], vis[maxn];
void dfs(int x, int f, int d) {
vis[x] = 1;
anc[x] = pre[x] = d;
for (int p = G.hed[x]; p != -1; p = G.nxt[p]) {
int y = G.pnt[p];
int e = G.id[p];
if (e != f && vis[y]) { // back edge
if (anc[x] > pre[y])
anc[x] = pre[y];
} else if (!vis[y]) {
dfs(y, e, d + 1); // tree edge
if (anc[y] < anc[x])
anc[x] = anc[y];
if (anc[y] > pre[x])
V.push_back(e);
}
}
}
int main() {
int T, N, M, i, x, y;
for (scanf("%d", &T); T--; ) {
scanf("%d %d", &N, &M);
G.init(N);
for (i = 1; i <= M; i++) {
scanf("%d %d", &x, &y);
G.addedge(x, y, i);
}
memset(vis + 1, 0, 4 * N);
V.clear();
dfs(1, -1, 0);
sort(V.begin(), V.end());
printf("%d\n", V.size());
for (i = 0; i < V.size(); i++) {
if (i) printf(" ");
printf("%d", V[i]);
}
if (V.size()) printf("\n");
if (T) printf("\n");
}
return 0;
}