模板

几个板子,以备不时之需。

顺序表

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 class Vector {
 6 private:
 7     int size, length;
 8     int *data;
 9 public:
10     Vector(int input_size) {
11         size = input_size;
12         length = 0;
13         data = new int[size];
14     }
15     ~Vector() {
16         delete[] data;
17     }
18     bool insert(int loc, int value) {
19         if (loc < 0 || loc > length) {
20             return false;
21         }
22         if (length >= size) {
23             return false;
24         }
25         for (int i = length; i > loc; --i) {
26             data[i] = data[i - 1];
27         }
28         data[loc] = value;
29         length++;
30         return true;
31     }
32     int search(int value) {
33         for (int i = 0; i < length; ++i) {
34             if (data[i] == value) {
35                 return i;
36             }
37         }
38         return -1;
39     }
40     bool remove(int index) {
41         if (index < 0 || index >= length) {
42             return false;
43         }
44         for (int i = index + 1; i < length; ++i) {
45             data[i - 1] = data[i];
46         }
47         length = length - 1;
48         return true;
49     }
50     void print() {
51         for (int i = 0; i < length; i++) {
52             if (i > 0) {
53                 cout << " ";
54             }
55             cout << data[i];
56         }
57         cout << endl;
58     }
59 
60     void MoveLeft(int n, int k)
61     {
62         int *temp = new int[n];
63         for (int i = 0; i != length; ++i) {
64             temp[i] = data[i];
65         }
66         for (int j = 0; j != n; ++j) {
67             data[j] = temp[(j+k)%n];
68         }
69         delete []temp;
70     }
71 };
72 
73 int main()
74 {
75     int n, k;
76     cin >> n >> k;
77     
78     Vector a(n);
79     int number;
80     for (int i = 0; i != n; ++i) {
81         cin >> number;
82         a.insert(i, number);
83     }
84     a.MoveLeft(n, k);
85     a.print();
86     return 0;
87 }
SequenceTable.cpp

表:

  1 #include <stdlib.h>
  2 #include <stdio.h>
  3 #include <stdbool.h>
  4 struct Node;
  5 typedef struct Node *PtrToNode;
  6 typedef PtrToNode List;
  7 typedef PtrToNode Position;
  8 
  9 typedef int ElementType;
 10 
 11 struct Node {
 12     ElementType Element;
 13     Position Pervious;
 14     Position Next;
 15 };
 16 
 17 
 18 List MakeEmpty()
 19 {
 20     List L;
 21     L = (List)malloc(sizeof(struct Node));
 22     L->Element = 0;
 23     L->Next = NULL;
 24     return L; 
 25 }
 26 
 27 int IsEmpty(List L)
 28 {
 29     return L->Next == NULL;
 30 }
 31 
 32 bool IsLast(Position P, List L)
 33 {
 34     return P->Next == NULL;
 35 }
 36 
 37 Position Find(ElementType X, List L)
 38 {
 39     Position P;
 40     P = L->Next;
 41     
 42     while (P->Next != NULL && P->Element != X)
 43         P = P->Next;
 44     return P;
 45 }
 46 
 47 Position FindPervious(ElementType X, List L)
 48 {
 49     Position P = L;
 50     while (P->Next != NULL && P->Next->Element != X)
 51         P = P->Next;
 52     return P;
 53 }
 54 
 55 void Delete(ElementType X, List L)
 56 {
 57     Position P, temp_cell;
 58     P = FindPervious(X, L);
 59     
 60     if (!IsLast(P, L)) {
 61         temp_cell = P->Next;
 62         P->Next = temp_cell->Next;
 63         free(temp_cell);
 64     }
 65 }
 66 
 67 void Insert(ElementType X, Position P, List L)
 68 {
 69     Position temp_cell;
 70     temp_cell = (Position)malloc(sizeof(struct Node));
 71     if (temp_cell == NULL)
 72         printf("Error!");
 73     temp_cell->Element = X;
 74     temp_cell->Next = P->Next;
 75     P->Next = temp_cell;
 76 }
 77 
 78 void DeleteList(List L)
 79 {
 80     Position P, temp;
 81     P = L->Next;
 82     L->Next = NULL;
 83     
 84     while (P != NULL) {
 85         temp = P->Next;
 86         free(P);
 87         P = temp;
 88     }
 89 }
 90 
 91 Position Header(List L)
 92 {
 93     return L;
 94 }
 95 
 96 Position First(List L)
 97 {
 98     return L->Next;
 99 }
100 
101 Position Advance(Position P, List L)
102 {
103     return FindPervious(P->Element, L);
104 }
105 
106 ElementType Retrieve(Position P, List L)
107 {
108     Position temp_cell = Find(P->Element, L);
109     return temp_cell->Element;
110 }
111 void PrintLots(const List L, const int* P)
112 {
113     int i, count;
114     i = count = 0;
115     while (L) {
116         if (P[i] == count) {
117             printf("%d ", L->value);
118             ++i;
119         }
120         else {
121             ++cout;
122             L = L->Next;
123         }
124     }
125 }
126 int main ()
127 {
128     List L = MakeEmpty();
129     Position P = L;
130     for (ElementType i = 0; i != 10; ++i) {
131         Insert(i, P, L);
132     }
133     P = Find(5, L);
134     printf("%d\t", P->Element);
135     P = FindPervious(5, L);
136     printf("%d\n", P->Element);
137     P = L->Next;
138     while (P->Next != NULL) {
139         printf("%d ", P->Element);
140         P = P->Next;
141     }
142     if (IsLast(P, L)) {
143         printf("\nTrue\n");
144     }
145     else {
146         printf("\nFalse\n");
147     }
148     Delete(5, L);
149     P = L->Next;
150     while (P->Next != NULL) {
151         printf("%d ", P->Element);
152         P = P->Next;
153     }
154     DeleteList(L);
155     IsEmpty(L);
156     
157     return 0;
158 }
List.c

顺序表:

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #define SpaceSize 100
  5 
  6 typedef int PtrToNode;
  7 typedef PtrToNode List;
  8 typedef PtrToNode Position;
  9 
 10 typedef int ElementType;
 11 
 12 struct Node {
 13     ElementType Element;
 14     Position Next;
 15 };
 16 
 17 struct Node CursorSpace[SpaceSize];
 18 
 19 static Position CursorAlloc(void)
 20 {
 21     Position P;
 22     P = CursorSpace[0].Next;
 23     CursorSpace[0].Next = CursorSpace[P].Next;
 24     return P;
 25 }
 26 static void CursorFree(Position P)
 27 {
 28     CursorSpace[P].Next = CursorSpace[0].Next;
 29     CursorSpace[0].Next = P;
 30 }
 31 
 32 void InitializeCursorSpace(void)
 33 {
 34     CursorSpace[0].Element = 0;
 35     CursorSpace[0].Next = -1;
 36 }
 37 
 38 List MakEmpty(List L)
 39 {
 40     CursorSpace[L].Element = 0;
 41     CursorSpace[L].Next = -1;
 42     return L;
 43 }
 44 int IsEmpty(const List L)
 45 {
 46     return CursorSpace[0].Next == -1; 
 47 }
 48 int IsLast(const Position P, const List L)
 49 {
 50     return CursorSpace[P].Next == -1;
 51 }
 52 
 53 Position Find(ElementType X, const List L)
 54 {
 55     Position P;
 56     P = CursorSpace[L].Next;
 57     while (P && CursorSpace[P].Element != X) {
 58         P = CursorSpace[P].Next;
 59     }
 60     return P;
 61 }
 62 
 63 Position FindPrevious(ElementType X, const List L)
 64 {
 65     Position P;
 66     P = CursorSpace[L].Next;
 67     while (P && CursorSpace[CursorSpace[P].Next].Element != X) {
 68         P = CursorSpace[P].Next;
 69     }
 70     return P;
 71 }
 72 
 73 void Delete(ElementType X, List L)
 74 {
 75     Position P, TmpCell;
 76     P = FindPrevious(X, L);
 77     if (!IsLast(P, L)) {
 78         TmpCell = CursorSpace[P].Next;
 79         CursorSpace[P].Next = CursorSpace[TmpCell].Next;
 80         CursorFree(TmpCell);
 81     }
 82 }
 83 
 84 void Insert(ElementType X, List L, Position P)
 85 {
 86     Position TmpCell;
 87     TmpCell = CursorAlloc();
 88     if (TmpCell == 0)
 89         exit(1);
 90     
 91     CursorSpace[TmpCell].Element = X;
 92     CursorSpace[TmpCell].Next = CursorSpace[P].Next;
 93     CursorSpace[P].Next = TmpCell;
 94 }
 95 
 96 void DeleteList(List L)
 97 {
 98     Position P, temp;
 99     P = CursorSpace[L].Next;
100     CursorSpace[L].Next = -1;
101     
102     while (P != 0) {
103         temp = CursorSpace[P].Next;
104         CursorFree(P);
105         P = temp;
106     }
107 }
108 
109 Position Header(const List L)
110 {
111     return L;
112 }
113 
114 Position First(const List L)
115 {
116     return CursorSpace[L].Next;
117 }
118 
119 Position Advance(const Position P, const List L)
120 {
121     return FindPrevious(CursorSpace[P].Element, L);
122 }
123 
124 
125 ElementType Retrieve(const Position P, const List L)
126 {
127     Position temp = Find(CursorSpace[P].Element, L);
128     return CursorSpace[temp].Element;
129 }
130 
131 int main ()
132 {
133     return 0;
134 }
ListCursor.c

