#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ar array
struct Dsu{
vector <int> fa;
Dsu(int n){
fa.resize(n);
iota(fa.begin(), fa.end(), 0);
}
int get(int x){ return x ^ fa[x] ? fa[x] = get(fa[x]) : x; }
bool merge(int u, int v){
u = get(u), v = get(v);
if ( u == v ) return false;
fa[v] = u;
return true;
}
};
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, k; cin >> n >> k;
vector <vector<int>> adj(n);
for ( int i = 0; i + 1 < n; i++ ){
int u, v; cin >> u >> v;
--u, --v;
adj[u].pb(v);
adj[v].pb(u);
}
vector <int> s(n);
for ( auto &x: s ){
cin >> x; --x;
}
auto check = [&](vector <int> t){
vector <vector<int>> cnt(n, vector <int> (k));
auto dfs = [&](auto dfs, int u, int p) -> void{
cnt[u][t[u]] = 1;
for ( auto &v: adj[u] ){
if ( v != p ){
dfs(dfs, v, u);
for ( int i = 0; i < k; i++ ){
cnt[u][i] += cnt[v][i];
}
}
}
};
dfs(dfs, 0, -1);
int bad = 0;
for ( int u = 0; u < n; u++ ){
bool flag = true;
for ( int t = 0; t < k; t++ ){
if ( cnt[u][t] > 0 && cnt[u][t] < cnt[0][t] ){
flag = false;
}
}
bad += flag;
}
return bad == 1;
};
vector <ar<int,2>> pa;
for ( int i = 0; i < k; i++ ){
for ( int j = i; j < k; j++ ) pa.pb({i, j});
}
int opt = n, m = pa.size();
for ( int mask = 0; mask < (1 << m); mask++ ){
Dsu ds(k);
for ( int i = 0; i < m; i++ ){
if ( mask >> i & 1 ){
ds.merge(pa[i][0], pa[i][1]);
}
}
vector <int> t(n);
for ( int i = 0; i < n; i++ ) t[i] = s[ds.get(s[i])];
if ( check(t) ){
opt = min(opt, __builtin_popcount(mask));
}
}
cout << opt;
cout << '\n';
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3053 ms |
348 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3053 ms |
348 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3053 ms |
348 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3086 ms |
31696 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3053 ms |
348 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |