标签:思维,贪心
时间限制: 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;
}