Cod sursa(job #1708364)

Utilizator PaulLuchianPaul Luchian PaulLuchian Data 26 mai 2016 22:38:41
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("f.in");
ofstream fout("f.out");

struct muchie
{
       int x,y,c;
};

muchie V[100];
int n,m,A[100][100],P[100],k;

void citire()
{
     fin>>n>>m;
     for(int i=1;i<=m;i++)
        { fin>>V[i].x>>V[i].y>>V[i].c;
          A[V[i].x][V[i].y]=A[V[i].y][V[i].x]=1;
        }
}
int costmu(int i,int j)
{
    for(int k=1;k<=m;k++)
        if((V[k].x==i && V[k].y==j) || (V[k].x==j && V[k].y==i)) return V[k].c;
}
int conex()
{
  int s,d,i,X[100];
  s=d=1;  X[1]=1;  P[1]=1;
  while(s<=d)
  {
	for(int i=1;i<=n;i++)
	if(!P[i] && A[X[s]][i])
	   {d++; X[d]=i; P[i]=1;
	   }
      s++;
  }
  if(d==n) return 1;
  else return 0;
}

void ordonare()
{
    muchie aux;
    for(int i=1;i<m;i++)
        for(int j=i+1;j<=m;j++)
               if(V[i].c<V[j].c)
               {
                   aux=V[i];
                   V[i]=V[j];
                   V[j]=aux;
               }
}

int main()
{
    int i,nrm=0,cost=0,costm=0;
    citire();
    ordonare();
    k=m; i=1;
    while(k>n-1)
    {
	    A[V[i].x][V[i].y]=A[V[i].y][V[i].x]=0;
	    for(int j=1;j<=n;j++) P[j]=0;
	    if(conex()) k--;
	    else A[V[i].x][V[i].y]=A[V[i].y][V[i].x]=1;
       i++;
    }

    for(int i=1;i<=n;i++)
        for(int j=i+1;j<=n;j++)
            if(A[i][j]) {fout<<i<<" "<<j<<" "<<costmu(i,j)<<endl;nrm=nrm+1;costm=costmu(i,j);cost=cost+costm;}
            fout<<"Nr muchii: "<<nrm<<endl;
            fout<<"Cost: "<<cost;
    return 0;
}