从来没写过blog,这篇就当开始吧,就随手找个简单的题目来练练手。
题目地址:http://acm.bit.edu.cn/mod/programming/view.php?a=487
Average Numbers
Problem Description
You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).
Input
The first line of the input is an integer t, which is the numbers of the test cases.
For each test case, the first line contains the integer n ( 2 ≤ n ≤ 2·10^5). The second line contains elements of the sequence a1, a2, ..., an ( 1 ≤ ai ≤ 1000). All the elements are positive integers.
Output
For each test case print on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n. If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.
Sample Input
2
5
1 2 3 4 5
4
50 50 50 50
Sample Output
1
3
4
1 2 3 4
大意就是给出一组长度为 n 的序列,判断一个序列中的第i个数 ai 是否等于除去这个数之外的,所有数的平均数。
means = (a1 +a2+a3+..a(i-1)+a(i+1)...+an)/n-1
问ai==means?吗,其实可以用上面的方法可以直接判断但是里面用到了除法,那么就会产生小数,也就是精度问题,但是此题变换一下,换成乘法,就避免了小数
上面的问题就是等效为 n*ai == 所有元素之和吗?
此题还需要注意处理输出的格式,零输出时的处理。
下面是程序
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int input_case,input_num_each,sum_each,count,space_flag;
int data[200003],data_map[200003];
scanf("%d",&input_case);
while(input_case--)
{
scanf("%d",&input_num_each);
memset(data_map,0,sizeof(int)*200003);
sum_each = 0;
count = 0;
space_flag = 0;
for(int i = 0;i<input_num_each;++i)
{
scanf("%d",&data[i]);
sum_each += data[i];
}
for(int i = 0; i < input_num_each; ++i)
{
if(sum_each == input_num_each*data[i])
{
data_map[i] = 1;
++count;
}
}
if(!count){
printf("0\n");
}
if(input_num_each!=1&&count)
{
printf("%d\n",count);
for(int i =0; i< input_num_each;++i)
{
if(data_map[i])
{
if(space_flag){
printf(" %d",i+1);
}else{
printf("%d",i+1);
}
space_flag = 1;
}
}
printf("\n");
}
}
return 0;
}