As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:
Yuta has a non-direct graph with n vertices and n+1 edges. Rikka can choose some of the edges (at least one) and delete them from the graph.
Yuta wants to know the number of the ways to choose the edges in order to make the remaining graph connected.
It is too difficult for Rikka. Can you help her?
Yuta has a non-direct graph with n vertices and n+1 edges. Rikka can choose some of the edges (at least one) and delete them from the graph.
Yuta wants to know the number of the ways to choose the edges in order to make the remaining graph connected.
It is too difficult for Rikka. Can you help her?
For each testcase, the first line contains a number n(n≤100) .
Then n+1 lines follow. Each line contains two numbers u,v , which means there is an edge between u and v.
1 3 1 2 2 3 3 1 1 3
9
分析:n个点形成边最少需要n-1条边,所以枚举1条边和条边的情况;
代码:
#include <stdio.h>
#include <string.h>
const int maxn = 1e2 + 10;
int par[maxn];
struct node //把边用结构体存下来,每个结构体对应一条边;
{
int st;
int edd;
}edge[maxn];
void init(int n)
{
for (int i = 0; i <= n; i++)
par[i] = i;
}
int find(int x)
{
return par[x] == x ? x : par[x] = find(par[x]);
}
void unite(int a, int b)
{
int fa = find(a);
int fb = find(b);
if (fa != fb)
par[fa] = fb;
}
bool check(int n) //统计是不是只有一个根节点,即使不是能全部连通
{
int sum = 0;
for (int i = 1; i <= n; i++)
if (par[i] == i)
sum++;
return sum == 1;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
int n;
scanf("%d", &n);
for (int i = 0; i < n + 1; i++)
scanf("%d%d", &edge[i].st, &edge[i].edd);
int sum = 0; //sum记录可行的个数
//题上说总共给出n + 1条边 然后我们已知n个点至少需要n - 1条边连接 数据是100左右 n^3也可以过 那就暴力枚举
//先枚举去掉一条边是否能连通
for (int i = 0; i < n + 1; i++)
{
init(n); //这一步记得 因为是枚举 每次枚举出来一条边 这个数组就要重新排列一下 回复初始状态
for (int j = 0; j < n + 1; j++)
{
if (i == j) //上面用i记录去掉的边 那么这一步就没有这条边了 所以遇到相等就跳过
continue;
unite(edge[j].st, edge[j].edd); //把剩下的每个边都连接起来
}
//然后在这做检查 看能不能连通所有的点
if (check(n))
sum++;
}
//枚举一条边的就结束了 下面的两条边的和一条边的几乎相同
for (int i = 0; i < n + 1; i++)
{
for (int j = i + 1; j < n + 1; j++)
{
init(n);
for (int k = 0; k < n + 1; k++)
{
if (k == i || k == j)
continue;
unite(edge[k].st, edge[k].edd);
}
if (check(n))
sum++;
}
}
printf("%d\n", sum);
}
return 0;
}
本文介绍了一种算法,用于解决给定一个非定向图,包含n个顶点和n+1条边的情况下,如何计算删除部分边后使得剩余图保持连通的不同方案数量。通过枚举删除不同数量的边,并利用并查集判断剩余图的连通性来实现。
302

被折叠的 条评论
为什么被折叠?



