Move Brackets(贪心+思维)
题目描述:
You are given a bracket sequence
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
Your task is to find the minimum number of moves required to obtain regular bracket sequence from
Recall what the regular bracket sequence is:
"( )" is regular bracket sequence;
if
if
For example, "( ) ( )", "( ( ) ) ( )", "( ( ) )" and "( )" are regular bracket sequences, but ") (", "( ) (" and ") ) )" are not.
You have to answer
输出描述:
The first line of the input contains one integer
The first line of the test case contains one integer
输出描述:
For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from
题解:
#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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话