Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdio>
- #include <bitset>
- #include <vector>
- using namespace std;
- const int MAXN=16*16+1;
- bitset<100000> used;
- bool A[16][16],B[16][16];
- int pi[MAXN][2];
- int c[MAXN][MAXN];
- int match[MAXN];
- const int INF=1000000000;
- int N;
- int cnt1=0,cnt2=0;
- void init(){
- for (int i=0;i<N;i++){
- int a; cin>>a;
- for (int j=0;j<12;j++)
- A[i][j]=((a&(1<<j))!=0);
- }
- for (int i=0;i<N;i++){
- int a; cin>>a;
- for (int j=0;j<12;j++)
- B[i][j]=((a&(1<<j))!=0);
- }
- }
- int mabs(int a){
- return a<0 ? -a : a;
- }
- int dest(pair<int,int> a,pair<int,int> b){
- return mabs(a.first-b.first)+mabs(a.second-b.second);
- }
- void to_graph(){
- vector <pair<int,int> > p1,p2;
- for (int i=0;i<N;i++)
- for (int j=0;j<13;j++){
- if (A[i][j]==1)
- p1.push_back(make_pair(i,j));
- }
- for (int i=0;i<N;i++)
- for (int j=0;j<13;j++){
- if (B[i][j]==1)
- p2.push_back(make_pair(i,j));
- }
- cnt1=p1.size();
- cnt2=p2.size();
- for (int i=0;i<cnt1;i++)
- for (int j=0;j<cnt2;j++){
- c[i][j]=dest(p1[i],p2[j]);
- pi[i][0]=0;
- pi[i][1]=0;
- match[j]=-1;
- }
- }
- bool khun_algorithm(int u){
- if (used[u])
- return false;
- used[u]=true;
- for (int i=0;i<cnt1;i++)
- if (pi[u][0]+pi[i][1]==c[u][i] && (match[i]==-1 || khun_algorithm(match[i]))){
- match[i]=u;
- return true;
- }
- return false;
- }
- int form_delta (int u){
- if (used[u])
- return INF;
- used[u]=true;
- int delta=INF;
- for (int i=0;i<cnt1;i++){
- if (pi[u][0]+pi[i][1]!=c[u][i])
- delta=min(delta,c[u][i]-(pi[u][0]+pi[i][1]));
- else
- delta=min(delta,form_delta(match[i]));
- }
- return delta;
- }
- void graph_upgrade(int u, int delta,int dole=0){
- if (used[u])
- return;
- used[u]=true;
- for (int i=0;i<cnt1;i++){
- if (pi[u][0]+pi[i][1]==c[u][i]){
- if (!used[match[i]]){
- graph_upgrade(match[i],delta);
- pi[i][1]-=delta;
- }
- }
- }
- pi[u][0]+=delta;
- }
- int venger_algorithm(){
- for (int i=0;i<cnt1;i++){
- for(;;){
- used.reset();
- if (khun_algorithm(i)) break;
- used.reset();
- int delta=form_delta(i);
- used.reset();
- graph_upgrade(i,delta);
- }
- }
- int ans=0;
- for (int i=0;i<cnt1;i++)
- ans+=c[match[i]][i];
- return ans;
- }
- int main(){
- freopen("input.txt","r",stdin);
- freopen("output.txt","w",stdout);
- while(cin>>N){
- if (N==0) break;
- init();
- to_graph();
- if (cnt1!=cnt2){
- cout<<"Impossible"<<endl;
- continue;
- }
- int ans=venger_algorithm();
- cout<<ans<<endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment