In this question, the maximum weight is calculated using the km () algorithm, but the minimum cost is required,
The distance from people to the House should be negative. If the distance from others is negative infinity
You can add a negative number to the final result of KM ..
It should be noted that N is the number of people, and then calculate the number of people
The distance of each house is stored in map ..
# Include "stdio. H"
# Include "string. H"
# Include "math. H"
Int map [1000] [1000];
Int SX [1000], Sy [1000];
Int lx [1000], Ly [1000];
Int link [1000], N;
# Define INF 0x7fffffff
Int find (int K)
{
Int I;
SX [k] = 1;
For (I = 0; I <n; I ++)
{
If (SY [I] = 0 & lx [k] + ly [I] = map [k] [I])
{
Sy [I] = 1;
If (link [I] =-1 | find (link [I])
{
Link [I] = K;
Return 1;
}
}
}
Return 0;
}
Int km ()
{
Int I, J, K, D;
Memset (LX, 0, sizeof (LX ));
Memset (ly, 0, sizeof (ly ));
Memset (link,-1, sizeof (Link ));
For (I = 0; I <n; I ++)
For (j = 0; j <n; j ++)
If (LX [I] <map [I] [J])
Lx [I] = map [I] [J];
For (I = 0; I <n; I ++)
{
While (1)
{
Memset (sx, 0, sizeof (SX ));
Memset (SY, 0, sizeof (SY ));
D = inf;
If (find (I ))
Break;
For (j = 0; j <n; j ++)
{
If (SX [J])
For (k = 0; k <n; k ++)
If (! Sy [k])
{
If (D> lx [J] + ly [k]-map [J] [k])
D = Lx [J] + ly [k]-map [J] [k];
}
}
For (j = 0; j <n; j ++)
{
If (SX [J])
Lx [J]-= D;
If (SY [J])
Ly [J] + = D;
}
}
}
Int sum = 0;
For (I = 0; I <n; I ++)
{
Sum + = map [LINK [I] [I];
}
Return sum;
}
Int main ()
{
Int I, J, K, h, T, T1, T2, P;
Char STR [1, 1000] [2, 100];
While (scanf ("% d", & K, & H), k | H)
{
N = 0;
Memset (MAP, 0, sizeof (MAP ));
For (I = 0; I <K; I ++)
{
Scanf ("% s", STR [I]);
For (j = 0; j If (STR [I] [J] = 'M ')
N ++;
}
T1 = 0; t2 = 0;
For (I = 0; I <K; I ++)
{
For (j = 0; j {
If (STR [I] [J] = 'M ')
{
For (P = 0; P <K; P ++)
For (t = 0; t If (STR [p] [T] = 'H ')
{
Map [T1] [T2] =-1 * (ABS (p-I) + ABS (t-j ));
T2 ++;
}
T1 ++;
T2 = 0;
}
}
}
For (I = 0; I <K; I ++)
For (j = 0; j If (Map [I] [J] = 0)
Map [I] [J] =-INF;
Printf ("% d \ n",-km ());
}
Return 0;
}