1. 程式人生 > >CodeForces - 245C Game with Coins(貪心+思維)

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;
}