#NOIP模拟赛#同色齿轮问题(Hungary最大匹配 or 网络流)

16 篇文章 0 订阅
13 篇文章 0 订阅

一共只有三种颜色,假设前两种颜色反向,对于第三种颜色,它与前两种齿轮中必有一种同向。

枚举两种齿轮的颜色,假设它们旋转方向矛盾(同向),另一种只需要与它们反向就一定不矛盾了,所以此处可以不考虑。

对于这两种需要啮合的颜色齿轮连边,Hungary求二分图最大匹配,最大匹配数就是矛盾需删除掉的齿轮数(注:删掉的不一定是同色齿轮)。

Code:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;

const int Max = 50;

struct node{
    int v, nxt;
}edge[Max * Max + 5];

int N, cnt, Ans = 0x3f3f3f3f;
int fir[Max + 5], match[Max + 5];
bool vis[Max + 5];
char Col[Max + 5];
char Ori[3] = {'R', 'G', 'B'};
char map[Max + 5][Max + 5];

void addedge(int a, int b){
    edge[++ cnt].v = b, edge[cnt].nxt = fir[a], fir[a] = cnt;
}

bool Dfs(int u){
    for(int i = fir[u]; i; i = edge[i].nxt) if(! vis[edge[i].v]){
        vis[edge[i].v] = 1;
        if(! match[edge[i].v] || Dfs(match[edge[i].v])){
            match[edge[i].v] = u;
            return 1;
        }
    }
    return 0;
}

void Hungary(){
    int now = 0;
    memset(match, 0, sizeof match );
    for(int i = 1; i <= N; ++ i){
        memset(vis, 0, sizeof vis );
        now += Dfs(i);
    }
    Ans = min(Ans, now);
}

int main(){
    //freopen("data1.in", "r", stdin);
    freopen("gear.in", "r", stdin);
    freopen("gear.out", "w", stdout);
    scanf("%s", Col + 1);
    N = strlen(Col + 1);
    for(int i = 1; i <= N; ++ i)
        scanf("%s", map[i] + 1);
    for(int a = 0; a < 3; ++ a)
        for(int b = a + 1; b < 3; ++ b){
            memset(fir, 0, sizeof fir );
            cnt = 0;
            for(int i = 1; i <= N; ++ i)    if(Col[i] == Ori[a]){
                for(int j = 1; j <= N; ++ j)    if(Col[j] == Ori[b])
                    if(map[i][j] == 'Y')
                        addedge(i, j);
            }
            Hungary();
        }
    printf("%d\n", Ans);
    return 0;
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值