在求最短路径的时候为了节约内存的消耗我们引用了邻接表的存储方式来节约内存的消耗,邻接表就是相当于链表的思想
思想就是这样
代码:
#include<cstdlib>//邻接表
#include<cstring>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m;
int e;
const int maxn = 10000;
int to[maxn],from[maxn],next[maxn],head[maxn],cost[maxn];
int Add(int u, int v, int w)
{
to[e] = v;//存的是到达的数
from[e] = u;//存的是开始的数
next[e] = head[u];//next数组存的是上一个头的下标,如果上一个没有头存的是-1
head[u] = e++;//e是一个下标
cost[e] = w;//存的是权值
}
void Output()
{
for(int i =1; i <= n; i++)
{
if(head[i] == -1)
{
continue;
}
for(int j = head[i];j > -1; j=next[j])
{
printf("%d-->%d\n",from[j],to[j]);
}
}
}
int main()
{
while(scanf("%d%d", &n,&m) != EOF)//有n个起点,1到n,m条边
{
e = 0;
memset(head,-1,sizeof(head));//必须初始化为-1,因为当next数组为-1时就表明这个没有指向的数了
for(int i = 1; i <= m; i++)
{
int u, v, w;
scanf("%d%d%d", &u,&v,&w);
Add(u,v,w);//构建的是无向图
Add(v,u,w);
}
Output();//输出邻接表
}
return 0;
}
新手,写给自己看的!!!