Description
You are given n integers. Your task is very easy. You should find the maximum integer a and the minimum integer b among these nintegers. And then you should replace both a and b with a-b. Your task will not be finished unless all the integers are equal.
Now the problem come, you want to know whether you can finish you task. And if you can finish the task, you want to know the final result.
Input
The first line of the input contain an integer T(T≤ 20) indicates the number of test cases.
Then T cases come. Each case consists of two lines. The first line is an integer n(2≤ n≤ 10) as the problem described. The second line contains n integers, all of them are no less than -100000 and no more than 100000.
Output
For each case you should print one line. If you can finish your task, you should print one of the n integers. Otherwise, you should print "Nooooooo!"(without quotes).
Sample Input
2 3 1 2 3 2 5 5
Sample Output
2 5
分析:其实我想说这题有个bug,嗯,当你看了提交状态就知道了,代码的内存时间和长度有很大区别。
下面按照正常的hash算法讲解:
对于输入的数组,最大和为10000×10,数据处理很简单,关键要记住不同的数组,这里我们用数组和做hash映射,算法如下:
1、接收输入数据,累加求和存入sum
2、对数组排序
3、按题意处理第一个和最后一个数据
4、对数组排序,如果首尾两个数相等则退出循环
5、更新sum,在sum对应的数组集中挨个判断是否和当前数组一致,若一致则转到第7步
6、把数组按照sum存入hash表,转到第3步
7、输出结果
下面是第一种解法的程序:
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 11;
const int mod = 1000000 + 10;
struct Node { int n[maxn]; };
vector<Node> v[mod];
int num[maxn];
int main()
{
int T, n;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
int sum = 0;
for(int i=0; i<n; i++) { scanf("%d", &num[i]); sum += num[i]; }
for(int i=0; i<mod; i++) v[i].clear();
sort(num, num+n);
if(num[0] == num[n-1]) { printf("%d\n", num[0]); continue; }
int yes = 0;
Node nd;
while(1) {
memcpy(nd.n, num, sizeof(num));
v[(sum+mod)%mod].push_back(nd);
int tmp = num[n-1] - num[0];
sum = sum - num[n-1] - num[0] + 2*tmp;
num[0] = num[n-1] = tmp;
sort(num, num+n);
if(num[0] == num[n-1]) { yes = 1; break; }
int index = (sum+mod)%mod, exist = 0;
for(int i=0; i<v[index].size(); i++) {
int j;
for(j=0; j<n; j++) {
if(v[index][i].n[j] != num[j]) break;
}
if(j==n) { exist = 1; break; }
}
if(exist) break;
}
if(yes) printf("%d\n", num[0]);
else printf("Nooooooo!\n");
}
return 0;
}
第二种方法:可以说是bug?其实根本没有No的情况,所以可以直接循环排序处理数据直到首尾数据相等
#include <cstdio>
#include <algorithm>
int ans[11];
int main()
{
int T, n;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
for(int i=0; i<n; i++) scanf("%d", &ans[i]);
while(std::sort(ans, ans+n), ans[0]!=ans[n-1]) ans[0] = ans[n-1] = ans[n-1]-ans[0];
printf("%d\n", ans[0]);
}
return 0;
}