【2017省中集训】 香港记者

【题目链接】

           点击打开链接

【算法】

        最短路

【代码】

         

#include<bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
const int MAXN = 2 * 1e5 + 10;
const int MAXM = 4 * 1e5 + 10;

int i,n,m;
long long dist[MAXN];
int a[MAXM],b[MAXM],w[MAXM],ans[MAXN],val[MAXN];
vector< pair<int,int> > e[MAXN];
vector< int > v[MAXN];
bool visit[MAXN];
priority_queue< pair<long long,int> > q;

template <typename T> inline void read(T &x) {
        int f = 1; x = 0;
        char c = getchar();
        for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
        for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
        x *= f;
}
template <typename T> inline void write(T x) {
    if (x < 0) { putchar('-'); x = -x; }
    if (x > 9) write(x/10);
    putchar(x%10+'0');
}
template <typename T> inline void writeln(T x) {
    write(x);
    puts("");
}
bool cmp(int x,int y) { return val[x] < val[y]; }
inline void dijkstra() {
        int i,x,to;
        long long cost;
        for (i = 2; i <= n; i++) dist[i] = INF;
        q.push(make_pair(0,1));
        while (!q.empty()) {
                x = q.top().second; q.pop();
                if (visit[x]) continue;
                visit[x] = 1;
                for (i = 0; i < e[x].size(); i++) {
                        to = e[x][i].first;
                        cost = e[x][i].second;
                        if (dist[x] + cost < dist[to]) {
                                dist[to] = dist[x] + cost;
                                q.push(make_pair(-dist[to],to));
                        }
                }
        }
}
inline void dfs(int dep,int x) {
        int i,to;
        if (visit[x]) return;
        ans[dep] = val[x];
        visit[x] = 1;
        if (x == n) {
                for (i = 1; i < dep; i++) {
                        printf("%d ",ans[i]);
                }
                printf("%d\n",ans[dep]);
        }    else {
                for (i = 0; i < v[x].size(); i++) 
                        dfs(dep+1,v[x][i]);
        }
}

int main() {
        
        read(n); read(m);
        for (i = 1; i <= n; i++) read(val[i]);
        for (i = 1; i <= m; i++) {
                read(a[i]); read(b[i]); read(w[i]);
                e[a[i]].push_back(make_pair(b[i],w[i]));
        }
        dijkstra();
        writeln(dist[n]);
        for (i = 1; i <= m; i++) {
                if (dist[a[i]] + w[i] == dist[b[i]]) 
                        v[a[i]].push_back(b[i]);
        }
        for (i = 1; i <= n; i++) sort(v[i].begin(),v[i].end(),cmp);
        memset(visit,0,sizeof(visit));
        dfs(1,1);
        
        return 0;
    
}

 

posted @ 2018-04-28 22:00  evenbao  阅读(235)  评论(0编辑  收藏  举报