#include <stdio.h>
#include <iostream>
#include <vector>
#pragma warning(disable:4996);
using namespace std;
const int maxn = 10;
int a[maxn];
bool choose[maxn];
int cal()
{
int w = -1;
for (int i = 0; i < 5; i++)
{
for (int j = i + 1; j < 5; j++)
{
for (int k = j + 1; k < 5; k++)
{
if ((a[i] + a[j] + a[k]) % 10 == 0)
{
w = 0;
for (int m = 0; m < 5; m++)
{
if (m != i && m != j && m != k)
{
w = (w + a[m]) % 10;
}
}
return w;
}
}
}
}
return w;
}
int main()
{
int m;
scanf("%d", &m);
while (m--)
{
for (int i = 0; i < 5; i++)
{
scanf("%d", &a[i]);
}
int w = cal();
printf("%d\n", w);
}
}
回溯法
#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#pragma warning(disable:4996);
using namespace std;
const int maxn = 10;
int a[maxn];
bool visit[maxn];
int calSum()
{
int ans = 0;
for (int i = 0; i < 5; i++)
{
ans += a[i];
}
return ans;
}
int cal(int num,int sum)
{
if (num > 3)
return -1;
if (num == 3)
{
if (sum % 10 == 0)
{
int w = (calSum() - sum)%10;
return w;
}
return -1;
}
for (int i = 0; i < 5; i++)
{
if (visit[i] == false)
{
visit[i] = true;
int f = cal(num + 1, sum + a[i]);
if (f != -1)
return f;
visit[i] = false;
}
}
return -1;
}
int main()
{
int m;
scanf("%d", &m);
while (m--)
{
fill(a, a + maxn, 0);
fill(visit, visit + maxn, false);
for (int i = 0; i < 5; i++)
{
scanf("%d", &a[i]);
}
int w = cal(0,0);
printf("%d\n", w);
}
}