#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;
}
邻接表
最新推荐文章于 2020-09-03 17:04:53 发布