Pagini recente » Cod sursa (job #1312410) | Cod sursa (job #412105) | Cod sursa (job #1104355) | Cod sursa (job #2694542) | Cod sursa (job #648820)
Cod sursa(job #648820)
#include <stdio.h>
#include <set>
#define NMAX 200100
#include <vector>
using namespace std;
struct graf
{
int son, cost;
};
struct cmp
{
bool operator() (const graf val1, const graf val2) const
{
return val1.cost < val2.cost;
}
};
vector <graf> L[NMAX];
bool used [NMAX];
int minCost [NMAX];
multiset <graf, cmp> Q;
inline graf mp (int x, int y)
{
graf now;
now.son = x; now.cost = y;
return now;
}
int main ()
{
int i, N, M, x, y, cost, sum = 0;
vector <graf> :: iterator it;
graf now, aux;
freopen ("apm.in", "r", stdin);
freopen ("apm.out", "w", stdout);
scanf ("%d%d", &N, &M);
for (i = 1; i <= N; i ++)
minCost[i] = 1 << 30;
for (i = 1; i <= M; i ++)
{
scanf ("%d%d%d", &x, &y, &cost);
L[x].push_back (mp (y, cost));
L[y].push_back (mp (x, cost));
}
used[1] = 1;
for (it = L[1].begin (); it != L[1].end(); it ++)
{
now = *it;
Q.insert (*it);
if (now.cost < minCost [now.son])
minCost [now.son] = now.cost;
}
for (i = 1; i < N; i ++)
{
now = *Q.begin ();
if (used[now.son])
{
i --;
Q.erase (Q.begin ());
continue;
}
sum += now.cost;
used[now.son] = 1;
Q.erase (Q.begin ());
for (it = L[now.son].begin (); it != L[now.son].end (); it ++)
{
aux = *it;
if (!used[aux.son])
if (aux.cost < minCost [aux.son])
{
minCost [aux.son] = aux.cost;
Q.insert (*it);
}
}
}
printf ("%d", sum);
return 0;
}