POJ 1840 Eqs(hash)

版权声明:听说这里让写版权声明~~~ https://blog.csdn.net/m0_37691414/article/details/82153510

题意:给出a1, a2, a3, a4, a5
求满足表达式 a1x13+ a2x23+ a3x33+ a4x43+ a5x53=0 的解(x1, x2, x3, x4, x5)的个数,其中xi范围是[-50, 50], xi != 0 (i = 1, 2, 3, 4, 5)

分析:这题挺简单的,将解分成两组(x1, x2) 和 (x3,x4, x5),先两重循环求出a1x13+ a2x23他们的解,用开散列法对应到数组中,再用两重循环求出a3x3 + 3a4x43+ a5x53求得结果在hash表中查找然后判断就行了。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
using namespace std;
const int N = 1000020;
const int mode = 100003;
vector<int> v[N];
int cube(int x){
	return x*x*x;
}
int getHash(int x){
	int key = x % mode;
	if(key < 0) key += mode;
	return key;
}
int isZero(int x){
	int cnt = 0;
	int key = getHash(x);
	for(int i = 0; i < v[key].size(); ++i)
		if(v[key][i] == x)	cnt++;
	return cnt;
}
int main(){
	int x1, x2, x3, x4, x5;
	int a1, a2, a3, a4, a5;
	int tmp, h;
    scanf("%d%d%d%d%d", &a1, &a2, &a3, &a4, &a5);
    for(x1 = -50; x1 <= 50; ++x1){
    	if(x1 == 0)	continue;
    	for(x2 = -50; x2 <= 50; ++x2){
    		if(x2 == 0)	continue;
    		tmp = a1 * cube(x1) + a2*cube(x2);
    		h = getHash(tmp);
    		v[h].push_back(tmp);
		}
	}
	int res = 0;
	for(x3 = -50; x3 <= 50; ++x3){
		if(x3 == 0)	continue;
		for(x4 = -50; x4 <= 50; ++x4){
			if(x4 == 0)	continue;
			for(x5 = -50; x5 <= 50; ++x5){
				if(x5 == 0)	continue;
				tmp = a3 * cube(x3) + a4 * cube(x4) + a5 * cube(x5);
				tmp = - tmp;
				res += isZero(tmp);
			}
		}
	}
    printf("%d\n", res);
}

猜你喜欢

转载自blog.csdn.net/m0_37691414/article/details/82153510
今日推荐