刚刚学习hash,做了两道题,挺有体会的。还在摸索中,代码写的很乱……
http://acm.pku.edu.cn/JudgeOnline/problem?id=2549
//首先枚举a+b,建立hashtable,(注意a+b小于0时的取址问题),
//然后枚举d-c,同样注意取址,在hashtable中查找地址相同的,
//并比较是否是所查的结果.记录当前最大的d值 
//注意,i,j,k,l不能重复…… 
#include<iostream>
#include
<cmath>
using namespace std;
int n;
struct q
{   
long val;
    
int x1,x2;
}hash[
1000001];
int prime=999983;
long num[10001]; 
long sum,cha;
int i,j;
void build(long t)
{   
if(hash[t].val==0)
    {  hash[t].val
=sum;
       hash[t].x1
=i;
       hash[t].x2
=j;
    }
    
else 
    {   
if(hash[t].val!=0&&hash[t].val!=sum)
            build(t
+1);
    }
}
bool find(long t)
{   
if(hash[t].val==0)
        
return 0;
    
else if(hash[t].val==cha&&hash[t].x1!=i&&hash[t].x2!=i&&hash[t].x1!=j&&hash[t].x2!=j)
       
return 1;
    
else if(hash[t].val!=0&&hash[t].val!=cha)
    {   find(t
+1);
    }
    
else return 0;
}
int main()
{   
while(scanf("%d",&n)&&n)
    {   memset(hash,
0,sizeof(hash));
        memset(num,
0,sizeof(num));
        
long k;
        
long temp;
        
for(i=0;i<n;i++)
        {   scanf(
"%ld",&num[i]);
        }
        
for(i=0;i<n;i++)
        {   
for(j=0;j<n;j++)
            {    
if(i==j)
                     
continue;
                 sum
=num[i]+num[j];
                 
if(sum<0)
                    temp
=(-1)*sum;
                 
else temp=sum;
                 build(temp
%prime);
            }
        }
//build hashtable[]=a+b;
        long best=-536870913;
        
for(i=0;i<n;i++)
        {  
for(j=0;j<n;j++)
           {   
if(i==j)
                 
continue;
               cha
=num[i]-num[j];
               
if(cha<0)
                  temp
=(-1)*cha;
               
else temp=cha;
               
if(find(temp%prime)&&num[i]>best)
                   best
=num[i];
           }
        }
//穷举hash[x]=d-c==a+b 
        if(best==-536870913)
            printf(
"no solution\n");
        
else
            printf(
"%ld\n",best);
    }
    system(
"pause");
    
return 0;
}