标签:dfs
2 3 2 1 2 10 3 1 15 1 2 2 3 2 2 1 2 100 1 2 2 1
10 25 100 100
#include <iostream> #include <cstring> #include <vector> #include <cstdio> using namespace std; const int M = 4 * 1e4 + 100; typedef long long ll; typedef pair<int,int> P; vector<P>G[M]; int vis[M],isGO,e; void dfs(int x, int cost) { if(isGO || vis[x]) return ; if(x == e)//数据太大,要改成全局变量 { isGO = 1; printf("%d\n",cost); return ; } vis[x] = 1; for(int i = 0; i < G[x].size(); i++) { P a = G[x][i]; dfs(a.first,cost + a.second); } vis[x] = 0; } void solve() { int x,y,c,n,m; scanf("%d %d",&n,&m); for(int i = 1; i < n; i++) { scanf("%d %d %d",&x,&y,&c); G[x].push_back(make_pair(y,c)); G[y].push_back(make_pair(x,c)); } while(m--) { isGO = 0; scanf("%d %d",&x,&e); dfs(x,0); } for(int i = 1; i <= n; i++) G[i].clear(); } int main() { int T,cnt = 0; scanf("%d",&T); while(T--) { solve(); } return 0; }
标签:dfs
原文地址:http://blog.csdn.net/zsgg_acm/article/details/39717533