# Repetitive K-Sums

### Problem Statement :

```Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.

What is this? Let the sequence be {A, A, ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i1] + A[i2] + ... + A[iK], where 1 ≤ i1 ≤ i2 ≤ ... ≤ iK ≤ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.

Consider an example. Let N = 3 and K = 2. The sequence is {A, A, A}. The sequence of its 2-sums with repetitions is {A + A, A + A, A + A, A + A, A + A, A + A}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.

Input Format

The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence Si of all K-sums with repetitions of the sequence Alice initially thought of.

Note
The total number of elements in any input sequence does not exceed 105
Each element of each input sequence is non-negative integer not exceeding 1018.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.

Output Format

For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.```

### Solution :

```                            ```Solution in C :

In  C  :

#include <stdio.h>
#include <stdlib.h>
typedef struct _tree_node{
enum {red,black} colour;
long long data;
int count;
struct _tree_node *left,*right,*parent;
}tree_node;
void add_num(long long num,long long **dp,tree_node **root,int K);
int bin(int n,int k);
long long get_min(tree_node *root);
void left_rotate(tree_node **root,tree_node *x);
void right_rotate(tree_node **root,tree_node *y);
void reconstruct(tree_node **root,tree_node *x);
int normal_insert(tree_node **root,tree_node *x);
void insert(tree_node **root,tree_node *x);
void delete(tree_node **root,tree_node *head,long long data);
void clean_tree(tree_node *root);

