P5994 [PA2014]Kuglarz(思维 最小生成树)
P5994 [PA2014]Kuglarz(思维 最小生成树)
题意:
你可以询问
思路:
很容易知道,若想要知道第
那就能想到一个很暴力的方法,也就是区间DP(n ^ 3)。不过复杂度过高,不可写。
现在假设一个超级源点0,[0, 0]是没有球的。如果我们知道所有的
所以,对于区间
我们按上述做法建图,跑一个裸的最小生成树就可以了。
实现:
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2005, M = N * N / 2;
int n;
int cost[N][N];
int res;
struct node {
int l, r, cost;
bool operator < (const node &a) const {
return cost < a.cost;
}
} edges[M];
int idx = 0;
int fa[N];
int fd(int x)
{
if(fa[x] != x) fa[x] = fd(fa[x]);
return fa[x];
}
void kruskal()
{
int cnt = 0;
res = 0;
for(int i = 1; i <= idx; i ++)
{
auto [a, b, w] = edges[i];
int ta = fd(a), tb = fd(b);
if(ta == tb) continue;
fa[tb] = ta;
res += w, cnt ++;
if(cnt == n) break;
}
}
signed main()
{
scanf("%lld", &n);
for(int i = 1; i <= n; i ++) fa[i] = i;
for(int i = 1; i <= n; i ++)
for(int j = i; j <= n; j ++)
{
scanf("%lld", &cost[i][j]);
edges[++ idx] = {i - 1, j, cost[i][j]};
}
sort(edges + 1, edges + idx + 1);
kruskal();
printf("%lld\n", res);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现