UVA 10269 Adventure of Super Mario

UVA_10269

    由于马里奥的飞行距离有限,因此为了方便处理,我们首先用floyd预处理出马里奥可以飞行的两点间的最短路,然后再将图分成K+1层用SPFA求最短路即可。

#include<stdio.h>
#include<string.h>
#define MAXD 130
#define MAXN 20
#define INF 1000000000
int A, B, M, L, K, N;
int G[MAXD][MAXD], d[MAXD][MAXN], st[MAXD * MAXN];
int q[MAXD * MAXN], inq[MAXD][MAXN];
void init()
{
int i, j, k, a, b, t;
scanf("%d%d%d%d%d", &A, &B, &M, &L, &K);
N = A + B;
for(i = 1; i <= N; i ++)
for(j = 1; j <= N; j ++)
{
if(i == j)
G[i][j] = 0;
else
G[i][j] = INF;
}
for(i = 0; i < M; i ++)
{
scanf("%d%d%d", &a, &b, &t);
G[a][b] = G[b][a] = t;
}
}
void floyd()
{
int i, j, k;
for(k = 1; k <= N; k ++)
for(i = 1; i <= N; i ++)
for(j = 1; j <= N; j ++)
if(k <= A && G[i][k] + G[k][j] < G[i][j])
G[i][j] = G[i][k] + G[k][j];
}
int SPFA()
{
int i, j, k, u, v, front, rear, max = (K + 1) * N;
front = rear = 0;
memset(inq, 0, sizeof(0));
for(i = 1; i <= N; i ++)
for(j = 0; j <= K; j ++)
d[i][j] = INF;
d[N][0] = 0;
q[rear] = N;
st[rear] = 0;
rear ++;
while(front != rear)
{
u = q[front];
k = st[front];
front ++;
if(front > max)
front = 0;
inq[u][k] = 0;
for(v = 1; v <= N; v ++)
{
if(G[u][v] + d[u][k] < d[v][k])
{
d[v][k] = G[u][v] + d[u][k];
if(!inq[v][k])
{
q[rear] = v;
st[rear] = k;
rear ++;
if(rear > max)
rear = 0;
inq[v][k] = 1;
}
}
if(G[u][v] <= L && k < K && d[u][k] < d[v][k + 1])
{
d[v][k + 1] = d[u][k];
if(!inq[v][k + 1])
{
q[rear] = v;
st[rear] = k + 1;
rear ++;
if(rear > max)
rear = 0;
inq[v][k + 1] = 1;
}
}
}
}
int res = INF;
for(i = 0; i <= K; i ++)
if(d[1][i] < res)
res = d[1][i];
return res;
}
int main()
{
int t;
scanf("%d", &t);
while(t --)
{
init();
floyd();
int res = SPFA();
printf("%d\n", res);
}
return 0;
}


你可能感兴趣的:(super)