Pagini recente » Cod sursa (job #1303063) | Cod sursa (job #711759) | Cod sursa (job #358379) | Cod sursa (job #1667703) | Cod sursa (job #2273308)
#include <bits/stdc++.h>
#define MaxN 200005
#define inf (int)(2e9+5)
#define int_pair std::pair <int, int>
#define mp std::make_pair
std::ifstream InFile("apm.in");
std::ofstream OutFile("apm.out");
int N, M, Ans;
std::map <int, int> Edge[MaxN];
std::vector <int_pair> ADC[MaxN];
int Parent[MaxN],
Key[MaxN];
bool InMST[MaxN];
void Prim(int Source = 1) {
for (int i=0; i<N; ++i)
Parent[i+1] = 0,
Key[i+1] = inf;
struct PrimData {
int Value;
bool operator < (const PrimData &Other) const {
return Key[Value] > Key[Other.Value];
}
}; std::priority_queue <PrimData> PQ;
PQ.push({Source});
Key[Source] = 0;
int Top;
while (!PQ.empty()) {
Top = PQ.top().Value;
PQ.pop();
InMST[Top] = 1;
for (auto Edge:ADC[Top]) {
if (!InMST[Edge.first] && Key[Edge.first] > Edge.second)
Key[Edge.first] = Edge.second,
Parent[Edge.first] = Top,
PQ.push({Edge.first});
}
}
}
void Citire() {
InFile >> N >> M;
for (int i=0, x, y, c; i<M; ++i)
InFile >> x >> y >> c,
ADC[x].push_back(mp(y, c)),
ADC[y].push_back(mp(x, c)),
Edge[x][y] = c;
}
void Rezolvare() {
Prim();
int Sum = 0;
for (int i=0; i<N; ++i)
Sum += Key[i+1];
OutFile << Sum << '\n';
for (int i=0; i<N; ++i)
if (Parent[i+1])
OutFile << i+1 << ' ' << Parent[i+1] << '\n' ;
}
int main()
{
Citire();
Rezolvare();
return 0;
}