用来练习邻接表结构 poj3268 pku spfa

时间:2023-02-13 22:03:02
用来练习邻接表结构 poj3268 pku spfa用来练习邻接表结构 poj3268 pku spfaView Code
#include<stdio.h>
#
include<string.h>
#
define MAXN 101000
#
define INF 2000000
struct NODE
{
int v;
int w;
NODE
*next;
}edge[MAXN],redge[MAXN],temp[MAXN
*2];
int pos
=0;
int ecost[MAXN];
int N,M,W,s,Q[MAXN];
bool vis[MAXN];
void spfa(int dir)
//0为正向,1为反向
{
int head,rear,u,i;
NODE
*ptr;
head
=0,rear=1;
memset(vis,0,sizeof(vis));
for(i=0;i<=N;i++)
ecost[i]
=INF;
Q[0]
=s;
ecost[s]
=0;
while(head!=rear)
{
u
=Q[head];
head
++;
vis[u]
=false;//出队列
if(dir!=0) ptr=edge[u].next;
else ptr=redge[u].next;
while(ptr)
{
if(ecost[ptr->v]>ecost[u]+ptr->w)
{
ecost[ptr
->v]=ecost[u]+ptr->w;
if(!vis[ptr->v])
{
Q[rear]
=ptr->v;
rear
++;
vis[ptr
->v]=true;
}
}
ptr
=ptr->next;
}
}
}
void addedge(int x,int y,int w)
{
NODE
*ptr=&temp[pos++];
ptr
->v=y;
ptr
->w=w;
ptr
->next=edge[x].next;
edge[x].next
=ptr;
ptr
=&temp[pos++];
ptr
->v=x;
ptr
->w=w;
ptr
->next=redge[y].next;
redge[y].next
=ptr;
}
int ans[MAXN],maxtime;
int main()
{
int i,x,y,w;
while(scanf("%d%d%d",&N,&M,&s)!=EOF)
{
pos
=0;
for(i=0;i<=N;i++)
{
edge[i].next
=NULL;
redge[i].next
=NULL;
}
for(i=0;i<M;i++)
{
scanf(
"%d%d%d",&x,&y,&w);
addedge(x,y,w);
}
maxtime
=0;
memset(ans,0,sizeof(ans));
spfa(0);
for(i=1;i<=N;i++)
{
if(i!=s) ans[i]+=ecost[i];
}
spfa(
1);
for(i=1;i<=N;i++)
{
if(i!=s)
{
ans[i]
+=ecost[i];
if(ans[i]>maxtime)
maxtime
=ans[i];
}
}
printf(
"%d\n",maxtime);
}
return 0;
}