这题A 的很是纠结,从下午5点多开始做到现在,一直WA。。。其中滋味,别提了。。。请容我发泄两句。。。1385!WA你妹啊!!!
My Code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 105;
const int inf = 10000000;
int dis[N][N];
int map[N][N];
int low[N];
int vis[N];
int pre[N];
int v[N];
int cmp(int src, int dest1, int dest2)
{
int path1[N], path2[N];
int len1 = 0, len2 = 0;
memset(path1, 0, sizeof(path1));
memset(path2, 0, sizeof(path2));
while (src != dest1)
{
path1[len1++] = dest1;
dest1 = pre[dest1];
}
while (src != dest2)
{
path2[len2++] = dest2;
dest2 = pre[dest2];
}
while (path1[len1-1] == path2[len2-1])
{
len1--;
len2--;
}
return path1[len1-1] < path2[len2-1];
}
void Dijkstra(int n, int v)
{
int flag, i, j, min;
for(i = 1; i <= n; i++)
{
low[i] = dis[v][i];
vis[i] = 0;
if(dis[v][i] >= inf)
pre[i] = 0;
else
pre[i] = v;
}
vis[v] = 1;
low[v] = 0;
for(i = 2; i <= n; i++)
{
min = inf; flag = -1;
for(j = 1; j <= n; j++)
{
if(min > low[j] && !vis[j])
{
min = low[j];
flag = j;
}
}
if(flag == -1)
continue;
vis[flag] = 1;
for(j = 1; j <= n; j++)
{
if(!vis[j] && dis[flag][j] < inf)
{
int tmp = dis[flag][j] + low[flag];
if(tmp < low[j])
{
low[j] = tmp;
pre[j] = flag;
}
if(tmp == low[j])
{
if(cmp(v, flag, pre[j]))
{
pre[j] = flag;
}
}
//printf("%d %d\n", j, pre[j]);
}
}
}
}
void printroad(int a, int b)
{
int sta[N];
int len = 0;
int root = b;
while(root != a)
{
sta[len++] = root;
root = pre[root];
}
printf("%d", a);
while(len > 0)
{
printf("-->%d", sta[len-1]);
len--;
}
printf("\n");
}
int main()
{
//freopen("data.in", "r", stdin);
int n, i, j, a, b;
while(scanf("%d", &n), n)
{
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
{
scanf("%d", &map[i][j]);
if(map[i][j] == -1)
map[i][j] = inf;
}
for(i = 1; i <= n; i++)
scanf("%d", &v[i]);
while(~scanf("%d%d", &a, &b))
{
if(a == -1 && b == -1)
break;
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
{
if(j == a || j == b || i == j)
dis[i][j] = map[i][j];
else
dis[i][j] = map[i][j] + v[j];
}
Dijkstra(n, a);
printf("From %d to %d :\n", a, b);
printf("Path: ");
printroad(a, b);
printf("Total cost : %d\n\n", low[b]);
}
}
return 0;
}