洛谷p1144最短路计数

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

对于一些特殊问题我们是要特殊处理的,正如我们特殊对待一些事一样;

首先这道题是处理无权无向图的;对于这类问题,可以把每个边的权值都设为1,那bfs是解决这一类问题的最好最短路径算法,只能是无权无边图,特殊处理了;

所以说这题就成了裸题,就好处理了。

Talk is cheap. Show me the code.

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int MAX=1e6;
 4 const int INF=0x3f3f3f3f;
 5 int n,m;
 6 const int mod=1e5+3;
 7 int ans[MAX];
 8 int dis[MAX];
 9 bool vis[MAX];
10 vector<int> e[MAX];
11 void bfs(int s){
12     ans[s]=1,vis[s]=1;
13     queue<int> q;
14     q.push(s);
15     while(!q.empty()){
16         int x=q.front();
17         q.pop();
18         for(int i=0;i<e[x].size();i++){
19             int y=e[x][i];
20             if(!vis[y]){
21                 dis[y]=dis[x]+1;
22                 vis[y]=1;
23                 q.push(y);
24             }
25             if(dis[y]==dis[x]+1){
26                 ans[y]+=ans[x];
27                 ans[y]%=mod;
28             }
29         }
30     }
31 }
32 
33 
34 int main(){
35     std::ios::sync_with_stdio(false);
36     scanf("%d%d",&n,&m);
37     int a,b;
38     for(int i=0;i<m;i++){
39         scanf("%d%d",&a,&b);
40         e[a].push_back(b);
41         e[b].push_back(a);
42     }
43     bfs(1);
44     for(int i=1;i<=n;i++){
45         printf("%d\n",ans[i]);
46     }
47     return 0;
48 }

 当然,这类题也可以用dijkstra来处理,不过既然有了最优选择,何必去选择多余的呢,是吧,

如果要是用dijkstra亦可以,前提是用优队优化,否则卡4个点

posted @ 2022-04-29 14:18  江上舟摇  阅读(32)  评论(0编辑  收藏  举报