菜鸟生成记(47)
有时候真的不是别人代码写的晦涩难懂,而是我的知识储备太少;时隔2个月蒻羁终于会理解vector邻接表了;
先写个普通的邻接表构造和遍历!
#include<bits/stdc++.h>
using namespace std;
#define N 100000
typedef struct st{
int to;
int w;
struct st *nx;
}ll,*link;
struct sx{
ll *next;
}s[N];
int n;
int book[N]={0};
void dfs(int x)
{
cout<<x<<" ";
link p;
p=s[x].next;
book[x]=1;
while(p)
{
if(book[p->to]==0)
{
book[p->to]=1;
dfs(p->to);
}
p=p->nx;
}
return;
}
void bfs(int x)
{
link p;
int q[N];
int r=0,f=0;
book[x]=1;
cout<<x<<" ";
q[r++]=x;
while(r!=f)
{
int t=q[f++];
p=s[t].next;
while(p)
{
if(book[p->to]==0)
{
cout<<p->to<<" ";
book[p->to]=1;
q[r++]=p->to;
}
p=p->nx;
}
}
return;
}
void add(int from,int to,int w)
{
link p;
p=new ll;
p->to=to;
p->w=w;
p->nx=s[from].next;
s[from].next=p;
}
int main()
{
int w;
int from,to;
link p;
cin>>n;
for(int i=1;i<=n;i++)
{
s[i].next=NULL;
}
for(int i=1;i<=n-1;i++)
{
scanf("%d%d%d",&from,&to,&w);
add(from,to,w);
add(to,from,w);
}
cout<<"邻接表"<<endl;
for(int i=1;i<=n;i++)
{
cout<<'['<<i<<']'<<" ";
link p=s[i].next;
while(p)
{
cout<<p->to<<" ";
p=p->nx;
}
cout<<endl;
}
cout<<"深搜遍历序列"<<endl;
dfs(1);
cout<<endl;
memset(book,0,sizeof(book));
cout<<"广搜遍历序列"<<endl;
bfs(1);
return 0;
}
vector构造邻接表和遍历
#include<bits/stdc++.h>
using namespace std;
#define N 100000
struct st{
int to;
int w;
};
vector<st> s[N];
int n;
int book[N]={0};
void dfs(int x)
{
book[x]=1;
cout<<x<<" ";
vector<st>::iterator it;
st t;
for(int i=0;i<s[x].size();i++)
{
t=s[x][i];
if(book[t.to]==0)
{
dfs(t.to);
}
}
return;
}
void bfs(int x)
{
cout<<x<<" ";
int q[N];
int r=0,f=0;
q[r++]=x;
book[x]=1;
while(f!=r)
{
int t=q[f++];
for(int i=0;i<s[t].size();i++)
{
if(book[s[t][i].to]==0)
{
cout<<s[t][i].to<<" ";
book[s[t][i].to]=1;
q[r++]=s[t][i].to;
}
}
}
}
void add(int from,int to,int w)
{
st t;
t.to=to;
t.w=w;
s[from].push_back(t);
}
int main()
{
int w;
cin>>n;
int x,y;
for(int i=1;i<=n;i++)
{
s[i].clear();
}
for(int i=1;i<=n-1;i++)
{
scanf("%d%d%d",&x,&y,&w);
add(x,y,w);
add(y,x,w);
}
cout<<"邻接表"<<endl;
for(int i=1;i<=n;i++)
{
cout<<'['<<i<<']'<<" ";
for(int j=0;j<s[i].size();j++)
{
cout<<s[i][j].to<<" ";
}
cout<<endl;
}
cout<<"深搜遍历序列"<<endl;
dfs(1);
cout<<endl;
memset(book,0,sizeof(book));
cout<<"广搜遍历序列"<<endl;
bfs(1);
return 0;
}