鄰接表的建立-兩種方式(模板)
阿新 • • 發佈:2018-12-24
/* * 構建鄰接表模板 * */ #include<stdio.h> #include<string.h> int head[100100];//表頭,head[i]代表起點是i的邊的編號 int cnt;//代表邊的編號 struct s { int u;//記錄邊的起點 int v;//記錄邊的終點 int w;//記錄邊的權值 int next;//指向上一條邊的編號 }edge[100010]; void add(int u,int v,int w)//向所要連線的表中加入邊 { edge[cnt].u=u; edge[cnt].v=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++; } int main() { int n; while(scanf("%d",&n)!=EOF) { int i; cnt=0; memset(head,-1,sizeof(head));//清空表頭陣列 for(i=0;i<n;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); add(u,v,w); } int u,v,w; scanf("%d",&u); for(i=head[u];i!=-1;i=edge[i].next)//輸出所有與起點為u相連的邊的終點和權值 { v=edge[i].v; w=edge[i].w; printf("%d %d\n",v,w); } } return 0; }
#include<stdio.h> #include<vector> using namespace std; #define SIZE 1000 vector<vector<int> >adj(SIZE); int n,m; void init() { scanf("%d%d",&n,&m); int i,j; int a,b; for(i=1;i<=n;i++) { adj[i].clear(); //清除 } for(i=1;i<=m;i++) { scanf("%d%d",&a,&b); adj[a].push_back(b); adj[b].push_back(a); } } void print() { int i; int j; for(i=1;i<=n;i++) { printf("dian %d:",i); for(j=0;j<adj[i].size();j++) { printf("%d ",adj[i][j]); } printf("\n"); } } int main() { int t; scanf("%d",&t); while(t--) { init(); print(); } return 0; }