題目描述
東東在老家農村無聊,想種田。農田有 n 塊,編號從 1~n。種田要灌氵
衆所周知東東是一個魔法師,他可以消耗一定的 MP 在一塊田上施展魔法,使得黃河之水天上來。他也可以消耗一定的 MP 在兩塊田的渠上建立傳送門,使得這塊田引用那塊有水的田的水。 (1<=n<=3e2)
黃河之水天上來的消耗是 Wi,i 是農田編號 (1<=Wi<=1e5)
建立傳送門的消耗是 Pij,i、j 是農田編號 (1<= Pij <=1e5, Pij = Pji, Pii =0)
東東爲所有的田灌氵的最小消耗
輸入
第1行:一個數n
第2行到第n+1行:數wi
第n+2行到第2n+1行:矩陣即pij矩陣
輸出
第1行:一個數n
第2行到第n+1行:數wi
第n+2行到第2n+1行:矩陣即pij矩陣
樣例輸入
4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0
樣例輸出
9
思路
綜述
這道題主要考察了一個新的算法:Kruskal
參考:圖論、並查集。
Kruskal
Step1:
邊集排序
std::sort(e, e + tot, cmp);
Step2:
從最小的開始遍歷邊集;
如果頂點個數集爲n,退出;
if (unit(e[i].u, e[i].v)) {
total += e[i].w;
num++;
if (num == n)break;
}
本題
所有的農田看成點,連接之間有邊,天空看做一個點,該點與所有的農田點都有邊相連。所以該題就成了n+1個點的最小生成樹問題;
過程
Step1:輸入
注意一點,如果輸入爲0則不加入到邊集內
輸入超級源點
if (w != 0) {
term.u = n;
term.v = i;
term.w = w;
e[tot] = term;
tot++;
}
輸入農田點
注意一點:因爲這是無向圖,所以只需要記錄一半即可;
可以這樣處理:只記錄(i,j)中,i>j的情況;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> w;
if (i < j)continue;
if (w == 0)continue;
term.u = i;
term.v = j;
term.w = w;
e[tot] = term;
tot++;
}
}
Step2:跑Kruskal
具體過程見上面
int kruskal() {
std::sort(e, e + tot, cmp);
int total = 0;
int num = 0;
for (int i = 0; i < tot; i++) {
if (unit(e[i].u, e[i].v)) {
total += e[i].w;
num++;
if (num == n)break;
}
}
return total;
}
總結
Kruskal算法用到兩個知識:並查集和Kruskal算法本身;
圖論的問題,常常需要我們從長長的文字中抽象出圖,然後再根據所學解決問題;
代碼
上文有詳細註釋
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 5;
int n;
int tot = 0;
struct Edge {
int u, v, w;
bool operator < (Edge& t) {
return w < t.w;
}
}e[maxn];
int par[maxn];
Edge term;
void init() {
for (int i = 0; i < maxn; i++) {
par[i] = i;
}
}
int find(int x) {
if (par[x] == x)return x;
else return par[x] = find(par[x]);
}
bool unit(int ax, int ay) {
int x = find(ax);
int y = find(ay);
if (x == y)return false;
par[x] = par[y];
return true;
}
bool cmp(Edge a, Edge b) { return a.w < b.w; }
int kruskal() {
std::sort(e, e + tot, cmp);
int total = 0;
int num = 0;
for (int i = 0; i < tot; i++) {
if (unit(e[i].u, e[i].v)) {
total += e[i].w;
num++;
if (num == n)break;
}
}
return total;
}
int main() {
cin >> n;
int w;
init();
for (int i = 0; i < n; i++) {
cin >> w;
if (w != 0) {
term.u = n;
term.v = i;
term.w = w;
e[tot] = term;
tot++;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> w;
if (i < j)continue;
if (w == 0)continue;
term.u = i;
term.v = j;
term.w = w;
e[tot] = term;
tot++;
}
}
cout << kruskal() << endl;
}