Submission #636597

# Submission time Handle Problem Language Result Execution time Memory
636597 2022-08-29T16:34:48 Z marlicu Zagrade (COI17_zagrade) C++14
0 / 100
3000 ms 942528 KB
#include <bits/stdc++.h>

using namespace std;

#define X first
#define Y second

typedef long long ll;
typedef pair <int, int> pii;

const int MAXN = 3e5 + 5;

int n;
char parentesi[MAXN];
vector <int> connessioni[MAXN];
map <int, int> piu[MAXN];
map <int, int> meno[MAXN];
int subalbero[MAXN];
int shift[MAXN];
int gruppo[MAXN];
ll risposta;

void collegare(int a, int b, int delta) {
  int& ga = gruppo[a]; 
  int& gb = gruppo[b];

  int nodo = b;

  if (subalbero[ga] < subalbero[gb]) {
    swap(a, b);
    swap(ga, gb);
  }

  int shiftR = shift[gb] - shift[ga];

  for (auto nx : piu[gb]) risposta += meno[ga][-nx.X - shiftR];
  for (auto nx : meno[gb]) risposta += piu[ga][-nx.X - shiftR];

  shift[gruppo[nodo]] += delta;
  shiftR = shift[gb] - shift[ga];

  for (auto nx : piu[gb]) piu[ga][nx.X + shiftR] += nx.Y;
  for (auto nx : meno[gb]) meno[ga][nx.X + shiftR] += nx.Y;

  piu[ga][-1 - shift[ga]] = 0;
  meno[ga][1 - shift[ga]] = 0;

  gb = ga;
}

int dfs(int nodo, int pnodo) {
  int& gn = gruppo[nodo];

  subalbero[nodo] = 1;

  if (parentesi[nodo] == '(') piu[gn][1]++;
  else meno[gn][-1]++;

  for (auto nnodo : connessioni[nodo]) {
    if (nnodo == pnodo) continue;
    //cerr << "qui "<< nodo << ' ' << nnodo <<"\n";

    subalbero[nodo] += dfs(nnodo, nodo);
    collegare(nodo, nnodo, (parentesi[nodo] == '(' ? 1 : -1));
  }
  
  return subalbero[nodo];
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> parentesi[i];
    gruppo[i] = i;
  }

  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    u--, v--;

    connessioni[u].push_back(v);
    connessioni[v].push_back(u);
  }

  dfs(0, -1);

  cout << risposta << '\n';

  return 0;
}

# Verdict Execution time Memory Grader output
1 Incorrect 17 ms 35796 KB Output isn't correct
2 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Execution timed out 3094 ms 942528 KB Time limit exceeded
2 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Incorrect 17 ms 35796 KB Output isn't correct
2 Halted 0 ms 0 KB -