HDU 5778 BestCoder Round #85 abs (暴力枚举)

abs

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 868    Accepted Submission(s): 309

Problem Description
Given a number x, ask positive integer y2, that satisfy the following conditions:
1. The absolute value of y - x is minimal
2. To prime factors decomposition of Y, every element factor appears two times exactly.
Input
The first line of input is an integer T ( 1T50)
For each test case,the single line contains, an integer x ( 1x1018)
Output
For each testcase print the absolute value of y - x
Sample Input

5 1112 4290 8716 9957 9095

Sample Output

23 65 67 244 70

Source
BestCoder Round #85

Recommend
wange2014   |   We have carefully selected several similar problems for you:  5780 5779 5775 5774 5773 

题意:
给定一个数x,求正整数y,使得满足以下条件:
1.y-x的绝对值最小。
2.y的质因数分解式中每个质因数均恰好出现2次。
叫你求出y-x的最小绝对值。

官方题解:由于y质因数分解式中每个质因数均出现2次,那么y是一个完全平方数,设y=z*z,题目可转换成求z,使得每个质因数出现1次. 我们可以暴力枚举z,检查z是否符合要求,显然当z是质数是符合要求,由素数定理可以得,z的枚举量在logn级别复杂度


AC代码:
#include
using namespace std;
const long long INF = 0x7ffffffffll;
long long ans;
long long n;
bool solve(long long x) //判断这个数满不满足条件 
{
    if(x<2)
        return false;
    long long t=x;
    for(long long i=2;i*i<=x;i++) //暴力枚举质因数分解式 
    {
        if(x%i==0)
        {
            if(x%(i*i)==0) //出现了超过一次
            {
                return false;
            }
            x/=i;
        }
    }
    ans=min(ans,abs(t*t-n)); //最小绝对值 :y-x=(t^2-n) 
    return true;
}
int main ()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%I64d",&n);
        long long x=(long long)(sqrt(n)+0.5);
        int flag=0;
        ans=INF;
        for(int i=0; ;i++)
        {
            if(solve(x+i))
                flag=1;
            if(solve(x-i))
                flag=1;
            if(flag==1)
                break;
        }
        printf("%I64d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(HDUOJ,bestcoder,ACM_暴力穷举,ACM_素数)