题目传送门
Problem Description
There are some locations in a park, and some of them are connected by roads. The park manger needs to build some railways along the roads, and he would like to arrange tourist routes to each circuit. If a railway belongs to more than one tourist routes, there might be clash on it, and if a railway belongs to none tourist route, it doesn’t need to build.
Now we know the plan, and can you tell us how many railways are no need to build and how many railways where clash might happen.
Input
The Input consists of multiple test cases. The first line of each test case contains two integers, n (0 < n <= 10000), m (0 <= m <= 100000), which are the number of locations and the number of the railways. The next m lines, each line contains two integers, u, v (0 <= u, v < n), which means the manger plans to build a railway on the road between u and v.
You can assume that there is no loop and no multiple edges.
The last test case is followed by two zeros on a single line, which means the end of the input.
Output
Output the number of railways that are no need to build, and the number of railways where clash might happen. Please follow the format as the sample.
Sample Input
8 10
0 1
1 2
2 3
3 0
3 4
4 5
5 6
6 7
7 4
5 7
0 0
Sample Output
1 5
思路
不冲突路也就是桥边,这个直接一个模板就完事了。对于有n个节点和n条边的点双连通分量,这种分量只有一个大环,不存在其他任何环了,所以这种分量中的边都不是冲突边。而一个点双连通分量(大环)有小的点双连通分量(小环),也就是大环是由多个小环组成的这种点双连通分量,那么这个大环所有的边都是冲突边。根据这个原理 并且 图没有重边那么同时跑割边和点双连通分量。用堆栈记录边,用Set对点判重。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <stack>
#include <set>
using namespace std;
const int maxn = 10005;
struct edge{
int from;
int to;
int next;
}e[maxn*20];
int head[maxn];
int dfn[maxn];
int low[maxn];
stack<int>st;
set<int>s;
int tot,cnt;
int res,sum;
void clear_set()
{
tot = cnt = sum = res = 0;
memset(head,-1,sizeof(head));
memset(low,0,sizeof(low));
memset(dfn,0,sizeof(dfn));
while(!st.empty()) st.pop();
}
void addedge(int x,int y)
{
e[tot].from = x;
e[tot].to = y;
e[tot].next = head[x];
head[x] = tot++;
}
void tarjan(int x,int fx)
{
dfn[x] = low[x] = ++cnt;
int k = 0;
for(int i = head[x];~i;i = e[i].next){
int y = e[i].to;
if(y == fx) continue;
if(!dfn[y]){
st.push(i);
tarjan(y,x);
low[x] = min(low[x],low[y]);
if(low[y] > dfn[x]){ //桥边
res++;
}
if(low[y] >= dfn[x]){ //点双连通分量
int num = 0;s.clear();
while(true){
int t = st.top();
num++;
st.pop();
s.insert(e[t].from);
s.insert(e[t].to);
if(e[t].from == x && e[t].to == y) break;
}
if(num > s.size()) sum += num; //边数多于点数则冲突
}
}
else if(dfn[y] < dfn[x]){
st.push(i);
low[x] = min(low[x],dfn[y]);
}
}
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m)){
if(n == 0 && m == 0) break;
clear_set();
int x,y;
for(int i = 0;i < m;i++){
scanf("%d%d",&x,&y);
addedge(x,y); addedge(y,x);
}
for(int i = 0;i < n;i++){
if(!dfn[i]){
tarjan(i,-1);
}
}
printf("%d %d\n",res,sum);
}
return 0;
}
愿你走出半生,归来仍是少年~