POJ 1016 Numbers That Count

模擬即可,注意最後條件判斷的順序,我就是因爲這個WA了2次。

 

#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <cstring>

using namespace std;

int cnt[10];

int main()
{
    char start_num[105],tmp[105],last_num[105];
    map<string,int> mp;
    map<string,int>::iterator it;
    string str;
    int i,step,j,tens,unit;
    while (scanf("%s",start_num)==1 && start_num[0]!='-')
    {
        mp.clear();
        str.assign(start_num);
        mp.insert(pair<string,int> (str,0));
        strcpy(last_num,start_num);
        for (step=0;step<15; step++)
        {
            memset(cnt,0,sizeof(cnt));
            for (i=0; last_num[i]!='\0'; i++)
                cnt[last_num[i]-'0']++;
            for (i=0,j=0;i<=9;i++)
            {
                if (cnt[i]>=10)
                {
                    tens=cnt[i]/10;
                    unit=cnt[i]%10;
                    tmp[j++]=tens+'0';
                    tmp[j++]=unit+'0';
                    tmp[j++]=i+'0';
                }
                else if (cnt[i]>=1 && cnt[i]<=9)
                {
                    tmp[j++]=cnt[i]+'0';
                    tmp[j++]=i+'0';
                }
            }
            tmp[j]='\0';
            str.assign(tmp);
            it=mp.find(str);
            if (it==mp.end())
                mp.insert(pair<string,int> (str,step+1));
            else
                break;
            strcpy(last_num,tmp);
        }
        if (step==0)
            printf("%s is self-inventorying\n",start_num);
        else if (step==15)
            printf("%s can not be classified after 15 iterations\n",start_num);
        else if (mp[str]==step)
            printf("%s is self-inventorying after %d steps\n",start_num,step);
        else
            printf("%s enters an inventory loop of length %d\n",start_num,step-mp[str]+1);
    }
    return 0;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章