Submission #109766

#TimeUsernameProblemLanguageResultExecution timeMemory
109766luciocfMergers (JOI19_mergers)C++14
56 / 100
3043 ms25336 KiB
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5+10; const int maxl = 20; int n, k; int pai[maxn], peso[maxn]; int s[maxn]; int nivel[maxn]; int tab[maxn][maxl]; int grau[maxn]; bool mark[maxn]; vector<int> grafo[maxn], state[maxn]; void init(void) { for (int i = 1; i <= n; i++) pai[i] = i, peso[i] = 1; } int Find(int x) { if (pai[x] == x) return x; return pai[x] = Find(pai[x]); } void Join(int x, int y) { x = Find(x), y = Find(y); if (x == y) return; if (peso[x] < peso[y]) swap(x, y); pai[y] = x, peso[x] += peso[y]; } void dfs(int u, int p) { for (auto v: grafo[u]) { if (v == p) continue; nivel[v] = nivel[u]+1, tab[v][0] = u; dfs(v, u); } } void build(void) { for (int j = 1; j < maxl; j++) for (int i = 1; i <= n; i++) tab[i][j] = tab[tab[i][j-1]][j-1]; } int lca(int u, int v) { if (nivel[u] < nivel[v]) swap(u, v); for (int i = maxl-1; i >= 0; i--) if (nivel[u]-(1<<i) >= nivel[v]) u = tab[u][i]; if (u == v) return u; for (int i = maxl-1; i >= 0; i--) if (tab[u][i] && tab[v][i] && tab[u][i] != tab[v][i]) u = tab[u][i], v = tab[v][i]; return tab[u][0]; } int main(void) { scanf("%d %d", &n, &k); for (int i = 1; i < n; i++) { int u, v; scanf("%d %d", &u, &v); grafo[u].push_back(v); grafo[v].push_back(u); } for (int i = 1; i <= n; i++) { scanf("%d", &s[i]); state[s[i]].push_back(i); } init(); nivel[1] = 1; dfs(1, 0); build(); for (int i = 1; i <= n; i++) { if (mark[s[i]]) continue; mark[s[i]] = 1; for (auto j: state[s[i]]) { int v = j; int l = lca(i, v); while (nivel[v] >= nivel[l]) { Join(i, v); v = tab[v][0]; } v = i; while (nivel[v] >= nivel[l]) { Join(i, v); v = tab[v][0]; } } } for (int i = 1; i <= n; i++) for (auto v: grafo[i]) if (Find(v) != Find(i)) grau[Find(v)]++; int leaf = 0; for (int i = 1; i <= n; i++) if (grau[i] == 1) leaf++; printf("%d\n", (leaf+1)/2); }

Compilation message (stderr)

mergers.cpp: In function 'int main()':
mergers.cpp:82:7: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
  scanf("%d %d", &n, &k);
  ~~~~~^~~~~~~~~~~~~~~~~
mergers.cpp:87:8: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
   scanf("%d %d", &u, &v);
   ~~~~~^~~~~~~~~~~~~~~~~
mergers.cpp:95:8: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
   scanf("%d", &s[i]);
   ~~~~~^~~~~~~~~~~~~
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...