【 Game with Coins 】【CodeForces - 245C】(思维)

版权声明:本人原创,未经许可,不得转载 https://blog.csdn.net/qq_42505741/article/details/83819300

题目:

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 aicoins.

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

扫描二维码关注公众号,回复: 4111904 查看本文章
-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个箱子,两个人轮流从箱子取球,且取x ,2*x ,2*x+1个箱子 ,是一起取的,问最少进行多少步能够使全部箱子的球都取出来,当选择的箱子是空的时候是取不出球的但是是可以选择的。思路是应该逆推,因为咱们首先要满足最远的箱子是取空的,才能进一步考虑近的,首先倒推回去,记录倒推的时候中间箱子的变化就可以啦。

ac代码:
 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;

const int maxn =110;
int n;
int num[maxn];
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		memset(num,0,sizeof(num));
		for(int i=1;i<=n;i++)
			scanf("%d",&num[i]);
		if(n==1||n==2||(n&1)==0)//坑点就是偶数的最大箱子是永远取不到的
		{
			printf("-1\n");
			continue;
		}
		int cnt=0;
		for(int i=n;i>1;i-=2)
		{
			if(num[i]!=0||num[i-1]!=0)
			{
				cnt+=max(num[i],num[i-1]);	
				if(num[i>>1]>=max(num[i],num[i-1]))
					num[i>>1]-=max(num[i],num[i-1]);
				else 
					num[i>>1]=0;
				
			}
		}
		cnt+=num[1];
		printf("%d\n",cnt);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/83819300