POJ 1016--Numbers That Count

题意

题目的意思很简单,就是对字符串的反复压缩。比如,5553141里面有2个1,1个3,1个4,3个5,所以压缩一下变为21131435,接着压缩变为3112231415,4122231415,3132132415,3122331415,3122331415,直到出现自身循环,或者像314213241519→412223241519→314213241519出现loop为2的循环,最大迭代次数为15,

分析

比较简单,直接上代码:
Memory: 232K Time: 79MS Length:50LINES

#include<iostream>
#include<string>
using namespace std;
int Search(const string* vecstr, string str, int k)      //搜索有没有出现循环
{
    int i = 0;
    for (; i < k; ++i)    if (vecstr[i] == str) break;
    return i;
}
int main()
{
    string input;
    while (cin >> input && input[0] != '-')
    {
        string temp = input;
        string vecstr[16] = { "" };
        int count = 0;
        do
        {
            vecstr[count] = temp;
            int number[10] = { 0 };
            for (string::size_type i = 0; i < temp.length(); ++i)   ++number[temp[i] - 48];  //统计每个字符出现的次数
            temp = "";
            for (int i = 0; i < 10; ++i)
            {
                if (number[i] == 0) continue;
                if (number[i] >= 10)
                {
                    temp += number[i] / 10 + 48;
                    temp += number[i] % 10 + 48;
                }
                else    temp += number[i] + 48;
                temp += i + 48;                         //组成新的字符串
            }
            ++count;
        } while (Search(vecstr, temp, count) == count && count <= 15);
        if (count > 15)
            cout << input << " can not be classified after 15 iterations" << endl;
        else if (count == 1)
            cout << input << " is self-inventorying" << endl;
        else if (Search(vecstr, temp, count) == count - 1)
            cout << input << " is self-inventorying after " << count - 1 << " steps" << endl;
        else
        {
            cout << input << " enters an inventory loop of length ";
            cout << count - Search(vecstr, temp, count) << endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值