Codeforces Round #449 (Div. 2).B

B. Chtholly’s request

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output

— 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.

In the second example, 在這裏插入圖片描述

題解
這道題k的取值達到105次方,若暴力,從1開始累加再判斷肯定超時,但我們可以看到題目只要求位數是偶數的數,因此,根據迴文數的特徵,比如123321,1221,前一半的數會等於後一半數的倒置。
當n=1時,所得迴文數是11;
當n=2時,所得迴文數是22;


當n=11時,所得迴文數是1111;
不難發現迴文數的大小和n的取值有關,當n1<n2時,所得迴文數M1<M2,根據這個特徵,我們便很容易找出前k個迴文數,再進行相加,因爲第105 個迴文數會十分大,再加上sum會超出int範圍,因此,在每次相加過程都必須對sum取模。

在這裏插入圖片描述

代碼如下:

#include<cstdio>  
#include<cstring>  
#include<cstdlib>  
#include<cmath>  
#include<iostream>  
#include<algorithm>  


using namespace std;

int ss(int d){
	int num = 0;
	while(d){
		d /= 10;
		num++;
	}
	return num;
}
int xx(int d,int num){
	int s=0;
	int j=num;
	while(d){
		int t = d % 10;
		s += t * pow(10.0,num-1);
		d /= 10;
		num --;
	}
	return s;
}
int main(int argc, char *argv[]) {
	int k,p;
	while(~scanf("%d%d",&k,&p)){
		long long sum = 0;
		for(int i=1; i<=k; ++i){
			int num = ss(i);
			sum += i * pow(10.0,num); 
			sum %= p;
			sum += xx(i,num);
			sum %= p;
		}
		printf("%lld\n",sum);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章