Pagini recente » Cod sursa (job #2359576) | Cod sursa (job #2515415) | Cod sursa (job #2729304) | Cod sursa (job #1867099) | Cod sursa (job #891658)
Cod sursa(job #891658)
#include<fstream>
#include<algorithm>
#include<vector>
#define inf "apm.in"
#define outf "apm.out"
#define mp make_pair
#define pb push_back
#define maxn 200010
#define INF 1<<30
using namespace std;
ifstream in(inf);
ofstream out(outf);
long long N,M,sum,nr;
vector<pair<int,int> > vect[maxn],apm;
int h[2*maxn+100],poz[maxn],c[maxn],k,tata[maxn];
void read()
{
int i;
for(i=1;i<=M;i++)
{
int x,y,z;
in>>x>>y>>z;
vect[x].pb(mp(y,z));
vect[y].pb(mp(x,z));
}
}
void swap(int x,int y)
{
int aux=h[x];
h[x]=h[y];
h[y]=aux;
poz[h[x]]=x;
poz[h[y]]=y;
}
void upheap(int i)
{
while(i>1 && c[h[i/2]]>c[h[i]])
{
swap(i/2,i);
i=i/2;
}
}
void downheap(int i)
{
int stg,dr,max=i;
stg=2*i;
dr=2*i+1;
if(stg<=k && c[h[stg]]<c[h[i]])
max=stg;
if(dr<=k && c[h[dr]]<c[h[max]])
max=dr;
if(max!=i)
{
swap(max,i);
downheap(max);
}
}
void insert(int i)
{
for(int j=0;j<vect[i].size();j++)
{
int nod=vect[i][j].first;
int cost=vect[i][j].second;
c[nod]=min(c[nod],cost);
if(c[nod]==cost) tata[nod]=i;
}
}
void insert_heap(int i)
{
h[++k]=i;
poz[i]=k;
upheap(k);
}
int extract_min()
{
int root=h[1];
swap(1,k);
k--;
downheap(1);
poz[root]=0;
return root;
}
int main()
{
in>>N>>M;
read();
int i;
for(i=1;i<=N;i++)
c[i]=INF;
c[1]=0;
insert(1);
for(i=2;i<=N;i++)
{
insert_heap(i);
}
for(i=1;i<N;i++)
{
int nod=extract_min();
insert(nod);
sum+=c[nod];
apm.pb(mp(tata[nod],nod));
for(int j=0;j<vect[nod].size();j++)
{
int vertex=vect[nod][j].first;
if(poz[vertex]) upheap(poz[vertex]);
}
}
out<<sum<<"\n"<<N-1<<"\n";
for(i=0;i<apm.size();i++)
out<<apm[i].first<<" "<<apm[i].second<<"\n";
return 0;
}