HDU 2236 no question II

Source: Internet
Author: User

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;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.