题解: https://xiaoxiaoh.blog.csdn.net/article/details/104297536
一、内容
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
二、思路
- 题意:求任意2点之间至少存在2条不同的路径。
- 首先我们可以对图进行边连通分量缩点, 缩点后图就会变成一颗树, 代表任意2点之间的路径是唯一的。 这时候题目转化为添加最少的边使任意2点的路径至少有2条。
- 结论: 对有n个入度为1的点的树,至少需要 (n + 1) / 2 的边使其变成一个边连通分量。
三、代码
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 5e3 + 5, M = 2e4 + 5;
struct E{int v, next;} e[M];
int n, m, u, v, len, h[N], id[N], dcc_cnt, stack[N], dfn[N], low[N], num, top, ind[N];
bool bridge[M];
void add(int u, int v) { e[++len].v = v; e[len].next = h[u]; h[u] = len;}
void tarjan(int u, int from) {
dfn[u] = low[u] = ++num;
stack[++top] = u;
for (int j = h[u]; j; j = e[j].next) {
int v = e[j].v;
if (!dfn[v]) {
tarjan(v, j);
low[u] = min(low[u], low[v]);
//判断这条边是否是桥
if (dfn[u] < low[v]) bridge[j] = bridge[j ^ 1] = true;
//如果不是反向边的话
} else if (j != (from ^ 1)) low[u] = min(low[u], dfn[v]);
}
if (dfn[u] == low[u]) {
++dcc_cnt; int v;
do {
v = stack[top--];
id[v] = dcc_cnt;
} while (u != v);
}
}
int main() {
len = 1; //节点编号从2开始
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
add(u, v); add(v, u);
}
tarjan(1, 0);
//判断入度为0的点的个数
int ans = 0;
for (int u = 1; u <= n; u++) {
for (int j = h[u]; j; j = e[j].next) {
int v = e[j].v;
if (id[u] == id[v]) continue;
ind[id[v]]++;
}
}
for (int i = 1; i <= dcc_cnt; i++) if (ind[i] == 1) ans++;
printf("%d", (ans + 1) / 2);
return 0;
}
为什么节点编号要从2开始啊,求解