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;
}

 

全部评论

相关推荐

程序员牛肉:你这简历有啥值得拷打的?在牛客你这种简历一抓一大把,也就是个人信息不一样而已。 关键要去找亮点,亮点啊,整个简历都跟流水线生产出来的一样。
点赞 评论 收藏
分享
12-24 20:49
武汉大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务