您的位置:首页 > 其它

UVA 10125 Sumsets(中途相遇法)

2016-10-13 09:05 441 查看
首先从大到小枚举d,然后枚举c和b,a根据公示算出,a=d-c-b,只要在剩下的区间中二分查找a就可以了,找到就是成功了。我认为时间复杂度是O(n^3)吧,但是在其他博客看到时间复杂度是O(n^2)。#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define ss(x) scanf("%d",&x);
#define rep(i,a,b) for(int i=(a);i<(b);i++)
vector<int> s;
int read()
{
int num;
ss(num);
return num;
}
int main()
{
int n;
while(true)
{
ss(n);if(n==0) break;
int maxd=0;
bool find=false;
s.reserve(1024);
s.clear();
rep(i,0,n) s.push_back(read());
sort(s.begin(),s.end(),greater<int>());
vector<int>::iterator pd,pb,pc;
for(pd=s.begin();pd!=s.end();pd++)
{
for(pc=s.begin();pc!=s.end();pc++)
{
if(*pd==*pc) continue;
pb=pc;
while(pb!=s.end()&&*pb==*pc) pb++;
for(;pb!=s.end();pb++)
{
if(*pd==*pb) continue;
int a=*pd-*pc-*pb;
if(a>=*pb||*pd==a) continue;
if(binary_search(pb,s.end(),a,greater<int>())){
find=true;
maxd=*pd;
goto RESULT;
}
}
}
}
RESULT:
if(find) printf("%d\n",maxd);
else puts("no solution");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: