Simplified mahjong

标签:思维,贪心
时间限制: 2 Sec 内存限制: 256 MB

题目描述
Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it. He has Ai cards with an integer i.

Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1.

Snuke wants to create the maximum number of pairs from his cards, on the condition that no card should be used in multiple pairs. Find the maximum number of pairs that he can create.

Constraints
1≤N≤105
0≤Ai≤109(1≤i≤N)
All input values are integers.
输入
The input is given from Standard Input in the following format:

N
A1
:
AN
输出
Print the maximum number of pairs that Snuke can create.
样例输入
4
4
0
3
2
样例输出
4
提示
For example, Snuke can create the following four pairs: (1,1),(1,1),(3,4),(3,4).

**解题思路:**贪心,从前往后结合,保证先把前面的数结合完。
首先是相同的数两两结合,即/2操作,判断是否剩余,即%2操作。那么会有两种考虑的情况,如果i和i-1都剩余1个,那么正好,这两个结合就好。如果i剩余0个,i-1剩余1个,那么拿出一个i和i-1结合,那么单独的i就会有一个,i-1没有单独的存在,也就是a[i]++,a[i-1]–。

note:要用一个数组标记i的个数是否为0,这是特殊情况。

#include <bits/stdc++.h>
#define ll long long
//#define local
using namespace std;
const int N = 1e5+5;
const int inf = 0x3f3f3f3f;//1061109567
ll n,ans=0;
int a[N],vis[N];
int main()
{
#ifdef local
    freopen("input.txt","r",stdin);
#endif // local
    scanf("%lld",&n);
    memset(vis,0,sizeof(vis));
    for(int i=1; i<=n; i++)
    {
        scanf("%d",&a[i]);
        if(a[i])
            vis[i]=1;
        ans+=(a[i]/2);
        a[i]%=2;
    }
    for(int i=2; i<=n; i++)
    {
        if(a[i]&&a[i-1])
        {
            ans++;
            a[i]=a[i-1]=0;
        }
        if(!a[i]&&a[i-1])
        {
            if(vis[i])
                a[i]++,a[i-1]--;
        }
    }
    printf("%lld",ans);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值