Advertisement
aimon1337

Prim

May 26th, 2020
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. ifstream fin("date.in");
  5. const int inf=1e9;
  6. int n,m,A[100][100],P[100];
  7. void citire(){
  8.     int i,j,k,c;
  9.     fin>>n>>m;
  10.     for(i=1; i<n; i++)
  11.         for(j=i+1; j<=n; j++)
  12.             A[i][j]=A[j][i]=inf;
  13.     for(int k=1; k<=m; k++){
  14.         fin>>i>>j>>c;
  15.         A[i][j]=A[j][i]=c;
  16.     }
  17. }
  18.  
  19. int main(){
  20.     int ct=0;
  21.     int i,k,minn,x;
  22.     citire();
  23.     for(i=2; i<=n; i++) P[i]=1;
  24.     for(k=1; k<n; k++){
  25.         minn=inf;
  26.         for(i=1; i<=n; i++)
  27.             if(P[i] && A[P[i]][i]<minn){
  28.                 minn=A[P[i]][i];
  29.                 x=i;
  30.             }
  31.         ct+=A[P[x]][x];
  32.         for(i=1; i<=n; i++)
  33.             if(P[i] && A[P[i]][i]>A[i][x])
  34.                 P[i]=x;
  35.         P[x]=0;
  36.     }
  37.     cout<<ct;
  38.     fin.close();
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement