CodeForces - 245C Game with Coins(贪心+思维)

CodeForces - 245C Game with Coins(思维)

Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins.

Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2·x + 1 ≤ n) and take a coin from each chest with numbers x, 2·x, 2·x + 1. It may turn out that some chest has no coins, in this case the player doesn’t take a coin from this chest. The game finishes when all chests get emptied.

Polycarpus isn’t a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily’s moves.

Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of chests with coins. The second line contains a sequence of space-separated integers: a1, a2, …, an (1 ≤ ai ≤ 1000), where ai is the number of coins in the chest number i at the beginning of the game.

Output
Print a single integer — the minimum number of moves needed to finish the game. If no sequence of turns leads to finishing the game, print -1.

Examples
Input
1
1
Output
-1
Input
3
1 2 3
Output
3
Note
In the first test case there isn’t a single move that can be made. That’s why the players won’t be able to empty the chests.

In the second sample there is only one possible move x = 1. This move should be repeated at least 3 times to empty the third chest

  • 题目大意:
    给你n个箱子,编号分别事1-n,每个箱子里有ci个金币,每次都能选一个X,然后从X,2 * X,2 * X+1,号箱子里分别拿一个金币,箱子里没了就不拿了,如果不能把金币拿完就输出-1 能的话就输出最小的次数。
  • 解题思路:
    我们可以先从后面拿,因为拿后面的箱子能够惠及前面的箱子。所以往前的都是最小的次数。
    如果n<3肯定没法选出3个箱子,直接输出-1 ,如果n事偶数的话,就没法找到一个x来让这个最后的箱子里面的金币减少,因为x x2 x2+1 ,最后一个一定得是奇数才行。。。(这点刚开始我也没想到)。
    然后就是从后往前遍历了,如果是奇数i,那就让a[i] a[i-1] a[(i-1)/2] 都减一 一直减到 a[i]==0,如果是偶数的话那就让 a[i] a[i+1] a[i/2] 都减一 一直减到 a[i]==0 当然每减一次 都让 ans++;
  • 代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n;
int a[11110];
void show()
{
	for(int i=1;i<=n;i++)
		cout<<a[i]<<" ";
	cout<<endl;
}

int main()
{
	cin>>n;
	
	for(int i=1;i<=n;i++)
		cin>>a[i];
	if(n<3)
	{
		cout<<"-1"<<endl;
		return 0;
	}
	int cnt=0;
	for(int i=1;i<=n;i++)
	{
		if(i*2+1<=n)
		{
			while(a[i]>0)
			{
				a[i]--;
				a[i*2]--;
				a[i*2+1]--;
				cnt++;
			//	show();
			}
		}
		else
		{
			if(i%2==0)
			{
				while(a[i]>0)
				{
					a[i]--;
					a[i+1]--;
					cnt++;
				//	show();
				}
			}
			else
			{
				while(a[i]>0)
				{
					a[i]--;
					cnt++;
				//	show();
				}
			}
		}
	}
	cout<<cnt<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43179892/article/details/83796743