Array Construction


Problem Statement :


Professor GukiZ has hobby — constructing different arrays. His best student, Nenad, gave him the following task that he just can't manage to solve:

Construct an n-element array, A, where the sum of all elements is equal to s and the sum of absolute differences between each pair of elements is equal to k. All elements in A must be non-negative integers.
  A0+A1+...+An-1 = s
  ΣΣ |Ai-Aj| = k
If there is more then one such array, you need to find the lexicographically smallest one. In the case no such array A exists, print -1.

Note: An array, A, is considered to be lexicographically smaller than another array, B, if there is an index i such that Ai<Bi and, for any index j<i, Aj=Bj.

Input Format

The first line contains an integer, q, denoting the number of queries.
Each of the q subsequent lines contains three space-separated integers describing the respective values of n (the number of elements in array A), s (the sum of elements in A), and k (the sum of absolute differences between each pair of elements).

Constraints
1 <= q <= 100
1 <= n <= 50
0 <= s <= 200
0 <= k <=2000



Solution :



title-img


                            Solution in C :

In C++ :





#include <bits/stdc++.h>
typedef long long LL;
using namespace std;

int main(){
	int q;
	cin >> q;
	for(int Q = 0; Q < q; Q++){
		int n, s, k;
		cin >> n >> s >> k;
		int dp[s+1][k+1];
		for(int i = 0; i <= s; i++){
			for(int j = 0; j <= k; j++){
				dp[i][j] = 0;
			}
		}
		dp[0][0] = 1;
		int done = 0;
		for(int c = 1; c <= n; c++){
			int d = c*(n-c);
			for(int i = 0; i + c <= s; i++){
				for(int j = 0; j + d <= k; j++){
					if(dp[i][j] != 0 && dp[i+c][j+d] == 0){
						dp[i+c][j+d] = c;
					}
				}
			}
			if(dp[s][k]){
				int diff[n];
				for(int i = 0; i < n; i++) diff[i] = 0;
				int cs = s;
				int ck = k;
				while(cs > 0 || ck > 0){
					int a = dp[cs][ck];
					int b = a*(n-a);
					diff[n-a]++;
					cs -= a;
					ck -= b;
				}
				int r = 0;
				for(int i = 0; i < n; i++){
					r += diff[i];
					cout << r << " ";
				}
				cout << endl;
				done = 1;
				break;
			}
		}
		if(!done){
			cout << -1 << endl;
		}
	}
}








In Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        while (q-- > 0){
            List<Integer> solution = solve(in.nextInt(), in.nextInt(), in.nextInt());
            if (solution == null)
                System.out.println(-1);
            else{
                String s = "";
                for (int i : solution)
                    s = i + " " + s;
                System.out.println(s);
            }
        }
    }
    
    private static List<Integer> solve(int n, int s, int k){
        if (k < 0)
            return null;
        else if (n == 1){
            if (k > 0)
                return null;
            else{
                List<Integer> l = new ArrayList<Integer>();
                l.add(s);
                return l;
            }
        }
        else if (k > s * (n - 1) || (s * (n - 1)) % 2 != k % 2)
            return null;
        else{
            for (int x = 0; x <= s / n; x++){
                List<Integer> solution = solve(n - 1, s - n * x, k + n * x - s);
                if (solution != null){
                    for (int i = 0; i < n - 1; i++)
                        solution.set(i, solution.get(i) + x);
                    solution.add(x);
                    return solution;
                }
            }
            return null;
        }
    }
}









In C :






#include <stdio.h>
#include <stdlib.h>

#define maxS 200
#define maxN 50
#define maxK 2000
#define maxNodes (200 + 1) * (2000 + 1)


void printArray(short array[], int size) {
    for (int i = 1; i < size; i++) {
        printf("%hd ", array[i]);
    }
    printf("%hd\n", array[size]);
}


struct Node {
    short init;
    short s, k, val;
    struct Node* prevNode;
};


