Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

# -*- coding: utf-8 -*- 

r""" 

Disjoint-set data structure 

  

The main entry point is :func:`DisjointSet` which chooses the appropriate 

type to return. For more on the data structure, see :func:`DisjointSet`. 

  

This module defines a class for mutable partitioning of a set, which 

can not be used as a key of a dictionary, vertex of a graph etc. For 

immutable partitioning see :class:`SetPartition`. 

  

AUTHORS: 

  

- Sébastien Labbé (2008) - Initial version. 

- Sébastien Labbé (2009-11-24) - Pickling support 

- Sébastien Labbé (2010-01) - Inclusion into sage (:trac:`6775`). 

  

EXAMPLES: 

  

Disjoint set of integers from ``0`` to ``n - 1``:: 

  

sage: s = DisjointSet(6) 

sage: s 

{{0}, {1}, {2}, {3}, {4}, {5}} 

sage: s.union(2, 4) 

sage: s.union(1, 3) 

sage: s.union(5, 1) 

sage: s 

{{0}, {1, 3, 5}, {2, 4}} 

sage: s.find(3) 

1 

sage: s.find(5) 

1 

sage: list(map(s.find, range(6))) 

[0, 1, 2, 1, 2, 1] 

  

Disjoint set of hashables objects:: 

  

sage: d = DisjointSet('abcde') 

sage: d 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}} 

sage: d.union('a','b') 

sage: d.union('b','c') 

sage: d.union('c','d') 

sage: d 

{{'a', 'b', 'c', 'd'}, {'e'}} 

sage: d.find('c') 

'a' 

""" 

  

#***************************************************************************** 

# Copyright (C) 2009 Sebastien Labbe <slabqc at gmail.com> 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 2 of the License, or 

# (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

  

from sage.rings.integer import Integer 

from sage.structure.sage_object cimport SageObject 

from cpython.object cimport PyObject_RichCompare 

from sage.groups.perm_gps.partn_ref.data_structures cimport * 

  

  

def DisjointSet(arg): 

r""" 

Constructs a disjoint set where each element of ``arg`` is in its 

own set. If ``arg`` is an integer, then the disjoint set returned is 

made of the integers from ``0`` to ``arg - 1``. 

  

A disjoint-set data structure (sometimes called union-find data structure) 

is a data structure that keeps track of a partitioning of a set into a 

number of separate, nonoverlapping sets. It performs two operations: 

  

- :meth:`~sage.sets.disjoint_set.DisjointSet_of_hashables.find` -- 

Determine which set a particular element is in. 

  

- :meth:`~sage.sets.disjoint_set.DisjointSet_of_hashables.union` -- 

Combine or merge two sets into a single set. 

  

REFERENCES: 

  

- :wikipedia:`Disjoint-set_data_structure` 

  

INPUT: 

  

- ``arg`` -- non negative integer or an iterable of hashable objects. 

  

EXAMPLES: 

  

From a non-negative integer:: 

  

sage: DisjointSet(5) 

{{0}, {1}, {2}, {3}, {4}} 

  

From an iterable:: 

  

sage: DisjointSet('abcde') 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}} 

sage: DisjointSet(range(6)) 

{{0}, {1}, {2}, {3}, {4}, {5}} 

sage: DisjointSet(['yi',45,'cheval']) 

{{'cheval'}, {'yi'}, {45}} 

  

TESTS:: 

  

sage: DisjointSet(0) 

{} 

sage: DisjointSet('') 

{} 

sage: DisjointSet([]) 

{} 

  

The argument must be a non negative integer:: 

  

sage: DisjointSet(-1) 

Traceback (most recent call last): 

... 

ValueError: arg (=-1) must be a non negative integer 

  

or an iterable:: 

  

sage: DisjointSet(4.3) 

Traceback (most recent call last): 

... 

TypeError: 'sage.rings.real_mpfr.RealLiteral' object is not iterable 

  

Moreover, the iterable must consist of hashable:: 

  

sage: DisjointSet([{}, {}]) 

Traceback (most recent call last): 

... 

TypeError: unhashable type: 'dict' 

""" 

if isinstance(arg, (Integer, int)): 

