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
| package main
import ( "bytes" "fmt" )
type IntSet struct { words []uint64 }
func (s *IntSet) Has(x int) bool { word, bit := x / 64, uint(x % 64) return word < len(s.words) && s.words[word] & (1 << bit) != 0 }
func (s *IntSet) Add(x int) { word, bit := x / 64, uint(x % 64) for word >= len(s.words) { s.words = append(s.words, 0) } s.words[word] |= 1 << bit }
func (s *IntSet) UnionWith(t *IntSet) { for i, tword := range t.words { if i < len(s.words) { s.words[i] |= tword } else { s.words = append(s.words, tword) } } }
func (s *IntSet) String() string { var buf bytes.Buffer buf.WriteByte('{') for i, word := range s.words { if word == 0 { continue } for j := 0; j < 64; j++ { if word & (1 << uint(j)) != 0 { if buf.Len() > len("{") { buf.WriteByte(' ') } fmt.Fprintf(&buf, "%d", 64 * i + j) } } } buf.WriteByte('}') return buf.String() }
func (s *IntSet) Len() int { ans := 0 for _, e := range s.words { for e != 0 { ans ++ e &= e - 1 } } return ans } func (s *IntSet) Remove(x int) { word, bit := x / 64, uint(x % 64) bit = ^bit s.words[word] |= 1 << bit
} func (s *IntSet) Clear() { s.words = nil } func (s *IntSet) Copy() *IntSet { ans := new(IntSet) for _, e := range s.words { ans.words = append(ans.words, e) } return ans } func main(){ var x, y IntSet x.Add(1) x.Add(144) x.Add(9) fmt.Println(x.String()) y.Add(9) y.Add(42) fmt.Println(y.String()) x.UnionWith(&y) fmt.Println(x.String()) }
|