poj 1984 Navigation Nightmare(帶權並查集+小小的技巧)

來源:互聯網
上載者:User

標籤:tar   targe   方便   pre   題目   str   target   cpp   ios   

題目連結:http://poj.org/problem?id=1984

題意:題目是說給你n個線,並告知其方向,然後對於後面有一些詢問,每個詢問有一個時間點,要求你輸出在該時間點a,b的笛卡爾距離,如果不存在則輸出-1

其實就是將權值分一下x,y,x表示x軸方向的權值,y表示y軸方向的權值。然後最後詢問時稍微有點技巧

可以先記錄一下每次詢問的位置然後再按照時間點從小到大來排序最後這樣就方便並查集了。

 

#include <iostream>#include <cstring>#include <algorithm>#include <cmath>#include <cstdio>using namespace std;const int M = 4e4 + 10;int n , m , f[M] , ans[M];struct TnT {    int x , y , num , pos , sum;    char aim;}root[M] , T[M] , qu[M];bool cmp(TnT a , TnT b) {    return a.num < b.num;}int find(int x) {    if(x == f[x])        return x;    int tmp = find(f[x]);    root[x].x += root[f[x]].x;    root[x].y += root[f[x]].y;    return f[x] = tmp;}void Union(int x , int y , int addx , int addy) {    int a = find(x) , b = find(y);    if(a != b) {        f[a] = b;        root[a].x = root[y].x - root[x].x - addx;        root[a].y = root[y].y - root[x].y - addy;    }}int main() {    int x , y , l , q;    char cp[2];    scanf("%d%d" , &n , &m);    for(int i = 1 ; i <= m ; i++) {        scanf("%d%d%d%s" , &x , &y , &l , cp);        T[i].x = x , T[i].y = y , T[i].sum = l , T[i].aim = cp[0];    }    for(int i = 1 ; i <= n ; i++) {        f[i] = i , root[i].x = 0 , root[i].y = 0;    }    scanf("%d" , &q);    for(int i = 1 ; i <= q ; i++) {        scanf("%d%d%d" , &qu[i].x , &qu[i].y , &qu[i].num);        qu[i].pos = i;    }    sort(qu + 1 , qu + 1 + q , cmp);    int temp = 1;    for(int i = 1 ; i <= q ; i++) {        for(int j = temp ; j <= qu[i].num ; j++) {            x = T[j].x , y = T[j].y , l = T[j].sum;            if(T[j].aim == ‘W‘)                Union(x , y , -l , 0);            if(T[j].aim == ‘E‘)                Union(x , y , l , 0);            if(T[j].aim == ‘N‘)                Union(x , y , 0 , l);            if(T[j].aim == ‘S‘)                Union(x , y , 0 , -l);        }        temp = qu[i].num + 1;        int a = find(qu[i].x) , b = find(qu[i].y);        if(a != b)            ans[qu[i].pos] = -1;        else            ans[qu[i].pos] = abs(root[qu[i].x].x - root[qu[i].y].x) + abs(root[qu[i].x].y - root[qu[i].y].y);    }    for(int i = 1 ; i <= q ; i++) {        printf("%d\n" , ans[i]);    }    return 0;}

poj 1984 Navigation Nightmare(帶權並查集+小小的技巧)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.