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:


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.


2 <= n <= 10^5
1 <= u, v <= n
It is guaranteed that all cities are connected.


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;
    Solve(1, 1, -1);
    cout << (dp[1][1]+dp[1][1])%MOD << endl;
    return 0;

In Java :

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) {

        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]) {
        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(;
        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;
  return 0;
void insert_edge(int x,int y,int w){
  lnode *t=(lnode*)malloc(sizeof(lnode));
void dfs(int x,int y){
  int f=0;
  long long not_safe=1;
  lnode *p;

In 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()]

todo = [1]
i = 0

while i < len(todo):
    c = todo[i]
    child[c] = False
    for j in roads[c]:
        if child[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]
    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]

View More Similar Problems

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

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 →