How far away ? 【HDU - 2586】【DFS+鏈式前向星優化】
阿新 • • 發佈:2018-11-20
題目連結
其實這道題可以不用鏈式前向星優化換做vector<>也是可以跑的,只是會許會慢些而已。
來換個中文題意好讀些:
勇氣小鎮是一個有著n個房屋的小鎮,為什麼把它叫做勇氣小鎮呢,這個故事就要從勇氣小鎮成立的那天說起了,
修建小鎮的時候,為了讓小鎮有特色,鎮長特地只修了n-1條路,並且規定說,所有在勇氣小鎮的村民,每一次出門必須規劃好路線,
路線必須滿足在到達終點之前絕對不走回頭路。每個人都要這樣,不然那個人就不配在小鎮生活下去,因為他沒有這個勇氣。
事實上,這並不能算一項挑戰,因為n-1條路已經連通了每戶人家,不回頭地從起點到終點,只是一個時間上的問題。
由於小鎮上的福利特別好,所以小懶入住了這個小鎮,他規劃了m次的行程,每次從L房屋到R房屋,他想問你他每次從L房屋到R房屋需要走多遠的路。
Input
輸入的第一行是一個整數t,表示有t組資料
每組資料第一行是n,m兩個數字,分別表示小鎮上房屋的個數,和小懶計劃的行程的數量。
之後第2行到第n行,每行三個整數a,b,c表示,a房屋與b房屋之間連線著一條距離為c的小路。
第n+1行到第n+m行,每行兩個整數,L,R,代表一次小懶的詢問,也就是詢問小懶從L房屋走到R房屋所走的最近距離為多少。
Output
對於每組測試資料輸出m行,每行一個整數,代表小懶從詢問的L到R需要走的最近的距離
直接DFS去搜索何時能抵達目標節點即可,畢竟只有M條邊的上限的嘛,時間複雜度一定是可以跑的。
#include <iostream> #include <cstdio> #include <cmath> #include <string> #include <cstring> #include <algorithm> #include <limits> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #define lowbit(x) ( x&(-x) ) #define pi 3.141592653589793 #define e 2.718281828459045 using namespace std; typedef unsigned long long ull; typedef long long ll; const int maxN=40005; int N, M, head[maxN], cnt; bool vis[maxN]; struct Eddge { int next, to, val; Eddge(int a=-1, int b=0, int c=0):next(a), to(b), val(c) {} }edge[maxN<<1]; void addEddge(int u, int v, int val) { edge[cnt] = Eddge(head[u], v, val); head[u] = cnt++; } void init() { cnt = 0; memset(head, -1, sizeof(head)); } bool flag; void dfs(int now, int ed, ll cost) { if(flag || vis[now] || head[now]==-1) return; vis[now] = true; if(now == ed) { printf("%lld\n", cost); flag=true; return; } for(int u=head[now]; u!=-1; u=edge[u].next) { dfs(edge[u].to, ed, cost+edge[u].val); } } int main() { int T; scanf("%d", &T); while(T--) { scanf("%d%d", &N, &M); init(); for(int i=1; i<=N-1; i++) { int e1, e2, e3; scanf("%d%d%d", &e1, &e2, &e3); addEddge(e1, e2, e3); addEddge(e2, e1, e3); } for(int i=1; i<=M; i++) { int l, r; scanf("%d%d", &l, &r); memset(vis, false, sizeof(vis)); flag = false; dfs(l, r, 0); } } return 0; }