codeforces 650C. Table Compression 并查集

题目链接

 

首先想到的应该是排个序然后从小到大填, 每一个填的数应该是这一行和这一列已经有的数的最大值+1。

然后就是处理相同的数, 可以用并查集把它们都并起来, 然后他们的值就一样了, 具体的并查集方法看代码。

 

我的代码参考的http://www.cnblogs.com/qscqesze/p/5253195.html这里

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int mod = 1e9+7;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
const int maxn = 1e6+5;
pair <int, pll> q[maxn];
int ans[maxn], X[maxn], Y[maxn], ansx[maxn], ansy[maxn], f[maxn];
int findd(int u) {
    return u == f[u]?u:f[u] = findd(f[u]);
}
void unionn(int u, int v) {
    u = findd(u), v = findd(v);
    if(u != v)
        f[u] = v;
}
int main()
{
    int n, m;
    cin>>n>>m;
    for(int i = 0; i<n*m; i++) {
        scanf("%d", &q[i].fi);
        f[i] = i;
        q[i].se.fi = i/m;
        q[i].se.se = i%m;
    }
    sort(q, q+n*m);
    int j = -1, x, y, pos;
    for(int i = 0; i<n*m; i++) {
        if(i != n*m-1 && q[i].fi == q[i+1].fi)
            continue;
        for(int k = j+1; k<=i; k++) {
            x = q[k].se.fi, y = q[k].se.se;
            pos = x*m+y;
            X[x] = pos, Y[y] = pos;
        }
        for(int k = j+1; k<=i; k++) {
            x = q[k].se.fi, y = q[k].se.se;
            pos = x*m+y;
            unionn(X[x], pos);
            unionn(Y[y], pos);
        }
        for(int k = j+1; k<=i; k++) {
            x = q[k].se.fi, y = q[k].se.se;
            pos = x*m+y;
            pos = findd(pos);
            ans[pos] = max(ans[pos], max(ansx[x], ansy[y])+1);
        }
        for(int k = j+1; k<=i; k++) {
            x = q[k].se.fi, y = q[k].se.se;
            pos = x*m+y;
            pos = findd(pos);
            ansx[x] = max(ansx[x], ans[pos]);
            ansy[y] = max(ansy[y], ans[pos]);
        }
        j = i;
    }
    for(int i = 0; i<n; i++) {
        for(int j = 0; j<m; j++) {
            printf("%d ", ans[findd(i*m+j)]);
        }
        cout<<endl;
    }
    return 0;
}

 

posted on 2016-03-08 21:10  yohaha  阅读(212)  评论(0编辑  收藏  举报

导航