Codeforces962F. Simple Cycles Edges(点双连通分量)

tech2022-07-09  173

You are given an undirected graph, consisting of 𝑛 vertices and 𝑚 edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself).

A cycle in a graph is called a simple, if it contains each own vertex exactly once. So simple cycle doesn’t allow to visit a vertex more than once in a cycle.

Determine the edges, which belong to exactly on one simple cycle.

Input The first line contain two integers 𝑛 and 𝑚 (1≤𝑛≤100000, 0≤𝑚≤min(𝑛⋅(𝑛−1)/2,100000)) — the number of vertices and the number of edges.

Each of the following 𝑚 lines contain two integers 𝑢 and 𝑣 (1≤𝑢,𝑣≤𝑛, 𝑢≠𝑣) — the description of the edges.

Output In the first line print the number of edges, which belong to exactly one simple cycle.

In the second line print the indices of edges, which belong to exactly one simple cycle, in increasing order. The edges are numbered from one in the same order as they are given in the input.

Examples inputCopy 3 3 1 2 2 3 3 1 outputCopy 3 1 2 3 inputCopy 6 7 2 3 3 4 4 2 1 2 1 5 5 6 6 1 outputCopy 6 1 2 3 5 6 7 inputCopy 5 6 1 2 2 3 2 4 4 3 2 5 5 3 outputCopy 0

题意: 求有多少条边,仅属于一个简单环。

思路: 求出点双连通分量后(除去单个点和两个点的情况),每个连通分量内部就是很多个环嵌套起来的结构。

题意仅要求简单环,那就是要求仅存在一个环。这等价与点双连通分量的边数等于点数。求出所有符合条件的双连通分量即可。

#include <cstdio> #include <algorithm> #include <cstring> #include <iostream> #include <vector> using namespace std; const int maxn = 2e5 + 7; int head[maxn],nex[maxn],to[maxn],tot = 1; int dfn[maxn],low[maxn],num; int bcnt[maxn],cnt; int vis[maxn]; int stk[maxn],top; vector<int>ans; void add(int x,int y) { to[++tot] = y; nex[tot] = head[x]; head[x] = tot; } void tarjan(int x,int fa) { dfn[x] = low[x] = ++num; for(int i = head[x];i;i = nex[i]) { int v = to[i]; if(v == fa || vis[i]) continue; vis[i] = vis[i ^ 1] = 1; stk[++top] = i; if(!dfn[v]) { tarjan(v,fa); low[x] = min(low[x],low[v]); if(low[v] >= dfn[x]) { cnt++; int point = 0; vector<int>edge; int t; do { t = stk[top];top--; edge.push_back(t); if(bcnt[to[t]] != cnt) { bcnt[to[t]] = cnt; point++; } if(bcnt[to[t ^ 1]] != cnt) { bcnt[to[t ^ 1]] = cnt; point++; } }while(t != i); if(edge.size() == point) { for(int j = 0;j < edge.size();j++) { ans.push_back(edge[j]); } } } } else { low[x] = min(low[x],dfn[v]); } } } int main() { int n,m;scanf("%d%d",&n,&m); for(int i = 1;i <= m;i++) { int x,y;scanf("%d%d",&x,&y); add(x,y);add(y,x); } for(int i = 1;i <= n;i++) { if(!dfn[i]) { tarjan(i,0); } } sort(ans.begin(),ans.end()); printf("%d\n",ans.size()); for(int i = 0;i < ans.size();i++) { printf("%d ",ans[i] / 2); } return 0; }
最新回复(0)