if arg < 0: 

raise ValueError('arg (=%s) must be a non negative integer' % arg) 

return DisjointSet_of_integers(arg) 

else: 

return DisjointSet_of_hashables(arg) 

  

cdef class DisjointSet_class(SageObject): 

r""" 

Common class and methods for :class:`DisjointSet_of_integers` and 

:class:`DisjointSet_of_hashables`. 

""" 

def _repr_(self): 

r""" 

Return ``self`` as a unique str. 

  

EXAMPLES:: 

  

sage: e = DisjointSet(5) 

sage: e.union(2,4); e._repr_() 

'{{0}, {1}, {2, 4}, {3}}' 

sage: e = DisjointSet(5) 

sage: e.union(4,2); e._repr_() 

'{{0}, {1}, {2, 4}, {3}}' 

  

:: 

  

sage: e = DisjointSet(range(5)) 

sage: e.union(2,4); e._repr_() 

'{{0}, {1}, {2, 4}, {3}}' 

sage: e = DisjointSet(range(5)) 

sage: e.union(4,2); e._repr_() 

'{{0}, {1}, {2, 4}, {3}}' 

""" 

res = [] 

for l in (<dict?>self.root_to_elements_dict()).itervalues(): 

l.sort() 

res.append('{%s}' % ', '.join(repr(u) for u in l)) 

res.sort() 

return '{%s}' % ', '.join(res) 

  

def __iter__(self): 

""" 

Iterate over elements of the set. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(4) 

sage: d.union(2,0) 

sage: sorted(d) 

[[0, 2], [1], [3]] 

  

sage: d = DisjointSet('abc') 

sage: sorted(d) 

[['a'], ['b'], ['c']] 

""" 

return (<dict?>self.root_to_elements_dict()).itervalues() 

  

def __richcmp__(self, other, int op): 

r""" 

Compare the disjoint sets ``self`` and ``other``. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d == d 

True 

  

:: 

  

sage: e = DisjointSet(5) 

sage: e == d 

True 

  

:: 

  

sage: d.union(0,3) 

sage: d.union(3,4) 

sage: e.union(4,0) 

sage: e.union(3,0) 

sage: e == d 

True 

  

:: 

  

sage: DisjointSet(3) == DisjointSet(5) 

False 

sage: DisjointSet(3) == 4 

False 

  

:: 

  

sage: d = DisjointSet('abcde') 

sage: e = DisjointSet('abcde') 

sage: d.union('a','b') 

sage: d.union('b','c') 

sage: e.union('c','a') 

sage: e == d 

False 

sage: e.union('a','b') 

sage: e == d 

True 

""" 

from sage.sets.all import Set 

s = Set(map(Set, self.root_to_elements_dict().values())) 

try: 

t = Set(map(Set, other.root_to_elements_dict().values())) 

except AttributeError: 

return NotImplemented 

return PyObject_RichCompare(s, t, op) 

  

def cardinality(self): 

r""" 

Return the number of elements in ``self``, *not* the number of subsets. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d.cardinality() 

5 

sage: d.union(2, 4) 

sage: d.cardinality() 

5 

sage: d = DisjointSet(range(5)) 

sage: d.cardinality() 

5 

sage: d.union(2, 4) 

sage: d.cardinality() 

5 

""" 

return self._nodes.degree 

  

def number_of_subsets(self): 

r""" 

Return the number of subsets in ``self``. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d.number_of_subsets() 

5 

sage: d.union(2, 4) 

sage: d.number_of_subsets() 

4 

sage: d = DisjointSet(range(5)) 

sage: d.number_of_subsets() 

5 

sage: d.union(2, 4) 

sage: d.number_of_subsets() 

4 

""" 

return self._nodes.num_cells 

  

cdef class DisjointSet_of_integers(DisjointSet_class): 

r""" 

Disjoint set of integers from ``0`` to ``n-1``. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d 

{{0}, {1}, {2}, {3}, {4}} 

sage: d.union(2,4) 

sage: d.union(0,2) 

sage: d 

{{0, 2, 4}, {1}, {3}} 

sage: d.find(2) 

2 

  

TESTS:: 

  

sage: a = DisjointSet(5) 

sage: a == loads(dumps(a)) 

True 

  

:: 

  

sage: a.union(3,4) 

sage: a == loads(dumps(a)) 

True 

""" 

