CF1450F The Struggling Contestant
Description
To help those contestants who struggle a lot in contests, the headquarters of Codeforces are planning to introduce Division 5. In this new division, the tags of all problems will be announced prior to the round to help the contestants.
The contest consists of $ n $ problems, where the tag of the $ i $ -th problem is denoted by an integer $ a_i $ .
You want to AK (solve all problems). To do that, you must solve the problems in some order. To make the contest funnier, you created extra limitations on yourself. You do not want to solve two problems consecutively with the same tag since it is boring. Also, you are afraid of big jumps in difficulties while solving them, so you want to minimize the number of times that you solve two problems consecutively that are not adjacent in the contest order.
Formally, your solve order can be described by a permutation $ p $ of length $ n $ . The cost of a permutation is defined as the number of indices $ i $ ( $ 1\leq i< n$ ) where $ |p_{i+1}-p_i|>1 $ . You have the requirement that $ a_{p_i}\ne a_{p_{i+1}} $ for all $ 1\leq i< n$ .
You want to know the minimum possible cost of permutation that satisfies the requirement. If no permutations meet this requirement, you should report about it.
Solution
a数组中相邻的相同数字是不合法的,需要改变它们两个数的相对位置
若一共有$k$对相邻的相同数,那么将数组分成$k+1$段,只关注每个段的左右端点的排列是否合法
记$f(x)$为数$x$作为端点的次数,一个区间左右端点相同时仍计数两次
存在可行解的条件为$max\{f(x)\} \leq k+2$
证明不想打,搬运官方题解https://codeforces.com/blog/entry/85348
最终答案为$k+max\{ 0,max\{ f(x)\}-k-2\}$
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> using namespace std; int T,n,a[100005],f[100005],k,vst[100005],max1,max2; inline int read() { int f=1,w=0; char ch=0; while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();} while(ch>='0'&&ch<='9') w=(w<<1)+(w<<3)+ch-'0',ch=getchar(); return f*w; } int main() { T=read(); for(;T;T--) { memset(f,0,sizeof(f)),memset(vst,0,sizeof(vst)); n=read(),k=max1=max2=0; for(int i=1;i<=n;i++) { a[i]=read(); vst[a[i]]++; if(i!=1&&a[i]==a[i-1]) { ++k; f[a[i]]+=2; } } f[a[1]]++,f[a[n]]++; for(int i=1;i<=n;i++) max1=max(max1,vst[i]),max2=max(max2,f[i]); if(max1*2>n+1) puts("-1"); else printf("%d\n",k+max(0,max2-k-2)); } return 0; }