传送门
题意
给出n种袜子,每种袜子个数a[i],两只相同种类袜子配成一对,询问至少拿出多少只袜子能确保配出k对袜子
分析
In order to find out the minimum number of socks needed, we should analyse the worst possible scenario.
This happens when we first take one sock of each color. Next, whatever color we choose, we're going to make a pair. But if the next sock is also of the same color, we won't be able to make a new pair. Any other color, and we'd be able to make a second pair. So in our worst case analysis, we can always assume that we take two consecutive socks of the same color, while possible.
If we run out of colors with two available socks, but we still can't make (K) pairs, we will start choosing the socks left, until we're able to make (K) pairs.
trick
1.注意一开始统计的时候会爆int
代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define F(i,a,b) for(int i=a;i<=b;++i)
#define R(i,a,b) for(int i=a;i<b;++i)
#define mem(a,b) memset(a,b,sizeof(a))
//#pragma comment(linker, "/STACK:102400000,102400000")
//inline void read(int &x){x=0; char ch=getchar();while(ch<'0') ch=getchar();while(ch>='0'){x=x*10+ch-48; ch=getchar();}}
int n;
ll k;
ll a[100100];
ll avaliable_pairs,pairs,total;
int main()
{
cin>>n>>k;
F(i,1,n)
{
cin>>a[i];
avaliable_pairs+=a[i]/2;
a[i]--;
}
if(avaliable_pairs<k) puts("-1");
else
{
total+=n;
F(i,1,n)
{
if(a[i]>=2)
{
total+=a[i]/2*2;
pairs+=a[i]/2;
}
}
if(pairs>=k) cout<<k*2+n-1<<endl;
else cout<<total+k-pairs<<endl;
}
return 0;
}