Codeforces Round #698 (Div. 2)-A. Nezzar and Colorful Balls
传送门
Time Limit: 1 second
Memory Limit: 512 megabytes
Problem Description
Nezzar has n n n balls, numbered with integers 1 , 2 , … , n 1, 2, \ldots, n 1,2,…,n. Numbers a 1 , a 2 , … , a n a_1, a_2, \ldots, a_n a1,a2,…,an are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that a i ≤ a i + 1 a_i \leq a_{i+1} ai≤ai+1 for all 1 ≤ i < n 1 \leq i < n 1≤i<n.
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 1 1 1 is considered as a strictly increasing sequence.
Please help Nezzar determine the minimum number of colors.
Input
The first line contains a single integer t t t ( 1 ≤ t ≤ 100 1 \le t \le 100 1≤t≤100) — the number of testcases.
The first line of each test case contains a single integer n n n ( 1 ≤ n ≤ 100 1 \le n \le 100 1≤n≤100).
The second line of each test case contains n n n integers a 1 , a 2 , … , a n a_1,a_2,\ldots,a_n a1,a2,…,an ( 1 ≤ a i ≤ n 1 \le a_i \le n 1≤ai≤n). It is guaranteed that a 1 ≤ a 2 ≤ … ≤ a n a_1 \leq a_2 \leq \ldots \leq a_n a1≤a2≤…≤an.
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 [ 1 , 2 , 3 , 3 , 2 , 1 ] [1,2,3,3,2,1] [1,2,3,3,2,1].
In the second test case, one optimal color assignment is [ 1 , 2 , 1 , 2 , 1 ] [1,2,1,2,1] [1,2,1,2,1].
题目大意
给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)