题目链接:UVA - 1152 4 Values whose Sum is 0
题目大意:每列找一个数,使得到和为0,有几种不同的方案。
解题思路:中途相遇法,枚举前两列, 建一个哈希表存两两相加对应的值的个数 , 然后枚举后两列两两相加, 查找与之互为相反数的值出现了几次, 加到答案里。
#include <bits/stdc++.h>
using namespace std;
long long a[4005], b[4005], c[4005], d[4005];
struct node
{
long long data, num;
struct node *next;
}ha[10000008];
void add(long long x)
{
long long xx = abs(x);
long long loc = xx % 10000007;
struct node *p = &ha[loc], *w;
while(p -> next != NULL && p -> data != x)p = p -> next; //拉链法处理冲突
if(p -> data == x)p -> num++;
else
{
w = (struct node *)malloc(sizeof(struct node ));
w -> data = x;
w -> num = 1;
w -> next = NULL;
p -> next = w;
}
}
long long fin(long long x)
{
long long xx = abs(x);
long long loc = xx % 10000007;
struct node *p = &ha[loc];
while(p != NULL){if(p -> data == x)return p -> num; else p = p -> next;}
return 0;
}
int main()
{
long long t, n, i, j, k;
scanf("%lld", &t);
while(t--)
{
for(i = 0; i <= 10000007; i++){ha[i].data = -268435457; ha[i].num = 0;ha[i].next = NULL;}//初始化Hash表
scanf("%lld", &n);
for(i = 1; i <= n; i++)
{
scanf("%lld %lld %lld %lld", &a[i], &b[i], &c[i], &d[i]);
}
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
add(a[i] + b[j]);//建立哈希
}
}
long long ans = 0;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
ans += fin(-c[i] - d[j]);//查找出现个数
}
}
if(t)printf("%lld\n\n", ans);
else printf("%lld\n", ans);
}
return 0;
}