cf25d 修路使其联通 (并查集)

本文介绍了一个算法问题,涉及如何通过每日替换一条旧路并新建一条新路的方式,使得由n个城市组成的路网能够保持各城市间的连通性。讨论了在特定条件下(如路网仅包含n-1条路的情况下),如何最小化所需的天数,并给出了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


题意是给出n个城市,n-1条路,每天会修路(删除原本的一条路,然后增添一条新路)


这题的亮点就在路只有n-1条,要联通的话只能有一个祖先,且不存在回路...


故只要删除有回路的,然后把每个不相连的路连接起来即可....


Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones.

Input

The first line contains integer n (2 ≤ n ≤ 1000) — amount of cities in Berland and neighboring countries. Next n - 1lines contain the description of roads. Each road is described by two space-separated integers aibi(1 ≤ ai, bi ≤ n, ai ≠ bi) — pair of cities, which the road connects. It can't be more than one road between a pair of cities. No road connects the city with itself.

Output

Output the answer, number t — what is the least amount of days needed to rebuild roads so that from each city it became possible to reach all the others. Then output t lines — the plan of closure of old roads and building of new ones. Each line should describe one day in the format i j u v — it means that road between cities i and jbecame closed and a new road between cities u and v is built. Cities are numbered from 1. If the answer is not unique, output any.

Examples
input
2
1 2
output
0
input
7
1 2
2 3
3 1
4 5
5 6
6 7
output
1
3 1 3 7

#include<bits/stdc++.h>
using namespace std;
const int N = 1111;
int fa[N];
struct node
{
	int x,y;
}a[N];
int b[N];
int find(int x)
{
	int r=x;
	while(fa[r]!=r) r=fa[r];
	int i=x,j;
	while(i!=r) {
		j=fa[i];
		fa[i]=r;
		i=j;
	}
	return r;
}


int main()
{
	int n,i,j,x,y,cnt;
	cin>>n;
	for(i=1;i<=n;i++) fa[i]=i;
	cnt=0;
	for(i=1;i<n;i++) {
		cin>>x>>y;
		int fx=find(x);
		int fy=find(y);
		if(fx!=fy) fa[fx]=fy;
		else {
			a[++cnt].x=x;
			a[cnt].y=y;
		}
	}
	cnt=0;
	for(i=1;i<=n;i++) {
		if(find(i)==i) b[++cnt]=i;
	}
	printf("%d\n",cnt-1);
	for(i=1;i<cnt;i++) {
		printf("%d %d %d %d\n",a[i].x,a[i].y,b[i],b[i+1]);
	}
	return 0;
}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值