2 solutions

  • 0
    @ 2026-7-29 16:48:40

    这是一道极其经典的鸽巢原理(抽屉原理)与图论(二分图最小顶点覆盖)相结合的神仙题。它将一个看似无从下手的物理机械问题,完美转化为了经典的网络流模型。

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


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

    1. 寻找突破口:齿轮的旋转方向

    题目描述了几个关键物理限制:

    1. 咬合的齿轮必须以相反的方向转动(要么顺时针 CW,要么逆时针 CCW)。
    2. 同颜色的齿轮必须以相同的方向转动。
    3. 颜色只有三种:红(R)、绿(G)、蓝(B)。
    4. 同色齿轮之间不会咬合(原图已经是三分图)。

    齿轮的转动方向只有 2 种,但齿轮的颜色有 3 种。 抽屉原理(鸽巢原理)闪亮登场! 把 3 种颜色放进 2 种转动方向里,必然至少有 2 种颜色的齿轮,它们的旋转方向是完全相同的!

    2. 方向相同意味着什么?

    假设红色(R)和绿色(G)的齿轮旋转方向相同,那么它们之间绝对不能有任何连边(咬合)。因为一旦连边,根据物理规律它们必须反向旋转,这就与“同向旋转”矛盾了。 但是蓝色(B)的齿轮可以和 R、G 放心连边,因为 B 可以独占另一种旋转方向,与 R、G 都反向。

    因此,整个问题转化为: 我们必须从 {R,G},{G,B},{B,R}\{R, G\}, \{G, B\}, \{B, R\} 这三个颜色对中,挑选至少一对,并将它们之间的所有连边全部破坏掉。破坏连边的方法就是拆除齿轮(删除顶点)。

    3. 化繁为简:图论模型映射

    “在一个图中删除最少的顶点,使得某两部分之间没有边” —— 这正是一个经典的最小顶点覆盖(Minimum Vertex Cover)问题。

    由于同色内部本来就没有边,所以任意两种颜色(例如 R 和 G)构成的子图,是一个纯粹的二分图。 在图论中,有一个极其著名的柯尼希定理(König's theorem): 二分图的最小顶点覆盖 = 二分图的最大匹配。

    所以,最终的算法浮出水面: 我们只需要分别计算 R-G, G-B, B-R 这三个二分图的最大匹配数,然后取这三个数值中的最小值,就是我们需要移除的最少齿轮数!


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

    1. 陷入 NP-Hard 的恐慌: 求一般图的最小顶点覆盖是著名的 NP-Hard 问题,数据范围如果稍大就绝对做不了。但题意中“同色不相连”的性质保证了导出子图必定是二分图,从而可以将复杂度降为多项式级别的网络流(二分图匹配)。
    2. 试图给每个点分配具体的方向去 DP: 这是很多人的第一直觉(想要给每个齿轮赋状态 0/10/1)。但因为齿轮是按“颜色”绑定的,状态其实是定死在颜色上的,全图只有 23=82^3 = 8 种宏观状态。用抽屉原理将视角上升到颜色层面,是破局的核心。
    3. 连边时正反双向建边: 在建立网络流求最大匹配时,左边集合连向右边集合只能建单向边。如果 R-G 图中把 R 连向 G,又把 G 连向 R,就会导致流量成环或计算重复。原作者的代码非常严谨,通过 s[i]==ch[0] (只在左侧) 和 s[j]==ch[1] (只在右侧) 严格限制了方向。

    三、 代码正确性原理解析

    原作者的代码写得极为巧妙,特别是用极其精简的字符串移位操作,遍历了三种颜色组合。

    1. 图的轮换构建:
    • 初始 ch = "GBR"。
    • 第一次循环:匹配 ch[0]='G' 和 ch[1]='B',求出了 G-B 之间的最大匹配。
    • 然后 ch = ch.substr(1,2) + ch.substr(0,1),ch 变成了 "BRG"。
    • 第二次循环:匹配 B 和 R,求出了 B-R 之间的最大匹配。
    • 第三次循环:ch 变成 "RGB",匹配了 R 和 G。 短短几行代码优雅地完成了三组二分图的构建。
    1. 网络流(Dinic)求解二分图匹配:
    • 源点 0 连向所有的左侧节点(由于嫌过滤麻烦,作者把所有 0…N−10 \dots N-1 的点都当左侧接了源点,容量为 1)。
    • 所有的右侧节点(偏移了 NN)都连向汇点 1,容量为 1。
    • 对于真正的有效边,只有满足条件 s[i] == ch[0] 且 s[j] == ch[1] 且有边 t[i][j] == 'Y' 时,才从 i+2 连向 j+N+2。
    • 因为只有符合 ch[0] 的点才有向外的出边,符合 ch[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;}
    
    // ---------------- Dinic 最大流模板开始 ----------------
    struct flow {
        struct edge {
            int y, f; // y: 目标节点, f: 剩余容量
        } a[200005];
        vector<int> v[20000];
        int tot, n;
        
        void init(int _n) {
            n = _n; tot = 0;
            REP(i, 0, n) v[i].clear();
        }
        
        // 加边函数:正向边容量 w,反向边容量 0
        void addedge(int x, int y, int w = 1) {
            v[x].pb(tot); a[tot++] = {y, w};
            v[y].pb(tot); a[tot++] = {x, 0};
        }
        
        int dis[2000], E[2000];
        
        // BFS 构建分层图
        bool bfs() {
            REP(i, 0, n) dis[i] = 1e18, E[i] = 0;
            dis[0] = 0; // 0 是超级源点
            queue<int> q; q.push(0);
            while(!q.empty()){
                int x = q.front(); q.pop();
                for(auto i : v[x]){
                    auto [y, w] = a[i];
                    if(w && dis[y] == 1e18){
                        dis[y] = dis[x] + 1;
                        q.push(y);
                    }
                }
            }
            return dis[1] != 1e18; // 1 是超级汇点
        }
        
        // DFS 多路增广
        int dfs(int x, int fl) {
            if(!fl || x == 1) return fl; // 到达汇点
            int ans = 0;
            for(int & _ = E[x]; _ < (int)v[x].size(); ++_) {
                int i = v[x][_]; auto [y, w] = a[i];
                if(w && dis[y] == dis[x] + 1){
                    int c = dfs(y, min(fl - ans, w));
                    a[i].f -= c; a[i^1].f += c; ans += c;
                    if(ans == fl) return ans;
                }
            }
            return ans;
        }
        
        int dinic() {
            int ans = 0;
            while(bfs()) ans += dfs(0, 1e18);
            return ans;
        }
    } f;
    // ---------------- Dinic 最大流模板结束 ----------------
    
    int n;
    string s, ch = "GBR", t[100];
    vector<int> v[100];
    
    void Main() {
        cin >> n >> s;
        REP(i, 0, n) cin >> t[i];
        
        int ans = n; // 最坏情况是移除所有齿轮
        
        // 三种颜色,根据鸽巢原理必然至少有两种颜色方向相同
        // 我们分别尝试破坏 {G,B}, {B,R}, {R,G} 之间的所有边
        REP(p, 0, 3) {
            // 总节点数:源点(0) + 汇点(1) + 左侧副本(N个) + 右侧副本(N个) = 2N+2
            f.init(2 * n + 2);
            
            // 建立源点到左侧的边,以及右侧到汇点的边
            // 虽然连了所有的点,但后续二分图的边只会连目标颜色的点,因此不会有冗余流量
            REP(i, 0, n) {
                f.addedge(0, i + 2); // 源点 -> 左侧节点(偏移 2)
                f.addedge(i + n + 2, 1); // 右侧节点(偏移 n+2) -> 汇点
            }
            
            // 构造选定颜色对的二分图
            REP(i, 0, n) {
                REP(j, 0, n) {
                    // 如果左节点是当前指定的第一种颜色,右节点是第二种颜色,且它们之间咬合
                    if(s[i] == ch[0] && s[j] == ch[1] && t[i][j] == 'Y') {
                        // 左侧对应节点连接到右侧对应节点
                        f.addedge(i + 2, j + n + 2);
                    }
                }
            }
            
            // 二分图的最大匹配 = 最小顶点覆盖 = 破坏该对颜色所有连边所需的最少点数
            ans = min(ans, f.dinic());
            
            // 循环移位,依次测试 (G,B), (B,R), (R,G)
            ch = ch.substr(1, 2) + ch.substr(0, 1);
        }
        
        // 输出三种可能性中最小的一个
        cout << ans << endl;
    }
    
    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:37:52
      /*
       *                                                     __----~~~~~~~~~~~------___
       *                                    .  .   ~~//====......          __--~ ~~
       *                    -.            \_|//     |||\\  ~~~~~~::::... /~
       *                 ___-==_       _-~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,f;
      	}a[200005];
      	vector<int>v[20000];
      	int tot,n;
      	void init(int _n){
      		n=_n;tot=0;
      		REP(i,0,n)v[i].clear();
      	}
      	void addedge(int x,int y,int w=1){
      		v[x].pb(tot);a[tot++]={y,w};
      		v[y].pb(tot);a[tot++]={x,0};
      	}
      	int dis[2000],E[2000];
      	bool bfs(){
      		REP(i,0,n)dis[i]=1e18,E[i]=0;
      		dis[0]=0;
      		queue<int>q;q.push(0);
      		while(!q.empty()){
      			int x=q.front();q.pop();
      			for(auto i:v[x]){
      				auto [y,w]=a[i];
      				if(w&&dis[y]==1e18){
      					dis[y]=dis[x]+1;
      					q.push(y);
      				}
      			}
      		}
      		return dis[1]!=1e18;
      	}
      	int dfs(int x,int fl){
      		if(!fl||x==1)return fl;
      		int ans=0;
      		for(int &_=E[x];_<(int)v[x].size();++_){
      			int i=v[x][_];auto [y,w]=a[i];
      			if(w&&dis[y]==dis[x]+1){
      				int c=dfs(y,min(fl-ans,w));
      				a[i].f-=c;a[i^1].f+=c;ans+=c;
      				if(ans==fl)return ans;
      			}
      		}
      		return ans;
      	}
      	int dinic(){
      		int ans=0;
      		while(bfs())ans+=dfs(0,1e18);
      		return ans;
      	}
      }f;
      int n;
      string s,ch="GBR",t[100];
      vector<int>v[100];
      void Main() {
      	cin>>n>>s;
      	REP(i,0,n)cin>>t[i];
      	int ans=n;
      	REP(p,0,3){
      		f.init(2*n+2);
      		REP(i,0,n)f.addedge(0,i+2),f.addedge(i+n+2,1);
      		REP(i,0,n)REP(j,0,n)if(s[i]==ch[0]&&s[j]==ch[1]&&t[i][j]=='Y')f.addedge(i+2,j+n+2);
      		ans=min(ans,f.dinic());
      		ch=ch.substr(1,2)+ch.substr(0,1);
      	}
      	cout<<ans<<endl;
      }
      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
      3040
      Time
      1000ms
      Memory
      256MiB
      Difficulty
      10
      Tags
      # Submissions
      1
      Accepted
      1
      Uploaded By