Sereja loves integer sequences very much. He especially likes stairs.
Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met:
For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.
Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?
The first line contains integer m (1 ≤ m ≤ 105) — the number of Sereja's cards. The second line contains m integers bi (1 ≤ bi ≤ 5000) — the numbers on the Sereja's cards.
In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.
5 1 2 3 4 5
5 5 4 3 2 1
6 1 1 2 2 3 3
5 1 2 3 2 1
题意:
给出M(1到10^5),并给出M个数。要求对这M个数排序,排序方式为a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.
思路:
模拟。用 map 对这个数数值和个数进行匹配,每个数除了最大数之外,最多出现两次,分别出现在最大值两边,故 map 匹配的个数最多只为2,最大项最多为 1,最后按要求输出即可。
AC:
#include<cstdio>
#include<map>
using namespace std;
int ans[100005],k = 0;
int main()
{
int n,sum = 0,maxnum= 0;
map<int,int> m;
scanf("%d",&n);
for(int i = 1;i <= n;i++)
{
int num;
scanf("%d",&num);
if(maxnum <= num) maxnum = num;
if(m[num] < 2)
{
m[num]++;
sum++;
}
} //匹配数值和个数,除最大项其他最多为2
if(m[maxnum] != 1)
{
sum -= (m[maxnum] - 1);
m[maxnum] = 1;
} //最大项最多只为1
printf("%d\n",sum);
map<int,int>::iterator it;
for(it = m.begin();it != m.end();it++)
{
if(it == m.begin()) //注意输出格式
{
printf("%d",it -> first);
it -> second--;
}
else
{
printf(" %d",it -> first);
it -> second--;
}
if(it -> second) ans[k++] = it -> first;
} //前半段输出
for(int i = k - 1;i >= 0 ;i--)
printf(" %d",ans[i]); //后半段输出
printf("\n");
}
本文介绍了一个有趣的问题:如何从一组卡片中构建出最长的楼梯序列。通过使用数据结构map来跟踪每个数字的出现次数,可以有效地解决这个问题,并实现序列的最优构建。
258

被折叠的 条评论
为什么被折叠?



