HDU_2236
To ensure that each column in each row has only one element, we can start with the idea of the maximum matching of the Bipartite Graph and view the rows and columns as the left and right parts of the Bipartite Graph, the Edge Weight of I-j is the value of the element in column j of row I. In this way, the maximum matching four sides of the obtained bipartite graph are the four elements that are not in the same row or in the same column.
With this idea, we only need to ensure that the difference between the maximum and minimum values of the four elements is as small as possible. Therefore, we can calculate the difference between the maximum and minimum values in binary enumeration, and enumerate the lower boundary of Edge Weight. If the bottom boundary of an edge weight is enumerated, max is updated if the graph has a maximum matching value. Otherwise, min is updated.
#include<stdio.h>
#include<string.h>
int n,G[110][110],xM[110],yM[110],check[110];
int max,min,mid,gmin,gmax,p;
int searchpath(int u)
{
int v;
for(v=0;v<n;v++)
if(G[u][v]>=p&&G[u][v]<=p+mid&&!check[v])
{
check[v]=1;
if(yM[v]==-1||searchpath(yM[v]))
{
yM[v]=u;
xM[u]=v;
return 1;
}
}
return 0;
}
int judge()
{
int i;
memset(xM,-1,sizeof(xM));
memset(yM,-1,sizeof(yM));
for(i=0;i<n;i++)
{
memset(check,0,sizeof(check));
if(!searchpath(i))
return 0;
}
return 1;
}
int main()
{
int i,j,k,T,t,ok;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
gmin=100;
gmax=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&G[i][j]);
if(G[i][j]<gmin)
gmin=G[i][j];
if(G[i][j]>gmax)
gmax=G[i][j];
}
max=gmax-gmin;
min=0;
while(1)
{
mid=(min+max)/2;
ok=0;
for(p=gmin;p+mid<=gmax;p++)
if(judge())
{
ok=1;
break;
}
if(ok)
max=mid;
if(mid==min)
break;
if(!ok)
min=mid;
}
printf("%d\n",max);
}
return 0;
}