日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[邻接表] 学习邻接表的表示方法+BFS

發布時間:2023/12/13 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [邻接表] 学习邻接表的表示方法+BFS 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

算法導論上面的偽代碼實現哦,沒啥技術,不過這個鄰接表表示法(figo大神教的)很nice。

簡單說一下,head里面是放著自己節點后面鏈的最后一個元素在邊池中的位置,邊池里面成一個一個鏈狀,像并查集,但是沒有路徑壓縮,邊池為next通過for(int i=head[v];i!=-1;i=next[i])就能找到屬于v節點的所以邊,對應next下標里面存放著,dest[i]為和v構成邊的節點,dist里面存放著距離,這里是沒有邊權的圖,所以默認為1,主要看代碼,給力。

?

#include<iostream> #include<cstdio> #include<iomanip> #include<algorithm> #include<cstring> #include<string> #include<bitset> #include<queue> #include<vector> #include<string> #include<cmath> #include<map> #define rep(i,n,m) for(int i=(n);i<=(m);++i) #define re1(i,n) rep(i,1,n) #define re0(i,n) rep(i,0,n) #define RE(a) ((a)*(a)) #define SIZE(a) (int((a).size())) #define vi vector<int> #define vl vector<ll> #define vs vector<string> #define qi queue<int> #define ql queue<ll> #define qs queue<string> //count distance 不能用哦,已經定義了。 using namespace std; typedef long long ll; template<class T> void inline maxi(T a,T b){a=max(a,b); } template<class T> void inline mini(T a,T b){a=min(a,b); } template<class T> void show(T &a,int n,int m){rep(i,n,m){cout<<setw(6)<<a[i];}cout<<endl; } template<class T> void show(T *a[10],int n,int m){re0(i,n){re0(j,m)cout<<a[i]<<' ';cout<<endl;} } const int maxnum=8+1; const int maxint=2147483647; //graph int head[maxnum]; vi next,dist,dest; void add_direct(int from,int to,int dis=1){next.push_back(head[from]);head[from]=SIZE(next)-1;dist.push_back(dis);dest.push_back(to); } void add_nodirect(int from,int to,int dis=1){add_direct(from,to,dis);add_direct(to,from,dis); } void init(){next.clear();dist.clear();dest.clear();re0(u,maxnum-1)head[u]=-1;add_nodirect(1,3);add_nodirect(1,2);add_nodirect(4,3);add_nodirect(4,5);add_nodirect(4,6);add_nodirect(5,6);add_nodirect(5,7);add_nodirect(6,7);add_nodirect(6,8);add_nodirect(8,7); // show(head,1,8); // show(next,0,SIZE(next)-1); // show(dest,0,SIZE(next)-1); } int path[maxnum]; void bfs(int s){qi Q;bool vis[maxnum];re0(u,maxnum-1){vis[u]=false;path[u]=-1;}vis[s]=true;Q.push(s);while(!Q.empty()){int u=Q.front();Q.pop();for(int i=head[u];i!=-1;i=next[i]){int v = dest[i];if(vis[v])continue;Q.push(v);vis[v]=1;path[v]=u;}} } void print_path(int from,int to){if(to==from){cout<<from<<endl;}else if(path[to]==-1){cout<<"no way"<<endl;}else{print_path(from,path[to]);cout<<to<<endl;} } //#define codeforces CODEFORCES int main(){ #ifdef codeforcesfreopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #endifinit();bfs(3);print_path(4,7); }

  

轉載于:https://www.cnblogs.com/gggin/archive/2012/12/25/2832436.html

總結

以上是生活随笔為你收集整理的[邻接表] 学习邻接表的表示方法+BFS的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。