#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;
}
邻接表
最新推荐文章于 2025-08-03 15:28:47 发布
本文介绍了一个基于C++实现的图的深度优先遍历算法。通过定义边结构体和使用数组来存储边和顶点信息,实现了图的构建,并通过深度优先搜索(DFS)算法计算了所有边的权值之和。
3135

被折叠的 条评论
为什么被折叠?



