杭电oj1496,代码解析

Equations
Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 4745    Accepted Submission(s): 1890



Problem Description

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 1
 

Sample Output
 
  
39088 0
 

Author
LL
 

Source
 

Recommend
LL   |   We have carefully selected several similar problems for you:   1280  1800  1264  2600  2522 
 

题目大意:
给定a,b,c,d。a*x1^2+b*x2^2+c*x3^2+d*x4^2=0
其中x1~x4 在 [-100,100]区间内, a,b,c,d在[-50,50] 区间内。
求满足上面那个式子的所有解的个数。


这题也能用hash做,涨姿势了……

思路:将等式变形为a*x1^2+b*x2^2= -(c*x3^2+d*x4^2) 先用两重循环列举a,b的所有情况,将等式的左边结果存入hash表。再用两重循环列举c,d的所有情况,看看结果的相反数在不在hash表中。统计输出。

优化:x1^2与x1的正负号无关,x2--x4同理,循环时从1-100循环即可,最后答案乘以16;若abcd均大于或小于0,直接输出0.

#include <iostream>
#include <cstring>
using namespace std;
int a,b,c,d,pin[101],hash[2000010],i,j,sum;
int main()
{
    for (i=1;i<=100;++i)
        pin[i]=i*i;
    
    while (cin>>a>>b>>c>>d){
        if ((a>0 && b>0 && c>0 && d>0) || (a<0 && b<0 && c<0 && d<0)){
            cout<<"0\n";
            continue;
        }
        memset(hash,0,sizeof(hash)); sum=0;
        for (i=1;i<=100;++i)
            for (j=1;j<=100;++j)
                hash[a*pin[i]+b*pin[j]+1000000]++;		//列举等式左边的所有x的解和a,b的组合,并置偏移1000000,这样可以偏置为正值,1000000减之可以偏置为负值
        for (i=1;i<=100;++i)
            for (j=1;j<=100;++j)
                sum+=hash[1000000-(c*pin[i]+d*pin[j])];
                /*例如hash[1000001]=1时也就是a*pin[i]+b*pin[j]=1,如果对应的(c*pin[i]+d*pin[j])=-1则sum+=hash[1000001]这里sum+=1也就是这个等式成立的情况+1,若前面一个循环没有获得这次索引为(c*pin[i]+d*pin[j]) 的哈希表,则+0也就是等式没有成立,最后根据sum的数量,有四个变量的组合,共16种,所有最后sum*16*/
        cout<<sum*16<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44617722/article/details/88795973