Pagini recente » Cod sursa (job #1948469) | Cod sursa (job #2481040) | Cod sursa (job #1278769) | Cod sursa (job #1680226) | Cod sursa (job #2869818)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
typedef pair < int, int > PII;
const int NMAX = 2e5 + 1;
const int Source = 1;
const int INF = 1e9;
int N, M;
vector < PII > G[NMAX];
int d[NMAX], t[NMAX];
bool Sel[NMAX];
auto cmp = [] (PII A, PII B)
{
if(!(A.first < B.first))
return 1;
return 0;
};
priority_queue < PII, vector < PII >, decltype(cmp) > H(cmp);
static inline void Add_Edge (int x, int y, int c)
{
G[x].push_back({c, y}), G[y].push_back({c, x});
return;
}
static inline void Read ()
{
f.tie(nullptr);
f >> N >> M;
for(int e = 1; e <= M; ++e)
{
int x = 0, y = 0, c = 0;
f >> x >> y >> c;
Add_Edge(x, y, c);
}
return;
}
static inline void Initialize (int Node)
{
for(int i = 1; i <= N; ++i)
if(i == Node)
d[i] = 0, t[i] = 0, Sel[i] = true;
else
d[i] = INF, t[i] = -1, Sel[i] = false;
return;
}
static inline void Expand (int Node)
{
for(auto it : G[Node])
if(it.first < d[it.second])
d[it.second] = it.first, t[it.second] = Node, H.push(it);
return;
}
static inline void Prim (int X)
{
Initialize(X);
Expand(X);
int Total = 0;
while(!H.empty())
{
while(!H.empty() && Sel[H.top().second])
H.pop();
if(H.empty())
break;
PII Top = H.top();
H.pop();
int edge = Top.first, Node = Top.second;
Total += edge;
Sel[Node] = 1;
for(auto it : G[Node])
if(!Sel[it.second] && it.first < d[it.second])
d[it.second] = it.first, t[it.second] = Node, H.push(it);
}
g << Total << '\n' << (N - 1) << '\n';
for(int i = 1; i <= N; ++i)
if(i != X)
g << i << ' ' << t[i] << '\n';
return;
}
int main ()
{
Read();
Prim(Source);
return 0;
}