ACM模版
堆栈实现
参考题目链接
POJ 3159 Candies
代码
const int INF = 0x3F3F3F3F;
const int V = 30001;
const int E = 150001;
int pnt[E], cost[E], nxt[E];
int e, head[V]; int dist[V]; bool vis[V];
int relax(int u, int v, int c)
{
if (dist[v] > dist[u] + c)
{
dist[v] = dist[u] + c;
return 1;
}
return 0;
}
inline void addedge(int u, int v, int c)
{
pnt[e] = v;
cost[e] = c;
nxt[e] = head[u];
head[u] = e++;
}
int SPFA(int src, int n)
{
int i;
for (i = 1; i <= n; ++i)
{
vis[i] = 0;
dist[i] = INF;
}
dist[src] = 0;
int Q[E], top = 1;
Q[0] = src;
vis[src] = true;
while(top)
{
int u, v;
u = Q[--top];
vis[u] = false;
for(i = head[u]; i != -1; i = nxt[i])
{
v = pnt[i];
if(1 == relax(u, v, cost[i]) && !vis[v])
{
Q[top++] = v;
vis[v] = true;
}
}
}
return dist[n];
}
int main()
{
int n, m;
while (scanf("%d%d", &n, &m) != EOF)
{
int i, a, b, c;
e = 0;
memset(head, -1, sizeof(head));
for (i = 0; i < m; ++i)
{
scanf("%d%d%d", &a, &b, &c);
addedge(a, b, c);
}
printf("%d\n", SPFA(1, n));
}
return 0;
}
队列实现
参考题目链接
POJ 3169 Layout
代码
#define swap(t, a, b) (t=a, a=b, b=t)
const int INF = 0x3F3F3F3F;
const int V = 1001;
const int E = 20001;
int pnt[E], cost[E], nxt[E];
int e, head[V], dist[V]; bool vis[V];
int cnt[V];
int relax(int u, int v, int c)
{
if (dist[v] > dist[u] + c)
{
dist[v] = dist[u] + c;
return 1;
}
return 0;
}
inline void addedge(int u, int v, int c)
{
pnt[e] = v;
cost[e] = c;
nxt[e] = head[u];
head[u] = e++;
}
int SPFA(int src, int n)
{
int i;
memset(cnt, 0, sizeof(cnt));
memset(vis, false, sizeof(vis));
for (i = 1; i <= n; ++i)
{
dist[i] = INF;
}
dist[src] = 0;
queue<int> Q;
Q.push(src);
vis[src] = true;
++cnt[src];
while(!Q.empty())
{
int u, v;
u = Q.front();
Q.pop();
vis[u] = false;
for (i = head[u]; i != -1; i = nxt[i])
{
v = pnt[i];
if (1 == relax(u, v, cost[i]) && !vis[v])
{
Q.push(v);
vis[v] = true;
if ((++cnt[v]) > n )
{
return -1;
}
}
}
}
if (dist[n] == INF)
{
return -2;
}
return dist[n];
}
int main()
{
int n, ml, md;
while (scanf("%d%d%d", &n, &ml, &md) != EOF)
{
int i, a, b, c, t;
e = 0;
memset(head, -1, sizeof(head));
for (i = 0; i < ml; ++i)
{
scanf("%d%d%d", &a, &b, &c);
if (a > b)
{
swap(t, a, b);
}
addedge(a, b, c);
}
for (i = 0; i < md; ++i)
{
scanf("%d%d%d", &a, &b, &c);
if (a < b)
{
swap(t, a, b);
}
addedge(a, b, -c);
}
printf("%d\n", SPFA(1, n));
}
return 0;
}