Test instructions: Given a sequence of parentheses, change the minimum parentheses so that all the parentheses match.
Analysis: Greedy, sweep from left to right, and then count the number of left and right brackets, and then in the statistics, if there are more right parenthesis, then the left parenthesis, and finally if the number of parentheses is not equal,
Just change it.
The code is as follows:
#pragma COMMENT (linker, "/stack:1024000000,1024000000") #include <cstdio> #include <string> #include < cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include < queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include < cmath> #include <stack> #define FREOPENR freopen ("In.txt", "R", stdin) #define FREOPENW freopen ("OUT.txt", "W", STDOUT) using namespace Std;typedef long Long ll;typedef pair<int, int> p;const int inf = 0x3f3f3f3f;const double inf = 0x3f3f3f3f3f3f;const LL LNF = 0x3f3f3f3f3f3f;const Double PI = ACOs ( -1.0); const double EPS = 1e-8;const int maxn = 1E3 + 100;const int mod = 1e9 + 7;const int dr[] = {-1, 0, 1, 0};const int dc[] = {0, 1, 0, -1};const char *hex[] = {"0000", " 0001 "," 0010 "," 0011 "," 0100 "," 0101 "," 0110 "," 0111 "," "," 1001 "," 1010 "," 1011 "," 1100 "," 1101 "," 1110 "," 1111 "};int N, m;const int mon[] = {0, 31, 28, 31, 30, 31, 30, [0], +, +, +, 31};const int monn[] = (= {+), H, H, H, +, +,,,,, int, int. b) {return a < b a:b;} inline int Max (int a, int b) {return a > b a:b;} inline ll Min (ll A, ll b) {return a < b a:b;} inline ll Max (ll A, ll b) {return a > b a:b;} inline bool Is_in (int r, int c) {return R >= 0 && r < n && C >= 0 && C < m;} Char S[105];int main () {int T; Cin >> T; while (t--) {scanf ("%d", &n); scanf ("%s", s); int ans = 0; int L = 0, r = 0; for (int i = 0; i < n; ++i) {if (s[i] = = ') ') {if (R = = L) {++l; ++ans; } else ++r; } else ++l; } while (L! = r) {--l; ++r; ++ans; } printf ("%d\n", ans); } return 0;}
Uvalive 7454 parentheses (water problem, greed)