hdoj1914(稳定婚姻问题)

/***************************************************************\
* Author: Hu Wenbiao
* Created Time: Sun 12 Sep 2010 08:36:41 M CST
* File Name: main.cpp
* Description: 延迟认可算法。
\***************************************************************/
//*========================*Head File*========================*\\

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
/*----------------------*Global Variable*----------------------*/
struct PERSON {
    int cur;			//对男士来说是即将表白的对象在它的列表中的位置,对女
						//士来说是她现在的对象。
    int rank[27];		//列表
} M[27], F[27];
int T, n, m, f, LOVE[27][27];	//F[i][j]女士i对男士j的好感度,0最高,25最低
char ch;
bool exist_m[27], exist_f[27];
//*=======================*Main Program*=======================*//
using namespace std;

int solve(int m)
{				//m向M[m].rank[M[m].cur]表白,返回失恋者
    f = M[m].rank[M[m].cur];
    int cur = F[f].cur;
    if (LOVE[f][m] < LOVE[f][cur]) {
	F[f].cur = m;
	return cur;
    } else
	return m;
}

int main()
{
//freopen("input","r",stdin);
    scanf("%d", &T);
    queue < int >q;

    while (T--) {
	scanf("%d", &n);
	memset(M, 0, sizeof(M));
	memset(F, 0, sizeof(F));
	memset(exist_m, 0, sizeof(exist_m));
	memset(exist_f, 0, sizeof(exist_f));
	for (int i = 0; i < n; i++) {
	    while (scanf("%c", &ch), ch < 'a' || ch > 'z');
	    ch -= 'a';
	    exist_m[ch] = true;
	    q.push((int) ch);	//男士加入单身队列
	}
	for (int i = 0; i < n; i++) {
	    while (scanf("%c", &ch), ch < 'A' || ch > 'Z');
	    ch -= 'A';
	    exist_f[ch] = true;
	}
	for (int i = 0; i < n; i++) {
	    while (scanf("%c", &ch), ch < 'a' || ch > 'z');
	    m = ch - 'a';
	    for (int j = 0; j < n; j++) {
		while (scanf("%c", &ch), ch < 'A' || ch > 'Z');
		M[m].rank[j] = ch - 'A';
	    }
	}
	for (int i = 0; i < n; i++) {
	    while (scanf("%c", &ch), ch < 'A' || ch > 'Z');
	    f = ch - 'A';
	    for (int j = 0; j < n; j++) {
		while (scanf("%c", &ch), ch < 'a' || ch > 'z');
		LOVE[f][ch - 'a'] = j;
	    }
	}
	for (int i = 0; i < 27; i++)
	    F[i].cur = 26;	//女士对象全部初始化为26
	for (int i = 0; i < 27; i++)
	    LOVE[i][26] = 26;	//女士对26的好感度最低
	while (!q.empty()) {
	    m = q.front();
	    q.pop();

	    int fail = solve(m);
	    if (fail == 26)
		continue;
	    M[fail].cur++;
	    q.push(fail);
	}
	for (int i = 0; i < 26; i++) {
	    if (exist_m[i])
		for (int j = 0; j < 27; j++)
		    if (F[j].cur == i) {
			printf("%c %c\n", 'a' + i, 'A' + j);
			break;
		    }
	}
	if (T)
	    printf("\n");
    }
}

posted @ 2010-09-14 20:05  open source  阅读(356)  评论(0编辑  收藏  举报