STL存储邻接表

用到了c++的STL 来存储邻接表

参考网站:https://www.cnblogs.com/yzm10/p/7235501.html

/*
    STL中的vector实现邻接表
    2020.4.27
    参考网址:https://www.cnblogs.com/yzm10/p/7235501.html
*/

#include <iostream>
#include <vector>
#include <cstdlib>
#define MAX 10000
using namespace std;

struct EdgeNode{ //边表节点类型
    int to, w; //顶点序号和边长
};
vector<EdgeNode> map[MAX];

int main(){
    EdgeNode e;
    int n, m, i, j, k, w;
    cin >> n >> m; //n个顶点m组数据

    for(i = 0; i < m; ++i){
        cin >> j >> k >> w;
        e.to = k; e.w = w;
        map[j].push_back(e);
    }

    //遍历
    for(i = 1; i <= n; ++i){
        for(vector<EdgeNode>:: iterator k = map[i].begin();
        k != map[i].end(); ++k){
            EdgeNode t = *k;
            cout << i << ' ' << t.to << ' ' << t.w << endl;
        }
    }
    system("pause");
    return 0;
}

强化训练 

 QDUOJ 生化危机 邻接表+BFS

参考网址 https://www.cnblogs.com/yzm10/p/7236210.html

#include<stdio.h>
#include<string.h>
#include<vector>
#include<queue>

using namespace std;

struct Node{
    int x,s;//s表示第几天感染的城市数量
}node;

int main()
{
    int t,n,k,x,y,tx,cc,c,i;
    int a[10005],b[10005];
    queue<Node> q;
    vector<int> v[10005];
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&k);
        for(i=1;i<=n;i++){
            v[i].clear();
        }
        for(i=1;i<n;i++){
            scanf("%d%d",&x,&y);
            v[x].push_back(y);
            v[y].push_back(x);
        }
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        b[k]=1;
        node.x=k;
        node.s=1;
        q.push(node);
        cc=0;c=1;
        while(q.size()){
            if(a[q.front().s]==0){
                a[++cc]=c;
                c=0;
            }
            for(i=0;i<v[q.front().x].size();i++){   //切记从0开始
                tx=v[q.front().x][i];
                if(b[tx]==0){
                    c++;
                    b[tx]=1;
                    node.x=tx;
                    node.s=q.front().s+1;
                    q.push(node);
                }
            }
            q.pop();
        }
        printf("%d\n",cc);
        for(i=1;i<=cc;i++){
            printf("%d ",a[i]);
        }
        printf("\n");
    }
    return 0;
}

 

 

posted @ 2020-04-27 10:14  someonezero  阅读(224)  评论(0编辑  收藏  举报