Equations HDU - 1496(哈希或三层for循环)求满足公式有多少种情况
題意:求x在(-100<=x<=100)區(qū)間上,已知a,b,c,d,滿足a*x1^2+b*x2^2+c*x3^2+d*x4^2=0 的情況有多少種
思路:很明顯四層for循環(huán)肯定超時(shí),可用三層for循環(huán)來(lái)判斷,或是,兩兩組合,求多少種情況。分正負(fù)故最后
要乘上2^4;
題目
Consider equations having the following form:?
a*x1^2+b*x2^2+c*x3^2+d*x4^2=0?
a, b, c, d are integers from the interval [-50,50] and any of them cannot be 0.?
It is consider a solution a system ( x1,x2,x3,x4 ) that verifies the equation, xi is an integer from [-100,100] and xi != 0, any i ∈{1,2,3,4}.?
Determine how many solutions satisfy the given equation.?
Input
The input consists of several test cases. Each test case consists of a single line containing the 4 coefficients a, b, c, d, separated by one or more blanks.?
End of file.
Output
For each test case, output a single line containing the number of the solutions.?
Sample Input
1 2 3 -4 1 1 1 1Sample Output
39088 0AC代碼
哈希:
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int f1[1000005],f2[1000005];//f1保存得數(shù)是正的 f2保存得數(shù)是負(fù)的 int a,b,c,d; int main() {while(~scanf("%d%d%d%d",&a,&b,&c,&d)){if((a>0&&b>0&&c>0&&d>0)||(a<0&&b<0&&c<0&&d<0)) //abcd全部大于0或者小于0,肯定無(wú)解。要加上這個(gè),不然超時(shí){printf("0\n");continue;}memset(f1,0,sizeof(f1));memset(f2,0,sizeof(f2));for(int i=1; i<=100; i++)for(int j=1; j<=100; j++){int ans=a*i*i+b*j*j;if(ans>=0) f1[ans]++;else f2[-ans]++;}int sum=0;for(int i=1; i<=100; i++)for(int j=1; j<=100; j++){int ans=c*i*i+d*j*j;if(ans>0) sum+=f2[ans];else sum+=f1[-ans];}printf("%d\n",16*sum);//每個(gè)解有正有負(fù),結(jié)果有2^4種}return 0; }三層for循環(huán):
#include<iostream> #include<cstdio> #include<cmath>/*暴力*/ #include<cstring> using namespace std; int main() {int a,b,c,d;while(~scanf("%d%d%d%d",&a,&b,&c,&d)){if(a>0&&b>0&&c>0&&d>0||a<0&&b<0&&c<0&&d<0){printf("0\n");continue;}int sum=0;for(int i=1; i<=100; i++)//因?yàn)檎?fù)號(hào)不同不影響平方的效果,所以只枚舉正數(shù)for(int j=1; j<=100; j++)for(int l=1; l<=100; l++){int f=a*i*i+b*j*j+c*l*l;if(f%d==0){int h=sqrt(abs((0-f)/d));if(h<=100&&h>0&&h*h==abs((0-f)/d)&&f+d*h*h==0)sum++;}}printf("%d\n",sum*16);}return 0; }?
總結(jié)
以上是生活随笔為你收集整理的Equations HDU - 1496(哈希或三层for循环)求满足公式有多少种情况的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 七招打造有逼格的字体
- 下一篇: Colossal Fibonacci N