Zurikela's Graph


Problem Statement :


Zurikela is creating a graph with a special graph maker. At the begining, it is empty and has no nodes or edges. He can perform 3 types of operations:

1. A x : Create a set of x new nodes and name it set-K.
2. B x y: Create edges between nodes of set-x and set-y.
3. C x : Create a set composed of nodes from set-x and its directly and indirectly connected nodes, called set-K. Note that each node can only exist in one set, so other sets become empty.
The first set's name will be set-1. In first and third operation K is referring to the index of new set:

K = [index of last created set] + 1
Create the graph by completing the Q operations specified during input. Then calculate the maximum number of independent nodes (i.e.:how many nodes in the final graph which don't have direct edge between them).

Input Format

The first line contains Q.
The Q subsequent lines each contain an operation to be performed.

Constraints
.1 <= Q <= 10^5
For the first operation, 1 <= x <= 10^4.
For the second operation, x < y and all ys are distinct.
For the second and third operation, it's guaranteed that set-x and set-y exist.

Output Format

Print maximum number of independent nodes in the final graph (i.e.: nodes which have no direct connection to one another).



Solution :



title-img


                            Solution in C :

In C++ :





#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <queue>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <cctype>
#include <cassert>
#include <limits>
#include <functional>
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i))
#define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i))
#if defined(_MSC_VER) || __cplusplus > 199711L
#define aut(r,v) auto r = (v)
#else
#define aut(r,v) __typeof(v) r = (v)
#endif
#define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it)
#define all(o) (o).begin(), (o).end()
#define pb(x) push_back(x)
#define mp(x,y) make_pair((x),(y))
#define mset(m,v) memset(m,v,sizeof(m))
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL
using namespace std;
typedef vector<int> vi; 
typedef pair<int, int> pii;
typedef vector<pair<int, int> > vpii; typedef long long ll;
template<typename T, typename U> inline void amin(T &x, U y)
 { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) 
{ if(x < y) x = y; }

vector<int> weight;
vector<vi> tree;
vector<int> child;
vector<int> memo;
int K;

int recTree(int i, int p, int j, bool b) {
	if(tree[i].size() == j) {
		int &r = memo[(K + i) * 2 + b];
		if(r != -1) return r;
		if(!b) {
			return r = 0;
		} else if(child[i] == -1) {
			return r = weight[i];
		} else {
			r = 0;
			rep(cb, 2)
				amax(r, recTree(child[i], -1, 0, cb != 0));
			return r;
		}
	}
	int c = tree[i][j];
	if(c == p)
		return recTree(i, p, j + 1, b);
	int &r = memo[c * 2 + b];
	if(r != -1) return r;
	r = 0;
	amax(r, recTree(c, i, 0, false) + recTree(i, p, j + 1, b));
	if(!b)
		amax(r, recTree(c, i, 0, true) + recTree(i, p, j + 1, b));
	return r;
}

void traverse(int x, vi &q, vector<bool> &vis) {
	q.clear();
	q.push_back(x);
	for(int h = 0; h != q.size(); ++ h) {
		int i = q[h];
		for(int j : tree[i]) if(!vis[j]) {
			vis[j] = true;
			q.push_back(j);
		}
	}
}

int main() {
	int Q;
	while(~scanf("%d", &Q)) {
		K = 0;
		weight.assign(Q, -1);
		tree.assign(Q, vi());
		child.assign(Q, -1);
		vi q;
		vector<bool> vis(Q, false);
		for(int ii = 0; ii < Q; ++ ii) {
			char ty[10];
			scanf("%s", ty);
			if(*ty == 'A') {
				int x;
				scanf("%d", &x);
				weight[K] = x;
				++ K;
			} else if(*ty == 'B') {
				int x; int y;
				scanf("%d%d", &x, &y), -- x, -- y;
				if(!vis[x] && !vis[y]) {
					tree[x].push_back(y);
					tree[y].push_back(x);
				}
			} else if(*ty == 'C') {
				int x;
				scanf("%d", &x), -- x;
				traverse(x, q, vis);
				child[K] = x;
				++ K;
			} else abort();
		}
		memo.assign(K * 4, -1);
		int ans = 0;
		rep(i, K) if(!vis[i]) {
			traverse(i, q, vis);
			int x = 0;
			rep(b, 2)
				amax(x, recTree(i, -1, 0, b != 0));
			ans += x;
		}
		printf("%d\n", ans);
	}
	return 0;
}








In Java :





import java.io.*;
import java.math.*;
import java.util.*;

public class CodeSprint6_2 {
    static class Node{
        int val;
        boolean active;
        int parent;
        int ansTake;
        int ansNotTake;
        ArrayList<Integer> next;
        public Node(){
            next=new ArrayList<>();
        }
    }
    static int[] val;
    static boolean[] active;
    static int[] parent;
    static int n;
    static int ansTake[];
    static int ansNotTake[]; 
    static ArrayList<Integer> next[];
    static Node[] v;
    public static void main(String ars[]) {
        Scanner in = new Scanner(System.in);
        int q=in.nextInt();
        in.nextLine();
        n=0;
        v=new Node[q];
        for(int i=0;i<q;i++){
            v[i]=new Node();
        }
        for(int t=0;t<q;t++){
            String[] input = in.nextLine().split(" ");
            if(input[0].equals("A")){
                v[n].val=Integer.parseInt(input[1]);
                v[n].next=new ArrayList<>();
                v[n].active=true;
                v[n].parent=-1;
                n++;
            }
            if(input[0].equals("B")){
                int x=Integer.parseInt(input[1])-1;
                int y=Integer.parseInt(input[2])-1;
                if(v[x].active && v[y].active){
                    v[x].next.add(y);
                    v[y].parent=x;
                }
            }
            if(input[0].equals("C")){
                int z=Integer.parseInt(input[1])-1;
                while(v[z].parent!=-1)
                    z=v[z].parent;
                int ans=findAnswer(z)[1];
                v[n].val=ans;
                v[n].next=new ArrayList<>();
                v[n].active=true;
                v[n].parent=-1;
                n++;
            }
        }
        int finalAnswer=0;
        for(int i=0;i<n;i++){
            if(v[i].active){
                int z=i;
                while(v[z].parent!=-1)
                    z=v[z].parent;
                finalAnswer+=findAnswer(z)[1];
            }
        }
        System.out.println(finalAnswer);
    }
    
    static int[] findAnswer(int z){
        int[] duet = new int[2];
        duet[0]=0;
        duet[1]=v[z].val;
        
        for(int x:v[z].next){
            int temp[] = findAnswer(x);
            duet[1]+=temp[0];
            duet[0]+=temp[1];
        }
        duet[1]=Math.max(duet[0], duet[1]);
        v[z].active=false;
        return duet;
    }
    
}








In C :





#include <stdio.h>
#include <stdlib.h>
typedef struct _lnode{
  int x;
  int w;
  struct _lnode *next;
} lnode;
void insert_edge(int x,int y,int w);
void dfs(int x,int y);
int max(int x,int y);
char str[2];
int a[100000],dp1[2][100000],track[100000]={0};
lnode *table[100000]={0};

int main(){
  int Q,x,y,c=0;
  scanf("%d",&Q);
  while(Q--){
    scanf("%s",str);
    switch(str[0]){
      case 'A':
        scanf("%d",&x);
        a[c++]=x;
        break;
      case 'B':
        scanf("%d%d",&x,&y);
        insert_edge(x-1,y-1,1);
        break;
      default:
        scanf("%d",&x);
        dfs(x-1,-1);
        a[c++]=max(dp1[0][x-1],dp1[1][x-1]);
    }
  }
  for(x=y=0;x<c;x++)
    if(!track[x]){
      dfs(x,-1);
      y+=max(dp1[0][x],dp1[1][x]);
    }
  printf("%d",y);
  return 0;
}
void insert_edge(int x,int y,int w){
  lnode *t=malloc(sizeof(lnode));
  t->x=y;
  t->w=w;
  t->next=table[x];
  table[x]=t;
  t=malloc(sizeof(lnode));
  t->x=x;
  t->w=w;
  t->next=table[y];
  table[y]=t;
  return;
}
void dfs(int x,int y){
  lnode *p;
  track[x]=1;
  for(p=table[x];p;p=p->next)
    if(p->x!=y)
      dfs(p->x,x);
  dp1[1][x]=0;
  dp1[0][x]=a[x];
  for(p=table[x];p;p=p->next)
    if(p->x!=y){
      dp1[0][x]+=dp1[1][p->x];
      if(dp1[0][p->x]>dp1[1][p->x])
        dp1[1][x]+=dp1[0][p->x];
      else
        dp1[1][x]+=dp1[1][p->x];
    }
  return;
}
int max(int x,int y){
  return (x>y)?x:y;
}








In Python3 :





from itertools import repeat
M = 200010
AdjList = [[] for i in repeat(None, M)];
dppp = [0 for i in range(M)];
dpp1 = [0 for i in range(M)];
my_str = ""
done = [0 for i in range(M)];
max_ind = [0 for i in range(M)];
N = 0;

def dfs(node, dad):
	dpp1[node] = max_ind[node];
	for i in range(len(AdjList[node])):
		v = AdjList[node][i];
		if v != dad:
			dfs(v, node);
			dppp[node] = dppp[node] + max(dppp[v], dpp1[v]);
			dpp1[node] = dpp1[node] + dppp[v];
	done[node] = 0;

Q = int(input());

for q in range(Q):
	my_str = str(input());
	u = my_str.split(' ');
	if(my_str[0] == 'A'):
		x = int(u[1]);
		N = N + 1;
		max_ind[N] = x;
		done[N] = 1;
	elif my_str[0] == 'B':
		x = int(u[1]);
		y = int(u[2]);
		AdjList[x].append(y);
		AdjList[y].append(x);
	elif my_str[0] == 'C':
		x = int(u[1]);
		dfs(x, x);
		N = N + 1;
		max_ind[N] = max(dppp[x], dpp1[x]);
		done[N] = 1;
ans = 0;
for i in range(N):
	if done[i + 1] == 1 :
		dfs(i + 1, i + 1);
		ans = ans + max(dppp[i + 1], dpp1[i + 1]);
print(str(ans));
                        








View More Similar Problems

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →