Pagini recente » Cod sursa (job #157312) | Cod sursa (job #3138278) | Cod sursa (job #2122046) | Cod sursa (job #1254729) | Cod sursa (job #3323125)
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
#include <ctype.h>
using namespace std;
ofstream g("apm.out");
const int INF = 1e8;
class InParser{
private:
FILE *file_in;
char *buff;
int ebp;
int read_ch(){
++ebp;
if(ebp == 4096){
ebp = 0;
fread(buff, 1, 4096, file_in);
}
return buff[ebp];
}
public:
InParser(const char* file_name){
file_in = fopen(file_name, "r");
buff = new char[4096];
ebp = 4095;
}
template<typename T, typename = typename enable_if<is_integral<T>::value>::type>
InParser& operator>>(T& n){
char ch;
while(!isdigit(ch = read_ch()) && ch != '-');
long long sgn = 1;
long long acc;
if(ch == '-'){
sgn = -1;
acc = 0;
}
else{
acc = ch - '0';
}
while(isdigit(ch = read_ch())){
acc = acc * 10 + (ch - '0');
}
n = static_cast<T>(acc * sgn);
return *this;
}
~InParser(){
fclose(file_in);
delete[] buff;
}
};
vector<pair<int,int>> graf[200001];
int n,m,x,y,c;
void prim_apm(int start){
vector<int> tata(n+1,0);
vector<int> dist(n+1, INF);
vector<int> visited(n+1, 0);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
pq.push(make_pair(0,start));
dist[start] = 0;
long long costAPM = 0;
while(!pq.empty()){
auto [cost,nodCrt] = pq.top();
pq.pop();
if(visited[nodCrt]){
continue;
}
visited[nodCrt] = 1;
costAPM += cost;
for(auto [nod,c]: graf[nodCrt]){
if(visited[nod] == false && c < dist[nod]){
pq.push(make_pair(c,nod));
dist[nod] = c;
tata[nod] = nodCrt;
}
}
}
g << costAPM << '\n';
g << n-1 << '\n';
for(int i=1; i<=n; i++){
if(tata[i] != 0){
g << tata[i] << " " << i << '\n';
}
}
}
int main(){
InParser f("apm.in");
f >> n >> m;
for(int i=0; i<m; i++){
f >> x >> y >> c;
graf[x].push_back(make_pair(y,c));
graf[y].push_back(make_pair(x,c));
}
prim_apm(1);
}