HDU 2448 Mining Station on the Sea

HDU_2448

    首先求出各个港口和船之间的最短路,然后用KM算法求二分图最优匹配即可。

#include<stdio.h>
#include<string.h>
#define MAXD 110
#define INF 1000000000
#define MAX 100000
int M, K, P, N, d[MAXD], G[MAXD][MAXD], yM[MAXD];
int A[MAXD], B[MAXD], slack, visx[MAXD], visy[MAXD];
int f[2 * MAXD][2 * MAXD];
void init()
{
int i, j, k, a, b, c, temp;
memset(f, -1, sizeof(f));
for(i = 0; i < N; i ++)
{
scanf("%d", &d[i]);
d[i] --;
}
for(i = 0; i < K; i ++)
{
scanf("%d%d%d", &a, &b, &c);
a --;
b --;
f[a][b] = f[b][a] = c;
}
for(i = 0; i < M; i ++)
f[i][i] = 0;
for(k = 0; k < M; k ++)
for(i = 0; i < M; i ++)
for(j = 0; j < M; j ++)
if(f[i][k] != -1 && f[k][j] != -1)
{
temp = f[i][k] + f[k][j];
if(f[i][j] == -1 || temp < f[i][j])
f[i][j] = temp;
}
memset(G, 0, sizeof(G));
for(i = 0; i < P; i ++)
{
scanf("%d%d%d", &a, &b, &c);
a --;
b --;
for(j = 0; j < N; j ++)
{
temp = MAX - (c + f[b][d[j]]);
if(temp > G[a][j])
G[a][j] = temp;
}
}
}
int searchpath(int u)
{
int v, temp;
visx[u] = 1;
for(v = 0; v < N; v ++)
if(!visy[v])
{
temp = A[u] + B[v] - G[u][v];
if(temp == 0)
{
visy[v] = 1;
if(yM[v] == -1 || searchpath(yM[v]))
{
yM[v] = u;
return 1;
}
}
else if(temp < slack)
slack = temp;
}
return 0;
}
void EK()
{
int i, j, u;
for(i = 0; i < N; i ++)
{
A[i] = 0;
for(j = 0; j < N; j ++)
if(G[i][j] > A[i])
A[i] = G[i][j];
}
memset(B, 0, sizeof(B));
memset(yM, -1, sizeof(yM));
for(u = 0; u < N; u ++)
for(;;)
{
memset(visx, 0, sizeof(visx));
memset(visy, 0, sizeof(visy));
slack = INF;
if(searchpath(u))
break;
for(i = 0; i < N; i ++)
{
if(visx[i])
A[i] -= slack;
if(visy[i])
B[i] += slack;
}
}
}
void printresult()
{
int i, res = 0;
for(i = 0; i < N; i ++)
res += MAX - G[yM[i]][i];
printf("%d\n", res);
}
int main()
{
while(scanf("%d%d%d%d", &N, &M, &K, &P) == 4)
{
init();
EK();
printresult();
}
return 0;
}


你可能感兴趣的:(HDU)