Pagini recente » Cod sursa (job #2502728) | Cod sursa (job #951016) | Cod sursa (job #826047) | Cod sursa (job #779708) | Cod sursa (job #2348602)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ofstream fout("apm.out");
const int NMAX = 200005;
struct muchie
{
int from, to, cost;
bool operator < (const muchie other) const
{
return this->cost > other.cost;
}
};
int N, M;
vector < pair<int, int> > G[NMAX];
bool chosen[NMAX];
priority_queue <muchie> pq;
vector <muchie> apmEdges;
long long apmCost;
class InParser
{
private:
FILE *fin;
char *buff;
int sp;
char read_ch()
{
++sp;
if (sp == 4096)
{
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume)
{
fin = fopen(nume, "r");
buff = new char[4096]();
sp = 4095;
}
InParser& operator >> (int &n)
{
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-')
{
n = 0;
sgn = -1;
}
else
{
n = c - '0';
}
while (isdigit(c = read_ch()))
{
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
InParser& operator >> (long long &n)
{
char c;
n = 0;
while (!isdigit(c = read_ch()) && c != '-');
long long sgn = 1;
if (c == '-')
{
n = 0;
sgn = -1;
}
else
{
n = c - '0';
}
while (isdigit(c = read_ch()))
{
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
};
int main()
{
int x, y, c;
InParser fin("apm.in");
fin >> N >> M;
for(int i = 1; i <= M; i++)
{
fin >> x >> y >> c;
G[x].push_back(make_pair(y, c));
G[y].push_back(make_pair(x, c));
}
chosen[1] = true;
for(auto it : G[1])
pq.push({1, it.first, it.second});
for(int i = 2; i <= N; i++)
{
while(chosen[pq.top().to] != false)
pq.pop();
muchie mc = pq.top();
apmCost += mc.cost;
chosen[mc.to] = true;
apmEdges.push_back(mc);
for(auto it : G[mc.to])
if(chosen[it.first] == false)
pq.push({mc.to, it.first, it.second});
}
fout << apmCost << '\n' << N - 1 << '\n';
for(auto it : apmEdges)
fout << it.from << ' ' << it.to << '\n';
return 0;
}