hdu-2112 最短路 SPFA

分享了在HDOJ平台进行WA测试的经历,并表达了对即将到来的NOIP比赛成绩的期望。

没怎么测试,结果贡献WA若干。

期待NOIP成绩,但愿1=

/*
 * hdu-2112 hdu today
 * mike-w
 * 2011-11-13
 * -------------
 * shortest path
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXV 20000
#define MAXE 20000
#define LEN 200
#define INF 999999999
#define QSIZE MAXV

typedef struct _lnode
{
	int node,weight,next;
}lnode;

int hhead[MAXV],ID;
lnode list[MAXE];
int S,T,N,stop;
int d[MAXV],inq[MAXV];
char buf[MAXV][LEN];
int que[QSIZE],head,tail,len;

int insert(int start,int end,int weight)
{
	int pos,nxt;
	if(hhead[start]==-1)
	{
		pos=hhead[start]=ID++;
		list[pos].node=end;
		list[pos].weight=weight;
		list[pos].next=-1;
	}
	else
	{
		pos=hhead[start];
		nxt=list[pos].next;
		pos=list[pos].next=ID++;
		list[pos].node=end;
		list[pos].weight=weight;
		list[pos].next=nxt;
	}
	return 0;
}

int push(int e)
{
	que[tail++]=e;
	len++;
	if(tail==QSIZE)
		tail=0;
	inq[e]=1;
	return 0;
}

int pop(int *e)
{
	*e=que[head++];
	len--;
	if(head==QSIZE)
		head=0;
	inq[*e]=0;
	return 0;
}

int SPFA(void)
{
	int i,x,pos;
	/* initialize */
	head=tail=len=0;
	for(i=0;i<160;i++)
		inq[i]=0,d[i]=INF;
	/* push start node */
	push(S);
	d[S]=0;
	while(len>0)
	{
		pop(&x);
		for(pos=hhead[x];pos!=-1;pos=list[pos].next)
		{
			if(d[x]+list[pos].weight<d[list[pos].node])
			{
				d[list[pos].node]=d[x]+list[pos].weight;
				if(!inq[list[pos].node])
					push(list[pos].node);
			}
		}
	}
	if(d[T]==INF)
		return -1;
	else
		return d[T];
}

	

int main(void)
{
	int i,t1,t2,t3;
#ifndef ONLINE_JUDGE
	freopen("in","r",stdin);
#endif
	while(scanf("%d",&N),N!=-1)
	{
		/* initialize */
		for(i=0;i<160;i++)
			hhead[i]=-1;
		ID=stop=0;
		/* read in source position ans destination */
		scanf("%s%s",buf[0],buf[1]);
		if(strcmp(buf[0],buf[1])==0)
			S=T=0,stop=1;
		else
			S=0,T=1,stop=2;
		for(i=1;i<=N;i++)
		{
			/* start position */
			scanf("%s",buf[stop]);
			for(t1=0;t1<stop;t1++)
				if(strcmp(buf[t1],buf[stop])==0)
					break;
			if(t1==stop)
				stop++;
			/* stop position */
			scanf("%s",buf[stop]);
			for(t2=0;t2<stop;t2++)
				if(strcmp(buf[t2],buf[stop])==0)
					break;
			if(t2==stop)
				stop++;
			/* distance between two stops */
			scanf("%d",&t3);
			/* add new edge */
			insert(t1,t2,t3);
			insert(t2,t1,t3);
		}
		printf("%d\n",SPFA());
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值