summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 41a5f5ba5e376f354a764e18f94351602194c3c8 (plain)
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
use std::fmt;
use std::io::{self, BufRead};
use std::time::Instant;

struct Graph {
    size: usize,
    matrix: Vec<Vec<i32>>,
}

struct Cutset {
    cardinality: usize,
    vertices: Vec<i32>,
    graph: Graph,
}

impl Clone for Graph {
    fn clone(&self) -> Self {
        let mut matrix = vec![vec![0; self.size]; self.size];
        for row in 0..self.size {
            for col in 0..self.size {
                matrix[row][col] = self.matrix[row][col];
            }
        }
        return Graph {
            size: self.size,
            matrix,
        };
    }
}

impl fmt::Display for Graph {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for row in 0..self.size {
            for col in 0..self.size {
                write!(f, "{}", self.matrix[row][col])?;
                if col < self.size - 1 {
                    write!(f, " ")?;
                }
            }
            if row < self.size - 1 {
                write!(f, "\n")?;
            }
        }
        return Ok(());
    }
}

fn iterate(n: usize) -> Vec<Vec<i32>> {
    let mut components = Vec::new();

    let mut v: Vec<i32> = vec![0; n];
    loop {
        let mut sum: usize = 0;
        for i in &v {
            sum += *i as usize;
        }

        if sum == v.len() {
            break;
        }

        let mut k = 0;
        for i in 0..v.len() {
            if v[i] == 1 {
                v[i] = 0;
            } else {
                k = i;
                break;
            }
        }
        v[k] = 1;
        components.push(v.clone());
    }

    return components;
}

impl Graph {
    fn from_g6(line: &String) -> Graph {
        let mut chars: Vec<u8> = Vec::new();
        for character in line.chars() {
            chars.push((character as i32 - 63) as u8);
        }
        // TODO: spec allows multi-byte vector size
        let size = chars[0] as usize;
        let bytes = &chars[1..];

        let mut matrix: Vec<Vec<i32>> = vec![vec![0; size]; size];
        let mut i = 0;
        for col in 1..size {
            for row in 0..col {
                let bit: i32 = (bytes[i / 6] >> (5 - i % 6) & 1) as i32;
                matrix[row][col] = bit;
                matrix[col][row] = bit;
                i += 1;
            }
        }
        return Graph { size, matrix };
    }

    fn degree(&self, vertex: usize) -> usize {
        let mut sum: usize = 0;
        for i in &self.matrix[vertex] {
            sum += if *i == 0 { 0 } else { 1 } as usize;
        }
        return sum;
    }

    fn min_degree(&self) -> usize {
        let mut min = self.size + 1;
        for i in 0..self.size {
            let d = self.degree(i);
            if d < min {
                min = d;
            }
        }
        return min;
    }

    fn get_closure_traced(&self, trace_steps: bool) -> Graph {
        let mut step = if trace_steps { 2 } else { 1 };

        let mut closure = self.clone();
        for _ in 0..(closure.size * closure.size) {
            let mut changed = false;
            for row in 0..closure.size {
                for col in 0..closure.size {
                    if row == col || closure.matrix[row][col] != 0 {
                        continue;
                    }
                    let sum = closure.degree(row) + closure.degree(col);
                    if sum >= closure.size {
                        closure.matrix[row][col] = step;
                        if trace_steps {
                            step += 1;
                        }
                        changed = true;
                    }
                }
            }
            if !changed {
                break;
            }
        }
        return closure;
    }

    fn get_hamiltonian_cycle(&self) -> Vec<usize> {
        let closure = self.get_closure_traced(true);

        let mut cycle = Vec::new();
        for i in 0..self.size - 1 {
            cycle.push(i + 1);
        }
        cycle.push(0);

        loop {
            let mut start = 0;
            let mut m = 0;

            let mut end = start;
            let mut new_start = start;
            let mut current = start;
            loop {
                let next = cycle[current];
                let val = closure.matrix[current][next];
                // println!("{current} -> {next} = {val}");
                if val > m {
                    m = val;
                    end = current;
                    new_start = next;
                }
                current = next;
                if current == start {
                    break;
                }
            }
            if m == 1 {
                break;
            }
            // println!("New start: {new_start}, end: {end}, m = {m}");
            start = new_start;

            let mut s = start;
            let mut current = cycle[start];
            while current != end {
                let next = cycle[current];
                let u1 = closure.matrix[start][next];
                let u2 = closure.matrix[end][current];
                if u1 < m && u2 < m {
                    s = current;
                    break;
                }
                current = next;
            }
            // println!("s = {s}");

            let mut new_cycle = Vec::new();
            new_cycle.push(start);
            let mut current = cycle[s];
            while current != end {
                new_cycle.push(current);
                current = cycle[current];
            }
            new_cycle.push(end);
            {
                let mut tmp = Vec::new();
                let mut current = cycle[start];
                while current != s {
                    tmp.push(current);
                    current = cycle[current];
                }
                tmp.push(s);
                tmp.reverse();
                for i in tmp {
                    new_cycle.push(i);
                }
            }
            for i in 0..self.size - 1 {
                cycle[new_cycle[i]] = new_cycle[i + 1];
            }
            cycle[new_cycle[self.size - 1]] = new_cycle[0];
        }

        return cycle;
    }

    fn cutsets(&self) -> Vec<Cutset> {
        let mut cs = Vec::new();
        for vertices in iterate(self.size) {
            let mut g = self.clone();
            for vertex in 0..g.size {
                for i in 0..g.size {
                    if vertices[vertex] == 0 {
                        g.matrix[vertex as usize][i as usize] = 0;
                        g.matrix[i as usize][vertex as usize] = 0;
                    }
                }
            }
            let cardinality = vertices.iter().sum::<i32>() as usize;
            cs.push(Cutset {
                cardinality,
                vertices: vertices.clone(),
                graph: g,
            });
        }
        return cs;
    }

    fn max_independent_cutset(&self) -> Cutset {
        let mut max_cutset = None;
        for cutset in self.cutsets() {
            if cutset.graph.is_independent() {
                match &max_cutset {
                    None => max_cutset = Some(cutset),
                    Some(m_cutset) => {
                        if cutset.cardinality > m_cutset.cardinality {
                            max_cutset = Some(cutset);
                        }
                    }
                };
            }
        }
        return max_cutset.unwrap();
    }

    fn dfs(&self, vertex: &usize, visited: &mut Vec<usize>) {
        visited[*vertex] = 1;
        for i in 0..self.size {
            if visited[i] == 0 && self.matrix[*vertex][i] != 0 {
                self.dfs(&i, visited);
            }
        }
    }

    fn count_components_partial(&self, included_vertices: &Vec<i32>) -> usize {
        let mut visited = vec![0; self.size];
        for i in 0..included_vertices.len() {
            if included_vertices[i] == 0 {
                visited[i] = 1;
            }
        }
        let mut count = 0;
        while visited.iter().sum::<usize>() != visited.len() {
            let mut next = 0;
            for i in 0..self.size {
                if visited[i] == 0 {
                    next = i;
                    break;
                }
            }
            self.dfs(&next, &mut visited);
            count += 1;
        }
        return count;
    }

    fn count_components(&self) -> usize {
        self.count_components_partial(&vec![1; self.size])
    }

    fn get_closure(&self) -> Graph {
        self.get_closure_traced(false)
    }

    fn check_toughness(&self, t: f64) -> bool {
        for cutset in self.cutsets() {
            let components_count = cutset.graph.count_components_partial(&cutset.vertices) as f64;
            let cut_cardinality = (self.size - cutset.cardinality) as f64;
            if components_count > 1.0 && cut_cardinality < t * components_count {
                return false;
            }
        }
        return true;
    }

    fn get_toughness(&self) -> f64 {
        let mut left: f64 = 0.0;
        let mut right: f64 = 1024.0; // Reasonable limit
        let eps: f64 = 1e-9;

        while (right - left).abs() > eps {
            let mid = (left + right) / 2.0;

            if self.check_toughness(mid) == false {
                right = mid;
            } else {
                left = mid;
            }
        }

        return (left * 1e7).round() / 1e7;
    }

    fn is_complete(&self) -> bool {
        for row in 0..self.size {
            for col in 0..self.size {
                if row != col && self.matrix[row][col] == 0 {
                    return false;
                }
            }
        }
        return true;
    }

    fn is_independent(&self) -> bool {
        for row in 0..self.size {
            for col in 0..self.size {
                if row != col && self.matrix[row][col] != 0 {
                    return false;
                }
            }
        }
        return true;
    }
}

struct Counters {
    graphs: i32,
    tough_1: i32,
    tough_2: i32,
    bch_hamiltonian: i32,
    t15_hamiltonian: i32,
    t25_hamiltonian: i32,
    dirac_hamiltonian: i32,
    ore_hamiltonian: i32,
    posa_hamiltonian: i32,
}

impl Counters {
    fn new() -> Counters {
        return Counters {
            graphs: 0,
            tough_1: 0,
            tough_2: 0,
            bch_hamiltonian: 0,
            t15_hamiltonian: 0,
            t25_hamiltonian: 0,
            dirac_hamiltonian: 0,
            ore_hamiltonian: 0,
            posa_hamiltonian: 0,
        };
    }
}

fn theorem15(g: &Graph, toughness: f64, min_degree: f64) -> bool {
    let max_ind_cutset_size = g.max_independent_cutset().cardinality as f64;
    let third_of_size = g.size as f64 / 3.0;
    let tmp = if third_of_size > max_ind_cutset_size - 1.0 {
        third_of_size
    } else {
        max_ind_cutset_size - 1.0
    };

    return toughness >= 1.0 && min_degree >= tmp;
}

fn theorem25(g: &Graph, toughness: f64, min_degree: f64) -> bool {
    return min_degree > g.size as f64 / (toughness + 1.0) - 1.0;
}

fn dirac_theorem(g: &Graph) -> bool {
    for vertex in 0..g.size {
        if (g.degree(vertex) as f64) < g.size as f64 / 2.0 {
            return false;
        }
    }
    return true;
}

fn ore_theorem(g: &Graph) -> bool {
    for v1 in 0..g.size {
        for v2 in 0..g.size {
            if v1 == v2 || g.matrix[v1][v2] != 0 {
                continue;
            }
            let d1 = g.degree(v1);
            let d2 = g.degree(v2);
            if d1 + d2 < g.size {
                return false;
            }
        }
    }
    return true;
}

fn posa_theorem(g: &Graph) -> bool {
    let mut degrees = Vec::new();
    for v in 0..g.size {
        degrees.push(g.degree(v));
    }

    let end = if g.size % 2 == 0 {
        g.size / 2
    } else {
        (g.size - 1) / 2
    };

    for k in 1..end {
        let mut cnt = 0;
        for d in &degrees {
            if *d <= k {
                cnt += 1;
            }
        }
        if cnt >= k {
            return false;
        }
    }
    if g.size % 2 != 0 {
        let mut cnt = 0;
        for d in &degrees {
            if *d <= end {
                cnt += 1;
            }
        }
        if cnt > end {
            return false;
        }
    }
    return true;
}

fn main() {
    let stdin = io::stdin();

    let mut time = 0;
    let mut counters = Counters::new();

    for line in stdin.lock().lines() {
        let line = line.unwrap();

        let g = Graph::from_g6(&line);
        counters.graphs += 1;

        let start = Instant::now();
        let closure = g.get_closure();
        let is_complete = closure.is_complete();

        let toughness = if g.is_complete() {
            f64::MAX
        } else {
            g.get_toughness()
        };

        if toughness >= 1.0 {
            counters.tough_1 += 1;
        }
        if toughness >= 2.0 {
            counters.tough_2 += 1;
        }

        let min_degree = g.min_degree() as f64;

        if theorem15(&g, toughness, min_degree) {
            counters.t15_hamiltonian += 1;
        }

        if theorem25(&g, toughness, min_degree) {
            counters.t25_hamiltonian += 1;
        }

        if dirac_theorem(&g) {
            counters.dirac_hamiltonian += 1;
        }

        if ore_theorem(&g) {
            counters.ore_hamiltonian += 1;
        }

        if posa_theorem(&g) {
            counters.posa_hamiltonian += 1;
        }

        if is_complete {
            counters.bch_hamiltonian += 1;
        }

        if is_complete && false {
            println!("Graph: {line}\n{g}");

            let components_count = g.count_components();
            println!("Components count: {components_count}");
            let min_degree = g.min_degree();
            println!("Minimal degree: {min_degree}");

            let cutset = g.max_independent_cutset();
            println!("Maximal independent cutset:\n{}", cutset.graph);
            println!("Included vertices: {:?}", cutset.vertices);
            println!("Cutset cardinality: {}", cutset.cardinality);

            let cycle = g.get_hamiltonian_cycle();
            print!("Hamiltonian cycle: ");
            let start = 0;
            let mut current = start;
            loop {
                print!("{}", current + 1);
                print!(" -> ");
                current = cycle[current];
                if current == start {
                    println!("{}", current + 1);
                    break;
                }
            }
        }

        let elapsed = start.elapsed();
        time += elapsed.as_nanos();
    }

    println!("Total count of graphs: {}", counters.graphs);
    println!("Count of 1-tough graphs: {}", counters.tough_1);
    println!("Count of 2-tough graphs: {}", counters.tough_2);
    println!( "Count of Dirac's Hamiltonian graphs: {}",
        counters.dirac_hamiltonian
    );
    println!( "Count of Ore's Hamiltonian graphs: {}",
        counters.ore_hamiltonian
    );
    println!( "Count of Posa's Hamiltonian graphs: {}",
        counters.posa_hamiltonian
    );
    println!( "Count of Bondy-Chvatal Hamiltonian graphs: {}",
        counters.bch_hamiltonian
    );
    println!(
        "Count of Theorem 15 Hamiltonian graphs: {}",
        counters.t15_hamiltonian
    );
    println!(
        "Count of Theorem 25 Hamiltonian graphs: {}",
        counters.t25_hamiltonian
    );
    println!("Time elapsed: {}s", time as f64 / 1e9);
}