Redundant Paths
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 15390 Accepted: 6476
Description
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.
Sample Input
7 7
1 2
2 3
3 4
2 5
4 5
5 6
5 7
Sample Output
2
题目大意:
有F个牧场,1<=F<=5000,现在一个牧群经常需要从一个牧场迁移到另一个牧场。奶牛们已经厌烦老是走同一条路,所以有必要再新修几条路,这样它们从一个牧场迁移到另一个牧场时总是可以选择至少两条独立的路。现在F个牧场的任何两个牧场之间已经至少有一条路了,奶牛们需要至少有两条。
给定现有的R条直接连接两个牧场的路,F-1<=R<=10000,计算至少需要新修多少条直接连接两个牧场的路,使得任何两个牧场之间至少有两条独立的路。两条独立的路是指没有公共边的路,但可以经过同一个中间顶点
解题思路:
开始给出了一个无向连通图,但其中有一些点之间只有一条路径,要求我们添加一些路径使得每两个点之间都有两条或两条以上的路径,可以发现在一个连通块之间至少有两条路径,假如我们把连通块缩点成一个点,那么可以得到一颗树,而我们只要将叶子节点之间连上就可以再次形成一个连同图。所以我们最少要连的边=(叶子节点数+1)/2
代码如下:
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 5000 + 5;
int n,m;
int M[maxn][maxn];
int dfn[maxn],low[maxn],my_index;
void Tarjan(int u,int fa){
dfn[u] = low[u] = ++my_index;
for(int v = 1;v <= n; v++){
if(!M[u][v])continue;
if(!dfn[v]){
Tarjan(v,u);
low[u] = min(low[u],low[v]);
}
else if(v != fa)low[u] = min(low[u],dfn[v]);
}
}
int cnt[maxn];
int main(){
scanf("%d%d",&n,&m);
int u,v;
for(int i = 1;i <= m; i++){
scanf("%d%d",&u,&v);
M[u][v] = M[v][u] = 1;
}
Tarjan(1,-1);
for(int i = 1;i <= n; i++){
for(int j = 1;j <= n; j++){
if(M[i][j]){
if(low[i] != low[j]){
cnt[low[j]]++;
}
}
}
}
int ans = 0;
for(int i = 1;i <= n; i++){
if(cnt[i] == 1)ans++;
}
printf("%d\n",(ans+1)/2);
}