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.
The first line contains integer n (2 ≤ n ≤ 1000) — amount of cities in Berland and neighboring countries. Next n - 1 lines contain the description of roads. Each road is described by two space-separated integers ai, bi (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 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 j became 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.
2 1 2
0
7 1 2 2 3 3 1 4 5 5 6 6 7
1 3 1 3 7
虽然是个水题,不过也是自己周赛第一次拿一血的题目啊 纪念一下喽
E题题意:告诉n个城市,然后告诉n-1条已经连通的道路,为使n个城市全都连通,即可以从任意城市到另外一个城市,现在每天可以新修一条路并且关闭一条路,问最少需要多少天可以使n个城市连通。
思路:并查集。在输入的时候把每个点之间的关系建立起来,并记录下有多少条多余的路,即已经添加到同一个集合中。然后遍历每一个fa[i]记录集合数num,那么num-1就是需要建立的道路数。
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#define N 10009
using namespace std;
int fa[N];
struct Node
{
int a,b;
}f[N];
int findfa(int x)
{
if(x==fa[x])
return fa[x];
else
return findfa(fa[x]);
}
int n;
int g[N];
int main()
{
while(~scanf("%d",&n))
{
int a,b;
for(int i=1;i<=n;i++)
fa[i]=i;
int ans1=0;
for(int i=1;i<n;i++)
{
scanf("%d %d",&a,&b);
int aa=findfa(a);
int bb=findfa(b);
if(aa==bb)
{
f[ans1].a=a;
f[ans1].b=b;
ans1++;
}
if(aa<bb)
fa[bb]=aa;
else
fa[aa]=bb;
}
// for(int i=0;i<ans1;i++)
// cout<<f[0].a<<" "<<f[0].b<<endl;
int num=0;
for(int i=1;i<=n;i++)
{
if(fa[i]==i)
{
g[num]=i;
num++;
}
}
printf("%d\n",num-1);
int i=0;
while(1)
{
if(i>=num-1) break;
printf("%d %d %d ",f[i].a,f[i].b,g[i]);
i++;
printf("%d\n",g[i]);
}
}
return 0;
}