Before we start this problem, it is helpful to know about the union find data structure. The main idea is this: given some elementsx1, x2, x3, ..., xn that are partitioned in some way, we want to be able to do the following:
- merge any two sets together quickly
- find the parent set of any xi
Back to the problem: Every day we are allowed to build exactly 1 road, and close exactly 1 road. Thus, we can break the problem into two parts:
- How do we connect the parts of the graph that are disconnected?
- How do we remove roads in a way that does not disconnect parts of the graph?
Now consider the format of the input data:
a1, b1
a2, b2
...
an - 1, bn - 1
We can show that edge (ai, bi) is unnecessary if and only if the nodes ai, bi have already been connected by edges(a1, b1), (a2, b2), ..., (ai - 1, bi - 1). In other words, if the vertices ai, bi are in the same connected component before we, add (ai, bi)then we do not need to add (ai, bi). We can use union-find to help us solve this problem:
<code>
for( i from 1 to n-1 )
{
if( find(ai)=find(bi) ) close.add(ai, bi);
else merge(ai, bi);
}
</code>
In other words, we treat each connected component as a set. Union find allows us to find the connected component for each node. If the two connected components are the same, then our new edge is unnecessary. If they are different, then we can merge them together (with union find). This allows us to find the edges that we can remove.
In order to find the edges that we need to add to the graph, we can also use union-find: whenever we find a component that is disconnected from component 1, then we just add an edge between them.
<code>
for( i from 2 to n )
if( find(vi)!=find(v1) )
{
then merge(v1, vi);
build.add(v1, vi);
}
</code>
We just need to store the lists of roads that are unnecessary, and the roads that need to be built.
--------------------------------------------------CODE-------------------------------------------------------
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
int rank[1000100];
int parent[1000100];
int find(int a)
{
if(parent[a]!=parent[parent[a]])
{
parent[a]=find(parent[a]);
}
return parent[a];
}
int merge(int a, int b)
{
int x=find(a);
int y=find(b);
if(rank[x]>rank[y])
{
parent[y]=x;
}
else
{
parent[x]=y;
if(rank[x]==rank[y])
rank[y]++;
}
}
int main()
{
int n,m;
cin>>n;
for(int i=0;i<=n+10;i++)
{
parent[i]=i;
rank[i]=1;
}
vector<pair<int,int> > ex;
for(int i=0;i<n-1;i++)
{
int a,b;
scanf("%d %d",&a,&b);
int fin1=find(a);
int fin2=find(b);
if(find(a)==find(b))
{
ex.push_back({a,b});
}
else
{
merge(a,b);
}
}
vector<int> pp;
for(int i=1;i<=n;i++)
{
int r=find(i);
if(r==i)
{
pp.push_back(i);
}
}
int size=pp.size();
cout<<size-1<<endl;
int bos;
if(size>0) bos=pp[0];
int use=0;
for(int i=1;i<size;i++)
{
printf("%d %d %d %d\n",ex[use].first,ex[use].second,bos,pp[i]);
use++;
}
return 0;
}
No comments:
Post a Comment