constructive algorithms greedy implementation math *2000

Please click on ads to support us..

Python Code:

import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

t = int(input())
ans = []
pow10 = [1]
for _ in range(9):
    pow10.append(10 * pow10[-1])
sp = set(pow10)
inf = pow(10, 9) + 1
for _ in range(t):
    s, n = map(int, input().split())
    ans0, x = [], 10
    while s and n ^ 1:
        while not s % x:
            x *= 10
        ans0.append(x // 10)
        s -= ans0[-1]
        n -= 1
    if n == 1 and s:
        ans0.append(s)
    else:
        for _ in range(n):
            ok = 0
            mi, j = inf, -1
            for i in range(len(ans0)):
                if not ans0[i] in sp:
                    x = pow10[len(str(ans0[i])) - 1]
                    ans0.append(ans0[i] - x)
                    ans0[i] = x
                    ok = 1
                    break
                elif mi > ans0[i] and ans0[i] ^ 1:
                    mi, j = ans0[i], i
            if not ok:
                ans0.append(ans0[j] // 2)
                ans0[j] //= 2
    ans.append(" ".join(map(str, ans0)))
sys.stdout.write("\n".join(ans))

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int s,n,x,T;
int main(){
	scanf("%d",&T);
	while (T--){
		scanf("%d %d",&s,&n);
		for (;--n;s-=x) printf("%d ",x=pow(10,(int)log10(s-n)));
		printf("%d\n",s);
	}
	return 0;
} 
	 	 		 		    		     			  		   	


Comments

Submit
0 Comments
More Questions

264A - Escape from Stones
1506A - Strange Table
456A - Laptops
855B - Marvolo Gaunt's Ring
1454A - Special Permutation
1359A - Berland Poker
459A - Pashmak and Garden
1327B - Princesses and Princes
1450F - The Struggling Contestant
1399B - Gifts Fixing
1138A - Sushi for Two
982C - Cut 'em all
931A - Friends Meeting
1594A - Consecutive Sum Riddle
1466A - Bovine Dilemma
454A - Little Pony and Crystal Mine
2A - Winner
1622B - Berland Music
1139B - Chocolates
1371A - Magical Sticks
1253A - Single Push
706B - Interesting drink
1265A - Beautiful String
214A - System of Equations
287A - IQ Test
1108A - Two distinct points
1064A - Make a triangle
1245C - Constanze's Machine
1005A - Tanya and Stairways
1663F - In Every Generation