UVA 10986 - Sending email


这道题就是在求最短路,而且是单源最短路吗,所以我先想到了dijkstra算法,结果TLE了,

dijkstra的代码:

#include<stdio.h>
#include<string.h>
#define INF 200000005
#define MAXD 20005
int u, v, w, S, T, n, m, N;
int d[MAXD][MAXD], f[MAXD];
bool vis[MAXD];

int min( int a, int b)
{
return a < b ? a : b;
}

void init()
{
for( int i = 0; i < n; i ++)
f[i] = ( i == S ? 0 : INF );
memset( vis, false, sizeof vis);
for( int i = 0; i < n; i ++)
for( int j = 0; j < n; j ++)
{
if( i == j) d[i][j] = 0;
else d[i][j] = INF;
}
for( int i = 0; i < m; i ++)
{
scanf( "%d%d%d", &u, &v, &w);
d[u][v] = d[v][u] = w;
}
}

void dijkstra()
{
for( int i = 0; i < n; i ++)
{
int x, tt = INF;
for( int y = 0; y < n; y ++)
if( !vis[y] && f[y] <= tt)
tt = f[ x = y];
vis[x] = true;
for( int y = 0; y < n; y ++) {
f[y] = min( f[y], f[x] + d[x][y]);
}
}
}

int main()
{
scanf( "%d", &N);
for( int cas = 1; cas <= N; cas ++)
{
scanf( "%d%d%d%d", &n, &m, &S, &T);
init();
dijkstra();
if( f[T] >= INF) printf( "Case #%d: unreachable\n", cas);
else
printf( "Case #%d: %d\n", cas, f[T]);
}
return 0;
}

下面参考了staginner的SPFA:

#include<stdio.h>
#include<string.h>
#define MAXD 100005
#define INF 200000005

int N, n, m, S, T, e, a, b, c, cas;
int first[MAXD], next[MAXD], v[MAXD], w[MAXD], d[MAXD], q[MAXD];
bool inq[MAXD];

void input( int a, int b, int c)
{
v[e] = b;
w[e] = c;
next[e] = first[a];
first[a] = e;
e ++;
}

void init()
{
scanf( "%d%d%d%d", &n, &m, &S, &T);
memset( first, -1, sizeof first);
e = 0;
for( int i = 0; i < m; i ++)
{
scanf( "%d%d%d", &a, &b, &c);
input( a, b, c);
input( b, a, c);
}
}

void SPFA()
{
int front, rear, u;
front = rear = 0;
for( int i = 0; i < n; i ++)
d[i] = ( i == S ? 0 : INF);
q[rear ++] = S;
while( front != rear)
{
u = q[front ++];
if( front == n) front = 0;
inq[u] = false;
for( int i = first[u]; i != -1; i = next[i])
if( d[u] + w[i] < d[v[i]])
{
d[ v[i] ] = d[u] + w[i];
if( !inq[ v[i] ])
{
q[rear ++] = v[i];
if( rear == n) rear = 0;
inq[ v[i]] = true;
}
}
}
if( d[T] == INF)
printf( "Case #%d: unreachable\n", cas);
else
printf( "Case #%d: %d\n", cas, d[T]);
}

int main()
{
scanf( "%d", &N);
for( cas = 1; cas <= N; cas ++)
{
init();
SPFA();
}
return 0;
}



 

 

你可能感兴趣的:(email)