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.
这里写图片描述

题目大意:

分页,去重排序后有连续的比如1,2,3就简写成1-3。2,3,4,5就写成2-5,其他单个的就单飞。
哈哈,其实思路就已经说完了,需要注意的也就是输出的逗号了,第一个直接输出,后面的先出逗号再出结果。直接上代码了:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct result
{
  int  qi;
  int len;
}r[110];
int main()
{
  int a[110]={0},book[1010]={0};
  string s;
  cin>>s;
  int k=0,temp=0;
  for(int i=0;i<s.size();i++)
  {
    if(s[i]>='0'&&s[i]<='9')
    {
       temp=temp*10+s[i]-'0';
     }
    else
    {
      if(!book[temp])
      {
        book[temp]=1;
        a[k++]=temp;
      }
      temp=0;
    }
  }
  if(!book[temp])a[k++]=temp;
  sort(a,a+k);
  int cur=0;
  for(int i=0;i<k;i++)
  {
    int len=1;
    if(a[i]+1==a[i+1])
    {
      r[cur].qi=a[i];
      r[cur].len++;
      while(i<k)
      {
        if(a[i]+1==a[i+1])r[cur].len++;
        else break;
        i++;
      }
      cur++;
    }
    else
    {
      r[cur].qi=a[i];
      r[cur].len=0;
      cur++;
    }
  }
  if(r[0].len>=1)cout<<r[0].qi<<'-'<<r[0].qi+r[0].len-1;
  else cout<<r[0].qi;
  for(int i=1;i<cur;i++)
  {
    cout<<',';
    if(r[i].len>1)cout<<r[i].qi<<'-'<<r[i].qi+r[i].len-1;
    else cout<<r[i].qi;
  }
  cout<<endl;
}

猜你喜欢

转载自blog.csdn.net/A7_RIPPER/article/details/81461163