arc059 F - Unhappy Hacking

博客讨论了一种动态规划方法,用于计算在限定操作步数下,构建特定长度且有未匹配左括号的括号序列的方案数。通过构建长度为n的括号序,找到最终没能匹配的左括号为m个的方案数,再乘以2的(m次方)幂次,得到最终答案。代码中展示了具体的dp解决方案,并在主函数中进行了测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

F - Unhappy Hacking

显然跟串具体是什么无关,仅跟操作数n、串长m有关

然后考虑定下结尾m个元素,现在问题发现此时要达到n个操作步数,就相当于在这m个元素空隙间(包括第一个元素前、最后一个元素后)插入n - m括号的方案数(左括号为插入0/1,右括号为退格操作,其中可以有无效右括号,但每个左括号必须匹配),然后再乘上2^(左括号数)。

进一步我们能够发现,整体来考虑,方案数就相当于构建一个长为n的括号序(可以有一些无效的右括号,表示空的时候退格),最终没能匹配的左括号有m个的方案数乘上 2 ^ (t - m), 其中t为放下的实际左括号个数,可以用一个n^2的简单dp解决。

#include<bits/stdc++.h>
#define pii pair<int,int>
#define fi first
#define sc second
#define pb push_back
#define ll long long
#define trav(v,x) for(auto v:x)
#define all(x) (x).begin(), (x).end()
#define VI vector<int>
#define VLL vector<ll>
#define pll pair<ll, ll>
#define double long double
//#define int long long
using namespace std;
const int N = 1e6 + 100;
const int inf = 1e9;
//const ll inf = 1e18;
const ll mod = 1e9 + 7;

#ifdef LOCAL
void debug_out(){cerr << endl;}
template<typename Head, typename... Tail>
void debug_out(Head H, Tail... T)
{
	cerr << " " << to_string(H);
	debug_out(T...);
}
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

ll qpow(ll x, ll y = mod - 2)
{
	ll res = 1;
	while(y)
	{
		if(y & 1)
			res = res * x % mod;
		x = x * x % mod;
		y >>= 1;
	}
	return res;
}

void sol()
{
	int n, m;
	cin >> n;
	string s;
	cin >> s;
	m = s.length();
	vector<VLL> f(n + 1, VLL(n + 1, 0));
	f[0][0] = 1;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 0; j <= i - 1; j++)
		{
			f[i][j + 1] = (f[i][j + 1] + f[i - 1][j] * 2) % mod;
			if(j > 0)
				f[i][j - 1] = (f[i][j - 1] + f[i - 1][j]) % mod;
			else
				f[i][j] = (f[i][j] + f[i - 1][j]) % mod;
		}
	}
	ll tmp = qpow(2, m);
	tmp = qpow(tmp);
	ll ans = f[n][m] * tmp % mod;
	cout << ans << '\n';
}

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
//	int tt;
//	cin >> tt;
//	while(tt--)
		sol();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值