Pagini recente » Cod sursa (job #1996245) | Cod sursa (job #1581331) | Cod sursa (job #1731425) | Cod sursa (job #2503397) | Cod sursa (job #1837227)
/**
APM cu algoritmul Prim
**/
#include<bits/stdc++.h>
#define maxN 200005
#define INF INT_MAX
using namespace std;
int cost,n,dp[maxN],m[maxN],seen[maxN],x,y,c,muchii;
vector<pair<int,int> > v[maxN];
typedef struct edge
{
int nod;
int cost;
};
bool operator<(const edge& a,const edge& b)
{
return a.cost>b.cost;
}
priority_queue<edge> q;
void BuildAPM()
{
int nodes=0;
while(nodes<n)
{
int nod=q.top().nod;
int c=q.top().cost;
q.pop();
if(c>dp[nod]) continue;
cost+=c;
seen[nod]=1;
nodes++;
for(vector<pair<int,int> >::iterator it=v[nod].begin();it!=v[nod].end();it++)
{
if(!seen[(*it).first] && dp[(*it).first]>(*it).second)
{
dp[(*it).first]=(*it).second;
m[(*it).first]=nod;
q.push({(*it).first,dp[(*it).first]});
}
}
}
}
int main()
{
freopen("apm.in","r",stdin);
freopen("apm.out","w",stdout);
scanf("%d%d",&n,&muchii);
for(int i=1;i<=muchii;i++)
{
scanf("%d%d%d",&x,&y,&c);
v[x].push_back(make_pair(y,c));
v[y].push_back(make_pair(x,c));
}
for(int i=2;i<=n;i++) dp[i]=INF;
q.push({1,0});
BuildAPM();
printf("%d\n",cost);
printf("%d\n",n-1);
for(int i=2;i<=n;i++)
{
printf("%d %d\n",m[i],i);
}
return 0;
}