POJ - 2785 4 Values whose Sum is 0(折半枚舉+二分)

題目大意:給出一個整數n,接下來有n組數,每組數包含四個數 a、b、c、d 求有多少中組合方式使得 a+b+c+d = 0

 

題目數據範圍 n <= 4000, 強行枚舉的話,一共有4000^4種方式。這是必不可行的。

我們來引入一下折半枚舉的思想:

當枚舉的集合過大導致無法簡單實現,同時剛好只需要他們的和或其他可以處理出的東西,就可以一半一半的枚舉搜索。

在本題當中:

a + b + c + d = 0   >>    (a + b)  = -(c + d)  而對於 a + b 和 c + d 都分別有4000^2 種情況,可以枚舉出來。這時就可以利用折半枚舉。

#include <cstdio>
#include <algorithm>
using namespace std;

typedef long long ll;
const int N = 4005;

ll n, ans;
ll a[N], b[N], c[N], d[N], f[N*N];

int main(){
	scanf("%lld", &n);
	for(int i = 1; i <= n; i++)
		scanf("%lld%lld%lld%lld", &a[i], &b[i], &c[i], &d[i]);
	ll cnt = 1;
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= n; j++){
			f[cnt++] = c[i] + d[j];
		}
	}//枚舉c + d 並保存起來
	sort(f+1, f+cnt);
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= n; j++){
			ll temp = -(a[i] + b[j]);//枚舉a+b
			ans += upper_bound(f+1, f+n*n+1, temp) - lower_bound(f+1, f+n*n+1, temp);
			//同時找出有多少組c+d滿足情況
		}
	}
	printf("%lld\n", ans);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章