题意:给出一段数列,里面有N个数ai,奇数个数和偶数个数相同,然后你可以在奇数和偶数个数相等的时候,你就可以剪一个片段,需要花费|a[i]-a[i+1]|。现在总共预算是b,让你在b预算内,尽可能的多剪片段,输出最多的剪的次数。
题解:贪心 先把所有能减的片段,奇数和偶数个数相等的时候,把花费存起来,然后排个序,从前面累加,如果没有超出预算b剪的次数就++
c++:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,a[110],ans=0,cnt1=0,cnt2=0,b[110],c=0,sum=0;
cin>>n>>m;
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
{
if(a[i]%2) cnt1++;
else cnt2++;
if(cnt1==cnt2&&i+1<n)
b[c++]=abs(a[i]-a[i+1]);
}
sort(b,b+c);
for(int i=0;i<c;i++)
{
sum+=b[i];
if(sum<=m)
ans++;
else break;
}
cout<<ans;
return 0;
}
python:
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=[]
cnt1=0;cnt2=0
for i in range(len(a)):
if a[i]%2==0:cnt1+=1
else:cnt2+=1
if cnt1==cnt2 and i+1<len(a):
b.append(abs(a[i]-a[i+1]))
b.sort()
sum=0;ans=0
for i in b:
sum+=i
if sum<=m:
ans+=1
else:
break
print(ans)