Black and White Tree


Problem Statement :


Nikita is making a graph as a birthday gift for her boyfriend, a fellow programmer! She drew an undirected connected graph with N nodes numbered from 1 to N in her notebook.

Each node is shaded in either white or black. We define nW to be the number of white nodes, and nB to be the number of black nodes. The graph is drawn in such a way that:

No 2 adjacent nodes have same coloring.
The value of |nW - nB|, which we'll call D, is minimal.
Nikita's mischievous little brother erased some of the edges and all of the coloring from her graph! As a result, the graph is now decomposed into one or more components. Because you're her best friend, you've decided to help her reconstruct the graph by adding K edges such that the aforementioned graph properties hold true.

Given the decomposed graph, construct and shade a valid connected graph such that the difference |nW - nB| between its shaded nodes is minimal.

Input Format

The first line contains 2 space-separated integers, N (the number of nodes in the original graph) and M (the number of edges in the decomposed graph), respectively.
The M subsequent lines each contain2  space-separated integers, u and v, describing a bidirectional edge between nodes u and v in the decomposed graph.

Constraints
1 <= N <= 2*10^5
0 <= M <= min(5*10^5, (N *(N-1))/2)

It is guaranteed that every edge will be between 2 distinct nodes, and there will never be more than 1 edge between any 2 nodes.
Your answer must meet the following criteria:
The graph is connected and no 2 adjacent nodes have the same coloring.
The value of |nB - nW| is minimal.
K <= 2*10^5

Output Format

You must have K+1 lines of output. The first line contains 2 space-separated integers: D (the minimum possible value of |nB - nW|) and K (the number of edges you've added to the graph), respectively.
Each of the K subsequent lines contains 2 space-separated integers, u and v, describing a newly-added bidirectional edge in your final graph (i.e.: new edge u <-> v).

You may print any 1 of the possible reconstructions of Nikita's graph such that the value of D in the reconstructed shaded graph is minimal.



Solution :



title-img


                            Solution in C :

In C++ :





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

#define ft first
#define sd second
#define pb push_back
#define all(x) x.begin(),x.end()

#define ll long long int
#define vi vector<int>
#define vii vector<pair<int,int> >
#define pii pair<int,int>
#define vl vector<ll>
#define vll vector<pair<ll,ll> >
#define pll pair<ll,ll>
#define pli pair<ll,int>
#define mp make_pair

#define sc1(x) scanf("%d",&x)
#define sc2(x,y) scanf("%d%d",&x,&y)
#define sc3(x,y,z) scanf("%d%d%d",&x,&y,&z)

#define scll1(x) scanf("%lld",&x)
#define scll2(x,y) scanf("%lld%lld",&x,&y)
#define scll3(x,y,z) scanf("%lld%lld%lld",&x,&y,&z)

#define pr1(x) printf("%d\n",x)
#define pr2(x,y) printf("%d %d\n",x,y)
#define pr3(x,y,z) printf("%d %d %d\n",x,y,z)

#define prll1(x) printf("%lld\n",x)
#define prll2(x,y) printf("%lld %lld\n",x,y)
#define prll3(x,y,z) printf("%lld %lld %lld\n",x,y,z)

#define pr_vec(v) for(int i=0;i<v.size();i++) cout << v[i] << " " ;

#define f_in(st) freopen(st,"r",stdin)
#define f_out(st) freopen(st,"w",stdout)

#define fr(i, a, b) for(i=a; i<=b; i++)
#define fb(i, a, b) for(i=a; i>=b; i--)

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

const int maxn = 1e5 + 10;
const int mod = 1e9 + 7;
const int N=200010;
int w[2];
vector <int> v[N];
int a[N], d[N], p[N], c[N], col[N], sz, ccol[2][N];
bool f[N];
queue<int> q[N];
void dfs(int x,int y)
{
    f[x]=1;
    w[y]++;
    col[x] = y;
    ccol[y][sz] = x;
    for (int i=0;i<v[x].size();i++)
    if (!f[v[x][i]])
        dfs(v[x][i],(y^1));
    else if( col[v[x][i]] != 1 - y ) 
        assert(0);
}

int main() 
{
    int n,m;
    scanf("%d%d",&n,&m);
    for (int i=0,x,y;i<m;i++)
    {
        scanf("%d%d",&x,&y);
        v[x].push_back(y);
        v[y].push_back(x);
    }

    int k=0;
    for (int i=1;i<=n;i++) 
    {
        if (!f[i]) 
        {
            w[0] = w[1]=0;
            dfs(i,0);
            c[i] = (w[0] < w[1]);
            k+=abs(w[0]-w[1]);
            a[abs(w[0]-w[1])]++;
            q[abs(w[0]-w[1])].push( i );
        }
    }

    for (int j=1;j<=k;j++) 
        d[j]=N;

    for (int i=1;i<=n;i++)
    {
        if (a[i]) 
        {
            for (int j=0;j+i<=k;j++) 
            {
                if( d[i+j] == N && d[j] != N ) 
                {
                    d[i+j] = d[j] + 1;
                    p[i+j] = j;
                }
            }

            for (int j=1;j<=k;j++) 
            {
                if (d[j]>a[i]) 
                {
                    d[j]=N;
                    p[j]=0;
                } 
                else 
                {
                    d[j]=0;
                }
            }
        }
    }
    
    int ans=k, v = 0;
    for (int i=0;i<=k;i++) 
    {
        if(d[i]<N) 
        {
            if( ans >= abs(k - 2 * i) ) 
            {
                ans = abs(k - 2 * i);
                v = i;
            }
        }
    }

    memset(f, 0, sizeof f);
    while( v != 0 ) 
    {
        int diff = v - p[v];
        int nd = q[diff].front();
        q[diff].pop();
        sz ++;
        dfs(nd, c[nd]);
        v = p[v];
    }

    for(int i=1; i<=n; i++) 
    {
        if( !f[i] ) 
        {
            sz ++;
            dfs(i, 1 - c[i]);
        }
    }

    int blk, wht, idb, idw;
    blk = wht = idb = idw = -1;
    for(int i=1; i<=sz; i++) 
    {
        if( ccol[0][i] ) 
        {
            blk = ccol[0][i];
            idb = i;
        }

        if( ccol[1][i] ) 
        {
            wht = ccol[1][i];
            idw = i;
        }
    }
    cout << ans << " " << sz - 1 << "\n";
    if( idb != idw ) cout << blk << " " << wht << "\n";
    for(int i=1; i<=sz; i++) 
    {
        if( i != idb && i != idw ) 
        {
            if( ccol[0][i] ) 
            {
                cout << wht << " " << ccol[0][i] << "\n";
            } 
            else 
            {
                cout << blk << " " << ccol[1][i] << "\n";
            }
        }
    }
    return 0;
}
                        








View More Similar Problems

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →