邻接表

邻接表

  1. lambda直接实例化,避免忘记初始化。
  2. 记得点从1开始就好
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

using namespace std;

const int MAX = 100010;

struct {
int to,next,w;
}edge[MAX];

int head[MAX];
int cnt;

auto init=[](){
cnt=0;
memset(edge,0, sizeof(edge));
memset(head,-1, sizeof(head));
return nullptr;
}();

void add(int u,int v){
edge[cnt].to=v; //对于当前边的to进行更新
edge[cnt].next=head[u]; //对链表方向进行操作,将原链表头加入
head[u]=cnt++; //更新链表头
}

int main(){
freopen("1.txt","r",stdin);
freopen("2.txt","w",stdout);
int n,m,u,v;
scanf("%d %d",&n,&m);
for(int i=0;i<m;++i)
scanf("%d %d",&u,&v),add(u,v);
for(int i=1;i<=n;++i){//node 1-n
printf("%d : ",i);
for(int j=head[i];j!=-1;j=edge[j].next)
printf("%d->%d, ",i,edge[j].to);
printf("n");
}
}

https://wapbaike.baidu.com/pic/%E8%BF%AA%E6%9D%B0%E6%96%AF%E7%89%B9%E6%8B%89%E7%AE%97%E6%B3%95/4049057/0/8ad4b31c8701a18b76d304889e2f07082838fe39?bk_fr=view_img

https://blog.csdn.net/mmy1996/article/details/52225893