标签:roo therefore rop name 0ms mis vector i++ nts
任意门:http://poj.org/problem?id=1986
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 16648 | Accepted: 5817 | |
Case Time Limit: 1000MS |
Description
Input
Output
Sample Input
7 6 1 6 13 E 6 3 9 E 3 5 7 S 4 1 3 N 2 4 20 W 4 7 2 S 3 1 6 1 4 2 6
Sample Output
13 3 36
Hint
输入:
第一行输入结点数 N 和 边数 M。
接下来 M 行输入边的信息:起点 u 终点 v 距离 w 方向 s
输入查询数 K
接下来 K 行 输入查询值: 起点 u,终点 v;
一个有向无环图,当作一棵树来处理,根结点随意,假设为 1;
LCA 两点最短距离 老套路。
AC code:
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <vector> 5 #include <cstring> 6 #define INF 0x3f3f3f3f 7 #define LL long long 8 using namespace std; 9 const int MAXN = 5e5+5; 10 struct Edge{int v, w, nxt;}edge[MAXN<<1]; 11 struct Query 12 { 13 int v, id; 14 Query(){}; 15 Query(int _v, int _id):v(_v),id(_id){}; 16 }; 17 vector<Query> q[MAXN]; 18 19 int head[MAXN], cnt; 20 int dis[MAXN]; 21 int fa[MAXN]; 22 bool vis[MAXN]; 23 int ans[MAXN]; 24 int N, M, K; 25 26 void init() 27 { 28 memset(vis, false, sizeof(vis)); 29 memset(head, -1, sizeof(head)); 30 memset(dis, 0, sizeof(dis)); 31 memset(ans, 0, sizeof(ans)); 32 for(int i = 0; i <= N; i++) q[i].clear(); 33 cnt = 0; 34 } 35 36 int getfa(int x){return fa[x]==x?x:fa[x]=getfa(fa[x]);} 37 38 void AddEdge(int from, int to, int weight) 39 { 40 edge[cnt].v = to; 41 edge[cnt].w = weight; 42 edge[cnt].nxt = head[from]; 43 head[from] = cnt++; 44 } 45 46 void dfs(int s, int f) 47 { 48 int root = s; 49 for(int i = head[s]; i != -1; i = edge[i].nxt){ 50 if(edge[i].v == f) continue; 51 dis[edge[i].v] = dis[root] + edge[i].w; 52 dfs(edge[i].v, s); 53 } 54 } 55 56 void Tarjan(int s, int f) 57 { 58 int root = s; 59 fa[s] = s; 60 for(int i = head[s]; i != -1; i = edge[i].nxt){ 61 int Eiv = edge[i].v; 62 if(Eiv == f) continue; 63 Tarjan(Eiv, root); 64 fa[getfa(Eiv)] = root; 65 } 66 vis[s] = true; 67 for(int i = 0; i < q[s].size(); i++){ 68 if(vis[q[s][i].v] && ans[q[s][i].id] == 0){ 69 ans[q[s][i].id] = dis[q[s][i].v] + dis[s] - 2*dis[getfa(q[s][i].v)]; 70 } 71 } 72 } 73 74 int main() 75 { 76 scanf("%d%d", &N, &M); 77 init(); 78 char s; 79 for(int i = 1, u, v, w; i <= M; i++){ 80 scanf("%d%d%d %c", &u, &v, &w, &s); 81 AddEdge(u, v, w); 82 AddEdge(v, u, w); 83 } 84 scanf("%d", &K); 85 for(int i = 1, u, v; i <= K; i++){ 86 scanf("%d%d", &u, &v); 87 q[u].push_back(Query(v, i)); 88 q[v].push_back(Query(u, i)); 89 } 90 dfs(1, -1); 91 Tarjan(1, -1); 92 for(int i = 1; i <= K; i++){ 93 printf("%d\n", ans[i]); 94 } 95 return 0; 96 }
POJ 1986 Distance Queries 【输入YY && LCA(Tarjan离线)】
标签:roo therefore rop name 0ms mis vector i++ nts
原文地址:https://www.cnblogs.com/ymzjj/p/9749641.html