【KM匹配】 HDOJ 3718 Similarity

由于二分图匹配的时候两边的点数不相同,所以要把两边点数补全,都补到26个点。。。。。

#include <iostream>
#include <queue> 
#include <stack> 
#include <map> 
#include <set> 
#include <bitset> 
#include <cstdio> 
#include <algorithm> 
#include <cstring> 
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 35
#define maxm 400005
#define eps 1e-10
#define mod 1000000007
#define INF 99999999
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
// head

int g[maxn][maxn];
int linker[maxn];
int slack[maxn];
int hash1[maxn];
int hash2[maxn];
int visx[maxn];
int visy[maxn];
int lx[maxn];
int ly[maxn];
int a[10005];
int b[10005];
char s[100];
int c[50];
int n, nx, ny, m, k;

bool dfs(int x)
{
	visx[x] = true;
	for(int y = 0; y < ny; y++) {
		if(visy[y]) continue;
		int tmp = lx[x] + ly[y] - g[x][y];
		if(!tmp) {
			visy[y] = true;
			if(linker[y] == -1 || dfs(linker[y])) {
				linker[y] = x;
				return true;
			}
		}
		else slack[y] = min(slack[y], tmp);
	}
	return false;
}

int km()
{
	memset(linker, -1, sizeof linker);
	memset(ly, 0, sizeof ly);
	for(int i = 0; i < nx; i++) {
		lx[i] = -INF;
		for(int j = 0; j < ny; j++)
			lx[i] = max(lx[i], g[i][j]);
	}
	for(int x = 0; x < nx; x++) {
		for(int i = 0; i < ny; i++)
			slack[i] = INF;
		while(true) {
			memset(visx, 0, sizeof visx);
			memset(visy, 0, sizeof visy);
			if(dfs(x)) break;
			int d = INF;
			for(int i = 0; i < ny; i++)
				if(!visy[i] && d > slack[i])
					d = slack[i];
			for(int i = 0; i < nx; i++)
				if(visx[i]) lx[i] -= d;
			for(int i = 0; i < ny; i++)
				if(visy[i]) ly[i] += d;
				else slack[i] -= d;
		}
	}

	int res = 0;
	for(int i = 0; i < ny; i++) res += g[linker[i]][i];
	return res;
}

void read()
{
	scanf("%d%d%d", &n, &k, &m);
	for(int i = 0; i < n; i++) {
		scanf("%s", s);
		a[i] = s[0] - 'A';
	}
	nx = ny = 26;
}

void build()
{
	memset(g, 0, sizeof g);
	for(int i = 0; i < n; i++) {
		scanf("%s", s);
		b[i] = s[0] - 'A';
	}
	for(int i = 0; i < n; i++) g[a[i]][b[i]]++;
}

void work()
{
	while(m--) {
		build();
		int res = km(); 
		double ans = n;
		ans = res * 1.0 / ans;
		printf("%.4f\n", ans);
	}
}

int main()
{
	int _;
	while(scanf("%d", &_)!=EOF) {
		while(_--) {
			read();
			work();
		}
	}
	
	
	return 0;
}


你可能感兴趣的:(hdoj)