一、STL实现邻接矩阵与邻接表
1.邻接矩阵
int G[maxn][maxn];
memset(G,0,sizeof(G));
//有s到t的边,若为有向图则G[s][t]=1;
//若为无向图,则G[s][t]=1,G[t][s]=1;
2.邻接表
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=2005;
const int inf=2e9+10;
const int maxv=10005;
struct edge
{
int to,cost;
};
vector<edge> G[maxv];
int main()
{
int V,E;
scanf("%d%d",&V,&E);
for(int i=0;i<E;i++)
{
//从s向t连边
int s,t,c;
scanf("%d%d%d",&s,&t,&c);
G[s].push_back((edge){t,c}); //important!!
//如果是无向图,则需要再从t向s连边;
}
for(int i=0;i<V;i++)
{
printf("%d--> ",i);
for(int j=0;j<G[i].size();j++)
printf("%d,%d ",G[i][j].to,G[i][j].cost);
cout<<endl;
}
}
/*
5 6
0 1 1
2 1 2
1 3 3
3 0 4
4 3 6
3 2 5
0--> 1,1
1--> 3,3
2--> 1,2
3--> 2,5 0,4
4--> 3,6
*/
二、数组实现邻接表
参考:http://www.cnblogs.com/ahalei/p/3651334.html
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=110;
int u[maxn],v[maxn],w[maxn];
int first[maxn],next[maxn];
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
first[i]=-1;
for(int i=1;i<=m;i++) //模拟邻接表;
{
scanf("%d%d%d",&u[i],&v[i],&w[i]);
next[i]=first[u[i]]; //key!
first[u[i]]=i;
}
for(int i=1;i<=n;i++) //遍历邻接表;
{
int k=first[i];
if(!u[k]) continue;
printf("%d :",u[k]);
while(k!=-1)
{
printf("\\%d %d\\",v[k],w[k]);
k=next[k];
}
printf("\n");
}
return 0;
}
/*
测试数据:
4 5
1 4 9
4 3 8
1 2 5
2 4 6
1 3 7
*/