B - Chtholly's request CodeForces - 897B

B - Chtholly’s request CodeForces - 897B


— Thanks a lot for today.
— I experienced so many great things.
— You gave me memories like dreams… But I have to leave now…
— One last request, can you…
— Help me solve a Codeforces problem?
— …
— What?
Chtholly has been thinking about a problem for days:
If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.
Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo p.
Unfortunately, Willem isn’t good at solving this kind of problems, so he asks you for help!

Input
The first line contains two integers k and p (1 ≤ k ≤ 105, 1 ≤ p ≤ 109).

Output
Output single integer — answer to the problem.

Examples
Input
2 100
Output
33
Input
5 30
Output
15
Note
In the first example, the smallest zcy number is 11, and the second smallest zcy number is 22.
[题目链接]https://vjudge.net/contest/290237#problem/B


思路:

  • 题目的要求是要将位数为偶数的回文数字(zcy),从最小开始加,加到回文数的数量为k时停止,(记回文数的和为sum),最后输出sum%p。
  • 我在看题的时候,虽然看懂了题目,可是却想不出具体的求解方法,到比赛结束后,听了做出来的同学的做法,觉得真的很奇妙,原来是有规律的
11 22 33 44 55 66 77 88 99
1001 1111 1221 1331 1441 1551 1661 1771 1881 1991
2002 2112 2222 2332 2442 2552 2662 2772 2882 2992

从表,我们可以看出来,这组回文数的左半部分是从1开始,每次都递增1,;而左半部分的数字倒过来,就是右半部分的值;左右合起来就是对应的回文数

  • 现在目标就很明确了,我们只要把两部分连起来就可以了。刚开始,我的想法是把这两部分当做字符串连起来,再将字符串转为long int,但最后觉得太麻烦,还是没有采用了这种方法。最后,我将左半部分的值拆分,算出右半部分的值之后,再将两个部分合起来,形成回文数

AC代码:

#include<stdio.h>
#include<math.h>
//拆分并合并,形成回文数
long long f(int n,int m){
    
    
	int k=0; 
	long long sum=0LL;
	int temp=n;
	int arr[100005];
	while(temp!=0){
    
    
		arr[k++]=temp%10;
		temp=temp/10;
	}
	for(int i = k-1 ; i >= 0 ; i--){
    
    
		sum+=arr[i]*pow(10,k-1-i);
	}
	sum+=n*pow(10,k);
	return sum%m;//每个回文数都%m,使值尽量变小
}
int main(){
    
    
	int k,p;
	while(~scanf("%d%d",&k,&p)){
    
    
		long long sum = 0;
		for(int i = 1 ; i <= k ; i++){
    
    
			sum=(sum+f(i,p))%p;
		}
		printf("%lld\n",sum);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43846755/article/details/88846544
今日推荐