hdu 2586 How far away ?
程序员文章站
2022-03-23 14:05:31
...
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
struct Edge{
int v,cost;
Edge(int _v=0,int _cost=0):v(_v),cost(_cost){
}
};
vector<Edge> mp[40004];
int vis[40004],s,e,flag;
void addEdge(int from,int to,int cost){
mp[from].push_back(Edge(to,cost));
mp[to].push_back(Edge(from,cost));
}
void dfs(int t, int dis)
{
if(mp[t].empty()) //注意判断是否为空
return;
if(t == e) //到达终点
{
flag = 1;//找到终点
cout<<dis<<endl;
}
int size = mp[t].size();
for(int j=0; j<size; j++)
{
if(!vis[mp[t][j].v])
{
vis[mp[t][j].v] = 1;
dfs(mp[t][j].v, dis + mp[t][j].cost);
if(flag)
return;
vis[mp[t][j].v] = 0;
}
}
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,m;
scanf("%d%d",&n,&m);
for(int i=0;i<n-1;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
addEdge(a,b,c);
}
for(int i=1; i<=m; i++)
{
memset(vis, 0, sizeof(vis));
flag = 0;
scanf("%d %d",&s,&e);
vis[s] = 1;
dfs(s, 0);
}
for(int i=0; i<n; i++)
{
mp[i].clear();
}
}
return 0;
}
下一篇: Stack in C++ STL