[bzoj1601]灌水(洛谷P1550)
[USACO08OCT]Watering Hole G
Farmer John已经决定把水灌到他的 块农田,农田被数字1到n标记。把一块土
地进行灌水有两种方法,从其他农田引水,或者这块土地建造水库。 建造一个水库需要花费
,连接两块土地需要花费. 计算Farmer John所需的最少代价。
Input
第一行:一个数
第二行到第 行:第 行含有一个数
第 行到第 行:第 行有 个被空格分开的数,第 个数代表
第一行:一个单独的数代表最小代价.
Sample Input
4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0
Sample Output
9
思路
老规矩 ,先看数据 暴力显然
咋看像一个最小生成树呢
自建水库的费用不就是超级源点到每一个土地的费用吗???
链接的费用不就是每一条边吗
#include <bits/stdc++.h>
using namespace std;
int n, m, fa[1000001], countt, sum, a, b[100001];
struct edge
{
int u, v, w;
} e[1000001];
bool comp(edge a, edge b)
{
return a.w < b.w;
}
int get(int x)
{
return fa[x] == x ? x : fa[x] = get(fa[x]);
}
bool merge(int x, int y)
{ //判断是否<尚未>连通
x = get(x);
y = get(y);
if (x == y)
return false;
fa[y] = x;
return true;
}
void Kruskal()
{
for (int i = 1; i <= m; i++)
{
if (merge(e[i].u, e[i].v))
countt++, sum += e[i].w;
if (countt == n)
return;
}
}
signed main()
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> b[i], e[++m].u = i, e[m].v = n + 1, e[m].w = b[i];
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> a;
if (a)
{
e[++m].u = i;
e[m].v = j;
e[m].w = a;
}
}
}
sort(e + 1, e + m + 1, comp);
for (int i = 1; i <= n; i++)
fa[i] = i;
Kruskal();
cout << sum;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
#define init(array, x) memset(array, x, sizeof(array))
const int maxn = 1e5 + 99;
int n, m, ans, vis[maxn];
struct node
{
int to, w;
bool operator<(const node tmp) const
{
return tmp.w < w;
}
};
vector<node> d[maxn];
priority_queue<node> q;
void Prim(int x)
{
int tot = 0;
ans = 0;
q.push((node){x, 0});
while (tot <= n && !q.empty())
{
node t = q.top();
q.pop();
int tmp = t.to;
if (vis[tmp])
continue;
vis[tmp] = 1;
ans += t.w;
tot++;
for (int i = 0; i < d[tmp].size(); i++)
{
int to = d[tmp][i].to, w = d[tmp][i].w;
if (!vis[to])
q.push(d[tmp][i]);
}
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
int a;
cin >> a;
d[0].push_back((node){i, a});
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
int a;
cin >> a;
if (i != j)
{
d[i].push_back((node){j, a});
}
}
}
Prim(0);
cout << ans << endl;
return 0;
}
本文来自博客园,作者:蒟蒻orz,转载请注明原文链接:https://www.cnblogs.com/orzz/p/18122190
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话