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

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →