#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
long long ans;
int n;
int op, clos;
string path;
vector< vector<int> > nei;
string a;
void Chain(const string& a)
{
vector< pair<pair<int, int>, int> > pref(a.length());
for (int i = 0; i < pref.size(); ++i)
{
pref[i].first.second = i;
if (a[i] == '(') ++pref[i].first.first;
else --pref[i].first.first;
if (i) pref[i].first.first += pref[i - 1].first.first;
if (i)
pref[i].second = pref[i - 1].second;
}
vector<int> r(n, -1);
for (int i = 0; i < n; ++i)
{
int minElem = pref[i].first.first;
for (int j = i; j < n; ++j)
{
minElem = min(minElem, pref[j].first.first);
if (minElem - (i ? pref[i - 1].first.first : 0) < 0)
break;
else
r[i] = j;
}
}
sort(pref.begin(), pref.end());
for (int i = 0; i < n; ++i)
if (r[pref[i].first.second] != -1)
for (int j = i; j < n && pref[j].first.first == pref[i].second; ++j)
{
if (pref[j].first.second <= r[pref[i].first.second])
++ans;
else
break;
}
}
void Dfs(int v, int par)
{
if (op == clos && a[v] == ')')
return;
if (a[v] == ')') ++clos;
else ++op;
path += a[v];
if (clos == op)
++ans;
for (int i = 0; i < nei[v].size(); ++i)
{
int to = nei[v][i];
if (to == par) continue;
Dfs(to, v);
}
path.pop_back();
if (a[v] == ')') --clos;
else --op;
}
int main()
{
cin >> n;
nei.resize(n);
cin >> a;
for (int i = 1; i < n; ++i)
{
int u, v;
cin >> u >> v; --u; --v;
nei[u].push_back(v);
nei[v].push_back(u);
}
if (false/*n <= 1000*/)
{
for (int v = 0; v < n; ++v)
{
op = clos = 0;
path = "";
Dfs(v, -1);
}
cout << ans << endl;
return 0;
}
else // Is a chain.
{
Chain(a);
reverse(a.begin(), a.end());
Chain(a);
cout << ans << endl;
char I;
cin >> I;
}
char I;
cin >> I;
}
Compilation message
zagrade.cpp: In function 'void Chain(const string&)':
zagrade.cpp:17:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int i = 0; i < pref.size(); ++i)
~~^~~~~~~~~~~~~
zagrade.cpp: In function 'void Dfs(int, int)':
zagrade.cpp:59:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int i = 0; i < nei[v].size(); ++i)
~~^~~~~~~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
376 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
819 ms |
21928 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
376 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |