程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> HDU 3722 Card Game(KM最大匹配)

HDU 3722 Card Game(KM最大匹配)

編輯:C++入門知識

HDU 3722 Card Game(KM最大匹配)


HDU 3722 Card Game

題目鏈接

題意:給定一些字符串,每次可以選兩個a,b出來,a的前綴和b的後綴的最長公共長度就是獲得的值,字符串不能重復選,問最大能獲得多少值

思路:KM最大匹配,兩兩串建邊,跑最大匹配即可

代碼:

#include 
#include 
#include 
#include 
using namespace std;

const int MAXNODE = 205;

typedef int Type;
const Type INF = 0x3f3f3f3f;

struct KM {
	int n, m;
	Type g[MAXNODE][MAXNODE];
	Type Lx[MAXNODE], Ly[MAXNODE], slack[MAXNODE];
	int left[MAXNODE], right[MAXNODE];
	bool S[MAXNODE], T[MAXNODE];

	void init(int n, int m) {
		this->n = n;
		this->m = m;
		memset(g, 0, sizeof(g));
	}

	void add_Edge(int u, int v, Type val) {
		g[u][v] = val;
	}

	bool dfs(int i) {
		S[i] = true;
		for (int j = 0; j < m; j++) {
			if (T[j]) continue;
			Type tmp = Lx[i] + Ly[j] - g[i][j];
			if (!tmp) {
				T[j] = true;
				if (left[j] == -1 || dfs(left[j])) {
					left[j] = i;
					right[i] = j;
					return true;
				}
			} else slack[j] = min(slack[j], tmp);
		}
		return false;
	}

	void update() {
		Type a = INF;
		for (int i = 0; i < m; i++)
			if (!T[i]) a = min(a, slack[i]);
		for (int i = 0; i < n; i++)
			if (S[i]) Lx[i] -= a;
		for (int i = 0; i < m; i++)
			if (T[i]) Ly[i] += a;
	}

	Type km() {
		memset(left, -1, sizeof(left));
		memset(right, -1, sizeof(right));
		memset(Ly, 0, sizeof(Ly));
		for (int i = 0; i < n; i++) {
			Lx[i] = -INF;
			for (int j = 0; j < m; j++)
				Lx[i] = max(Lx[i], g[i][j]);
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) slack[j] = INF;
			while (1) {
				memset(S, false, sizeof(S));
				memset(T, false, sizeof(T));
				if (dfs(i)) break;
				else update();
			}
		}
		Type ans = 0;
		for (int i = 0; i < n; i++) {
			if (right[i] == -1) return -1;
			if (g[i][right[i]] == -INF) return -1;
			ans += g[i][right[i]];
		}
		return ans;
	}
} gao;

int n;
char str[205][1005];

int cal(char *a, char *b) {
	int an = strlen(a), bn = strlen(b);
	int tot = min(an, bn);
	int cnt = 0;
	for (int i = 0; i < tot; i++) {
		if (a[i] != b[bn - i - 1]) break;
		cnt++;
	}
	return cnt;
}

int main() {
	while (~scanf("%d", &n)) {
		gao.init(n, n);
		for (int i = 0; i < n; i++) {
			scanf("%s", str[i]);
			for (int j = 0; j < i; j++) {
				gao.add_Edge(i, j, cal(str[i], str[j]));
				gao.add_Edge(j, i, cal(str[j], str[i]));
			}
		}
		printf("%d\n", gao.km());
	}
	return 0;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved