Pagini recente » Cod sursa (job #340980) | Cod sursa (job #127292) | Cod sursa (job #1813488) | Cod sursa (job #2161217) | Cod sursa (job #2204290)
#include <bits/stdc++.h>
using namespace std;
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;
}
};
class OutParser {
private:
FILE *fout;
char *buff;
int sp;
void write_ch(char ch) {
if (sp == 50000) {
fwrite(buff, 1, 50000, fout);
sp = 0;
buff[sp++] = ch;
} else {
buff[sp++] = ch;
}
}
public:
OutParser(const char* name) {
fout = fopen(name, "w");
buff = new char[50000]();
sp = 0;
}
~OutParser() {
fwrite(buff, 1, sp, fout);
fclose(fout);
}
OutParser& operator << (int vu32) {
if(vu32 == -1){
write_ch('-');
write_ch('1');
} else if (vu32 <= 9) {
write_ch(vu32 + '0');
} else {
(*this) << (vu32 / 10);
write_ch(vu32 % 10 + '0');
}
return *this;
}
OutParser& operator << (char ch) {
write_ch(ch);
return *this;
}
OutParser& operator << (const char *ch) {
while (*ch) {
write_ch(*ch);
++ch;
}
return *this;
}
};
struct edge{
int x, y, c;
bool operator<(const edge &obj)const{
return c >= obj.c;
}
};
int n, m;
bool ok[200005];
priority_queue<edge> q;
vector<edge> v[200005], sol;
edge make_edge(int x, int y, int c)
{
edge aux;
aux.x = x;
aux.y = y;
aux.c = c;
return aux;
}
int main()
{
InParser fin ("apm.in");
OutParser fout ("apm.out");
fin >> n >> m;
for (int i = 1; i <= m; ++i){
int x, y, z;
fin >> x >> y >> z;
v[x].push_back(make_edge(x, y, z));
v[y].push_back(make_edge(x, y, z));
}
for (vector<edge>::iterator it = v[1].begin(); it != v[1].end(); ++it)
q.push(*it);
int apm = 0;
for (int t = 1; t < n; ++t){
while(ok[q.top().x] && ok[q.top().y])
q.pop();
int x = q.top().x, y = q.top().y, c = q.top().c;
sol.push_back(q.top());
apm += c;
q.pop();
if(!ok[x]){
for (vector<edge>::iterator it = v[x].begin(); it != v[x].end(); ++it)
if(!((it->x == x && it->y == y) || (it->y == x && it->x == y)))
q.push(*it);
}
if(!ok[y]){
for (vector<edge>::iterator it = v[y].begin(); it != v[y].end(); ++it)
if(!((it->x == x && it->y == y) || (it->y == x && it->x == y)))
q.push(*it);
}
ok[x] = ok[y] = 1;
}
fout << apm << "\n" << n-1 << "\n";
for (int i = 0; i < n-1; ++i)
fout << sol[i].x << " " << sol[i].y << "\n";
return 0;
}