25D codeforces - Roads not only in Berland


25D codeforces  -  Roads not only in Berland






Solution in C++


#include <bits/stdc++.h>
using namespace std;

//Hello World

typedef long long int lli;
typedef long double ld;
#define pii pair<int,int>
#define piiti pair< pair<int,int>,int>
#define ipii pair<int,pair<int,int> >
#define mod 1000000007
#define lasB(b) (b&(-b))
#define N 1003


int fat[N] ,t1 , t2, n , cnt , vis[N];

vector<pii> all , re;
vector<int> adj[N];

int fin(int x)
{
    if(fat[x]!=x)
        fat[x]=fin(fat[x]);
    return fat[x];
}

void unio(int a , int b)
{
    int p1 = fin(a);
    int p2 = fin(b);
    fat[p1]=fat[p2];
}

void dfs(int x)
{
    if(vis[x])return ;
    vis[x]=1;
    for(auto u : adj[x])dfs(u);
    return ;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie();
    cin>>n;
    for(int i=1;i<=n;i++)
        fat[i]=i;
    for(int i=0;i<n-1;i++)
    {
        cin>>t1>>t2;
        if(fin(t1)!=fin(t2))
        {
            adj[t1].push_back(t2);
            adj[t2].push_back(t1);
            unio(t1,t2);
        }
        else all.push_back({ t1 , t2 }) , cnt++;
    }
    int base = 1;
    cout<<cnt<<"\n";
    for(int i=1;i<=n;i++)
    {
        if(vis[i])continue;
        dfs(i);
        if(i!=base)
        {
            cout<<all.back().first<<" "<<all.back().second<<" "<<base<<" "<<i<<"\n";
            all.pop_back();
        }
    }
    return 0;
}
Share on Google Plus

About Mohamed Sobhi

My name is Mo.Sobhy ,I study at School excelling high school in Ain Shams ,Cairo
My hobbies is programming ,and web development ,playing chess and writing horror stories.
    Blogger Comment
    Facebook Comment

0 التعليقات:

إرسال تعليق