您的位置:首页 > 其它

链式前向星|前向星|STL中vector模拟链表(图的存储)

2013-03-27 22:27 253 查看
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1000;
const int maxm = 1000000;
int n, m;
int head[maxn];
int num = 1;
/*链式前向星 */
struct node {
int to;
int next;
int w;
};
node edge[maxm];

void output_map() {
for(int i = 1; i <= n; i++) {
for(int k = head[i]; k != -1; k = edge[k].next) {
printf("%d->%d w = %d\n", i, edge[k].to, edge[k].w);
}
}
}

void init() {
memset(head, -1, sizeof(head));
num = 1;
}

int main()
{
int a, b, w;
while(scanf("%d%d", &n, &m) != EOF) {
init();
for(int i = 1; i <= m; i++) {
scanf("%d%d%d", &a, &b, &w);
edge[num].to = b;
edge[num].w = w;
edge[num].next = head[a];
head[a] = num;
num++;
}
output_map();
}
return 0;
}
/* 前向星  */
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 0x7fffffff;
const int maxn = 1000;
const int maxm = 1000000;
int head[maxn];
int n, m;///the numbers of edges and point

struct node{
int from;
int to;
int w;
};
node edge[maxn];//边

bool cmp(node a, node b) {
if(a.from == b.from && a.to == b.to) {
return a.w < b.w;
}
if(a.from == b.from) {
return a.to < b.to;
}
return a.from < b.from;
}

int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i++) {
cin >> edge[i].from >> edge[i].to >> edge[i].w;
}
sort(edge+1, edge+m+1, cmp);
memset(head, -1, sizeof(head));///init head[];
for(int i = 1; i <= m; i++) {
if(edge[i].from != edge[i-1].from) {///judge if the neibor edges has the same beginning point
head[edge[i].from] = i;///确定起点为Vi的第一条边的位置。
}
}
for(int i = 1; i <= n; i++) {
for(int k = head[i]; edge[k].from== i && k <= m; k++) {
cout << edge[k].from << ' ' << edge[k].to << ' ' << edge[k].w << endl;
}
}
return 0;
}
/*  vector模拟链表  */
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1000;
const int maxm = 1000000;

struct node {
int to;
int w;
};
int n, m;
vector<node> a[maxn];

void output() {
vector<node>::iterator k;
for(int i = 1; i <= n; i++) {
for(k = a[i].begin(); k != a[i].end(); k++) {
node tmp = *k;
cout << i << ' ' << tmp.to << ' ' << tmp.w << endl;
}
}
}

int main()
{
int n, m;
node e;
int i, j, w;
for(int i = 1; i<= m; i++) {
cin >> i >> j >> w;
e.to = j;
e.w = w;
a[i].push_back(e);
}
output();
return 0;
}

/***************************
测试样例:
5 8
1 2 2
1 3 3
2 4 7
2 5 12
3 5 10
4 5 9
3 2 6
3 4 1
喜爱编程的朋友加油!
***********************/


STL中vector模拟链表实现,代码量较少,也不易犯错误,内存的申请与释放都不需要自己处理,比较好!

静态建表(链式前向星)优点在于可以存储重边,需要空间也不多,与动态建表相比没有内存管理,

更安全,应该说除了不能直接

用起点和终点确定是否有边以外,链式前向星几乎是完美的!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: