-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathE.cpp
136 lines (108 loc) · 2.72 KB
/
E.cpp
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <bits/stdc++.h>
typedef long long ll;
#define all(c) (c).begin(), (c).end()
#define pb push_back
#define FOR(i,a,b) for( ll i = (ll)(a); i <= (ll)(b); i++ )
#define ROF(i,a,b) for( ll i = (ll)(a); i >= (ll)(b); i-- )
#define debug(x) cerr << "[DEBUG] " << #x << " = " << x << endl;
#define F first
#define S second
#define INPFILE freopen("input.in","r",stdin)
#define BOOST ios_base::sync_with_stdio(false); cin.tie(NULL)
using namespace std;
ll n, m;
inline ll id( ll i, ll j ) {
return (i-1)*m + (j-1) + 1;
}
ll parent[1000005];
ll ans[1000005];
ll out[1000005];
ll in[1000005];
vector<ll> v[1000005];
ll find( ll x ) {
if( parent[x] == x )
return x;
return parent[x] = find( parent[x] );
}
void join( ll x, ll y ) {
ll p = find(x);
ll q = find(y);
if( p == q ) return;
parent[p] = q;
}
int main() {
BOOST;
cin >> n >> m;
ll a[n+1][m+1];
memset( a, 0, sizeof a );
FOR(i,1,n)
FOR(j,1,m) {
cin >> a[i][j];
parent[ id(i,j) ] = id(i,j);
}
FOR(i,1,n) {
set< pair<ll,ll> > idx;
pair<ll,ll> last = { -1, -1 };
FOR(j,1,m)
idx.insert( { a[i][j], find( id(i,j) ) } );
for( auto x : idx )
if( last.F == x.F ) join( last.S, x.S );
else last = x;
}
FOR(j,1,m) {
set< pair<ll,ll> > idx;
pair<ll,ll> last = { -1, -1 };
FOR(i,1,n)
idx.insert( { a[i][j], find( id(i,j) ) } );
for( auto x : idx )
if( last.F == x.F ) join( last.S, x.S );
else last = x;
}
FOR(i,1,n) {
set< pair<ll,ll> > idx;
pair<ll,ll> last = { -1, -1 };
FOR(j,1,m)
idx.insert( { a[i][j], find( id(i,j) ) } );
last = *idx.begin();
idx.erase(idx.begin());
for( auto x : idx ) {
v[last.S].pb( x.S );
out[last.S]++; in[x.S]++;
last = x;
}
}
FOR(j,1,m) {
set< pair<ll,ll> > idx;
pair<ll,ll> last = { -1, -1 };
FOR(i,1,n)
idx.insert( { a[i][j], find( id(i,j) ) } );
last = *idx.begin();
idx.erase(idx.begin());
for( auto x : idx ) {
v[last.S].pb( x.S );
out[last.S]++; in[x.S]++;
last = x;
}
}
queue< pair<ll,ll> > Q;
FOR(i,1,n)
FOR(j,1,m)
if( !in[ find( id(i,j) ) ] && find( id(i,j) ) == id(i,j) )
Q.push( { 1 , find( id(i,j) ) } );
while(!Q.empty()) {
ll d = Q.front().F;
ll ptr = Q.front().S;
Q.pop();
ans[ptr] = d;
for( ll x : v[ptr] ) {
in[x]--;
if( in[x] == 0 )
Q.push( { d+1, x } );
}
}
FOR(i,1,n) {
FOR(j,1,m)
cout << ans[ find( id(i,j) ) ] << ' ';
cout << '\n';
}
}