C. Good Array

C. Good Array

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array a=[1,3,3,7]

is good because there is the element a4=7 which equals to the sum 1+3+3

.

You are given an array a

consisting of n integers. Your task is to print all indices j of this array such that after removing the j

-th element from the array it will be good (let's call such indices nice).

For example, if a=[8,3,5,2]

, the nice indices are 1 and 4

:

  • if you remove a1

, the array will look like [3,5,2]

  • and it is good;
  • if you remove a4

 

思路很简单:创建两个数组,数组 a 记录输入的数,数组 b 记录数字出现的次数,再创建一个容器vector用来存储符合要求的数字的下标(记住数组和容器一定要初始化或者在循环中创建),记录数字出现的次数,枚举每一个数字,用一个s记录每个数字相加的和,用s减去该数字的大小,如果原数组中出现了减去过后的一半,则满足条件,加进容器中。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
using namespace std;

long long a[1000005],b[1000005];
long long s,t;

int main()
{
	int n;
	while(cin>>n){
        vector<int> ans;
        s = 0;
        memset(b,0,sizeof(b));
        for(int i = 0;i < n;i++){
            cin>>a[i];
            s += a[i];
            b[a[i]]++;
        }
        for(int i = 0;i < n;i++){
            t = s-a[i];
            if(t % 2 != 0 || t > 2000000)//必须判断大于2e6的情况,不然第6个test就会RE 
                continue;//不是偶数的显然不合适
            t /= 2;
            if(b[t] - (a[i] == t) > 0){//(a[i] == t) 为真时为1,为假时为0,可以排除a[i]==t的情况
                ans.push_back(i);
            }
        }
        int len = ans.size();
        cout<<len<<endl;
        for(int i = 0;i < len;i++){
            if(i == 0)
                cout<<ans[i]+1;
            else
                cout<<" "<<ans[i]+1;
        }
        cout<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值