POJ - 1984 Navigation Nightmare(带权并查集维护两个d值)

题目链接

思路:
带权并查集维护两个权,此时有两个距离需要维护,dx表示横坐标距离,dy表示纵坐标距离,
东为x方向权值 +w,南为y方向 +w,西为x方向 -w,北为y方向 -w,
因为题目要求的查询是依据前c行的并查集构建程度查询的,所以可以先把所有构建并查集数据和查询数据输入存起来,将查询数据以c的大小升序排序,遍历m行并查集构建数据,当此时idx指向的查询数据c与i相等时就查询并记录答案,最后将查询数据按输入顺序降序排序输出即可。
神奇的一A了,跑了125s,但是那个abs函数编译器不知为啥一直报错

代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const int N = 5e4 + 10;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

int n, m;
int f[N], dx[N], dy[N];
struct node1
{
    int x, y, l;
    char d;
} a[N];
struct node2
{
    int id, x, y, c, ans;
} b[N];
bool cmp1(node2 x, node2 y)
{
    return x.c < y.c;
}
bool cmp2(node2 x, node2 y)
{
    return x.id < y.id;
}
int find(int x)
{
    if (f[x] != x)
    {
        int u = find(f[x]);
        dx[x] += dx[f[x]], dy[x] += dy[f[x]];
        f[x] = u;
    }
    return f[x];
}

int main()
{
    while (cin >> n >> m)
    {
        for (int i = 1; i <= n; i++)
            f[i] = i;
        for (int i = 1; i <= m; i++)
            scanf("%d%d%d %c", &a[i].x, &a[i].y, &a[i].l, &a[i].d);
        int k;
        cin >> k;
        for (int i = 1; i <= k; i++)
        {
            b[i].id = i;
            scanf("%d%d%d", &b[i].x, &b[i].y, &b[i].c);
        }
        sort(b + 1, b + k + 1, cmp1);
        int idx = 1;
        for (int i = 1; i <= m; i++)
        {
            int x = a[i].x, y = a[i].y, w = a[i].l, wx, wy;
            char op = a[i].d;
            if (op == 'N')
            {
                wx = 0;
                wy = -w;
            }
            else if (op == 'S')
            {
                wx = 0;
                wy = w;
            }
            else if (op == 'W')
            {
                wx = -w;
                wy = 0;
            }
            else
            {
                wx = w;
                wy = 0;
            }
            int f1 = find(x), f2 = find(y);
            if (f1 != f2)
            {
                f[f2] = f1;
                dx[f2] = dx[x] + wx - dx[y];
                dy[f2] = dy[x] + wy - dy[y];
            }
            while (b[idx].c == i)
            {
                int x = b[idx].x, y = b[idx].y;
                int f1 = find(x), f2 = find(y);
                if (f1 == f2)
                {
                    b[idx].ans = 0;
                    b[idx].ans += abs(dx[x] - dx[y]);
                    b[idx].ans += abs(dy[x] - dy[y]);
                }
                else
                    b[idx].ans = -1;
                idx++;
            }
        }
        sort(b + 1, b + k + 1, cmp2);
        for (int i = 1; i <= k; i++)
            cout << b[i].ans << endl;
    }

    return 0;
}

你可能感兴趣的:(刷题记录,算法)