BZOJ P2753 [SCOI2012] 滑雪與時間膠囊【最小生成樹】
阿新 • • 發佈:2018-12-10
按要求建圖跑最小生成樹:
#include <queue> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define ll long long #define rep(i,x,y) for(ll i=(x);i<=(y);i++) #define repl(i,x,y) for(ll i=(x);i<(y);i++) #define repd(i,x,y) for(ll i=(x);i>=(y);i--) using namespace std; const ll N=1e5+5; const ll M=2e6+5; const ll Inf=1e18; ll n,m,ans,tot,h[N],f[N],vis[N]; ll cnt,to[M],nxt[M],edge[M],head[M]; struct node { ll x,y,z; }G[M]; inline ll read() { ll x=0;char ch=getchar();bool f=0; while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();} return f?-x:x; } void ins(ll x,ll y,ll z) { ++cnt;G[cnt].x=x,G[cnt].y=y,G[cnt].z=z; to[cnt]=y;edge[cnt]=z;nxt[cnt]=head[x];head[x]=cnt; } void dfs(ll x) { if(vis[x]) return ;++tot;vis[x]=1; for(ll i=head[x];i;i=nxt[i]) dfs(to[i]); } bool cmp(node p,node q) { return h[p.y]==h[q.y]?p.z<q.z:h[p.y]>h[q.y]; } ll find(ll x) { return f[x]==x?x:f[x]=find(f[x]); } int main() { n=read(),m=read(); rep(i,1,n) h[i]=read(); rep(i,1,m) { ll x=read(),y=read(),z=read(); if(h[x]>=h[y]) ins(x,y,z); if(h[y]>=h[x]) ins(y,x,z); } dfs(1);printf("%lld ",tot); sort(G+1,G+1+cnt,cmp); rep(i,1,n) f[i]=i; rep(i,1,cnt) { ll x=G[i].x,y=G[i].y; if(!vis[x]||!vis[y]) continue; ll fx=find(x),fy=find(y); if(fx!=fy) { f[fx]=fy,ans+=G[i].z; } } printf("%lld",ans); return 0; }