您的位置:首页 > 其它

poj1016

2016-07-23 17:26 197 查看
Problem : Numbers That Count

Description:给你一串数字,例如111222234459,里边有3个1,4个2,1个3,2个4,1个5,1个9,所以新形成的字符串为314213241519,然后接着计算新的字符串中每个数字的个数。问多少次以后这个字符串能变成之前一样的字符串。

Solution:递归。主要要注意字符串与int型之间的转换。

Code(C++):

#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cstdio>

using namespace std;

int count[10];
string str[20];
int a[80];
int i,j,t,length;

void compare(string s,int k)
{
if(k==16)
{
cout<<str[0]<<" can not be classified after 15 iterations"<<endl;
return;
}
str[k]="";
length=s.size();
for(i=0; i<length; i++)
a[i]=s.at(i)-'0';
memset(count,0,sizeof(count));
int i;
for(i=0; i<length; i++)
count[a[i]]++;
for(i=0; i<10; i++)
{
if(count[i]==0)
continue;
/*char tmp[78];
_itoa(count[i],tmp,10);
str[k]+=string(tmp);
_itoa(i,tmp,10);
str[k]+=string(tmp);*/
char sr[5]="",t[5]="";
sprintf(sr,"%d",count[i]);
sprintf(t,"%d",i);
str[k]+=string(sr);
str[k]+=string(t);
}
for(i=k-1; i>=0; i--)
{
if(str[k]==str[i])
{
if(i==0&&k-i==1)
cout<<str[0]<<" is self-inventorying"<<endl;
else if(k-i==1)
cout<<str[0]<<" is self-inventorying after "<<i<<" steps"<<endl;
else
cout<<str[0]<<" enters an inventory loop of length "<<k-i <<endl;
return ;
}
}
compare(str[k],k+1);
}

int main()
{
string s;
while(cin>>s,s!="-1")
{
t=1;
str[0]=s;
compare(s,t);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj