Kingdom Division
Problem Statement :
King Arthur has a large kingdom that can be represented as a tree, where nodes correspond to cities and edges correspond to the roads between cities. The kingdom has a total of n cities numbered from 1 to n. The King wants to divide his kingdom between his two children, Reggie and Betty, by giving each of them 0 or more cities; however, they don't get along so he must divide the kingdom in such a way that they will not invade each other's cities. The first sibling will invade the second sibling's city if the second sibling has no other cities directly connected to it. For example, consider the kingdom configurations below: image Given a map of the kingdom's n cities, find and print the number of ways King Arthur can divide it between his two children such that they will not invade each other. As this answer can be quite large, it must be modulo 10^9 + 7. Input Format The first line contains a single integer denoting n (the number of cities in the kingdom). Each of the n-1 subsequent lines contains two space-separated integers, u and v, describing a road connecting cities u and v. Constraints 2 <= n <= 10^5 1 <= u, v <= n It is guaranteed that all cities are connected. Subtasks 2 <= n <= 20 for 40% of the maximum score. Output Format Print the number of ways to divide the kingdom such that the siblings will not invade each other, modulo 10^9 + 7.
Solution :
Solution in C :
In C++ :
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#define MOD 1000000007
#define MAXN 100010
using namespace std;
typedef long long ll;
typedef vector < int > vi;
ll dp[MAXN][2];
vector < vi > adj;
void Solve(int node, int isdiff, int pre) {
if (dp[node][isdiff] != -1LL) return;
for (int i=0; i<adj[node].size(); i++) if (adj[node][i] != pre) {
Solve(adj[node][i], 0, node);
Solve(adj[node][i], 1, node);
}
ll retval = 1LL;
for (int i=0; i<adj[node].size(); i++) if (adj[node][i] != pre)
retval = (retval * (dp[adj[node][i]][1] + dp[adj[node][i]][0])%MOD)%MOD;
ll del = 0LL;
if (isdiff) {
del = 1LL;
for (int i=0; i<adj[node].size(); i++) if (adj[node][i] != pre)
del = (del * (dp[adj[node][i]][1])%MOD)%MOD;
}
retval = (retval + MOD - del)%MOD;
dp[node][isdiff] = retval;
}
int main(){
memset(dp, -1, sizeof dp);
int n;
cin >> n;
adj.assign(n+2, vi());
for(int a0 = 0; a0 < n-1; a0++){
int u;
int v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
Solve(1, 1, -1);
cout << (dp[1][1]+dp[1][1])%MOD << endl;
return 0;
}
In Java :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
private static final int MOD = 1_000_000_007;
boolean[] visited;
Graph g;
private class Graph {
private Map<Integer, LinkedList<Integer>> nb;
public Graph(int n) {
nb = new HashMap<Integer, LinkedList<Integer>>();
for (int i = 0; i < n; ++i) {
nb.put(i, new LinkedList<Integer>());
}
}
private void addNb(int node1, int node2) {
nb.get(node1).add(node2);
}
private List<Integer> getNb(int node) {
return nb.get(node);
}
}
class Count {
long strong, weak;
Count(long strong, long weak) {
this.strong = strong;
this.weak = weak;
}
}
private Count compute(int node) {
visited[node] = true;
List<Integer> nb = g.getNb(node);
int cnb = 0;
for (int nei : nb) {
if (!visited[nei]) {
cnb++;
}
}
if (cnb == 0) {
return new Count(0, 1);
}
Count[] count = new Count[cnb];
int last = 0;
for (int nei : nb) {
if (!visited[nei]) {
count[last++] = compute(nei);
}
}
Count res = new Count(0, 0);
// Weak -> all have different color & strong.
res.weak = 1;
for (int i = 0; i < cnb; i++) {
res.weak = (res.weak * count[i].strong) % MOD;
}
// Strong -> All strong for the other color or
// strong+weak for this color, but at least one of this color.
// prod(StrongOther+StrongThis+WeakThis) - prod(StrongOther)
res.strong = 1;
long prodStrong = 1;
for (int i = 0; i < cnb; i++) {
res.strong = (res.strong *(2 * count[i].strong + count[i].weak)) % MOD;
prodStrong = (prodStrong * count[i].strong) % MOD;
}
res.strong = (res.strong + MOD - prodStrong) % MOD;
return res;
}
private void solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
g = new Graph(n);
for(int a0 = 0; a0 < n-1; a0++){
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
g.addNb(u, v);
g.addNb(v, u);
}
visited = new boolean[n];
Count res = compute(0);
System.out.println((2 * res.strong) % MOD);
}
public static void main(String[] args) {
new Solution().solve();
}
}
In C :
#include <stdio.h>
#include <stdlib.h>
#define MOD 1000000007
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);
long long not_care[100000],safe[100000];
lnode *table[100000]={0};
int main(){
int n,x,y,i;
scanf("%d",&n);
for(i=0;i<n-1;i++){
scanf("%d%d",&x,&y);
insert_edge(x-1,y-1,0);
}
dfs(0,-1);
printf("%lld",safe[0]*2%MOD);
return 0;
}
void insert_edge(int x,int y,int w){
lnode *t=(lnode*)malloc(sizeof(lnode));
t->x=y;
t->w=w;
t->next=table[x];
table[x]=t;
t=(lnode*)malloc(sizeof(lnode));
t->x=x;
t->w=w;
t->next=table[y];
table[y]=t;
return;
}
void dfs(int x,int y){
int f=0;
long long not_safe=1;
lnode *p;
not_care[x]=1;
for(p=table[x];p;p=p->next)
if(p->x!=y){
dfs(p->x,x);
f=1;
not_care[x]=(not_care[p->x]+safe[p->x])%MOD*not_care[x]%MOD;
not_safe=not_safe*safe[p->x]%MOD;
}
if(!f)
safe[x]=0;
else
safe[x]=(not_care[x]-not_safe+MOD)%MOD;
return;
}
In Python3 :
#!/bin/python3
mod = 1000000007
num_cities = int(input().strip())
roads = [None]+[list() for _ in range(num_cities)]
child = [True] * (num_cities+1)
for _ in range(num_cities-1):
u,v = [int(x) for x in input().split()]
roads[u].append(v)
roads[v].append(u)
todo = [1]
i = 0
while i < len(todo):
c = todo[i]
child[c] = False
for j in roads[c]:
if child[j]:
todo.append(j)
i += 1
combos = [[-1,-1]] * (num_cities+1)
for c in reversed(todo):
children = [combos[x] for x in roads[c] if combos[x] != [-1,-1]]
if not children:
combos[c] = [0,1]
continue
slaves = sum(1 for x in children if x[0]==0)
prod = 1
for cc in children:
prod = (prod * sum(cc)) % mod
unfree = 1
for cc in children:
haf = cc[0]
if 1 & haf:
haf += mod
haf = haf >> 1
unfree = (unfree * haf) % mod
free = (mod + mod +((prod-unfree)*2)) % mod
combos[c] = [free,unfree]
print(combos[1][0])
View More Similar Problems
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 →Tree Coordinates
We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For
View Solution →Array Pairs
Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .
View Solution →Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →Array and simple queries
Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty
View Solution →