struct Node** _initDP() {
    struct Node** output = malloc(sizeof(struct Node*) * maxN);
    struct Node* firstDP = malloc(sizeof(struct Node) * maxNodes);
    for (int i = 0; i <= maxS; i++) {
        firstDP[i].init = 1;
        firstDP[i].s = i;
        firstDP[i].k = 0;
        firstDP[i].val = i;
        firstDP[i].prevNode = &firstDP[i];
    }   
    output[0] = firstDP;
    return output;
}


struct Node** createDP() {
    struct Node** output = _initDP();
    struct Node* oldNode;
    int newVal, newS, newK;
    for (int i = 1; i < maxN; i++) {
        struct Node* oldDP = output[i - 1];
        struct Node* newDP = malloc(sizeof(struct Node) * maxNodes);
        short* hasFound =  (short*) calloc(maxNodes, sizeof(short));
        int nodeIdx = 0;
        for (int j = 0; j < maxNodes; j++) {
            oldNode = &(oldDP[j]);
            if (oldNode->init == 0) { break; }
            newVal = oldNode->val;
        
            while (1) {
                newS = oldNode->s + newVal;
                if (newS > maxS) { break; }
                newK = oldNode->k - oldNode->s + (newVal * i);
                if (newK > maxK) { break; }
                int newIdx = newK * (maxS + 1) + newS;
                if (hasFound[newIdx] == 0 || hasFound[newIdx] > newVal + 1) {
                    newDP[nodeIdx].init = 1;
                    newDP[nodeIdx].s = newS;
                    newDP[nodeIdx].k = newK;
                    newDP[nodeIdx].val = newVal;
                    newDP[nodeIdx].prevNode = oldNode;
                    hasFound[newIdx] = newVal + 1;
                    nodeIdx += 1;
                }
                newVal += 1;
            }          
        }
        output[i] = newDP;
        free(hasFound);       
    }
    return output; 
}

void printSolution(int n, int s, int k, struct Node* dp) {
    for (int i = 0; i < maxNodes; i++) {
        if (dp[i].init == 0) { break; }
        //printf("  s = %hd and k = %hd val = %hd\n", dp[i].s, dp[i].k, dp[i].val);
        if (dp[i].s == s && dp[i].k == k) {
            struct Node thisNode = dp[i];
            short* solution = malloc(sizeof(short) * (n + 1));
            int count = n;
            while (count > 0) {
                solution[count] = thisNode.val;
                count -= 1;
                thisNode = *(thisNode.prevNode);
            }
            printArray(solution, n);
            return;
        }
    }
    printf("-1\n");
}


int main() {
    int numQueries, n, s, k;
    struct Node** dp = createDP();
    scanf("%d", &numQueries);
    for (int i = 0; i < numQueries; i++) {
        scanf("%d %d %d", &n, &s, &k);
        printSolution(n, s, k, dp[n - 1]);
    }
    return 0;
}










In Python3 :





cumsum = []
res = []

def mn(ceil, beans):
    return (beans // ceil) * cumsum[ceil] + cumsum[beans % ceil]
def mx(ceil, beans):
    return cumsum[1] * beans

fmemo = set()
def f(ceil, sm, beans):
    if not (mn(ceil, beans) <= sm <= mx(ceil, beans)):
        return False
    if beans == 0 and sm == 0:
        return True
    if (ceil, sm, beans) in fmemo:
        return False
    
    for k in range(1, min(beans, ceil) + 1):
        if f(k, sm - cumsum[k], beans - k):
            res.append(k)
            return True
    fmemo.add((ceil, sm, beans))
    return False
    
        

for _ in range(int(input())):
    n, s, k = map(int, input().split())
    if n == 1:
        if k == 0:
            print(s)
        else:
            print(-1)
        continue
    if s == 0:
        if k == 0:
            print(' '.join(map(str,[0 for _ in range(n)])))
        else:
            print(-1)
        continue
    
    cumsum = [0, 2*n - 2]
    for i in range(1, n):
        cumsum.append(cumsum[-1] + 2*n - 2 - 2*i)
    res = []
    f(n, k + (n - 1) * s, s)
    if res:
        r = [0 for _ in range(n)]
        for num in res:
            for i in range(num):
                r[-1-i] += 1
        print(' '.join(map(str,r)))
    else:
        print(-1)
                        








View More Similar Problems

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 →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →