1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
/*
Projet d'algorithmique et programmation 2013-2014
(cours de C.Matthieu et J.Stern)
Alex AUVOLAT, Mendes OULAMARA
Fonctions pour la manipulation de graphes.
*/
#include <stdlib.h>
#include "graph.h"
graph load_graph(FILE *stream) {
int i, r, a, b;
graph k = malloc(sizeof(struct graph_descriptor));
fscanf(stream, "%d ", &k->N); // read node count
k->neighbour = malloc(k->N * sizeof(set));
for (i = 0; i < k->N; i++) k->neighbour[i] = empty_set(k->N);
fscanf(stream, "%d ", &r);
for (i = 0; i < r; i++) {
fscanf(stream, "%d %d ", &a, &b);
set_add_ip(b, k->neighbour[a]);
set_add_ip(a, k->neighbour[b]);
}
return k;
}
graph load_graph_dimacs(FILE *stream) {
int i, n, m, a, b;
char buf = fgetc(stream);
while (buf == 'c') {
buf = fgetc(stream);
if (buf == '\n') buf = fgetc(stream);
else buf = 'c';
}
if (buf != 'p') {
fprintf(stderr, "File format error (expected 'p' declaration)\n");
return NULL;
}
fscanf(stream, " col %d %d\n", &n, &m); // read node count
fprintf(stderr, "Load DIMACS: n = %d, m = %d\n", n, m);
graph k = malloc(sizeof(struct graph_descriptor));
k->N = n;
k->neighbour = malloc(n * sizeof(set));
for (i = 0; i < n; i++) k->neighbour[i] = empty_set(n);
for (i = 0; i < m; i++) {
buf = fgetc(stream);
while (buf == 'c') {
buf = fgetc(stream);
if (buf == '\n') buf = fgetc(stream);
else buf = 'c';
}
if (buf != 'e') {
fprintf(stderr, "File format error (expected 'e' declaration)\n");
return NULL;
}
fscanf(stream, " %d %d\n", &a, &b);
a--; b--;
set_add_ip(b, k->neighbour[a]);
set_add_ip(a, k->neighbour[b]);
}
return k;
}
const set graph_neighbours(const graph g, int n) {
return g->neighbour[n];
}
void dump_graphviz(const graph g, FILE *stream) {
int i = 0;
fprintf(stream, "graph A {\n");
for (i = 0; i < g->N; i++) {
fprintf(stream, " \"%d\" []\n", i);
}
for (i = 0; i < g->N; i++) {
set n = copy_set(graph_neighbours(g, i));
while (!(is_set_empty(n))) {
int j = elt_of_set(n);
if (j >= i) fprintf(stream, " \"%d\" -- \"%d\"\n", i, j);
set_remove_ip(j, n);
}
}
fprintf(stream, "}\n");
}
void delete_graph(graph g) {
int i;
for (i = 0; i < g->N; i++) {
delete_set(g->neighbour[i]);
}
free(g->neighbour);
free(g);
}
|