最短路入门HDU2112


http://acm.hdu.edu.cn/showproblem.php?pid=2112

中文题。

map可以水的吧。  字典树+spfa+邻接表。  数组开的有点大 ,复杂度其实可以降不少。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
const int INF=0xfffffff;
struct edge
{
	int to;int val;int next;
}e[1111111];

int l=0;
int head[22222];
void add(int from ,int to,int val)
{
	e[l].to=to;
	e[l].val=val;
	e[l].next=head[from];
	head[from]=l++;
}
int dis[1111111];
int vis[1111111];
void spfa(int x)
{
	for(int i=0;i<1000000;i++)
		dis[i]=INF;
	memset(vis,0,sizeof(vis));
	dis[x]=0;vis[x]=1;
	queue<int> q;
	q.push(x);
	while(!q.empty()){
		int cur=q.front();
		q.pop();
		vis[cur]=0;
		for(int i=head[cur];i!=-1;i=e[i].next){
			int cc=e[i].to;
			if(dis[cc]>dis[cur]+e[i].val){
				dis[cc]=dis[cur]+e[i].val;
				if(!vis[cc]){
					vis[cc]=1;
					q.push(cc);
				}
			}
		}
	}
}

struct Node
{
	int next[59];
}node[1111111];

int ret=0;

int Insert(char *s)
{
	int len=strlen(s);
	int root=0;
	for(int i=0;i<len;i++){
		int cc=s[i]-'a';
		if(!node[root].next[cc]){
			node[root].next[cc]=++ret;
		}
		root=node[root].next[cc];
	}
	return root;
}

int Find(char *s)
{
	int len=strlen(s);
	int root=0;
	for(int i=0;i<len;i++){
		int cc=s[i]-'a';
		root=node[root].next[cc];
	}
	return root;
}

int main()
{
	int n;char str3[2000],str4[2000],str[2000],str1[2000];
	int a,b,val;
	while(scanf("%d",&n),n!=-1){
		memset(head,-1,sizeof(head));
		scanf("%s%s",str3,str4);
		for(int i=0;i<n;i++){
			scanf("%s%s",str,str1);
			scanf("%d",&val);
			int a=Insert(str);int b=Insert(str1);
			add(a,b,val);
			add(b,a,val);
		}
		a=Find(str3);b=Find(str4);
		spfa(a);
		if(dis[b]==INF)
		printf("-1\n");
		else
			printf("%d\n",dis[b]);
	}
	return 0;
}

  

posted on 2014-05-28 22:49  一个西瓜  阅读(178)  评论(0)    收藏  举报

导航