이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define F first
#define S second
#define pb push_back
#define endl '\n'
#define Mp make_pair
#define all(x) x.begin(), x.end()
#define debug(x) cerr << #x << " = " << x << endl
#define set_dec(x) cout << fixed << setprecision(x);
#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define file_io freopen("in.txt" , "r+" , stdin) ; freopen("out.txt" , "w+" , stdout);
ll mod = 998244353;
ll power(ll a, ll b)
{
return (!b ? 1 : (b & 1 ? a * power(a * a % mod, b / 2) % mod : power(a * a % mod, b / 2) % mod));
}
const int N = 5e5+23, L =23 ;
vector<int>g[N], buc[N];
int st[N], h[N], par[N][L], sz[N], sum[N], is[N];
int ans;
int n , k ;
int a[N];
int tim;
void dfs(int v, int p=0){
sz[v]=1;
st[v]=++tim;
for (int u: g[v]) {
if(u==p)continue;
h[u]=h[v]+1;
par[u][0]=v;
dfs(u,v);
sz[v]+=sz[u];
}
}
void DFS(int v, int p=0){
int temp=0;
for (int u: g[v]){
if(u==p) continue;
DFS(u,v);
is[v]+=is[u];
sum[v]+=sum[u];
}
if(sum[v]==sz[v]){
if(is[v]==0 && v!=1)ans++;
if(is[v]==1 && v==1) ans++;
is[v]=1;
}
}
int LCA(int v, int u){
if(h[v]>h[u])swap(u,v);
int d =h[u]-h[v];
for (int i=L-1; i>=0; i--) {
if(d>>i&1) u=par[u][i];
}
if(u==v) return v;
for (int i=L-1; i>=0; i--){
if(par[u][i]!=par[v][i]){
v=par[v][i];
u=par[u][i];
}
}
return par[v][0];
}
int main()
{
fast_io
cin>>n>>k;
for (int i=0; i<n-1; i++){
int u , v; cin>>v>>u;
g[v].pb(u);
g[u].pb(v);
}
for (int i=1; i<=n; i++){
cin>>a[i];
buc[a[i]].pb(i);
}
dfs(1);
for (int j=1; j<L; j++){
for (int i=1; i<=n; i++){
par[i][j]=par[par[i][j-1]][j-1];
}
}
for (int w=1; w<=k; w++){
vector<pii> vec;
for (int i: buc[w]) vec.pb({st[i], i});
sort(all(vec));
int lca=LCA(vec[0].S, vec.back().S);
sum[lca]+=buc[w].size();
}
DFS(1);
//cout<<ans<<" ";
cout<<(ans+1)/2<<endl;
}
컴파일 시 표준 에러 (stderr) 메시지
mergers.cpp: In function 'void DFS(int, int)':
mergers.cpp:53:9: warning: unused variable 'temp' [-Wunused-variable]
53 | int temp=0;
| ^~~~
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |