Pagini recente » Cod sursa (job #1042293) | Cod sursa (job #427467) | Cod sursa (job #2980496) | Cod sursa (job #3257706) | Cod sursa (job #1414477)
#include <fstream>
#include <vector>
#define inf 2e9
#define maxn 2 * 100010
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m, d[maxn], t[maxn], tcost;
vector <pair <int, int> > g[maxn];
bool u[maxn];
void algPrim()
{
int nmin, node;
vector <pair <int, int> > :: iterator it;
for (int i = 2; i <= n; i++)
d[i] = inf;
for (int k = 1; k <= n; k++)
{
nmin = inf;
for (int i = 1; i <= n; i++)
{
if (!u[i] && d[i] < nmin)
{
nmin = d[i];
node = i;
}
}
tcost += nmin;
u[node] = 1;
for (it = g[node].begin(); it != g[node].end(); ++it)
{
int v = it -> first;
int c = it -> second;
if (!u[v] && d[v] > c)
{
d[v] = c;
t[v] = node;
}
}
}
fout << tcost << '\n';
fout << n - 1 << '\n';
for (int i = 2; i <= n; i++)
fout << i << " " << t[i] << '\n';
}
int main()
{
fin >> n >> m;
for (int a, b, c; m; --m)
{
fin >> a >> b >> c;
g[a].push_back(make_pair(b, c));
g[b].push_back(make_pair(a, c));
}
algPrim();
return 0;
}