def __init__(self, n): 

r""" 

Construction of the DisjointSet where each element (integers from ``0`` 

to ``n-1``) is in its own set. 

  

INPUT: 

  

- ``n`` -- Non negative integer 

  

EXAMPLES:: 

  

sage: DisjointSet(6) 

{{0}, {1}, {2}, {3}, {4}, {5}} 

sage: DisjointSet(1) 

{{0}} 

sage: DisjointSet(0) 

{} 

""" 

self._nodes = OP_new(n) 

  

def __dealloc__(self): 

r""" 

Deallocates self, i.e. the self._nodes 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: del d 

""" 

OP_dealloc(self._nodes) 

  

def __reduce__(self): 

r""" 

Return a tuple of three elements: 

  

- The function :func:`DisjointSet` 

- Arguments for the function :func:`DisjointSet` 

- The actual state of ``self``. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d.__reduce__() 

(<built-in function DisjointSet>, (5,), [0, 1, 2, 3, 4]) 

  

:: 

  

sage: d.union(2,4) 

sage: d.union(1,3) 

sage: d.__reduce__() 

(<built-in function DisjointSet>, (5,), [0, 1, 2, 1, 2]) 

""" 

return DisjointSet, (self._nodes.degree,), self.__getstate__() 

  

def __getstate__(self): 

r""" 

Return a list of the parent of each node from ``0`` to ``n-1``. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d.__getstate__() 

[0, 1, 2, 3, 4] 

sage: d.union(2,3) 

sage: d.__getstate__() 

[0, 1, 2, 2, 4] 

sage: d.union(3,0) 

sage: d.__getstate__() 

[2, 1, 2, 2, 4] 

  

Other parents are obtained when the operations are done is a 

distinct order:: 

  

sage: d = DisjointSet(5) 

sage: d.union(0,3) 

sage: d.__getstate__() 

[0, 1, 2, 0, 4] 

sage: d.union(2,0) 

sage: d.__getstate__() 

[0, 1, 0, 0, 4] 

""" 

l = [] 

cdef int i 

for i from 0 <= i < self.cardinality(): 

l.append(self._nodes.parent[i]) 

return l 

  

def __setstate__(self, l): 

r""" 

Merge the nodes ``i`` and ``l[i]`` (using union) for ``i`` in 

``range(len(l))``. 

  

INPUT: 

  

- ``l`` -- list of nodes 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d.__setstate__([0,1,2,3,4]) 

sage: d 

{{0}, {1}, {2}, {3}, {4}} 

  

:: 

  

sage: d = DisjointSet(5) 

sage: d.__setstate__([1,2,3,4,0]) 

sage: d 

{{0, 1, 2, 3, 4}} 

  

:: 

  

sage: d = DisjointSet(5) 

sage: d.__setstate__([1,1,1]) 

sage: d 

{{0, 1, 2}, {3}, {4}} 

  

:: 

  

sage: d = DisjointSet(5) 

sage: d.__setstate__([3,3,3]) 

sage: d 

{{0, 1, 2, 3}, {4}} 

""" 

for i,parent in enumerate(l): 

self.union(parent, i) 

  

def find(self, int i): 

r""" 

Return the representative of the set that ``i`` currently belongs to. 

  

INPUT: 

  

- ``i`` -- element in ``self`` 

  

EXAMPLES:: 

  

sage: e = DisjointSet(5) 

sage: e.union(4,2) 

sage: e 

{{0}, {1}, {2, 4}, {3}} 

sage: e.find(2) 

4 

sage: e.find(4) 

4 

sage: e.union(1,3) 

sage: e 

{{0}, {1, 3}, {2, 4}} 

sage: e.find(1) 

1 

sage: e.find(3) 

1 

sage: e.union(3,2) 

sage: e 

{{0}, {1, 2, 3, 4}} 

sage: [e.find(i) for i in range(5)] 

[0, 1, 1, 1, 1] 

sage: e.find(5) 

Traceback (most recent call last): 

... 

ValueError: i(=5) must be between 0 and 4 

""" 