链表

 1 #include<iostream>
 2 using namespace std;
 3 class Node {
 4 public:
 5     int data;
 6     Node* next;
 7     Node(int _data) {
 8         data = _data;
 9         next = NULL;
10     }
11 };
12 class LinkList {
13 private:
14     Node* head;
15 public:
16     LinkList() {
17         head = NULL;
18     }
19     void insert(Node *node, int index) {
20         if (head == NULL) {
21             head = node;
22             return;
23         }
24         if (index == 0) {
25             node->next = head;
26             head = node;
27             return;
28         }
29         Node *current_node = head;
30         int count = 0;
31         while (current_node->next != NULL && count < index - 1) {
32             current_node = current_node->next;
33             count++;
34         }
35         if (count == index - 1) {
36             node->next = current_node->next;
37             current_node->next = node;
38         }
39     }
40     void output() {
41         if (head == NULL) {
42             return;
43         }
44         Node *current_node = head;
45         while (current_node != NULL) {
46             cout << current_node->data << " ";
47             current_node = current_node->next;
48         }
49         cout << endl;
50     }
51     void delete_node(int index) {
52         if (head == NULL) {
53             return;
54         }
55         Node *current_node = head;
56         int count = 0;
57         if (index == 0) {
58             head = head->next;
59             delete current_node;
60             return;
61         }
62         while (current_node->next != NULL && count < index -1) {
63             current_node = current_node->next;
64             count++;
65         }
66         if (count == index - 1 && current_node->next != NULL) {
67             Node *delete_node = current_node->next;
68             current_node->next = delete_node->next;
69             delete delete_node;
70         }
71     }
72     void reverse() {
73         if (head == NULL) {
74             return ;
75         }
76         Node *next_node, *current_node;
77         current_node = head->next;
78         head->next = NULL;
79         while (current_node != NULL) {
80             next_node = current_node->next;
81             current_node->next = head;
82             head = current_node;
83             current_node = next_node;
84         }
85     }
86 };
87 int main() {
88     LinkList linklist;
89     for (int i = 1; i <= 10; i++) {
90         Node *node = new Node(i);
91         linklist.insert(node, i - 1);
92     }
93     linklist.output();
94     linklist.delete_node(3);
95     linklist.output();
96     linklist.reverse();
97     linklist.output();
98     return 0;
99 }
LinkedList.cpp

循环链表(约瑟夫环):

 1 #include<iostream>
 2 using namespace std;
 3 class Node {
 4 public:
 5     int data;
 6     Node* next;
 7     Node(int _data) {
 8         data = _data;
 9         next = NULL;
10     }
11 };
12 class LinkList {
13 private:
14     Node* head;
15 public:
16     LinkList() {
17         head = NULL;
18     }
19     void insert(Node *node, int index) {
20         if (head == NULL) {
21             head = node;
22             head->next = head;
23             return;
24         }
25         if (index == 0) {
26             node->next = head->next;
27             head->next = node;
28             return;
29         }
30         Node *current_node = head->next;
31         int count = 0;
32         while (current_node != head && count < index - 1) {
33             current_node = current_node->next;
34             count++;
35         }
36         if (count == index - 1) {
37             node->next = current_node->next;
38             current_node->next = node;
39         }
40         if (node == head->next) {
41             head = node;
42         }
43     }
44     void output_josephus(int m) {
45          Node *current_node = head;
46         while (current_node->next != current_node) {
47             for (int i = 1; i < m; ++i) {
48                 current_node = current_node->next;
49             }
50             cout << current_node->next->data << " ";
51             Node *delete_node = current_node->next;
52             current_node->next = current_node->next->next;
53             delete delete_node;
54         }
55         cout << current_node->data << endl;
56         delete current_node;
57     }
58 };
59 int main() {
60     LinkList linklist;
61     int n, m;
62     cin >> n >> m;
63     for (int i = 1; i <= n; i++) {
64         Node *node = new Node(i);
65         linklist.insert(node, i - 1);
66     }
67     linklist.output_josephus(m);
68     return 0;
69 }
CircularLinkedList.cpp

队列

 1 #include <iostream>
 2 #include <cassert>
 3 using namespace std;
 4 class Queue {
 5 private:
 6     int *data;
 7     int head, tail, length;
 8 public:
 9     Queue(int length_input) {
10         data = new int[length_input];
11         length = length_input;
12         head = 0;
13         tail = -1;
14     }
15     ~Queue() {
16         delete[] data;
17     }
18     void push(int element) {
19         if (tail + 1 < length) {
20             tail++;
21             data[tail] = element;
22         }
23     }
24     void output() {
25         for (int i = head; i <= tail; i++) {
26             cout << data[i] << " ";
27         }
28         cout << endl;
29     }
30     int front() {
31         assert(head <= tail);
32         return data[head];
33     }
34     void pop() {
35         assert(head <= tail);
36         head += 1;
37     }
38 };
39 int main() {
40     Queue queue(100);
41     for (int i = 1; i <= 10; i++) {
42         queue.push(i);
43     }
44     queue.output();
45     cout << queue.front() << endl;
46     queue.pop();
47     queue.output();
48     return 0;
49 }
Queue.cpp

队列

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <stdbool.h>
 4 #define MAXELEMENTS 100
 5 
 6 typedef int ElementType;
 7 typedef struct node QNode;
 8 struct node{
 9     ElementType item;
10     QNode* next;
11 };
12 
13 typedef struct queue{
14     QNode* front;
15     QNode* real;
16     int count;
17 } Queue;
18 
19 void InitQueue(Queue* Q)
20 {
21     Q = (Queue*)malloc(sizeof(Queue));
22     Q->count = 0;
23     Q->front = Q->real = NULL;
24 }
25 
26 bool QueueIsFull(const Queue* Q)
27 {
28     return Q->count == MAXELEMENTS;
29 }
30 
31 bool QueueIsEmpty(const Queue* Q)
32 {
33     return Q->count == 0;
34 }
35 
36 int QueueItemCount(const Queue* Q)
37 {
38     return Q->count;
39 }
40 
41 bool EnQueue(ElementType item, Queue* Q)
42 {   
43     if (QueueIsFull(Q))
44         return false;
45     QNode* node = (QNode*)malloc(sizeof(QNode));
46     if (!node)
47         exit(1);
48     node->item = item;
49     node->next = NULL;
50     if (QueueIsEmpty(Q))
51         Q->front = node;
52     else
53         Q->real->next = node;
54     Q->count++;
55     return true;
56 }
57 
58 bool DeQueue(ElementType item, Queue* Q)
59 {
60     QNode* node;
61     if (QueueIsEmpty(Q))
62         return false;
63     Q->front->item = item;
64     node = Q->front;
65     Q->front = Q->front->next;
66     free(node);
67     Q->count--;
68     if (Q->count == 0)
69         Q->real = NULL;
70     return true;
71 }
72 
73 void ClearQueue(Queue* Q)
74 {
75     ElementType data;
76     while (!QueueIsEmpty(Q))
77         DeQueue(&data, Q);
78 }
Queue.c

