題目大意:1,西服有六種款式{"XXL", "XL", "L", "M", "S", "XS"},給出西服總數,保證西服總數是衣服款式的整數倍,即每款西服數量相同;
2,每個人可選擇兩款衣服,但一個人只能挑一件適合自己的衣服;
3,若最後所有人都有適合自己的衣服,輸出YES,否則輸出NO;
解題策略:1,很明顯的二部圖最大匹配,只不過要最後檢驗每個人是否被匹配到;
2,建圖時,將每款衣服拆成每件衣服,二部圖模型={西服總數,人};
3,練習了一下用鄰接矩陣求最大匹配,還有就是調試的過程要細心,我在調試的過程中一直忘記在Main函數里加Initial()函數,結果老不對。。汗。
/*
UVA 11045 My T-shirt suits me
AC by J_Dark
ON 2013/4/21
Time 0.016s
*/
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <map>
using namespace std;
const int maxn = 40;
map <string, int> Suit;
int suitNum, perNum, NN, g[maxn][maxn];
bool visited[maxn];
int perMatch[maxn], suitMatch[maxn];
/////////////////////////////////////////////////////////
//建立西服款式與數字一一映射,用Map實現
void Prepare(){
string suitSize[6]={"XXL", "XL", "L", "M", "S", "XS"};
for(int i=0; i<6; i++)
Suit.insert(pair<string,int>(suitSize[i], i));
}
void Initial(){
memset(g, 0, sizeof(g));
memset(visited, false, sizeof(visited));
}
void Input(){
cin >> suitNum >> perNum;
NN = suitNum / 6;
string s1, s2;
//將每種款式衣服拆成NN件衣服
for(int i=0; i<perNum; i++){
cin >> s1 >> s2;
for(int k=0; k<NN; k++){
g[i][Suit[s2]*NN+k] = g[i][Suit[s1]*NN+k] = 1;
}
}
}
bool findPath(int u){
for(int i=0; i<suitNum; i++){
if(g[u][i] && !visited[i]){
visited[i] = true;
if(suitMatch[i]== -1 || findPath(suitMatch[i])){
perMatch[u] = i;
suitMatch[i] = u;
return true;
}
}
}
return false;
}
void MaxMatch(){
for(int i=0; i<perNum; i++) perMatch[i] = -1;
for(int i=0; i<suitNum; i++) suitMatch[i] = -1;
int maxMatch = 0;
for(int i=0; i<perNum; i++){
if(perMatch[i] == -1){ //發現未挑衣服者(未蓋點)
memset(visited, false, sizeof(visited));
if(findPath(i)){
maxMatch++;
}
}
}
int ff=1;
//尋找是否有未匹配的人
for(int i=0; i<perNum; i++){
if(perMatch[i] == -1){
ff = 0;
break;
}
}
//cout << maxMatch << " ";
if(ff) cout << "YES" << endl;
else cout << "NO" << endl;
}
///////////////////////////////
int main(){
int testCase;
Prepare();
while(cin >> testCase)
{
while(testCase--)
{
Initial();
Input();
MaxMatch();
}
}
return 0;
}