最短路径+路径保存+字典序。由于这都是模板题,多练就行。
今天下午不知道为什么感觉比较忧伤,可能是因为想起了那女生吧,弄得我魂不守舍的。
过去了就真的永远回不去了。
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
const int SIZE = 1001;
const int INF = 0x3f3f3f3f;
int d[SIZE][SIZE];
int path[SIZE][SIZE];
int tax[SIZE];
int n;
void Floyd()
{
int i, j, k;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
path[i][j] = j;
}
}
for(k = 1; k <= n; k++)
{
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
int m = d[i][k] + d[k][j] + tax[k];
if(m < d[i][j]) //松弛
{
d[i][j] = m;
path[i][j] = k;
}
if(m == d[i][j] && path[i][j] > path[i][k]) //更新字典序
{
path[i][j] = path[i][k];
}
}
}
}
}
void init()
{
memset(tax, 0, sizeof(tax));
memset(d, INF, sizeof(d));
memset(path, 0, sizeof(path));
}
int main()
{
int i, j;
int beg, end;
while(~scanf("%d", &n), n )
{
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
scanf("%d", &d[i][j]);
d[i][j] = (d[i][j] == -1)? INF:d[i][j];
}
}
for(i = 1; i <= n; i++) scanf("%d", &tax[i]);
Floyd();
while(scanf("%d%d", &beg, &end))
{
if(beg == -1 && end == -1) break;
printf("From %d to %d :\n", beg, end);
printf("Path: %d", beg);
int res = beg;
while(res != end)
{
printf("-->%d", path[res][end]);
res = path[res][end];
}
printf("\nTotal cost : %d\n\n", d[beg][end]);
}
}
return 0;
}
#include <stdlib.h>
#include <string.h>
using namespace std;
const int SIZE = 1001;
const int INF = 0x3f3f3f3f;
int d[SIZE][SIZE];
int path[SIZE][SIZE];
int tax[SIZE];
int n;
void Floyd()
{
int i, j, k;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
path[i][j] = j;
}
}
for(k = 1; k <= n; k++)
{
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
int m = d[i][k] + d[k][j] + tax[k];
if(m < d[i][j]) //松弛
{
d[i][j] = m;
path[i][j] = k;
}
if(m == d[i][j] && path[i][j] > path[i][k]) //更新字典序
{
path[i][j] = path[i][k];
}
}
}
}
}
void init()
{
memset(tax, 0, sizeof(tax));
memset(d, INF, sizeof(d));
memset(path, 0, sizeof(path));
}
int main()
{
int i, j;
int beg, end;
while(~scanf("%d", &n), n )
{
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
scanf("%d", &d[i][j]);
d[i][j] = (d[i][j] == -1)? INF:d[i][j];
}
}
for(i = 1; i <= n; i++) scanf("%d", &tax[i]);
Floyd();
while(scanf("%d%d", &beg, &end))
{
if(beg == -1 && end == -1) break;
printf("From %d to %d :\n", beg, end);
printf("Path: %d", beg);
int res = beg;
while(res != end)
{
printf("-->%d", path[res][end]);
res = path[res][end];
}
printf("\nTotal cost : %d\n\n", d[beg][end]);
}
}
return 0;
}