UVa 10125 - Sumsets 解题报告(中途相遇法)

来源:互联网 发布:数据通信与网络答案 编辑:程序博客网 时间:2024/05/08 09:25

Problem C - Sumsets

Given S, a set of integers, find the largest d such that a + b + c = d where a, b, c, and d are distinct elements of S.

Input

Several S, each consisting of a line containing an integer 1 <= n <= 1000indicating the number of elements in S, followed by the elements of S, one per line. Each element of S is a distinct integer between -536870912 and +536870911 inclusive.The last line of input contains 0.

Output

For each S, a single line containing d, or a single line containing "no solution".

Sample Input

52 3 5 7 1252 16 64 256 10240

Output for Sample Input

12no solution

    解题报告: a + b + c = d, 也就是 a + b = d - c 。Meet-in-the-middle题,先统计a + b的结果,然后看是否有d - c等于先前的结果。

    为了让结果尽量大,我们可以对原数组进行排序。让d尽量大,c尽量小,第一次找到的答案就是结果了。

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <cmath>#include <vector>#include <queue>#include <map>#include <string>using namespace std;#define ff(i, n) for(int i=0;i<(n);i++)#define fff(i, n, m) for(int i=(n);i<=(m);i++)#define dff(i, n, m) for(int i=(n);i>=(m);i--)#define mem(a) memset((a), 0, sizeof(a))typedef long long LL;typedef unsigned long long ULL;void work();int main(){#ifdef ACM    freopen("in.txt", "r", stdin);//    freopen("in.txt", "w", stdout);#endif // ACM    work();}/*****************************************/struct Node{    int idx, idy;} x;typedef vector<Node> vNode;int n;int num[1111];void solve(map<int, vNode> & mm){    dff(i, n, 1) fff(j, 1, n) if(i != j)    {        int res = num[i] - num[j];        if(mm.count(res))        {            vNode & vnode = mm[res];            ff(k, vnode.size()) if(vnode[k].idx != i && vnode[k].idy != i && vnode[k].idx != j && vnode[k].idy != j)            {                printf("%d\n", num[i]);                return;            }        }    }    puts("no solution");}void work(){    while(~scanf("%d", &n) && n)    {        fff(i, 1, n) scanf("%d", num+i);        sort(num+1, num+n+1);        map<int, vNode> mm;        fff(i, 1, n) fff(j, i+1, n)        {            x.idx = i, x.idy = j;            mm[num[i]+num[j]].push_back(x);        }        solve(mm);    }}


0 0
原创粉丝点击