给你一个长度为n的数组a,每个值要么是1或者-1.你可以选择其中若干个位置,并将对应位置上的值乘上-1,最终使得数组a满足以下条件:
a1+a2+a3+…+an≥0 a1a2a3*…*an=1 问你最少需要选择多少个位置。
接下来每组数据第一行输入一个正整数n(1≤n≤100)。
第二行输入长度为n的正整数数组a(a[i]∈{-1,1})。
输出最少需要选择的位置数。
7
4
-1 -1 1 -1
5
-1 -1 -1 1 1
4
-1 1 -1 1
3
-1 -1 -1
5
1 1 1 1 1
1
-1
2
-1 -1
1
1
0
3
0
1
2
#include <iostream>
using namespace std;
const int MAXN=105;
int a[MAXN],ans,n,t,s1,s2;//s1保存-1,s2保存1
int check(int,int);
int main()
{
std::cin>>t;
while(t--)
{
ans=s1=s2=0;
std::cin>>n;
for(int i=1; i<=n; i++)
{
std::cin>>a[i];
if(a[i]==-1)
s1++;
else
s2++;
}
std::cout<<check(s1,s2)<<endl;
}
return 0;
}
int check(int x,int y)
{
if(x==n)
return n;
if(x<=y&&x%2!=0)
return 0;
while(x>y)
{
if(x%2!=0)
x-=2,y+=2;
else
x--,y++;
ans++;
}
return ans;
}
//-1的个数为奇数,并且-1的个数小于等于1的个数
有问题吗?