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

版权声明:欢迎学习我的博客,希望ACM的发展越来越好~ https://blog.csdn.net/qq_41289920/article/details/83863787

题干:

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

-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的盒子,从位置为x,2*x,2*x+1这三个盒子中各拿走一个球(如果盒子已空则不拿。)问你最少几次操作可以把所有盒子都拿空。如果无法达到目的,,则输出-1。

解题报告:

  首先要知道何时是怎么也拿不走的,,,观察发现如果盒子是偶数个的话。。怎么都达不到目的。。或者盒子数小于3,也是这样。(因为我一次就要拿三个嘛)(读题啊读题啊!!英语啊英语啊!!)

   解法就是倒着拿,,因为最右边的必须要拿走,并且拿走的方法很唯一那就是当成2*x+1那一项,所以我们肯定先拿右边的啊,顺道着就拿走了左边的了。。于是贪心emmm

   其实这题不需要用while那样,,可以直接减到零,,但是这题数据量小,所以怎么搞都可以。。考察点在算法的设计而不在优化。。。

AC代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define ll long long
#define pb push_back
#define pm make_pair
#define fi first
#define se second
using namespace std;
const int MAX = 2e5 + 5;
ll a[MAX];
ll n,ans;
int main()
{
	cin>>n;
	for(int i = 1; i<=n; i++) scanf("%lld",a+i);
	if(n%2 == 0 || n<3) {
		puts("-1");return 0 ;
	}
	for(int i = n; i>=1; i--) {
		while(a[i]>0) {
			if(i&1) {
				a[i]--;
				a[i-1]--;
				a[(i-1)>>1]--;
			}
			else {
				a[i]--;
				a[i+1]--;
				a[i>>1]--;
			}
			ans++;
		} 
	}
	printf("%lld\n",ans);
	return 0 ;
 }

猜你喜欢

转载自blog.csdn.net/qq_41289920/article/details/83863787