站外题求援
  • 板块学术版
  • 楼主Xiao800
  • 当前回复13
  • 已保存回复13
  • 发布时间2023/7/10 16:13
  • 上次更新2023/11/3 10:43:49
查看原帖
站外题求援
931106
Xiao800楼主2023/7/10 16:13

题目描述:

给你一个长度为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的个数

有问题吗?

2023/7/10 16:13
加载中...