Codeforces 1090M - The Pleasant Walk - [签到水题][2018-2019 Russia Open High School Programming Contest Problem M]

题目链接:https://codeforces.com/contest/1090/problem/M

There are n houses along the road where Anya lives, each one is painted in one of k possible colors.

Anya likes walking along this road, but she doesn't like when two adjacent houses at the road have the same color. She wants to select a long segment of the road such that no two adjacent houses have the same color.

Help Anya find the longest segment with this property.

Input
The first line contains two integers n and k — the number of houses and the number of colors (1≤n≤100000, 1≤k≤100000).

The next line contains n integers a1,a2,…,an — the colors of the houses along the road (1≤ai≤k).

Output
Output a single integer — the maximum number of houses on the road segment having no two adjacent houses of the same color.

Example
input
8 3
1 2 3 3 2 1 2 2
output
4
Note
In the example, the longest segment without neighboring houses of the same color is from the house 4 to the house 7. The colors of the houses are [3,2,1,2] and its length is 4 houses.

题意:

路边有 $n$ 座房子,每座房子有可能涂上 $k$ 种颜色中的一种。Anya不喜欢相邻两座房子有相同颜色,因此要选择路上最长的一段,使得这一段上所有相邻的房子都满足颜色不同。

题解:

$O(n)$ 维护当前段长度和最长长度即可。

AC代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int n,k,a[maxn];
int main()
{
    cin>>n>>k;
    int res=0;
    for(int i=1,len;i<=n;i++)
    {
        scanf("%d",&a[i]);
        if(i==1 || a[i]==a[i-1]) len=1;
        else len++;
        res=max(len,res);
    }
    cout<<res<<endl;
}

猜你喜欢

转载自www.cnblogs.com/dilthey/p/10094378.html