关于空间开小的后果
查看原帖
关于空间开小的后果
772592
shuangmu楼主2023/7/12 21:03

为什么这次不是 RE 而变成了 TLE,最离谱的是我开 O2 后可以过题??? 附代码,这里边数是开少的。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 2.5e5+10;

inline int read(){
	int x = 0; char ch = getchar();
	while(ch<'0' || ch>'9') ch = getchar();
	while(ch>='0'&&ch<='9') x = x*10+ch-48, ch = getchar();
	return x;
}
struct node{
	int nxt, to, w;
};
struct Graph{
	int head[N], tot;
	int num;
	node edge[N<<1];
	void add(int u, int v, int w){
		edge[++tot].nxt = head[u];
		edge[tot].to = v;
		edge[tot].w = w;
		head[u] = tot;
	}
}G1, G2;//原树,虚树。 

int dfn[N];
struct HPD{//重链剖分,heavy path decomposition 
	int siz[N], totd, top[N], son[N], dep[N], fa[N];
	void dfs1(int u, int fath){
		dep[u] = dep[fath]+1;
		siz[u] = 1;
		fa[u] = fath;
		for(int i = G1.head[u]; i; i = G1.edge[i].nxt){
			int v = G1.edge[i].to;
			if(v == fath) continue;
			dfs1(v, u);
			siz[u]+=siz[v];
			if(siz[son[u]]<siz[v]) son[u] = v;
		}
	}
	void dfs2(int u, int Top){
		top[u] = Top;
		dfn[u] = ++totd;
		if(!son[u]) return;
		dfs2(son[u], Top);
		for(int i = G1.head[u]; i; i = G1.edge[i].nxt){
			int v = G1.edge[i].to;
			if(!dfn[v]) dfs2(v, v);
		}
	}
	int LCA(int x, int y){
		while(top[x] != top[y]){
			if(dep[top[x]] < dep[top[y]]) swap(x, y);
			x = fa[top[x]];
		}
		if(dep[x] > dep[y]) swap(x, y);
		return x;
	}
}th; 

int n;
int m, K;
int dst[N], p[N];

void dfsG1(int u, int fath){
	for(int i = G1.head[u]; i; i = G1.edge[i].nxt){
		int v = G1.edge[i].to;
		if(v == fath) continue;
		dst[v] = min(dst[u], G1.edge[i].w);
		dfsG1(v, u);
	}
}

bool cmp(int a, int b){
	return dfn[a] < dfn[b];
}
int stk[N], tp;
bool is_tar[N];
void build(){
	sort(p+1, p+K+1, cmp);
	tp = 0;
	stk[++tp] = 1, G2.head[1] = 0;
	for(int i = 1, l; i<=K; ++i){
		if(p[i] == 1) continue;
		l = th.LCA(p[i], stk[tp]);
		if(l != stk[tp]){
			while(dfn[l] < dfn[stk[tp-1]]){
				G2.add(stk[tp-1], stk[tp], dst[stk[tp]]);
				--tp;
			}
			if(dfn[l] > dfn[stk[tp-1]]){
				G2.head[l] = 0;
				G2.add(l, stk[tp], dst[stk[tp]]), stk[tp] = l;
			} else{
				G2.add(l, stk[tp], dst[stk[tp]]);
				--tp;
			}
			
		}
		G2.head[p[i]] = 0;
		stk[++tp] = p[i];
	}
	for(int i = 1; i<tp; ++i){
		G2.add(stk[i], stk[i+1], dst[stk[i+1]]);	
	}
}	

ll f[N];
void dfs_ans(int u, int fath){
	f[u] = 0;
	for(int i = G2.head[u]; i; i = G2.edge[i].nxt){
		int v = G2.edge[i].to;
		if(v == fath) continue;
		dfs_ans(v, u);
		if(is_tar[v]){
			f[u]+=G2.edge[i].w;
		} else{
			f[u]+= min(f[v], 1ll*G2.edge[i].w);
		}
	}
}
int main(){
	n = read();
	dst[1] = 0x3f3f3f3f;
	for(int i = 1; i<n; ++i){
		int u = read(), v = read(), w = read();
		G1.add(u, v, w);
		G1.add(v, u, w); 
	}
	th.dfs1(1, 0);
	th.dfs2(1, 1);
	dfsG1(1, 0);
	m = read();
	while(m--){
		K = read();
		for(int i = 1; i<=K; ++i){
			p[i] = read();
			is_tar[p[i]] = 1;
		} 
		build();
		dfs_ans(1, 0);
		printf("%lld\n", f[1]);
		for(int i = 1; i<=K; ++i){
			is_tar[p[i]] = 0;
		}
	}
	return 0;
} 
2023/7/12 21:03
加载中...