QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#865093#5418. Color the TreeHMZHMZHMZRE 0ms17096kbC++142.1kb2025-01-21 14:47:282025-01-21 14:47:29

Judging History

你现在查看的是最新测评结果

  • [2025-01-21 14:47:29]
  • 评测
  • 测评结果:RE
  • 用时:0ms
  • 内存:17096kb
  • [2025-01-21 14:47:28]
  • 提交

answer

#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define vi vector<int>
#define pb push_back
#define lowbit(x) (x)&-(x)
using namespace std;
const int N=1e5+10;
ll f[N],ans;
vi G[N],pos[N],tr[N];
int n,m,T,a[N],dfn[N],tot,anc[N][20],mn[N][20],dep[N];
inline int read(){
	int s=0,f=0;
	char ch=getchar();
	while(ch<'0'||ch>'9') f|=(ch=='-'),ch=getchar();
	while(ch<='9'&&ch>='0') s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
	return f?-s:s;
}
inline int cmin(int x,int y){return dfn[x]<dfn[y]?x:y;}
inline void dfs(int x,int fa){
	dep[x]=dep[fa]+1;
	pos[dep[x]].pb(x);
	dfn[x]=++tot;anc[tot][0]=fa;
	for(int to:G[x]) if(to!=fa) dfs(to,x);
}
inline int lca(int x,int y){
	if(x==y) return x;
	if((x=dfn[x])>(y=dfn[y])) swap(x,y);
	int k=__lg(y-x++);
	return cmin(anc[x][k],anc[y-(1<<k)+1][k]);
}
inline int query(int l,int r){
	int k=__lg(r-l+1);
	return min(mn[l][k],mn[r-(1<<k)+1][k]);
}
inline void dfs(int x,int fa,int d){
	f[x]=0;
	for(int to:tr[x]) dfs(to,x,d),f[x]+=f[to];
	ll val=query(d-dep[x]+1,d-dep[fa]);
	if(tr[x].empty()) f[x]=val;
	else f[x]=min(f[x],val);
}
int main(){
	T=read();
	while(T--){
		n=read();
		for(register int i=1;i<=n;++i) a[i]=read(),G[i].clear(),pos[i].clear();
		for(register int i=1;i<n;++i){
			int u=read(),v=read();
			G[u].pb(v),G[v].pb(u);
		}
		dfs(1,0);
		for(register int i=1;i<=n;++i) mn[i][0]=a[i];
		for(register int i=1;i<=19;++i){
			for(register int j=1;j+(1<<i)-1<=n;++j){
				mn[j][i]=min(mn[j][i-1],mn[j+(1<<(i-1))][i-1]);
				anc[j][i]=cmin(anc[j][i-1],anc[j+(1<<(i-1))][i-1]);
			}
		}
		ans=0;
		for(register int i=1;i<=n;++i){
			if(pos[i].empty()) continue;
			vi tmp;
			for(int x:pos[i]) tmp.pb(x);
			for(register int j=0;j+1<(int)pos[i].size();++j) tmp.pb(lca(pos[i][j],pos[i][j+1]));
			sort(tmp.begin(),tmp.end(),[](int x,int y){return dfn[x]<dfn[y];});
			tmp.erase(unique(tmp.begin(),tmp.end()),tmp.end());
			for(int x:tmp) tr[x].clear();
			for(register int j=1;j<(int)tmp.size();++j) tr[lca(tmp[j],tmp[j-1])].pb(tmp[j]);
			dfs(tmp[0],0,i);
			ans+=f[tmp[0]];
			//~ cout<<ans<<"\n";
		}
		cout<<ans<<'\n';
	}
}

详细

Test #1:

score: 100
Accepted
time: 0ms
memory: 17096kb

input:

3
4
10 15 40 1
1 2
2 3
2 4
5
10 5 1 100 1000
1 2
2 3
2 4
4 5
4
1000 200 10 8
1 2
2 3
3 4

output:

35
17
1218

result:

ok 3 number(s): "35 17 1218"

Test #2:

score: -100
Runtime Error

input:

3000
54
43 44 11 49 17 14 7 30 35 12 34 14 15 8 29 47 30 31 39 17 26 23 26 45 34 50 49 13 35 18 29 15 13 44 47 5 22 20 19 46 30 22 26 13 47 46 43 27 48 48 13 14 30 44
1 2
1 3
2 4
3 5
4 6
2 7
4 8
1 9
3 10
1 11
8 12
2 13
9 14
1 15
1 16
15 17
15 18
7 19
1 20
19 21
13 22
10 23
17 24
9 25
9 26
24 27
8 28...

output:


result: