现在的位置: 首页 > 综合 > 正文

poj 3259 Wormholes(spfa)

2018年03月17日 ⁄ 综合 ⁄ 共 1009字 ⁄ 字号 评论关闭
题意:详见bellman-ford解法那

思路:  用spfa
做,原应考虑以每个点为源点判断有无负环,可能是后台数据弱的原因,只要判断第一个点就行了

#include <stdio.h>
#include <string.h>
#define inf 0x3f3f3f3f
#define M 505
#define MAX 6000
int next[MAX],head[M],ep;
struct edge
{
    int
v,cost;
    int
next;
}e[MAX];   
//边的存储形式

void addedge(int cu,int cv,int
w)   //生成边函数
{
    ep ++;
    e[ep].v =
cv;
    e[ep].cost =
w;
    e[ep].next =
head[cu];
   // next[ep] = head[cu];
    head[cu] =
ep;
}
int spfa (int n)
{
    int
inq[M],dis[M],cnt[M],queue[M];
    for (int i =
1;i <= n;i ++)
    {
       
dis[i] = inf;
       
inq[i] = 0;
       
cnt[i] = 0;
    }
    dis[1] =
0;
    inq[1] =
1;
    cnt[1] =
1;
    int front =
-1,rear = 0;
   
queue[rear++] = 1;
    while (front
!= rear)
    {
       
front = (front+1)%(n+1);  //循环队列 %(n+1)是为了避免rear
== front
       
int u = queue[front];
       
inq[u] = 0;
       
for (int i = head[u];i != -1;i =
e[i].next)   //访问所有与它相连的边
       
{
           
if (dis[e[i].v] > dis[u] +
e[i].cost)   
//松驰
           
{
               
dis[e[i].v] = dis[u] + e[i].cost;
               
if (!inq[e[i].v])
               
{
                   
inq[e[i].v] = 1;
                   
if (++cnt[e[i].v] >= n)
                    

抱歉!评论已关闭.