现在的位置: 首页 > 综合 > 正文

hdu 4941 Magical Forest(hash映射)

2019年08月17日 ⁄ 综合 ⁄ 共 952字 ⁄ 字号 评论关闭

题目链接:hdu 4941 Magical Forest

题目大意:给定N,M和K,表示在一个N*M的棋盘上有K个棋子,给出K个棋子的位置和值,然后是Q次操作,对应的是:

  • 1 a b :交换a和b两行
  • 2 a b : 交换a和b两列
  • 3 a b :查询a b这个位置上棋子的值,没有棋子的话输出0

解题思路:一开始X[i]=iX[j]=j,如果需要交换i和j,那么就令X[i]=j,X[j]=i即可,因为N和M很大,所以用map映射。

#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>

using namespace std;
typedef pair<int, int> pii;
map<pii, int> g;
map<int , int> X;
map<int, int> Y;

int N, M, K;

void init () {
    g.clear();
    X.clear();
    Y.clear();

    int a, b, w;
    scanf("%d%d%d", &N, &M, &K);

    for (int i = 0; i < K; i++) {
        scanf("%d%d%d", &a, &b, &w);
        g[make_pair(a,b)] = w;
    }
}

int get (map<int, int>& u, int x) {
    if (u.count(x))
        return u[x];
    return u[x] = x;
}

int main () {
    int cas, n;
    scanf("%d", &cas);
    for (int kcas = 1; kcas <= cas; kcas++) {
        init();
        scanf("%d", &n);

        printf("Case #%d:\n", kcas);

        int s, a, b;
        for (int i = 0; i < n; i++) {
            scanf("%d%d%d", &s, &a, &b);
            if (s == 1) {
                int p = get(X, a);
                int q = get(X, b);
                swap(X[a], X[b]);
            } else if (s == 2) {
                int p = get(Y, a);
                int q = get(Y, b);
                swap(Y[a], Y[b]);
            } else {
                int p = get(X, a);
                int q = get(Y, b);
                printf("%d\n", g.count(make_pair(p, q)) ? g[make_pair(p, q)] : 0);
            }
        }
    }
    return 0;
}

抱歉!评论已关闭.