HDU 1914(稳定婚姻系统)

很经典的一道题目 几乎不用建模了 用hash记录ID号 然后套模版就OK了~~~

 

以下是代码:

 

 

#include <iostream>
#include 
<queue>
using namespace std;

#define MAX 1010

long n;
long mlove[MAX][MAX];
long wlove[MAX][MAX]; 
long couple[MAX];
long pare[MAX];

queue 
< long > SQ;
void gale_shapley()
{
    
long i,man,woman;
    
    
while(!SQ.empty()) 
        SQ.pop();
    memset(couple, 
-1sizeof(couple));
    
    
for(i=1;i<=n;i++
        SQ.push(i);
    
    
while(!SQ.empty())
    {
        man 
= SQ.front();    
        SQ.pop();
        
for(i=1;i<=n;i++)
        {
            
if(mlove[man][i] != -1
            {
                
//选择未被拒绝且最喜欢的女生
                woman = mlove[man][i];
                mlove[man][i] 
= -1;
                
long pre = couple[woman];
                
if(pre == -1
                {
                    couple[woman] 
= man;
                    pare[man] 
= woman;
                    
break;
                }
                
else 
                {
                    
if(wlove[woman][man] > wlove[woman][pre])
                    {
                        SQ.push(pre);
                        couple[woman] 
= man;
                        pare[man] 
= woman;                    
                        
break;
                    }
                }
            }
        }
    }
}

long hash[256];
char m_rev[256];
char w_rev[256];
char str[1000];
int main()
{
    
long i, j, t;
    scanf(
"%ld"&t);
    
long b=1;
    
while(t--)
    {
        
if (b==1)
        {
            
++b;
        }
        
else
        {
            puts(
"");
        }
        scanf(
"%ld"&n);
        memset(hash,
0,sizeof(hash));

        getchar();
        
for (i=1;i<=n;++i)
        {
            
char ch;
            scanf(
"%c ",&ch);
            hash[ch]
=i;    
            m_rev[i]
=ch;
        }

        
for (i=1;i<=n;++i)
        {
            
char ch;
            scanf(
"%c ",&ch);
            hash[ch]
=i;    
            w_rev[i]
=ch;
        }
    
         
for(i = 1; i <= n; i++)
         {
            
char ch;
            scanf(
"%c:%s",&ch,str);
            getchar();
             
for(j = 1; j <= n; j++)
             {
                 mlove[hash[ch]][j]
=hash[str[j-1]];//记录喜欢的人的号码
             }
        }

         
for(i = 1; i <= n; i++)
         {
            
char ch;
            scanf(
"%c:%s",&ch,str);
            getchar();
            
for(j = 1; j <= n; j++)
            {
                wlove[hash[ch]][hash[str[j
-1]]] = n - j;//记录喜欢程度从大到小
            }
        }
                
        gale_shapley();

        
for(i = 'a'; i <= 'z'; i++)
        {
            
if(hash[i])
            {
                printf(
"%c %c\n", i,w_rev[pare[hash[i]]]);//对于男方的配偶
            }
        }
    }
    
return 0;
}
posted @ 2008-09-07 11:11  Hdu-Lost  阅读(454)  评论(0编辑  收藏  举报