PAT甲级 -- 1019 General Palindromic Number (20 分)

博客介绍了回文数概念,即正读和反读相同的数。给定正十进制整数N和进制b,需判断N在b进制下是否为回文数。还给出输入、输出规格及示例输入输出,最终结果为AC。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.

Although palindromic numbers are most often considered in the decimal system, the concept of palindromicity can be applied to the natural numbers in any numeral system. Consider a number N>0 in base b≥2, where it is written in standard notation with k+1 digits a​i​​ as ∑​i=0​k​​(a​i​​b​i​​). Here, as usual, 0≤a​i​​<b for all i and a​k​​ is non-zero. Then N is palindromic if and only if a​i​​=a​k−i​​ for all i. Zero is written 0 in any base and is also palindromic by definition.

Given any positive decimal integer N and a base b, you are supposed to tell if N is a palindromic number in base b.

Input Specification:

Each input file contains one test case. Each case consists of two positive numbers N and b, where 0<N≤10​9​​ is the decimal number and 2≤b≤10​9​​ is the base. The numbers are separated by a space.

Output Specification:

For each test case, first print in one line Yes if N is a palindromic number in base b, or No if not. Then in the next line, print N as the number in base bin the form "a​k​​ a​k−1​​ ... a​0​​". Notice that there must be no extra space at the end of output.

Sample Input 1:

27 2

Sample Output 1:

Yes
1 1 0 1 1

Sample Input 2:

121 5

Sample Output 2:

No
4 4 1

AC 

#include <iostream>
#include <memory.h>
using namespace std;

long long n, b;
long long arr[20];
int ct = 0;

bool change(long long num, long long base)
{
    if(num == 0)
    {
        arr[ct++] = 0;
        return true;
    }
    memset(arr,0,sizeof(arr));
    while(num != 0)
    {
        arr[ct++] = num % base;
        num /= base;
    }
    for(int i = 0; i <= ct/2; i++)
    {
        if(arr[i] != arr[ct-1-i])
        {
            return false;
        }
    }
    return true;

}
int main()
{
	scanf("%lld %lld", &n, &b);
	if(change(n,b))
    {
        printf("Yes\n");
        for(int i = ct - 1; i >= 0; i--)
        {
            if(i!=0)
                printf("%lld ", arr[i]);
            else
                printf("%lld", arr[i]);
        }
    }else
    {
        printf("No\n");
        for(int i = ct - 1; i >= 0; i--)
        {
            if(i!=0)
                printf("%lld ", arr[i]);
            else
                printf("%lld", arr[i]);
        }
    }
	return 0;
}

 

### 使用 Rabin-Karp 算法结合二法查找最长回文子串 为了找到给定字符串中的最长回文子串,可以采用一种组合策略:利用二查找来决定可能的最大长度,并通过哈希函数验证该长度下的子串是否为回文。这种方法能够有效地减少不必要的比较次数。 #### 基本思路 1. 定义一个辅助函数 `is_palindrome` 来判断指定位置和长度的子串是不是回文; 2. 对于每一个潜在的中心点(单字符或双字符),尝试扩展到最大范围内的回文; 3. 利用二查找技术,在已知最小值0和当前发现的最大回文字串长度之间进行搜索; 4. 在每次迭代过程中应用Rabin-Karp算法快速检测是否存在相同长度的不同起始位置但具有相等哈希值的子串;如果找到了,则进一步确认这些候选者确实是回文并更新最优解。 下面是一个Python实现的例子: ```python def rabin_karp_hash(s, p=1_000_000_007, a=256): """计算字符串s基于质数p以及基数a的滚动散列""" hash_value = 0 for char in s: hash_value = (hash_value * a + ord(char)) % p return hash_value def check_palindrome(text, length): """检查text中是否有length长度的回文子串.""" if not text or len(text) < length: return False MOD = 1_000_000_007 BASE = 256 powerL = pow(BASE, length-1, MOD) hashes = set() current_hash = rabin_karp_hash(text[:length], MOD, BASE) for i in range(len(text)-length+1): if str(text[i:i+length]) == str(text[i:i+length])[::-1]: return True next_char_index = i + length if next_char_index < len(text): current_hash = ((current_hash - ord(text[i]) * powerL) * BASE + ord(text[next_char_index])) % MOD while current_hash < 0: current_hash += MOD if current_hash in hashes and \ str(text[i+1:i+length+1]) == str(text[i+1:i+length+1])[::-1]: return True else: hashes.add(current_hash) return False def longest_palindromic_substring_with_rk_and_binary_search(s): lo, hi = 0, len(s)+1 best_len = 0 result = "" while lo <= hi: mid = (lo + hi)//2 found = check_palindrome(s, mid) if found: best_len = max(best_len, mid) result = get_any_palindrome_of_length(s, mid) lo = mid + 1 else: hi = mid - 1 return result def get_any_palindrome_of_length(s, l): n = len(s) for start in range(n-l+1): substr = s[start:start+l] if substr == substr[::-1]: return substr raise ValueError(f"No palindrome of length {l} exists.") ``` 此代码实现了上述提到的功能,其中包含了几个重要的部- 计算字符串哈希值的方法 `rabin_karp_hash()`, - 验证特定长度下是否存在回文的方法 `check_palindrome()`, - 结合二查找逻辑寻找最长达标的回文子串的核心过程 `longest_palindromic_substring_with_rk_and_binary_search()`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值