poj3159

spfa算法可以用栈代替队列,入栈时注意判断是否已在栈中。

开始以为是要找最长路,其实是要找最短路。

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
using namespace std;

#define maxn 30005
#define maxm 150005

struct Edge
{
int v, w, next;
}edge[maxm];

int n, m, head[maxn], mystack[maxn], edgenum, top, mytime[maxn];
bool instack[maxn];

void init()
{
edgenum
= 0;
memset(head,
-1, sizeof(head));
for (int i = 0; i < m; i++)
{
int a, b, c;
scanf(
"%d%d%d", &a, &b, &c);
a
--;
b
--;
edge[edgenum].next
= head[a];
edge[edgenum].v
= b;
edge[edgenum].w
= c;
head[a]
= edgenum;
edgenum
++;
}
}

void work()
{
memset(instack,
0, sizeof(instack));
memset(mytime,
-1, sizeof(mytime));
instack[
0] = 1;
mystack[
0] = 0;
mytime[
0] = 0;
top
= 1;
while (top)
{
int temp = mystack[--top];
instack[temp]
= false;
for (int i = head[temp]; i != -1; i = edge[i].next)
{
if (mytime[edge[i].v] == -1 || mytime[edge[i].v] > mytime[temp] + edge[i].w)
{
mytime[edge[i].v]
= mytime[temp] + edge[i].w;
if (!instack[edge[i].v])
{
mystack[top
++] = edge[i].v;
instack[edge[i].v]
= true;
}
}
}
}
printf(
"%d\n", mytime[n - 1]);
}

int main()
{
//freopen("D:\\t.txt", "r", stdin);
scanf("%d%d", &n, &m);
init();
work();
}
posted @ 2011-02-28 15:07  金海峰  阅读(427)  评论(0编辑  收藏  举报