题
OvO http://codeforces.com/contest/908/problem/F
CF 908F
解
需要注意细节的模拟题。
如果三种颜色都存在,则记每两个相邻的G组成一个段,对每个段进行讨论。
如果三种颜色中缺了某种或某些颜色,则特殊地进行讨论。
如果是像 BRB 这组数据 如果把第一个B和第三个B连起来,那么中间的R也和这两个B相连了
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int M=3e5+44;
const int INF=1e9+44;
struct Node
{
int plc,tp;
} node[M];
int n;
void solve()
{
ll ans=0;
int big1,big2,sum1,sum2,lst0,lst1,lst2,tmp;
lst0=lst1=lst2=-1;
sum1=sum2=0; big1=big2=-1;
for(int i=1;i<=n;i++)
{
if(node[i].tp==0)
{
if(lst1!=-1)
sum1+=node[i].plc-lst1,big1=max(big1,node[i].plc-lst1);
if(lst2!=-1)
sum2+=node[i].plc-lst2,big2=max(big2,node[i].plc-lst2);
if(lst0==-1) ans+=sum1,ans+=sum2;
else
{
ans+=sum1,ans+=sum2,ans+=node[i].plc-lst0;
if(big1==-1) big1=0;
if(big2==-1) big2=0;
tmp=big1+big2;
if(big1!=0 && big2!=0)
tmp=max(tmp,node[i].plc-lst0);
// cout<<ans<<' '<<tmp<<' '<<big1<<' '<<big2<<' '<<sum1<<' '<<sum2<<endl;
ans-=tmp;
}
lst1=lst2=-1;
sum1=sum2=0; big1=big2=-1;
lst0=node[i].plc;
}
else if(node[i].tp==1)
{
if(lst1==-1)
{
if(lst0==-1)
sum1+=0;
else
sum1+=node[i].plc-lst0,big1=max(big1,node[i].plc-lst0);
}
else
sum1+=node[i].plc-lst1,big1=max(big1,node[i].plc-lst1);
lst1=node[i].plc;
}
else
{
if(lst2==-1)
{
if(lst0==-1)
sum2+=0;
else
sum2+=node[i].plc-lst0,big2=max(big2,node[i].plc-lst0);
}
else
sum2+=node[i].plc-lst2,big2=max(big2,node[i].plc-lst2);
lst2=node[i].plc;
}
}
ans+=sum1,ans+=sum2;
printf("%I64d",ans);
}
int main()
{
int cnt[3],lst[3],cst[3];
char chr[3];
scanf("%d",&n);
memset(cst,0,sizeof(cst));
memset(lst,-1,sizeof(lst));
memset(cnt,0,sizeof(cnt));
for(int i=1;i<=n;i++)
{
scanf("%d%s",&node[i].plc,chr);
if(chr[0]=='G')
{
node[i].tp=0;
cnt[0]++;
if(lst[0]!=-1) cst[0]+=node[i].plc-lst[0];
lst[0]=node[i].plc;
}
else if(chr[0]=='B')
{
node[i].tp=1;
cnt[1]++;
if(lst[1]!=-1) cst[1]+=node[i].plc-lst[1];
lst[1]=node[i].plc;
}
else
{
node[i].tp=2;
cnt[2]++;
if(lst[2]!=-1) cst[2]+=node[i].plc-lst[2];
lst[2]=node[i].plc;
}
}
if(cnt[0]!=0 && cnt[1]==0 && cnt[2]==0)
{
printf("%d",cst[0]);
return 0;
}
if(cnt[0]==0)
{
if(cnt[1]==0 || cnt[2]==0)
{
printf("%d",cst[1]+cst[2]);
return 0;
}
int mn=INF,flag12,flag21;
ll ans=0;
flag12=flag21=0;
for(int i=1;i<n;i++)
{
if(node[i].tp!=node[i+1].tp && (node[i+1].plc-node[i].plc<mn))
mn=node[i+1].plc-node[i].plc;
if(node[i].tp==1 && node[i+1].tp==2)
flag12=1;
if(node[i].tp==2 && node[i+1].tp==1)
flag21=1;
}
if(flag12 && flag21)
mn=0;
ans=0ll+cst[1]+cst[2]+mn;
printf("%I64d",ans);
return 0;
}
solve();
return 0;
}
/*
6
1 R
5 B
9 R
10 B
14 R
15 B
*/