/*
* @Author: Achan
* @Date: 2018-10-26 17:09:43
* @Last Modified by: Achan
* @Last Modified time: 2018-10-29 18:10:10
*/
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<iomanip>
#include<vector>
#include<queue>
#include<cmath>
using namespace std;
#define X first
#define Y second
#define eps 1e-2
#define gcd __gcd
#define pb push_back
#define PI acos(-1.0)
#define lowbit(x) (x)&(-x)
#define fin freopen("in.txt","r",stdin);
#define fout freopen("out.txt","w",stdout);
#define bug printf("!!!!!\n");
#define mem(x,y) memset(x,y,sizeof(x))
#define rep(i,j,k) for(int i=j;i<(int)k;i++)
#define per(i,j,k) for(int i=j;i<=(int)k;i++)
#define io std::ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL);
typedef long long ll;
typedef long double LD;
typedef pair<int,int> pii;
typedef unsigned long long ull;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int inf = 1<<30;
const ll INF = 1e18 ;
const int mod = 1e9+7;
const int maxn = 100+2;
int mp[maxn][maxn];
bool vis[maxn];
int dis[maxn];
int n;
struct node
{
int poi;
int w;
node (){}
node(int poi, int w): poi(poi),w(w) {};
bool operator < (const node & a) const
{
return w > a.w;
}
};
int Prim(int s)
{
fill(dis, dis + maxn, inf);
memset(vis, 0, sizeof(vis));
priority_queue <node> q;
q.push(node(s,0));
int ans = 0;
node t;
while(!q.empty())
{
t = q.top(); q.pop();
int cur = t.poi;
if(vis[cur]) continue;
vis[cur] = 1;
int w = t.w;
ans += w; //最短到cur点路径总和
for(int i=1; i<=n; i++) //遍历n个点
{
if(!vis[i] && dis[i] > mp[cur][i])
{
dis[i] = mp[cur][i] ;
q.push(node( i , dis[i]));
}
}
}
return ans;
}
int main(void)
{
// fin
//fout
io
while(n = read())
{
int r;
r = read();
fill(mp[0], mp[0]+maxn*maxn, inf);
while(r--)
{
int u,v,w;
u = read(), v = read(), w = read();
mp[u][v] = mp[v][u] = (mp[u][v] > w?w : mp[u][v]);
}
// per(i,1,n) per(j,1,n) cout<<mp[i][j]<<(j==n?"\n":" ");
cout<<Prim(1)<<endl;
}
}
Memory: 688K Time: 0MS
Language: G++ Result: Accepted
07-24
07-24