vector建图

//vector建图,顶点是数字,本质是邻接表;二维数组建图,顶点是数字,本质是邻接矩阵
#include<iostream>
#include<vector>
using namespace std;

const int N = 100;
struct Edge{
    int to,value;
}e;
vector<Edge> G[N+1];
int n,m,p;//n为顶点数、m为边数、p表示当前顶点(顶点的符号标志是数字)

int main(){
    cout<<"请输入顶点数、边数:";
    cin>>n>>m;
    cout<<"输入各条边及权重:"<<endl;
    for (int i=0;i<m;i++){
        cin>>p>>e.to>>e.value;
        G[p].push_back(e);
    }
    for (int i=0;i<n;i++){
        for (int j=0;j<G[i].size();j++){
            e=G[i][j];
            cout<<"From "<<i<<" to "<<e.to<<", the cost is "<<e.value<<endl;
        }
    }
    return 0;
}
//请输入顶点数、边数:3 3
//输入各条边及权重:
//0 1 4
//1 2 5
//2 0 6
//From 0 to 1, the cost is 4
//From 1 to 2, the cost is 5
//From 2 to 0, the cost is 6

 

posted @ 2020-07-28 17:49  执着于风  Views(384)  Comments(0)    收藏  举报