card = self.cardinality() 

if i < 0 or i>= card: 

raise ValueError('i(=%s) must be between 0 and %s' % (i, card - 1)) 

return OP_find(self._nodes, i) 

  

def union(self, int i, int j): 

r""" 

Combine the set of ``i`` and the set of ``j`` into one. 

  

All elements in those two sets will share the same representative 

that can be gotten using find. 

  

INPUT: 

  

- ``i`` - element in ``self`` 

- ``j`` - element in ``self`` 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d 

{{0}, {1}, {2}, {3}, {4}} 

sage: d.union(0,1) 

sage: d 

{{0, 1}, {2}, {3}, {4}} 

sage: d.union(2,4) 

sage: d 

{{0, 1}, {2, 4}, {3}} 

sage: d.union(1,4) 

sage: d 

{{0, 1, 2, 4}, {3}} 

sage: d.union(1,5) 

Traceback (most recent call last): 

... 

ValueError: j(=5) must be between 0 and 4 

""" 

cdef int card = self._nodes.degree 

if i < 0 or i >= card: 

raise ValueError('i(=%s) must be between 0 and %s'%(i, card-1)) 

if j < 0 or j >= card: 

raise ValueError('j(=%s) must be between 0 and %s'%(j, card-1)) 

OP_join(self._nodes, i, j) 

  

def root_to_elements_dict(self): 

r""" 

Return the dictionary where the keys are the roots of ``self`` and the 

values are the elements in the same set as the root. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d.root_to_elements_dict() 

{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]} 

sage: d.union(2,3) 

sage: d.root_to_elements_dict() 

{0: [0], 1: [1], 2: [2, 3], 4: [4]} 

sage: d.union(3,0) 

sage: d.root_to_elements_dict() 

{1: [1], 2: [0, 2, 3], 4: [4]} 

sage: d 

{{0, 2, 3}, {1}, {4}} 

""" 

s = {} 

cdef int i 

for i from 0 <= i < self.cardinality(): 

o = self.find(i) 

if o not in s: 

s[o] = [] 

s[o].append(i) 

return s 

  

def element_to_root_dict(self): 

r""" 

Return the dictionary where the keys are the elements of ``self`` and 

the values are their representative inside a list. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d.union(2,3) 

sage: d.union(4,1) 

sage: e = d.element_to_root_dict(); e 

{0: 0, 1: 4, 2: 2, 3: 2, 4: 4} 

sage: WordMorphism(e) 

WordMorphism: 0->0, 1->4, 2->2, 3->2, 4->4 

""" 

d = {} 

cdef int i 

for i from 0 <= i < self.cardinality(): 

d[i] = self.find(i) 

return d 

  

def to_digraph(self): 

r""" 

Return the current digraph of ``self`` where `(a,b)` is an oriented 

edge if `b` is the parent of `a`. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(5) 

sage: d.union(2,3) 

sage: d.union(4,1) 

sage: d.union(3,4) 

sage: d 

{{0}, {1, 2, 3, 4}} 

sage: g = d.to_digraph(); g 

Looped digraph on 5 vertices 

sage: g.edges() 

[(0, 0, None), (1, 2, None), (2, 2, None), (3, 2, None), (4, 2, None)] 

  

The result depends on the ordering of the union:: 

  

sage: d = DisjointSet(5) 

sage: d.union(1,2) 

sage: d.union(1,3) 

sage: d.union(1,4) 

sage: d 

{{0}, {1, 2, 3, 4}} 

sage: d.to_digraph().edges() 

[(0, 0, None), (1, 1, None), (2, 1, None), (3, 1, None), (4, 1, None)] 

  

""" 

d = {} 

for i from 0 <= i < self.cardinality(): 

d[i] = [self._nodes.parent[i]] 

from sage.graphs.graph import DiGraph 

return DiGraph(d) 

  

cdef class DisjointSet_of_hashables(DisjointSet_class): 

r""" 

Disjoint set of hashables. 

  

EXAMPLES:: 

  

sage: d = DisjointSet('abcde') 

sage: d 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}} 

sage: d.union('a', 'c') 

sage: d 

{{'a', 'c'}, {'b'}, {'d'}, {'e'}} 

sage: d.find('a') 

'a' 

  

TESTS:: 

  

sage: a = DisjointSet('abcdef') 

sage: a == loads(dumps(a)) 

True 

  

:: 

  

sage: a.union('a','c') 

sage: a == loads(dumps(a)) 

True 

""" 

def __init__(self, iterable): 

r""" 

Construction of the trivial disjoint set where each element is in its 

own set. 

  

INPUT: 

  

- ``iterable`` -- An iterable of hashable objects. 

  

EXAMPLES:: 

  

sage: DisjointSet('abcde') 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}} 

sage: DisjointSet(range(6)) 

{{0}, {1}, {2}, {3}, {4}, {5}} 

sage: DisjointSet(['yi',45,'cheval']) 

{{'cheval'}, {'yi'}, {45}} 

sage: DisjointSet(set([0, 1, 2, 3, 4])) 

{{0}, {1}, {2}, {3}, {4}} 

""" 

self._int_to_el = [] 

self._el_to_int = {} 

for (i,e) in enumerate(iterable): 

self._int_to_el.append(e) 

self._el_to_int[e] = i 

self._d = DisjointSet_of_integers(len(self._int_to_el)) 

self._nodes = self._d._nodes 

  

def __reduce__(self): 

r""" 

Return a tuple of three elements : 

  

- The function :func:`DisjointSet` 

- Arguments for the function :func:`DisjointSet` 

- The actual state of ``self``. 

  

EXAMPLES:: 

  

sage: DisjointSet(range(5)) 

{{0}, {1}, {2}, {3}, {4}} 

sage: d = _ 

sage: d.__reduce__() 

(<built-in function DisjointSet>, 

([0, 1, 2, 3, 4],), 

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]) 

  

:: 

  

sage: d.union(2,4) 

sage: d.union(1,3) 

sage: d.__reduce__() 

(<built-in function DisjointSet>, 

([0, 1, 2, 3, 4],), 

[(0, 0), (1, 1), (2, 2), (3, 1), (4, 2)]) 

""" 

return DisjointSet, (self._int_to_el,), self.__getstate__() 

  

def __getstate__(self): 

r""" 

Return a list of pairs (``n``, parent of ``n``) for each node ``n``. 

  

EXAMPLES:: 

  

sage: d = DisjointSet('abcde') 

sage: d.__getstate__() 

[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd'), ('e', 'e')] 

sage: d.union('c','d') 

sage: d.__getstate__() 

[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'c'), ('e', 'e')] 

sage: d.union('d','a') 

sage: d.__getstate__() 

[('a', 'c'), ('b', 'b'), ('c', 'c'), ('d', 'c'), ('e', 'e')] 

  

Other parents are obtained when the operations are done is a 

different order:: 

  

sage: d = DisjointSet('abcde') 

sage: d.union('d','c') 

sage: d.__getstate__() 

[('a', 'a'), ('b', 'b'), ('c', 'd'), ('d', 'd'), ('e', 'e')] 

""" 

gs = self._d.__getstate__() 

l = [] 

cdef int i 

for i from 0 <= i < self.cardinality(): 

l.append(self._int_to_el[gs[i]]) 

return list(zip(self._int_to_el, l)) 

  

def __setstate__(self, l): 

r""" 

Merge the nodes ``a`` and ``b`` for each pair of nodes 

``(a,b)`` in ``l``. 

  

INPUT: 

  

- ``l`` -- list of pair of nodes 

  

EXAMPLES:: 

  

sage: d = DisjointSet('abcde') 

sage: d.__setstate__([('a','a'),('b','b'),('c','c')]) 

sage: d 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}} 

  

:: 

  

sage: d = DisjointSet('abcde') 

sage: d.__setstate__([('a','b'),('b','c'),('c','d'),('d','e')]) 

sage: d 

{{'a', 'b', 'c', 'd', 'e'}} 

""" 

for a,b in l: 

self.union(a, b) 

  

def find(self, e): 

