Skip to main content

Weighted graph using stl

#include<bits/stdc++.h>
using namespace std;
void add_edge(vector<pair<int,int>> adj[],int u,int v,int wt)
{
    adj[u].push_back(make_pair(v,wt));
    adj[v].push_back(make_pair(u,wt));
}
void print_graph(vector<pair<int,int>> adj[],int V)
{
    int v,w;
    for(int i=0;i<V;i++)
    {
        cout<<"Node "<<i<<" makes an edge with"<<endl;
        for(auto it=adj[i].begin();it!=adj[i].end();it++)
        {
            v=it->first;
            w=it->second;
            cout<<"node "<<v<<"with weight "<<w<<endl;
        }
        cout<<endl;
    }
}
int main()
{
    int V;
    cin>>V;
    vector<pair<int,int>> adj[V];
    while(1)
    {
        int x,y,w;
        cout<<"Enter the nodes and weight"<<endl;
        cin>>x>>y>>w;
        add_edge(adj,x,y,w);
        cout<<"Enter -1 to exit"<<endl;
        int t;
        cin>>t;
        if(t==-1)
            break;
    }
    print_graph(adj,V);
    return 0;
}

Comments