int main (){
int T,N,K,C,i;
long long a,min,**dp;
tree_node *root,*node;
dp=(long long**)malloc(1000*sizeof(long long*));
for(i=0;i<1000;i++)
dp[i]=(long long*)malloc(50000*sizeof(long long));
scanf("%d",&T);
while(T--){
root=NULL;
scanf("%d%d",&N,&K);
for(i=0;i<K;i++)
dp[i]=0;
C=bin(N+K-1,K);
for(i=0;i<C;i++){
scanf("%lld",&a);
node=(tree_node*)malloc(sizeof(tree_node));
node->data=a;
node->count=1;
node->left=node->right=node->parent=NULL;
insert(&root,node);
}
min=get_min(root);
min/=K;
printf("%lld ",min);
for(i=1;i<N;i++){
a=get_min(root);
a-=min*(K-1);
printf("%lld ",a);
if(i<N-1)
}
clean_tree(root);
printf("\n");
}
return 0;
}
void add_num(long long num,long long **dp,tree_node **root,int K){
int i,j,k;
dp++;
dp[dp]=num;
if(K==1){
delete(root,*root,num);
return;
}
for(j=K-1;j>=0;j--)
for(k=1;k<=dp[j];k++)
delete(root,*root,dp[j][k]+num*(K-1-j));
for(i=K-2;i>0;i--)
for(j=i-1;j>=0;j--)
for(k=1;k<=dp[j];k++){
dp[i]++;
dp[i][dp[i]]=dp[j][k]+num*(i-j);
}
return;
}
int bin(int n,int k){
if(k>n-k)
k=n-k;
int p=1,i;
for(i=1;i<=k;++i){
p*=n+1-i;
p/=i;
}
return p;
}
long long get_min(tree_node *root){
if(!root)
return -1;
while(root->left)
root=root->left;
return root->data;
}
void left_rotate(tree_node **root,tree_node *x){
tree_node *y;
y=x->right;
if(!y) return;
x->right=y->left;
if(y->left)
y->left->parent=x;
y->parent=x->parent;
if(x->parent==NULL) *root=y;
else
if(x==x->parent->left)
x->parent->left=y;
else
x->parent->right=y;
y->left=x;
x->parent=y;
return;
}
void right_rotate(tree_node **root,tree_node *y){
tree_node *x;
x=y->left;
if(!x) return;
y->left=x->right;
if(x->right)
x->right->parent=y;
x->parent=y->parent;
if(y->parent==NULL) *root=x;
else
if(y==y->parent->right)
y->parent->right=x;
else
y->parent->left=x;
x->right=y;
y->parent=x;
return;
}
void reconstruct(tree_node **root,tree_node *x){
tree_node *y,*z;
y=x->parent;
z=x->parent->parent;
x->colour=black;
z->colour=red;
x->parent=z->parent;
if(z->parent==NULL)
*root=x;
else if(z==z->parent->left)
z->parent->left=x;
else
z->parent->right=x;
if(z->left==y){
x->left=y;
x->right=z;
}
else{
x->left=z;
x->right=y;
}
y->parent=z->parent=x;
y->left=y->right=z->left=z->right=NULL;
return;
}
int normal_insert(tree_node **root,tree_node *x){
if(*root==NULL)
*root=x;
else if((*root)->data==x->data){
(*root)->count++;
free(x);
return 0;
}
else{
x->parent=*root;
if((*root)->data>x->data)
return normal_insert(&((*root)->left),x);
else
return normal_insert(&((*root)->right),x);
}
return 1;
}
void insert(tree_node **root,tree_node *x){
if(!normal_insert(root,x))
return;
tree_node *y;
x->colour=red;
while(x!=*root && x->parent->colour==red){
if(x->parent==x->parent->parent->left){
y=x->parent->parent->right;
if(!y)
if(x==x->parent->left){
x->parent->colour=black;
x->parent->parent->colour=red;
right_rotate(root,x->parent->parent);
}
else{
y=x->parent;
reconstruct(root,x);
x=y;
}
else if(y->colour==red){
x->parent->colour=black;
y->colour=black;
x->parent->parent->colour=red;
x=x->parent->parent;
}
else{
if(x==x->parent->right){
x=x->parent;
left_rotate(root,x);
}
x->parent->colour=black;
x->parent->parent->colour=red;
right_rotate(root,x->parent->parent);
}
}
else{
y=x->parent->parent->left;
if(!y)
if(x==x->parent->right){
x->parent->colour=black;
x->parent->parent->colour=red;
left_rotate(root,x->parent->parent);
}
else{
y=x->parent;
reconstruct(root,x);
x=y;
}
else if(y->colour==red){
x->parent->colour=black;
y->colour=black;
x->parent->parent->colour=red;
x=x->parent->parent;
}
else{
if(x==x->parent->left){
x=x->parent;
right_rotate(root,x);
}
x->parent->colour=black;
x->parent->parent->colour=red;
left_rotate(root,x->parent->parent);
}
}
}
(*root)->colour=black;
return;
}
void delete(tree_node **root,tree_node *head,long long data){
tree_node *db,*parent,*brother,*child;
return;
return;
}
return;
}
return;
}
while(db->left)
db=db->left;
}
if(!parent){
*root=NULL;
return;
}
parent->left=NULL;
else
parent->right=NULL;
if(brother)
return;
else
db=parent;
}
else{
if(!parent){
*root=child;
child->parent=NULL;
child->colour=black;
return;
}
parent->left=child;
else
parent->right=child;
child->parent=parent;
db=parent;
}
}
while(db){
if(db->colour==red){
db->colour=black;
return;
}
if(db==*root)
return;
parent=db->parent;
brother=(parent->left==db)?parent->right:parent->left;
if(!brother)
db=parent;
else if(brother==parent->right){
if(brother->colour==black && brother->right && brother->right->colour==red){
brother->colour=parent->colour;
brother->right->colour=black;
parent->colour=black;
left_rotate(root,parent);
return;
}
else if(brother->colour==black && brother->left && brother->left->colour==red){
brother->left->colour=parent->colour;
parent->colour=black;
right_rotate(root,brother);
left_rotate(root,parent);
return;
}
else if(brother->colour==black){
brother->colour=red;
db=parent;
}
else{
brother->colour=black;
parent->colour=red;
left_rotate(root,parent);
}
}
else{
if(brother->colour==black && brother->left && brother->left->colour==red){
brother->colour=parent->colour;
brother->left->colour=black;
parent->colour=black;
right_rotate(root,parent);
return;
}
else if(brother->colour==black && brother->right && brother->right->colour==red){
brother->right->colour=parent->colour;
parent->colour=black;
left_rotate(root,brother);
right_rotate(root,parent);
return;
}
else if(brother->colour==black){
brother->colour=red;
db=parent;
}
else{
brother->colour=black;
parent->colour=red;
right_rotate(root,parent);
}
}
}
return;
}
void clean_tree(tree_node *root){
if(!root)
return;
clean_tree(root->left);
clean_tree(root->right);
free(root);
return;
}```
```

```                        ```Solution in C++ :

In  C++  :

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <queue>
using namespace std;

int Tot;

long long a;
map <long long,int> mp;

void dfs(int now,int ee,int les)
{
if (les==0||now+1==ee)
{
Tot++;
return;
}
for (int i=0;i<=les;i++)
dfs(now+1,ee,les-i);
}

void dfs2(int now,long long num,int les)
{
if (now==0) num+=les*a;
if (les==0||now==0)
{
mp[num]--;
if (mp[num]==0) mp.erase(num);
return;
}
for (int i=0;i<=les;i++)
dfs2(now-1,num+i*a[now],les-i);
}

int main()
{
int T;
scanf("%d",&T);
while (T--)
{
int n,m;
scanf("%d%d",&n,&m);
Tot=0;
dfs(0,n,m);
for (int i=0;i<Tot;i++)
{
long long x;
scanf("%lld",&x);
mp[x]++;
}
for (int i=0;i<n;i++)
{
long long now=mp.begin()->first;
if (i==0)
{
a[i]=now/m;
mp[now]--;
if (mp[now]==0) mp.erase(now);
}
else
{
a[i]=now-a*(m-1);
for (int j=1;j<=m;j++)
{
dfs2(i-1,a[i]*j,m-j);
}
}
}
for (int i=0;i<n;i++)
{
if (i) printf(" ");
printf("%lld",a[i]);
}
puts("");
}
return 0;
}```
```

