BZOJ3714 [PA2014]Kuglarz 【最小生成树】
题目链接
题解
我们如果知道了所有的数,同样就知道了所有的前缀和
相反,我们如果求出了所有前缀和,就知道了所有的数,二者是等价的
对于一个区间\([l,r]\)如果我们知道了前缀和\(sum[l - 1]\),我们就知道了\(sum[r]\)
所以区间\([l,r]\)相当于连接\(l - 1\)和\(r\)的边
而\(sum[0]\)我们是知道的
所以我们只需最小代价使所有点联通
最小生成树即可
由于边很多,使用\(prim\)算法
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
#define res register
using namespace std;
const int maxn = 2005,maxm = 2000005,INF = 1000000000;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
int G[maxn][maxn],n,d[maxn],vis[maxn];
priority_queue<cp,vector<cp>,greater<cp> > q;
LL prim(){
LL ans = 0;
memset(d,0x3f3f3f3f,sizeof(d));
d[0] = 0; q.push(mp(d[0],0));
int u;
while (!q.empty()){
u = q.top().second; q.pop();
if (vis[u]) continue;
vis[u] = true;
ans += d[u];
for (int to = 0; to <= n; to++)
if (to != u && !vis[to] && d[to] > G[u][to]){
d[to] = G[u][to];
q.push(mp(d[to],to));
}
}
return ans;
}
int main(){
n = read();
for (res int i = 0; i < n; i++){
for (res int j = i + 1; j <= n; j++){
G[i][j] = G[j][i] = read();
}
}
printf("%lld\n",prim());
return 0;
}