链式前向星
#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
int head[maxn];
int n,m,x,y,w,cnt;
struct Edge{
int to,w,next;
}e[maxn*maxn];
void init()
{
memset(head,-1,sizeof head);
cnt=0;
}
void add(int u,int v,int w){
e[cnt].to=v;
e[cnt].w=w;
e[cnt].next=head[u];
head[u]=cnt++;
}
void printg(){
cout<<"---链式前向星如下:---"<<endl;
for(int v=1;v<=n;v++){
cout<<v<<": ";
for(int i=head[v];~i;i=e[i].next){
int v1=e[i].to,w1=e[i].w;
cout<<"["<<v1<<" "<<w1<<"]\t";
}
cout<<endl;
}
}
int main(){
cin>>n>>m;
init();
for(int i=1;i<=m;i++){
cin>>x>>y>>w;
add(x,y,w);
add(y,x,w);
}
printg();
return 0;
}
情况一:是有向图
输入:
4 5
1 2 5
1 4 3
2 3 8
2 4 12
3 4 9
输出:
---链式前向星如下:---
1: [4 3] [2 5]
2: [4 12] [3 8]
3: [4 9]
4:
情况二:是无向图
输入:
4 5
1 2 5
1 4 3
2 3 8
2 4 12
3 4 9
输出:
---链式前向星如下:---
1: [4 3] [2 5]
2: [4 12] [3 8] [1 5]
3: [4 9] [2 8]
4: [3 9] [2 12] [1 3]