r""" 

Return the representative of the set that ``e`` currently belongs to. 

  

INPUT: 

  

- ``e`` -- element in ``self`` 

  

EXAMPLES:: 

  

sage: e = DisjointSet(range(5)) 

sage: e.union(4,2) 

sage: e 

{{0}, {1}, {2, 4}, {3}} 

sage: e.find(2) 

4 

sage: e.find(4) 

4 

sage: e.union(1,3) 

sage: e 

{{0}, {1, 3}, {2, 4}} 

sage: e.find(1) 

1 

sage: e.find(3) 

1 

sage: e.union(3,2) 

sage: e 

{{0}, {1, 2, 3, 4}} 

sage: [e.find(i) for i in range(5)] 

[0, 1, 1, 1, 1] 

sage: e.find(5) 

Traceback (most recent call last): 

... 

KeyError: 5 

""" 

i = self._el_to_int[e] 

r = self._d.find(i) 

return self._int_to_el[r] 

  

def union(self, e, f): 

r""" 

Combine the set of ``e`` and the set of ``f`` into one. 

  

All elements in those two sets will share the same representative 

that can be gotten using find. 

  

INPUT: 

  

- ``e`` - element in ``self`` 

- ``f`` - element in ``self`` 

  

EXAMPLES:: 

  

sage: e = DisjointSet('abcde') 

sage: e 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}} 

sage: e.union('a','b') 

sage: e 

{{'a', 'b'}, {'c'}, {'d'}, {'e'}} 

sage: e.union('c','e') 

sage: e 

{{'a', 'b'}, {'c', 'e'}, {'d'}} 

sage: e.union('b','e') 

sage: e 

{{'a', 'b', 'c', 'e'}, {'d'}} 

""" 

i = self._el_to_int[e] 

j = self._el_to_int[f] 

self._d.union(i, j) 

  

def root_to_elements_dict(self): 

r""" 

Return the dictionary where the keys are the roots of ``self`` and the 

values are the elements in the same set. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(range(5)) 

sage: d.union(2,3) 

sage: d.union(4,1) 

sage: e = d.root_to_elements_dict(); e 

{0: [0], 2: [2, 3], 4: [1, 4]} 

""" 

s = {} 

for e in self._int_to_el: 

r = self.find(e) 

if r not in s: 

s[r] = [] 

s[r].append(e) 

return s 

  

def element_to_root_dict(self): 

r""" 

Return the dictionary where the keys are the elements of ``self`` and 

the values are their representative inside a list. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(range(5)) 

sage: d.union(2,3) 

sage: d.union(4,1) 

sage: e = d.element_to_root_dict(); e 

{0: 0, 1: 4, 2: 2, 3: 2, 4: 4} 

sage: WordMorphism(e) 

WordMorphism: 0->0, 1->4, 2->2, 3->2, 4->4 

""" 

d = {} 

for a in self._int_to_el: 

d[a] = self.find(a) 

return d 

  

def to_digraph(self): 

r""" 

Return the current digraph of ``self`` where `(a,b)` is an oriented 

edge if `b` is the parent of `a`. 

  

EXAMPLES:: 

  

sage: d = DisjointSet(range(5)) 

sage: d.union(2,3) 

sage: d.union(4,1) 

sage: d.union(3,4) 

sage: d 

{{0}, {1, 2, 3, 4}} 

sage: g = d.to_digraph(); g 

Looped digraph on 5 vertices 

sage: g.edges() 

[(0, 0, None), (1, 2, None), (2, 2, None), (3, 2, None), (4, 2, None)] 

  

The result depends on the ordering of the union:: 

  

sage: d = DisjointSet(range(5)) 

sage: d.union(1,2) 

sage: d.union(1,3) 

sage: d.union(1,4) 

sage: d 

{{0}, {1, 2, 3, 4}} 

sage: d.to_digraph().edges() 

[(0, 0, None), (1, 1, None), (2, 1, None), (3, 1, None), (4, 1, None)] 

  

""" 

d = {} 

for i from 0 <= i < self.cardinality(): 

e = self._int_to_el[i] 

p = self._int_to_el[self._nodes.parent[i]] 

d[e] = [p] 

from sage.graphs.graph import DiGraph 

return DiGraph(d)