P2495 [SDOI2011] Consumption War

Posted by mlewis on Thu, 03 Oct 2019 01:20:39 +0200

P2495 [SDOI2011] Consumption War

Title Description

See: P2495 [SDOI2011] Consumption War

Solution

This topic is the classic version of the title of virtual tree bar qwq.

Just paste the code directly (it's not a luogu problem anyway, nobody checks).

Probably it is to build virtual trees first (usually given a bunch of key points are virtual trees), and then DP.

set upTo deal withThe minimum cost of all key points in a subtree,For the purpose ofThe minimum edge weight on the path to the root.

Then... No more.

Code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=5e5+50; 
const ll INF=1ll<<60;
int Log[MAXN],fa[MAXN][21],dfn[MAXN],dep[MAXN];
int stk[MAXN],a[MAXN],top,DFN=0;
ll mn[MAXN],f[MAXN];
struct enode{int to; ll c; };
vector<enode> e[MAXN];
vector<int> son[MAXN];

inline int read()
{
    int x=0,f=1; char c=getchar();
    while (c<'0'||c>'9') { if(c=='-') f=-1; c=getchar(); }
    while (c>='0'&&c<='9') { x=(x<<3)+(x<<1)+(c^48); c=getchar(); }
    return x*f;
}
void add_edge(int u,int v){ son[u].push_back(v); } 
void dfs(int x,int father)
{
	fa[x][0]=father;
	dep[x]=dep[father]+1;
	dfn[x]=++DFN;
	for (int i=1;i<=Log[dep[x]];i++) fa[x][i]=fa[fa[x][i-1]][i-1];
	for (int i=0;i<e[x].size();i++)
	    if (e[x][i].to!=father)
	    {
	    	mn[e[x][i].to]=min(mn[x],e[x][i].c);
	    	dfs(e[x][i].to,x);
	    }
}
int get_lca(int x,int y)
{
	if (dep[x]<dep[y]) swap(x,y);
	for (int i=Log[dep[x]];i>=0;i--)
	    if (dep[fa[x][i]]>=dep[y]) x=fa[x][i];
	if (x==y) return x;
	for (int i=Log[dep[x]];i>=0;i--)
	    if (fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i];
	return fa[x][0];
}
void insert(int x)
{
	if (top==1) { stk[++top]=x; return; }
	int lca=get_lca(stk[top],x);
	if (lca==stk[top]) return;
	while (top>1&&dfn[stk[top-1]]>=dfn[lca]) add_edge(stk[top-1],stk[top]),top--;
	if (lca!=stk[top]) add_edge(lca,stk[top]),stk[top]=lca;
	stk[++top]=x;
}
ll tree_dp(int x)
{
	for (int i=0;i<son[x].size();i++) tree_dp(son[x][i]);
	f[x]=mn[x];
	if (!son[x].size()) return f[x];
	ll s=0;
	for (int i=0;i<son[x].size();i++) s+=f[son[x][i]];
	son[x].clear();
	return f[x]=min(f[x],s);
}
int compare(int x,int y){ return dfn[x]<dfn[y]; }
int main()
{
	int n=read();
	for (int i=1;i<n;i++)
	{
		int u=read(),v=read(),c=read();
		e[u].push_back((enode){v,c});
		e[v].push_back((enode){u,c});
	}
	dep[0]=-1,Log[1]=0;
	for (int i=2;i<=n;i++) Log[i]=Log[i>>1]+1;
	for (int i=1;i<=n;i++) mn[i]=INF; 
	dfs(1,0);
    //for (int i=1;i<=n;i++) cout<<i<<":"<<dep[i]<<" "<<dfn[i]<<" "<<mn[i]<<endl;
	
	int Case=read();
	while (Case--)
	{
		int m=read();
		for (int i=1;i<=m;i++) a[i]=read();
		sort(a+1,a+m+1,compare);
		stk[top=1]=1;
		for (int i=1;i<=m;i++) insert(a[i]);
		while (top) add_edge(stk[top-1],stk[top]),top--;
		printf("%lld\n",tree_dp(1));
	}
	return 0;
}