社区讨论
数组大小
P2495【模板】虚树 / [SDOI2011] 消耗战参与者 1已保存回复 0
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @lz6bxdi2
- 此快照首次捕获于
- 2024/07/29 09:47 2 年前
- 此快照最后确认于
- 2024/07/29 10:43 2 年前
请问为什么N开2.5e5就过不了,这是哪里的问题
CPP#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
const int N=5e5,INT_INF=1e9;
const ll LL_INF=1e14;
int head[N],to[N<<1],nxt[N<<1],edge[N<<1],tot;
void add(int u,int v,int w=0) {
++tot;
to[tot]=v;
edge[tot]=w;
nxt[tot]=head[u];
head[u]=tot;
return;
}
int dep[N],fa[N][20],g[N],dfn[N],cnt;
void dfs(int p,int f) {
dep[p]=dep[f]+1;
fa[p][0]=f;
++cnt;
dfn[p]=cnt;
for(int i=1; (1<<i)<dep[p]; i++) fa[p][i]=fa[fa[p][i-1]][i-1];
for(int i=head[p]; i; i=nxt[i]) {
int y=to[i];
if(y==f)continue;
g[y]=min(g[p],edge[i]);
dfs(y,p);
}
return;
}
int lca(int x,int y) {
if(dep[x]<dep[y])swap(x,y);
for(int i=19; i>=0; i--)if(dep[x]-(1<<i)>=dep[y])x=fa[x][i];
if(x==y)return x;
for(int i=19; i>=0; i--) {
if(fa[x][i]!=fa[y][i]) {
x=fa[x][i];
y=fa[y][i];
}
}
return fa[x][0];
}
int P[N],st[N],top;
bool Q[N];
bool cmp(int a,int b) {
return dfn[a]<dfn[b];
}
void build(int n) {
sort(P,P+n,cmp);
top=1;
st[top]=1;
tot=0;
head[1]=0;
for(int i=0; i<n; i++) {
Q[P[i]]=true;
int l=lca(P[i],st[top]),dis;
if(l!=st[top]) {
while(dfn[st[top-1]]>dfn[l]) {
add(st[top-1],st[top]);
--top;
}
if(l!=st[top-1]) {
head[l]=0;
add(l,st[top]);
st[top]=l;
} else {
add(l,st[top]);
--top;
}
}
head[P[i]]=0;
++top;
st[top]=P[i];
}
for(int i=1; i<top; i++)add(st[i],st[i+1]);
return;
}
ll dp[N];
void solve(int p) {
ll sum=0;
for(int i=head[p]; i; i=nxt[i]) {
int y=to[i];
solve(y);
sum+=dp[y];
}
if(Q[p])dp[p]=g[p];
else dp[p]=min(sum,(p==1)?LL_INF:(ll)g[p]);
Q[p]=false;
return;
}
int main() {
int n,m;
cin>>n;
for(int i=0; i<n-1; i++) {
int u,v,w;
cin>>u>>v>>w;
add(u,v,w);
add(v,u,w);
}
g[1]=INT_INF;
dfs(1,0);
cin>>m;
for(int i=0,k; i<m; i++) {
cin>>k;
for(int i=0; i<k; i++)cin>>P[i];
build(k);
solve(1);
cout<<dp[1]<<'\n';
}
return 0;
}
回复
共 0 条回复,欢迎继续交流。
正在加载回复...