codeforces 245C Game with Coins

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

Sample Input
Input
1
1
Output
-1
Input
3
1 2 3
Output
3
Hint
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.

题意:一堆编号由1-n的箱子,每次取三个箱子,编号为n,2*n,2*n-1,取出其中的一枚银币,问最少取多少次可把里面的钱去完。当有箱子无法取到时(比如n小于三,或者为偶数),输出负一。

做法:贪心策略。远方的箱子取到的机会最少,可能只有一次,而且在去远方的箱子时,近端的箱子也能跟着收益,所以,从第n个箱子进行逆推。

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#pragma comment(linker,"/STACK:102400000,102400000")
using namespace std;
int main()
{
    int n;
    int a[1005];
    while(scanf("%d",&n)==1)
    {
        int i;
        for(i=1;i<=n;i++) scanf("%d",&a[i]);
        if(n<3||n%2==0) printf("-1\n");
        else
        {
            int cnt=0;
            for(i=n;i>=1;i--)
            {
                while(a[i]>0)
                {
                    a[i]--;
                   if(i%2==1) a[i-1]--; //2*i+1
                   else a[i+1]--;  //2*i
                    a[i/2]--;
                    cnt++;
                }
            }
            printf("%d\n",cnt);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值