POJ 3177 Redundant Paths
In order to get from one of the F (1 <= F <= 5,000) grazing fields (which are numbered 1…F) to another field, Bessie and the rest of the herd are forced to cross near the Tree of Rotten Apples. The cows are now tired of often being forced to take a particular path and want to build some new paths so that they will always have a choice of at least two separate routes between any pair of fields. They currently have at least one route between each pair of fields and want to have at least two. Of course, they can only travel on Official Paths when they move from one field to another.
Given a description of the current set of R (F-1 <= R <= 10,000) paths that each connect exactly two different fields, determine the minimum number of new paths (each of which connects exactly two fields) that must be built so that there are at least two separate routes between any pair of fields. Routes are considered separate if they use none of the same paths, even if they visit the same intermediate field along the way.
There might already be more than one paths between the same pair of fields, and you may also build a new path that connects the same fields as some other path.
Input
Line 1: Two space-separated integers: F and R
Lines 2…R+1: Each line contains two space-separated integers which are the fields at the endpoints of some path.
Output
Line 1: A single integer that is the number of new paths that must be built.
无向图
连多少条边使得整个无向图变成任意两个点之间都有两条完全不相同的路径。
首先我们可以对图进行边连通分量缩点, 缩点后图就会变成一颗树, 代表任意2点之间的路径是唯一的。 这时候题目转化为添加最少的边使树上任意
2点的路径至少有2条。
#include
#include
#include
using namespace std;
typedef long long ll;
const int N = 500007, M = 5000007, INF = 0x3f3f3f3f;
int n, m;
int dfn[N], low[N], num;
int head[N], ver[M], nex[M], edge[M], tot;
int dcc_cnt, cnt;
bool bridge[N];
int dcc_id[N];
int d[N];
void init(){
tot = num = cnt = dcc_cnt = 0;
memset(head, -1, sizeof head);
memset(dfn, 0, sizeof dfn);
memset(low, 0, sizeof low);
memset(bridge, 0, sizeof bridge);
}
void add(int x, int y)
{
ver[tot] = y;
nex[tot] = head[x];
head[x] = tot ++ ;
}
void tarjan(int x, int in_edge)
{
dfn[x] = low[x] = ++ num;
for(int i = head[x]; ~i; i = nex[i]){
int y = ver[i];
if(!dfn[y]){
tarjan(y, i);
low[x] = min(low[x], low[y]);
if(dfn[x] < low[y]){
bridge[i] = bridge[i ^ 1] = true;
}
}
else if(i != (in_edge ^ 1))
low[x] = min(low[x], dfn[y]);
}
}
void dfs(int x)
{
dcc_id[x] = dcc_cnt;
for(int i = head[x] ;~i; i = nex[i]){
int y = ver[i];
if(dcc_id[y] || bridge[i])continue;
dfs(y);
}
}
int main()
{
while(scanf("%d%d", &n, &m) != EOF){
init();
for(int i = 1; i <= m; ++ i){
int x, y;
scanf("%d%d", &x, &y);
add(x, y), add(y, x);
}
tarjan(1, -1);//整个图是连通的
for(int i = 1; i <= n; ++ i){
if(!dcc_id[i]){
++ dcc_cnt;
dfs(i);
}
}
for(int i = 0; i < tot; i += 2){
if(bridge[i]){
int x = ver[i], y = ver[i ^ 1];
d[dcc_id[x]] ++ ;
d[dcc_id[y]] ++ ;
}
}
ll cnt = 0;
for(int i = 1; i <= dcc_cnt; ++ i){
if(d[i] == 1)
cnt ++ ;
}
printf("%lld\n", (cnt + 1 ) / 2);
}
return 0;
}