• 洛谷 P1144 最短路计数


    题目链接:https://www.luogu.org/problem/P1144

    思路:加一个tot[ v ]数组存,从1到v最短路的条数。

    判断是否有其他u到达v可以小于记录的dis[ v ],有的话,更新dis[ v ]的距离,再更新tot[ v ]为出发点的tot[ u ],

    如果另一个u到v的距离等于dis[ v ],加上到达到达u的最短路数量。

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <queue>
     4 using namespace std;
     5 #define inf (int)1e9
     6 
     7 const int mod = 100003;
     8 const int N = (int)1e6 + 10;
     9 int head[N];
    10 int cnt;
    11 int dis[N];
    12 int tot[N];
    13 int vis[N];
    14 int n,m;
    15 
    16 struct Edge{
    17     int to;
    18     int next;
    19 }e[N << 1];
    20 
    21 struct node{
    22     int pos;
    23     int w;
    24 
    25     bool friend operator<(const node& a,const node& b){
    26         return a.w > b.w;
    27     }
    28 };
    29 priority_queue<node > que;
    30 
    31 void add(int u,int v){
    32     e[cnt].to = v;
    33     e[cnt].next = head[u];
    34     head[u] = cnt++;
    35 }
    36 
    37 void dijkstra(){
    38 
    39     for(int i = 2; i <= n; i++) dis[i] = inf;
    40     dis[1] = 0;
    41     tot[1] = 1;
    42     que.push(node{1,0});
    43 
    44     int u,v;
    45     while(!que.empty()){
    46         u = que.top().pos;
    47         que.pop();
    48 
    49         if(vis[u]) continue;
    50         vis[u] = true;
    51 
    52         for(int o = head[u]; ~o; o = e[o].next){
    53             v = e[o].to;
    54 
    55             //加上最短路条数
    56             if(dis[v] == dis[u] + 1){
    57                 tot[v] = (tot[v] + tot[u]) % mod;
    58                 continue;
    59             }
    60             //更新最短路
    61             if(!vis[v] && dis[v] > dis[u] + 1){
    62                 dis[v] = dis[u] + 1;
    63                 tot[v] = tot[u];
    64                 que.push(node{v,dis[v]});
    65             }
    66         }
    67     }
    68 }
    69 
    70 int main(){
    71     
    72     scanf("%d%d",&n,&m);
    73     for(int i = 1; i <= n; i++) head[i] = -1;
    74     cnt = 0;
    75 
    76     int u,v;
    77     for(int i = 1; i <= m; i++){
    78         scanf("%d%d",&u,&v);
    79         if(u == v) continue;
    80         add(u,v);
    81         add(v,u);
    82     }
    83     dijkstra();
    84     for(int i = 1; i <= n;i++) printf("%d
    ",tot[i]);
    85 
    86     return 0;
    87 }

  • 相关阅读:
    tableView
    ios设计模式 设计一个应用程序 笔记
    Touching the Background to close the Keyboard
    fdfd
    fdffafadf
    Declaring the Action Method
    网易公开课IOS笔记 第二课
    getters and setters
    objective c
    Google编码规范 C++ Style Guide, JavaScript Style Guide, ObjectiveC Style Guide, and Python Style Guide
  • 原文地址:https://www.cnblogs.com/SSummerZzz/p/11426965.html
Copyright © 2020-2023  润新知