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


题意是给出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
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>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





你可能感兴趣的:(codeforces,并查集)