Saturday, 20 February 2016

D. Roads not only in Berland

D. Roads not only in Berland

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 - 1 lines 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 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.
Sample test(s)
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

----------------------------------------EDITORIAL------------------------------------------------------------

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
This is a general data structure that sometimes appears in programming competitions. There are a lot of ways to implement it; one good example is written by Bruce Merry (aka BMerry) here.


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?
Let build be the list all roads that need to be built, and let close be the list of nodes that need to be closed. We can show that in fact, these lists are of the same size. This is because the connected graph with n nodes is a tree if and only if it has n - 1 edges. Thus, if we remove more roads than than we build, then the graph is disconnected. Also, if we build more roads than we remove, then we have some unnecessary roads (the graph is no longer a tree).

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;
}



Friday, 12 February 2016

***B. Lazy Student

B. Lazy Student

Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m () — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print  - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Sample test(s)
input
4 5
2 1
3 1
4 0
1 1
5 0
output
2 4
1 4
3 4
3 1
3 2
input
3 3
1 0
2 1
3 1
output
-1


---------------------------------------------------editorial---------------------------------------------------------

this problem can easily solve without using dsu

considerations
sort all  distance  , now one by one start adding these edge in the graph

for simplicity we can consider mst graph as a star graph or a linear graph (here in my code i considere as a star graph )

if any edge is exists in the mst add it with node 1 (since mst is a star graph in my soln )
else
add that edge b/w any two alreaded vertices , bcoze that edge not included in the mst means it is forming a cycle ,
now if all the nodes are connected there is no way to connect that edge with the existing connected edge , means that edge is a part of mst  soooooo ans=-1;

note there is one another most important observation is that sort the distance using own comparator such that if there are two edge having same length han edge which included in mst must comes earlier in sorted aray ( think why ?..easy think again)
else continue ,

implementation can be understand with this editorial;

Let’s order edges of ascending length, in case of a tie placing earlier edges we were asked to include to MST. Let’s start adding them to the graph in this order. If we asked to include the current edge to MST, use this edge to llink 1st vertex with the least currently isolated vertex. If we asked NOT to include the current edge to MST, use this edge to link some vertices that are already linked but have no edges between them. To do this it’s convenient to have two pointer on vertices (let’s call them FROM and TO). At the beginning, FROM=2, TO=2. When we are to link two already linked vertices, we add new edge (FROM, TO) and increment FROM. If FROM becomes equal to TO, we can assume we already added all possible edges to TO, so we increment TO and set FROM to 2. This means from this moment we will use non-MST edges to connect TO with all previous vertices starting from 2. If it appears that TO looks at currently isolated vertex, we can assume there are no place for non-MST edge it the graph, so the answer is Impossible. Keep doing in the described way, we’ll be adding MST edges as (1,2), …, (1,n) and non-MST edges as (2,3), (2,4), (3,4), (2,5), (3,5), (4,5), ...

--------------------------------------code------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
vector<pair<pair<int,int>,int> > v,ans;
#define pp pair<pair<int,int>,int>
bool compare(pp p1,pp p2)
 {
   if(p1.first.first<p2.first.first)return true;
   else if(p1.first.first>p2.first.first) return false;
   else
   {
     if(p1.first.second>p2.first.second) return true;
     else return false;
  }
 
 }
int main()
{

int n,m;
cin>>n>>m;

for(int i=0;i<m;i++)
 {
   int a,b;
    cin>>a>>b;
   // if(b==0) b=2;
    v.push_back(mp(mp(a,b),i+1));
 }

 sort(v.begin(),v.end(),compare);
 int left=2;
 int right=2;
 int max_inserted=1;


 for(int i=0;i<m;i++)
  {
   if(v[i].first.second==1)
    {
     ans.push_back(mp(mp(v[i].second,1),++max_inserted));
   }
   else
   {
      if(left<right)
       {
        ans.push_back(mp(mp(v[i].second,left),right));
        left++;
       
  }
  else
  {
   if(right<max_inserted)
    {
   right++;
   left=2;
    ans.push_back(mp(mp(v[i].second,left),right));
          left++;
  }
  else
  {
    cout<<"-1"<<endl;
    exit(0);
  }



  }
   }
  }
  sort(ans.begin(),ans.end());
  for(int i=0;i<m;i++)
   {
     cout<<ans[i].first.second<<" "<<ans[i].second<<endl;
   }

}