Description:
有
n
n
n个书架,每个书架有
m
m
m个位置,对于每个位置都放着不同的书,现在有两种操作:(1)若在某个书架上,某书的左边或右边为空,则可以将该书左移或右移;(2)可以将一本书拿出放在空位置上。
现在给出书架的初态和末态,求需要最少的操作2次数。
若无法完成,即输出-1。
n
,
m
≤
1000
n,m\le 1000
n,m≤1000,书的编号
≤
n
⋅
m
\le n\cdot m
≤n⋅m
Solution:
- 首先,对于操作1的情况,如果它的初态和末态的相对位置是不一样的,那么一定要换,可能需要操作2
- 模拟小数据发现,只需要关心该行是否还需要操作2,而需要操作2一定要它的初态和末态的相对位置不同。
- 而真正需要操作2的,即初态和末态不在同一个行时,我们可以建图跑环,发现只要有存在不同的位置,那么一定要进行一次操作2,
- 而末态位置的书架是满的,那么一定还要一次操作将该书架空出一个位置来。
Code:
#include<bits/stdc++.h>
using namespace std;
#define REP(i,f,t) for(int i=(f),i##_end_=(t);i<=i##_end_;++i)
#define SREP(i,f,t) for(int i=(f),i##_end_=(t);i<i##_end_;++i)
#define DREP(i,f,t) for(int i=(f),i##_end_=(t);i>=i##_end_;--i)
#define ll long long
template<class T>inline bool chkmax(T &x,T y){return x<y?x=y,1:0;}
template<class T>inline bool chkmin(T &x,T y){return x>y?x=y,1:0;}
template<class T>inline void Rd(T &x){
x=0;char c;
while((c=getchar())<48);
do x=(x<<1)+(x<<3)+(c^48);
while((c=getchar())>47);
}
const int N=1002;
int n,m;
int A[N][N],B[N][N];
typedef pair<int,int>pii;
#define fi first
#define se second
struct pwater{
pii pos1[N*N],pos2[N*N];
vector<pii>row[N];
vector<int>tmp;
vector<int>::iterator it;
int cnt[N];
int Mxid;
int qwq,head[N*N];
struct edge{
int to,nxt;
}E[(N*N)<<1];
void addedge(int x,int y){E[qwq]=(edge){y,head[x]};head[x]=qwq++;}
bool vis[N];
int move(int x){//看相对位置
tmp.clear();
sort(row[x].begin(),row[x].end());
SREP(i,0,row[x].size()){
it=lower_bound(tmp.begin(),tmp.end(),row[x][i].se);
if(it==tmp.end()) tmp.push_back(row[x][i].se);
else *it=row[x][i].se;
}
int res=0;
if(tmp.size()==row[x].size()) return 0;
if((int)row[x].size()==m) res=1;
res+=row[x].size()-tmp.size();
return res;
}
int dfs(int x){
int res=(cnt[x]==m);
vis[x]=1;
for(int i=head[x];~i;i=E[i].nxt){
int y=E[i].to;
if(vis[y])continue;
res&=dfs(y);
}
return res;
}
void solve(){
bool flag=1;
bool zero=0;
REP(i,1,n) REP(j,1,m) {
if(A[i][j]!=B[i][j]) flag=0;
if(!A[i][j]) zero=1;
pos1[A[i][j]]=(pii){i,j};
pos2[B[i][j]]=(pii){i,j};
chkmax(Mxid,A[i][j]);
cnt[i]+=(A[i][j]>0);
}
if(flag){puts("0");return;}
if(!zero){puts("-1");return;}
memset(head,-1,sizeof(head));
int ans=0;
REP(i,1,Mxid){
if(pos1[i].fi==pos2[i].fi){//同一行 可能可以移动
row[pos1[i].fi].push_back((pii){pos1[i].se,pos2[i].se});
}
else {//至少要拿出
addedge(pos1[i].fi,pos2[i].fi);
addedge(pos2[i].fi,pos1[i].fi);
++ans;
}
}
REP(i,1,n) ans+=move(i);
REP(i,1,n) if(!vis[i] && ~head[i]) ans+=dfs(i);
printf("%d\n",ans);
}
}p2;
int main(){
// freopen("book.in","r",stdin);
// freopen("book.out","w",stdout);
Rd(n),Rd(m);
REP(i,1,n) REP(j,1,m) Rd(A[i][j]);
REP(i,1,n) REP(j,1,m) Rd(B[i][j]);
p2.solve();
return 0;
}