Codeforces Round #345 (Div. 1) C. Table Compression dp+并查集 C. Table Compression
题目链接:
http://codeforces.com/problemset/problem/650/C
memory limit per test256 megabytes
样例输出
1 2
2 3
题意
给你一个n*m的方格,每个方格上有一个正整数,现在要把这些数离散化,要保证离散化之后同一行或同一列的数之间大小关系不变,构造一种解使得最大的那个值最小
题解
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<ctime>
#include<vector>
#include<cstdio>
#include<string>
#include<bitset>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define X first
#define Y second
#define mkp make_pair
#define lson (o<<1)
#define rson ((o<<1)|1)
#define mid (l+(r-l)/2)
#define sz() size()
#define pb(v) push_back(v)
#define all(o) (o).begin(),(o).end()
#define clr(a,v) memset(a,v,sizeof(a))
#define bug(a) cout<<#a<<" = "<<a<<endl
#define rep(i,a,b) for(int i=a;i<(b);i++)
#define scf scanf
#define prf printf
typedef __int64 LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<pair<int,int> > VPII;
const int INF=0x3f3f3f3f;
const LL INFL=0x3f3f3f3f3f3f3f3fLL;
const double eps=1e-8;
const double PI = acos(-1.0);
//start----------------------------------------------------------------------
const int maxn=1e6+10;
int n,m;
int val[maxn],dp[maxn],ra[maxn],ind[maxn];
VI G[maxn];
VPII egs;
int fa[maxn];
int find(int x){
return fa[x]=fa[x]==x?x:find(fa[x]);
}
bool cmp(int a,int b){
return val[a]<val[b];
}
void init(){
for(int i=0;i<=n*m;i++) fa[i]=i,dp[i]=-1,ind[i]=0;
}
int main() {
scf("%d%d",&n,&m);
init();
rep(i,0,n) rep(j,0,m){
scf("%d",&val[i*m+j]);
}
//每行/每列 排序,然后连成串(这样可以少连很多没有用的边
rep(i,0,n){
rep(j,0,m) ra[j]=i*m+j;
sort(ra,ra+m,cmp);
for(int j=0;j<m-1;j++){
int p1=ra[j],p2=ra[j+1];
if(val[p1]<val[p2]){
egs.pb(mkp(p1,p2));
}else{
fa[find(p2)]=fa[find(p1)];
}
}
}
rep(j,0,m){
rep(i,0,n) ra[i]=i*m+j;
sort(ra,ra+n,cmp);
for(int i=0;i<n-1;i++){
int p1=ra[i],p2=ra[i+1];
if(val[p1]<val[p2]){
egs.pb(mkp(p1,p2));
}else{
fa[find(p2)]=fa[find(p1)];
}
}
}
//用并查集缩点
for(int i=0;i<egs.sz();i++){
int pu=find(egs[i].X),pv=find(egs[i].Y);
G[pu].pb(pv);
ind[pv]++;
}
//拓扑排序
queue<int> Q;
rep(i,0,n*m){
if(fa[i]!=i) continue;
if(ind[i]==0){
dp[i]=1;
Q.push(i);
}
}
while(!Q.empty()){
int u=Q.front(); Q.pop();
for(int i=0;i<G[u].sz();i++){
int v=G[u][i];
dp[v]=max(dp[v],dp[u]+1);
ind[v]--;
if(ind[v]==0) Q.push(v);
}
}
rep(i,0,n){
rep(j,0,m){
int x=dp[find(i*m+j)];
prf("%d",x);
if(j==m-1) puts("");
else prf(" ");
}
}
return 0;
}
//end-----------------------------------------------------------------------