codeforces 568A A. Primes or Palindromes?(打表+暴力枚举)

题目链接:

codeforces 568A

题目大意:

p,q,A=pq,sum1[i]isum2[i]i,sum1[i]Asum2[i]i

题目分析:

首先通过线性筛将素数和回文数,然后暴力枚举即可。

AC代码:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#define MAX 2000007

using namespace std;
int sum1[MAX],sum2[MAX];
int maxPrime[MAX];
int p,q;

void init ()
{
    memset ( maxPrime , -1 , sizeof ( maxPrime) );
    sum1[1] = sum1[0] = 0;
    for ( int i = 2 ; i < MAX ; i++ )
    {
        if ( ~maxPrime[i] )
        {
            sum1[i] = sum1[i-1];
            continue;
        }
        sum1[i] = sum1[i-1] + 1;
        for ( int j = 2*i ; j < MAX ; j += i )
            maxPrime[j] = i;
    }
    sum2[0] = 0;
    int digit[15],cnt=0;
    for ( int i = 1; i < MAX ; i++ )
    {
        cnt = 0;
        int x = i;
        while ( x )
        {
            digit[cnt++] = x%10;
            x/=10;
        }
        bool flag = true;
        for ( int j = 0 ; j < (cnt+1)/2 ; j++ )
            if ( digit[j] != digit[cnt-1-j] )
                flag = false;
        sum2[i] = sum2[i-1];
        if ( flag ) sum2[i]++;
    }
}

int gcd ( int x , int y )
{
    return !y?x:gcd ( y , x%y );
}

int main ( )
{
    init ();
    while (~scanf ( "%d%d" , &p , &q ))
    {
        int ans = -1;
        int d = gcd ( p , q );
        p /= d , q /= d;
        for ( int i = MAX-1 ; i >= 1 ; i-- )
            if ( q* sum1[i] <= p * sum2[i] )
            {
                ans = i;
                break;
            }
        if ( ans == -1 ) puts ("Palindromic tree is better than splay tree");
        else printf ( "%d\n" , ans );
    }
}

你可能感兴趣的:(数论,codeforces)