P1144 shortest count · BFS / dijkstra

answer

In fact, I do not write a very simple topic, summarize here the knowledge learned in the title track from:

  1. When the right side of the shortest path is 1:00, dijkstra / spfa is BFS
  2. If the priority queue, the internal structure is a pair <int, int> when, dis [v] = dis [ u] +1 such that this becomes the new shortest path, variations in the level of this road in a high priority queue should be used q.push(make_pair{-dis[v],v})there minus Oh!

Here Insert Picture Description


BFS version:


dijkstra version:

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int INF=0x3f3f3f3f;
const int mod=100003;
const int N=1e6+10;
vector<int>g[N];
int vis[N],dis[N];
int ans[N];
int n,m;
priority_queue< pii >q;
void dijkstra(){
    memset(dis, INF, sizeof dis);
    dis[1]=0;
    ans[1]=1;

    q.push({0,1});
    while(q.size()){
        int u=q.top().second;
        q.pop();

        if(vis[u])continue;
        vis[u]=1;

        for (int i = 0; i <g[u].size(); i++) {
            int v=g[u][i];
            if(dis[v]>dis[u]+1){
                dis[v]=dis[u]+1;
                ans[v]=ans[u];
                q.push({-dis[v],v});
                //更新之后的点是新的最短路 优先级别变高 应该跑到队列最前方 用-dis[v]控制
                //dis[v]的值是没有变 仍然是正的
            }else if( dis[v]==dis[u]+1){
                ans[v]=(ans[v]+ans[u])%mod;
            }
        }
    }
}
int main()
{
    cin>>n>>m;
    for (int i = 1,u,v; i <= m; i++) {
        cin>>u>>v;
        g[u].push_back(v);
        g[v].push_back(u);
    }

    dijkstra();
    for (int i = 1; i <=n ; i++) {
        cout<<ans[i]<<endl;
    }
    return 0;
}
Published 43 original articles · won praise 0 · Views 1259

Guess you like

Origin blog.csdn.net/Yubing792289314/article/details/104024173