← Catalogo
TREE
PyJS

Completing a Tree

PhylogenyGraph Algorithms

Pagina originale su rosalind.info

Descrizione

Un albero è un grafo connesso senza cicli. Data una lista di adiacenza corrispondente a un grafo su n nodi senza cicli (ma non necessariamente connesso), il problema chiede il numero minimo di archi da aggiungere per trasformare il grafo in un albero (cioè per renderlo completamente connesso senza introdurre cicli).

Given

Un intero positivo n (n ≤ 1000) e una lista di adiacenza corrispondente a un grafo su n nodi che non contiene cicli.

Return

Il numero minimo di archi che possono essere aggiunti al grafo per produrre un albero.

Sample Dataset

10
1 2
2 8
4 10
5 9
6 10
7 9

Sample Output

3

La mia esecuzione

08/24/2026 11:24:47

Input · dataset.txt

829
443 595
712 120
11 13
181 702
451 152
784 243
67 606
11 23
293 690
450 826
44 292
641 13
452 112
650 641
20 196
71 285
2 6
12 67
264 190
400 394
635 107
157 148
672 204
32 250
469 67
571 500
278 47
117 500
569 709
119 794
6 27
647 819
232 53
674 529
109 238
617 268
271 787
473 130
342 741
427 93
373 808
38 513
671 148
9 75
781 660
69 26
652 216
622 381
211 483
315 813
667 192
87 459
368 535
187 716
84 368
755 815
351 189
20 25
202 426
374 685
144 197
88 491
541 380
222 204
84 428
505 495
495 634
35 116
778 25
246 172
375 797
681 277
192 258
241 22
15 799
203 192
107 132
355 71
112 255
439 424
192 284
252 770
362 279
561 222
290 633
138 307
532 120
355 521
390 199
581 679
817 30
497 554
104 379
205 422
809 147
70 143
409 578
245 698
285 403
128 61
8 1
159 572
44 54
33 181
264 276
173 200
61 68
65 248
45 62
507 337
295 540
146 358
61 23
387 217
66 72
96 240
769 34
45 98
19 495
482 370
272 503
280 165
18 32
140 484
20 350
732 247
504 86
26 13
472 234
502 406
4 673
715 161
475 115
669 566
66 508
253 47
755 474
138 6
79 41
80 458
263 68
390 573
425 461
476 357
349 546
34 158
118 357
138 185
674 821
5 3
83 96
691 181
259 174
94 290
624 230
449 209
369 261
165 527
405 584
152 347
31 800
669 825
197 233
116 394
246 289
104 161
354 108
233 514
82 490
394 649
816 764
198 4
46 88
75 638
54 58
51 146
209 413
7 539
240 262
352 666
152 130
95 2
600 537
184 286
312 276
94 74
38 20
531 26
814 116
578 677
15 104
74 20
229 8
795 456
510 351
391 421
44 53
592 571
623 24
5 39
614 424
653 187
256 360
144 752
361 591
763 205
2 155
440 89
357 377
640 572
114 167
478 557
292 365
327 159
759 716
214 163
694 127
765 828
268 756
73 121
628 582
706 66
55 110
283 20
101 430
208 133
771 136
375 63
581 590
362 435
11 15
654 279
385 11
265 670
371 651
682 557
740 267
335 314
51 18
117 466
636 106
60 85
396 369
247 338
16 6
74 76
332 179
626 607
652 686
688 494
333 26
59 17
200 353
807 69
738 540
704 320
106 216
501 553
214 547
642 502
66 20
753 67
89 190
516 90
783 22
287 659
11 31
643 75
8 10
223 45
545 243
478 512
2 103
256 69
114 117
118 57
57 523
764 681
48 32
376 228
538 537
239 7
424 67
37 543
98 178
434 529
254 441
684 573
612 354
330 52
151 662
51 173
803 791
29 9
717 322
427 639
444 230
279 14
601 713
276 742
226 485
496 224
319 227
493 121
288 678
386 399
54 520
6 7
12 90
315 433
658 30
597 81
94 536
326 62
724 280
408 664
38 386
722 533
127 67
110 596
49 563
33 228
125 79
263 589
256 310
782 516
251 88
304 212
3 57
42 785
374 27
305 696
3 20
261 4
268 42
92 113
367 163
222 478
465 602
416 309
142 406
23 479
86 215
601 589
285 780
806 656
645 630
315 192
41 160
790 444
309 173
511 91
517 248
320 431
529 549
465 311
98 106
33 300
41 55
461 570
60 12
85 774
739 586
254 191
462 40
737 279
42 148
829 354
556 98
661 487
750 493
285 736
79 730
3 2
582 607
120 32
305 779
71 39
77 608
334 39
366 548
181 213
761 505
83 586
689 113
692 199
141 765
620 442
648 496
333 464
687 495
7 9
169 489
296 665
8 613
145 122
163 6
773 593
37 711
58 147
75 499
97 218
526 455
4 3
418 720
312 471
131 101
407 200
53 209
115 54
228 257
694 733
305 108
442 30
372 233
216 754
605 211
89 273
248 725
569 71
36 20
438 550
348 13
177 9
537 93
85 311
47 11
630 572
73 567
62 73
212 594
111 32
420 385
767 494
498 32
100 53
103 269
242 757
382 506
66 87
319 721
235 98
185 383
391 362
811 203
705 322
525 186
418 577
524 158
735 383
766 588
137 36
23 247
515 281
244 208
231 443
90 325
275 3
760 554
29 102
277 18
214 298
320 157
751 263
302 308
238 583
349 208
58 252
218 295
7 45
139 429
195 329
226 75
166 221
579 252
56 282
358 468
162 68
170 37
119 85
306 133
414 812
392 348
21 139
619 60
460 519
143 446
796 594
729 776
78 84
336 63
49 544
393 171
27 236
587 526
637 80
483 683
225 575
731 594
288 303
331 436
297 97
291 501
154 562
693 487
95 793
522 278
133 109
388 159
480 269
192 75
363 218
647 729
609 403
368 568
574 565
83 65
171 62
1 2
291 169
109 43
173 225
405 364
213 646
229 318
62 176
20 34
166 364
14 3
26 183
558 278
456 169
34 179
148 494
12 7
345 33
699 50
182 486
559 121
109 130
434 366
337 610
410 6
184 460
328 477
54 153
603 388
207 344
112 38
449 714
521 734
99 36
509 338
560 111
323 322
510 585
745 143
444 798
154 119
697 576
217 16
667 777
76 77
34 37
701 243
576 506
144 19
614 615
772 415
196 389
271 331
9 260
805 178
457 16
668 402
101 135
419 198
804 717
58 93
136 378
76 186
74 97
14 28
768 61
503 680
818 99
12 18
40 14
78 12
593 81
35 17
383 409
59 126
465 708
423 138
16 105
562 743
72 174
49 180
225 249
746 232
810 663
24 11
13 89
744 683
5 656
205 158
65 108
274 144
542 200
207 123
723 567
288 140
49 17
212 41
168 90
233 621
70 107
632 371
417 351
230 414
63 175
429 564
19 63
666 676
80 55
200 211
21 64
579 707
158 382
593 655
129 44
89 136
152 361
488 292
165 40
50 22
42 9
25 219
425 631
675 26
299 40
189 108
337 54
210 40
775 141
34 201
93 401
231 107
159 97
53 346
317 87
30 2
271 599
710 312
33 272
70 242
324 175
50 293
227 77
481 300
34 370
301 213
453 346
267 234
94 823
70 35
663 185
780 822
28 92
747 176
65 40
83 220
149 96
749 457
321 88
243 51
140 91
773 788
42 150
96 188
14 21
53 792
281 124
204 101
45 134
582 625
363 487
627 152
187 728
528 180
79 86
195 270
32 703
149 438
50 398
52 114
82 65
22 33
191 168
827 729
181 447
151 164
35 41
474 23
127 397
337 695
238 726
169 137
87 172
46 30
449 518
405 437
412 149
99 302
717 748
801 74
352 356
2 19
226 402
381 39
119 341
184 158
9 43
596 660
530 520
6 237
206 146
758 589
173 604
155 194
67 101
339 117
299 448
150 616
404 454
361 789
35 373
322 249
126 432
532 762
415 147
146 700
552 11
328 75
181 202
224 183
352 110
492 647
300 611
260 371
287 314
551 136
467 212
305 657
227 566
234 40
449 455
802 754
565 33
10 265
414 418
21 81
343 15
122 26
279 727
463 232
555 315
460 718
271 78
411 286
455 497
71 266
89 296
445 222
254 786
618 588
266 404
11 342
85 313
103 166
55 123
79 450
771 824
118 287
195 18
557 629
199 198
44 9

Output · run_log.txt

OK
 39

Esegui nel browser · Pyodide

Mostra il codice sorgente (problem.py)
#http://rosalind.info/problems/tree/

#10
#1 2
#2 8
#4 10
#5 9
#6 10
#7 9

def lettura(filename):
    dati = []
    with open(filename) as f:
         n = int(f.readline().replace("\n", ""))
         for riga in f:
             #dati.append(list(map(int, riga.replace("\n", "").split(" "))))
             dati.append(riga.replace("\n", "").split(" "))
    return n, dati        

#http://www.bogotobogo.com/python/python_graph_data_structures.php
        
class Vertex:
    def __init__(self, node):
        self.id = node
        self.adjacent = {}

    def __str__(self):
        return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent])

    def add_neighbor(self, neighbor, weight=0):
        self.adjacent[neighbor] = weight

    def get_connections(self):
        return self.adjacent.keys()  

    def get_id(self):
        return self.id

    def get_weight(self, neighbor):
        return self.adjacent[neighbor]

class Graph:
    def __init__(self):
        self.vert_dict = {}
        self.num_vertices = 0

    def __iter__(self):
        return iter(self.vert_dict.values())

    def add_vertex(self, node):
        self.num_vertices = self.num_vertices + 1
        new_vertex = Vertex(node)
        self.vert_dict[node] = new_vertex
        return new_vertex

    def get_vertex(self, n):
        if n in self.vert_dict:
            return self.vert_dict[n]
        else:
            return None

    def add_edge(self, frm, to, cost = 0):
        if frm not in self.vert_dict:
            self.add_vertex(frm)
        if to not in self.vert_dict:
            self.add_vertex(to)

        self.vert_dict[frm].add_neighbor(self.vert_dict[to], cost)
        self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)

    def get_vertices(self):
        return self.vert_dict.keys()
         
