2 solutions

  • 0
    @ 2026-7-29 16:30:03

    这是一道非常经典的最小费用最大流(Min-Cost Max-Flow, MCMF)问题。题目要求将矩阵 AA 通过相邻交换变为矩阵 BB,并限制了每个格子能够参与交换的次数,最终求最小交换次数。

    下面我们按照独立思考推导 -> 避坑指南 -> 代码原理解析 -> 带注释的完整代码的顺序为你详细拆解。


    一、 独立思考:题目考的是什么?应该怎么想?

    1. 问题转化:移动的“0”

    • 在仅由 0 和 1 组成的矩阵中,交换两个相同的字符(如 0 和 0,1 和 1)是毫无意义的,只会白白消耗交换次数。因此,每一次有效的交换必然是一个 0 和一个 1 交换。
    • 这就可以等价地理解为:矩阵中所有的 0 在棋盘上“移动”,每移动一步(与其周围的 1 交换),消耗一次交换次数。
    • 我们的最终目标是:将 AA 矩阵中多余的 0(即 A=0,B=1A=0, B=1 的位置)沿着网格移动,填补到 BB 矩阵中需要的 0 的位置(即 A=1,B=0A=1, B=0 的位置)。最少交换次数,就是这些 0 移动的路径长度之和。

    2. 容量限制与点权拆解

    每个格子限制了交换次数 count。当一个 0 经过某个格子时,它经历“进入该格子”和“离开该格子”两个动作:

    • 进入该格子:该格子与上一个格子发生了一次交换。
    • 离开该格子:该格子与下一个格子发生了一次交换。 所以,如果一个格子被路过了(一进一出),它参与了 2 次交换。

    设某个格子有 inin 个 0 进入,outout 个 0 离开。它参与的总交换次数为 in+outin + out。题目要求 in+out≤countin + out \le count。 根据格子的初始状态和目标状态,有以下三种情况:

    1. 途径点 (A=BA = B): 该格子最终状态没变,所以进入的 0 必须全都离开,即 in=outin = out。 限制转化为:$2 \times in \le count \implies in \le \lfloor count / 2 \rfloor$。
    2. 起点 (A=0,B=1A = 0, B = 1): 该格子本身就提供了一个 0 出去,所以 out=in+1out = in + 1。 限制转化为:$2 \times in + 1 \le count \implies out \le \lfloor (count + 1) / 2 \rfloor$。 (注:这里的 outout 恰好等于流经该格子内部的总流量)
    3. 终点 (A=1,B=0A = 1, B = 0): 该格子最终要截留一个 0,所以 in=out+1in = out + 1。 限制转化为:$2 \times out + 1 \le count \implies in \le \lfloor (count + 1) / 2 \rfloor$。 (注:这里的 inin 也恰好等于流经该格子内部的总流量)

    神奇的统一公式: 如果我们把每个格子拆分成“入点 uinu_{in}”和“出点 uoutu_{out}”,中间连一条内部边,那么这条内部边的容量统一就是: Capacity = (count + (A != B)) / 2 这极大地简化了建图模型!


    二、 可能会哪里想错?(避坑指南)

    1. 直接把交换次数作为边的容量(大错特错): 在网络流中,边权控制的是流量,而我们这里的交换次数限制是作用在点上的,并且进入和离开都会消耗同一个点的次数。因此必须拆点,将点权限制转化为内部边的容量限制。
    2. 没有验证 0 的总数: 如果矩阵 AA 中 0 的总数和矩阵 BB 中 0 的总数都不一样,显然永远无法转换成功,应该在建图前直接特判输出 -1 节省时间。

    三、 代码正确性原理解析

    原作者的代码极其精准地实现了上述逻辑:

    1. 源汇点统计: c1 和 c2 分别统计了矩阵 AA 和 BB 中的 0 的数量,并在随后把 c1 更新为了纯粹处于错位状态的 0 的数量。网络流的终极满流目标就是这个 c1。
    2. 网络流建图:
    • id(i, j, 0) 是入点 uinu_{in},id(i, j, 1) 是出点 uoutu_{out}。
    • 拆点内部边:f.addedge(u_in, u_out, (count + (A!=B))/2, 0),容量为上述推导的公式,内部穿梭不产生步数(代价为0)。
    • 相邻网格边:循环 8 个方向,f.addedge(u_out, v_in, 1e18, 1)。从当前格子的出点走向相邻格子的入点,容量无穷大,每走一步代价为 1(代表 1 次交换)。
    • 超级源点/汇点边:如果 A=0A=0 且 B=1B=1,超级源点 00 连向入点,容量 1,代价 0;如果 A=1A=1 且 B=0B=0,出点连向超级汇点 11,容量 1,代价 0。
    1. 最小费用最大流: 使用经典的 SPFA 寻路 + DFS 增广的 Dinic 费用流算法。如果最终算出的最大流等于错位的 0 的数量,说明所有的 0 都找到了归宿,输出最小费用(步数)。否则,说明由于次数限制无法归位,输出 -1。

    四、 带详细注释的完整代码

    /*
     * (神兽保佑 永无BUG 注释已省略,保留核心风范)
     */
    #include<bits/stdc++.h>
    using namespace std;
    #define int         long long
    #define pb          push_back
    #define REP(i,b,e)  for(int i=(b);i<(int)(e);++i)
    #define over(x)     {cout<<(x)<<endl;return;}
    
    // Min-Cost Max-Flow 费用流模板
    struct flow {
        struct edge {
            int y, fl, c; // y: 目标点, fl: 剩余容量, c: 费用
        } a[1000005];
        vector<int> v[1000];
        int tot, n;
        
        // 加边函数:正向边容量 w 费用 c,反向边容量 0 费用 -c
        void addedge(int x, int y, int w, int c) {
            v[x].pb(tot); a[tot++] = {y, w, c};
            v[y].pb(tot); a[tot++] = {x, 0, -c};
        }
        
        int dis[1000], vis[1000], E[1000];
        
        // SPFA 寻找最短增广路(按费用寻找)
        bool spfa() {
            queue<int> q;
            REP(i, 0, n) E[i] = 0, vis[i] = 0, dis[i] = 1e18;
            dis[0] = 0; q.push(0); vis[0] = 1;
            while(!q.empty()){
                int x = q.front(); vis[x] = 0; q.pop();
                for(auto i : v[x]){
                    auto [y, fl, c] = a[i];
                    if(!fl) continue; // 没有容量跳过
                    if(dis[y] > dis[x] + c){
                        dis[y] = dis[x] + c;
                        if(!vis[y]) vis[y] = 1, q.push(y);
                    }
                }
            }
            REP(i, 0, n) vis[i] = 0;
            return dis[1] != 1e18; // 只要超级汇点可达就返回 true
        }
        
        int cost;
        
        // DFS 沿着最短路增广流量
        int dfs(int x, int fl) {
            if(x == 1 || !fl) return fl;
            int ans = 0; vis[x] = 1;
            // 当前弧优化
            for(int & _ = E[x]; _ < (int)v[x].size(); ++_) {
                int i = v[x][_];
                auto [y, f, c] = a[i];
                if(!vis[y] && dis[y] == dis[x] + c && f) {
                    int d = dfs(y, min(fl - ans, f));
                    ans += d; 
                    a[i].fl -= d; 
                    a[i^1].fl += d; 
                    cost += d * c; // 累加费用 = 流量 * 单价
                    if(ans == fl) return vis[x] = 0, fl;
                }
            }
            return vis[x] = 0, ans;
        }
        
        // 执行 Dinic 算法直到无法增广
        int dinic() {
            int ans = 0; cost = 0;
            while(spfa()) ans += dfs(0, 1e18);
            return ans;
        }
        
        // 初始化点数
        void init(int _n) {
            n = _n; tot = 0;
            REP(i, 0, n) v[i].clear();
        }
    } f;
    
    int n, m;
    string s1[105], s2[105], s3[105];
    
    // 坐标映射成一维节点 ID:op=0 为入点,op=1 为出点
    // +2 是为了留出 0 作为超级源点,1 作为超级汇点
    int id(int x, int y, int op = 0) {
        return (x * m + y) * 2 + op + 2; 
    }
    
    // 八连通移动方向
    int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
    int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
    
    void Main() {
        cin >> n >> m;
        int c1 = 0, c2 = 0;
        
        // 读入矩阵 A,并统计 0 的总数
        REP(i, 0, n) {
            cin >> s1[i];
            for(auto j : s1[i]) c1 += j == '0';
        }
        // 读入矩阵 B,并统计 0 的总数
        REP(i, 0, n) {
            cin >> s2[i];
            for(auto j : s2[i]) c2 += j == '0';
        }
        
        // 数量不一致绝不可能成功
        if(c1 != c2) over(-1)
        
        // 总点数 = 网格面积 * 2(拆点) + 源点(0) + 汇点(1)
        f.init(n * m * 2 + 2); 
        
        REP(i, 0, n) {
            string t; cin >> t; // t 是次数矩阵 count
            REP(j, 0, m) {
                // 拆点的内部连边:控制当前格子参与交换的最高次数
                // 公式:(次数 + 是否为错位节点) / 2
                int cap = (t[j] - '0' + ((s1[i][j] == '0') ^ (s2[i][j] == '0'))) / 2;
                f.addedge(id(i, j, 0), id(i, j, 1), cap, 0);
                
                // 当前格子连向周围 8 个相邻的格子
                REP(l, 0, 8) {
                    int x = i + dx[l], y = j + dy[l];
                    if(x >= 0 && x < n && y >= 0 && y < m) {
                        // 从当前出点 -> 相邻入点,容量无限,跨越一步的代价(交换次数)为 1
                        f.addedge(id(i, j, 1), id(x, y, 0), 1e18, 1);
                    }
                }
            }
        }
        
        // 连接源汇点
        REP(i, 0, n) {
            REP(j, 0, m) {
                if(s1[i][j] != s2[i][j]) {
                    if(s1[i][j] == '0') {
                        // 矩阵 A 中多余的 0 作为源头
                        f.addedge(0, id(i, j, 0), 1, 0); 
                    }
                    if(s2[i][j] == '0') {
                        // 矩阵 B 中缺失的 0 作为汇点(目标)
                        f.addedge(id(i, j, 1), 1, 1, 0); 
                    }
                } else if(s1[i][j] == '0') {
                    // 如果是匹配好的 0,不参与整体流,从错位池中扣除
                    --c1; 
                }
            }
        }
        
        // 运行最大流,判断最大流能否满足所有处于错位状态的 0 的数量
        if(f.dinic() != c1) over(-1) 
        
        // 如果可以满足,输出最小代价,即最少交换次数
        over(f.cost)
    }
    
    void TC() {
        int tc = 1;
        while(tc--){
            Main();
            cout.flush();
        }
    }
    
    signed main() {
        return cin.tie(0), cout.tie(0), ios::sync_with_stdio(0), TC(), 0;
    }
    
    
    • 0
      @ 2026-7-29 8:44:13
      /*
       *                                                     __----~~~~~~~~~~~------___
       *                                    .  .   ~~//====......          __--~ ~~
       *                    -.            \_|//     |||\\  ~~~~~~::::... /~
       *                 ___-==_       _-~o~  \/    |||  \\            _/~~-
       *         __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
       *     _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
       *   .~       .~       |   \\ -_    /  /-   /   ||      \   /
       *  /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
       *  |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
       *           '         ~-|      /|    |-~\~~       __--~~
       *                       |-~~-_/ |    |   ~\_   _-~            /\
       *                            /  \     \__   \/~                \__
       *                        _--~ _/ | .-~~____--~-/                  ~~==.
       *                       ((->/~   '.|||' -_|    ~~-/ ,              . _||
       *                                  -_     ~\      ~~---l__i__i__i--~~_/
       *                                  _-~-__   ~)  \--______________--~~
       *                                //.-~~~-~_--~- |-------~~~~~~~~
       *                                       //.-~~~--\
       *                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       *
       *                               神兽保佑            永无BUG
       */
      
      /*
       * @Description: I want to be the weakest vegetable in the world!
       * @Author: I.Z.
      */
      #include<bits/stdc++.h>
      using namespace std;
      #define MOD         998244353
      #define speMOD      2933256077ll
      #define int         long long
      #define pii         pair<int,int>
      #define all(v)      v.begin(),v.end()
      #define pb          push_back
      #define REP(i,b,e)  for(int i=(b);i<(int)(e);++i)
      #define over(x)     {cout<<(x)<<endl;return;}
      #define lowbit(x)   ((x)&(-(x)))
      #define cntbit(x)   __builtin_popcount(x)
      #define deal(v)     sort(all(v));v.erase(unique(v.begin(),v.end()),v.end())
      #define lbound(v,x) lower_bound(all(v),x)-v.begin()
      mt19937 sd(random_device{}());
      int qpow(int a,int b,int m=MOD,int res=1){
      	a%=m;
      	while(b>0)res=(b&1)?(res*a%m):(res),a=a*a%m,b>>=1;
      	return res;
      }
      int exgcd(int x,int y,int &a,int &b){
      	if(y==0){
      		a=1;b=0;
      		return x;
      	}
      	int d=exgcd(y,x%y,a,b);
      	int z=b;
      	b=a-b*(x/y);
      	a=z;
      	return d;
      }
      int _x_,_y_;
      inline int inverse(int x,int y=MOD){
      	exgcd(x,y,_x_,_y_);
      	return (_x_+y)%y;
      }
      int fac[2000005],inv[2000005];
      void init(int n){
      	fac[0]=inv[0]=1;
      	REP(i,1,n+1)fac[i]=fac[i-1]*i%MOD;
      	inv[n]=qpow(fac[n],MOD-2);
      	for(int i=n-1;i>=1;--i)inv[i]=inv[i+1]*(i+1)%MOD;
      }
      int binom(int x,int y){
      	return x<y||y<0? 0:fac[x]*inv[y]%MOD*inv[x-y]%MOD;
      }
      struct flow{
          struct edge{
              int y,fl,c;
          }a[1000005];
          vector<int>v[1000];
          int tot,n;
          void addedge(int x,int y,int w,int c){
      //    	cout<<x<<' '<<y<<' '<<w<<' '<<c<<endl;
              v[x].pb(tot);a[tot++]={y,w,c};
              v[y].pb(tot);a[tot++]={x,0,-c};
          }
          int dis[1000],vis[1000],E[1000];
          bool spfa(){
              queue<int>q;
              REP(i,0,n)E[i]=0,vis[i]=0,dis[i]=1e18;
              dis[0]=0;q.push(0);vis[0]=1;
              while(!q.empty()){
                  int x=q.front();vis[x]=0;q.pop();
                  for(auto i:v[x]){
                      auto [y,fl,c]=a[i];
                      if(!fl)continue;
                      if(dis[y]>dis[x]+c){
                          dis[y]=dis[x]+c;
                          if(!vis[y])vis[y]=1,q.push(y);
                      }
                  }
              }
              REP(i,0,n)vis[i]=0;
              return dis[1]!=1e18;
          }
          int cost;
          int dfs(int x,int fl){
          	if(x==1||!fl)return fl;
              int ans=0;vis[x]=1;
              for(int &_=E[x];_<(int)v[x].size();++_){
                  int i=v[x][_];
                  auto [y,f,c]=a[i];
                  if(!vis[y]&&dis[y]==dis[x]+c&&f){
                      int d=dfs(y,min(fl-ans,f));
                      ans+=d;a[i].fl-=d;a[i^1].fl+=d;cost+=d*c;
                      if(ans==fl)return vis[x]=0,fl;
                  }
              }
              return vis[x]=0,ans;
          }
          int dinic(){
              int ans=0;cost=0;
              while(spfa())ans+=dfs(0,1e18);
              return ans;
          }
          void init(int _n){
              n=_n;tot=0;
              REP(i,0,n)v[i].clear();
          }
      }f;
      int n,m;
      string s1[105],s2[105],s3[105];
      int id(int x,int y,int op=0){return (x*m+y)*2+op+2;}
      int dx[]={-1,-1,-1,0,0,1,1,1};
      int dy[]={-1,0,1,-1,1,-1,0,1};
      void Main() {
      	cin>>n>>m;
      	int c1=0,c2=0;
      	REP(i,0,n){
      		cin>>s1[i];
      		for(auto j:s1[i])c1+=j=='0';
      	}
      	REP(i,0,n){
      		cin>>s2[i];
      		for(auto j:s2[i])c2+=j=='0';
      	}
      	if(c1!=c2)over(-1)
      	f.init(n*m*2+2);
      	REP(i,0,n){
      		string t;cin>>t;
      		REP(j,0,m){
      			f.addedge(id(i,j),id(i,j,1),(t[j]-48+((s1[i][j]=='0')^(s2[i][j]=='0')))/2,0);
      			REP(l,0,8){
      				int x=i+dx[l],y=j+dy[l];
      				if(x>=0&&x<n&&y>=0&&y<m){
      					f.addedge(id(i,j,1),id(x,y),1e18,1);
      				}
      			}
      		}
      	}
      	REP(i,0,n){
      		REP(j,0,m)if(s1[i][j]!=s2[i][j]){
      			if(s1[i][j]=='0')f.addedge(0,id(i,j,0),1,0);
      			if(s2[i][j]=='0')f.addedge(id(i,j,1),1,1,0);
      		}else if(s1[i][j]=='0')--c1;
      	}
      	if(f.dinic()!=c1)over(-1)
      	over(f.cost)
      }
      void TC() {
          int tc=1;
      	while(tc--){
      		Main();
      		cout.flush();
      	}
      }
      signed main() {
      	return cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;
      }
      /*
      1. CLEAR the arrays (ESPECIALLY multitests)
      2. DELETE useless output
       */
      
      
      • 1

      Information

      ID
      3044
      Time
      1000ms
      Memory
      256MiB
      Difficulty
      10
      Tags
      # Submissions
      1
      Accepted
      1
      Uploaded By