HDU 3722 Card Game KM水题

本文介绍了一道关于字符串匹配的问题,通过预处理任意两字符串的匹配分数并运用KM算法求解最大得分组合。代码实现包括字符串比较、匈牙利算法及KM算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:http://acm.hdu.edu.cn/showproblem.php?pid=3722

大意就是给n个字符串,然后对于任意两个字符串进行匹配,第一个倒序,第二个正序,找它们的最长公共前缀长度,就是它们的分数,自己和自己匹配分数为0,然后把这些字符串组成一些圈,求能得到的最大分数

思路:预先处理出任意的两个字符串的分数,然后KM。。。

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

const int N = 210;
const int INF = 0x3f3f3f3f;
int nx, ny;
int lx[N], ly[N], match[N], slack[N];
bool visx[N], visy[N];
int s[N][N];
char str[N][1010];

bool hungary(int v)
{
    visx[v] = true;
    for(int i = 0; i < ny; i++)
    {
        if(visy[i]) continue;
        if(lx[v] + ly[i] == s[v][i])
        {
            visy[i] = true;
            if(match[i] == -1 || hungary(match[i]))
            {
                match[i] = v;
                return true;
            }
        }
        else slack[i] = min(slack[i], lx[v] + ly[i] - s[v][i]);
    }

    return false;
}

void km()
{
    memset(match, -1, sizeof match);
    memset(ly, 0, sizeof ly);
    memset(lx, 0, sizeof lx);
    for(int i = 0; i < nx; i++)
        for(int j = 0; j < ny; j++)
            lx[i] = max(lx[i], s[i][j]);
    for(int i = 0; i < nx; i++)
    {
        memset(slack, 0x3f, sizeof slack);
        while(true)
        {
            memset(visx, 0, sizeof visx);
            memset(visy, 0, sizeof visy);

            if(hungary(i)) break;
            else
            {
                int tmp = INF;
                for(int j = 0; j < ny; j++)
                    if(!visy[j]) tmp = min(tmp, slack[j]);
                for(int j = 0; j < nx; j++)
                    if(visx[j]) lx[j] -= tmp;
                for(int j = 0; j < ny; j++)
                    if(visy[j]) ly[j] += tmp;
                    else slack[j] -= tmp;
            }
        }
    }
}

int judge(char s1[], char s2[])
{
    int res = 0;
    for(int i = strlen(s1) - 1, j = 0; s1[i] && s2[j]; i--, j++)
        if(s1[i] != s2[j]) return res;
        else res++;
    return res;
}

int main()
{
    int n;

    while(~ scanf("%d", &n))
    {
        for(int i = 0; i < n; i++)
            scanf(" %s", str[i]);
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                if(i == j) s[i][j] = 0;
                else s[i][j] = judge(str[i], str[j]);

        nx = ny = n;
        km();

        int res = 0;
        for(int i = 0; i < n; i++)
            res += s[match[i]][i];
        printf("%d\n", res);
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值