邻接表

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#define MAX 10000

using namespace std;

int cnt;//输入的位置,即从0开始,输入边的序号
int lastshow[MAX];//在输入过程中i上次作为起点时的位置,初始化为-1
int sum;
int vis[MAX];

struct edge{   //边a->b
    int to;    //记录b
    int pro;  //记录a上次作为起点时的边的序号
    int weight;//边的权值
}e[MAX];

void insert(){
    int a, b, weight;
    scanf("%d %d %d", &a, &b, &weight);
    e[cnt].to = b;
    e[cnt].pro = lastshow[a]; //记录以a为起始的上次的边的序号
    e[cnt].weight = weight;
    lastshow[a] = cnt ++; //lastshow变成这次的边的序号
}

int dfs(int a){
    if(vis[a])
        return 0;
//    cout << endl << a << endl;
    vis[a] = 1;
    int ret = 0;
    int id = lastshow[a];
    while(id != -1){
        ret += e[id].weight;
//        cout << endl << e[id].weight << endl;
        ret += dfs(e[id].to);
        id = e[id].pro;
    }
    return ret;
}

int main(){
    int n, c, srch;
    int i, j, k;
    while(cin >> n >> c){
        cnt = 0;
        sum = 0;
        memset(vis, 0, sizeof(vis));
        for(i = 0; i < MAX; i ++){
            lastshow[i] = -1;
        }
        for(i = 0; i < c; i ++){
            insert();
        }
        //找到顶点i连接的所有顶点
        while(~scanf("%d", &srch)){
            if(-1 == srch)
                break;
            int id = lastshow[srch];
            cout << "与点" << srch << "连接到的点和边的权值有:"<<endl;
            while(id != -1){
                cout << e[id].to << " " << e[id].weight << endl;
                id = e[id].pro;
            }
        }
        cout << "所有边的权值和为" << dfs(0) << endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值