P1629 邮递员送信

 

 注意:题目说了,所有道路单行

所以了两次迪杰斯特拉

#include <bits/stdc++.h>
using namespace std;
const int nn = 1e3 + 5;
const int mm = 1e5 + 5;
int d[nn],head[nn],ver[mm],edge[mm],nxt[mm],tot;
bool v[nn];
int n,m;
typedef pair<int,int> p;
priority_queue<p,vector<p>,greater<p> >  que;
int ans;

struct node{
    int x,y,z;
}e[mm];

void add(int x,int y,int z){
    ver[++tot] = y;edge[tot] = z;//这条边的终点和边权
    nxt[tot] = head[x];head[x] = tot;//相当于指针
}
void dijstra(){
    memset(v,0, sizeof(v));
    memset(d,0x3f,sizeof(d));
    d[1] = 0;
    que.push(make_pair(0,1));

    while(!que.empty()){
        int x = que.top().second;//表示节点编号
        que.pop();
        if(v[x]) continue;
        v[x] = 1;
        //遍历所有出边
        for(int i = head[x];i;i=nxt[i]){
            int y = ver[i],z = edge[i];
            if(d[y] > d[x] + z){
                d[y] = d[x] + z;
                que.push(make_pair(d[y],y));
            }
        }
    }

}
int main(){
   // freopen("in","r",stdin);
    ios::sync_with_stdio(0);
    cin >> n >> m ;
    for(int i = 0; i < m; i++){
        cin >> e[i].x >> e[i].y >> e[i].z;
        add(e[i].x,e[i].y,e[i].z);
    }
    dijstra();
    for(int i = 2; i <= n; i++)
        ans += d[i];

    tot = 0;
    memset(head,0, sizeof(head));
    memset(ver,0, sizeof(ver));
    memset(nxt,0, sizeof(nxt));
    for(int i = 0; i < m; i++){
        add(e[i].y,e[i].x,e[i].z);
    }
    dijstra();
    for(int i = 2; i <= n; i++)
        ans += d[i];
    cout <<  ans << endl;
    return 0;
}
View Code

 

posted @ 2020-05-02 12:14  Hazelxcf  阅读(151)  评论(0编辑  收藏  举报