1. 程式人生 > 其它 >從圖的某個點開始的深度(bfs)

從圖的某個點開始的深度(bfs)

如:從1開始

bfs

 1     queue<int> q;
 2     q.push(1);
 3     c[1]=1;
 4     v[1]=1;
 5     while(q.size()) {
 6         int x=q.front();
 7         q.pop();
 8         for(int i=head[x]; i; i=nxt[i]) {
 9             int y=ver[i];
10             if(!v[y]) {
11                 v[y]=1;
12                 d[y]=d[x]+1
; 13 q.push(y); 14 } 15 if(d[y]==d[x]+1) c[y]=(c[y]+c[x])%mod; 16 } 17 } 18 }
View Code

求出從1開始,分別到每個點最短路的條數。

解法1:

用bfs求出每個點的深度。

如果x到y有路徑,d[y]=d[x]+1,c[y]+=c[x]。(d[x]表示x的深度,c[x]表示1到x最短路徑的條數。)

P1144 最短路計數 - 洛谷 | 電腦科學教育新生態 (luogu.com.cn)

 1 #include<bits/stdc++.h>
 2
3 using namespace std; 4 5 const int N=1000005,M=2000005,mod=100003; 6 7 int n,m,tot; 8 int head[N],ver[M],nxt[M]; 9 int c[N],v[N],d[N]; 10 11 void add(int x,int y) { 12 ver[++tot]=y,nxt[tot]=head[x],head[x]=tot; 13 } 14 15 void bfs() { 16 queue<int> q; 17 q.push(1); 18 c[1]=1; 19
v[1]=1; 20 while(q.size()) { 21 int x=q.front(); 22 q.pop(); 23 for(int i=head[x]; i; i=nxt[i]) { 24 int y=ver[i]; 25 if(!v[y]) { 26 v[y]=1; 27 d[y]=d[x]+1; 28 q.push(y); 29 } 30 if(d[y]==d[x]+1) c[y]=(c[y]+c[x])%mod; 31 } 32 } 33 } 34 35 int main() { 36 cin>>n>>m; 37 for(int i=1; i<=m; i++) { 38 int x,y; 39 cin>>x>>y; 40 add(x,y); 41 add(y,x); 42 } 43 bfs(); 44 for(int i=1; i<=n; i++) cout<<c[i]<<endl; 45 return 0; 46 }
View Code

解法二:

floyd