HDU 3718 Similarity KM算法

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

题意:给定一个字符串,然后输入m串字符串,使字符串中字符匹配数量最大,输出匹配量 / 字符串长度

思路:对于每对对应字符建边,权值加1,然后求最大匹配权值即可

总结:刚开始看貌似很难,在纸上画了两下,就有了思路,不小心水了过去~~~

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

const int N = 60;
const int LEN = 10010;
const int INF = 0x3f3f3f3f;
int n, nx, ny;
int lx[N], ly[N], slack[N], match[N], s[N][N];
bool visx[N], visy[N];
char str1[LEN], str2[LEN];

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 d = INF;
                for(int j = 0; j < ny; j++)
                    if(!visy[j]) d = min(d, slack[j]);
                for(int j = 0; j < nx; j++)
                    if(visx[j]) lx[j] -= d;
                for(int j = 0; j < ny; j++)
                    if(visy[j]) ly[j] += d;
                    else slack[j] -= d;
            }
        }
    }
}

void input(char str[], int n)
{
    for(int i = 0; i < n; i++)
        scanf(" %c", &str[i]);
}

int main()
{
    int t, n, m, k;

    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d%d", &n, &k, &m);
        input(str1, n);
        while(m--)
        {
            input(str2, n);
            memset(s, 0, sizeof s);
            for(int i = 0; i < n; i++)
                s[ str2[i]-'A' ][ str1[i]-'A' ]++;

            nx = 26, ny = 26;
            km();

            int res = 0;
            for(int i = 0; i < ny; i++)
                res += s[match[i]][i];
            printf("%.4f\n", 1.0 * res / n);
        }
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值