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 :
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
Swap Nodes [Algo]
A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from
View Solution →Kitty's Calculations on a Tree
Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a
View Solution →Is This a Binary Search Tree?
For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a
View Solution →Square-Ten Tree
The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the
View Solution →Balanced Forest
Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a
View Solution →Jenny's Subtrees
Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .
View Solution →