题解:P14731 [ICPC 2022 Seoul R] Parentheses Tree
题解:P14731 [ICPC 2022 Seoul R] Parentheses Tree
题目传送门
题目意思
给你一串括号,比如
数据范围是括号串最长能有
思路
既然括号串是 DFS 遍历,那我们边读边记当前在树的第几层不就行了?设一个变量
规则:
- 读到
\texttt{(} :- 如果下一个是
\texttt{)} \to 这是叶子!把当前的d 加到答案里 - 否则:
d \gets d + 1 (我们要进入一个新节点了)
- 如果下一个是
- 读到
\texttt{)} :d \gets d - 1 (我们离开当前节点,返回父亲)
代码
#include <bits/stdc++.h>
#define Jason227 return
#define Code 0
using namespace std;
int d = 0;
long long ans = 0;
string s;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> s;
for(int i = 0; i < s.size(); i++){
if(s[i] == '('){
if(i + 1 < s.size() && s[i + 1] == ')'){
ans += d;
i++;
}
else{
d++;
}
}
else{
d--;
}
}
cout << ans << '\n';
Jason227 Code;
}
复杂度分析
- 时间复杂度:
O(n) ,只扫描一遍字符串。 - 空间复杂度:
O(1) ,除了输入的字符串,只用几个变量。
这题的关键就是发现括号串和 DFS 遍历的关系,然后边扫边记深度。遇到
AC 记录