codeforces1303D Fill The Bag binary applications and greedy

URL: https://codeforces.com/contest/1303/problem/D

Meaning of the questions:

N-space is given $ $ $ m $ containers and boxes. The size of the box are $ 2 ^ k $ positive integers, and can be halved, so that the container just ask the box is filled half times the minimum number, if possible just filled, output $ $ -1.

answer:

Statistical $ 2 ^ k $-sized box how many, and greed from low to high, because of certain high need in order to halve the low, so the number will increase by half, while the low becomes high but no impact. For a bit in $ i $, if it is $ 1 $, then for this one, if you have no size is $ 2 ^ i $ the box, you need to first from $ i + 1 $ bit in half, $ i + number 1 on the cassette position is $ $ $ -1 does not matter, because it will from $ (i + 1) + 1 $ take place over similar subtraction step down. If there are remaining, they merge directly to the $ i + 1 $ of the last halve the number of output is the answer.

AC Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int cnt[65];
int solve()
{
	memset(cnt, 0, sizeof(cnt));
	ll n, sum = 0;
	int m, a;
	scanf("%lld%d", &n, &m);
	for (int i = 1; i <= m; ++i)
	{
		scanf("%d", &a);
		sum += a;
		int tmp = 0;
		while (a > 1)
			++tmp, a >>= 1;
		++cnt[tmp];
	}
	if (sum < n)
		return printf("-1\n"), 0;
	int years = 0;
	for (int i = 0; i <= 63; ++i)
	{
		int x = (n >> i) & 1;
		cnt[i] -= x;
		if (cnt[i] >= 2)
			cnt[i + 1] += cnt[i] / 2, cnt[i] -= (cnt[i] / 2) * 2;
		if (cnt[i] < 0)
			--cnt [i + 1] ++ years;
	}
	return printf("%d\n", ans), 0;
}
int main ()
{
	int t;
	scanf("%d", &t);
	while (t--)
		solve();
	return 0;
}

 

Guess you like

Origin www.cnblogs.com/Aya-Uchida/p/12319619.html
Bag
Recommended