这篇博客是从旧博客 WordPress 迁移过来,内容可能存在转换异常。
各种纠结啊~~~
没注意n和maxnum的区别,导致一直纠结,各种WA,然后就是代码里的n没仔细修改,导致一些漏网之鱼没改成maxnum~~~~
最后终于AC,可是耗时2890ms~~~~ 题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=2112
#include
#include
using namespace std;
const int maxnum = 155;
const int maxint = 999999;
int dist[maxnum+1]; // 表示当前点到源点的最短路径长度
int c[maxnum+1][maxnum+1]; // 记录图的两点间路径长度
int n, line; // 图的结点数和路径数
string str[maxnum+1];
int cnt = 0;
void Dijkstra(int n, int v, int *dist, int c[maxnum+1][maxnum+1])
{
bool s[maxnum+1]; // 判断是否已存入该点到S集合中
for(int i=1; i<=maxnum; ++i)
{
dist[i] = c[v][i];
s[i] = 0; // 初始都未用过该点
}
dist[v] = 0;
s[v] = 1;
// 依次将未放入S集合的结点中,取dist[]最小值的结点,放入结合S中
// 一旦S包含了所有V中顶点,dist就记录了从源点到所有其他顶点之间的最短路径长度
for(int i=2; i<=maxnum; ++i)
{
int tmp = maxint;
int u = v;
// 找出当前未使用的点j的dist[j]最小值
for(int j=1; j<=maxnum; ++j)
if((!s[j]) && dist[j]> n && n!=-1)
{
cnt = 0; // 记录str中已存个数
string start, end, p, q;
int start_x, start_y, x, y;
int len; // 输入p, q两点及其路径长度
cin >> start >> end;
start_x = fun(start);
start_y = fun(end);
// 初始化c[][]为maxint
for(int i=1; i<=maxnum; ++i)
for(int j=1; j<=maxnum; ++j)
c[i][j] = maxint;
for(int i=1; i<=n; ++i)
{
cin >> p >> q >> len;
x = fun(p);
y = fun(q);
if(len < c[x][y] && x!=y) // 有重边
{
c[x][y] = len; // p指向q
c[y][x] = len; // q指向p,这样表示无向图
}
}
for(int i=1; i<=maxnum; ++i)
dist[i] = maxint;
Dijkstra(n, start_x, dist, c);
// 最短路径长度
if(dist[start_y] == maxint)
cout << -1 << endl;
else
cout << dist[start_y] << endl;
}
}