UVa 1152 - 4 Values whose Sum is 0

題目:有四個集合(可以使重集)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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值