1585C - Minimize Distance - CodeForces Solution


greedy *1300

Please click on ads to support us..

Python Code:

def Solve(depot, k):
	ind = -1
	l = len(depot)
	sm = 0
	if(l%k):
		sm += depot[ind+(l%k)]*2
		ind += l%k	
	for i in range(l//k):
		sm += depot[ind+k]*2
		ind += k
	return sm 

def fndMax(p, n):
	if(bool(p) and bool(n)):
		return max(p[len(p)-1], n[len(n)-1])
	if(not(bool(p))):
		return n[len(n)-1]
	else:
		return p[len(p)-1]



t = int(input())
while(t):
	n, k = map(int, input().split())
	x = list(map(int, input().split()))
			neg = []
	pos = []
	for i in x:
		if(i<0):
			neg.append(-i)
		else:
			pos.append(i)
	neg.sort()
	pos.sort()
			sPos = Solve(pos, k)
	sNeg = Solve(neg, k)
	mx = fndMax(pos, neg)
	print(sPos+sNeg-mx)
	t-=1


Comments

Submit
0 Comments
More Questions

978B - File Name
1426B - Symmetric Matrix
732B - Cormen --- The Best Friend Of a Man
1369A - FashionabLee
1474B - Different Divisors
1632B - Roof Construction
388A - Fox and Box Accumulation
451A - Game With Sticks
768A - Oath of the Night's Watch
156C - Cipher
545D - Queue
459B - Pashmak and Flowers
1538A - Stone Game
1454C - Sequence Transformation
165B - Burning Midnight Oil
17A - Noldbach problem
1350A - Orac and Factors
1373A - Donut Shops
26A - Almost Prime
1656E - Equal Tree Sums
1656B - Subtract Operation
1656A - Good Pairs
1367A - Short Substrings
87A - Trains
664A - Complicated GCD
1635D - Infinite Set
1462A - Favorite Sequence
1445B - Elimination
1656C - Make Equal With Mod
567A - Lineland Mail