题目描述: 定义一个整数的inventory为:从0到9排列的(数字的个数+数字)。
例如”5553141”里面有2个1、1个3、1个4、3个5。所以”21131435”是”5553141”的inventory。
定义一个整数的第n(n>1)个inventory为:它的第n-1个inventory的inventory。
定义一个整数进入一个长度为n的inventory循环为:它的第n个inventory是它本身。
- 如果一个数的inventory是它本身,则说它是self-inventory的。
- 如果一个数的第n个inventory是self-inventorying的,则说它在第n步之后是self-inventorying的。
- 如果一个数进入了一个长度为k的inventory循环,则说它enters an inventory loop of length k。
- 如果一个数的前15个inventory都不满足上述三个条件的话,则说它can not be classified after 15 iterations
输入格式:有多组数据,每组数据输入一行,每行一个整数n,n为-1时结束输入
输出格式:每组数据都输出下面四句话中的一句:
- n is self-inventorying
- n is self-inventorying after j steps
- n enters an inventory loop of length k
- n can not be classified after 15 iterations
数据约定:n最大不超过80位。
解题思路:我不会告诉你这是一道水题的。。
#include <cstdio>
#include <cstring>
int handle(char *s, int *head, int *tail);
int main(int argc, char const *argv[])
{
char s[100];
while(scanf("%s", s) && s[0]!='-'){
int head=-1, tail=-1;
handle(s, &head, &tail);
if(head==-1) {
printf("%s can not be classified after 15 iterations\n", s);
} else if(head==0&&tail==1){
printf("%s is self-inventorying\n", s);
} else if(tail-head==1) {
printf("%s is self-inventorying after %d steps \n", s, head);
} else {
printf("%s enters an inventory loop of length %d\n", s, tail-head);
}
}
return 0;
}
void getinventory(char *ss, char *s)
{
int nums[10] = {0};
for(char *p=s;*p!='\0';nums[*p++-'0']++);
for(int i=0, p=0; i<10; ++i){
if(nums[i]!=0){
while(nums[i]!=0){
ss[p++]=nums[i]%10+'0';
nums[i]/=10;
}
ss[p++]=i+'0';
ss[p]='\0';
}
}
}
int handle(char *s, int *head, int *tail)
{
char cs[16][100];
strcpy(cs[0], s);
for(int i=0; i<15; ++i){
getinventory(cs[i+1], cs[i]);
}
for(int i=0; i<16; ++i){
for(int j=i+1; j<16; ++j){
if(strcmp(cs[i],cs[j])==0){ *head = i; *tail = j; }
if(*head!=-1) { break; }
}
if(*head!=-1) { break; }
}
return *head;
}