AtCoder Grand Contest 026 A - Colorful Slimes 2【模拟】【并查集】【map】

P r o b l e m S t a t e m e n t

Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1 , 2 , , 10000 .
Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is ai. If two slimes of the same color are adjacent, they will start to combine themselves. Because Takahashi likes smaller slimes, he has decided to change the colors of some of the slimes with his magic.
Takahashi can change the color of one slime to any of the 10000 colors by one spell. How many spells are required so that no slimes will start to combine themselves?

Constraints

2 N 100
1 a i N
All values in input are integers.

Input

Input is given from Standard Input in the following format
N
a 1   a 2 a N

Output

Print the minimum number of spells required.


一直以为 A G C 都是非常难的题一直没有敢做…原来 A G C 也有很水的题…

我们统计每个区间(区间长度可以为1且区间内的所有颜色相同且与相邻的其他区间颜色互不相同)的长度,假设这样的区间一共有 m 个,其中第 i 个区间长度为 L e n g t h i ,那么最后的答案显然就为:

A n s = i = 1 m L e n g t h i 1 2

至于如何统计每个区间的长度就有很多方法,我用的就是并查集与 m a p ,但是这样显然就比较麻烦了。

参考代码:

#include <map>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define SG string
#define DB double
#define Sec second
using namespace std;
const int Max=1e2+5;
map<int,int>Map;
map<int,int>::iterator It;
int N,Ans,F[Max],Col[Max];
inline int Read(){
    int X=0;char CH=getchar();bool F=0;
    while(CH>'9'||CH<'0'){if(CH=='-')F=1;CH=getchar();}
    while(CH>='0'&&CH<='9'){X=(X<<1)+(X<<3)+CH-'0';CH=getchar();}
    return F?-X:X;
}
inline void Write(int X){
    if(X<0)X=-X,putchar('-');
    if(X>9)Write(X/10);
    putchar(X%10+48);
}
int Find(int X){
    return F[X]==X?X:F[X]=Find(F[X]);
}
int main(){
    int I,J,K;
    N=Read();
    for(I=1;I<=N;I++){
        F[I]=I;
        Col[I]=Read();
    }
    for(I=2;I<=N;I++){
        if(Col[I]==Col[I-1]){
            int Fx=Find(I-1),Fy=Find(I);
            F[Fy]=F[Fx];
        }
    }
    for(I=1;I<=N;I++){
        int Fx=Find(I);
        Map[Fx]++;
    }
    for(It=Map.begin();It!=Map.end();It++){
        Ans+=(It->Sec>>1);
    }
    Write(Ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yanzhenhuai/article/details/81076847