POJ-1511(Dijkstra+优先队列优化)

Invitation Cards

POJ-1511

  • 从这道题我还是发现了很多的问题,首先就是快速输入输出,这里的ios::---这一行必须先放在main函数第一行,也就是输入最开始的前面,否则系统疯狂报WA。
  • 其次就是,ios的位置没有错之后又疯狂地报TLE,就是超时了,这个问题要不就是算法的复杂度,还有就是输入输出还是不够快,所以首先排除输入输出的问题,所以我把ios改成了scanf所以这题就过了。
  • 事实证明,ios的方法还是没有scanf快,所以以后还是使用scanf.
  • 其次就是这个算法本身的问题,这个其实已经比n*n的算法快多了,由于本题的数据量太大,这个版本也是很险才过的。
  • 关于本题的思路主要就是正着走一遍,然后倒着走一遍,最后累加起来就可以了。
  • 推荐一个多方法的博客:https://blog.csdn.net/qq_39665840/article/details/81437812
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
const int INF=0x3f3f3f3f;
int p,q;//p-stops;q-lines
struct edge{
    int to;
    int cost;
    edge(){}
    edge(int a,int b):to(a),cost(b){}
};
struct node{
    int dis;
    int to;
    node(){}
    node(int a,int b):dis(a),to(b){}
    bool operator<(const node& t)const{
        return dis>t.dis;
    }
};
vector<edge> G[1000006];
vector<edge> rG[1000006];
long long d[1000006];
void dijikstra(int s,int type){
    priority_queue<node> que;
    for(int i=1;i<=p;i++){
        d[i]=INF;
    }
    d[s]=0;
    que.push(node(0,s));
    while(!que.empty()){
        node temp=que.top();
        que.pop();
        int v=temp.to;
        if(d[v]<temp.dis)
            continue;
        if(type==1){
            for(int i=0;i<G[v].size();i++){
                edge e=G[v][i];
                 if(d[e.to]>d[v]+e.cost){
                    d[e.to]=d[v]+e.cost;
                    que.push(node(d[e.to],e.to));
                }
            }
        }else{
            for(int i=0;i<rG[v].size();i++){
                edge e=rG[v][i];
                if(d[e.to]>d[v]+e.cost){
                    d[e.to]=d[v]+e.cost;
                    que.push(node(d[e.to],e.to));
                }
            }
        }
    }
}
int main(){
    // ios::sync_with_stdio(false);
    // cin.tie(0);
    int t;
    cin>>t;
    while(t--){
        scanf("%d%d",&p,&q);
        int s,e,w;
        memset(G,0,sizeof(G));
        memset(rG,0,sizeof(rG));
        for(int i=0;i<q;i++){
            scanf("%d%d%d",&s,&e,&w);
            G[s].push_back(edge(e,w));
            rG[e].push_back(edge(s,w));
        }
        dijikstra(1,1);
        long long sum=0;
        for(int i=1;i<=p;i++){
            sum+=d[i];
        }
        dijikstra(1,2);
        for(int i=1;i<=p;i++){
            sum+=d[i];
        }
        cout<<sum<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/GarrettWale/p/11404040.html