Bus Numbers
Your favourite public transport company LS (we cannot use their real name here, so we permuted the letters) wants to change signs on all bus stops. Some bus stops have quite a few buses that stop there and listing all the buses takes space. However, if for example buses 141, 142, 143 stop there, we can write 141–143 instead and this saves space. Note that just for two buses this does not save space.
You are given a list of buses that stop at a bus stop. What is the shortest representation of this list?
Input
The first line of the input contains one integer N,1≤N≤1000N,1≤N≤1000, the number of buses that stop at a bus stop. Then next line contains a list of NN space separated integers between 1 and 10001000, which denote the bus numbers. All numbers are distinct.
Output
Print the shortest representation of the list of bus numbers. Use the format as in the example, separate numbers with single spaces and output them in sorted order.
Sample Input 1 | Sample Output 1 |
---|---|
6 |
141-143 174 175 180 |
题意
将给出的数字按照升序排好,然后是连续的就连起来直接输出
代码
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
#pragma warning(disable:4996);
int a[],n;
int main() {
while (~scanf("%d", &n))
{
for (int i = ; i < n; i++)
{
scanf("%d", &a[i]);
}
sort(a, a + n);
int key = ;
printf("%d", a[]);
if (a[] + == a[])key++;
for (int i = ; i < n; i++)
{
if (key == && a[i] + == a[i + ])
{
printf(" %d", a[i]);
key++;
}
else if (key &&a[i] + == a[i + ])
{
key++;
continue;
}
else if (a[i + ]!= a[i] + )
{
if (key>)
{
key = ;
printf("-%d", a[i]);
}
else
{
key = ;
printf(" %d", a[i]);
}
}
}puts("");
}
return ;
}