Codeforces 650C Table Compression

链接

传送门

题意

给出\(n \times m, (1 \leq n, m, n \dot m \leq 1000000)\)的矩阵,对其进行处理,用正整数替换矩阵中数值,使得原本每行和每列中数的大小关系不变,且矩阵中的最大元素最小。

思路

分别对列和行进行处理,对于每个阶段储存与其相邻的比它小或相等的元素。对元素排序后,对于每一个未赋值的元素,找出所有和它相等的在同一行或同一列的元素,对于所有找出的元素求比它们小的元素的最大值。

Tutorial里称这种做法为“lazy computations”。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
using namespace std;

const int maxn = 1000010;
bool vis[maxn];
int a[maxn], x[maxn], ans[maxn];
vector<int> eq[maxn], mr[maxn];
struct node {
int v, id;
void Set(int x) {
id = x;
v = a[id];
}
bool operator < (const node& rhs) const {
return v < rhs.v || (v == rhs.v && id == rhs.id);
}
} b[maxn];

int main() {
int n, m;
scanf("%d%d", &n, &m);
int num = n * m;
for (int i = 0; i < num; ++i) {
scanf("%d", &a[i]);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
b[j].Set(i * m + j);
}
sort(b, b + m);
for (int j = 1; j < m; ++j) {
int x = b[j].id;
int y = b[j - 1].id;
if (b[j].v == b[j - 1].v) {
eq[x].push_back(y);
eq[y].push_back(x);
} else {
mr[x].push_back(y);
}
}
}
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i) {
b[i].Set(i * m + j);
}
sort(b, b + n);
for (int i = 1; i < n; ++i) {
int x = b[i].id;
int y = b[i - 1].id;
if (b[i].v == b[i - 1].v) {
eq[x].push_back(y);
eq[y].push_back(x);
} else {
mr[x].push_back(y);
}
}
}
for (int i = 0; i < num; ++i) {
b[i].Set(i);
}
sort(b, b + num);
for (int i = 0; i < num; ++i) {
int id = b[i].id;
if (vis[id]) {
continue;
}
x[0] = id;
vis[id] = true;
int s = 0, e = 0;
while (s <= e) {
for (int u: eq[x[s]]) {
if (!vis[u]) {
x[++e] = u;
vis[u] = true;
}
}
++s;
}
++e;
int put = 0;
for (int j = 0; j < e; ++j) {
for (int v: mr[x[j]]) {
put = max(put, ans[v]);
}
}
++put;
for (int j = 0; j < e; ++j) {
ans[x[j]] = put;
}
}
num = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
printf("%d ",ans[num++]);
}
puts("");
}
return 0;
}