unordered_map疑问?求助dalao
  • 板块灌水区
  • 楼主ZYH20190341315
  • 当前回复6
  • 已保存回复6
  • 发布时间2021/6/8 15:04
  • 上次更新2023/11/4 22:09:04
查看原帖
unordered_map疑问?求助dalao
400760
ZYH20190341315楼主2021/6/8 15:04

从数组里选出四个数字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;
}
2021/6/8 15:04
加载中...