string有以下几个方便的特性:
1.string重载了+号,==号等符号.
2.string可以和char相加,也可以和char数组相加
通过这两个特性可以很方便的构造每一个数的另一种表示形式。
map 记录每个字符串首次出现的时间,判断周期的时候用。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#include <map>
#include <string>
int a[11];
int main(){
string s;
while(cin>>s){
if(s[0]=='-') break;
string ini=s;
map <string,int> cur;
cur[s]=0;
int T=0;
int flag=0;
for(int i=1;i<=15;i++){
memset(a,0,sizeof(a));
int len=s.size();
for(int j=0;j<len;j++){
a[s[j]-'0']++;
}
string tmp="";
char num[100];
for(int j=0;j<=9;j++){
if(!a[j]) continue;
sprintf(num,"%d",a[j]);
tmp+=num;
tmp+=char(j+'0');
}
if(tmp==s){
flag=1;
T=i;
break;
}
s=tmp;
if(cur.count(s)){
flag=2;
T=i-cur[s];
break;
}
cur[s]=i;
}
cout<<ini;
if(flag==1&&T==1){
printf(" is self-inventorying\n");
}
else if(flag==1&&T>1){
printf(" is self-inventorying after %d steps\n",T-1);
}
else if(flag==2){
printf(" enters an inventory loop of length %d\n",T);
}
else if(!flag){
printf(" can not be classified after 15 iterations\n");
}
}
return 0;
}
786



被折叠的 条评论
为什么被折叠?