队列数组实现

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #define MinQueueSize 5
  4 
  5 typedef int ElementType;
  6 
  7 struct QueueRecord{
  8     int Capacity;
  9     int Front;
 10     int Rear;
 11     int Size;
 12     ElementType *Array;
 13 };
 14 
 15 typedef struct QueueRecord *Queue;
 16 
 17 int IsEmpty(Queue Q)
 18 {
 19     return Q->Size == 0;
 20 }
 21 
 22 int IsFull(Queue Q)
 23 {
 24     return Q->Size == Q->Capacity;    //Q->Rear == Q->Front-1;
 25 }
 26 
 27 void MakeEmpty(Queue Q)
 28 {
 29     Q->Size = 0;
 30     Q->Front = 1;
 31     Q->Rear = 0;
 32 }
 33 
 34 Queue CreateQueue(int MaxElements)
 35 {
 36     Queue Q;
 37     
 38     if (MaxElements < MinQueueSize)
 39         printf("Queue size is too small");
 40         
 41     Q = malloc(sizeof(struct QueueRecord));
 42     if (Q == NULL)
 43         printf("Out of space!");
 44         
 45     Q->Array = malloc(sizeof(struct QueueRecord));
 46     if (Q == NULL)
 47         printf("Out of space!");
 48     Q->Capacity = MaxElements;
 49     MakeEmpty(Q);
 50     
 51     return Q;
 52 }
 53 
 54 void DisposeQueue(Queue Q)
 55 {
 56     if (Q != NULL) {
 57         free(Q->Array);
 58         free(Q);
 59     }
 60 }
 61 
 62 static int Succ(int value, Queue Q)
 63 {
 64     if (++value == Q->Capacity)
 65         value = 0;
 66     return value;
 67 }
 68 void Enqueue(ElementType X, Queue Q)
 69 {
 70     if (IsFull(Q))
 71         printf("Full Queue");
 72     else {
 73         Q->Size++;
 74         Q->Rear = Succ(Q->Rear, Q);
 75         Q->Array[Q->Rear] = X;
 76     }
 77 }
 78 
 79 ElementType Front(Queue Q)
 80 {
 81     return Q->Array[Q->Front];
 82 }
 83 
 84 static int Pres(int value, Queue Q)
 85 {
 86     if (--value == 0)
 87         value = 0;
 88     return value;
 89 }
 90 void Dequeue(Queue Q)
 91 {
 92     if (IsEmpty(Q))
 93         printf("Empty Queue");
 94     else {
 95         Q->Size--;
 96         Q->Front = Pres(Q->Front, Q);
 97     }
 98 }
 99 
100 ElementType FrontAndDequeue(Queue Q)
101 {
102     if (IsEmpty(Q)) {
103         printf("Empty Queue");
104         return 0;
105     }
106     else {
107         Q->Size--;
108         Q->Front = Pres(Q->Front, Q);
109         return Q->Array[Q->Front];
110     }
111 }
112 
113 int main ()
114 {
115     return 0;
116 }
QueueCursor.c

循环队列

 1 #include <iostream>
 2 #include <cassert>
 3 using namespace std;
 4 class Queue {
 5 private:
 6     int *data;
 7     int head, tail, length, count;
 8 public:
 9     Queue(int length_input) {
10         data = new int[length_input];
11         length = length_input;
12         head = 0;
13         tail = -1;
14         count = 0;
15     }
16     ~Queue() {
17         delete[] data;
18     }
19     bool push(int element) {
20         if (count < length) {
21             tail = (tail + 1) % length;
22             data[tail] = element;
23             count++;
24             return true;
25         } else {
26             return false;
27         }
28     }
29     void output() {
30         for (int i = head; i != tail + 1; i = (i + 1) % length) {
31             cout << data[i] << " ";
32         }
33         cout << endl;
34     }
35     int front() {
36         assert(count > 0);
37         return data[head];
38     }
39     void pop() {
40         assert(count > 0);
41         head = (head+1)%length;
42         count--;
43     }
44 };
45 int main() {
46     Queue queue(100); 
47     for (int i = 1; i <= 10; i++) {
48         queue.push(i);
49     }
50     queue.output();
51     cout << queue.front() << endl;
52     queue.pop();    
53     queue.output();
54     return 0;
55 }
CyclicQueue.cpp

栈:

 1 #include<iostream>
 2 #include<string>
 3 #include<cassert>
 4 using namespace std;
 5 template<class Type> class Stack {
 6 private:
 7     Type *urls;
 8     int max_size, top_index;
 9 public:
10     Stack(int length_input) {
11         urls = new Type[length_input];
12         max_size = length_input;
13         top_index = -1;
14     }
15     ~Stack() {
16         delete[] urls;
17     }
18     bool push(const Type &element) {
19         if (top_index >= max_size - 1) {
20             return false;
21         }
22         top_index++;
23         urls[top_index] = element;
24         return true;
25     }
26     bool pop() {
27         if (top_index < 0) {
28             return false;
29         }
30         top_index--;
31         return true;
32     }
33     Type top() {
34         assert(top_index >= 0);
35         return urls[top_index];
36     }
37 };
38 int main() {
39     int n, m;
40     cin >> n >> m;
41     Stack<string> stack(n);
42     for (int i = 1; i <= m; i++) {
43         int opr;
44         cin >> opr;
45         if (opr == 0) {
46             string element;
47             cin >> element;
48             if (stack.push(element)) {
49                 cout << "push success!" << endl;
50             } else {
51                 cout << "push failed!" << endl;
52             }
53         } else if (opr == 1) {
54             if (stack.pop()) {
55                 cout << "pop success!" << endl;
56             } else {
57                 cout << "pop failed!" << endl;
58             }
59         } else if (opr == 2) {
60             cout << stack.top() << endl;
61         }
62     }
63     return 0;
64 }
Stack.cpp

栈:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef struct Node *PtrToNode;
 5 typedef PtrToNode Stack;
 6 typedef int ElementType;
 7 
 8 struct Node{
 9     ElementType Element;
10     PtrToNode Next;
11 };
12 
13 
14 int IsEmpty(Stack S)
15 {
16     return S->Next == NULL;
17 }
18 
19 void Pop(Stack S)
20 {
21     PtrToNode FirstCell;
22     
23     if (IsEmpty(S))
24         printf("Empty stack\n");
25     else {
26         FirstCell = S->Next;
27         S->Next = S->Next->Next;
28         free(FirstCell);
29     }
30 }
31 
32 void MakeEmpty(Stack S)
33 {
34     if (S == NULL)
35         exit(1);
36     else
37         while (!IsEmpty(S))
38             Pop(S);
39 }
40 
41 Stack CreateSatck(void)
42 {
43     Stack S;
44     
45     S = malloc(sizeof(struct Node));
46     if (S == NULL)
47         exit(1);
48     S->Next = NULL;
49     MakeEmpty(S);
50     return S;    
51 }
52 
53 void Push(ElementType X, Stack S)
54 {
55     PtrToNode TmpCell;
56     
57     TmpCell = malloc(sizeof(struct Node));
58     if (TmpCell == NULL)
59         exit(1);
60     else {
61         TmpCell->Element = X;
62         TmpCell->Next = S->Next;
63         S->Next = TmpCell;
64     }
65 }
66 
67 ElementType Top(Stack S)
68 {
69     if (!IsEmpty(S))
70         return S->Next->Element;
71     printf("Empty stack\n");
72     return 0;
73 }
74 
75 void DisposeSatck(Stack S)
76 {
77     MakeEmpty(S);   /******/
78 }
79 
80 int main (void)
81 {
82     return 0;
83 }
Stack.c

