1. 程式人生 > >Codeforces 1090M - The Pleasant Walk - [簽到水題][2018-2019 Russia Open High School Programming Contest Problem M]

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;
}