def main():
    n, dati = lettura("dataset.txt")
    #print(dati)
    #[['1', '2'], ['2', '8'], ['4', '10'], ['5', '9'], ['6', '10'], ['7', '9']]
    
    g = Graph()

    for i in range(n):
        g.add_vertex(str(i+1))

    for pair in dati:
        g.add_edge(pair[0], pair[1])  

    #for v in g:
        #for w in v.get_connections():
            #vid = v.get_id()
            #wid = w.get_id()
            #print(vid, wid)

        #1 2
        #2 1
        #2 8
        #4 10
        #5 9
        #6 10
        #7 9
        #8 2
        #9 5
        #9 7
        #10 4
        #10 6

    sets = []
    for v in g:
        setv = {v.get_id()} | {x.id for x in v.adjacent}
        found = False 
        for i in range(len(sets)):
            if len(setv & sets[i]) > 0:
               sets[i] = sets[i] | setv
               found = True
               break
        if not found:     
           sets.append(setv)             
    
    #print(sets)
    print("", len(sets)-1)
    # 3
            
if __name__ == "__main__":
    # execute only if run as a script
    main() 
  

Soluzione JavaScript

Esegui ora, live

Mostra il codice sorgente
// Completing a Tree (Rosalind ID: TREE) - soluzione JavaScript
// indipendente, non una trascrizione di problem.py: stessa logica per
// contare le componenti connesse, riscritta in modo idiomatico per JS.
//
// ATTENZIONE - bug riprodotto intenzionalmente: per ogni vertice v,
// problem.py unisce l'insieme {v} ∪ vicini(v) al PRIMO insieme già
// esistente con cui interseca, senza controllare se dovrebbe unirsi
// anche ad altri insiemi già creati in precedenza. Su certe topologie
// (es. un vertice "ponte" che collega due gruppi già registrati come
// insiemi separati) questo può produrre più componenti di quelle
// realmente connesse, sovrastimando gli archi mancanti - un vero e
// proprio bug rispetto a un union-find corretto. Qui è riprodotto
// fedelmente - non corretto - perché il confronto "Corrisponde
// all'output registrato" si basa sull'output REALE già salvato in
// run_log.txt (che contiene lo stesso comportamento).
//
// Nota sul formato: come in inod.mjs, problem.py fa
// print("", len(sets)-1), che con il separatore di default di print
// produce uno SPAZIO INIZIALE prima del numero - riprodotto identico.
//
// Contratto: riceve il contenuto testuale di dataset.txt, restituisce
// l'output testuale (stessa forma dell'output Python).
function lettura(datasetText) {
  const righe = datasetText.split("\n").map((r) => r.replace(/\r$/, ""));
  const n = Number(righe[0]);
  const dati = righe
    .slice(1)
    .filter((r) => r !== "")
    .map((r) => r.split(" "));
  return { n, dati };
}

export default function solve(datasetText) {
  const { n, dati } = lettura(datasetText);

  if (!Number.isInteger(n) || n < 1) {
    throw new Error("Input non valido: attesa una prima riga con il numero di vertici");
  }

  // Adiacenza simmetrica, come Graph.add_edge in problem.py.
  const adiacenza = new Map();
  for (let i = 1; i <= n; i++) adiacenza.set(String(i), new Set());
  for (const [a, b] of dati) {
    if (!adiacenza.has(a)) adiacenza.set(a, new Set());
    if (!adiacenza.has(b)) adiacenza.set(b, new Set());
    adiacenza.get(a).add(b);
    adiacenza.get(b).add(a);
  }

  const sets = [];
  for (let i = 1; i <= n; i++) {
    const id = String(i);
    const setv = new Set([id, ...adiacenza.get(id)]);

    let found = false;
    for (let k = 0; k < sets.length; k++) {
      const intersecano = [...setv].some((x) => sets[k].has(x));
      if (intersecano) {
        for (const x of setv) sets[k].add(x);
        found = true;
        break;
      }
    }
    if (!found) sets.push(setv);
  }

  return ` ${sets.length - 1}\n`;
}