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;
}
相关推荐
辰烨chenye2 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考2 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
鱼子星_2 小时前
【C++】继承和多态(上)
c++·笔记
玖玥拾3 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研4 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
郝学胜-神的一滴4 小时前
Qt 高级编程 045:坐标体系深度实战
开发语言·c++·windows·python·qt·程序人生
码匠许师傅4 小时前
【设计模式精讲】22.中介者模式(Mediator)
c++·设计模式·软件工程·uml·中介者模式
a187927218315 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_962297485 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作