codeforces 1328D(思维)

时间:2022-07-28
本文章向大家介绍codeforces 1328D(思维),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

The round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the i-th figure equals ti. You want to color each figure in one of the colors. You think that it’s boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.

Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly k distinct colors, then the colors of figures should be denoted with integers from 1 to k.

有n个动物组成一个环,要求给每个动物染色,要求相邻的不同种类的动物不能有相同的颜色,求最小用到的颜色数量

思路

如果只有一种动物的话,那么只需要一种颜色即可。 如果有两种动物,那么需要两种颜色。 如果有三种及以上的动物的话,就需要分类讨论:因为是环形,如果首尾动物种类不同但是颜色相同,那么首尾颜色需要改变,但是首尾颜色的改变可能会使答案序列不满足题意,所以我们可以找到种类相同的动物的位置,然后把左侧或者右侧的1全部变为2,2全部变成1,这样的话是不会影响相互关系的。如果不满足,那么只需要将尾部颜色变为3即可。

AC代码

#include<bits/stdc++.h>
#define x first
#define y second
#define PB push_back
#define mst(x,a) memset(x,a,sizeof(x))
#define all(a) begin(a),end(a)
#define rep(x,l,u) for(ll x=l;x<u;x++)
#define rrep(x,l,u) for(ll x=l;x>=u;x--)
#define sz(x) x.size()
#define ins(x) inserter(x,x.begin())
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long ll;
const int N=4*1e5+10;
const int M=1e6+10;
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;
int a[N],ans[N];
void solve(){
    int n;cin>>n;
    rep(i,0,n) cin>>a[i];
    int flag=0,p=1,res=1;
    ans[0]=1;
    rep(i,1,n){
        if(a[i]!=a[i-1]){
            res=2;
            p=3-p;
            ans[i]=p;
        }else{
            flag=i;
            ans[i]=p;
        }
    }
    if(n>=3 && a[0]!=a[n-1] && ans[0]==ans[n-1]){
        if(flag){
            rep(i,flag,n) ans[i]=3-ans[i];
        }else{
            res=3;
            ans[n-1]=3;
        }
    }
    cout<<res<<endl;
    rep(i,0,n) cout<<ans[i]<<' ';
    cout<<endl;
}
int main(){
    IOS;
    int t;cin>>t;
    while(t--){
        solve();
    }
    return 0;
}