Page Numbers(字符串)

«Bersoft» company is working on a new version of its most popular text editor — Bord 2010. Bord, like many other text editors, should be

able to print out multipage documents. A user keys a sequence of the
document page numbers that he wants to print out (separates them with
a comma, without spaces).

Your task is to write a part of the program, responsible for «standardization» of this sequence. Your program gets the sequence,

keyed by the user, as input. The program should output this sequence
in format l1-r1,l2-r2,…,lk-rk, where ri + 1 < li + 1 for all i from
1 to k - 1, and li ≤ ri. The new sequence should contain all the page
numbers, keyed by the user, and nothing else. If some page number
appears in the input sequence several times, its appearances, starting
from the second one, should be ignored. If for some element i from the
new sequence li = ri, this element should be output as li, and not as
«li - li».

For example, sequence 1,2,3,1,1,2,6,6,2 should be output as 1-3,6. Input

The only line contains the sequence, keyed by the user. The sequence contains at least one and at most 100 positive integer

numbers. It’s guaranteed, that this sequence consists of positive
integer numbers, not exceeding 1000, separated with a comma, doesn’t
contain any other characters, apart from digits and commas, can’t end
with a comma, and the numbers don’t contain leading zeroes. Also it
doesn’t start with a comma or contain more than one comma in a row.
Output

Output the sequence in the required format. Examples
Input

1,2,3,1,1,2,6,6,2

Output

1-3,6

Input

3,2,1

Output

1-3

Input

30,20,10

Output

10,20,30

题目大意:

输入一系列用逗号隔开的数,将这些数排序并去重后,输出用区间表示的数据(区间表示就是合并连续的数,例如:1,2,4,5,6,9,12,就要写成1—6,9,12),注意:数据的输入没有结束,要用到Ctrl+z来终止。

解题思路:

输入数据后排序去重输出即可。

我还是用的set来自动排序+去重 很好用

感觉用set还是很坑坑巴巴的,但是现在已经能自己探索自己写了,还是不错的

#include<iostream>
#include<set>
using namespace std;
int main()
{
    set<int> ss;
    set<int>::iterator iter;
    int num;
    while(cin>>num)
    {
        char a;
        cin>>a;
        ss.insert(num);
    }
    int len=ss.size();
    int b[len];
    int i=0;
    while(!ss.empty())
    {
        b[i]=*ss.begin();
        ss.erase(ss.begin());
        i++;
    }
    int flag=0;
    for(int i=0;i<len-1;i++)
    {
        if(b[i+1]==b[i]+1)
        {
            if(flag==0)
            {
                flag=1;
                cout<<b[i]<<"-";
            }
            if(flag==1)
            {
                continue;
            }
        }
        else
        {
            cout<<b[i]<<",";
            flag=0;
        }
    }
    cout<<b[len-1];
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值