栈数组实现:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define EmptyTOS -1
 4 #define MinStackSize 5
 5 #define MaxElements 100
 6 
 7 typedef int ElementType;
 8 struct StackRecord{
 9     int Capacity;
10     int TopOfStack;
11     ElementType *Array;
12 };
13 typedef struct StackRecord *Stack;
14 
15 int IsEmpty(Stack S)
16 {
17     return S->TopOfStack == EmptyTOS;
18 }
19 
20 int IsFull(Stack S)
21 {
22     return S->Capacity == MaxElements;
23 }
24 
25 void MakeEmpty(Stack S)
26 {
27     S->TopOfStack = EmptyTOS;
28 }
29 
30 Stack CreateStack(int MaxElement)
31 {
32     Stack S;
33     
34     if (MaxElement < MinStackSize)
35         printf("Stack size is too small");
36     
37     S = malloc(sizeof(struct StackRecord));
38     if (S == NULL)
39         printf("Out of space!");
40     
41     S->Array = malloc(sizeof(struct StackRecord));
42     if (S->Array == NULL)
43         printf("Out of space!");
44     S->Capacity = MaxElements;
45     MakeEmpty(S);
46     
47     return S;
48 }
49 
50 void DisposeStack(Stack S)
51 {
52     if (S != NULL) {
53         free(S->Array);
54         free(S);
55     }
56 }
57 
58 void Push(ElementType X, Stack S)
59 {
60     if (IsFull(S))
61         printf("Full stack");
62     else
63         S->Array[++S->TopOfStack] = X;
64 }
65 
66 ElementType Top(Stack S)
67 {
68     if (!IsEmpty(S))
69         return S->Array[S->TopOfStack];
70     printf("Empty Satck");
71     return 0;
72 }
73 
74 void Pop(Stack S)
75 {
76     if (IsEmpty(S))
77         printf("Empty Stack");
78     else
79         S->TopOfStack--;
80 }
81 
82 ElementType TopAndPop(Stack S)
83 {
84     if (!IsEmpty(S))
85         return S->Array[S->TopOfStack--];
86     printf("Empty Satck");
87     return 0;
88 }
89 
90 int main ()
91 {
92     return 0;
93 }
StackCursor.c

表达式求值

 1 #include<iostream>
 2 #include<string>
 3 #include<cassert>
 4 using namespace std;
 5 template<class Type> class Stack {
 6 private:
 7     Type *urls;
 8     int max_size, top_index;
 9 public:
10     Stack(int length_input) {
11         urls = new Type[length_input];
12         max_size = length_input;
13         top_index = -1;
14     }
15     ~Stack() {
16         delete[] urls;
17     }
18     bool push(const Type &element) {
19         if (top_index >= max_size - 1) {
20             return false;
21         }
22         top_index++;
23         urls[top_index] = element;
24         return true;
25     }
26     bool pop() {
27         if (top_index < 0) {
28             return false;
29         }
30         top_index--;
31         return true;
32     }
33     Type top() {
34         assert(top_index >= 0);
35         return urls[top_index];
36     }
37     bool empty() {
38         if (top_index < 0) {
39             return true;
40         } else {
41             return false;
42         }
43     }
44 };
45 bool precede(char a, char b) {
46     if (a == '*') {
47         return true;
48     } else {
49         return false;
50     }
51 }
52 int operate(char theta, int a, int b) {
53     if (theta == '+') {
54         return a + b;
55     } else {
56         return a * b;
57     }
58 }
59 void calc(Stack<int> &numbers, Stack<char> &operators) {
60     int a = numbers.top();
61     numbers.pop();
62     int b = numbers.top();
63     numbers.pop();
64     numbers.push(operate(operators.top(), a, b));
65     operators.pop();
66 }
67 int main() {
68     int n;
69     cin >> n;
70     Stack<int> numbers(n);
71     Stack<char> operators(n);
72     string buffer;
73     cin >> buffer;
74     int i = 0;
75     while (i < n) {
76         if (isdigit(buffer[i])) {
77             numbers.push(buffer[i]-'0');
78             i++;
79         } else {
80             if (operators.empty() || precede(buffer[i], operators.top())) {
81                 operators.push(buffer[i]);
82                 i++;
83             } else {
84                 calc(numbers, operators);
85             }
86         }
87     }
88     while (!operators.empty()) {
89         calc(numbers, operators);
90     }
91     cout << numbers.top() << endl;
92     
93     return 0;
94 }
ExpressionEvaluation.cpp

哈希表(开放地址法):

  1 #include <iostream>
  2 #include <string>
  3 using namespace std;
  4 class HashTable {
  5 private:
  6     string *elem;
  7     int size;
  8 public:
  9     HashTable() {
 10         size = 2000;
 11         elem = new string[size];
 12         for (int i = 0; i < size; i++) {
 13             elem[i] = "#";
 14         }
 15     }
 16     ~HashTable() {
 17         delete[] elem;
 18     }
 19     int hash(string& index) {
 20         int code = 0;
 21         for (size_t i = 0; i < index.length(); i++) {
 22             code = (code * 256 + index[i] + 128) % size;
 23         }
 24         return code;
 25     }
 26     bool search(string& index, int& pos, int& times) {
 27         pos = hash(index);
 28         times = 0;
 29         while (elem[pos] != "#" && elem[pos] != index) {
 30             times++;
 31             if (times < size) {
 32                 pos = (pos + 1) % size;
 33             } else {
 34                 return false;
 35             }
 36         }
 37         if (elem[pos] == index) {
 38             return true;
 39         } else {
 40             return false;
 41         }
 42     }
 43     int insert(string& index) {
 44         int pos, times;
 45         if (search(index, pos, times)) {
 46             return 2;
 47         } else if (times < size / 2) {
 48             elem[pos] = index;
 49             return 1;
 50         } else {
 51             recreate();
 52             return 0;
 53         }
 54     }
 55     void recreate() {
 56         string* temp_elem;
 57         temp_elem = new string[size];
 58         for (int i = 0; i < size; ++i) {
 59             temp_elem[i] = elem[i];
 60         }
 61         int copy_size = size;
 62         size *= 2;
 63         delete[] elem;
 64         elem = new string[size];
 65         for (int i = 0; i < size; ++i) {
 66             elem[i] = "#";
 67         }
 68         for (int i = 0; i < copy_size; ++i) {
 69             if (temp_elem[i] != "#") {
 70                 insert(temp_elem[i]);
 71             }
 72         }
 73         delete[] temp_elem;
 74     }
 75 };
 76 int main() {
 77     HashTable hashtable;
 78     string buffer;
 79     int n;
 80     cin >> n;
 81     for (int i = 1; i <= n; i++) {
 82         cin >> buffer;
 83         int ans = hashtable.insert(buffer);
 84         if (ans == 0) {
 85             cout << "insert failed!" << endl;
 86         } else if (ans == 1) {
 87             cout << "insert success!" << endl;
 88         } else if (ans == 2) {
 89             cout << "It already exists!" << endl;
 90         }
 91     }
 92     int temp_pos, temp_times;
 93     cin >> buffer;
 94     if (hashtable.search(buffer, temp_pos, temp_times)) {
 95         cout << "search success!" << endl;
 96     } else {
 97         cout << "search failed!" << endl;
 98     }
 99     return 0;
100 }
Hashtable.cpp

 二叉树的先序、中序和后序遍历:

 1 #include<iostream>
 2 using namespace std;
 3 class Node {
 4 public:
 5     int data;
 6     Node *lchild, *rchild;
 7     Node(int _data) {
 8         data = _data;
 9         lchild = NULL;
10         rchild = NULL;
11     }
12     ~Node() {
13         if (lchild != NULL) {
14             delete lchild;
15         }
16         if (rchild != NULL) {
17             delete rchild;
18         }
19     }
20     void preorder() {
21         cout << data << " ";
22         if (lchild != NULL) {
23             lchild->preorder();
24         }
25         if (rchild != NULL) {
26             rchild->preorder();
27         }
28     }
29     void inorder() {
30         if (lchild != NULL) {
31             lchild->inorder();
32         }
33         cout << data << " ";
34         if (rchild != NULL) {
35             rchild->inorder();
36         }
37     }
38     void postorder() {
39         if (lchild != NULL) {
40             lchild->postorder();
41         }
42         if (rchild != NULL) {
43             rchild->postorder();
44         }
45         cout << data << " ";
46     }
47 };
48 class BinaryTree {
49 private:
50     Node *root;
51 public:
52     BinaryTree() {
53         root = NULL;
54     }
55     ~BinaryTree() {
56         if (root != NULL) {
57             delete root;
58         }
59     }
60     void build_demo() {
61         root = new Node(1);
62         root->lchild = new Node(2);
63         root->rchild = new Node(3);
64         root->lchild->lchild = new Node(4);
65         root->lchild->rchild = new Node(5);
66         root->rchild->rchild = new Node(6);
67     }
68     void preorder() {
69         root->preorder();
70     }
71     void inorder() {
72         root->inorder();
73     }
74     void postorder() {
75         root->postorder();
76     }
77 };
78 int main() {
79     BinaryTree binarytree;
80     binarytree.build_demo();
81     binarytree.preorder();
82     cout << endl;
83     binarytree.inorder();
84     cout << endl;
85     binarytree.postorder();
86     cout << endl;
87     return 0;
88 }
BinaryTree.cpp

