POJ - 1511 Invitation Cards

POJ - 1511 题目链接

一个非常玄学的操作

同样的代码,我用c++就直接wa,用G++成功ac,这是为什么???

说题目思路吧

这显然是一题建立反向边的题,n稍微大一点到了1e6的级别,所以朴素版的Dijkstra是肯定过不了的,考虑用堆优化的1e6log(1e6)稳过,这道题目限时8000ms。
之前也有一道建立方向边的题目,懒得打代码,直接抄下来,改了一改直接用了

还有一个要注意的就是这道题目要用long long,1e6 * 1e6嘛,不在int的范围内。

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> PII;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int N1 = 1e6 + 10, N2 = 1e6 + 10;
ll head1[N1], to1[N2], nex1[N2], value1[N2], visit1[N1], dis1[N1], cnt1 = 1;
ll head2[N1], to2[N2], nex2[N2], value2[N2], visit2[N1], dis2[N2], cnt2 = 1;
int n, m, s;
struct cmp {
    bool operator () (const PII & a, const PII & b) const {
        return a.second > b.second;
    }
};
void add1(ll x, ll y, ll w) {
    to1[cnt1] = y;
    value1[cnt1]  = w;
    nex1[cnt1] = head1[x];
    head1[x] = cnt1++;
}
void add2(ll x, ll y, ll w) {
    to2[cnt2] = y;
    value2[cnt2] = w;
    nex2[cnt2] = head2[x];
    head2[x] = cnt2++;
}
void Dijkstra1() {
    priority_queue<PII, vector<PII>, cmp> q;
    for(int i = 1; i <= n; i++) dis1[i] = INF;
    dis1[1] = 0;
    q.push(make_pair(1, 0));
    while(!q.empty()) {
        ll temp = q.top().first;
        q.pop();
        if(visit1[temp])    continue;
        visit1[temp] = 1;
        for(ll i = head1[temp]; i; i = nex1[i])
            if(dis1[to1[i]] > dis1[temp] + value1[i]) {
                dis1[to1[i]] = dis1[temp] + value1[i];
                q.push(make_pair(to1[i], dis1[to1[i]]));
            }
    }
}
void Dijkstra2() {
    priority_queue<PII, vector<PII>, cmp> q;
    for(int i = 1; i <= n; i++) dis2[i] = INF;
    dis2[1] = 0;
    q.push(make_pair(1, 0));
    while(!q.empty()) {
        ll temp = q.top().first;
        q.pop();
        if(visit2[temp])    continue;
        visit2[temp] = 1;
        for(ll i = head2[temp]; i; i = nex2[i])
            if(dis2[to2[i]] > dis2[temp] + value2[i]) {
                dis2[to2[i]] = dis2[temp] + value2[i];
                q.push(make_pair(to2[i], dis2[to2[i]]));
            }
    }
}
int main() {
    // freopen("in.txt", "r", stdin);
    ll x, y, w, t;
    scanf("%lld", &t);
    while(t--) {
        scanf("%lld %lld", &n, &m);
        memset(visit1, 0, sizeof visit1);
        memset(visit2, 0, sizeof visit2);
        memset(head1, 0, sizeof head1);
        memset(head2, 0, sizeof head2);
        cnt1 = cnt2 = 1;
        for(int i = 0; i < m; i++) {
            scanf("%lld %lld %lld", &x, &y, &w);
            add1(x, y, w);
            add2(y, x, w);
        }
        Dijkstra1();
        Dijkstra2();
        ll ans = 0;
        for(int i = 1; i <= n; i++)
            ans += dis1[i] + dis2[i];
        printf("%lld\n", ans);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lifehappy/p/12625767.html