I am implementing a simple version of Prim's algorithm using adjacency list using basic graph implementation idea.Here is my approach for this algorithm-
1.Pick an index.
2.Inside the Prims function,mark the index as visited.
3.If any adjacent vertex is not visited and cost of that vertex is less than mi(which is initialized as INF at the start of the function) then mi stores the cost and parent stores the index.
4.At the last adjacent vertex mi stores the smallest cost and parent stores the smallest cost index.
5.Again call the prims for parent vertex.
6.At last return the total cost.
But the problem in my approach is when I am comparing cost[v] with mi then it gives me an error cause I am comparing int with vector.I have tried using mi as a vector but then it gives me error in result section.My code is given below-
#include<bits/stdc++.h>
using namespace std;
#define mx 10005
#define INF 1000000007
vector<int>graph[mx],cost[mx];
int visited[mx]={0};
int result=0,parent;
int n,e,x,y,w,mi;
int prims(int u)
{
mi=INF;
visited[u]=1;
for(int i=0;i<graph[u].size();++i)
{
int v=graph[u][i];
if(visited[v]==0 and cost[v]<mi)
{
mi=cost[v];
parent=v;
}
if(i==graph[u].size()-1)
{
result+=mi;
prims(parent);
}
}
return result;
}
int main()
{
cin>>n>>e;
for(int i=1;i<=e;++i)
{
cin>>x>>y>>w;
graph[x].push_back(y);
graph[y].push_back(x);
cost[x].push_back(w);
cost[y].push_back(w);
}
int src;cin>>src;
int p=prims(src);
cout<<p<<endl;
return 0;
}