最小树形图模板题
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int n,X,Y,Z;
struct node
{
int x,y,z;
}vill[1200];
const int MAXM=40010;
const int MAXN=1010;
const int INF=0x3f3f3f3f;
int dis(node a,node b){
return abs(a.x-b.x)+abs(a.y-b.y)+abs(a.z-b.z);
}
struct Edge
{
int u,v,cost;
}edge[MAXM];
int pre[MAXN],id[MAXN],visit[MAXN],in[MAXN];
int zhuliu(int root,int n,int m,Edge edge[]){
int res=0,u,v;
while(1){
for(int i=0;i<n;i++)
in[i]=INF;
for(int i=0;i<m;i++)
if(edge[i].u!=edge[i].v&&edge[i].cost<in[edge[i].v]){
pre[edge[i].v]=edge[i].u;
in[edge[i].v]=edge[i].cost;
}
for(int i=0;i<n;i++){
if(i!=root&&in[i]==INF){
return -1;
}
}
int tn=0;
memset(id,-1,sizeof(id));
memset(visit,-1,sizeof(visit));
in[root]=0;
for(int i=0;i<n;i++){
res+=in[i];
v=i;
while(visit[v]!=i&&id[v]==-1&&v!=root){
visit[v]=i;
v=pre[v];
}
if(v!=root&&id[v]==-1){
for(int u=pre[v];u!=v;u=pre[u])
id[u]=tn;
id[v]=tn++;
}
}
if(tn==0)
break;
for(int i=0;i<n;i++)
if(id[i]==-1)
id[i]=tn++;
for(int i=0;i<m;){
v=edge[i].v;
edge[i].u=id[edge[i].u];
edge[i].v=id[edge[i].v];
if(edge[i].u!=edge[i].v)
edge[i++].cost-=in[v];
else
swap(edge[i],edge[--m]);
}
n=tn;
root=id[root];
}
return res;
}
int main(){
while(scanf("%d%d%d%d",&n,&X,&Y,&Z)!=EOF&&(X||Y||Z)){
memset(vill,0,sizeof(vill));
for(int i=1;i<=n;i++){
scanf("%d%d%d",&vill[i].x,&vill[i].y,&vill[i].z);
}
int L=0;
for(int i=1;i<=n;i++){
edge[L].u=0;
edge[L].v=i;
edge[L++].cost=X*vill[i].z;
}
for(int i=1;i<=n;i++){
int k;
scanf("%d",&k);
while(k--){
int num;
scanf("%d",&num);
if(num==i)
continue;
edge[L].u=i;
edge[L].v=num;
edge[L].cost=Y*dis(vill[i],vill[num]);
if(vill[num].z>vill[i].z){
edge[L].cost+=Z;
}
L++;
}
}
int ans=zhuliu(0,n+1,L,edge);
if(ans!=-1)
printf("%d\n",ans);
else
printf("poor XiaoA\n");
}
return 0;
}