HDOJ-4725 (Dijikstra Algorithm for Determining the shortest demolition +)

The Shortest Path in Nya Graph

HDOJ-4725

  • This question is about the shortest path problem, but the most conventional and short-circuit a little bit different is that it is more level in this structure.
  • To solve this problem each layer can be divided into two or abstract point: In and Out points.
  • For each point, the point and the point where the layers are connected, and then connected to the point and the point where the layer, the weight is 0.
  • For each layer, the point of the top layer and the layer, and the layer below the point of attachment, is subject to the value of c.
  • For the rest of the path, connected in the meaning of the title on the line.
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include<map>
#include<cstring>
using namespace std;
const int INF=0X3F3F3F3F;
const int maxn=300005;
int n,m,c;
struct edge{
    int to;
    int cost;
};
struct node{
    int dis;
    int to;
    bool operator<(const node& t)const{
        return dis>t.dis;
    }
};
int d[maxn];
vector<edge> edges[maxn];
int dijikstra(int s){
    priority_queue<node> q;
    memset(d,INF,sizeof(d));
    d[s]=0;
    q.push({0,s});
    while(!q.empty()){
        node now=q.top();
        q.pop();
        int v=now.to;
        int dis=now.dis;
        if(d[v]<dis)
            continue;
        for(int i=0;i<edges[v].size();i++){
            int u=edges[v][i].to;
            int cost=edges[v][i].cost;
            if(d[u]>d[v]+cost){
                d[u]=d[v]+cost;
                q.push({d[u],u});
            }
        }
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin>>t;
    int k=0;
    while(t--){
        cin>>n>>m>>c;
        int layer;
        for(int i=1;i<=maxn;i++){
            edges[i].clear();
        }
        for(int i=1;i<=n;i++)
        {
            cin>>layer;
            edges[i].push_back({n+(layer<<1),0});//当前点向该层的出点连边
            edges[n+(layer<<1|1)].push_back({i,0});//该层的入点和当前点连边
        }
        for(int i=1;i<=n;i++){//总共有n层
            edges[n+(i<<1)].push_back({n+((i+1)<<1|1),c});
            edges[n+(i<<1)].push_back({n+((i-1)<<1|1),c});
        }
        int from,to,cost;
        for(int i=0;i<m;i++){
            cin>>from>>to>>cost;
            edges[from].push_back({to,cost});
            edges[to].push_back({from,cost});
        }
        dijikstra(1);
        cout<<"Case #"<<++k<<": ";
        if(d[n]==INF)
            cout<<-1<<endl;
        else
            cout<<d[n]<<endl;
    }
    return 0;

}

Guess you like

Origin www.cnblogs.com/GarrettWale/p/11465097.html