KSzsh

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Move Brackets(贪心+思维)

题目链接

题目描述:

You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n2 opening brackets '(' and n2 closing brackets ')'.

In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remove the i-th character of s and insert it before or after all remaining characters of s).

Your task is to find the minimum number of moves required to obtain regular bracket sequence from s. It can be proved that the answer always exists under the given constraints.

Recall what the regular bracket sequence is:

"( )" is regular bracket sequence;
if s is regular bracket sequence then "(" + s + ")" is regular bracket sequence;
if s and t are regular bracket sequences then s+t is regular bracket sequence.
For example, "( ) ( )", "( ( ) ) ( )", "( ( ) )" and "( )" are regular bracket sequences, but ") (", "( ) (" and ") ) )" are not.

You have to answer t independent test cases.

输出描述:

The first line of the input contains one integer t (1t2000) — the number of test cases. Then t test cases follow.

The first line of the test case contains one integer n (2n50) — the length of s. It is guaranteed that n is even. The second line of the test case containg the string s consisting of n2 opening and n2 closing brackets.

输出描述:

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from s. It can be proved that the answer always exists under the given constraints.

题解:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10;
int T = 1;
int n, m, x;
int a[N];
int b[N];
void solve()
{
cin >> n;
string s;
cin >> s;
int ans = 0, num = 0;
for (int i = 0; i < n; i++) // 贪心的想,若想要移动次数最少,则需要把已经是符合条件的找出来,则剩下的不符合条件的就需要移动
{
if (s[i] == '(') // 从前往后找出 (
num++;
else
{
num--; // 若为 ) 则将 ( 的数量减一
if (num < 0) // 若减一之后的 ( 的数量大于等于0,则代表有 ( 和 ) 匹配,否则则没有
{
ans++; // num 小于0则代表这个 ) 要移动
num = 0; // 随后要置为零,以防影响之后的判断
}
}
}
cout << ans << '\n';
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
// scanf("%d", &T);
cin >> T;
while (T--)
{
solve();
}
return 0;
}

posted on   KSzh  阅读(48)  评论(2编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示