Pagini recente » Cod sursa (job #2072819) | Cod sursa (job #2724019) | Cod sursa (job #3041660) | Cod sursa (job #285020) | Cod sursa (job #2420715)
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <bitset>
#include <tuple>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
const int Inf = 0x3f3f3f3f;
const int MaxN = 200000;
struct Edge{
Edge() : node {0}, key{0}
{}
Edge(int node, int key) : node {node}, key {key}
{}
bool operator < (const Edge& e) const
{
return key > e.key;
}
int node, key;
};
int n;
bitset<MaxN> v;
vector<vector<pair<int, int>>> G;
vector<pair<int, int>> apm;
vector<int> key;
long long cost_apm;
void ReadGraph();
void Prim(int x);
void WriteAPM();
int main()
{
ReadGraph();
Prim(1);
WriteAPM();
}
void ReadGraph()
{
int a, b, w, m;
fin >> n >> m;
G = vector<vector<pair<int, int>>>(n + 1);
while(m--)
{
fin >> a >> b >> w;
G[a].emplace_back(b, w);
G[b].emplace_back(a, w);
}
}
void Prim(int x)
{
priority_queue<Edge> Q;
key = vector<int>(n + 1, Inf);
vector<int> t = vector<int>(n + 1);
int y, ky;
key[x] = 0;
Q.emplace(x, 0);
while(!Q.empty())
{
x = Q.top().node;
v[x] = 1;
for(auto& p : G[x])
{
tie(y, ky) = p;
if(v[y])
continue;
if(key[y] > ky)
{
key[y] = ky;
t[y] = x;
Q.emplace(y, ky);
}
}
apm.emplace_back(x, t[x]);
cost_apm += key[x];
while(!Q.empty() && v[Q.top().node])
Q.pop();
}
}
void WriteAPM()
{
fout << cost_apm << '\n' << apm.size() - 1 << '\n';
for(size_t i = 1; i < apm.size(); ++i)
fout << apm[i].first << ' ' << apm[i].second << '\n';
}