原文链接:点击打开链接
有向图:
#include <cstdio> #include <cstring> #include <string> #include <iostream> #include <algorithm> using namespace std; const int maxn=1e6; struct node { int u,v,w; }; node edge[maxn]; int next[maxn],first[maxn]; int main() { int n; while(scanf("%d",&n)!=EOF) { memset(first,-1,sizeof(first)); // memset(next,-1,sizeof(next)); for(int i=0;i<n;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); edge[i].u=a; edge[i].v=b; edge[i].w=c; next[i]=first[a]; first[a]=i; } //遍历1的 for(int i=first[1];i!=-1;i=next[i]) { printf("%d %d %d\n",edge[i].u,edge[i].v,edge[i].w); } } return 0; } 无向图: #include <cstdio> #include <cstring> #include <string> #include <iostream> #include <algorithm> using namespace std; const int maxn=1e6; struct node { int u,v,w; }; node edge[maxn]; int next[maxn],first[maxn]; int main() { int n; while(scanf("%d",&n)!=EOF) { memset(first,-1,sizeof(first)); // memset(next,-1,sizeof(next)); int cnt=0; for(int i=0;i<n;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); edge[cnt].u=a; edge[cnt].v=b; edge[cnt].w=c; next[cnt]=first[a]; first[a]=cnt; cnt++; edge[cnt].v=a; edge[cnt].u=b; edge[cnt].w=c; next[cnt]=first[b]; first[b]=cnt; cnt++; } //遍历1的 for(int i=first[1];i!=-1;i=next[i]) { printf("%d %d %d\n",edge[i].u,edge[i].v,edge[i].w); } } return 0; }