little w and Sum(思维)

链接:https://ac.nowcoder.com/acm/contest/297/B
来源:牛客网
 

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

小w与tokitsukaze一起玩3ds上的小游戏,现在他们遇到了难关。

他们得到了一个数列,通关要求为这个数列的和为0,并且只有一次改变一个数的符号的机会(正数变成负数,负数变成正数)。

请问小w与tokitsukaze能否通关,如果能,请输出有多少个数符合要求,如果不能,请输出-1。

输入描述:

第一行包括一个正整数n(1≤n≤10^5),表示这个数列有n个数。
接下来一行有n个数x (-100≤x≤100),表示数列(数列的和保证不等于0)。

输出描述:

输出有多少个符合要求的数,如果没有,请输出-1。

示例1

输入

复制

5
1 3 -5 3 4

输出

复制

2

说明

只要把一个3变成-3,数列的和就变为0。数列里总共有两个3,所以有2个符合要求的数。

示例2

输入

复制

4
1 2 4 8

输出

复制

-1

题解:

若sum为奇数,肯定不存在这个数,若是偶数,除2遍历即可

代码1:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>


using namespace std;

int main()
{

   int n;
   cin>>n;
   int a[100005];
   long long int sum=0;
   for(int t=0;t<n;t++)
   {
   	scanf("%d",&a[t]);
   	sum+=a[t];
   }
   int temp;
   if(sum%2==0)
   {
   	temp=sum/2;
   }
   else
   {
   	printf("-1\n");
   	return 0;
   }
   int s=0;
   for(int t=0;t<n;t++)
   {
   	 if(a[t]==temp)
   	 {
   	 	s++;
	 }
   }
   if(s==0)
   {
   	printf("-1\n");
   }
   else
   {
   	printf("%d\n",s);
   }
   return 0;
} 

代码2:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
 
 
using namespace std;
 
int main()
{
    int n;
     
    while(scanf("%d",&n)!=EOF)
    {
     
    int a[100005];
    long long int sum=0;
    for(int t=0;t<n;t++)
    {
         
        scanf("%d",&a[t]);
        sum+=a[t];
    }
    int flag=0;
    long long int s=0;
    for(int t=0;t<n;t++)
    {
        if(sum-2*a[t]==0)
        {
            s++;
            flag=1;
        }
    }
    if(flag)
    printf("%lld\n",s);
    else
    {
        cout<<"-1"<<endl;
    }
   }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lbperfect123/article/details/85009533