Two Two


Problem Statement :


Prof. Twotwo as the name suggests is very fond powers of 2. Moreover he also has special affinity to number 800. He is known for carrying quirky experiments on powers of 2.

One day he played a game in his class. He brought some number plates on each of which a digit from 0 to 9 is written. He made students stand in a row and gave a number plate to each of the student. Now turn by turn, he called for some students who are standing continuously in the row say from index i to index j (i<=j) and asked them to find their strength.

The strength of the group of students from i to j is defined as:

strength(i , j)
{
    if a[i] = 0
        return 0; //If first child has value 0 in the group, strength of group is zero
    value = 0;
    for k from i to j
        value = value*10 + a[k]
    return value;
} 
Prof called for all possible combinations of i and j and noted down the strength of each group. Now being interested in powers of 2, he wants to find out how many strengths are powers of two. Now its your responsibility to get the answer for prof.

Input Format

First line contains number of test cases T
Next T line contains the numbers of number plates the students were having when standing in the row in the form of a string A.

Constraints

1 ≤ T ≤ 100
1 ≤ len(A) ≤ 105
0 ≤ A[i] ≤ 9

Output Format

Output the total number of strengths of the form 2x such that 0 ≤ x ≤ 800.



Solution :



title-img


                            Solution in C :

In   C++ :






#include <iostream>
#include <cstdio>
#include <ctime>

using namespace std;

struct node
{
	int e;
	struct node *path[10];
};

int prodf[400],prodlen;
char bstr[123456];
struct node *posStack[300];
int stackSize=0;

struct node* addEdge(struct node *start, int edge)
{
    if (start->path[edge]==NULL)
    {
        struct node *tempNode = new node;
        tempNode->e=0;
        for(int i=0;i<10;++i)
            tempNode->path[i]=NULL;
        start->path[edge]=tempNode;
    }
    return (start->path[edge]);
}

void markEnd(struct node *vnode)
{
    vnode->e=1;
}

int main()
{
	clock_t t_start =clock();
    prodlen=1;
	prodf[0]=1;
    struct node *automaton = new struct node;
    automaton->e=0;
    for(int i=0;i<10;++i)
        automaton->path[i]=NULL;
    struct node *ppos=automaton;
    ppos=addEdge(ppos,1);
    markEnd(ppos);
	for(int n=1;n<=800;++n)
	{
		int rem=0;
		for(int i=0;i<prodlen;++i)
		{
			rem=(2*prodf[i]+rem);
			prodf[i]=rem%10;
			rem/=10;
		}
		if(rem!=0)
			prodf[prodlen++]=rem;
		ppos=automaton;
		for(int i=prodlen-1;i>=0;--i)
		{
			ppos = addEdge(ppos,prodf[i]);
		}
		markEnd(ppos);
	}
    clock_t t_end=clock();
 //   cout<<(t_end+0.0-t_start)/CLOCKS_PER_SEC<<endl;

    int T,k;
    cin>>T;
    while(T--)
    {
    	long long ans=0;
    	stackSize=0;
    	scanf("%s",bstr);
    	for(int i=0,j;bstr[i]!='\0';++i)
    	{
    		k=bstr[i]-'0';
    		for(j=0;j<stackSize;)
    		{
    			if(posStack[j]->path[k]!=NULL)
    			{
    				posStack[j]=posStack[j]->path[k];
    				if(posStack[j]->e==1)
    					ans++;
    				++j;
    			}
    			else
    				posStack[j]=posStack[--stackSize];
    		}
    		if(automaton->path[k]!=NULL)
    		{
    			posStack[stackSize]=automaton->path[k];
    			if(posStack[stackSize]->e==1)
    				ans++;
    			++stackSize;
    		}
    	}
    	cout<<ans<<endl;
    }

    return 0;
}









In   Java  :







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

public class Solution {

    static class Node {
        Node[] edges = new Node[10];
        Node slink;

        int weight;
    }

