UVA 10125 - Sumsets

来源:互联网 发布:vmware14 mac os补丁 编辑:程序博客网 时间:2024/05/19 06:51

题目大意:给出 n 个数,找出 n 个数中满足 a + b + c = d,的组合,输出 d,不存在输出”no soluution",(注意 d 要求最大)


解题思路:首先将 n 个数排序,d 从最大的数开始遍历,而 a 也从最大的开始遍历,b刚好比 a 小一点开始遍历,c 从最小的遍历,直到 b < c 为止,如果a + b + c > d , b 应该向小一点的数值移动,反之,c 向大一点的数值移动。等于的时候即是满足的情况。

#include <cstdio>#include <algorithm>using namespace std;int a, b, c, d, n, arr[1005];bool judge() {for (d = n - 1; d >= 0; d--)for (a = n - 1; a > 0; a--)for (b = a - 1, c = 0; b > c && a != d; )if (arr[a] + arr[b]+ arr[c] == arr[d])return true;else arr[a] + arr[b] + arr[c] < arr[d] ? c++ : b--;return false;}int main() {while (scanf("%d", &n), n) {for (int i = 0; i < n; i++)scanf("%d", &arr[i]);sort(arr, arr + n);judge() ? printf("%d\n",arr[d]) : printf("no solution\n");}return 0;}


0 0