2018 ACM-ICPC 中国大学生程序设计竞赛线上赛 (Reversion Count) (一个数和一个数的倒序的差一定是 9的倍数,还有...)

Description:

There is a positive integer X, X's reversion count is Y. For example, X=123, Y=321; X=1234, Y=4321. Z=(X-Y)/9, Judge if Z is made up of only one number(0,1,2...9), like Z=11,Z=111,Z=222,don't consider '+'and '-'.

Input:

Input contains of several test cases. Each test case only contains of a number X, L is the length of X. ( 2 <= L < 100)

Output:

Output “YES”or “NO”.

样例输入

10
13

样例输出

YES
YES

题目来源

2018 ACM-ICPC 中国大学生程序设计竞赛线上赛


题意:输入一个长度为 小于100的数,判断这个数和这个数的倒序被 9 整除后的数中 的数字是不是都相同;

思路:通常大家想法一定和我一样 把过程模拟一边就行了呗,但是这其中是有规律可询的,找到规律,你将受益无穷;

首先 一个数n与他反序数的差的绝对值,一定是9的倍数。证明如下:


设四位数 ABCD 他的反序数是DBCA

ABCD-DCBA=(1000*A+100*B+10*C+D)-(1000*D+100*C+10*B+A)

=(1000-1)*A+(100-10)*B-(100-10)*C-(1000-1)*D

=999*A+90*B-90*C-999*D

=(111*A+10*B-10*C-111*D)*9


再设五位数 ABCDE 他的反序数是 EDCBA

ABCDE-EDCBA=(10000*A+1000*B+100*C+10*D+E)-(10000*E+1000*D+100*C+10*B+A)

=9999*A+990*B+0*C-990*D-9999*E

=(1111*A+110*B-110*D-1111*E)*9

可以接着模拟 6位数;

最后两个数的差要是每一位都相等的话,那么 一定是 1,11, 111, 1111.......的倍数,四位时,(111A-111D)一定是 111的倍数,10B-10C = 10(B-C) 要是B-C不为0时,一定不会是 1, 11, 111, 1111......的倍数,当 位数为 偶数时, 只需判断 当位数为 奇数时,中间的哪一位的差值,是一定被消除了,只需除首末位 和 中间位外,对称位是否相等 就行了

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define Max 110
int main()
{
	char str[Max],s[Max];
	while(~scanf("%s",str))
	{
		int i,j;
		int l = strlen(str);
		int f = 1;
		for(i = 0;i<l/2;i++)
		{
			if(i==0)
				continue;
			else
				if(str[i]!=str[l-1-i])
					f = 0;
		}
		if(f) printf("YES\n");
		else printf("NO\n");
	}
	return 0;
} 

模拟:代码二:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define Max 110


int a[Max],b[Max],c[Max];
int fff(int a[Max],int b[Max],int l)
{
	int i,j;
	for(i = l-1;i>=0;i--)
	{
		if(a[i]<b[i])
		{
			int k = i-1;
			while(a[k]==0)
			{
				a[k] = 9;
				k--;
			}
			a[k] = a[k] - 1;
			a[i] = a[i] + 10;
			c[i] = a[i] - b[i];
		}
		else 
		{
			c[i] = a[i] - b[i];
		}
	}
	i = 0;
	while(c[i]==0&&i<l)
		i++;
	int sum = 0;
	int f = 0,tmp;
	while(i<l)
	{
		//printf("%d",c[i]);
		sum = sum*10 + c[i];
		int t = sum/9;
		sum = sum%9;
		if(t!=0&&!f)
		{
			tmp = t;
			f = 1;
		}
		if(f)
		{
			if(t!=tmp)
				return 0;
		}
		i++;
	}
	//printf()
	return 1;
}
int main()
{
	char str[Max],s[Max];
	int i,j;
	while(~scanf("%s",str))
	{
		int l = strlen(str);
		for(i = 0;i<l;i++)
		{
			a[i] = str[i] - '0'; // 因为两个数的长度相同,相减时,可以不用倒着存; 
			b[l-1-i] = str[i]-'0';
			s[l-1-i] = str[i];
		}
		s[l] = '\0';
		if(strcmp(str,s)>=0)
		{
			if(fff(a,b,l))
				printf("YES\n");
			else printf("NO\n");
		}
		else 
		{
			if(fff(b,a,l))
				printf("YES\n");
			else printf("NO\n");
		}
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/obsorb_knowledge/article/details/80051587