POJ 1984 Navigation Nightmare 二維帶權並查集

來源:互聯網
上載者:User

標籤:http   io   for   html   ar   htm   amp   size   

題目來源:POJ 1984 Navigation Nightmare

題意:給你一顆樹 k次詢問 求2點之間的曼哈頓距離 並且要在只有開始k條邊的情況下

思路:按照方向 我是以左上方為根 左上方為原點 dx[i]為i點距離根的x座標 dy[]是y座標 這兩個可以通過路徑壓縮求出 只不過是二維而已

#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;const int maxn = 40010;int f[maxn], dx[maxn], dy[maxn];struct node{int u, v, w;char s[3];}a[maxn];void init(int n){for(int i = 1; i <= n; i++)f[i] = i;memset(dx, 0, sizeof(dx));memset(dy, 0, sizeof(dy));}int find(int x){if(x != f[x]){int rt = find(f[x]);dx[x] += dx[f[x]];dy[x] += dy[f[x]];f[x] = rt;return rt;}return x;}int main(){int n, m;scanf("%d %d", &n, &m);init(n);for(int i = 1; i <= m; i++){scanf("%d %d %d %s", &a[i].u, &a[i].v, &a[i].w, a[i].s);}int q;scanf("%d", &q);int i = 1;while(q--){int s, e, w;scanf("%d %d %d", &s, &e, &w);while(i <= m && i <= w){int u = a[i].u;int v = a[i].v;int x = find(u);int y = find(v);if(x == y)continue;if(a[i].s[0] == 'E'){f[y] = x;dx[y] = dx[u]-dx[v]+a[i].w;dy[y] = dy[u]-dy[v];}else if(a[i].s[0] == 'W'){f[x] = y;dx[x] = dx[v]-dx[u]+a[i].w;dy[x] = dy[v]-dy[u];}else if(a[i].s[0] == 'N'){f[x] = y;dy[x] = dy[v]-dy[u]+a[i].w;dx[x] = dx[v]-dx[u];}else{f[y] = x;dy[y] = dy[u]-dy[v]+a[i].w;dx[y] = dx[u]-dx[v];}i++;}int x = find(s);int y = find(e);if(x == y){int d = abs(dx[s]-dx[e]) + abs(dy[s]-dy[e]);printf("%d\n", d);}else{puts("-1");}}return 0;}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.