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 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

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;
}

你可能感兴趣的:(acm水题)