QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#345250#3420. Jingle BallsPetroTarnavskyi#AC ✓33ms20192kbC++201.6kb2024-03-06 17:53:352024-03-06 17:53:35

Judging History

你现在查看的是最新测评结果

  • [2024-03-06 17:53:35]
  • 评测
  • 测评结果:AC
  • 用时:33ms
  • 内存:20192kb
  • [2024-03-06 17:53:35]
  • 提交

answer

#include <bits/stdc++.h> 

using namespace std;

#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define RFOR(i, a, b) for(int i = (a) - 1; i >= (b); i--)
#define SZ(a) int(a.size())
#define ALL(a) a.begin(), a.end()
#define PB push_back
#define MP make_pair
#define F first
#define S second

typedef long long LL;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef double db;

const int N = 1 << 11;

template<typename T>
void updMin(T& a, T b)
{
	a = min(a, b);
}

string s;
VI g[N];
int ball[N];
int dp[N][N];
int totBalls;
int sz[N];

void dfs(int v)
{
	if (g[v].empty())
	{
		sz[v] = 1;
		FOR(i, 0, 2)
		{
			dp[v][i] = max(0, i - ball[v]);
		}
		return;
	}
	assert(SZ(g[v]) == 2);
	int u1 = g[v][0], u2 = g[v][1];
	dfs(u1);
	dfs(u2);
	sz[v] = sz[u1] + sz[u2];
	FOR(k, 0, sz[v] + 1)
	{
		FOR(k1, k / 2, (k + 1) / 2 + 1)
		{
			int k2 = k - k1;
			updMin(dp[v][k], dp[u1][k1] + dp[u2][k2]);
		}
	}
}

void solve()
{
	int n = min(N, SZ(s));
	FOR(i, 0, n)
	{
		g[i].clear();
		ball[i] = 0;
		sz[i] = 0;
	}
	totBalls = 0;
	stack<int> st;
	int v = 0;
	for (char c : s)
	{
		if (c == '(')
		{
			if (!st.empty())
				g[st.top()].PB(v);
			st.push(v);
			v++;
		}
		else if (c == ')')
		{
			st.pop();
		}
		else
		{
			assert(c == 'B');
			ball[st.top()] = 1;
			totBalls++;
		}
	}
	FOR(i, 0, n)
		FOR(j, 0, n)
			dp[i][j] = N;
	dfs(0);
	if (dp[0][totBalls] == N)
		cout << "impossible\n";
	else
		cout << dp[0][totBalls] << "\n";
}

int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	while (cin >> s)
		solve();
	return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 1ms
memory: 3904kb

input:

((B)())
((((B)(B))((B)()))(B))
(()(((B)(B))(B)))

output:

0
impossible
1

result:

ok 3 lines

Test #2:

score: 0
Accepted
time: 33ms
memory: 20192kb

input:

(()())
(()(B))
((B)(B))
(((B)(B))(B))
(()((B)(B)))
((()((B)(B)))(B))
((()())((B)(B)))
(((B)((B)(B)))(B))
(()(((B)((B)(B)))()))
(((B)(B))(()((B)(B))))
((B)(((B)((B)()))(B)))
((((((B)(B))(()(((B)(B))())))(((B)((B)(B)))((()())(()()))))((((()(B))((B)()))(((((B)(B))((B)(()(B))))())(B)))((((B)())())((B)(B...

output:

0
0
0
0
1
1
1
impossible
2
1
impossible
6
56
2
1
impossible
2
2
2
0
1
1
impossible
0
2
impossible
2
1
impossible
25
18
11
0
8
1
impossible
6
7
impossible
2
1
impossible
250
231
222
0
8
1
impossible
15
20
impossible
2
1
impossible
6
3
2
0
8
1
impossible
2
1
impossible
2
1
impossible
62
53
54
0
8
1
im...

result:

ok 78 lines