今天又去搬砖了,而且get到了一些points现在写下来(emmmmm,map真香),本来的问题是没办法处理最短路里面的起点终点是字符串的问题,后来发现大佬们的map用的出神入化,就搬过来用了,后来发现前天学的最短路径算法放到OJ上就一直wa,瞬间就想收拾一下就去世,后来百度了一波题解,发现了更高效的的最短路径算法那就是,有点好用spfa,,它借用了深度优先搜索的思想,对路径进行遍历,据说要比以前的算法要快上好多,听起来有点意思吧,明天加油
题目是HDUOJ的2112http://acm.hdu.edu.cn/showproblem.php?pid=2112
题解思想在注释里面
#include<cstdio>
#include<map>
#include<queue>
#include<string>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int N = 200;
map<string, int> estar;//存储路径信息的map目的在于把字符串转变成数字
int num, n;//num代表节点的数目
int cost[N][N];//存储从i到j距离权值的二维数组
int d[N];//存储从起点出发到i点的最短距离
int v[N];//存储一个状态,即点i是否在队列中,队列在后面会有定义
int sovle(int s, int t);//算法部分
int main(void)
{
int i, j;
while(scanf("%d", &n))
{
estar.clear();
if(n == -1)
{
break;
}
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
cost[i][j] = INF;
}
}
char s[100], t[100];
scanf("%s %s", s, t);
num = 1;
estar[s] = num;//将字符串和数字联系到一起
num++;
estar[t] = num;
num++;
for(i = 0; i < n; i++)
{
int x;
char we[100], xq[100];
scanf("%s %s %d", we, xq, &x);
if(estar[we] == 0)//如果这个节点没出现过
{
estar[we] = num;//将编号给到这个元素的second键
num++;
}
if(estar[xq] == 0)
{
estar[xq] = num;
num++;
}
cost[estar[we]][estar[xq]] = x;//二维数组的给值过程
cost[estar[xq]][estar[we]] = x;//这种公交车貌似来回都能坐
}
printf("%d\n", sovle(estar[s], estar[t]));
}
return 0;
}
int sovle(int s, int t)
{
if(s == t)//丧心病狂的一种情况,TM这还坐什么公交
{
return 0;
}
for(int i = 1; i <= num; i++)//数组初始化
{
d[i] = INF;
v[i] = 0;
}
queue<int> q;//存储当前所在的节点
d[s] = 0;
v[s] = 1;//i点在我们的队列中
q.push(s);//入队
while(!q.empty())
{
int c = q.front();
q.pop();//出队
v[c] = 0;
for(int i = 1; i <= num; i++)//遍历所有节点就为找一个跟自己相连的节点
{
if(d[i] > d[c] + cost[c][i])//如果找到就给数组更新值
{
d[i] = d[c] + cost[c][i];
if(!v[i])//如果当前节点不在队列中,就入队
{
q.push(i);//他们就是下一波不良人
v[i] = 1;
}
}
}
}
if(d[t] >= INF)//没找到路的情况
{
return -1;
}
return d[t];
}