題目:有四個集合(可以使重集)A、B、C、D,各含有n個元素,問每個集合中各取出一個數字,
使得他們的和為0,問有多少種取法。
分析:排序。計算A+B中所有的可能組合、排序,C+D的所有可能組合、排序,然後匹配。
匹配過程,如果A+B中的元素x與C+D中的元素y不為0,移動對應索引(指針);
如果x+y = 0匹配,則統計相同元素個數,解的個數為x的個數*y的個數,然後移動指針。
說明:( ⊙ o ⊙ )。
#include <stdio.h>
#include <stdlib.h>
int A[4004];
int B[4004];
int C[4004];
int D[4004];
int list1[16000001];
int list2[16000001];
int cmp(const void *p, const void *q)
{
return *(int *)p - *(int *)q;
}
int main()
{
int t, n;
while (~scanf("%d",&t))
while (t --) {
scanf("%d",&n);
for (int i = 0; i < n; ++ i) {
scanf("%d%d%d%d",&A[i],&B[i],&C[i],&D[i]);
}
int count1 = 0;
for (int i = 0; i < n; ++ i) {
for (int j = 0; j < n; ++ j) {
list1[count1 ++] = A[i] + B[j];
}
}
int count2 = 0;
for (int i = 0; i < n; ++ i) {
for (int j = 0; j < n; ++ j) {
list2[count2 ++] = C[i] + D[j];
}
}
qsort(list1, count1, sizeof(int), cmp);
qsort(list2, count2, sizeof(int), cmp);
int index1 = 0, index2 = count2 - 1, ans = 0;
while (index1 < count1 && index2 >= 0) {
if (list1[index1] + list2[index2] < 0) {
index1 ++;
}else if (list1[index1] + list2[index2] > 0) {
index2 --;
}else {
int same_index1 = index1;
for (int i = index1; i < count1; ++ i) {
if (list1[i] != list1[index1]) {
break;
}
same_index1 = i;
}
int same_index2 = index2;
for (int i = index2; i >= 0; -- i) {
if (list2[i] != list2[index2]) {
break;
}
same_index2 = i;
}
ans += (same_index1 - index1 + 1)*(index2 - same_index2 + 1);
index1 = same_index1 + 1;
index2 = same_index2 - 1;
}
}
printf("%d\n",ans);
if (t) {
puts("");
}
}
return 0;
}