HDU 1233: 還是暢通工程
阿新 • • 發佈:2017-09-16
pri top edi efi urn bold max parent weight
///@author Sycamore
///@date 9/16/2017
///@link http://acm.hdu.edu.cn/showproblem.php?pid=1233
#include <bits/stdc++.h>
//n:= # of vertices
//dist[i]:= distance between Vertex i and current MST
//inMST[i]:= weather Vertex i is in the MST
//parent[i]:= stores the edge (i,u) by which u is added to MST
using namespace std;
const intMAXN = 105, INF = INT_MAX/2;
int n;
//Adjacency list representation
struct Edge
{
int to, weight;
Edge()= default;
Edge(int t, int w) :to(t), weight(w)
{
};
//Notice that it‘s ‘>‘ in this occasion, serving as the predicate of pq
friend bool operator<(const Edge &e, const Edge &f)
{
returne.weight > f.weight;
}
};
vector<Edge>edge[MAXN];
int dist[MAXN], parent[MAXN];
bool inMST[MAXN];
void Init()
{
for (int i = 0; i < n; i++)
{
edge[i].clear();
inMST[i] = false;
dist[i] = INF;//vital
parent[i] = -1;
}
}
void AddEdge(int i, int j, int w)
{
edge[i].emplace_back(Edge(j,w));
}
//transforms the adjacency matrix into a adjacency list
void ReadInput()
{
int i,j,w;
for(int a=0;a<n*(n-1)/2;a++)
{
cin>>i>>j>>w;
AddEdge(--i, --j, w);
AddEdge(j,i,w);
}
}
//a utility which counts the total weight of edges in MST
int Prim()
{
int ret = 0;
priority_queue<Edge>pq;
//the source can be any vertex, here we start from Vertex 0
pq.push(Edge(0, 0));
dist[0] = 0;
//totally n-1 edges in MST, because Edge(0,0) is virtual
for (int i = 0; i<n && !pq.empty();)
{
//define variable u for convenience,
//representing the vertex on which the current loop based
int u = pq.top().to;
if (inMST[u])//u is already put in MST
{
pq.pop();
continue;
}
i++;
ret += pq.top().weight; //update ret
inMST[u] = true;//mark it as used
//for-loop to add adjacency edges of u
for (const auto &adj : edge[u])
if (!inMST[adj.to] && adj.weight < dist[adj.to])
{
pq.push(adj);
parent[adj.to] = u;
}
}
return ret;
}
int main()
{
//speeds up cin/cout
cin.tie(nullptr);
ios::sync_with_stdio(false);
while (cin >> n&&n)
{
Init();
ReadInput();
cout << Prim() << endl;
}
return 0;
}
HDU 1233: 還是暢通工程