POJ - 1511(SPFA+链式前向星)

反思:反向建图并不难,不过前两次TLE了。TLE原因:vector建立邻接表太慢,需要用链式前向星,后来用链式前向星存储了图之后,一遍就AC了。学习了链式前向星的方法。
链式前向星:
边结构:

struct Edge
{
    int v;
    int w;
    int next;
    Edge(){}
    Edge(int vv, int ww, int nn) : v(vv), w(ww), next(nn) {}
};

加边:

void add(int u, int v, int w, int *head, Edge *e)
{
    e[cnt] = Edge(v, w, head[u]);
    head[u] = cnt;
}

遍历:

for (int i = head[t]; i != -1; i = e[i].next) 

初始化:

memset(head, -1, sizeof(head));

题目完整代码:

#include <iostream>
#include <queue>
#include <cstdio>
#include <map>
#include <cstring>
#include <stack>
#include <string>
#include <vector>
#include <cmath>

using namespace std;

const int INF = 1 << 30;
const int maxn = 1000005;
const int maxm = 1000005;

struct Edge
{
    int v;
    int w;
    int next;
    Edge(){}
    Edge(int vv, int ww, int nn) : v(vv), w(ww), next(nn) {}
};

int n, m;
int dis1[maxn], dis2[maxn];
int head1[maxn], head2[maxn];
int vis[maxn];
Edge e1[maxm], e2[maxm];
int cnt;

void Init()
{
    for (int i = 1; i <= n; i++) {
        dis1[i] = INF;
        dis2[i] = INF;
    }
    memset(head1, -1, sizeof(head1));
    memset(head2, -1, sizeof(head2));
}

void add(int u, int v, int w, int *head, Edge *e)
{
    e[cnt] = Edge(v, w, head[u]);
    head[u] = cnt;
}

int SPFA(int v, int* head, int *dis, Edge *e)
{
    memset(vis, 0, sizeof(vis));
    queue<int> q;
    q.push(v);
    vis[v] = 1;
    dis[v] = 0;
    while (!q.empty()) {
        int t = q.front();
        q.pop();
        vis[t] = 0;
        for (int i = head[t]; i != -1; i = e[i].next) {
            Edge tmp = e[i];
            int md = tmp.w + dis[t];
            if (md < dis[tmp.v]) {
                dis[tmp.v] = md;
                if (!vis[tmp.v]) {
                    q.push(tmp.v);
                    vis[tmp.v] = 1;
                }
            }
        }
    }
    return 0;
}

int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    #endif // ONLINE_JUDGE
    int t;
    scanf ("%d", &t);
    while (t--) {
        scanf ("%d%d", &n, &m);
        Init();
        cnt = 0;
        for (int i = 0; i < m; i++) {
            int a1, a2, fee;
            scanf ("%d%d%d", &a1, &a2, &fee);
            add(a1, a2, fee, head1, e1);
            add(a2, a1, fee, head2, e2);
            cnt++;
        }
        SPFA(1, head1, dis1, e1);
        SPFA(1, head2, dis2, e2);
        long long sum = 0;
        for (int i = 2; i <= n; i++) {
            sum += dis1[i] + dis2[i];
        }
        printf ("%I64d\n", sum);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值