    public static void solve(Input in, PrintWriter out) throws IOException {
        Node root = new Node();
        for (int pow = 0; pow <= 800; ++pow) {
            String s = BigInteger.ONE.shiftLeft(pow).toString();
            Node cur = root;
            for (char c : s.toCharArray()) {
                if (cur.edges[c - '0'] == null) {
                    cur.edges[c - '0'] = new Node();
                }
                cur = cur.edges[c - '0'];
            }
            cur.weight++;
        }
        ArrayList<Node> q = new ArrayList<Node>();
        q.add(root);
        for (int it = 0; it < q.size(); ++it) {
            Node n = q.get(it);
            for (int i = 0; i < 10; ++i) {
                Node n1 = n.edges[i];
                if (n1 == null) {
                    continue;
                }
                q.add(n1);
                n1.slink = n.slink;
                while (n1.slink != null && n1.slink.edges[i] == null) {
                    n1.slink = n1.slink.slink;
                }
                if (n1.slink == null) {
                    n1.slink = root;
                } else {
                    n1.slink = n1.slink.edges[i];
                }
            }
        }
        for (Node n : q) {
            if (n.slink != null) {
                n.weight += n.slink.weight;
            }
        }
        for (Node n : q) {
            for (int i = 0; i < 10; ++i) {
                if (n.edges[i] == null) {
                    if (n.slink == null) {
                        n.edges[i] = root;
                    } else {
                        n.edges[i] = n.slink.edges[i];
                    }
                }
            }
        }
        int tests = in.nextInt();
        for (int test = 0; test < tests; ++test) {
            String s = in.next();
            int ans = 0;
            Node cur = root;
            for (char c : s.toCharArray()) {
                cur = cur.edges[c - '0'];
                ans += cur.weight;
            }
            out.println(ans);
        }
    }

    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);
        solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);
        out.close();
    }

    static class Input {
        BufferedReader in;
        StringBuilder sb = new StringBuilder();

        public Input(BufferedReader in) {
            this.in = in;
        }

        public Input(String s) {
            this.in = new BufferedReader(new StringReader(s));
        }

        public String next() throws IOException {
            sb.setLength(0);
            while (true) {
                int c = in.read();
                if (c == -1) {
                    return null;
                }
                if (" \n\r\t".indexOf(c) == -1) {
                    sb.append((char)c);
                    break;
                }
            }
            while (true) {
                int c = in.read();
                if (c == -1 || " \n\r\t".indexOf(c) != -1) {
                    break;
                }
                sb.append((char)c);
            }
            return sb.toString();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }
    }
}









In   C  :







#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int read_int() {
    int ret;
    scanf("%d", &ret);
    return ret;
}
static int *read_int_array(int n) {
    int *ret = malloc(n * sizeof(int));
    for (int i = 0; i < n; ++i) {
        scanf("%d", ret + i);
    }
    return ret;
}
static int intcomp(const void *v1, const void *v2) {
    return *(const int *)v1 - *(const int *)v2;
}
#define BASE 801
static char powers[BASE][250];
static int power_nums[801];
static void build_powers() {
    powers[0][0] = '1';
    powers[0][1] = '\0';
    power_nums[0] = 1;
    for (int i = 1; i <= 800; ++i) {
        int previous = power_nums[i - 1];
        char *ppower  = powers[i - 1];
        int start_pos = previous;
        if (ppower[0] >= '5') {
            start_pos ++;
        }
        power_nums[i] = start_pos;
        char *current = powers[i];
        current[start_pos] = '\0';
        int rem = 0;
        for (int j = previous - 1; j >= 0; --j) {
            int val = (ppower[j] - '0') * 2 + rem;
            rem = val / 10;
            current[start_pos - 1] = '0' + (val % 10);
            start_pos --;
        }
        if (rem != 0) {
            current[0] = '0' + rem;
        }
    }
}
struct node {
    struct node *childs;
    char child_count;
    char c;
    char end;
};
static void init_node(struct node *n, char c, char end) {
    n->c = c;
    n->end = end;
}
static struct node *build_node() {
    struct node * root = malloc(sizeof(struct node));
    init_node(root, 0, -1);
    for (int i = 0; i < BASE; ++i) {
        struct node *n = root;
        for (const char *iter = powers[i]; *iter; iter++) {
            if (!n->childs) {
                n->childs = malloc(10 * sizeof(struct node));
                n->child_count = 10;
                for (int i = 0; i < 10; ++i) {
                    n->childs[i].c = '0' + i;
                }
            }
            n = n->childs + (*iter - '0');
        }
        n->end = 1;
    }
    return root;
}
static long long int count_appearance(const char *haystack, const char *needle) {
    long long int result = 0;
    while (1) {
        if ((haystack = strstr(haystack, needle))) {
            result ++;
            haystack++;
        } else {
            return result;
        }
    }
}
static long long int solve(const char *buffer, struct node *root) {
    long long result = 0;
    for (const char *iter = buffer; *iter; ++iter) {
        struct node *n = root;
        for (const char *iter2 = iter; *iter2; ++iter2) {
            if (!n->childs) {
                break;
            } else {
                n = &n->childs[*iter2 - '0'];
                if (n->end) {
                    result++;
                }
            }
        }
    }
    return result;
}
int main(int argc, char *argv[]) {
    build_powers();
    struct node *root = build_node();
    int t = read_int();
    char buffer[100001];
    for (int i = 0; i < t; ++i) {
        scanf(" %s", buffer);
        printf("%lld\n", solve(buffer, root));
    }
    return 0;
}









In   Python3  :








        
tree = [False, {}]

def add(word) :
    current = tree
    for c in word :
        try :
            current = current[1][c]
        except KeyError :
            current[1][c] = [False, {}]
            current = current[1][c]
    current[0] = True
    
def count(word) :
    count = 0
    for start in range(len(word)) :
        current, index = tree, start
        while True :
            if current[0] :
                count += 1
            try :
                current = current[1][word[index]]
                index += 1
            except (KeyError, IndexError) :
                break
    return count
    
v = 1
for x in range(801) :
    add(str(v)[::-1])
    v <<= 1

Done = {}    
T = int(input())
for t in range(T) :
    A = input()
    if not A in Done :
        Done[A] = count(A[::-1])
    print(Done[A])
                        








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 →