跳到正文

算法·理论

信友队21027最优解0ms

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前
C++
#include<bits/stdc++.h>
#define np nullptr
#define int int32_t
#define INF 2147483647
#define constOP "impossible\n"s
using namespace std;
struct Tree{
	bool y=false, light=false; // 叶子, 有灯
	int s=0;Tree *l=np, *r=np;
	vector<int> dp; // $dp_k$ 表示该子树有 k 个灯谜时的最小移动代价
};inline Tree *cutInput(const string &s, int &i){
	if(s[i++] != '(') return np;
	Tree *tree = new Tree;
	switch(s[i]){
		case ')': // 没灯的叶子
			i++,tree->y = true,tree->s = 1;break;
		case 'B': // 有灯的叶子
			i++;if(s[i++] != ')') return np;
			tree->y = tree->light = true, tree->s=1;break;
		default: // 不是叶子
			tree->l = cutInput(s, i),tree->r = cutInput(s, i);
			if(s[i++] != ')') return np;
			tree->s = tree->l->s + tree->r->s;break;
	}
	return tree;
}
inline int cntLight(Tree* node){
	return ((!node)?(0):((node->y)?(node->light?1:0):(cntLight(node->l)+cntLight(node->r))));
	/*
		空节点
			0
		else
			叶子节点
				有灯迷
					1
				else
					0
			else
				左右子树灯谜和
	*/
}inline void orz(Tree* node){
	if(!node) return;
	if(node->y){ // 叶子, cntLight \in {0, 1}
		node->dp = {(node->light)?1:0,(node->light)?0:1};
	}else{
		orz(node->l);orz(node->r); // 递归子树
		int faster = node->s; // 子树总叶 && 最多灯谜
		node->dp.resize(faster+1, INF); // 给 DP 开胃
		for(int i=0;i<faster+1;i++)
			// 左子树灯谜只能 \in {i/2, (i+1)/2}
			// 保证 abs(j - (i-j)) \le 1
			for(int j:{i/2, (i+1)/2}){
				int faster2 = i - j; // 右子树 cntLight
				if(j>=0 && j<=node->l->s && faster2>=0 && faster2<=node->r->s)
					if(node->l->dp[j]!=INF && node->r->dp[faster2]!=INF)
						node->dp[i] = min(node->dp[i], node->l->dp[j] + node->r->dp[faster2]);
			}}return;
}signed main(){
	ios_base::sync_with_stdio(false);
	cin.tie(np);cout.tie(np);
	string s;cin>>s;
	int idx = 0, rp = 0;
	Tree *god = cutInput(s, idx);
	if(!god){cout<<constOP;return 0;}
	int sumLight = cntLight(god);
	orz(god);
	if(god->dp[sumLight] == INT_MAX) cout<<constOP;
	// DP 中代价是移走+移来, 所以除以 2 才是 ans
	else cout<<god->dp[sumLight]/2<<"\n";
	return rp++;
}
原文