二叉树已知先序中序求后序:

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Node {
 5 public:
 6     int data;
 7     Node *lchild, *rchild;
 8     Node(int _data) {
 9         data = _data;
10         lchild = NULL;
11         rchild = NULL;
12     }
13     ~Node() {
14         if (lchild != NULL) {
15             delete lchild;
16         }
17         if (rchild != NULL) {
18             delete rchild;
19         }
20     }
21     void postorder() {
22         if (lchild != NULL) {
23             lchild->postorder();
24         }
25         if (rchild != NULL) {
26             rchild->postorder();
27         }
28         cout << data << " ";
29     }
30     Node* build(const string& pre_str, const string& in_str, int len) {
31         Node* p = new Node(pre_str[0]-'0');
32         int pos = in_str.find(pre_str[0]);
33         if (pos > 0) {
34             p->lchild = build(pre_str.substr(1, pos), in_str.substr(0, pos), pos);
35         }
36         if (len - pos - 1 > 0) {
37             p->rchild = 
38                 build(pre_str.substr(pos+1), in_str.substr(pos+1), len-pos-1);
39         }
40         return p;
41     }
42 };
43 class BinaryTree {
44 private:
45     Node *root;
46 public:
47     BinaryTree() {
48         root = NULL;
49     }
50     ~BinaryTree() {
51         if (root != NULL) {
52             delete root;
53         }
54     }
55     BinaryTree(const string& pre_str, const string& in_str, int len) {
56         root = root->build(pre_str, in_str, len);
57     }
58     void postorder() {
59         root->postorder();
60     }
61 };
62 int main() {
63     string pre_str = "136945827";
64     string in_str = "963548127";
65     BinaryTree binarytree(pre_str, in_str, in_str.length());
66     binarytree.postorder();
67     cout << endl;
68     return 0;
69 }
BinaryTree.cpp

二叉排序树:

  1 #include<iostream>
  2 using namespace std;
  3 class Node {
  4 public:
  5     int data;
  6     Node *lchild, *rchild, *father;
  7     Node(int _data, Node *_father = NULL) {
  8         data = _data;
  9         lchild = NULL;
 10         rchild = NULL;
 11         father = _father;
 12     }
 13     ~Node() {
 14         if (lchild != NULL) {
 15             delete lchild;
 16         }
 17         if (rchild != NULL) {
 18             delete rchild;
 19         }
 20     }
 21     void insert(int value) {
 22         if (value == data) {
 23             return;
 24         } else if (value > data) {
 25             if (rchild == NULL) {
 26                 rchild = new Node(value, this);
 27             } else {
 28                 rchild->insert(value);
 29             }
 30         } else {
 31             if (lchild == NULL) {
 32                 lchild = new Node(value, this);
 33             } else {
 34                 lchild->insert(value);
 35             }
 36         }
 37     }
 38     Node* search(int value) {
 39         if (data == value) {
 40             return this;
 41         } else if (value > data) {
 42             if (rchild == NULL) {
 43                 return NULL;
 44             } else {
 45                 return rchild->search(value);
 46             }
 47         } else {
 48             if (lchild == NULL) {
 49                 return NULL;
 50             } else {
 51                 return lchild->search(value);
 52             }
 53         }
 54     }
 55     Node* predecessor() {
 56         Node *temp = lchild;
 57         while (temp != NULL && temp->rchild != NULL) {
 58             temp = temp->rchild;
 59         }
 60         return temp;
 61     }
 62     Node* successor() {
 63         Node *temp = rchild;
 64         while (temp != NULL && temp->lchild != NULL) {
 65             temp = temp->lchild;
 66         }
 67         return temp;
 68     }
 69     void remove_node(Node *delete_node) {
 70         Node *temp = NULL;
 71         if (delete_node->lchild != NULL) {
 72             temp = delete_node->lchild;
 73             temp->father = delete_node->father;
 74             delete_node->lchild = NULL;
 75         }
 76         if (delete_node->rchild != NULL) {
 77             temp = delete_node->rchild;
 78             temp->father = delete_node->father;
 79             delete_node->rchild = NULL;
 80         }
 81         if (delete_node->father->lchild == delete_node) {
 82             delete_node->father->lchild = temp;
 83         } else {
 84             delete_node->father->rchild = temp;
 85         }
 86         delete delete_node;
 87     }
 88     bool delete_tree(int value) {
 89         Node *delete_node, *current_node;
 90         current_node = search(value);
 91         if (current_node == NULL) {
 92             return false;
 93         }
 94         if (current_node->lchild != NULL) {
 95             delete_node = current_node->predecessor();
 96         }
 97         else if (current_node->rchild != NULL) {
 98             delete_node = current_node->successor();
 99         }
100         else {
101             delete_node = current_node;
102         }
103         current_node->data = delete_node->data;
104         remove_node(delete_node);
105         return true;
106     }
107 };
108 class BinaryTree {
109 private:
110     Node *root;
111 public:
112     BinaryTree() {
113         root = NULL;
114     }
115     ~BinaryTree() {
116         if (root != NULL) {
117             delete root;
118         }
119     }
120     void insert(int value) {
121         if (root == NULL) {
122             root = new Node(value);
123         } else {
124             root->insert(value);
125         }
126     }
127     bool find(int value) {
128         if (root->search(value) == NULL) {
129             return false;
130         } else {
131            return true;
132         }
133     }
134     bool delete_tree(int value) {
135         return root->delete_tree(value);
136     }
137 };
138 int main() {
139     BinaryTree binarytree;
140     int arr[10] = { 8, 9, 10, 3, 2, 1, 6, 4, 7, 5 };
141     for (int i = 0; i < 10; i++) {
142         binarytree.insert(arr[i]);
143     }
144     int value;
145     cin >> value;
146     if (binarytree.find(value)) {
147         cout << "search success!" << endl;
148     } else {
149         cout << "search failed!" << endl;
150     }
151     cin >> value;
152     if (binarytree.delete_tree(value)) {
153         cout << "delete success!" << endl;
154     }
155     else {
156         cout << "delete failed!" << endl;
157     }
158     return 0;
159 }
BinarySearchTree.cpp

