#include<bits/stdc++.h>
using namespace std;
#define task "a"
#define ll long long
#define ii pair<ll, ll>
#define fi first
#define se second
const long mxN = 1e5 + 7;
int n, in[mxN], h[mxN], par[mxN][20], root[mxN], mn[mxN], k, num, c[mxN], ans, lst[mxN];
vector<int> w[mxN], ww[mxN];
void TiTo(int j)
{
in[j] = ++num;
h[j] = h[par[j][0]] + 1;
for (int i = 1; i <= 20; i++)
par[j][i] = par[par[j][i - 1]][i - 1];
for (int i : w[j])
{
if (in[i])
return;
par[i][0] = j;
TiTo(i);
}
}
bool cmp(int u, int v)
{
return in[u] < in[v];
}
int LCA(int u, int v)
{
if (h[u] < h[v])
swap(u, v);
for (int i = 20; i >= 0; i--)
{
if (h[par[u][i]] >= h[v])
u = par[u][i];
}
if (u == v)
return h[u];
for (int i = 20; i >= 0; i--)
{
if (par[u][i] != par[v][i])
{
u = par[u][i];
v = par[v][i];
}
}
return h[u] - 1;
}
void DFS(int j)
{
root[j] = h[mn[c[j]]];
for (int i : w[j])
{
if (h[i] < h[j])
continue;
DFS(i);
root[j] = min(root[j], root[i]);
if (root[i] < h[i])
ww[c[i]].push_back(c[j]);
}
}
int cs[mxN], low[mxN], dsu[mxN];
bool vis[mxN];
vector<int> vc;
void Tarzan(int j)
{
cout << j << '\n';
cs[j] = low[j] = ++num;
vis[j] = 1;
vc.push_back(j);
for (int i : ww[j])
{
if (!vis[i])
Tarzan(i);
if (vis[i] == 1)
low[j] = min(low[i], low[j]);
}
if (low[j] != cs[j])
return;
// bool tt = 0;
// int cntt = 0;
// k++;
// while (vis[j] == 1)
// {
// int i = vc.back();
// vc.pop_back();
//
// cout << i << " ";
//
// vis[i] = 2;
// dsu[i] = k;
//
// cntt++;
// for (int u : ww[i])
// tt |= (dsu[u] && dsu[u] != k);
//
// if (i == j)
// break;
// }
//
// if (!tt)
// ans = min(ans, cntt - 1);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
//freopen(task".INP", "r", stdin);
//freopen(task".OUT", "w", stdout);
cin >> n >> k;
for (int i = 1; i < n; i++)
{
int u, v;
cin >> u >> v;
w[u].push_back(v);
w[v].push_back(u);
}
TiTo(1);
for (int i = 1; i <= n; i++)
{
cin >> c[i];
if (mn[c[i]])
mn[c[i]] = LCA(mn[c[i]], i);
else
mn[c[i]] = i;
}
DFS(1);
for (int i = 1; i <= k; i++)
{
cout << i << " : ";
for (int j : ww[i])
cout << j << " ";
cout << '\n';
}
ans = n;
for (int i = 1; i <= k; i++)
{
if (!vis[i])
Tarzan(i);
cout << '\n';
}
cout << ans;
}
컴파일 시 표준 에러 (stderr) 메시지
capital_city.cpp: In function 'void TiTo(int)':
capital_city.cpp:19:19: warning: iteration 19 invokes undefined behavior [-Waggressive-loop-optimizations]
19 | par[j][i] = par[par[j][i - 1]][i - 1];
| ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~
capital_city.cpp:18:23: note: within this loop
18 | for (int i = 1; i <= 20; i++)
| ~~^~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |