跳到正文

题解

题解:CF962E Byteland, Berland and Disputed Cities

HD0X约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年10月16日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 4 分钟
获赞
8
题目
CF962E

版本

  1. v1当前

鲜花:2200的紫?

CF962E

题意

数轴上有三种点 PBR ,要求连边使得所有 BP 联通和所有 RP 联通, RB 间不能连边。问最小花费(边权为两点间的距离)。 n≤2e5n≤2e5

思路

首先第一个 P 前和最后一个 P 后正常连接,然后考虑如下两种排列。

PP 型(紧密连接)

这种情况下,必连多个 P 。注意不要重复计数。

P—P 型

第一反应是不考虑连两 P ,再在中间找最大的间隙,其它的依次连接至 P 点,这样另一种字符可以直接越过(中间只有一种字符)或一起使用(两种字符),可以省下空隙之和 −- 两 P 距离。注意 RB 分开讨论,如图:

手残轻喷

RT

如果 R 和 B 省下的花费多于两 P 之间的距离,才合法可用。

如图,可以省下 R1R2R_1R_2 ++ P1BP_1B −- P1P2P_1P_2 。

CODE

别忘了开 long long 。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN=2e5+10;
int n,a[MAXN],mn1=INT_MAX,mn2=INT_MAX,mx1=-INT_MAX,mx2=-INT_MAX,t[MAXN],ans,pr;
char s[MAXN];
int vis[MAXN];
inline int read()
{
	int x=0,p=1;char ch=getchar();
	while(ch<'0'||ch>'9'){
		if (ch=='-') p=-1;
		ch=getchar();}
	while('0'<=ch&&ch<='9'){
		x=x*10+ch-'0';
		ch=getchar();}
	return x*p;
}
void make(char c,bool f)
{
	int sum=0,lst=0;
	for(int i=1;i<=n;i++)
	{
		if(s[i]==c) t[++sum]=i;
		else if(s[i]=='P')
		{
			if(lst!=0 && (i!=lst+1||i==lst+1&&!vis[lst]))
			{
				int y=0;
				t[++sum]=i;
				for(int j=0;j<sum;j++) y=max(y,a[t[j+1]]-a[t[j]]);
				if(1==i-lst) pr+=y;
				if(!f) vis[lst]=y;
				if(f && vis[lst]!=0 && vis[lst]+y>a[i]-a[lst]) pr+=vis[lst]+y-a[i]+a[lst];
			}
			lst=i;
			sum=0;
			t[0]=lst;
		}
	}
}
signed main()
{
	n=read();
	int cnt=0;
	for(int i=1;i<=n;i++)
	{
		a[i]=read(),s[i]=getchar();
		if(s[i]=='P')
		{
			mn1=min(mn1,a[i]);
			mn2=min(mn2,a[i]);
			mx1=max(mx1,a[i]);
			mx2=max(mx2,a[i]);
			++cnt;
		}
		else if(s[i]=='B')
		{
			mn1=min(mn1,a[i]);
			mx1=max(mx1,a[i]);
		}
		else
		{
			mn2=min(mn2,a[i]);
			mx2=max(mx2,a[i]);
		}
	}
	if(mn1==INT_MAX) mn1=mx1;
	if(mn2==INT_MAX) mn2=mx2;
	if(cnt<=1)
	{
		cout<<mx1-mn1+mx2-mn2<<endl;
		return 0;
	}
	make('R',0),make('B',1);
	int cha=max(0ll,pr);
	ans=mx1+mx2-mn1-mn2;
	cout<<ans-cha<<endl;
}
原文
存档评论4 条抓取于