本文已参与「新人创作礼」活动,一起开启掘金创作之路。
Codeforces Round #698 (Div. 2)-A. Nezzar and Colorful Balls
传送门 Time Limit: 1 second Memory Limit: 512 megabytes
Problem Description
Nezzar has balls, numbered with integers . Numbers are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that for all .
Nezzar wants to color the balls using the minimum number of colors, such that the following holds.
Note that a sequence with the length at most is considered as a strictly increasing sequence.
Please help Nezzar determine the minimum number of colors.
Input
The first line contains a single integer () — the number of testcases.
The first line of each test case contains a single integer ().
The second line of each test case contains integers (). It is guaranteed that .
Output
For each test case, output the minimum number of colors Nezzar can use.
Sample Input
5
6
1 1 1 2 3 4
5
1 1 2 2 3
4
2 2 2 2
3
1 2 3
1
1
Sample Onput
3
2
4
1
1
Note
Let's match each color with some numbers. Then:
In the first test case, one optimal color assignment is .
In the second test case, one optimal color assignment is .
题目大意
给n个气球,每个气球都有编号 现在给气球涂色 相同编号的气球颜色不能相同,问至少需要几种颜色。
解题思路
很显然,看哪个编号的气球最多,就需要这么多的颜色。
题目很友好,给的编号都是按顺序的,因此就不需要再排序了。
下面用一种空间消耗比较小的方法,输入完毕即可得到答案。 用变量last记录上一个气球的编号,如果这个气球编号不同于上一个,就更新最大值M。 初始值last = -1,这样第一个气球就会与它颜色不同。
用变量locLast记录上次是第几个气球(第一个气球按第0个处理)。
AC代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int N;
cin >> N;
while (N--)
{
int n;
cin >> n;
int last = -1; //上一个气球的编号
int M = 1;
int locLast = -1; //这个颜色的气球的上一个location
for (int i = 0; i < n; i++)
{
int t;
scanf("%d", &t); //这个气球的编号
if (t != last) //这个气球编号和上一个不同
{
last = t; //更新last
M = max(M, i - locLast); //更新最大值M
locLast = i; //更新locLast
}
}
/*最后一个气球与倒数第二个气球编号相同的话,最后一个气球没有更新。
可以理解为多加上一个编号为-1的气球,这个气球loc=n*/
M = max(n - locLast, M);
printf("%d\n", M);
}
return 0;
}
时间复杂度 O(n) 空间复杂度 O(1)
同步发文于我的CSDN