Time spent here:

Monday, 11 April 2016

NIKITHA AND THE GAME

PROBLEM STATEMENT:

Nikita just came up with a new array game. The rules are as follows:
  • Initially, there is an array, AA, containing NN integers.
  • In each move, Nikita must partition the array into 22 non-empty parts such that the sum of the elements in the left partition is equal to the sum of the elements in the right partition. If Nikita can make such a move, she gets 11 point; otherwise, the game ends.
  • After each successful move, Nikita discards either the left partition or the right partition and continues playing by using the remaining partition as array AA.
Nikita loves this game and wants your help getting the best score possible. Given AA, can you find and print the maximum number of points she can score?
Input Format
The first line contains an integer, TT, denoting the number of test cases. Each test case is described over 22 lines in the following format:
  1. A line containing a single integer, NN, denoting the size of array AA.
  2. A line of NN space-separated integers describing the elements in array AA.
Constraints
  • 1T101T10
  • 1N2141N214
  • 0Ai1090Ai109
Scoring
  • 1N281N28 for 30%30% of the test data
  • 1N2111N211 for 60%60% of the test data
  • 1N2141N214 for 100%100% of the test data
Output Format
For each test case, print Nikita's maximum possible score on a new line.

PYTHON CODE: 
T = input()

while T > 0:
    N = input()
    A = map(int, raw_input().strip().split(' '))

    score = 0

    fsum = A*1
    h = {fsum[0]:0}
    for i in xrange(1,N):
        fsum[i] += fsum[i-1]
        h[fsum[i]] = i
    anchors = {0:True}      # half-points in sum-space

    if fsum[-1]==0:         # if all zeros
        score = N-1
    elif fsum[-1]%2==0:
        offset = fsum[-1]/2
        while anchors:
            for a in anchors.keys():
                if (a+offset) in h:
                    anchors[a+offset] = True
                else:
                    del anchors[a]
            if anchors:     # some offsets succeeded
                score += 1
            if offset%2==0:
                offset /= 2
            else:
                anchors = None

    print score

    T -= 1
OUTPUT:

No comments:

Post a Comment