Submission #960491

#TimeUsernameProblemLanguageResultExecution timeMemory
960491abczzMergers (JOI19_mergers)C++14
100 / 100
1121 ms203364 KiB
#include <iostream> #include <vector> #include <array> #define ll long long using namespace std; vector <ll> adj[500000]; vector <ll> G[500000]; vector <array<ll, 2>> edge; ll n, k, a, b, p, cnt, f, A[500000], dp[500000], D[500000], H[500000], P[500000], bl[500000][19], deg[500000]; ll dsu(ll u) { if (P[u] == u) return u; else return P[u] = dsu(P[u]); } void dfs(ll u, ll p) { for (auto v : adj[u]) { if (v != p) { D[v] = D[u]+1; dfs(v, u); bl[v][0] = u; } } } ll lca(ll a, ll b) { if (D[a] > D[b]) swap(a, b); ll db = D[b]; for (int i=18; i>=0; --i) { if (db-(1LL<<i) >= D[a]) { db -= (1LL<<i); b = bl[b][i]; } } for (int i=18; i>=0; --i) { if (bl[a][i] != bl[b][i]) { a = bl[a][i], b = bl[b][i]; } } if (a == b) return a; else return bl[a][0]; } void solve(ll u, ll p) { dp[u] = H[A[u]]; for (auto v : adj[u]) { if (v != p) { solve(v, u); if (dp[v] > D[u]) { ++cnt; edge.push_back({u, v}); } else P[v] = u; dp[u] = min(dp[u], dp[v]); } } } int main() { cin >> n >> k; for (int i=0; i<n-1; ++i) { cin >> a >> b; --a, --b; adj[a].push_back(b); adj[b].push_back(a); } for (int i=0; i<n; ++i) { P[i] = i; cin >> A[i]; --A[i]; G[A[i]].push_back(i); } dfs(0, -1); for (int j=1; j<19; ++j) { for (int i=0; i<n; ++i) { bl[i][j] = bl[bl[i][j-1]][j-1]; } } for (int i=0; i<k; ++i) { p = G[i][0]; for (int j=1; j<G[i].size(); ++j) { p = lca(p, G[i][j]); } H[i] = D[p]; } solve(0, -1); for (auto [u, v] : edge) { auto a = dsu(u); auto b = dsu(v); ++deg[a]; ++deg[b]; } for (int i=0; i<n; ++i) { if (deg[i] == 1) ++f; } cout << (f+1)/2 << '\n'; }

Compilation message (stderr)

mergers.cpp: In function 'int main()':
mergers.cpp:83:20: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<long long int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   83 |     for (int j=1; j<G[i].size(); ++j) {
      |                   ~^~~~~~~~~~~~
mergers.cpp:89:13: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
   89 |   for (auto [u, v] : edge) {
      |             ^
#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...