TLE求调

P1015 [NOIP1999 普及组] 回文数

HZT1121 @ 2024-10-06 12:37:13

代码:

# include <cstdio>
# include <string>
using namespace std;

int n, m, l;
char a[305];

int fz(int a)
{
    int n = 0;
    while(a != 0)
    {
        n = (n + a % 10) * 10;
        a /= 10;
    }
    return n;
}

void gj(int x, int b)
{
    int jw = 0, i = 1;
    string s = "0123456789ABCDEFG";
    while(x != 0 || b != 0)
    {
        i++;
        int tmp = x % 10 + b % 10 + jw;
        if(tmp >= n)
        {
            tmp -= n;
            jw ++;
            a[i] = s[tmp];
        }
    }
    l = i;
}

int zh()
{
    int n = 0;
    for(int i = l; i >= 1; i--)
    {
        n = (n + a[i]) * 10;
    }
    return n;
}

bool hw(int a)
{
    if(fz(a) == a) return 1;
    return 0;
}

int main(){
    scanf("%d %d", &n, &m);
    int number = m;
    for(int i = 1; i <= 30; i++)
    {
        if(hw(number))
        {
            printf("STEP=%d", number);
            return 0;
        }
        gj(number, fz(number));
        number = zh();
    }
    printf("Impossible!");
    return 0;
}

by Lisuyang @ 2024-10-06 12:40:53

@HZT1121

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string M;
int N;
char w1[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int w2[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
string down(string k1){
    string k2;
    for(int i = k1.size()-1; i >= 0; -- i) k2 += k1[i];
    return k2;
}

string add(string k1, int N){
    string k2 = down(k1), ans = "";
    int a, b, s = 0;
    for(int i = k1.size()-1; i >= 0; -- i){
        if(isdigit(k1[i])) a = w2[k1[i] - '0'];
        else a = w2[k1[i] - 'A' + 10];
        if(isdigit(k2[i])) b = w2[k2[i] - '0'];
        else b = w2[k2[i] - 'A' + 10];
        a += (b + s);
        b = a % N, s = a / N;
        ans += w1[b];
    }
    if(s != 0) ans += w1[s];
    ans = down(ans);
    return ans;
}

bool is_palindrome(string k1){
    return k1 == down(k1);
}

int main(){
    cin >> N >> M;
    if(is_palindrome(M)){
        printf("0");
        return 0;
    }
    for(int i = 1; i <= 30; ++ i){
        M = add(M, N);
        if(is_palindrome(M)){
            printf("STEP=%d", i);
            return 0;
        }
    }
    printf("Impossible!");
    return 0;
}

|