SBtree:

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 class SBTNode {
  6 public:
  7     int data, size, value;
  8     SBTNode * lchild, * rchild, * father;
  9     SBTNode(int init_data, int init_size = 0, SBTNode * init_father = NULL);
 10     ~SBTNode();
 11 
 12     void insert(int value);
 13     SBTNode * search(int value);
 14     SBTNode * predecessor();
 15     SBTNode * successor();
 16     void remove_node(SBTNode * delete_node);
 17     bool remove(int value);
 18 };
 19 
 20 class BinaryTree {
 21 private:
 22     SBTNode * root;
 23 public:
 24     BinaryTree();
 25     ~BinaryTree();
 26     void insert(int value);
 27     bool find(int value);
 28     bool remove(int value);
 29 };
 30 
 31 SBTNode ZERO(0);
 32 SBTNode * ZPTR = &ZERO;
 33 
 34 SBTNode::SBTNode(int init_data, int init_size, SBTNode * init_father) {
 35     data = init_data;
 36     size = init_size;
 37     lchild = ZPTR;
 38     rchild = ZPTR;
 39     father = init_father;
 40 }
 41 
 42 SBTNode::~SBTNode() {
 43     if (lchild != ZPTR) {
 44         delete lchild;
 45     }
 46     if (rchild != ZPTR) {
 47         delete rchild;
 48     }
 49 }
 50 
 51 SBTNode * left_rotate(SBTNode * node) {
 52     SBTNode * temp = node->rchild;
 53     node->rchild = temp->lchild;
 54     temp->lchild->father = node;
 55     temp->lchild = node;
 56     temp->father = node->father;
 57     node->father = temp;
 58     temp->size = node->size;
 59     node->size = node->lchild->size + node->rchild->size + 1;
 60     return temp;
 61 }
 62 
 63 SBTNode * right_rotate(SBTNode * node) {
 64     SBTNode* temp = node->lchild;
 65     node->lchild = temp->rchild;
 66     temp->rchild->father = node;
 67     temp->rchild = node;
 68     temp->father = node->father;
 69     node->father = temp;
 70     temp->size = node->size;
 71     node->size = node->lchild->size + node->rchild->size + 1;
 72     return temp;
 73 }
 74 
 75 SBTNode * maintain(SBTNode * node, bool flag) {
 76     if (flag == false) {
 77         if (node->lchild->lchild->size > node->rchild->size) {
 78             node = right_rotate(node);
 79         }
 80         else if (node->lchild->rchild->size > node->rchild->size) {
 81             node->lchild = left_rotate(node->lchild);
 82             node = right_rotate(node);
 83         }
 84         else {
 85             return node;
 86         }
 87     }
 88     else {
 89         if (node->rchild->rchild->size > node->lchild->size) {
 90             node = left_rotate(node);
 91         }
 92         else if (node->rchild->lchild->size > node->lchild->size) {
 93             node->rchild = right_rotate(node->rchild);
 94             node = left_rotate(node);
 95         }
 96         else {
 97             return node;
 98         }
 99     }
100     node->lchild = maintain(node->lchild, false);
101     node->rchild = maintain(node->rchild, true);
102     node = maintain(node, false);
103     node = maintain(node, true);
104     return node;
105 }
106 
107 SBTNode * insert(SBTNode * node, int value) {
108     if (value == node->data) {
109         return node;
110     } else {
111         node->size++;
112         if (value > node->data) {
113             if (node->rchild == ZPTR) {
114                 node->rchild = new SBTNode(value, 1, node);
115             } else {
116                 node->rchild = insert(node->rchild, value);
117             }
118         } else {
119             if (node->lchild == ZPTR) {
120                 node->lchild = new SBTNode(value, 1, node);
121             } else {
122                 node->lchild = insert(node->lchild, value);
123             }
124         }
125     }
126     return maintain(node, value > node->data);
127 }
128 
129 SBTNode * SBTNode::search(int value) {
130     if (data == value) {
131         return this;
132     } else if (value > data) {
133         if (rchild == ZPTR) {
134             return ZPTR;
135         } else {
136             return rchild->search(value);
137         }
138     } else {
139         if (lchild == ZPTR) {
140             return ZPTR;
141         } else {
142             return lchild->search(value);
143         }
144     }
145 }
146 
147 SBTNode * SBTNode::predecessor() {
148     SBTNode * temp = lchild;
149     while (temp != ZPTR && temp->rchild != ZPTR) {
150         temp = temp->rchild;
151     }
152     return temp;
153 }
154 
155 SBTNode * SBTNode::successor() {
156     SBTNode * temp = rchild;
157     while (temp != ZPTR && temp->lchild != ZPTR) {
158         temp = temp->lchild;
159     }
160     return temp;
161 }
162 
163 void SBTNode::remove_node(SBTNode * delete_node) {
164     SBTNode * temp = ZPTR;
165     if (delete_node->lchild != ZPTR) {
166         temp = delete_node->lchild;
167         temp->father = delete_node->father;
168         delete_node->lchild = ZPTR;
169     }
170 
171     if (delete_node->rchild != ZPTR) {
172         temp = delete_node->rchild;
173         temp->father = delete_node->father;
174         delete_node->rchild = ZPTR;
175     }
176     if (delete_node->father->lchild == delete_node) {
177         delete_node->father->lchild = temp;
178     } else {
179         delete_node->father->rchild = temp;
180     }
181     temp = delete_node;
182     while (temp != NULL) {
183         temp->size--;
184         temp = temp->father;
185     }
186     delete delete_node;
187 }
188 
189 bool SBTNode::remove(int value) {
190     SBTNode * delete_node, * current_node;
191     current_node = search(value);
192     if (current_node == ZPTR) {
193             return false;
194     }
195     size--;
196     if (current_node->lchild != ZPTR) {
197         delete_node = current_node->predecessor();
198     } else if (current_node->rchild != ZPTR) {
199         delete_node = current_node->successor();
200     } else {
201         delete_node = current_node;
202     }
203     current_node->data = delete_node->data;
204     remove_node(delete_node);
205     return true;
206 }
207 
208 int SBTNode::select(int k) {
209     int rank = lchild->size + 1;
210     if (rank == k) {
211         return data;
212     }
213     else if (rank > k) {
214         return lchild->select(k);
215     }
216     else {
217         return rchild->select(k-rank);
218     }
219 }
220     
221 BinaryTree::BinaryTree() {
222     root = NULL;
223 }
224 
225 BinaryTree::~BinaryTree() {
226     if (root != NULL) {
227         delete root;
228     }
229 }
230 
231 void BinaryTree::insert(int value) {
232     if (root == NULL) {
233         root = new SBTNode(value, 1);
234     } else {
235         root = ::insert(root, value);
236     }
237 }
238 
239 bool BinaryTree::find(int value) {
240     if (root->search(value) == NULL) {
241         return false;
242     } else {
243        return true;
244     }
245 }
246     
247 bool BinaryTree::remove(int value) {
248     return root->remove(value);
249 }
250 
251 int BinaryTree::select(int k) {  //树中第K小元素
252     return root->select(k);
253 }
254 
255 int main() {
256     BinaryTree binarytree;
257     int arr[10] = { 8, 9, 10, 3, 2, 1, 6, 4, 7, 5 };
258     for (int i = 0; i < 10; i++) {
259         binarytree.insert(arr[i]);
260     }
261     int value;
262     cin >> value;
263     if (binarytree.find(value)) {
264         cout << "search success!" << endl;
265     } else {
266         cout << "search failed!" << endl;
267     }
268     cin >> value;
269 
270     if (binarytree.remove(value)) {
271         cout << "delete success!" << endl;
272     } else {
273         cout << "delete failed!" << endl;
274     }
275     return 0;
276 }
SBTree.cpp

堆排:

 1 #include<iostream>
 2 using namespace std;
 3 class Heap {
 4 private:
 5     int *data, size;
 6 public:
 7     Heap(int length_input) {
 8         data = new int[length_input];
 9         size = 0;
10     }
11     ~Heap() {
12         delete[] data;
13     }
14     void push(int value) {
15         data[size] = value;
16         int current = size;
17         int father = (current - 1) / 2;
18         while (data[current] > data[father]) {
19             swap(data[current], data[father]);
20             current = father;
21             father = (current - 1) / 2;
22         }
23         size++;
24     }
25     void output() {
26         for (int i = 0; i < size; i++) {
27             cout << data[i] << " ";
28         }
29         cout << endl;
30     }
31     int top() {
32          return data[0];
33     }
34     void update(int pos, int n) {
35         int lchild = 2 * pos + 1, rchild = 2 * pos + 2;
36         int max_value = pos;
37         if (lchild < n && data[lchild] > data[max_value]) {
38             max_value = lchild;
39         }
40         if (rchild < n && data[rchild] > data[max_value]) {
41             max_value = rchild;
42         }
43         if (max_value != pos) {
44             swap(data[pos], data[max_value]);
45             update(max_value, n);
46         }
47     }
48     void pop() {
49         swap(data[0], data[size - 1]);
50         size--;
51         update(0, size);
52     }
53     void heap_sort() {
54         for (int i = size - 1; i >= 1; --i) {
55             swap(data[i], data[0]);
56             update(0, i);
57         }
58     }
59 };
60 int main() {
61     int arr[10] = { 12, 9, 30, 24, 30, 4, 55, 64, 22, 37 };
62     Heap heap(100);
63     for (int i = 0; i < 10; i++) {
64         heap.push(arr[i]);
65     }
66     heap.output();
67     cout << heap.top() << endl;
68     heap.pop();
69     heap.output();
70     heap.heap_sort();
71     heap.output();
72     return 0;
73 }
Heap.cpp

