1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
| #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int>pii; const int maxn=3e5+10,inf=0x3f3f3f3f,mod=1000000007; const ll INF=0x3f3f3f3f3f3f3f3f; void read(){} template<typename T,typename... T2>inline void read(T &x,T2 &... oth) { x=0; int ch=getchar(),f=0; while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();} while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} if(f)x=-x; read(oth...); } struct edge { int v,nex; ll w; edge(int v=0,ll w=0,int nex=0): v(v),w(w),nex(nex){} } e[maxn<<1]; int head[maxn],cnt=0; void add(int u,int v,int w=0) { e[++cnt].v=v; e[cnt].w=w; e[cnt].nex=head[u]; head[u]=cnt; } const int maxl=30; int gene[maxn][maxl],depth[maxn],lg[maxn],dfn[maxn],tim=0; ll dp[maxn]; void dfs(int x,int fa) { if(!dfn[x]) dfn[x]=++tim; depth[x]=depth[fa]+1; gene[x][0]=fa; for(int i=1;(1<<i)<=depth[x];i++) gene[x][i]=gene[gene[x][i-1]][i-1]; for(int i=head[x];~i;i=e[i].nex) if(e[i].v!=fa) { dp[e[i].v]=min(dp[x],e[i].w); dfs(e[i].v,x); } } int lca(int x,int y) { if(depth[x]<depth[y]) swap(x,y); while(depth[x]>depth[y]) x=gene[x][lg[depth[x]-depth[y]-1]]; if(x==y) return x; for(int i=lg[depth[x]];i>=0;i--) if(gene[x][i]!=gene[y][i]) { x=gene[x][i]; y=gene[y][i]; } return gene[x][0]; } void init(int s,int n) { depth[s]=1; for(int i=1;i<=n;i++) lg[i]=lg[i-1]+((1<<(lg[i-1]+1))==i); dfs(s,0); }
int h[maxn],stk[maxn],top=0; bool key[maxn]; struct edge2 { int v,nex; edge2(int v=0,int nex=-1): v(v),nex(nex){}; } G[maxn<<1]; int head2[maxn],cnt2=0; void adde(int u,int v) { G[++cnt2].v=v; G[cnt2].nex=head2[u]; head2[u]=cnt2; } ll dfs2(int x) {
ll sum=0,ret=0; for(int i=head2[x];~i;i=G[i].nex) { int v=G[i].v; sum+=dfs2(v); } if(key[x]) ret=dp[x]; else ret=min(dp[x],sum); key[x]=0; head2[x]=-1; return ret; } signed main() { memset(head,-1,sizeof(head)); memset(head2,-1,sizeof(head2)); int n,u,v,w,m,k; read(n); for(int i=1;i<n;i++) { read(u,v,w); add(u,v,w); add(v,u,w); } dp[1]=INF; init(1,n); read(m); while(m--) { read(k); for(int i=1;i<=k;i++) { read(h[i]); key[h[i]]=1; } sort(h+1,h+k+1,[](const int &x,const int &y){ return dfn[x]<dfn[y]; }); stk[top=1]=h[1]; cnt2=0; for(int i=2;i<=k;i++) { int now=h[i]; int lc=lca(now,stk[top]); while(top>1&&dfn[lc]<=dfn[stk[top-1]]) { adde(stk[top-1],stk[top]); top--; } if(dfn[lc]<dfn[stk[top]]) { adde(lc,stk[top]); stk[top]=lc; } stk[++top]=now; } while(--top) adde(stk[top],stk[top+1]); printf("%lld\n",dfs2(stk[1])); } return 0; }
|