Pagini recente » Cod sursa (job #1640255) | Cod sursa (job #402044) | Monitorul de evaluare | Cod sursa (job #2737864) | Cod sursa (job #2420714)
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <bitset>
#include <tuple>
using namespace std;
ifstream fin ("apm.in");
ofstream fout ("apm.out");
const int Inf = 0x3f3f3f3f, MaxN = 200001;
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; //v[x] = 1, daca nodul x e vizitat, altfel v[x] = 0
vector<vector<pair<int, int>>> G;
vector<pair<int, int>> apm;
vector<int> key, t;
long long cost_apm;
void ReadData();
void Prim(int x);
void WriteAPM();
int main()
{
ReadData();
Prim(1);
WriteAPM();
}
void ReadData()
{
int x, y, w, m;
fin >> n >> m;
G = vector<vector<pair<int, int>>>(n + 1);
while (m--)
{
fin >> x >> y >> w;
G[x].emplace_back(y, w);
G[y].emplace_back(x, w);
}
}
void Prim(int x)
{
priority_queue<Edge> Q;
key = vector<int>(n + 1, Inf);
t = vector<int>(n + 1); //retine APM
int y, ky; // ky = cheia lui y
key[x] = 0;
Q.emplace(x, 0);
while (!Q.empty())
{
x = Q.top().node;
v[x] = 1; //true pentru bitset
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' << n - 1 << '\n';
for (size_t i = 1; i <= n; ++i)
fout << apm[i].first << ' ' << apm[i].second << '\n';
}