```                        ```Solution in Java :

In  Java :

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.PriorityQueue;

public class Solution {
static InputStream is;
static PrintWriter out;
static String INPUT = "";

static void solve()
{
for(int T = ni();T >= 1;T--){
int n = ni(), K = ni();
long xx = 1;
int U = Math.min(K, n-1);
for(int i = 1;i <= U;i++){
xx *= n-1+K-i+1;
xx /= i;
}
int x = (int)xx;
long[] a = new long[x];
for(int i = 0;i < x;i++)a[i] = nl();
Arrays.sort(a);
long[] ret = new long[n];
ret = a / K;
if(n == 1){
out.println(ret);
continue;
}
if(n == 2){
ret = a[x-1] / K;
out.println(ret + " " + ret);
continue;
}
// K <= 16
PriorityQueue<Long> pq = new PriorityQueue<Long>(x+1);
PriorityQueue<Long> ng = new PriorityQueue<Long>(x+1);
pq.poll();
for(int i = 1;i < n;i++){
while(!ng.isEmpty() && ng.peek().equals(pq.peek())){
pq.poll(); ng.poll();
}
//				tr("pq", pq);
//				tr("ng", ng);
ret[i] = pq.poll() - (K-1)*ret;
//				tr(ng);
if(i < n-1){
dfs(K-1, ret[i], 0, i, ret, ng);
ng.poll();
}
}
for(int i = 0;i < n;i++){
if(i > 0)out.print(" ");
out.print(ret[i]);
}
out.println();
}
}

static void dfs(int rem, long cur, int ind, int sup, long[] ret, PriorityQueue<Long> ng)
{
if(rem == 0){
}else{
for(int j = ind;j <= sup;j++){
dfs(rem-1, cur+ret[j], j, sup, ret, ng);
}
}
}

static void dff(int rem, long cur, int ind, int sup, long[] ret, StringBuilder sb)
{
if(rem == 0){
sb.append(cur + " ");
}else{
for(int j = ind;j <= sup;j++){
dff(rem-1, cur+ret[j], j, sup, ret, sb);
}
}
}

public static void main(String[] args) throws Exception
{
//		Random gen = new Random();
//		StringBuilder sb = new StringBuilder();
//		int n = 0, K = 0;
//		int x = 0;
//		outer:
//		while(true){
//			n = gen.nextInt(50)+1;
//			K = gen.nextInt(50)+1;
//			long xx = 1;
//			for(int i = 1;i <= K;i++){
//				xx *= n-1+K-i+1;
//				xx /= i;
//				if(xx >= 10000000)continue outer;
//			}
//			if(xx <= 100000){
//				x = (int)xx;
//				break;
//			}
//		}
//		tr(n, K);
//		sb.append(1 + " ");
//		sb.append(n + " ");
//		sb.append(K + " ");
//
//		long[] a = new long[n];
//		for(int i = 0;i < n;i++){
//			long M = 1000000000000000000L / K;
////			long M = 100L / K;
//			a[i] = Math.abs(gen.nextLong() % M) + 1;
//		}
//		Arrays.sort(a);
//		tr(a);
//		dff(K, 0, 0, n-1, a, sb);
//		tr(sb);
//		INPUT = sb.toString();

long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);

solve();
out.flush();
long G = System.currentTimeMillis();
tr(G-S+"ms");
}

private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;

try {
is.mark(1000);
while(true){
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}

private static byte[] inbuf = new byte;
static int lenbuf = 0, ptrbuf = 0;

{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}

private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

private static double nd() { return Double.parseDouble(ns()); }
private static char nc() { return (char)skip(); }

private static String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
}
return sb.toString();
}

private static char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
}
return n == p ? buf : Arrays.copyOf(buf, p);
}

private static char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}

private static int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}

private static int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
}

while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
}

private static long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
}

while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
}

private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}```
```

```                        ```Solution in Python :

In  Python3 :

from collections import Counter
import sys

sys.setrecursionlimit(10000)

T = int(input())
for case in range(T):
N,K = map(int,input().split())
S = list(sorted(map(int,input().split())))
A = *N
used = Counter(S)
i = 0
for s in S:
if used[s] == 0: continue
A[i] = s - (K-1)*A if i!=0 else s//K
#print('f',A[i])
def set_used(sum,idx,cnt):
if cnt == K:
#print(sum,S[-1])
used.subtract([sum])
return
set_used(sum+A[idx],idx,cnt+1)
if idx>0:
set_used(sum,idx-1,cnt)

set_used(A[i],i,1)
i+=1
if i==N:
break
print(' '.join(map(str,A)))```
```

## View More Similar Problems

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

## Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

## Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

## Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

## Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

## Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie