从数组里选出四个数字a,b,c,d,使a+b+c=d
数组中每个数字都只出现一次。
若能够找到,输出d,若有多组答案,输出最大的d,若找不到,输出“no solution"
1<=n<=1000
-536870912<=A[i]<=536870911
同一道题,unordered_map(自定义哈希函数和自动生成)用时1900ms,map用时420ms
不应该是unordered_map更快吗
#include<iostream>
#include<algorithm>
#include <tr1/unordered_map>
using std::tr1::unordered_map;
using namespace std;
const int N=1e3+100,M=1<<31;
int a[N];
class hash_v{
public:
size_t operator()(const int &p)const
{
return p%M;
}
};
unordered_map<int,int,hash_v>m;
int cmp(int a,int b)
{
return a>b;
}
int main() {
int n;//1<=n<=1000
while(cin>>n)
{
m.clear();
int f=0;
for(int i=0; i<n; i++)
{
cin>>a[i];
m[a[i]]=1;
}
sort(a,a+n,cmp);
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
for(int k=j+1; k<n; k++)
{
int sum=0;
sum=a[i]-a[j]-a[k];
if(a[j]!=sum&&a[k]!=sum&&a[i]!=sum)
if(m.count(sum)!=0)
{
f=1;
cout<<a[i]<<endl;
break;
}
}
if(f==1)
break;
}
if(f==1)
break;
}
if(f==0)
cout<<"no solution"<<endl;
}
return 0;
}