UVA1152 4 Values whose Sum is 0

meet-in-the-middle模板题。。。

复杂度太大了,我们就要想想能不能折半,折半后的复杂度如果刚好能过的话就是折半了。。。

这道题要做的就是预处理出所有的\(a_i+b_j\),然后用一个表来存下来。

然后就可以再枚举所有的\(c_i+d_j\),看看是否有等于\(-(a_i+b_j)\)的,如果有的话将个数计入答案。

如果用map来做的话因为常数大还过不了。

上github翻了蓝书的代码,居然用了个数组解决了,直接sort、upper_bound和lower_bound乱用就求出答案来了。。。

代码:

#include<cstdio>
#include<algorithm>
const int maxn = 4005;
int a[maxn], b[maxn], c[maxn], d[maxn];
int e[16000005];
int n, ans, cnt;

int read()
{
	int ans = 0, s = 1;
	char ch = getchar();
	while(ch > '9' || ch < '0'){ if(ch == '-') s = -1; ch = getchar(); }
	while(ch >= '0' && ch <= '9') ans = (ans << 3) + (ans << 1) + ch - '0', ch = getchar();
	return s * ans;
}
void solve()
{
	ans = 0;
	cnt = 0;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			int res = a[i] + b[j];
			e[++cnt] = res;
		}
	}
	std::sort(e + 1, e + cnt + 1);// 直接排序走一波
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			int res = c[i] + d[j];
			int temp = std::upper_bound(e + 1, e + n * n + 1, -res) - std::lower_bound(e + 1, e + n * n + 1, -res);// 直接算出有多少个,第一次见这么用
			ans += temp;
		}
	}
}
int main()
{
	int T = read();
	while(T--)
	{
		n = read();
		for(int i = 1; i <= n; i++)
		{
			a[i] = read(), b[i] = read(), c[i] = read(), d[i] = read();
		}
		solve();
		printf("%d\n", ans);
		if(T) printf("\n");
	}
	return 0;
}
posted @ 2018-10-25 22:00  Garen-Wang  阅读(88)  评论(0)    收藏  举报