(Prim堆优化)滑雪与时间胶囊
\(本题可作为\ Prim堆优化\ 求最小生成树的模板题\)
\(由于受高度的限制,所以队列中存的不止要有边权,还得有点的高度,\\如果只存边权,就可能先把高度小的入队,最后发现走不通,又得回到高度大的点\\这个时候统计的ans就不对了.\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 1e5 + 10, M = 2e6 + 10;
int h[N];
bool st[N];
vector<PII> e[N];
int dist[N];
int n, m;
struct qnode {
int v, h, dis;
qnode(int _v = 0, int _h = 0, int _dis = 0) : v(_v), h(_h), dis(_dis){}
bool operator < (const qnode &t) const {
return h == t.h ? dis > t.dis : h < t.h;
}
};
void prim() {
ll ans = 0;
int cnt = 0;
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
priority_queue<qnode> q;
q.push({1, h[1], 0});
while(q.size()) {
qnode t = q.top();
q.pop();
int ver = t.v;
if (st[ver]) continue;
st[ver] = true;
ans += dist[ver];
++cnt;
for (int i = 0; i < e[ver].size(); ++i) {
int j = e[ver][i].y, w = e[ver][i].x;
if (!st[j] && dist[j] > w) {
dist[j] = w;
q.push({j, h[j], w});
}
}
}
cout << cnt << " " << ans << '\n';
}
int main() {
IO;
//freopen("in.txt", "r", stdin);
cin >> n >> m;
for (int i = 1; i <= n; ++i) cin >> h[i];
while (m--) {
int a, b, w;
cin >> a >> b >> w;
if (h[a] < h[b]) swap(a, b);
e[a].pb({w, b});
if (h[a] == h[b]) e[b].pb({w, a});
}
prim();
return 0;
}