Pagini recente » Cod sursa (job #1636635) | Cod sursa (job #1930201) | Cod sursa (job #2484421) | Cod sursa (job #2089238) | Cod sursa (job #726964)
Cod sursa(job #726964)
#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<<29
using namespace std;
ifstream in(inf);
ofstream out(outf);
int N,M,sum,nr;
vector<pair<int,int> > vect[maxn],apm;
int h[maxn],poz[maxn],c[maxn],k,tata[maxn];
bool parc[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,i/2);
i=i/2;
}
}
void downheap(int i)
{
int stg,dr,max=i;
stg=2*i+1;
dr=2*i;
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);
upheap(max);
}
}
int main()
{
in>>N>>M;
read();
int i;
for(i=1;i<=N;i++)
c[i]=INF;
tata[1]=0;
parc[1]=true;
for(i=2;i<=N;i++)
{
h[++k]=i;
poz[i]=k;
}
for(i=0;i<vect[1].size();i++)
{
int nod=vect[1][i].first;
int cost=vect[1][i].second;
c[nod]=cost;
tata[nod]=1;
swap(poz[nod],k);
upheap(k);
}
for(i=1;i<=N;i++)
{
int root=h[1];
swap(1,k);
k--;
downheap(1);
if(parc[root]==true)
continue;
parc[root]=true;
apm.pb(mp(tata[root],root));
sum+=c[root];
nr++;
for(int j=0;j<vect[root].size();j++)
{
int nod=vect[root][j].first;
int cost=vect[root][j].second;
if(parc[nod]==false)
if(cost<c[nod])
{
c[nod]=cost;
tata[nod]=root;
swap(poz[nod],k);
upheap(k);
}
}
}
out<<sum<<"\n"<<nr<<"\n";
for(i=0;i<apm.size();i++)
out<<apm[i].first<<" "<<apm[i].second<<"\n";
return 0;
}