P5597 【XR-4】复读

[题目通道](【XR-4】复读 - 洛谷)

cpp 复制代码
#include<bits/stdc++.h>
#define inf 2147483647
using namespace std;

struct ed{
	int ls,rs,f,sz,dd;
}p[3000],c[3000];
string s;
int st,lq,ans=inf/2;

int build(int fa,int poi){
	p[poi].f=fa; p[poi].sz=1; p[poi].dd=p[fa].dd+1; 
	if (s[poi]=='3') {
		p[poi].ls=build(poi,poi+1), p[poi].sz+=p[p[poi].ls].sz;
		p[poi].rs=build(poi,poi+p[poi].sz), p[poi].sz+=p[p[poi].rs].sz;}
	if (s[poi]=='2') 
		p[poi].rs=build(poi,poi+1), p[poi].sz+=p[p[poi].rs].sz;
	if (s[poi]=='1')
		p[poi].ls=build(poi,poi+1), p[poi].sz+=p[p[poi].ls].sz;
	return poi;
}

int gd(int now,string t)
{	int l=t.size();
	for (int i=0;i<l;i++) now=((t[i]=='L')?p[now].ls:p[now].rs);
	return now;
}

int merge(int now,int cs,int sp){	
	if (!now) return cs;
	if (!cs) cs=++st; c[cs].sz=1;
	if (now==sp) return cs;
	c[cs].ls=merge(p[now].ls,c[cs].ls,sp); c[cs].sz+=c[c[cs].ls].sz;
	c[cs].rs=merge(p[now].rs,c[cs].rs,sp); c[cs].sz+=c[c[cs].rs].sz;
	return cs;
}

int find(string rep)
{
	int now=1,last=0;
	while (now){ 
		last=now , now=gd(now,rep); 
		merge(last,1,now);
	}
	return c[1].sz;
}

void search(int now,string rep){  
	int cnt=0;
	if (now==0) return;
	if (now!=1) {
		memset(c,0,sizeof(c)); st=1; cnt=find(rep);
		ans=min(ans,2*(cnt-1)-p[now].dd+1);
	}
	
	search(p[now].ls,rep+'L');
	search(p[now].rs,rep+'R');
}

int main()
{
	cin>>s; lq=s.size(); s='.'+s; 
	build(0,1);
	search(1,"");
	cout<<ans<<endl;
}
相关推荐
MengYiKeNan18 分钟前
C++二分函数lower_bound和upper_bound的用法
开发语言·c++·算法
戊子仲秋37 分钟前
【LeetCode】每日一题 2024_9_19 最长的字母序连续子字符串的长度(字符串,双指针)
算法·leetcode·职场和发展
小林熬夜学编程1 小时前
C++第五十一弹---IO流实战:高效文件读写与格式化输出
c语言·开发语言·c++·算法
月夕花晨3741 小时前
C++学习笔记(30)
c++·笔记·学习
蠢蠢的打码1 小时前
8584 循环队列的基本操作
数据结构·c++·算法·链表·图论
不是编程家1 小时前
C++ 第三讲:内存管理
java·开发语言·c++
jianglq1 小时前
C++高性能线性代数库Armadillo入门
c++·线性代数
无问8173 小时前
数据结构-排序(冒泡,选择,插入,希尔,快排,归并,堆排)
java·数据结构·排序算法
Lenyiin3 小时前
《 C++ 修炼全景指南:十 》自平衡的艺术:深入了解 AVL 树的核心原理与实现
数据结构·c++·stl
程序猿进阶3 小时前
如何在 Visual Studio Code 中反编译具有正确行号的 Java 类?
java·ide·vscode·算法·面试·职场和发展·架构