RT.
调了一天了。
做法与第一篇题解基本一致(我就是看的这篇题解)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e3 + 5;
struct Tree
{
int ls, rs;
} givtree[maxn], mertree[maxn];
char givenstr[maxn];
int node_cnt = 0;
int id = 0;
int build()
{
id++;
int nowid=id;
int now = ++node_cnt;
if (givenstr[nowid] == '1' || givenstr[nowid] == '3')
{
givtree[now].ls = build();
}
if (givenstr[nowid] == '2' || givenstr[nowid] == '3')
{
givtree[now].rs = build();
}
return now;
}
char order[maxn];
int ordertop;
int find_node(int now)
{
for (int i = 1; i <= ordertop; i++)
{
if (order[i] == 'L')
{
now = givtree[now].ls;
}
else
{
now = givtree[now].rs;
}
}
return now;
}
int nodecnt2 = 1;
void merge(int givnow, int mernow, int exce)
{
if(givnow==exce)return;
if (givtree[givnow].ls)
{
if (!mertree[mernow].ls)
{
mertree[mernow].ls = ++nodecnt2;
}
// printf("into 1\n");
// printf("ls: %d\n",mertree[mernow].ls);
merge(givtree[givnow].ls, mertree[mernow].ls, exce);
}
if (givtree[givnow].rs)
{
if (!mertree[mernow].rs)
{
mertree[mernow].rs = ++nodecnt2;
}
// printf("into 2\n");
merge(givtree[givnow].rs, mertree[mernow].rs, exce);
}
}
int calc()
{
int now = 1, last = 0;
while (now)
{
// printf("calc now: %d\n", now);
last = now;
now = find_node(now);
if(!now)break;
merge(last, 1, now);
}
return nodecnt2;
}
int ans = 1e9;
void find_ans(int now, int dep)
{
if (!now)
return;
if (now != 1)
{
nodecnt2 = 1;
memset(mertree, 0, sizeof mertree);
ans = min(ans, 2 * (calc()-1) - dep);
}
order[++ordertop] = 'L';
find_ans(givtree[now].ls, dep + 1);
order[ordertop] = 'R';
find_ans(givtree[now].rs, dep + 1);
ordertop--;
}
int main()
{
scanf("%s", givenstr + 1);
int n = strlen(givenstr + 1);
build();
find_ans(1, 0);
printf("%d", ans);
return 0;
}