Prims Algorithm

#include <iostream>
#include <queue>
#include <vector>
#define INF 100000
using namespace std;

struct edge{
    vector <int> Adj;
    vector <int> Cost;
};

struct node{
    int x,y;
};

edge Ed[100];
int N,E;
int key[100];
char F[100];
int P[100], Cost;
int SS[100][100];

class comp{
    public:
    bool operator()(const node &a, const node &b){
        return a.y>b.y;
    }
};

void CT(int u){
    if(F[u]==1||u==1) return;
    F[u]=1;
    if(P[u]==-1) return;
    Cost+=SS[u][P[u]];
    CT(P[u]);
}

int Prim(){
    int i,j,u,v,c,cost;
    Cost=0;
    priority_queue<node, vector<node>, comp>Q;
    node temp, dum;
    for(i=1;i<=N;i++) key[i]=INF;
    key[1]=0;
    temp.x=1;
    temp.y=0;
    Q.push(temp);
    P[1]=-1;
    while(!Q.empty()){
        temp=Q.top();
        Q.pop();
        u=temp.x;
        F[u]=1;
        for(i=0;i<Ed[u].Adj.size();i++){
            v=Ed[u].Adj[i];
            c=Ed[u].Cost[i]+temp.y;
            if(F[v]==0){
                if(key[v]>c){
                    dum.x=v;
                    dum.y=c;
                    key[v]=c;
                    P[v]=u;
                    Q.push(dum);
                }
            }
        }
    }
    for(i=1;i<=N;i++) F[i]=0;
    for(i=1;i<=N;i++){
        if(F[i]==0)
            CT(i);
    }
    return Cost;
}

int main()
{
    int c,u,v,n;
    cin>>N>>E;
    n=E;
    while(n--)
    {
        cin>>u>>v>>c;
        Ed[u].Adj.push_back(v);
        Ed[u].Cost.push_back(c);
        Ed[v].Adj.push_back(u);
        Ed[v].Cost.push_back(c);
        SS[u][v]=SS[v][u]=c;
    }
    cout<<Prim()<<endl;
}

No comments:

Post a Comment