首页 文章

邻接列表使用向量和对的图表表示

提问于
浏览
4

我想从书籍竞争性编程实现邻接列表图形表示1.实现使用V顶点的向量并且对于每个顶点v,另一个包含与vI am连接的(相邻顶点和它的边缘权重)对的向量有问题需要输入此图表并显示输出 .

在书中,他们做了这样的宣言:

#include <iostream>
#include <vector>
using namespace std;
typedef pair<int, int> ii;
typedef vector<ii> vii;
vector <vii> AdjList;

我应该如何将以下图形的输入作为邻接列表并输出它的邻接列表表示?假设边缘的每个成本是10 .

Various representation of graphs http://img35.imageshack.us/img35/8370/edrp.png

1 回答

  • 8

    如果我们想要使用图形邻接实现以n个顶点和m个边缘的形式读取图形输入 .

    #include<iostream>
    #include<vector>
    using namespace std;
    typedef vector<int> vi;
    typedef pair<int,int> ii;
    typedef vector<ii> vii;
    
    int main()
    {
       int n,m ; 
       cin>>n>>m;
       vector<vii> adjList(n+1); //For vertex 1...n
       //Reading edges for the input for graph
       for(int i=0;i<m;i++)
       {
          int u,v;
          cin>>u>>v;
        /*Here u->v is the edge and pair second term can be used to store weight in
          case of weighted graph.
        */
          adjList[u].push_back(make_pair(v,10));
       }
       //To print the edges stored in the adjacency list
       for(int i=1;i<=n;i++)
       {
           for(int j=0;j<(int)adjList[i].size();j++)
           {
               cout<<"Edge is "<<i<<" -> "<<adjList[i][j].first<<endl;
               cout<<"Weight is "<<adjList[i][j].second<<endl;
           }
       }
       return 0;
    }
    

相关问题