这题是属于contest里10级算法设计与应用课程练习题2
题目链接 http://soj.me/show_problem.php?pid=1009&cid=892 ,不知道还能否访问这个链接。
Description
There are N numbers. To form an equation, we could use operator ‘+’, ‘*’, ‘(‘, ‘)’ conjoining them and working out the result. Though these numbers are out of order, there may be many combinations. We must find out the result which mod by Q is maximal. Please output the module.
Input
The first line of input is the number of test cases T. The following T lines each line contains N (N<=6), Q (1<=Q<=32768), followed by N integers within the range [0, 10000].
Output
For each test, output the maximum module on single line.
Sample Input
23 7 2 2 24 5 1 2 3 4
Sample Output
64
Hint
(2+2+2)%7=6
((1+3)*(2+4))%5=4
这题原本觉得不算难,因为觉得用深搜下就应该可以了,而且N值又小于7,比较小,不存在时间超时问题,结果提交后是WA。自己反反复复看了好久自己写的,觉得算法没问题。到最后才注意到输入整数的范围最大10000,如果是6个这么大的数相乘,那么就超过int型了>_<。于是我改成unsigned long long就果断ac了。这也隐藏得太深了~
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
unsigned long long ans;
void dfs(unsigned long long arr[], unsigned long long m, unsigned long long n)
{
if (n == 1) {
if (arr[0]%m > ans)
ans = arr[0]%m;
return ;
}
for (unsigned long long i = 0; i < n; i++) {
for (unsigned long long j = i+1; j < n; j++) {
if (i != j) {
unsigned long long num[8], t = 0;
for (unsigned long long k = 0; k < n; k++)
if (k != i && k != j)
num[t++] = arr[k];
num[t] = arr[i] + arr[j];
dfs(num, m, n-1);
if (ans == m-1)
return ;
num[t] = arr[i] * arr[j];
dfs(num, m, n-1);
if (ans == m-1)
return ;
}
}
}
}
int main()
{
unsigned long long t;
cin >> t;
while (t--)
{
unsigned long long n, q;
cin >> n >> q;
unsigned long long num[8];
for (unsigned long long i = 0; i < n; i++)
cin >> num[i];
ans = 0;
dfs(num, q, n);
cout << ans << endl;
}
return 0;
}