diff options
| author | pjungeblut <paul.jungeblut@gmail.com> | 2014-11-02 16:57:06 +0100 |
|---|---|---|
| committer | pjungeblut <paul.jungeblut@gmail.com> | 2014-11-02 16:57:06 +0100 |
| commit | ac16d3eb6c2d9058495a2f88a747e7d24ce3a095 (patch) | |
| tree | 3ca20f8f2674bad600eca9fa060a2781d2eb9b4a /datastructures | |
| parent | 07a1c4f87dcccbfe2ca4fbbc100a07c9be801502 (diff) | |
union find und Segementbaum
Diffstat (limited to 'datastructures')
| -rw-r--r-- | datastructures/datastructures.tex | 7 | ||||
| -rw-r--r-- | datastructures/segmentTree.cpp | 32 | ||||
| -rw-r--r-- | datastructures/unionFind.cpp | 19 |
3 files changed, 58 insertions, 0 deletions
diff --git a/datastructures/datastructures.tex b/datastructures/datastructures.tex new file mode 100644 index 0000000..f7b1d36 --- /dev/null +++ b/datastructures/datastructures.tex @@ -0,0 +1,7 @@ +\section{Datenstrukturen} + +\subsection{Union-Find} +\lstinputlisting{datastructures/unionFind.cpp} + +\subsection{Segmentbaum)} +\lstinputlisting{datastructures/segmentTree.cpp}
\ No newline at end of file diff --git a/datastructures/segmentTree.cpp b/datastructures/segmentTree.cpp new file mode 100644 index 0000000..6b73ec0 --- /dev/null +++ b/datastructures/segmentTree.cpp @@ -0,0 +1,32 @@ +int a[MAX_N], m[4 * MAX_N]; + +int query(int x, int y, int k = 0, int X = 0, int Y = MAX_N - 1) { + if (x <= X && Y <= y) return m[k]; + if (y < X || Y < x) return -1000000000; //ein "neutrales" Element + int M = (X + Y) / 2; + return max(query(x, y, 2 * k + 1, X, M), query(x, y, 2 * k + 2, M + 1, Y)); +} + +void update(int i, int v, int k = 0, int X = 0, int Y = MAX_N - 1) { + if (i < X || Y < i) return; + if (X == Y) { + m[k] = w; + a[i] = w; + return; + } + int M = (X + Y) / 2; + update(i, v, 2 * k + 1, X, M); + update(i, v, 2 * k + 2, M + 1, Y); + m[k] = max(m[2 * k + 1], m[2 * k + 2]); +} + +void init(int k = 0, int X = 0, int Y = MAX_N - 1) { + if (X == Y) { + m[k] = a[X]; + return; + } + int M = (X + Y) / 2; + init(2 * k + 1, X, M); + init(2 * k + 2, M + 1, Y); + m[k] = max(m[2 * k + 1], m[2 * k + 2]); +}
\ No newline at end of file diff --git a/datastructures/unionFind.cpp b/datastructures/unionFind.cpp new file mode 100644 index 0000000..19513ab --- /dev/null +++ b/datastructures/unionFind.cpp @@ -0,0 +1,19 @@ +vector<int> parent, rank2; //mache compiler verbieten Variable mit Namen rank + +int findSet(int n) { //Pfadkompression + if (parent[n] != n) parent[n] = findSet(parent[n]); + return parent[n]; +} + +void linkSets(int a, int b) { //union by rank + if (rank2[a] < rank2[b]) parent[a] = b; + else if (rank2[b] < rank2[a]) parent[b] = a; + else { + parent[a] = b; + rank2[b]++; + } +} + +void unionSets(int a, int b) { + if (findSet(a) != findSet(b)) linkSets(findSet(a), findSet(b)); +}
\ No newline at end of file |
