hash

来源:互联网 发布:w3cschool mysql 编辑:程序博客网 时间:2024/06/11 01:57

UVA 10125】Sumsets

在一串大小为s的数列中,是否存在a + b + c = d, 如果存在,输出最大的d,否则输出no solution

这题的数据很水,直接暴力也是能过的

#include <bits/stdc++.h>using namespace std;#define maxn 500510#define inf 0x7FFFFFFFint p[1005];int head[maxn],next[maxn];struct node {int x,y,sum;}b[maxn];int Hash(int s){int seek = (s >> 1) + (s << 1);return (seek & inf) % 500503;}int insert(int s){int h = Hash(b[s].sum);int u=head[h];while(u){if(b[u].sum == b[s].sum) return 0;u = next[u];}next[s]=u;head[h]=s;return 1;}int search(int x , int y){int h = Hash(p[x] - p[y]);int u = head[h];while(u){if(p[x] - p[y] == b[u].sum && x != b[u].x && y != b[u].y && x != b[u].y && y != b[u].x) return 1;u = next[u];}return 0;}int main(){int n;while(~scanf("%d",&n)){if(n==0) break;for(int i=0;i<n;i++){scanf("%d",&p[i]);}int num=1,maxv=-inf;memset(head,0,sizeof(head));for(int i=0;i<n;i++){for(int j=i+1;j<n;j++){b[num].sum = p[i] + p[j];if(insert(num)){b[num].x = i;b[num].y = j;num++;}}}for(int i = 0 ; i < n ; i++){for(int j = 0 ; j < n ; j++){if(j != i && search(i , j) && maxv < p[i]){maxv = p[i];}}}if(maxv == -inf) printf("no solution\n");else printf("%d\n",maxv);}return 0;}


0 0