COCI2014/2015 Contest#7 F

Description:

nn個書架,每個書架有mm個位置,對於每個位置都放着不同的書,現在有兩種操作:(1)若在某個書架上,某書的左邊或右邊爲空,則可以將該書左移或右移;(2)可以將一本書拿出放在空位置上。
現在給出書架的初態和末態,求需要最少的操作2次數。
若無法完成,即輸出-1。
n,m1000n,m\le 1000,書的編號nm\le n\cdot 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章