优先队列:

 1 #include<iostream>
 2 using namespace std;
 3 class Heap {
 4 private:
 5     int *data, size;
 6 public:
 7     Heap(int length_input) {
 8         data = new int[length_input];
 9         size = 0;
10     }
11     ~Heap() {
12         delete[] data;
13     }
14     void push(int value) {
15         data[size] = value;
16         int current = size;
17         int father = (current - 1) / 2;
18         while (data[current] < data[father]) {
19             swap(data[current], data[father]);
20             current = father;
21             father = (current - 1) / 2;
22         }
23         size++;
24     }
25     int top() {
26          return data[0];
27     }
28     void update(int pos, int n) {
29         int lchild = 2 * pos + 1, rchild = 2 * pos + 2;
30         int max_value = pos;
31         if (lchild < n && data[lchild] < data[max_value]) {
32             max_value = lchild;
33         }
34         if (rchild < n && data[rchild] < data[max_value]) {
35             max_value = rchild;
36         }
37         if (max_value != pos) {
38             swap(data[pos], data[max_value]);
39             update(max_value, n);
40         }
41     }
42     void pop() {
43         swap(data[0], data[size - 1]);
44         size--;
45         update(0, size);
46     }
47     int heap_size() {
48         return size;
49     }
50 };
51 int main() {
52     int n, value, ans = 0;
53     cin >> n;
54     Heap heap(n);
55     for (int i = 1; i <= n; ++i) {
56         cin >> value;
57         heap.push(value);
58     }
59     if (n == 1) {
60         ans += heap.top();
61     }
62     while (heap.heap_size() > 1) {
63         int a = heap.top();
64         heap.pop();
65         int b = heap.top();
66         heap.pop();
67         ans += a + b;
68         heap.push(a+b);
69     }
70     cout << ans << endl;
71     return 0;
72 }
priority_queue.cpp

并查集:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class DisjointSet {
 5 private:
 6     int *father;
 7 public:
 8     DisjointSet(int size) {
 9         father = new int[size];
10         for (int i = 0; i < size; ++i) {
11             father[i] = i;
12         }
13     }
14     ~DisjointSet() {
15         delete[] father;
16     }
17     int find_set(int node) {
18         if (father[node] != node) {
19             return find_set(father[node]);
20         }
21         return node;
22     }
23     bool merge(int node1, int node2) {
24         int ancestor1 = find_set(node1);
25         int ancestor2 = find_set(node2);
26         if (ancestor1 != ancestor2) {
27             father[ancestor1] = ancestor2;
28             return true;
29         }
30         return false;
31     } 
32 };
33 
34 int main() {
35     DisjointSet dsu(100);
36     int m, x, y;
37     cin >> m;
38     for (int i = 0; i < m; ++i) {
39         cin >> x >> y;
40         bool ans = dsu.merge(x, y);
41         if (ans) {
42             cout << "success" << endl;
43         }
44         else {
45             cout << "failed" << endl;
46         }
47     }
48     return 0;
49 }
dsu.cpp

并查集-按秩合并优化(最坏操作从O(n)降为O(log(n))):

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class DisjointSet {
 5 private:
 6     int *father, *rank;
 7 public:
 8     DisjointSet(int size) {
 9         father = new int[size];
10         rank = new int[size];
11         for (int i = 0; i < size; ++i) {
12             father[i] = i;
13             rank[i] = 0;
14         }
15     }
16     ~DisjointSet() {
17         delete[] father;
18         delete[] rank;
19     }
20     int find_set(int node) {
21         if (father[node] != node) {
22             return find_set(father[node]);
23         }
24         return node;
25     }
26     bool merge(int node1, int node2) {
27         int ancestor1 = find_set(node1);
28         int ancestor2 = find_set(node2);
29         if (ancestor1 != ancestor2) {
30             if (rank[ancestor1] > rank[ancestor2]) {
31                 swap(ancestor1, ancestor2);
32             } 
33             father[ancestor1] = ancestor2;
34             rank[ancestor2] = max(rank[ancestor1] + 1, rank[ancestor2]);
35             return true;
36         }
37         return false;
38     }
39 };
40 
41 int main() {
42     DisjointSet dsu(100);
43     int m, x, y;
44     cin >> m;
45     for (int i = 0; i < m; ++i) {
46         cin >> x >> y;
47         bool ans = dsu.merge(x, y);
48         if (ans) {
49             cout << "success" << endl;
50         } else {
51             cout << "failed" << endl;
52         }
53     }
54     return 0;
55 }
dsu.cpp

并查集-路径压缩优化:

 1  #include <iostream>
 2 using namespace std;
 3 
 4 class DisjointSet {
 5 private:
 6     int *father, *rank;
 7 public:
 8     DisjointSet(int size) {
 9         father = new int[size];
10         rank = new int[size];
11         for (int i = 0; i < size; ++i) {
12             father[i] = i;
13             rank[i] = 0;
14         }
15     }
16     ~DisjointSet() {
17         delete[] father;
18         delete[] rank;
19     }
20     int find_set(int node) {
21         if (father[node] != node) {
22             father[node] = find_set(father[node]);
23         }
24         return father[node];
25     }
26     bool merge(int node1, int node2) {
27         int ancestor1 = find_set(node1);
28         int ancestor2 = find_set(node2);
29         if (ancestor1 != ancestor2) {
30             if (rank[ancestor1] > rank[ancestor2]) {
31                 swap(ancestor1, ancestor2);
32             }
33             father[ancestor1] = ancestor2;
34             rank[ancestor2] = max(rank[ancestor1] + 1, rank[ancestor2]);
35             return true;
36         }
37         return false;
38     }
39 };
40 
41 int main() {
42     DisjointSet dsu(100);
43     int m, x, y;
44     cin >> m;
45     for (int i = 0; i < m; ++i) {
46         cin >> x >> y;
47         bool ans = dsu.merge(x, y);
48         if (ans) {
49             cout << "success" << endl;
50         } else {
51             cout << "failed" << endl;
52         }
53     }
54     return 0;
55 }
dsu.cpp

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class LinkedListNode {
 5 public:
 6     int vertex;
 7     LinkedListNode *next;
 8 
 9     LinkedListNode(int vertex_input) {
10         vertex = vertex_input;
11         next = NULL;
12     }
13 };
14 
15 class LinkedList {
16 public:
17     LinkedListNode *head;
18 
19     LinkedList() {
20         head = NULL;
21     }
22 
23     ~LinkedList() {
24         while (head != NULL) {
25             LinkedListNode *delete_node = head;
26             head = head->next;
27             delete delete_node;
28         }
29     }
30 
31     void insert(int vertex) {
32         LinkedListNode *node = new LinkedListNode(vertex);
33         node->next = head;
34         head = node;
35     }
36 };
37 
38 class Graph {
39 private:
40     LinkedList *edges;
41     int n;
42 public:
43     Graph(int input_n) {
44         n = input_n;
45         edges = new LinkedList[n];
46     }
47 
48     ~Graph() {
49         delete[] edges;
50     }
51 
52     void insert(int x, int y) {
53         edges[x].insert(y);
54     }
55 
56     void output() {
57         for (int i = 0; i < n; ++i) {
58             cout << i << ":";
59             for (auto j = edges[i].head; j != NULL; j = j->next) {
60                 cout << j->vertex << " ";
61             }
62             cout << endl;
63         }
64     }
65 };
66 
67 int main() {
68     int n, m, x, y;    //n为顶点个数,m为有向边的数量, x点y点之间的为一条边
69     cin >> n >> m;
70     Graph g(n);
71     for (int i = 0; i < m; ++i) {
72         cin >> x >> y;
73         g.insert(x, y);
74     }
75     g.output();
76     return 0;
77 }
Graph.cpp

DFS

 1 #include <iostream>
 2 #include <vector>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 class Graph {
 8 private:
 9     int n;  // 顶点个数
