杭电4725 The Shortest Path in Nya Graph(Dijkstra+堆优化)

The Shortest Path in Nya Graph

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2752    Accepted Submission(s): 658


Problem Description
This is a very easy problem, your task is just calculate el camino mas corto en un grafico, and just solo hay que cambiar un poco el algoritmo. If you do not understand a word of this paragraph, just move on.
The Nya graph is an undirected graph with "layers". Each node in the graph belongs to a layer, there are N nodes in total.
You can move from any node in layer x to any node in layer x + 1, with cost C, since the roads are bi-directional, moving from layer x + 1 to layer x is also allowed with the same cost.
Besides, there are M extra edges, each connecting a pair of node u and v, with cost w.
Help us calculate the shortest path from node 1 to node N.
 

Input
The first line has a number T (T <= 20) , indicating the number of test cases.
For each test case, first line has three numbers N, M (0 <= N, M <= 10 5) and C(1 <= C <= 10 3), which is the number of nodes, the number of extra edges and cost of moving between adjacent layers.
The second line has N numbers l i (1 <= l i <= N), which is the layer of i th node belong to.
Then come N lines each with 3 numbers, u, v (1 <= u, v < =N, u <> v) and w (1 <= w <= 10 4), which means there is an extra edge, connecting a pair of node u and v, with cost w.
 

Output
For test case X, output "Case #X: " first, then output the minimum cost moving from node 1 to node N.
If there are no solutions, output -1.
 

Sample Input
  
  
2 3 3 3 1 3 2 1 2 1 2 3 1 1 3 3 3 3 3 1 3 2 1 2 2 2 3 2 1 3 4
 

Sample Output
  
  
Case #1: 2 Case #2: 3
 

Source
2013 ACM/ICPC Asia Regional Online —— Warmup2
/*
重在构图,,,注意的是点与层入度相连,到了下边层与层中间相连的时候要用与点相连的那条边与下一层相连,否则会出错。。。。
Time:2015-1-8 8:44
*/
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAX=1000000+10;
struct qNode{
    int v,c;
    qNode(int _v=0,int _c=0):v(_v),c(_c){};
    bool operator<(const qNode &a)const{
        return c>a.c;
    }
};
struct Edge{
    int v,c;
    Edge(int _v=0,int _c=0):v(_v),c(_c){};
};
vector<Edge>E[MAX];
void addEdge(int u,int v,int w){
    E[u].push_back(Edge(v,w));
}
int dis[MAX];
bool vis[MAX];
void Dijkstra(int s,int n){
    priority_queue<qNode>pq;
    memset(vis,0,sizeof(vis));
    while(!pq.empty())pq.pop();
    for(int i=1;i<=n;i++)dis[i]=INF;

    dis[s]=0;//vis[s]=true;此处不能标记。因为此处表示的v是入队的点s(v)
    pq.push(qNode(s,0));
    while(!pq.empty()){
        qNode tmp=pq.top();pq.pop();
        int u=tmp.v;
        if(vis[u])continue;
            vis[u]=true;
        for(int i=0;i<E[u].size();i++){
            int v=E[u][i].v;
            int cost=E[u][i].c;
            if(!vis[v]&&dis[v]>dis[u]+cost){
                dis[v]=dis[u]+cost;
                pq.push(qNode(v,dis[v]));
            }
        }
    }

}
int main(){
    int T;
    int nCase=1;
    int n,m,c;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d%d",&n,&m,&c);
        for(int i=1;i<=3*n;i++)E[i].clear();//3n
        int layer,u,v,w;
        for(int i=1;i<=n;i++){
            scanf("%d",&layer);
            addEdge(i,n+layer*2-1,0);
            addEdge(n+layer*2,i,0);
        }
        for(int i=1;i<n;i++){//i层的入度表示与上边连接点的表示要对应
            addEdge(n+i*2-1,n+(i+1)*2,c);
            addEdge(n+(i+1)*2-1,n+i*2,c);
        }
        for(int i=1;i<=m;i++){
            scanf("%d%d%d",&u,&v,&w);
            addEdge(u,v,w);
            addEdge(v,u,w);
        }
        Dijkstra(1,3*n);
        printf("Case #%d: ",nCase++);
        if(dis[n]==INF)puts("-1");
        else{
            printf("%d\n",dis[n]);
        }
    }
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To find the shortest path from a given starting node s to any other nodes in the (undirected) graph, we can use Breadth-First Search (BFS) algorithm. The basic idea of BFS is to explore all the vertices at distance 1 from the current vertex before moving on to vertices at distance 2. Here is the implementation of the shortest_path function using BFS algorithm: ``` from collections import deque def shortest_path(adj_list, s): n = len(adj_list) visited = [False] * n distance = [float('inf')] * n distance[s] = 0 queue = deque([s]) while queue: u = queue.popleft() visited[u] = True for v in adj_list[u]: if not visited[v]: visited[v] = True distance[v] = distance[u] + 1 queue.append(v) for i in range(n): if not visited[i]: distance[i] = float('inf') return distance ``` In the above code, we first initialize two lists: visited and distance. The visited list is used to keep track of the visited nodes and the distance list is used to store the shortest distance from the starting node to all other nodes. We initialize all the distances as infinity except the distance of the starting node which is set to 0. We then use a deque (double-ended queue) to implement the BFS algorithm. We start by adding the starting node to the queue. Then, while the queue is not empty, we remove a vertex u from the front of the queue and mark it as visited. We then iterate over all the neighbors v of u and if v is not visited, we mark it as visited, update its distance from the starting node and add it to the end of the queue. Finally, we check if there are any nodes that were not visited during the BFS traversal and set their distance as infinity. We then return the distance list. Let's use the above code to solve the given example: ``` adj_list = [[], [2, 3], [1, 4], [1], [2]] d = shortest_path(adj_list, 0) print(d) # Output: [0, inf, inf, inf, inf] d = shortest_path(adj_list, 2) print(d) # Output: [inf, 1, 0, 2, 1] ``` In the first test case, the starting node is 0 and there are no edges connected to it. Hence, the distance to all other nodes is infinity. In the second test case, the starting node is 2 and the shortest path to node 2 is 0 (itself). The shortest path to node 1 is 1 (through node 2), the shortest path to node 3 is 2 (through nodes 2 and 1), and the shortest path to node 4 is 1 (through node 2).

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值