1222 信与信封问题
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 钻石 Diamond
题目描述 Description
John先生晚上写了n封信,并相应地写了n个信封将信装好,准备寄出。但是,第二天John的儿子Small John将这n封信都拿出了信封。不幸的是,Small John无法将拿出的信正确地装回信封中了。
将Small John所提供的n封信依次编号为1,2,…,n;且n个信封也依次编号为1,2,…,n。假定Small John能提供一组信息:第i封信肯定不是装在信封j中。请编程帮助Small John,尽可能多地将信正确地装回信封。
输入描述 Input Description
n文件的第一行是一个整数n(n≤100)。信和信封依次编号为1,2,…,n。
n接下来的各行中每行有2个数i和j,表示第i封信肯定不是装在第j个信封中。文件最后一行是2个0,表示结束。
输出描述 Output Description
输出文件的各行中每行有2个数i和j,表示第i封信肯定是装在第j个信封中。请按信的编号i从小到大顺序输出。若不能确定正确装入信封的任何信件,则输出“none”。
样例输入 Sample Input
3
1 2
1 3
2 1
0 0
样例输出 Sample Output
1 1
二分图匹配变式。。
要求出可以确定的对应关系。。
那么先求出反图中的完美匹配,然后枚举匹配中的边,那么在不使用这条边的情况下不能得到完美匹配,那么该边一定在匹配中。。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<iomanip>
#include<ctime>
#include<climits>
#include<cctype>
#include<algorithm>
using namespace std;
const int maxn=105;
struct Edge
{
int letter,mail;
Edge(int _u=0,int _v=0)
{
letter=_u;
mail=_v;
}
bool operator < (const Edge &e) const
{
return letter<e.letter;
}
};
vector <Edge> edge,ans;
int g[maxn][maxn];
bool g0[maxn][maxn];
int n;
int mail[maxn];
bool exist[maxn];
int last_mail;
Edge out;
int hungarian(int u)//u must be the same side -- letter!! coz following is the mail[v], goes back to letter
{
for(int i=1;i<=g[u][0];i++)
{
int v=g[u][i];
if(u==out.letter&&v==out.mail) continue;
if(!exist[v])
{
exist[v]=true;
if(mail[v]==-1 || hungarian(mail[v]))
{
mail[v]=u;
return 1;
}
}
}
return 0;
}
int maxmatch()
{
memset(mail,-1,sizeof(mail));
int ret=0;
for(int i=1;i<=n;i++)
{
memset(exist,false,sizeof(exist));
ret+=hungarian(i);
}
return ret;
}
int main()
{
freopen("match.in","r",stdin);
freopen("match.out","w",stdout);
cin>>n;
int u,v;
while(scanf("%d%d",&u,&v)==2 && u!=0 && v!=0) g0[u][v]=true;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(!g0[i][j]) g[i][++g[i][0]]=j;
if(maxmatch()!=n){ printf("none");exit(0); }
for(int i=1;i<=n;i++)
edge.push_back(Edge(mail[i],i));
for(int i=0;i<edge.size();i++)
{
out=edge[i];
if(maxmatch()!=n) { ans.push_back(out);}
}
if(ans.size()==0) { printf("none");exit(0); }
sort(ans.begin(),ans.end());
for(int i=0;i<ans.size();i++)
printf("%d %d\n",ans[i].letter,ans[i].mail);
return 0;
}