10     vector<int> *edges;  // 邻接表
11     bool * visited;
12     
13 public:
14     Graph(int input_n) {
15         n = input_n;
16         edges = new vector<int>[n];
17         visited = new bool[n];
18         memset(visited, 0, n);
19     }
20 
21     ~Graph() {
22         delete[] edges;
23         delete[] visited;
24     }
25 
26     void insert(int x, int y) {
27         edges[x].push_back(y);
28         edges[y].push_back(x);
29     }
30 
31     void dfs(int vertex) {
32         cout << vertex << endl;
33         visited[vertex] = true;
34         for (int adj_vertex : edges[vertex]) {
35             if (!visited[adj_vertex]) {
36                 dfs(adj_vertex);
37             }
38         }
39     }
40 };
41 
42 int main() {
43     int n, m, k;
44     cin >> n >> m;
45     Graph g(n);
46     for (int i = 0; i < m; ++i) {
47         int x, y;
48         cin >> x >> y;
49         g.insert(x, y);
50     }
51     cin >> k;
52     g.dfs(k);
53     return 0;
54 }
Dfs.cpp

BFS

 1 #include <iostream>
 2 #include <vector>
 3 #include <cstring>
 4 #include <queue>
 5 
 6 using namespace std;
 7 
 8 class Graph {
 9 private:
10     int n;
11     bool *visited;
12     vector<int> *edges;
13 
14 public:
15     Graph(int input_n) {
16         n = input_n;
17         edges = new vector<int>[n];
18         visited = new bool[n];
19         memset(visited, 0, n);
20     }
21 
22     ~Graph() {
23         delete[] edges;
24         delete[] visited;
25     }
26 
27     void insert(int x, int y) {
28         edges[x].push_back(y);
29         edges[y].push_back(x);
30     }
31 
32     void bfs(int start_vertex) {
33         queue<int> bfs_queue;
34         bfs_queue.push(start_vertex);
35         visited[start_vertex] = true;
36         while (!bfs_queue.empty()) {
37             int vertex = bfs_queue.front();
38             cout << vertex << endl;
39             bfs_queue.pop();
40             for (int adj_vertex : edges[vertex]) {
41                 if (!visited[adj_vertex]) {
42                     visited[adj_vertex] = true;
43                     bfs_queue.push(adj_vertex);
44                 }
45             }
46         }
47     }
48 };
49 
50 int main() {
51     int n, m, k;
52     cin >> n >> m;
53     Graph g(n);
54     for (int i = 0; i < m; ++i) {
55         int x, y;
56         cin >> x >> y;
57         g.insert(x, y);
58     }
59     cin >> k;
60     g.bfs(k);
61     return 0;
62 }
Bfs.cpp

Floodfill:

 1 #include <iostream>
 2 #include <vector>
 3 #include <cstring>
 4 #include <queue>
 5 
 6 using namespace std;
 7 
 8 class Graph {
 9 private:
10     int n;
11     int * color;
12     vector<int> * edges;
13 
14 public:
15     Graph(int input_n) {
16         n = input_n;
17         edges = new vector<int>[n];
18         color = new int[n];
19         memset(color, 0, n * sizeof(int));
20     }
21 
22     ~Graph() {
23         delete[] edges;
24         delete[] color;
25     }
26 
27     void insert(int x, int y) {
28         edges[x].push_back(y);
29         edges[y].push_back(x);
30     }
31 
32     void floodfill() {
33         int color_cnt = 0;
34         for (int i = 0; i < n; ++i) {
35             if (color[i] == 0) {
36                 color_cnt++;
37                 color[i] = color_cnt;
38                 queue<int> q;
39                 q.push(i);
40                 while (!q.empty()) {
41                     int vertex = q.front();
42                     for (int j : edges[vertex]) {
43                         if (color[j] == 0) {
44                             color[j] = color_cnt;
45                             q.push(j);
46                         }
47                     }
48                     q.pop();
49                 }
50             }
51         }
52         for (int i = 0; i < n; ++i) {
53             cout << i << " " << color[i] << endl;
54         }
55     }
56 };
57 
58 int main() {
59     int n, m, k;
60     cin >> n >> m;
61     Graph g(n);
62     for (int i = 0; i < m; ++i) {
63         int x, y;
64         cin >> x >> y;
65         g.insert(x, y);
66     }
67     g.floodfill();
68     return 0;
69 }
Floodfill.cpp

Prim:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <vector>
 4 #include <queue>
 5 using namespace std;
 6 
 7 const int INF = 0x3f3f3f3f;
 8 
 9 struct Edge {
10     int vertex, weight;
11 };
12 
13 class Graph {
14 private:
15     int n;
16     bool * visited;
17     vector<Edge> * edges;
18 public:
19     int * dist;
20     Graph (int input_n) {
21         n = input_n;
22         edges = new vector<Edge>[n];
23         dist = new int[n];
24         visited = new bool[n];
25         memset(visited, false, n * sizeof(bool));
26         memset(dist, 0x3f, n * sizeof(int));
27     }
28     ~Graph() {
29         delete[] dist;
30         delete[] visited;
31         delete[] edges;
32     }
33     void insert(int x, int y, int weight) {
34         edges[x].push_back(Edge{y, weight});
35         edges[y].push_back(Edge{x, weight});
36     }
37     int prim(int v) {
38         int total_weight = 0;
39         dist[v] = 0;
40         for (int i = 0; i < n; ++i) {
41             int min_dist = INF, min_vertex;
42             for (int j = 0; j < n; ++j) {
43                 if (!visited[j] && dist[j] < min_dist) {
44                     min_dist = dist[j];
45                     min_vertex = j;
46                 }
47             }
48             total_weight += min_dist;
49             visited[min_vertex] = 1;
50             for (Edge& j : edges[min_vertex]) {
51                 if (!visited[j.vertex] && j.weight < dist[j.vertex]) {
52                     dist[j.vertex] = j.weight;
53                 }
54             }
55         }
56         return total_weight;
57     }
58 };
59 
60 
61 int main() {
62     int n, m;
63     cin >> n >> m;
64     Graph g(n);
65     for (int i = 0; i < m; i++) {
66         int a, b, c;
67         cin >> a >> b >> c;
68         g.insert(a, b, c);
69     }
70     cout << g.prim(0) << endl;
71     return 0;
72 }
Prim.cpp

Dijkstra:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <vector>
 4 #include <queue>
 5 using namespace std;
 6 
 7 const int INF = 0x3f3f3f3f;
 8 
 9 struct Edge {
10     int vertex, weight;
11 };
12 
13 class Graph {
14 private:
15     int n;
16     vector<Edge> * edges;
17     bool * visited;
18 public:
19     int * dist;
20     Graph (int input_n) {
21         n = input_n;
22         edges = new vector<Edge>[n];
23         dist = new int[n];
24         visited = new bool[n];
25         memset(visited, 0, n);
26         memset(dist, 0x3f, n * sizeof(int));
27     }
28     ~Graph() {
29         delete[] dist;
30         delete[] edges;
31         delete[] visited;
32     }
33     void insert(int x, int y, int weight) {
34         edges[x].push_back(Edge{y, weight});
35         edges[y].push_back(Edge{x, weight});
36     }
37     void dijkstra(int v) {
38         dist[v] = 0;
39         for (int i = 0; i < n; ++i) {
40             int min_dist = INF, min_vertex;
41             for (int j = 0; j < n; ++j) {
42                 if (!visited[j] && dist[j] < min_dist) {
43                     min_dist = dist[j];
44                     min_vertex = j;
45                 }
46             }
47             visited[min_vertex] = 1;
48             for (Edge& j : edges[min_vertex]) {
49                 if (min_dist + j.weight < dist[j.vertex]) {
50                     dist[j.vertex] = min_dist + j.weight;
51                 }
52             }
53         }
54     }
55 };
56 
57 int main() {
58     int n, m;
59     cin >> n >> m;
60     Graph g(n);
61     for (int i = 0; i < m; i++) {
62         int a, b, c;
63         cin >> a >> b >> c;
64         g.insert(a, b, c);
65     }
66     g.dijkstra(0);
67     for (int i = 0; i < n; i++) {
68         cout << i << ": " << g.dist[i] << endl;
69     }
70     return 0;
71 }
Dijkstra.cpp

 

posted @ 2016-05-10 20:34  clairvoyant  阅读(167)  评论(0编辑  收藏  举报