1. 程式人生 > >【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 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 ;
 }