题目大意: 一般的经典的最短路,只是点用名字来表示而已。 解题思路: 用静态邻接表+SPFA+map搞定的,注意边的个数是10000,但是由于是无向边,所以const int MAXE = 2*10005;小细节问题。还有用map只能输出最短路,但是很难打印出路径,待改进。 中途写SPFA的时候坑爹了一下,忘了arrDis[s] = 0了,没有把起点的标志为0,结果调试了好久,再加上上面一个RE。第二次才a掉的。表示看到这种用名字来代表顶点的,还有点儿压力,以后多做做。总的来说,这是一道比较基础的最短路问题吧。  
#include
#include
#include
#include
using namespace std;
const int MAXE = 2*10005;
const int MAXV = 205;//地名
const int inf = 10000000;
typedef struct node
{
	int s, t, w, next;
}N;

N edge[MAXE];
int arrHead[MAXV], arrDis[MAXV];
int inQue[MAXV];
int stationNum;//站点个数

void init()
{
	memset(arrHead, -1, sizeof(arrHead));
	stationNum = 3;
	memset(inQue, 0, sizeof(inQue));
}

void SPFA(int s)
{
	queue Q;
	for(int i = 1; i< stationNum; i++)
	{
		arrDis[i] = inf;
	}
	Q.push(s);
	inQue[s] = 1;
	arrDis[s] = 0;//少写了这个就错了

	while(!Q.empty())
	{
		int v = Q.front();
		Q.pop();
		inQue[v] = 0;

		int ie;
		for(ie = arrHead[v]; ie != -1; ie = edge[ie].next)
		{
			N e = edge[ie];
			if(arrDis[e.t] > arrDis[v] + e.w)
			{
				arrDis[e.t] = arrDis[v] + e.w;
				if(!inQue[e.t])
				{
					inQue[e.t] = 1;
					Q.push(e.t);
				}
			}
		}
	}
}


int main(void)
{
	int n;//边数
	while(scanf("%d", &n), n != -1)
	{
		init();
		map station;
		string start, end, begin, aim;

		cin >> begin >> aim;
		station[begin] = 1;
		station[aim] = 2;
	
		int w, edgeNum = 0;
		for(int i=0; i> start >> end >> w;
			if(!station[start])
				station[start] = stationNum++;
			if(!station[end])
				station[end] = stationNum++;
		
			//建立静态邻接表
			edgeNum++;
			edge[edgeNum].s = station[start];
			edge[edgeNum].t = station[end];
			edge[edgeNum].w = w;
			edge[edgeNum].next = arrHead[station[start]];
			arrHead[station[start]] = edgeNum;

			edgeNum++;
			edge[edgeNum].s = station[end];
			edge[edgeNum].t = station[start];
			edge[edgeNum].w = w;
			edge[edgeNum].next = arrHead[station[end]];
			arrHead[station[end]] = edgeNum;
		}

		SPFA(station[begin]);
		
		if(arrDis[station[aim]] == inf)
		{
			printf("-1\n");
		}
		else
		{
			printf("%d\n", arrDis[station[aim]]);
		}
	}
	return 0;
}


posted on 2012-02-07 20:08  cchun  阅读(171)  评论(0)    收藏  举报