HDU 4009Transfer water 最小树形图

时间:2022-10-13 16:01:24

题目:http://acm.hdu.edu.cn/showproblem.php?pid=4009

题意:山上有n户人,均给出三维坐标,这n户人要吃水,可以挖井,花费为所处高度 * X,从别人家引水,若水源处不低于当前人家,那么为两户人的曼哈顿距离 * Y,若低于则额外加上一个水泵的费用Z,然后只有给定的家庭之间才能引水,问能使所有人都用到水的最小花费

思路:无定根最小树形图。定0为虚拟根,从0向每户连边,权值为高度 * X,意为打井的费用,然后根据题目给出的关系连边,跑一遍最小树形图即可

总结:模板敲错了,T了好久。。。真白痴!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
using namespace std;

typedef long long ll;
const int N = 1010;
const int INF = 0x3f3f3f3f;
struct edge
{
int v, u, cost;
}g[N*N*2];
struct node
{
int x, y, z;
}node[N];
int n, X, Y, Z;
int pre[N], id[N], vis[N], in[N];
void work(int i, int j, int &num, int k)
{
g[num].v = i, g[num].u = j;
if(k == 1)
{
g[num].cost = node[j].z * X;
}
else
{
g[num].cost = Y * (abs(node[i].x - node[j].x) + abs(node[i].y - node[j].y) + abs(node[i].z - node[j].z));
if(node[i].z < node[j].z) g[num].cost += Z;
}
num++;
}
int ma(int s, int n, int m)
{
int res = 0;
while(true)
{
for(int i = 0; i < n; i++) in[i] = INF;
for(int i = 0; i < m; i++)
{
int v = g[i].v, u = g[i].u;
if(v != u && g[i].cost < in[u]) in[u] = g[i].cost, pre[u] = v;
}
for(int i = 0; i < n; i++)
{
if(i == s) continue;
if(in[i] == INF) return -1;
}
int num = 0;
memset(id, -1, sizeof id);
memset(vis, -1, sizeof vis);
in[s] = 0;
for(int i = 0; i < n; i++)
{
res += in[i];
int v = i;
while(vis[v] != i && id[v] == -1 && v != s) vis[v] = i, v = pre[v];
if(v != s && id[v] == -1)
{
for(int j = pre[v]; j != v; j = pre[j]) id[j] = num;
id[v] = num++;
}
}
if(num == 0) break;
for(int i = 0; i < n; i++)
if(id[i] == -1) id[i] = num++;
for(int i = 0; i < m; i++)
{
int v = g[i].v, u = g[i].u;
g[i].v = id[v], g[i].u = id[u];
if(id[v] != id[u]) g[i].cost -= in[u];
}
n = num, s = id[s];
}
return res;
}
int main()
{
while(scanf("%d%d%d%d", &n, &X, &Y, &Z), n || X || Y || Z)
{
for(int i = 1; i <= n; i++) scanf("%d%d%d", &node[i].x, &node[i].y, &node[i].z);
int num = 0, k, a;
for(int i = 1; i <= n; i++)
{
scanf("%d", &k);
work(0, i, num, 1);
for(int j = 0; j < k; j++)
{
scanf("%d", &a);
if(i == a) continue;
work(i, a, num, 2);
}
}
int res = ma(0, n + 1, num);
if(res == -1) printf("poor XiaoA\n");
else printf("%d\n", res);
}
return 0;
}