USACO Palindromic Squares (数制转换)

题目大意:找出1到300的数中其平方在b进制下是回文的数,并打印这些数数及其平方在b进制下的表示。

View Code
/*

ID: lijian42

LANG: C++

TASK: palsquare

*/

#include <stdio.h>

#define LEN 20

#define N 300

char t[20]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J'};

char s1[LEN],s2[LEN];

int cnt1,cnt2;

int b;

void tran(int k,char s[],int &cnt)

{

    cnt=0;

    while(k)

    {

        s[cnt++]=t[k%b];

        k/=b;

    }

}

bool judge(char s[],int cnt)

{

    int i,j;

    for(i=0,j=cnt-1;i<j;i++,j--)

    {

        if(s[i]!=s[j])  return false;

    }

    return true;

}

void print()

{

    int i;

    for(i=cnt2-1;i>=0;i--)  printf("%c",s2[i]);

    printf(" ");

    for(i=cnt1-1;i>=0;i--)   printf("%c",s1[i]);

    puts("");

}

void solve()

{

    int i;

    for(i=1;i<=N;i++)

    {

        tran(i*i,s1,cnt1);

        if(judge(s1,cnt1))

        {

            tran(i,s2,cnt2);

            print();

        }

    }

}

int main()

{

    freopen("palsquare.in","r",stdin);

    freopen("palsquare.out","w",stdout);

    while(~scanf("%d",&b))

    {

        solve();

    }

    return 0;

}

 

你可能感兴趣的:(USACO)