├── AlgorithmsAndStructures
├── GraphAlgorithms
│ ├── SpanTree.cs
│ ├── CheckOriented.cs
│ ├── CheckParallelEdges.cs
│ ├── VertexDegree.cs
│ ├── Distances.cs
│ ├── EdgeListsToMatrix.cs
│ ├── Components.cs
│ ├── MstPoints.cs
│ ├── Game.cs
│ ├── Mst.cs
│ ├── BipartiteGraph.cs
│ ├── TopSort.cs
│ ├── HamiltonianPath.cs
│ ├── Condensation.cs
│ ├── Cycle.cs
│ ├── Labyrinth.cs
│ └── TwoChinese.cs
├── SimpleTasks
│ ├── AplusB.cs
│ ├── AplusBB.cs
│ ├── Turtle.cs
│ ├── SimpleSort.cs
│ └── SorlLand.cs
├── AlgorithmsAndStructures.csproj
├── SortingAlgorithms
│ ├── AntiQuickSort.cs
│ ├── RadixSort.cs
│ ├── MergeSort.cs
│ ├── InversionsCount.cs
│ ├── HeapSort.cs
│ ├── SortForRunners.cs
│ └── KStaticstic.cs
├── DataStructures
│ ├── IsHeap.cs
│ ├── Stack.cs
│ ├── Queue.cs
│ ├── PostfixNotation.cs
│ ├── CorrectBracketSequence.cs
│ └── PriorityQueue.cs
├── BST
│ ├── BstHeight.cs
│ ├── IsBst.cs
│ └── Bst.cs
├── BinarySearch
│ ├── Garland.cs
│ └── BinarySearch.cs
├── HashTables
│ ├── MySet.cs
│ ├── MyMap.cs
│ ├── MyLinkedMap.cs
│ └── MyMultiMap.cs
└── Quack
│ └── QuackInterpreter.cs
├── AlgorithmsAndStructures.cpp
├── PrefixFunction.cpp
├── Floyd.cpp
├── Garland.cpp
├── SubStringSearch.cpp
├── KmpMachine.cpp
├── Dijkstra.cpp
├── DijkstraMatrix.cpp
├── AlgorithmsAndStructures.cpp.vcxproj.filters
├── NegativeCycle.cpp
├── Ford.cpp
├── TwoChinese.cpp
└── AlgorithmsAndStructures.cpp.vcxproj
├── .gitattributes
├── AlgorithmsAndStrutures.sln
├── .gitignore
└── README.md
/AlgorithmsAndStructures/GraphAlgorithms/SpanTree.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace AlgorithmsAndStructures.GraphAlgorithms
6 | {
7 | class SpanTree
8 | {
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SimpleTasks/AplusB.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.SimpleTasks
5 | {
6 | class AplusB
7 | {
8 | public static void Solve()
9 | {
10 | int a, b;
11 | string[] input = File.ReadAllText("aplusb.in").Split();
12 | a = Int32.Parse(input[0]);
13 | b = Int32.Parse(input[1]);
14 | File.WriteAllText("aplusb.out", Convert.ToString(a + b));
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SimpleTasks/AplusBB.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.SimpleTasks
5 | {
6 | class AplusBB
7 | {
8 | public static void Solve()
9 | {
10 | long a, b;
11 | string[] input = File.ReadAllText("aplusbb.in").Split();
12 | a = Int64.Parse(input[0]);
13 | b = Int64.Parse(input[1]);
14 | long result = a + b * b;
15 | File.WriteAllText("aplusbb.out", Convert.ToString(result));
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/AlgorithmsAndStructures.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.1
6 |
7 |
8 |
9 |
10 | Never
11 |
12 |
13 |
14 |
15 |
16 | Always
17 |
18 |
19 | Always
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SortingAlgorithms/AntiQuickSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Linq;
4 |
5 | namespace AlgorithmsAndStructures.SortingAlgorithms
6 | {
7 | class AntiQuickSort
8 | {
9 | private static void Swap(ref Template firstElement, ref Template secondElement)
10 | {
11 | Template swapHelper = firstElement;
12 | firstElement = secondElement;
13 | secondElement = swapHelper;
14 | }
15 |
16 | public static void Solve()
17 | {
18 | int n = int.Parse(Console.ReadLine());
19 |
20 | int[] antiArray = Enumerable.Range(1, n).ToArray();
21 |
22 | for (int i = 2; i < n; i++)
23 | {
24 | Swap(ref antiArray[i], ref antiArray[i / 2]);
25 | }
26 |
27 | Console.WriteLine(String.Join(" ", antiArray));
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/PrefixFunction.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | using namespace std;
6 |
7 | void prefixFunc(string str, vector& prefix)
8 | {
9 | prefix = vector(str.size());
10 |
11 | for (int i = 1; i < str.size(); ++i)
12 | {
13 | int currentPrefix = prefix[i - 1];
14 |
15 | while(currentPrefix > 0 && str[i] != str[currentPrefix])
16 | currentPrefix = prefix[currentPrefix - 1];
17 |
18 | if(str[i] == str[currentPrefix])
19 | currentPrefix++;
20 |
21 | prefix[i] = currentPrefix;
22 | }
23 | }
24 |
25 | int solve()
26 | {
27 | ifstream fin("prefix.in");
28 | ofstream fout("prefix.out");
29 |
30 | string str;
31 | fin >> str;
32 | vector prefix;
33 | prefixFunc(str, prefix);
34 |
35 | for (int pi: prefix)
36 | {
37 | fout << pi << " ";
38 | }
39 | fout << endl;
40 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/Floyd.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | using namespace std;
8 |
9 | typedef long long int64;
10 | const int64 inf = 1e12 + 7;
11 |
12 |
13 |
14 | int solve()
15 | {
16 | ifstream fin("pathsg.in");
17 | ofstream fout("pathsg.out");
18 | int n, m;
19 | fin >> n >> m;
20 |
21 | int from, to;
22 | int64 weight;
23 | vector> matrix(n, vector(n, inf));
24 | for (int i = 0; i < n; ++i)
25 | matrix[i][i] = 0;
26 |
27 | for (int i = 0; i < m; ++i)
28 | {
29 | fin >> from >> to >> weight;
30 | from--;
31 | to--;
32 | matrix[from][to] = weight;
33 | }
34 |
35 | for (int k = 0; k < n; ++k)
36 | for (int i = 0; i < n; ++i)
37 | for (int j = 0; j < n; ++j)
38 | matrix[i][j] = min(matrix[i][j], matrix[i][k] + matrix[k][j]);
39 |
40 | for (auto line : matrix)
41 | {
42 | for (auto dist : line)
43 | {
44 | fout << dist << ' ';
45 | }
46 | fout << '\n';
47 | }
48 |
49 | fout << '\n';
50 |
51 | return 0;
52 | }
53 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/DataStructures/IsHeap.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 |
6 | namespace AlgorithmsAndStructures.DataStructures
7 | {
8 | class IsHeap
9 | {
10 | public static void Solve()
11 | {
12 | int n;
13 | Int64[] array;
14 | using (var inputFile = new StreamReader("isheap.in"))
15 | {
16 | n = int.Parse(inputFile.ReadLine());
17 | array = inputFile.ReadLine()?.Trim().Split(' ').Select(Int64.Parse).ToArray();
18 | }
19 | bool isHeap = true;
20 |
21 | for (int i = 0; i < n / 2; ++i)
22 | {
23 | if (2 * i + 1 < n && array[2 * i + 1] < array[i])
24 | isHeap = false;
25 |
26 | if (2 * i + 2 < n && array[2 * i + 2] < array[i])
27 | isHeap = false;
28 | }
29 | using (var outputFile = new StreamWriter("isheap.out"))
30 | {
31 | outputFile.WriteLine(isHeap ? "YES" : "NO");
32 | }
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SimpleTasks/Turtle.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.SimpleTasks
5 | {
6 | class Turtle
7 | {
8 | public static void Solve(string[] args)
9 | {
10 | int h, w;
11 | string[] input = File.ReadAllLines("turtle.in");
12 | h = Int32.Parse(input[0].Split()[0]);
13 | w = Int32.Parse(input[0].Split()[1]);
14 | int[,] cost = new int[h + 2, w + 2];
15 | string[] line;
16 | for (int i = 1; i <= h; ++i)
17 | {
18 | line = input[i].Split();
19 | for (int j = 1; j <= w; ++j)
20 | {
21 | cost[i, j] = Int32.Parse(line[j - 1]);
22 | }
23 | }
24 | int[,] dp = new int[h + 2, w + 2];
25 | for (int i = h; i > 0; --i)
26 | {
27 | for (int j = 1; j <= w; ++j)
28 | {
29 | dp[i, j] = Math.Max(dp[i, j - 1], dp[i + 1, j]) + cost[i, j];
30 | }
31 | }
32 |
33 | string result = Convert.ToString(dp[1, w]);
34 | File.WriteAllText("turtle.out", result);
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/Garland.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | using namespace std;
6 |
7 | double answer;
8 | int bulbsCount;
9 | vector bulbsHeight;
10 |
11 | bool checkValid(double secondBulbHeight)
12 | {
13 | bulbsHeight[1] = secondBulbHeight;
14 | for (int i = 2; i < bulbsCount; ++i)
15 | {
16 | bulbsHeight[i] = 2.0 * bulbsHeight[i - 1] + 2.0 - bulbsHeight[i - 2];
17 | if (bulbsHeight[i] < 0)
18 | {
19 | return false;
20 | }
21 | }
22 | answer = bulbsHeight[bulbsCount - 1];
23 | return true;
24 | }
25 |
26 | void binSearch(double left, double right)
27 | {
28 | while (right - left > 0.000005)
29 | {
30 | double mid = (right + left) / 2.0;
31 | if (checkValid(mid))
32 | {
33 | right = mid;
34 | }
35 | else
36 | {
37 | left = mid;
38 | }
39 | }
40 | }
41 |
42 | int solve()
43 | {
44 | ifstream fin("garland.in");
45 | ofstream fout("garland.out");
46 |
47 | fin >> bulbsCount;
48 | bulbsHeight.resize(bulbsCount);
49 |
50 | double firstBulbHeight;
51 | fin >> firstBulbHeight;
52 | bulbsHeight[0] = firstBulbHeight;
53 |
54 | binSearch(0.0, firstBulbHeight);
55 | fout << fixed;
56 | fout.precision(2);
57 | fout << answer << '\n';
58 | cerr << answer << '\n';
59 | return 0;
60 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SimpleTasks/SimpleSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.SimpleTasks
5 | {
6 | class SimpleSort
7 | {
8 | public static void Solve()
9 | {
10 | string[] input = File.ReadAllLines("smallsort.in");
11 | int n = Int32.Parse(input[0]);
12 | string[] stringArray = input[1].Split();
13 | int[] array = new int[n];
14 |
15 | for (int i = 0; i < n; ++i)
16 | {
17 | array[i] = Int32.Parse(stringArray[i]);
18 | }
19 |
20 | int temp;
21 | for (int t = 0; t < n; ++t)
22 | {
23 | for (int i = 0; i < n - 1; ++i)
24 | {
25 | if (array[i] > array[i + 1])
26 | {
27 | temp = array[i];
28 | array[i] = array[i + 1];
29 | array[i + 1] = temp;
30 | }
31 | }
32 | }
33 | string result = "";
34 | for (int i = 0; i < n; ++i)
35 | {
36 | result += Convert.ToString(array[i]) + " ";
37 | }
38 | File.WriteAllText("smallsort.out", result);
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/SubStringSearch.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | using namespace std;
6 |
7 | void prefixFunc(string str, vector& prefix)
8 | {
9 | prefix = vector(str.size());
10 |
11 | for (int i = 1; i < str.size(); ++i)
12 | {
13 | int currentPrefix = prefix[i - 1];
14 |
15 | while(currentPrefix > 0 && str[i] != str[currentPrefix])
16 | currentPrefix = prefix[currentPrefix - 1];
17 |
18 | if(str[i] == str[currentPrefix])
19 | currentPrefix++;
20 |
21 | prefix[i] = currentPrefix;
22 | }
23 | }
24 |
25 | int solve()
26 | {
27 | ifstream fin("search2.in");
28 | ofstream fout("search2.out");
29 |
30 | string searchString;
31 | string str;
32 | fin >> searchString;
33 | fin >> str;
34 | vector prefix;
35 | prefixFunc(searchString + "$" + str, prefix);
36 | vector result;
37 | for (int i = searchString.size() + 1; i < prefix.size(); ++i)
38 | {
39 | if (prefix[i] == searchString.size())
40 | {
41 | result.push_back(i - 2 * searchString.size() + 1);
42 | }
43 | }
44 | fout << result.size() << endl;
45 | for (int position: result)
46 | {
47 | fout << position << " ";
48 | }
49 | fout << endl;
50 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/KmpMachine.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | using namespace std;
6 |
7 | void prefixFunc(string str, vector& prefix)
8 | {
9 | prefix = vector(str.size());
10 |
11 | for (int i = 1; i < str.size(); ++i)
12 | {
13 | int currentPrefix = prefix[i - 1];
14 |
15 | while(currentPrefix > 0 && str[i] != str[currentPrefix])
16 | currentPrefix = prefix[currentPrefix - 1];
17 |
18 | if(str[i] == str[currentPrefix])
19 | currentPrefix++;
20 |
21 | prefix[i] = currentPrefix;
22 | }
23 | }
24 |
25 | int main()
26 | {
27 | int n;
28 | cin >> n;
29 | string str;
30 | cin >> str;
31 | str += "$";
32 | vector prefix;
33 | prefixFunc(str, prefix);
34 | vector> akmp(str.size(), vector(n));
35 | for (int i = 0; i < str.size(); ++i)
36 | {
37 | for (char chr = 0; chr < n; ++chr)
38 | {
39 | if (i > 0 && chr + 'a' != str[i])
40 | akmp[i][chr] = akmp[prefix[i - 1]][chr];
41 | else if (chr + 'a' == str[i])
42 | akmp[i][chr] = i + 1;
43 | else
44 | akmp[i][chr] = i;
45 | }
46 | }
47 |
48 | for (auto row : akmp)
49 | {
50 | for (int a : row)
51 | {
52 | cout << a << " ";
53 | }
54 | cout << endl;
55 | }
56 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SimpleTasks/SorlLand.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Globalization;
4 |
5 | namespace AlgorithmsAndStructures.SimpleTasks
6 | {
7 | class SorlLand
8 | {
9 | public static void Solve()
10 | {
11 | string[] input = File.ReadAllLines("sortland.in");
12 | int n = Int32.Parse(input[0]);
13 | string[] stringArray = input[1].Split();
14 | (int, float)[] array = new (int, float)[n];
15 | var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
16 | culture.NumberFormat.NumberDecimalSeparator = ".";
17 | for (int i = 0; i < n; ++i)
18 | {
19 | array[i] = (i + 1, float.Parse(stringArray[i], culture));
20 | }
21 |
22 | (int, float) temp;
23 | for (int t = 0; t < n; ++t)
24 | {
25 | for (int i = 0; i < n - 1; ++i)
26 | {
27 | if (array[i].Item2 > array[i + 1].Item2)
28 | {
29 | temp = array[i];
30 | array[i] = array[i + 1];
31 | array[i + 1] = temp;
32 | }
33 | }
34 | }
35 | string result = "";
36 | result += Convert.ToString(array[0].Item1) + " ";
37 | result += Convert.ToString(array[n / 2].Item1) + " ";
38 | result += Convert.ToString(array[n - 1].Item1);
39 | File.WriteAllText("sortland.out", result);
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/Dijkstra.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | using namespace std;
7 |
8 | typedef long long int64;
9 | const int64 inf = 1e12 + 7;
10 |
11 | struct Edge
12 | {
13 | int to;
14 | int64 weight;
15 | Edge(int to, int64 weight) : to(to), weight(weight) {}
16 | Edge() {}
17 | };
18 |
19 | typedef vector> edgesLists;
20 |
21 |
22 | vector Dijkstra(int s, const edgesLists& graph)
23 | {
24 | int n = graph.size();
25 | vector distances(n, inf);
26 | set> dijkstraQueue;
27 |
28 | distances[s] = 0;
29 | dijkstraQueue.insert({ 0, s });
30 |
31 | while (!dijkstraQueue.empty())
32 | {
33 | pair cur = *dijkstraQueue.begin();
34 | dijkstraQueue.erase(dijkstraQueue.begin());
35 |
36 | for (auto edge : graph[cur.second])
37 | if (distances[edge.to] > cur.first + edge.weight)
38 | {
39 | dijkstraQueue.erase({ distances[edge.to], edge.to });
40 | dijkstraQueue.insert({ cur.first + edge.weight, edge.to });
41 | distances[edge.to] = cur.first + edge.weight;
42 | }
43 | }
44 | return distances;
45 | }
46 |
47 | int solve()
48 | {
49 | ifstream fin("pathbgep.in");
50 | ofstream fout("pathbgep.out");
51 | int n, m;
52 | fin >> n >> m;
53 |
54 | edgesLists graph(n);
55 | int from, to;
56 | int64 weight;
57 | for (int i = 0; i < m; ++i)
58 | {
59 | fin >> from >> to >> weight;
60 | from--;
61 | to--;
62 | graph[from].emplace_back(to, weight);
63 | graph[to].emplace_back(from, weight);
64 | }
65 | for (auto dist : Dijkstra(0, graph))
66 | {
67 | fout << dist << ' ';
68 | }
69 | fout << '\n';
70 |
71 | return 0;
72 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/DijkstraMatrix.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | using namespace std;
7 |
8 | typedef long long int64;
9 | const int64 inf = 1e12 + 7;
10 |
11 | struct Edge
12 | {
13 | int to;
14 | int64 weight;
15 | Edge(int to, int64 weight) : to(to), weight(weight) {}
16 | Edge() {}
17 | };
18 |
19 | typedef vector> edgesLists;
20 |
21 |
22 | int64 Dijkstra(int s, int f, const edgesLists& graph)
23 | {
24 | int n = graph.size();
25 | vector distances(n, inf);
26 | set> dijkstraQueue;
27 |
28 | distances[s] = 0;
29 | dijkstraQueue.insert({ 0, s });
30 |
31 | while (!dijkstraQueue.empty())
32 | {
33 | pair cur = *dijkstraQueue.begin();
34 | dijkstraQueue.erase(dijkstraQueue.begin());
35 |
36 | for (auto edge : graph[cur.second])
37 | if (distances[edge.to] > cur.first + edge.weight)
38 | {
39 | dijkstraQueue.erase({ distances[edge.to], edge.to });
40 | dijkstraQueue.insert({ cur.first + edge.weight, edge.to });
41 | distances[edge.to] = cur.first + edge.weight;
42 | }
43 | }
44 | return distances[f] == inf ? -1 : distances[f];
45 | }
46 |
47 | int solve()
48 | {
49 | ifstream fin("pathmgep.in");
50 | ofstream fout("pathmgep.out");
51 | int n, s, f;
52 | fin >> n >> s >> f;
53 | s--;
54 | f--;
55 |
56 | edgesLists graph(n);
57 | int64 weight;
58 | for (int from = 0; from < n; ++from)
59 | {
60 | for (int to = 0; to < n; ++to)
61 | {
62 | fin >> weight;
63 | if (weight != -1 && to != from)
64 | graph[from].emplace_back(to, weight);
65 | }
66 | }
67 | fout << Dijkstra(s, f, graph) << "\n";
68 |
69 |
70 | return 0;
71 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/BST/BstHeight.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 |
5 | namespace AlgorithmsAndStructures.BST
6 | {
7 | class BstHeight
8 | {
9 | private static int CountHeight((int, int)[] tree)
10 | {
11 | int maxHeight = 0;
12 | Stack<(int, int)> stack = new Stack<(int, int)>();
13 | stack.Push((1, 0));
14 | while (stack.Count > 0)
15 | {
16 | var (i, height) = stack.Pop();
17 | var (left, right) = tree[i];
18 | maxHeight = Math.Max(maxHeight, height + 1);
19 | if (left != 0)
20 | stack.Push((left, height + 1));
21 | if (right != 0)
22 | stack.Push((right, height + 1));
23 | }
24 |
25 | return maxHeight;
26 | }
27 |
28 | public static void Solve()
29 | {
30 | int n;
31 | (int, int)[] tree;
32 | using (var input = new StreamReader("height.in"))
33 | {
34 | n = int.Parse(input.ReadLine());
35 | tree = new (int, int)[n + 1];
36 | for (int i = 1; i <= n; ++i)
37 | {
38 | string[] line = input.ReadLine().Trim().Split();
39 | tree[i] = (int.Parse(line[1]), int.Parse(line[2]));
40 | // Console.WriteLine($"{tree[i].Item1}, {tree[i].Item2}");
41 | }
42 | }
43 |
44 | int height = 0;
45 | if (n > 0)
46 | height = CountHeight(tree);
47 | using (var output = new StreamWriter("height.out"))
48 | {
49 | output.WriteLine(height);
50 | // Console.WriteLine(height);
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/CheckOriented.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.GraphAlgorithms
7 | {
8 | class CheckOriented
9 | {
10 | private static bool IsOriented(int[,] matrix)
11 | {
12 | int n = (int)(Math.Sqrt(matrix.Length));
13 | for (int i = 0; i < n; i++)
14 | {
15 | for (int j = 0; j < n; j++)
16 | {
17 | if (matrix[i, j] + matrix[j, i] == 1)
18 | return false;
19 | if (i == j && matrix[i, j] == 1)
20 | return false;
21 | }
22 | }
23 |
24 | return true;
25 | }
26 |
27 | private static int[,] ReadMatrix(StreamReader input, int n)
28 | {
29 | int[,] matrix = new int[n, n];
30 | for (int i = 0; i < n; i++)
31 | {
32 | string[] stringElements = input.ReadLine().Split();
33 |
34 | for (int j = 0; j < n; j++)
35 | {
36 | matrix[i, j] = int.Parse(stringElements[j]);
37 | }
38 | }
39 |
40 | return matrix;
41 | }
42 |
43 | public static void Solve()
44 | {
45 | int n;
46 | int[,] matrix;
47 |
48 | using (var input = new StreamReader("input.txt"))
49 | {
50 | n = int.Parse(input.ReadLine());
51 | matrix = ReadMatrix(input, n);
52 | }
53 |
54 | bool result = IsOriented(matrix);
55 |
56 | using (var output = new StreamWriter("output.txt"))
57 | {
58 | output.WriteLine(result ? "YES" : "NO");
59 | }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/DataStructures/Stack.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.DataStructures
5 | {
6 | class Stack
7 | {
8 | private Int64[] data;
9 | private int size;
10 |
11 | public Stack()
12 | {
13 | data = new Int64[1000000];
14 | size = 0;
15 | }
16 |
17 | public int Size()
18 | {
19 | return size;
20 | }
21 |
22 | public void Push(Int64 element)
23 | {
24 | data[size++] = element;
25 | }
26 |
27 | public Int64 Top()
28 | {
29 | return data[size - 1];
30 | }
31 |
32 | public Int64 Pop()
33 | {
34 | return data[--size];
35 | }
36 | }
37 |
38 | class SolutionStack
39 | {
40 | public static void Solve()
41 | {
42 | int commandCount;
43 | using (var inputFile = new StreamReader("stack.in"))
44 | {
45 | commandCount = Int32.Parse(inputFile.ReadLine());
46 |
47 | Stack stack = new Stack();
48 | using (var outputFile = new StreamWriter("stack.out"))
49 | {
50 | for (int i = 0; i < commandCount; ++i)
51 | {
52 | string[] commands = inputFile.ReadLine().Split();
53 | if (commands[0] == "+")
54 | {
55 | Int64 newElement = Int64.Parse(commands[1]);
56 | stack.Push(newElement);
57 | }
58 | else
59 | {
60 | outputFile.WriteLine(stack.Pop());
61 | }
62 | }
63 | }
64 | }
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/BinarySearch/Garland.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.BinarySearch
7 | {
8 | class Garland
9 | {
10 | private static double answer;
11 |
12 | private static void BinSearch(double[] bulbsHeight, double left, double right, int bulbsCount)
13 | {
14 | while (right - left > 0.000005)
15 | {
16 | double mid = (right + left) / 2.0;
17 | if (CheckValid(bulbsHeight, mid, bulbsCount))
18 | {
19 | right = mid;
20 | }
21 | else
22 | {
23 | left = mid;
24 | }
25 | }
26 | }
27 |
28 | private static bool CheckValid(double[] bulbsHeight, double secondBulbHeight, int bulbsCount)
29 | {
30 | bulbsHeight[1] = secondBulbHeight;
31 |
32 | for (int i = 2; i < bulbsCount; ++i)
33 | {
34 | bulbsHeight[i] = 2.0 * bulbsHeight[i - 1] + 2.0 - bulbsHeight[i - 2];
35 | if (bulbsHeight[i] < 0)
36 | {
37 | return false;
38 | }
39 | }
40 |
41 | answer = bulbsHeight[bulbsCount - 1];
42 | return true;
43 | }
44 |
45 | public static void Solve()
46 | {
47 | string[] input;
48 | input = Console.ReadLine()?.Split();
49 |
50 | int bulbsCount = int.Parse(input[0]);
51 | double firstBulbHeight = double.Parse(input[1].Replace(".", ","));
52 | double[] bulbsHeight = new double[bulbsCount];
53 | bulbsHeight[0] = firstBulbHeight;
54 |
55 | BinSearch(bulbsHeight, 0.00, firstBulbHeight, bulbsCount);
56 | Console.WriteLine($"{(int)(answer)}.{(int)(answer * 100 % 100)}");
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/CheckParallelEdges.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.GraphAlgorithms
7 | {
8 | class CheckParallelEdges
9 | {
10 | private static bool IsHaveParallelEdges(int[,] matrix)
11 | {
12 | int n = (int)(Math.Sqrt(matrix.Length));
13 | for (int i = 0; i < n; i++)
14 | {
15 | for (int j = 0; j < n; j++)
16 | {
17 | if (matrix[i, j] > 1)
18 | return true;
19 | }
20 | }
21 |
22 | return false;
23 | }
24 |
25 | private static (int, int) ReadTwoNumbers(StreamReader input)
26 | {
27 | int a, b;
28 | string inputLine = input.ReadLine();
29 | string[] inputStrings = inputLine.Split();
30 | a = int.Parse(inputStrings[0]);
31 | b = int.Parse(inputStrings[1]);
32 |
33 | return (a, b);
34 | }
35 |
36 | public static void Solve()
37 | {
38 | int n, m;
39 | int[,] matrix;
40 | using (var input = new StreamReader("input.txt"))
41 | {
42 | (n, m) = ReadTwoNumbers(input);
43 | matrix = new int[n, n];
44 |
45 | int v, u;
46 | for (int i = 0; i < m; i++)
47 | {
48 | (v, u) = ReadTwoNumbers(input);
49 | v--;
50 | u--;
51 | matrix[v, u]++;
52 | matrix[u, v]++;
53 | }
54 | }
55 |
56 | bool result = IsHaveParallelEdges(matrix);
57 |
58 | using (var output = new StreamWriter("output.txt"))
59 | {
60 | output.WriteLine(result ? "YES" : "NO");
61 | }
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/BinarySearch/BinarySearch.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.BinarySearch
7 | {
8 | class BinarySearch
9 | {
10 | private static int BinSearch(int[] array, int searchValue, bool leftSearch)
11 | {
12 | const int notFound = -1;
13 |
14 | if (array[0] > searchValue || array[array.Length - 1] < searchValue)
15 | {
16 | return notFound;
17 | }
18 |
19 | int leftPointer = -1;
20 | int rightPointer = array.Length;
21 |
22 | while (rightPointer - leftPointer > 1)
23 | {
24 | int midPointer = (rightPointer + leftPointer) / 2;
25 | if (leftSearch ? array[midPointer] < searchValue : array[midPointer] <= searchValue)
26 | {
27 | leftPointer = midPointer;
28 | }
29 | else
30 | {
31 | rightPointer = midPointer;
32 | }
33 | }
34 |
35 | if (leftSearch ? array[rightPointer] == searchValue : array[rightPointer - 1] == searchValue)
36 | {
37 | return leftSearch ? rightPointer + 1 : rightPointer;
38 | }
39 |
40 | return notFound;
41 | }
42 |
43 | public static void Solve()
44 | {
45 | var n = int.Parse(Console.ReadLine() ?? "");
46 | var array = Console.ReadLine()?.Split(' ').Select(int.Parse).ToArray();
47 |
48 | var m = int.Parse(Console.ReadLine() ?? "");
49 | var requests = Console.ReadLine()?.Split(' ').Select(int.Parse).ToArray();
50 |
51 | for (int i = 0; i < m; ++i)
52 | {
53 | Console.WriteLine($"{BinSearch(array, requests[i], true)} {BinSearch(array, requests[i], false)}");
54 | }
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/AlgorithmsAndStructures.cpp.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
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 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/NegativeCycle.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | using namespace std;
8 |
9 | typedef long long int64;
10 | const int64 inf = 1e12 + 7;
11 |
12 | struct Edge
13 | {
14 | int from;
15 | int to;
16 | int64 weight;
17 | Edge(int from, int to, int64 weight) : from(from), to(to), weight(weight) {}
18 | Edge() {}
19 | };
20 |
21 | vector FindNegativeCycle(int n, const vector& edges)
22 | {
23 | vector dist(n);
24 | vector parents(n, -1);
25 | int lastChanged;
26 | for (int i = 0; i < n; ++i)
27 | {
28 | lastChanged = -1;
29 | for (auto edge : edges)
30 | {
31 | if (dist[edge.to] > dist[edge.from] + edge.weight)
32 | {
33 | dist[edge.to] = max(-inf, dist[edge.from] + edge.weight);
34 | parents[edge.to] = edge.from;
35 | lastChanged = edge.to;
36 | }
37 | }
38 | }
39 | if (lastChanged == -1)
40 | {
41 | return vector(0);
42 | }
43 | else
44 | {
45 | int v = lastChanged;
46 | for (int i = 0; i < n; ++i)
47 | v = parents[v];
48 |
49 | vector path;
50 | int u = v;
51 | do
52 | {
53 | path.push_back(u);
54 | u = parents[u];
55 | } while (u != v);
56 | path.push_back(u);
57 | reverse(path.begin(), path.end());
58 | return path;
59 | }
60 | }
61 |
62 |
63 | int solve()
64 | {
65 | ifstream fin("negcycle.in");
66 | ofstream fout("negcycle.out");
67 | int n;
68 | fin >> n;
69 |
70 | int64 weight;
71 | vector edges;
72 |
73 | for (int from = 0; from < n; ++from)
74 | {
75 | for (int to = 0; to < n; ++to)
76 | {
77 | fin >> weight;
78 | if (weight != 1e9)
79 | edges.emplace_back(from, to, weight);
80 | }
81 | }
82 |
83 | vector result = FindNegativeCycle(n, edges);
84 |
85 | if (result.empty())
86 | {
87 | fout << "NO\n";
88 | }
89 | else
90 | {
91 | fout << "YES\n";
92 | fout << result.size() << "\n";
93 | for (auto v : result)
94 | {
95 | fout << v + 1 << " ";
96 | }
97 | fout << "\n";
98 | }
99 |
100 | fout << '\n';
101 |
102 | return 0;
103 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/VertexDegree.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace AlgorithmsAndStructures.GraphAlgorithms
8 | {
9 | class VertexDegree
10 | {
11 | private static int[] GetVertexDegrees(int vertexCount, IEnumerable<(int, int)> edgesList)
12 | {
13 | int[] vertexDegrees = new int[vertexCount];
14 | foreach (var edge in edgesList)
15 | {
16 | vertexDegrees[edge.Item1]++;
17 | vertexDegrees[edge.Item2]++;
18 | }
19 | return vertexDegrees;
20 | }
21 |
22 | private static (int, int) ReadTwoNumbers(StreamReader input)
23 | {
24 | int a, b;
25 | string inputLine = input.ReadLine();
26 | string[] inputStrings = inputLine.Split();
27 | a = int.Parse(inputStrings[0]);
28 | b = int.Parse(inputStrings[1]);
29 |
30 | return (a, b);
31 | }
32 |
33 | private static (int, int) ReadTwoNumbers()
34 | {
35 | int a, b;
36 | string inputLine = Console.ReadLine();
37 | string[] inputStrings = inputLine.Split();
38 | a = int.Parse(inputStrings[0]);
39 | b = int.Parse(inputStrings[1]);
40 |
41 | return (a, b);
42 | }
43 |
44 | public static void Solve()
45 | {
46 | int n, m;
47 | List<(int, int)> edgesList = new List<(int, int)>();
48 | using (var input = new StreamReader("input.txt"))
49 | {
50 | (n, m) = ReadTwoNumbers(input);
51 | int v, u;
52 | for (int i = 0; i < m; i++)
53 | {
54 | (v, u) = ReadTwoNumbers(input);
55 | edgesList.Add((v - 1, u - 1));
56 | }
57 | }
58 |
59 | int[] vertexDegrees = GetVertexDegrees(n, edgesList);
60 |
61 | using (var output = new StreamWriter("output.txt"))
62 | {
63 | output.WriteLine(string.Join(" ", vertexDegrees.Select(d => d.ToString()).ToArray()));
64 | }
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SortingAlgorithms/RadixSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace AlgorithmsAndStructures.SortingAlgorithms
6 | {
7 | class RadixSort
8 | {
9 | private static string[] Sort(string[] arrayToSort, int digitsCount, int phasesCount)
10 | {
11 | string[] array = new string[arrayToSort.Length];
12 | arrayToSort.CopyTo(array, 0);
13 | string[] nextPhaseArray = new string[arrayToSort.Length];
14 |
15 | for (int phase = 0; phase < phasesCount; phase++)
16 | {
17 | int j = digitsCount - phase - 1;
18 | int[] digits = new int[26];
19 | int digit;
20 | for (int i = 0; i < array.Length; ++i)
21 | {
22 | digit = (int) (array[i][j] - 'a');
23 | digits[digit]++;
24 | }
25 |
26 | int preCount = 0;
27 | int temp;
28 | for (int i = 0; i < 26; ++i)
29 | {
30 | temp = digits[i];
31 | digits[i] = preCount;
32 | preCount += temp;
33 | }
34 |
35 | for (int i = 0; i < array.Length; ++i)
36 | {
37 | digit = (int) (array[i][j] - 'a');
38 | nextPhaseArray[digits[digit]] = array[i];
39 | digits[digit]++;
40 | }
41 |
42 | nextPhaseArray.CopyTo(array, 0);
43 | }
44 |
45 | return array;
46 | }
47 |
48 | public static void Solve()
49 | {
50 | int n, m, k;
51 | string[] input = Console.ReadLine().Split();
52 | n = int.Parse(input[0]);
53 | m = int.Parse(input[1]);
54 | k = int.Parse(input[2]);
55 | string[] array = new string[n];
56 | for (int i = 0; i < n; ++i)
57 | {
58 | array[i] = Console.ReadLine();
59 | }
60 |
61 | array = Sort(array, m, k);
62 | for (int i = 0; i < n; ++i)
63 | {
64 | Console.WriteLine(array[i]);
65 | }
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/DataStructures/Queue.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.DataStructures
5 | {
6 | class Queue
7 | {
8 | const int maxDataSize = 1000000;
9 | private Int64[] data;
10 | private int begin, end;
11 |
12 | public Queue()
13 | {
14 | data = new Int64[maxDataSize];
15 | begin = 0;
16 | end = 0;
17 | }
18 |
19 | public int Size()
20 | {
21 | if (begin < end)
22 | {
23 | return end - begin;
24 | }
25 | else
26 | {
27 | return maxDataSize - begin + end;
28 | }
29 | }
30 |
31 | public void Push(Int64 element)
32 | {
33 | data[end] = element;
34 | end = (end + 1) % maxDataSize;
35 | }
36 |
37 | public Int64 Front()
38 | {
39 | return data[begin];
40 | }
41 |
42 | public Int64 Pop()
43 | {
44 | Int64 deleted = data[begin];
45 | begin = (begin + 1) % maxDataSize;
46 | return deleted;
47 | }
48 | }
49 |
50 | class SolutionQueue
51 | {
52 | public static void Solve()
53 | {
54 | int commandCount;
55 | using (var inputFile = new StreamReader("queue.in"))
56 | {
57 | commandCount = Int32.Parse(inputFile.ReadLine());
58 |
59 | Queue queue = new Queue();
60 | using (var outputFile = new StreamWriter("queue.out"))
61 | {
62 | for (int i = 0; i < commandCount; ++i)
63 | {
64 | string[] commands = inputFile.ReadLine().Split();
65 | if (commands[0] == "+")
66 | {
67 | Int64 newElement = Int64.Parse(commands[1]);
68 | queue.Push(newElement);
69 | }
70 | else
71 | {
72 | outputFile.WriteLine(queue.Pop());
73 | }
74 | }
75 | }
76 | }
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/DataStructures/PostfixNotation.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.DataStructures
7 | {
8 | class PostfixNotation
9 | {
10 | class Stack
11 | {
12 | private int[] data;
13 | private int size;
14 |
15 | public Stack()
16 | {
17 | data = new int[1000000];
18 | size = 0;
19 | }
20 |
21 | public int Size()
22 | {
23 | return size;
24 | }
25 |
26 | public void Push(int element)
27 | {
28 | data[size++] = element;
29 | }
30 |
31 | public int Top()
32 | {
33 | return data[size - 1];
34 | }
35 |
36 | public int Pop()
37 | {
38 | return data[--size];
39 | }
40 | }
41 |
42 | public static void Solve()
43 | {
44 | string[] sequence = File.ReadAllText("postfix.in").Split();
45 | Stack stack = new Stack();
46 |
47 | for (int i = 0; i < sequence.Length; ++i)
48 | {
49 | string element = sequence[i];
50 | if (element == "")
51 | continue;
52 | int a, b;
53 | switch (element)
54 | {
55 | case "+":
56 | b = stack.Pop();
57 | a = stack.Pop();
58 | stack.Push(a + b);
59 | break;
60 | case "-":
61 | b = stack.Pop();
62 | a = stack.Pop();
63 | stack.Push(a - b);
64 | break;
65 | case "*":
66 | b = stack.Pop();
67 | a = stack.Pop();
68 | stack.Push(a * b);
69 | break;
70 | default:
71 | stack.Push(int.Parse(element));
72 | break;
73 | }
74 | }
75 |
76 | int result = stack.Top();
77 | File.WriteAllText("postfix.out", result.ToString());
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/Distances.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace AlgorithmsAndStructures.GraphAlgorithms
8 | {
9 | class Distances
10 | {
11 | private static int[] GetDistances(List[] edgesLists, int start)
12 | {
13 | int n = edgesLists.Length;
14 | int[] distances = new int[n];
15 |
16 | for (int i = 0; i < n; i++)
17 | {
18 | distances[i] = -1;
19 | }
20 |
21 | Queue queue = new Queue();
22 | queue.Enqueue(start);
23 | distances[start] = 0;
24 | while (queue.Count > 0)
25 | {
26 | int v = queue.Dequeue();
27 |
28 | for (int i = 0; i < edgesLists[v].Count; i++)
29 | {
30 | int u = edgesLists[v][i];
31 | if (distances[u] == -1)
32 | {
33 | queue.Enqueue(u);
34 | distances[u] = distances[v] + 1;
35 | }
36 | }
37 | }
38 |
39 | return distances;
40 | }
41 |
42 | private static (int, int) ReadTwoNumbers()
43 | {
44 | int a, b;
45 | string inputLine = Console.ReadLine();
46 | string[] inputStrings = inputLine.Split();
47 | a = int.Parse(inputStrings[0]);
48 | b = int.Parse(inputStrings[1]);
49 |
50 | return (a, b);
51 | }
52 |
53 | public static void Solve()
54 | {
55 | int n, m;
56 | (n, m) = ReadTwoNumbers();
57 | var edgesLists = new List[n];
58 | for (int i = 0; i < n; i++)
59 | {
60 | edgesLists[i] = new List();
61 | }
62 |
63 | int v, u;
64 | for (int i = 0; i < m; i++)
65 | {
66 | (v, u) = ReadTwoNumbers();
67 | v--;
68 | u--;
69 | edgesLists[v].Add(u);
70 | edgesLists[u].Add(v);
71 | }
72 |
73 |
74 | int[] distances = GetDistances(edgesLists, 0);
75 |
76 | Console.WriteLine(String.Join(" ", distances.Select(e => e.ToString())));
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/Ford.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | using namespace std;
8 |
9 | typedef long long int64;
10 | const int64 inf = 8e18;
11 |
12 | struct Edge
13 | {
14 | int from;
15 | int to;
16 | int64 weight;
17 | Edge(int from, int to, int64 weight) : from(from), to(to), weight(weight) {}
18 | Edge() {}
19 | };
20 |
21 | typedef vector> edgesLists;
22 |
23 | void Dfs(int from, const vector>& graph, vector& used)
24 | {
25 | used[from] = true;
26 | for (auto to : graph[from])
27 | {
28 | if (!used[to])
29 | Dfs(to, graph, used);
30 | }
31 | }
32 |
33 | vector Ford(int v, const vector& edges, const vector>& graph)
34 | {
35 | int n = graph.size();
36 | vector dist(n, inf);
37 | vector parents(n, -1);
38 | int lastChanged;
39 | dist[v] = 0;
40 | for (int i = 0; i < n; ++i)
41 | {
42 | lastChanged = -1;
43 | for (auto edge : edges)
44 | {
45 | if (dist[edge.from] < inf)
46 | {
47 | if (dist[edge.to] > dist[edge.from] + edge.weight)
48 | {
49 | dist[edge.to] = max(-inf, dist[edge.from] + edge.weight);
50 | parents[edge.to] = edge.from;
51 | lastChanged = edge.to;
52 | }
53 | }
54 | }
55 | }
56 |
57 | if (lastChanged != -1)
58 | {
59 | for (int i = 0; i < n; ++i)
60 | lastChanged = parents[lastChanged];
61 |
62 | vector used(n);
63 | Dfs(lastChanged, graph, used);
64 |
65 | for (int i = 0; i < n; ++i)
66 | {
67 | if (used[i])
68 | dist[i] = -inf;
69 | }
70 | }
71 |
72 | return dist;
73 | }
74 |
75 |
76 | int solve()
77 | {
78 | ifstream fin("path.in");
79 | ofstream fout("path.out");
80 | int n, m, s;
81 | fin >> n >> m >> s;
82 | s--;
83 |
84 | int64 from, to, weight;
85 | vector edges;
86 | vector> graph(n);
87 |
88 | for (int i = 0; i < m; ++i)
89 | {
90 | fin >> from >> to >> weight;
91 | edges.emplace_back(from - 1, to - 1, weight);
92 | graph[from - 1].push_back(to - 1);
93 | }
94 |
95 | for (auto dist : Ford(s, edges, graph))
96 | {
97 | switch (dist)
98 | {
99 | case inf:
100 | fout << "*";
101 | break;
102 | case -inf:
103 | fout << "-";
104 | break;
105 | default:
106 | fout << dist;
107 | }
108 | fout << "\n";
109 | }
110 |
111 | fout << '\n';
112 |
113 | return 0;
114 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SortingAlgorithms/MergeSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 |
4 | namespace AlgorithmsAndStructures.SortingAlgorithms
5 | {
6 | class Sort where Template: IComparable
7 | {
8 | private static Template[] MergeSort (Template[] needToSortArray)
9 | {
10 | if (needToSortArray.Length == 1)
11 | {
12 | return needToSortArray;
13 | }
14 | int middlePosition = needToSortArray.Length / 2;
15 | return Merge(MergeSort(needToSortArray.Take(middlePosition).ToArray()), MergeSort(needToSortArray.Skip(middlePosition).ToArray()));
16 | }
17 |
18 | private static Template[] Merge(Template[] leftArray, Template[] rightArray)
19 | {
20 | int leftIterator = 0;
21 | int rightIterator = 0;
22 | Template[] mergedArray = new Template[leftArray.Length + rightArray.Length];
23 | int mergedIterator = 0;
24 |
25 | while (leftIterator < leftArray.Length && rightIterator < rightArray.Length)
26 | {
27 | if (leftArray[leftIterator].CompareTo(rightArray[rightIterator]) <= 0)
28 | {
29 | mergedArray[mergedIterator] = leftArray[leftIterator++];
30 | }
31 | else
32 | {
33 | mergedArray[mergedIterator] = rightArray[rightIterator++];
34 | }
35 | mergedIterator++;
36 | }
37 |
38 | while (leftIterator < leftArray.Length)
39 | {
40 | mergedArray[mergedIterator++] = leftArray[leftIterator++];
41 | }
42 |
43 | while (rightIterator < rightArray.Length)
44 | {
45 | mergedArray[mergedIterator++] = rightArray[rightIterator++];
46 | }
47 |
48 | return mergedArray;
49 |
50 | }
51 | public static void Solve()
52 | {
53 | int n = Int32.Parse(Console.ReadLine());
54 | int[] array = new int[n];
55 | string[] inputArray = Console.ReadLine().Split();
56 | for (int i = 0; i < n; ++i)
57 | {
58 | array[i] = Int32.Parse(inputArray[i]);
59 | }
60 | array = Sort.MergeSort(array);
61 | Console.WriteLine(String.Join(" ", array));
62 | }
63 | }
64 | class StartMergeSort
65 | {
66 | public static void Solve()
67 | {
68 | Sort.Solve();
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/EdgeListsToMatrix.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.GraphAlgorithms
7 | {
8 | class EdgeListsToMatrix
9 | {
10 | private static bool[,] GetMatrix(List[] edgeLists)
11 | {
12 | int n = edgeLists.Length;
13 | bool[,] matrix = new bool[n, n];
14 |
15 | for (int i = 0; i < n; i++)
16 | {
17 | for (int j = 0; j < edgeLists[i].Count; j++)
18 | {
19 | matrix[i, edgeLists[i][j]] = true;
20 | }
21 | }
22 |
23 | return matrix;
24 | }
25 |
26 | private static (int, int) ReadTwoNumbers(StreamReader input)
27 | {
28 | int a, b;
29 | string inputLine = input.ReadLine();
30 | string[] inputStrings = inputLine.Split();
31 | a = int.Parse(inputStrings[0]);
32 | b = int.Parse(inputStrings[1]);
33 |
34 | return (a, b);
35 | }
36 |
37 | private static void WriteMatrix(StreamWriter output, bool[,] matrix)
38 | {
39 | int n = (int)(Math.Sqrt(matrix.Length));
40 | int e;
41 | for (int i = 0; i < n; i++)
42 | {
43 | for (int j = 0; j < n; j++)
44 | {
45 | e = matrix[i, j] ? 1 : 0;
46 | output.Write($"{e} ");
47 | }
48 | output.Write("\n");
49 | }
50 | }
51 |
52 | public static void Solve()
53 | {
54 | int n, m;
55 | List[] edgeLists;
56 | using (var input = new StreamReader("input.txt"))
57 | {
58 | (n, m) = ReadTwoNumbers(input);
59 | edgeLists = new List[n];
60 | for (int i = 0; i < n; i++)
61 | {
62 | edgeLists[i] = new List();
63 | }
64 |
65 | int v, u;
66 | for (int i = 0; i < m; i++)
67 | {
68 | (v, u) = ReadTwoNumbers(input);
69 | v--;
70 | u--;
71 | edgeLists[v].Add(u);
72 | }
73 | }
74 |
75 | bool[,] matrix = GetMatrix(edgeLists);
76 |
77 | using (var output = new StreamWriter("output.txt"))
78 | {
79 | WriteMatrix(output, matrix);
80 | }
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/HashTables/MySet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text.RegularExpressions;
6 |
7 | namespace AlgorithmsAndStructures.HashTables
8 | {
9 | class MySet
10 | {
11 | List[] hashTable = new List[1000001];
12 |
13 | private static int Hash(Int64 element)
14 | {
15 | int hashCode = Math.Abs((int)(element % 1000001));
16 | return hashCode;
17 | }
18 |
19 | public void Insert(Int64 element)
20 | {
21 | int hashCode = Hash(element);
22 | if (hashTable[hashCode] == null)
23 | hashTable[hashCode] = new List();
24 | if (!hashTable[hashCode].Contains(element))
25 | hashTable[hashCode].Add(element);
26 | }
27 |
28 | public bool Exists(Int64 element)
29 | {
30 | int hashCode = Hash(element);
31 | return hashTable[hashCode]?.Contains(element) ?? false;
32 | }
33 |
34 | public void Delete(Int64 element)
35 | {
36 | int hashCode = Hash(element);
37 | hashTable[hashCode]?.Remove(element);
38 | }
39 | }
40 |
41 | class SolutionMySet
42 | {
43 | public static void Solve()
44 | {
45 | using (var input = new StreamReader("set.in"))
46 | {
47 | using (var output = new StreamWriter("set.out"))
48 | {
49 | MySet set = new MySet();
50 | while (true)
51 | {
52 | string inp = input.ReadLine()?.Trim();
53 | if (inp == null)
54 | break;
55 | inp = Regex.Replace(inp, @"\s+", " ");
56 | string[] line = inp.Split();
57 | Int64 element = Int64.Parse(line[1]);
58 | switch (line[0])
59 | {
60 | case "insert":
61 | set.Insert(element);
62 | break;
63 | case "exists":
64 | output.WriteLine(set.Exists(element) ? "true" : "false");
65 | break;
66 | case "delete":
67 | set.Delete(element);
68 | break;
69 | }
70 | }
71 | }
72 | }
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/BST/IsBst.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.BST
5 | {
6 | class IsBst
7 | {
8 | class Node
9 | {
10 | public long Value;
11 | public int LeftChild;
12 | public int RightChild;
13 |
14 | public Node(long value, int left, int right)
15 | {
16 | Value = value;
17 | LeftChild = left;
18 | RightChild = right;
19 | }
20 | }
21 |
22 | class CheckBstParams
23 | {
24 | public long Min;
25 | public long Max;
26 | public int Index;
27 |
28 | public CheckBstParams(int index, long min, long max)
29 | {
30 | Index = index;
31 | Min = min;
32 | Max = max;
33 | }
34 | }
35 | private static bool CheckBst(Node[] tree)
36 | {
37 | if (tree.Length == 1)
38 | return true;
39 | Stack stack = new Stack();
40 | stack.Push(new CheckBstParams(1, long.MinValue, long.MaxValue));
41 | while (stack.Count > 0)
42 | {
43 | CheckBstParams x = stack.Pop();
44 | if (tree[x.Index].Value <= x.Min || tree[x.Index].Value >= x.Max)
45 | return false;
46 | if (tree[x.Index].LeftChild != 0)
47 | stack.Push(new CheckBstParams(tree[x.Index].LeftChild, x.Min, tree[x.Index].Value));
48 | if (tree[x.Index].RightChild != 0)
49 | stack.Push(new CheckBstParams(tree[x.Index].RightChild, tree[x.Index].Value, x.Max));
50 | }
51 |
52 | return true;
53 | }
54 |
55 | public static void Solve()
56 | {
57 | using (var input = new StreamReader("check.in"))
58 | {
59 | using (var output = new StreamWriter("check.out"))
60 | {
61 | int n = int.Parse(input.ReadLine());
62 | Node[] tree = new Node[n + 1];
63 | for (int i = 1; i <= n; ++i)
64 | {
65 | string[] line = input.ReadLine().Trim().Split();
66 | long value = long.Parse(line[0]);
67 | int left = int.Parse(line[1]);
68 | int right = int.Parse(line[2]);
69 | tree[i] = new Node(value, left, right);
70 | }
71 |
72 | string result = CheckBst(tree) ? "YES" : "NO";
73 | output.WriteLine(result);
74 | }
75 | }
76 | }
77 | }
78 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/Components.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace AlgorithmsAndStructures.GraphAlgorithms
8 | {
9 | class Components
10 | {
11 | private static int[] GetComponents(List[] edgesLists)
12 | {
13 | int n = edgesLists.Length;
14 | int[] components = new int[n];
15 | int color = 1;
16 | for (int i = 0; i < n; i++)
17 | {
18 | if (components[i] == 0)
19 | Bfs(edgesLists, components, i, color++);
20 | }
21 |
22 | return components;
23 | }
24 |
25 | private static void Bfs(List[] edgesLists, int[] components, int start, int color)
26 | {
27 | Queue queue = new Queue();
28 | queue.Enqueue(start);
29 | while (queue.Count > 0)
30 | {
31 | int v = queue.Dequeue();
32 | components[v] = color;
33 |
34 | for (int i = 0; i < edgesLists[v].Count; i++)
35 | {
36 | int u = edgesLists[v][i];
37 | if (components[u] == 0)
38 | queue.Enqueue(u);
39 | }
40 | }
41 | }
42 |
43 | private static (int, int) ReadTwoNumbers(StreamReader input)
44 | {
45 | int a, b;
46 | string inputLine = input.ReadLine();
47 | string[] inputStrings = inputLine.Split();
48 | a = int.Parse(inputStrings[0]);
49 | b = int.Parse(inputStrings[1]);
50 |
51 | return (a, b);
52 | }
53 |
54 | public static void Solve()
55 | {
56 | int n, m;
57 | List[] edgesLists;
58 | using (var input = new StreamReader("components.in"))
59 | {
60 | (n, m) = ReadTwoNumbers(input);
61 | edgesLists = new List[n];
62 | for (int i = 0; i < n; i++)
63 | {
64 | edgesLists[i] = new List();
65 | }
66 |
67 | int v, u;
68 | for (int i = 0; i < m; i++)
69 | {
70 | (v, u) = ReadTwoNumbers(input);
71 | v--;
72 | u--;
73 | edgesLists[v].Add(u);
74 | edgesLists[u].Add(v);
75 | }
76 | }
77 |
78 | int[] components = GetComponents(edgesLists);
79 | int componentCount = components.Max();
80 |
81 | using (var output = new StreamWriter("components.out"))
82 | {
83 | output.WriteLine(componentCount);
84 | output.WriteLine(String.Join(" ", components.Select(e => e.ToString())));
85 | }
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/AlgorithmsAndStrutures.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29306.81
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AlgorithmsAndStructures", "AlgorithmsAndStructures\AlgorithmsAndStructures.csproj", "{6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}"
7 | EndProject
8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AlgorithmsAndStructures.cpp", "AlgorithmsAndStructures.cpp\AlgorithmsAndStructures.cpp.vcxproj", "{508C3440-B04C-4A1F-8E4B-9538699AB86A}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Debug|x64 = Debug|x64
14 | Debug|x86 = Debug|x86
15 | Release|Any CPU = Release|Any CPU
16 | Release|x64 = Release|x64
17 | Release|x86 = Release|x86
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Debug|x64.ActiveCfg = Debug|Any CPU
23 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Debug|x64.Build.0 = Debug|Any CPU
24 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Debug|x86.ActiveCfg = Debug|Any CPU
25 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Debug|x86.Build.0 = Debug|Any CPU
26 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
27 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Release|Any CPU.Build.0 = Release|Any CPU
28 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Release|x64.ActiveCfg = Release|Any CPU
29 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Release|x64.Build.0 = Release|Any CPU
30 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Release|x86.ActiveCfg = Release|Any CPU
31 | {6AB4CDD4-722D-4AD9-94B2-FAFFB691C3B1}.Release|x86.Build.0 = Release|Any CPU
32 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Debug|Any CPU.ActiveCfg = Debug|Win32
33 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Debug|x64.ActiveCfg = Debug|x64
34 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Debug|x64.Build.0 = Debug|x64
35 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Debug|x86.ActiveCfg = Debug|Win32
36 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Debug|x86.Build.0 = Debug|Win32
37 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Release|Any CPU.ActiveCfg = Release|Win32
38 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Release|x64.ActiveCfg = Release|x64
39 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Release|x64.Build.0 = Release|x64
40 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Release|x86.ActiveCfg = Release|Win32
41 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}.Release|x86.Build.0 = Release|Win32
42 | EndGlobalSection
43 | GlobalSection(SolutionProperties) = preSolution
44 | HideSolutionNode = FALSE
45 | EndGlobalSection
46 | GlobalSection(ExtensibilityGlobals) = postSolution
47 | SolutionGuid = {D7BF6386-2596-4056-87E8-77DE04EBB258}
48 | EndGlobalSection
49 | EndGlobal
50 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/MstPoints.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading;
5 |
6 | namespace AlgorithmsAndStructures.GraphAlgorithms
7 | {
8 | class MstPoints
9 | {
10 | private static double Prim(List<(int, int)> points)
11 | {
12 | const int inf = int.MaxValue;
13 |
14 | int n = points.Count;
15 | int[,] matrix = CountDistances(points);
16 | bool[] visited = new bool[n];
17 |
18 | int[] distances = Enumerable.Repeat(inf, n).ToArray();
19 | distances[0] = 0;
20 |
21 | for (int i = 0; i < n; i++)
22 | {
23 | int from = -1;
24 | for (int j = 0; j < n; j++)
25 | if (!visited[j] && (from == -1 || distances[j] < distances[from]))
26 | from = j;
27 | visited[from] = true;
28 | for (int to = 0; to < n; to++)
29 | if (!visited[to] && matrix[from, to] < distances[to] && from != to)
30 | distances[to] = matrix[from, to];
31 | }
32 |
33 | double result = 0;
34 |
35 | foreach (var distance in distances)
36 | {
37 | result += Math.Sqrt(distance);
38 | }
39 |
40 | return result;
41 | }
42 |
43 | private static int DistanceBetween((int, int) from, (int, int) to)
44 | {
45 | return (from.Item1 - to.Item1) * (from.Item1 - to.Item1) + (from.Item2 - to.Item2) * (from.Item2 - to.Item2);
46 | }
47 |
48 | private static int[,] CountDistances(List<(int, int)> points)
49 | {
50 | int n = points.Count;
51 | int[,] distances = new int[n, n];
52 |
53 | for (int i = 0; i < n; i++)
54 | {
55 | for (int j = 0; j < n; j++)
56 | {
57 | distances[i, j] = DistanceBetween(points[i], points[j]);
58 | }
59 | }
60 |
61 | return distances;
62 | }
63 |
64 | private static void Program()
65 | {
66 | int n;
67 | List <(int, int)> points = new List<(int, int)>();
68 |
69 | n = int.Parse(Console.ReadLine());
70 | int x, y;
71 | string[] line;
72 | for (int i = 0; i < n; i++)
73 | {
74 | line = Console.ReadLine().Split();
75 | x = int.Parse(line[0]);
76 | y = int.Parse(line[1]);
77 | points.Add((x, y));
78 | }
79 |
80 | double result = Prim(points);
81 | Console.WriteLine(result.ToString("0.0000000000", System.Globalization.CultureInfo.InvariantCulture));
82 | }
83 |
84 | public static void Solve()
85 | {
86 | var stackSize = 100000000;
87 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
88 | thread.Start();
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/DataStructures/CorrectBracketSequence.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.DataStructures
7 | {
8 | class CorrectBracketSequence
9 | {
10 | class Stack
11 | {
12 | private char[] data;
13 | private int size;
14 |
15 | public Stack()
16 | {
17 | data = new char[1000000];
18 | size = 0;
19 | }
20 |
21 | public int Size()
22 | {
23 | return size;
24 | }
25 |
26 | public bool IsEmpty()
27 | {
28 | return Size() == 0;
29 | }
30 |
31 | public void Push(char element)
32 | {
33 | data[size++] = element;
34 | }
35 |
36 | public char Top()
37 | {
38 | return data[size - 1];
39 | }
40 |
41 | public char Pop()
42 | {
43 | return data[--size];
44 | }
45 | }
46 |
47 | private static bool CheckSequence(string sequence)
48 | {
49 | Stack stack = new Stack();
50 | for (int i = 0; i < sequence.Length; ++i)
51 | {
52 | if (sequence[i] == '(' || sequence[i] == '[')
53 | {
54 | stack.Push(sequence[i]);
55 | }
56 | else if (!stack.IsEmpty())
57 | {
58 | if (sequence[i] == ')' && stack.Top() == '(')
59 | {
60 | stack.Pop();
61 | }
62 | else if(sequence[i] == ']' && stack.Top() == '[')
63 | {
64 | stack.Pop();
65 | }
66 | else
67 | {
68 | return false;
69 | }
70 | }
71 | else
72 | {
73 | return false;
74 | }
75 | }
76 |
77 | if (stack.IsEmpty())
78 | {
79 | return true;
80 | }
81 |
82 | return false;
83 | }
84 |
85 | public static void Solve()
86 | {
87 | string[] sequences = File.ReadAllLines("brackets.in");
88 | string answer = string.Empty;
89 | for (int i = 0; i < sequences.Length; ++i)
90 | {
91 | string sequence = sequences[i];
92 | if (CheckSequence(sequence))
93 | {
94 | answer += "YES\n";
95 | }
96 | else
97 | {
98 | answer += "NO\n";
99 | }
100 | }
101 | File.WriteAllText("brackets.out", answer);
102 | }
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/HashTables/MyMap.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Runtime.InteropServices.ComTypes;
5 | using System.Text;
6 |
7 | namespace AlgorithmsAndStructures.HashTables
8 | {
9 | class MyMap
10 | {
11 | private const int maxHashSize = 20000003;
12 | private const int hashHelper = 37;
13 | List<(string, string)>[] hashTable = new List<(string, string)>[maxHashSize];
14 |
15 | public static int Hash(string value)
16 | {
17 | Int64 hashCode = 0;
18 | Int64 helper = 1;
19 | foreach (var ch in value.ToLower())
20 | {
21 | hashCode += (Int64)(ch - 'a') * helper % maxHashSize;
22 | hashCode %= maxHashSize;
23 | helper *= hashHelper;
24 | helper %= maxHashSize;
25 | }
26 | return (int)hashCode;
27 | }
28 |
29 | public void Put((string, string) value)
30 | {
31 | int hashCode = Hash(value.Item1);
32 | if (hashTable[hashCode] == null)
33 | hashTable[hashCode] = new List<(string, string)>();
34 | hashTable[hashCode].RemoveAll(v => v.Item1 == value.Item1);
35 | hashTable[hashCode].Add(value);
36 | }
37 |
38 | public string Get(string key)
39 | {
40 | int hashCode = Hash(key);
41 | if (hashTable[hashCode] != null && hashTable[hashCode].Exists(v => v.Item1 == key))
42 | return hashTable[hashCode].Find(v => v.Item1 == key).Item2;
43 | return "none";
44 | }
45 |
46 | public void Delete(string key)
47 | {
48 | int hashCode = Hash(key);
49 | if (hashTable[hashCode] != null)
50 | {
51 | hashTable[hashCode].RemoveAll(v => v.Item1 == key);
52 | }
53 | }
54 | }
55 |
56 | class SolutionMap
57 | {
58 | public static void Solve()
59 | {
60 | using (var input = new StreamReader("map.in"))
61 | {
62 | using (var output = new StreamWriter("map.out"))
63 | {
64 | MyMap map = new MyMap();
65 | while(true)
66 | {
67 | string[] line = input.ReadLine()?.Trim().Split();
68 | if (line == null)
69 | break;
70 | switch (line[0])
71 | {
72 | case "put":
73 | map.Put((line[1], line[2]));
74 | break;
75 | case "delete":
76 | map.Delete(line[1]);
77 | break;
78 | case "get":
79 | output.WriteLine(map.Get(line[1]));
80 | break;
81 | }
82 | }
83 | }
84 | }
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SortingAlgorithms/InversionsCount.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.IO;
4 |
5 | namespace AlgorithmsAndStructures.SortingAlgorithms
6 | {
7 | class InversionsCount where Template : IComparable
8 | {
9 | public static decimal cnt = 0;
10 | private static Template[] CountInversions(Template[] needToSortArray)
11 | {
12 | if (needToSortArray.Length == 1)
13 | {
14 | return needToSortArray;
15 | }
16 | int middlePosition = needToSortArray.Length / 2;
17 | return Merge(CountInversions(needToSortArray.Take(middlePosition).ToArray()), CountInversions(needToSortArray.Skip(middlePosition).ToArray()));
18 | }
19 |
20 | private static Template[] Merge(Template[] leftArray, Template[] rightArray)
21 | {
22 | int leftIterator = 0;
23 | int rightIterator = 0;
24 | Template[] mergedArray = new Template[leftArray.Length + rightArray.Length];
25 | int mergedIterator = 0;
26 |
27 |
28 | while (leftIterator < leftArray.Length && rightIterator < rightArray.Length)
29 | {
30 | if (leftArray[leftIterator].CompareTo(rightArray[rightIterator]) <= 0)
31 | {
32 | mergedArray[mergedIterator] = leftArray[leftIterator++];
33 | }
34 | else
35 | {
36 | InversionsCount.cnt += leftArray.Length - leftIterator;
37 | mergedArray[mergedIterator] = rightArray[rightIterator++];
38 | }
39 | mergedIterator++;
40 | }
41 |
42 | while (leftIterator < leftArray.Length)
43 | {
44 | mergedArray[mergedIterator++] = leftArray[leftIterator++];
45 | }
46 |
47 | while (rightIterator < rightArray.Length)
48 | {
49 | mergedArray[mergedIterator++] = rightArray[rightIterator++];
50 | }
51 |
52 | return mergedArray;
53 | }
54 |
55 | public static void Solve()
56 | {
57 | int[] array;
58 | using (var inputFile = new StreamReader("inversions.in"))
59 | {
60 | int n = Int32.Parse(inputFile.ReadLine());
61 | array = new int[n];
62 | string[] inputArray = inputFile.ReadLine().Split();
63 | for (int i = 0; i < n; ++i)
64 | {
65 | array[i] = Int32.Parse(inputArray[i]);
66 | }
67 | }
68 | InversionsCount.cnt = 0;
69 | InversionsCount.CountInversions(array);
70 | decimal result = InversionsCount.cnt;
71 |
72 | using (var outputFile = new StreamWriter("inversions.out"))
73 | {
74 | outputFile.WriteLine(result);
75 | }
76 | }
77 | }
78 |
79 | class StartInversionsCounter
80 | {
81 | public static void Solve()
82 | {
83 | InversionsCount.Solve();
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SortingAlgorithms/HeapSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 |
6 | namespace AlgorithmsAndStructures.SortingAlgorithms
7 | {
8 | class Heap
9 | {
10 | public Int64[] heap { get; set; }
11 | public int heapSize;
12 |
13 | public Heap(Int64[] array)
14 | {
15 | BuildHeap(array);
16 | }
17 |
18 | public static void Swap(ref Int64 a, ref Int64 b)
19 | {
20 | Int64 temp = a;
21 | a = b;
22 | b = temp;
23 | }
24 |
25 | public void SiftDown(int parent)
26 | {
27 | while (2 * parent + 1 < heapSize)
28 | {
29 | int leftSon = 2 * parent + 1;
30 | int rightSon = 2 * parent + 2;
31 | int biggestSon = leftSon;
32 |
33 | if (rightSon < heapSize && heap[rightSon] > heap[leftSon])
34 | biggestSon = rightSon;
35 |
36 | if (heap[parent] >= heap[biggestSon])
37 | break;
38 |
39 | Swap(ref heap[parent], ref heap[biggestSon]);
40 | parent = biggestSon;
41 | }
42 | }
43 |
44 | public void SiftUp(int son)
45 | {
46 | while (heap[son] > heap[(son - 1) / 2])
47 | {
48 | Swap(ref heap[son], ref heap[(son - 1) / 2]);
49 | son = (son - 1) / 2;
50 | }
51 | }
52 |
53 | public void BuildHeap(Int64[] array)
54 | {
55 | heapSize = array.Length;
56 | heap = new Int64[heapSize];
57 | array.CopyTo(heap, 0);
58 |
59 | for (int i = heapSize / 2; i >= 0; --i)
60 | {
61 | SiftDown(i);
62 | }
63 | }
64 | }
65 | class HeapSort
66 | {
67 | private static Int64[] Sort(Int64[] array)
68 | {
69 | Heap heap = new Heap(array);
70 | for (int i = 0; i < array.Length - 1; ++i)
71 | {
72 | Heap.Swap(ref heap.heap[0], ref heap.heap[array.Length - 1 - i]);
73 | heap.heapSize--;
74 | heap.SiftDown(0);
75 | }
76 |
77 | return heap.heap;
78 | }
79 |
80 | public static void Solve()
81 | {
82 | int n;
83 | Int64[] array;
84 | using (var inputFile = new StreamReader("sort.in"))
85 | {
86 | n = int.Parse(inputFile.ReadLine());
87 | string[] line = inputFile.ReadLine().Split(' ');
88 | array = new Int64[n];
89 | for (int i = 0; i < n; ++i)
90 | {
91 | array[i] = Int64.Parse(line[i]);
92 | }
93 | }
94 | array = Sort(array);
95 | using (var outputFile = new StreamWriter("sort.out"))
96 | {
97 | for (int i = 0; i < n; ++i)
98 | {
99 | outputFile.Write(array[i]);
100 | outputFile.Write(" ");
101 | }
102 | outputFile.WriteLine();
103 | }
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/Game.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | namespace AlgorithmsAndStructures.GraphAlgorithms
9 | {
10 | class Game
11 | {
12 | private static bool CheckFirstWin(int s, HashSet[] edgeslists)
13 | {
14 | int n = edgeslists.Length;
15 | bool?[] winHere = new bool?[n];
16 |
17 | void Dfs(int v)
18 | {
19 | foreach (var u in edgeslists[v])
20 | {
21 | if (winHere[u] == null)
22 | Dfs(u);
23 | }
24 |
25 | if (edgeslists[v].Count == 0)
26 | {
27 | winHere[v] = false;
28 | return;
29 | }
30 |
31 | winHere[v] = edgeslists[v].Select((e) => !winHere[e]).Aggregate((a, b) => a | b);
32 | }
33 |
34 | Dfs(s);
35 |
36 | return winHere[s].Value;
37 | }
38 |
39 |
40 | private static (int, int) ReadTwoNumbers(StreamReader input)
41 | {
42 | int a, b;
43 | string inputLine = input.ReadLine();
44 | string[] inputStrings = inputLine.Split();
45 | a = int.Parse(inputStrings[0]);
46 | b = int.Parse(inputStrings[1]);
47 |
48 | return (a, b);
49 | }
50 |
51 | private static (int, int) ReadTwoNumbers()
52 | {
53 | int a, b;
54 | string inputLine = Console.ReadLine();
55 | string[] inputStrings = inputLine.Split();
56 | a = int.Parse(inputStrings[0]);
57 | b = int.Parse(inputStrings[1]);
58 |
59 | return (a, b);
60 | }
61 |
62 | private static (int, int, int) ReadThreeNumbers()
63 | {
64 | int a, b, c;
65 | string inputLine = Console.ReadLine();
66 | string[] inputStrings = inputLine.Split();
67 | a = int.Parse(inputStrings[0]);
68 | b = int.Parse(inputStrings[1]);
69 | c = int.Parse(inputStrings[2]);
70 |
71 | return (a, b, c);
72 | }
73 |
74 | private static void Program()
75 | {
76 | int n, m, s;
77 |
78 | (n, m, s) = ReadThreeNumbers();
79 | s--;
80 |
81 | var edgesLists = new HashSet[n];
82 | for (int i = 0; i < n; i++)
83 | {
84 | edgesLists[i] = new HashSet();
85 | }
86 | int v, u;
87 | for (int i = 0; i < m; i++)
88 | {
89 | (v, u) = ReadTwoNumbers();
90 | v--;
91 | u--;
92 | edgesLists[v].Add(u);
93 | }
94 |
95 | bool isHamiltonian = CheckFirstWin(s, edgesLists);
96 | Console.WriteLine(isHamiltonian ? "First player wins" : "Second player wins");
97 | }
98 |
99 | public static void Solve()
100 | {
101 | var stackSize = 100000000;
102 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
103 | thread.Start();
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/Mst.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading;
6 |
7 | namespace AlgorithmsAndStructures.GraphAlgorithms
8 | {
9 | class Mst
10 | {
11 | class Dsu
12 | {
13 | private int[] _parent;
14 | private int[] _rank;
15 |
16 | public Dsu(int count)
17 | {
18 | _parent = new int[count];
19 | for (int i = 0; i < count; i++)
20 | {
21 | _parent[i] = i;
22 | }
23 |
24 | _rank = new int[count];
25 | for (int i = 0; i < count; i++)
26 | {
27 | _rank[i] = 0;
28 | }
29 | }
30 |
31 | public int Get(int v)
32 | {
33 | if (_parent[v] == v)
34 | return v;
35 | return _parent[v] = Get(_parent[v]);
36 | }
37 |
38 | private void Swap(ref int a, ref int b)
39 | {
40 | int temp = a;
41 | a = b;
42 | b = temp;
43 | }
44 |
45 | public bool Unite(int v, int u)
46 | {
47 | v = Get(v);
48 | u = Get(u);
49 | if (u != v)
50 | {
51 | if (_rank[v] < _rank[u])
52 | Swap(ref v, ref u);
53 | _parent[u] = v;
54 | if (_rank[v] != _rank[u])
55 | _rank[v]++;
56 |
57 | return true;
58 | }
59 |
60 | return false;
61 | }
62 | }
63 |
64 | class Edge
65 | {
66 | public int From { get; private set; }
67 | public int To { get; private set; }
68 | public int Weight { get; private set; }
69 |
70 | public Edge(int from, int to, int weight)
71 | {
72 | From = from;
73 | To = to;
74 | Weight = weight;
75 | }
76 | }
77 |
78 | private static void Program()
79 | {
80 | int n, m;
81 | var input = Console.ReadLine().Split().Select(c => int.Parse(c)).ToArray();
82 | n = input[0];
83 | m = input[1];
84 |
85 | Dsu dsu = new Dsu(n);
86 |
87 | List edgeList = new List(m);
88 |
89 | for (int i = 0; i < m; i++)
90 | {
91 | input = Console.ReadLine().Split().Select(c => int.Parse(c)).ToArray();
92 | edgeList.Add(new Edge(input[0] - 1, input[1] - 1, input[2]));
93 | }
94 |
95 | Int64 result = edgeList
96 | .OrderBy(e => e.Weight)
97 | .Select(e => (Int64)(dsu.Unite(e.From, e.To) ? e.Weight : 0))
98 | .Sum();
99 |
100 | Console.WriteLine(result);
101 | }
102 |
103 | public static void Solve()
104 | {
105 | var stackSize = 100000000;
106 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
107 | thread.Start();
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SortingAlgorithms/SortForRunners.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 |
6 | namespace AlgorithmsAndStructures.SortingAlgorithms
7 | {
8 | class SortForRunners
9 | {
10 | private static List Sort(List needToSortArray)
11 | {
12 | if (needToSortArray.Count() == 1)
13 | {
14 | return needToSortArray;
15 | }
16 | int middlePosition = needToSortArray.Count() / 2;
17 | return Merge(Sort(needToSortArray.Take(middlePosition).ToList()), Sort(needToSortArray.Skip(middlePosition).ToList()));
18 | }
19 |
20 | private static List Merge(List leftArray, List rightArray)
21 | {
22 | int leftIterator = 0;
23 | int rightIterator = 0;
24 | int leftLenght = leftArray.Count();
25 | int rightLength = rightArray.Count();
26 | List mergedArray = new List(leftLenght + rightLength);
27 |
28 | while (leftIterator < leftLenght && rightIterator < rightLength)
29 | {
30 | if (String.CompareOrdinal(leftArray[leftIterator], rightArray[rightIterator]) <= 0)
31 | {
32 | mergedArray.Add(leftArray[leftIterator++]);
33 | }
34 | else
35 | {
36 | mergedArray.Add(rightArray[rightIterator++]);
37 | }
38 | }
39 |
40 | while (leftIterator < leftLenght)
41 | {
42 | mergedArray.Add(leftArray[leftIterator++]);
43 | }
44 |
45 | while (rightIterator < rightLength)
46 | {
47 | mergedArray.Add(rightArray[rightIterator++]);
48 | }
49 |
50 | return mergedArray;
51 |
52 | }
53 | public static void Solve()
54 | {
55 | Dictionary> names = new Dictionary>();
56 |
57 | using (var inputFile = new StreamReader("race.in"))
58 | {
59 | int n = Int32.Parse(inputFile.ReadLine());
60 |
61 | string name, country;
62 | for (int i = 0; i < n; ++i)
63 | {
64 | string[] inp = inputFile.ReadLine().Split();
65 | country = inp[0];
66 | name = inp[1];
67 | if (!names.ContainsKey(country))
68 | {
69 | names[country] = new List() { name };
70 | }
71 | else
72 | {
73 | names[country].Add(name);
74 | }
75 | }
76 | }
77 | List array = Sort(names.Keys.ToList());
78 | string lastCountry = string.Empty;
79 | using (var outputFile = new StreamWriter("race.out"))
80 | {
81 | foreach (string i in array)
82 | {
83 | outputFile.WriteLine($"=== {i} ===");
84 | foreach(string j in names[i])
85 | {
86 | outputFile.WriteLine(j);
87 | }
88 | }
89 | }
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/BipartiteGraph.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | namespace AlgorithmsAndStructures.GraphAlgorithms
9 | {
10 | class BipartiteGraph
11 | {
12 | private static bool CheckBipartite(HashSet[] edgesLists)
13 | {
14 | int n = edgesLists.Length;
15 | int[] color = new int[n];
16 |
17 | bool Dfs(int v, int c)
18 | {
19 | color[v] = c;
20 | foreach (var u in edgesLists[v])
21 | {
22 | if (color[u] == 0)
23 | {
24 | if (!Dfs(u, -c)) return false;
25 | }
26 | else if (color[u] == c)
27 | {
28 | return false;
29 | }
30 | }
31 |
32 | return true;
33 | }
34 |
35 | for (int i = 0; i < n; i++)
36 | {
37 | if (color[i] == 0)
38 | {
39 | if (!Dfs(i, 1)) return false;
40 | }
41 | }
42 |
43 | return true;
44 | }
45 |
46 | private static (int, int) ReadTwoNumbers(StreamReader input)
47 | {
48 | int a, b;
49 | string inputLine = input.ReadLine();
50 | string[] inputStrings = inputLine.Split();
51 | a = int.Parse(inputStrings[0]);
52 | b = int.Parse(inputStrings[1]);
53 |
54 | return (a, b);
55 | }
56 |
57 | private static (int, int) ReadTwoNumbers()
58 | {
59 | int a, b;
60 | string inputLine = Console.ReadLine();
61 | string[] inputStrings = inputLine.Split();
62 | a = int.Parse(inputStrings[0]);
63 | b = int.Parse(inputStrings[1]);
64 |
65 | return (a, b);
66 | }
67 |
68 | private static void Program()
69 | {
70 | int n, m;
71 | HashSet[] edgesLists;
72 |
73 | using (StreamReader input = new StreamReader("bipartite.in")) {
74 | (n, m) = ReadTwoNumbers(input);
75 |
76 | edgesLists = new HashSet[n];
77 | for (int i = 0; i < n; i++)
78 | {
79 | edgesLists[i] = new HashSet();
80 | }
81 |
82 | int v, u;
83 | for (int i = 0; i < m; i++)
84 | {
85 | (v, u) = ReadTwoNumbers(input);
86 | v--;
87 | u--;
88 | edgesLists[v].Add(u);
89 | edgesLists[u].Add(v);
90 | }
91 | }
92 |
93 | bool isBipartite = CheckBipartite(edgesLists);
94 |
95 | using (StreamWriter output = new StreamWriter("bipartite.out"))
96 | {
97 | output.WriteLine(isBipartite ? "YES" : "NO");
98 | }
99 | }
100 |
101 | public static void Solve()
102 | {
103 | var stackSize = 100000000;
104 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
105 | thread.Start();
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/TopSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Threading;
6 |
7 | namespace AlgorithmsAndStructures.GraphAlgorithms
8 | {
9 | class TopSort
10 | {
11 | private static List GetTopSort(HashSet[] edgesLists)
12 | {
13 | int n = edgesLists.Length;
14 | int[] used = new int[n];
15 |
16 | List topSort = new List();
17 |
18 | for (int i = 0; i < n; i++)
19 | {
20 | if (used[i] == 0)
21 | {
22 | if (!Dfs(i, edgesLists, used, topSort))
23 | return null;
24 | }
25 | }
26 |
27 | topSort.Reverse();
28 | return topSort;
29 | }
30 |
31 | private static bool Dfs(int v, HashSet[] edgesLists, int[] used, List topSort)
32 | {
33 | used[v] = 1;
34 | foreach (var u in edgesLists[v])
35 | {
36 | if (used[u] == 0)
37 | {
38 | if (!Dfs(u, edgesLists, used, topSort)) return false;
39 | }
40 | else if (used[u] == 1)
41 | {
42 | return false;
43 | }
44 | }
45 | used[v] = 2;
46 | topSort.Add(v);
47 | return true;
48 | }
49 |
50 | private static (int, int) ReadTwoNumbers(StreamReader input)
51 | {
52 | int a, b;
53 | string inputLine = input.ReadLine();
54 | string[] inputStrings = inputLine.Split();
55 | a = int.Parse(inputStrings[0]);
56 | b = int.Parse(inputStrings[1]);
57 |
58 | return (a, b);
59 | }
60 |
61 | private static (int, int) ReadTwoNumbers()
62 | {
63 | int a, b;
64 | string inputLine = Console.ReadLine();
65 | string[] inputStrings = inputLine.Split();
66 | a = int.Parse(inputStrings[0]);
67 | b = int.Parse(inputStrings[1]);
68 |
69 | return (a, b);
70 | }
71 |
72 | private static void Program()
73 | {
74 | int n, m;
75 |
76 | (n, m) = ReadTwoNumbers();
77 |
78 | var edgesLists = new HashSet[n];
79 | for (int i = 0; i < n; i++)
80 | {
81 | edgesLists[i] = new HashSet();
82 | }
83 | int v, u;
84 | for (int i = 0; i < m; i++)
85 | {
86 | (v, u) = ReadTwoNumbers();
87 | v--;
88 | u--;
89 | edgesLists[v].Add(u);
90 | }
91 |
92 | List topSort = GetTopSort(edgesLists);
93 | if (topSort == null)
94 | {
95 | Console.WriteLine(-1);
96 | }
97 | else
98 | {
99 | Console.WriteLine(String.Join(" ", topSort.Select(e => (e + 1).ToString()).ToArray()));
100 | }
101 | }
102 |
103 | public static void Solve()
104 | {
105 | var stackSize = 100000000;
106 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
107 | thread.Start();
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/HamiltonianPath.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | namespace AlgorithmsAndStructures.GraphAlgorithms
9 | {
10 | class HamiltonianPath
11 | {
12 | private static bool CheckHamiltonianPath(HashSet[] edgesLists, HashSet[] parents)
13 | {
14 | int n = edgesLists.Length;
15 | HashSet deleted = new HashSet();
16 |
17 | bool IsSource(int v)
18 | {
19 | bool result = parents[v].Select((u) => !deleted.Contains(u))
20 | .Aggregate(false, (a, b) => a | b);
21 |
22 | return !result;
23 | }
24 |
25 | int? FindOnlySource(int v)
26 | {
27 | var result = edgesLists[v].Where((u) => IsSource(u)).ToList();
28 | if (result.Count != 1)
29 | return null;
30 | return result[0];
31 | }
32 |
33 | int? source = null;
34 | for (int i = 0; i < n; ++i)
35 | {
36 | if (IsSource(i))
37 | {
38 | if (source != null)
39 | return false;
40 | source = i;
41 | }
42 | }
43 | if (source == null)
44 | return false;
45 |
46 | deleted.Add(source.Value);
47 |
48 | while (deleted.Count < n)
49 | {
50 | source = FindOnlySource(source.Value);
51 | if (source == null)
52 | return false;
53 | deleted.Add(source.Value);
54 | }
55 |
56 | return true;
57 | }
58 |
59 | private static (int, int) ReadTwoNumbers(StreamReader input)
60 | {
61 | int a, b;
62 | string inputLine = input.ReadLine();
63 | string[] inputStrings = inputLine.Split();
64 | a = int.Parse(inputStrings[0]);
65 | b = int.Parse(inputStrings[1]);
66 |
67 | return (a, b);
68 | }
69 |
70 | private static (int, int) ReadTwoNumbers()
71 | {
72 | int a, b;
73 | string inputLine = Console.ReadLine();
74 | string[] inputStrings = inputLine.Split();
75 | a = int.Parse(inputStrings[0]);
76 | b = int.Parse(inputStrings[1]);
77 |
78 | return (a, b);
79 | }
80 |
81 | private static void Program()
82 | {
83 | int n, m;
84 |
85 | (n, m) = ReadTwoNumbers();
86 |
87 | var edgesLists = new HashSet[n];
88 | var parents = new HashSet[n];
89 | for (int i = 0; i < n; i++)
90 | {
91 | edgesLists[i] = new HashSet();
92 | parents[i] = new HashSet();
93 | }
94 | int v, u;
95 | for (int i = 0; i < m; i++)
96 | {
97 | (v, u) = ReadTwoNumbers();
98 | v--;
99 | u--;
100 | edgesLists[v].Add(u);
101 | parents[u].Add(v);
102 | }
103 |
104 | bool isHamiltonian = CheckHamiltonianPath(edgesLists, parents);
105 | Console.WriteLine(isHamiltonian ? "YES" : "NO");
106 | }
107 |
108 | public static void Solve()
109 | {
110 | var stackSize = 100000000;
111 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
112 | thread.Start();
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/Condensation.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | namespace AlgorithmsAndStructures.GraphAlgorithms
9 | {
10 | class Condensation
11 | {
12 | private static (int, int[]) GetCondensation(List[] edgesLists, List[] edgesListsT)
13 | {
14 | int n = edgesLists.Length;
15 | bool[] used = new bool[n];
16 | int[] condensation = new int[n];
17 | List order = GetTopSort(edgesLists);
18 |
19 | int componentNumber = 1;
20 | void Dfs(int v)
21 | {
22 | used[v] = true;
23 | condensation[v] = componentNumber;
24 | foreach (var u in edgesListsT[v])
25 | {
26 | if (!used[u])
27 | Dfs(u);
28 | }
29 | }
30 |
31 | foreach (var i in order)
32 | {
33 | if(!used[i])
34 | {
35 | Dfs(i);
36 | componentNumber++;
37 | }
38 | }
39 |
40 | return (componentNumber - 1, condensation);
41 | }
42 |
43 | private static List GetTopSort(List[] edgesLists)
44 | {
45 | int n = edgesLists.Length;
46 | bool[] used = new bool[n];
47 | List topSort = new List();
48 |
49 | void Dfs(int v)
50 | {
51 | used[v] = true;
52 | foreach (var u in edgesLists[v])
53 | {
54 | if (!used[u])
55 | Dfs(u);
56 | }
57 | topSort.Add(v);
58 | }
59 |
60 | for (int i = 0; i < n; i++)
61 | {
62 | if (!used[i])
63 | Dfs(i);
64 | }
65 |
66 | topSort.Reverse();
67 | return topSort;
68 | }
69 |
70 | private static (int, int) ReadTwoNumbers(StreamReader input)
71 | {
72 | int a, b;
73 | string inputLine = input.ReadLine();
74 | string[] inputStrings = inputLine.Split();
75 | a = int.Parse(inputStrings[0]);
76 | b = int.Parse(inputStrings[1]);
77 |
78 | return (a, b);
79 | }
80 |
81 | private static (int, int) ReadTwoNumbers()
82 | {
83 | int a, b;
84 | string inputLine = Console.ReadLine();
85 | string[] inputStrings = inputLine.Split();
86 | a = int.Parse(inputStrings[0]);
87 | b = int.Parse(inputStrings[1]);
88 |
89 | return (a, b);
90 | }
91 |
92 | private static void Program()
93 | {
94 | int n, m;
95 |
96 | (n, m) = ReadTwoNumbers();
97 |
98 | var edgesLists = new List[n];
99 | var edgesListsT = new List[n];
100 | for (int i = 0; i < n; i++)
101 | {
102 | edgesLists[i] = new List();
103 | edgesListsT[i] = new List();
104 | }
105 | int v, u;
106 | for (int i = 0; i < m; i++)
107 | {
108 | (v, u) = ReadTwoNumbers();
109 | v--;
110 | u--;
111 | edgesLists[v].Add(u);
112 | edgesListsT[u].Add(v);
113 | }
114 |
115 | var (k, condensation) = GetCondensation(edgesLists, edgesListsT);
116 | Console.WriteLine(k);
117 | Console.WriteLine(String.Join(" ", condensation.Select(e => e.ToString()).ToArray()));
118 | }
119 |
120 | public static void Solve()
121 | {
122 | var stackSize = 100000000;
123 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
124 | thread.Start();
125 | }
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/Cycle.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | namespace AlgorithmsAndStructures.GraphAlgorithms
9 | {
10 | class Cycle
11 | {
12 | private static List GetCycle(HashSet[] edgesLists)
13 | {
14 | int n = edgesLists.Length;
15 | int[] used = new int[n];
16 | int[] parent = new int[n];
17 |
18 | List cycle = new List();
19 |
20 | (int, int)? result = null;
21 | for (int i = 0; i < n; i++)
22 | {
23 | if (used[i] == 0)
24 | {
25 | result = Dfs(i, edgesLists, used, parent) ?? result;
26 | if (result != null)
27 | {
28 | break;
29 | }
30 | }
31 | }
32 |
33 | if (result == null)
34 | return null;
35 |
36 | var (u, v) = result.Value;
37 | while (v != u)
38 | {
39 | cycle.Add(v);
40 | v = parent[v];
41 | }
42 | cycle.Add(u);
43 | cycle.Reverse();
44 |
45 | return cycle;
46 | }
47 |
48 | private static (int, int)? Dfs(int v, HashSet[] edgesLists, int[] used, int[] parent)
49 | {
50 | used[v] = 1;
51 |
52 | foreach (var u in edgesLists[v])
53 | {
54 | if (used[u] == 0)
55 | {
56 | parent[u] = v;
57 | var result = Dfs(u, edgesLists, used, parent);
58 | if (result != null)
59 | return result;
60 | }
61 | else if (used[u] == 1)
62 | {
63 | return (u, v);
64 | }
65 | }
66 |
67 | used[v] = 2;
68 | return null;
69 | }
70 |
71 | private static (int, int) ReadTwoNumbers(StreamReader input)
72 | {
73 | int a, b;
74 | string inputLine = input.ReadLine();
75 | string[] inputStrings = inputLine.Split();
76 | a = int.Parse(inputStrings[0]);
77 | b = int.Parse(inputStrings[1]);
78 |
79 | return (a, b);
80 | }
81 |
82 | private static (int, int) ReadTwoNumbers()
83 | {
84 | int a, b;
85 | string inputLine = Console.ReadLine();
86 | string[] inputStrings = inputLine.Split();
87 | a = int.Parse(inputStrings[0]);
88 | b = int.Parse(inputStrings[1]);
89 |
90 | return (a, b);
91 | }
92 |
93 | private static void Program()
94 | {
95 | int n, m;
96 |
97 | (n, m) = ReadTwoNumbers();
98 |
99 | var edgesLists = new HashSet[n];
100 | for (int i = 0; i < n; i++)
101 | {
102 | edgesLists[i] = new HashSet();
103 | }
104 | int v, u;
105 | for (int i = 0; i < m; i++)
106 | {
107 | (v, u) = ReadTwoNumbers();
108 | v--;
109 | u--;
110 | edgesLists[v].Add(u);
111 | }
112 |
113 | List cycle = GetCycle(edgesLists);
114 | if (cycle == null)
115 | {
116 | Console.WriteLine("NO");
117 | }
118 | else
119 | {
120 | Console.WriteLine("YES");
121 | Console.WriteLine(String.Join(" ", cycle.Select(e => (e + 1).ToString()).ToArray()));
122 | }
123 | }
124 |
125 | public static void Solve()
126 | {
127 | var stackSize = 100000000;
128 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
129 | thread.Start();
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/SortingAlgorithms/KStaticstic.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.SortingAlgorithms
5 | {
6 | class KStaticstic
7 | {
8 | private static int FindKStatistic(int[] inputArray, int searchPosition)
9 | {
10 | int leftPosition = 0, rightPosition = inputArray.Length - 1;
11 | while (true)
12 | {
13 | if (leftPosition + 1 >= rightPosition)
14 | {
15 | if (leftPosition + 1 == rightPosition && inputArray[leftPosition] > inputArray[rightPosition])
16 | {
17 | Swap(ref inputArray[leftPosition], ref inputArray[rightPosition]);
18 | }
19 | return inputArray[searchPosition];
20 | }
21 |
22 | int middle = (leftPosition + rightPosition) / 2;
23 | Swap(ref inputArray[middle], ref inputArray[leftPosition + 1]);
24 | if (inputArray[leftPosition] > inputArray[rightPosition])
25 | Swap(ref inputArray[leftPosition], ref inputArray[rightPosition]);
26 |
27 | if (inputArray[leftPosition + 1] > inputArray[rightPosition])
28 | Swap(ref inputArray[leftPosition + 1], ref inputArray[rightPosition]);
29 |
30 | if (inputArray[leftPosition] > inputArray[leftPosition + 1])
31 | Swap(ref inputArray[leftPosition], ref inputArray[leftPosition + 1]);
32 |
33 | int leftPointer = leftPosition + 1;
34 | int rightPointer = rightPosition;
35 |
36 | int value = inputArray[leftPointer];
37 |
38 | while (true)
39 | {
40 | do
41 | {
42 | leftPointer++;
43 | } while (inputArray[leftPointer] < value);
44 | do
45 | {
46 | rightPointer--;
47 | } while (inputArray[rightPointer] > value);
48 | if (leftPointer > rightPointer)
49 | {
50 | break;
51 | }
52 |
53 | Swap(ref inputArray[leftPointer], ref inputArray[rightPointer]);
54 | }
55 |
56 | inputArray[leftPosition + 1] = inputArray[rightPointer];
57 | inputArray[rightPointer] = value;
58 |
59 | if (rightPointer >= searchPosition)
60 | {
61 | rightPosition = rightPointer - 1;
62 | }
63 | if (rightPointer <= searchPosition)
64 | {
65 | leftPosition = leftPointer;
66 | }
67 | }
68 | }
69 | public static int[] FillArray(int n, int a, int b, int c, int firstElement, int secondElement)
70 | {
71 | int[] filledArray = new int[n];
72 | filledArray[0] = firstElement;
73 | if (n > 1)
74 | {
75 | filledArray[1] = secondElement;
76 | }
77 |
78 | for (int i = 2; i < n; i++)
79 | {
80 | filledArray[i] = a * filledArray[i - 2] + b * filledArray[i - 1] + c;
81 | }
82 | return filledArray;
83 | }
84 |
85 | public static void Swap(ref Template firstElement, ref Template secondElement)
86 | {
87 | Template swapHelper = firstElement;
88 | firstElement = secondElement;
89 | secondElement = swapHelper;
90 | }
91 |
92 | public static void Solve()
93 | {
94 | int n, k;
95 | int a, b, c;
96 | int firstElement, secondElement;
97 |
98 | string[] firstLine = Console.ReadLine().Split();
99 | string[] secondLine = Console.ReadLine().Split();
100 | n = Int32.Parse(firstLine[0]);
101 | k = Int32.Parse(firstLine[1]);
102 | a = Int32.Parse(secondLine[0]);
103 | b = Int32.Parse(secondLine[1]);
104 | c = Int32.Parse(secondLine[2]);
105 | firstElement = Int32.Parse(secondLine[3]);
106 | secondElement = Int32.Parse(secondLine[4]);
107 |
108 | int[] array = FillArray(n, a, b, c, firstElement, secondElement);
109 | int result = FindKStatistic(array, k - 1);
110 |
111 | Console.WriteLine(result);
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/DataStructures/PriorityQueue.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.DataStructures
7 | {
8 | class PriorityQueue
9 | {
10 | private const int maxDataSize = 1000000;
11 | private (Int64, int)[] data { get; set; }
12 | private int size;
13 |
14 | public PriorityQueue()
15 | {
16 | data = new (Int64, int)[maxDataSize];
17 | }
18 |
19 | public int Size()
20 | {
21 | return size;
22 | }
23 |
24 | public void Print()
25 | {
26 | for (int i = 0; i < size; ++i)
27 | {
28 | Console.Write(data[i]);
29 | Console.Write(" ");
30 | }
31 | Console.WriteLine();
32 | }
33 |
34 | private static void Swap(ref template a, ref template b)
35 | {
36 | template temp = a;
37 | a = b;
38 | b = temp;
39 | }
40 |
41 | private void SiftDown(int parent)
42 | {
43 | while (2 * parent + 1 < size)
44 | {
45 | int leftSon = 2 * parent + 1;
46 | int rightSon = 2 * parent + 2;
47 | int biggestSon = leftSon;
48 |
49 | if (rightSon < size && data[rightSon].Item1 < data[leftSon].Item1)
50 | biggestSon = rightSon;
51 |
52 | if (data[parent].Item1 <= data[biggestSon].Item1)
53 | break;
54 |
55 | Swap(ref data[parent], ref data[biggestSon]);
56 | parent = biggestSon;
57 | }
58 | }
59 |
60 | private void SiftUp(int son)
61 | {
62 | while (data[son].Item1 < data[(son - 1) / 2].Item1)
63 | {
64 | Swap(ref data[son], ref data[(son - 1) / 2]);
65 | son = (son - 1) / 2;
66 | }
67 | }
68 |
69 | public void Add(Int64 newElement, int id)
70 | {
71 | data[size] = (newElement, id);
72 | SiftUp(size++);
73 | }
74 |
75 | public Int64 ExtractMin()
76 | {
77 | Int64 result = data[0].Item1;
78 | if (size > 1)
79 | Swap(ref data[0], ref data[size - 1]);
80 | size--;
81 | if (size > 0)
82 | SiftDown(0);
83 | return result;
84 | }
85 |
86 | public int FindIndex(int id)
87 | {
88 | for (int i = 0; i < size; ++i)
89 | {
90 | if (id == data[i].Item2)
91 | return i;
92 | }
93 |
94 | return -1;
95 | }
96 |
97 | public void DecreaseElement(Int64 newElement, int id)
98 | {
99 | int index = FindIndex(id);
100 | data[index].Item1 = newElement;
101 | SiftUp(index);
102 | }
103 | }
104 |
105 | class SolutionPriorityQueue
106 | {
107 | public static void Solve()
108 | {
109 | PriorityQueue pq = new PriorityQueue();
110 | string[] com;
111 | int i = 0;
112 | do
113 | {
114 | com = Console.ReadLine()?.Split();
115 | if (com == null)
116 | break;
117 | switch (com[0])
118 | {
119 | case "push":
120 | Int64 element = Int64.Parse(com[1]);
121 | pq.Add(element, i);
122 | break;
123 | case "decrease-key":
124 | int id = int.Parse(com[1]) - 1;
125 | Int64 newElement = Int64.Parse(com[2]);
126 | pq.DecreaseElement(newElement, id);
127 | break;
128 | case "extract-min":
129 | if (pq.Size() > 0)
130 | {
131 | Int64 result = pq.ExtractMin();
132 | Console.WriteLine(result.ToString());
133 | }
134 | else
135 | {
136 | Console.WriteLine("*");
137 | }
138 |
139 | break;
140 | }
141 |
142 | i++;
143 | } while (com != null);
144 |
145 | }
146 | }
147 | }
148 |
149 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/HashTables/MyLinkedMap.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Runtime.InteropServices.ComTypes;
6 | using System.Text;
7 |
8 | namespace AlgorithmsAndStructures.HashTables
9 | {
10 | class LinkedMapItem
11 | {
12 | public string key;
13 | public string value;
14 | public LinkedMapItem prev;
15 | public LinkedMapItem next;
16 |
17 | public LinkedMapItem(string key, string value, LinkedMapItem prev, LinkedMapItem next = null)
18 | {
19 | this.key = key;
20 | this.value = value;
21 | this.prev = prev;
22 | this.next = next;
23 | }
24 |
25 | public LinkedMapItem()
26 | {
27 | }
28 | }
29 | class MyLinkedMap
30 | {
31 | private const int maxHashSize = 20000003;
32 | private const int hashHelper = 37;
33 | List[] hashTable = new List[maxHashSize];
34 |
35 | public static int Hash(string value)
36 | {
37 | Int64 hashCode = 0;
38 | Int64 helper = 1;
39 | foreach (var ch in value.ToLower())
40 | {
41 | hashCode += (Int64)(ch - 'a') * helper % maxHashSize;
42 | hashCode %= maxHashSize;
43 | helper *= hashHelper;
44 | helper %= maxHashSize;
45 | }
46 | return (int)hashCode;
47 | }
48 |
49 | public LinkedMapItem Put(LinkedMapItem item)
50 | {
51 | int hashCode = Hash(item.key);
52 | if (hashTable[hashCode] == null)
53 | hashTable[hashCode] = new List();
54 | if(!hashTable[hashCode].Exists(i => i.key == item.key))
55 | {
56 | hashTable[hashCode].Add(item);
57 | if (item.prev != null)
58 | {
59 | item.prev.next = item;
60 | }
61 | return item;
62 | }
63 | else
64 | {
65 | hashTable[hashCode].Find(i => i.key == item.key).value = item.value;
66 | return item.prev;
67 | }
68 | }
69 |
70 |
71 | public LinkedMapItem Get(string key)
72 | {
73 | int hashCode = Hash(key);
74 | if (hashTable[hashCode] != null && hashTable[hashCode].Exists(i => i.key == key))
75 | return hashTable[hashCode].Find(i => i.key == key);
76 | return null;
77 | }
78 |
79 | public LinkedMapItem Delete(string key)
80 | {
81 | int hashCode = Hash(key);
82 | if (hashTable[hashCode] == null || !hashTable[hashCode].Exists(i => i.key == key))
83 | return null;
84 | LinkedMapItem item = hashTable[hashCode].Find(i => i.key == key);
85 | if (item.prev != null)
86 | item.prev.next = item.next;
87 | if (item.next != null)
88 | item.next.prev = item.prev;
89 | item = hashTable[hashCode].Find(i => i.key == key);
90 | hashTable[hashCode].RemoveAll(i => i.key == key);
91 | return item;
92 | }
93 |
94 | public LinkedMapItem Prev(string key)
95 | {
96 | return Get(key)?.prev;
97 | }
98 |
99 | public LinkedMapItem Next(string key)
100 | {
101 | return Get(key)?.next;
102 | }
103 | }
104 |
105 | class SolutionLinkedMap
106 | {
107 | public static void Solve()
108 | {
109 | using (var input = new StreamReader("linkedmap.in"))
110 | {
111 | using (var output = new StreamWriter("linkedmap.out"))
112 | {
113 | MyLinkedMap map = new MyLinkedMap();
114 | LinkedMapItem lastItem = null;
115 | LinkedMapItem deleted = null;
116 | while (true)
117 | {
118 | string[] line = input.ReadLine()?.Trim().Split();
119 | if (line == null)
120 | break;
121 | switch (line[0])
122 | {
123 | case "put":
124 | lastItem = map.Put(new LinkedMapItem(line[1], line[2], lastItem));
125 | break;
126 | case "delete":
127 | deleted = map.Delete(line[1]);
128 | if (deleted?.key == lastItem?.key)
129 | lastItem = deleted?.prev;
130 | break;
131 | case "get":
132 | output.WriteLine(map.Get(line[1])?.value ?? "none");
133 | break;
134 | case "prev":
135 | output.WriteLine(map.Prev(line[1])?.value ?? "none");
136 | break;
137 | case "next":
138 | output.WriteLine(map.Next(line[1])?.value ?? "none");
139 | break;
140 | }
141 | }
142 | }
143 | }
144 | }
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/Labyrinth.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Runtime.InteropServices.ComTypes;
6 | using System.Text;
7 |
8 | namespace AlgorithmsAndStructures.GraphAlgorithms
9 | {
10 | class Labyrinth
11 | {
12 | static List FindWay(string[] map, int n, int m, int startI, int startJ, int endI, int endJ)
13 | {
14 | char[,] pathLetter = new char[n, m];
15 | (int, int)[,] pre = new (int, int)[n, m];
16 | int[,] distances = new int[n, m];
17 |
18 | for (int i = 0; i < n; i++)
19 | {
20 | for (int j = 0; j < m; j++)
21 | {
22 | distances[i, j] = -1;
23 | pre[i, j] = (-1, -1);
24 | }
25 | }
26 |
27 | Queue<(int, int)> queue = new Queue<(int, int)>();
28 | distances[startI, startJ] = 0;
29 | pathLetter[startI, startJ] = 'S';
30 | queue.Enqueue((startI, startJ));
31 | int curI, curJ;
32 | while (queue.Count > 0)
33 | {
34 | (curI, curJ) = queue.Dequeue();
35 | if (CanGo(map, n, m, curI - 1, curJ) && distances[curI - 1, curJ] == -1)
36 | {
37 | distances[curI - 1, curJ] = distances[curI, curJ] + 1;
38 | pre[curI - 1, curJ] = (curI, curJ);
39 | pathLetter[curI - 1, curJ] = 'U';
40 |
41 | queue.Enqueue((curI - 1, curJ));
42 | }
43 |
44 | if (CanGo(map, n, m, curI + 1, curJ) && distances[curI + 1, curJ] == -1)
45 | {
46 | distances[curI + 1, curJ] = distances[curI, curJ] + 1;
47 | pre[curI + 1, curJ] = (curI, curJ);
48 | pathLetter[curI + 1, curJ] = 'D';
49 |
50 | queue.Enqueue((curI + 1, curJ));
51 | }
52 |
53 | if (CanGo(map, n, m, curI, curJ - 1) && distances[curI, curJ - 1] == -1)
54 | {
55 | distances[curI, curJ - 1] = distances[curI, curJ] + 1;
56 | pre[curI, curJ - 1] = (curI, curJ);
57 | pathLetter[curI, curJ - 1] = 'L';
58 |
59 | queue.Enqueue((curI, curJ - 1));
60 | }
61 |
62 | if (CanGo(map, n, m, curI, curJ + 1) && distances[curI, curJ + 1] == -1)
63 | {
64 | distances[curI, curJ + 1] = distances[curI, curJ] + 1;
65 | pre[curI, curJ + 1] = (curI, curJ);
66 | pathLetter[curI, curJ + 1] = 'R';
67 |
68 | queue.Enqueue((curI, curJ + 1));
69 | }
70 | }
71 |
72 | List path = new List();
73 | curI = endI;
74 | curJ = endJ;
75 | while (pathLetter[curI, curJ] != 'S' && pathLetter[curI, curJ] != 0)
76 | {
77 | path.Add(pathLetter[curI, curJ]);
78 | (curI, curJ) = pre[curI, curJ];
79 | }
80 |
81 | path.Reverse();
82 |
83 | return path;
84 | }
85 |
86 | static bool IsValidCoordinates(int i, int j, int n, int m)
87 | {
88 | return i >= 0 && i < n && j >= 0 && j < m;
89 | }
90 |
91 | static bool CanGo(string[] map,int n, int m, int i, int j)
92 | {
93 | return IsValidCoordinates(i, j, n, m) && map[i][j] != '#';
94 | }
95 |
96 | private static (int, int) ReadTwoNumbers(StreamReader input)
97 | {
98 | int a, b;
99 | string inputLine = input.ReadLine();
100 | string[] inputStrings = inputLine.Split();
101 | a = int.Parse(inputStrings[0]);
102 | b = int.Parse(inputStrings[1]);
103 |
104 | return (a, b);
105 | }
106 |
107 | public static void Solve()
108 | {
109 | int n, m;
110 | string[] map;
111 | using (var input = new StreamReader("input.txt"))
112 | {
113 | (n, m) = ReadTwoNumbers(input);
114 | map = new string[n];
115 | for (int i = 0; i < n; i++)
116 | {
117 | map[i] = input.ReadLine();
118 | }
119 | }
120 |
121 | int startI = -1, startJ = -1;
122 | int endI = -1, endJ = -1;
123 | for (int i = 0; i < n; i++)
124 | {
125 | for (int j = 0; j < m; ++j)
126 | {
127 | if (map[i][j] == 'S')
128 | {
129 | startI = i;
130 | startJ = j;
131 | }
132 | if (map[i][j] == 'T')
133 | {
134 | endI = i;
135 | endJ = j;
136 | }
137 | }
138 | }
139 |
140 | List path = FindWay(map, n, m, startI, startJ, endI, endJ);
141 |
142 | using (var output = new StreamWriter("output.txt"))
143 | {
144 | if (path.Count == 0)
145 | {
146 | output.WriteLine(-1);
147 | return;
148 | }
149 | output.WriteLine(path.Count);
150 | foreach (var c in path)
151 | {
152 | output.Write(c);
153 | }
154 | output.WriteLine();
155 | }
156 | }
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/TwoChinese.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | using namespace std;
7 |
8 | typedef long long int64;
9 |
10 | struct Edge
11 | {
12 | int64 to;
13 | mutable int64 weight;
14 |
15 | Edge(int64 to, int64 weight) : to(to), weight(weight) {}
16 | Edge() {}
17 |
18 | friend istream& operator>> (istream& is, Edge& edge)
19 | {
20 | is >> edge.to >> edge.weight;
21 | edge.to--;
22 | return is;
23 | }
24 | };
25 |
26 | typedef vector>> edgesLists;
27 |
28 |
29 | const int64 inf = 228228228228228;
30 |
31 | int64 getMst(int64 root, const edgesLists& graph);
32 | bool checkAvailability(int64 from, const edgesLists& graph);
33 | void countVertex(int64 from, const edgesLists& graph, vector& visited);
34 | void getCondensation(const edgesLists& graph, vector& components);
35 | edgesLists getTransposed(const edgesLists& graph);
36 | void markComponents(int64 from, const edgesLists& graph, vector& components, int64& component);
37 | void getTopSort(const edgesLists& graph, vector& topSort);
38 | void sortByTimeOut(int64 from, const edgesLists& graph, vector& visited, vector& topSort);
39 |
40 | int64 getMst(int64 root, const edgesLists& graph)
41 | {
42 | int64 result = 0;
43 | int64 n = graph.size();
44 | vector minInEdge = vector(n, inf);
45 |
46 | for (int64 from = 0; from < n; ++from)
47 | {
48 | for (auto edge : graph[from])
49 | {
50 | minInEdge[edge.first] = min(minInEdge[edge.first], edge.second);
51 | }
52 | }
53 |
54 | for (int64 i = 0; i < n; ++i)
55 | if (i != root)
56 | result += minInEdge[i];
57 |
58 | edgesLists zeroGraph = edgesLists(n);
59 | for (int64 from = 0; from < n; ++from)
60 | {
61 | for (auto edge : graph[from])
62 | {
63 | if (edge.second == minInEdge[edge.first])
64 | {
65 | edge.second = 0;
66 | zeroGraph[from].push_back(edge);
67 | }
68 | }
69 | }
70 |
71 | if (checkAvailability(root, zeroGraph))
72 | return result;
73 |
74 | vector components = vector(n);
75 | getCondensation(zeroGraph, components);
76 | int64 componentsCount = 0;
77 | for (auto component : components)
78 | {
79 | componentsCount = max(componentsCount, component);
80 | }
81 | componentsCount++;
82 |
83 | edgesLists newGraph = edgesLists(componentsCount);
84 | for (int64 from = 0; from < n; ++from)
85 | {
86 | for (auto edge : graph[from])
87 | {
88 | if (components[from] != components[edge.first])
89 | newGraph[components[from]].emplace_back(components[edge.first], edge.second - minInEdge[edge.first]);
90 | }
91 | }
92 |
93 | return result + getMst(components[root], newGraph);
94 | }
95 |
96 | bool checkAvailability(int64 from, const edgesLists& graph)
97 | {
98 | int64 n = graph.size();
99 | vector visited = vector(n);
100 | countVertex(from, graph, visited);
101 | for (auto v : visited)
102 | if (!v)
103 | return false;
104 | return true;
105 | }
106 |
107 | void countVertex(int64 from, const edgesLists& graph, vector& visited)
108 | {
109 | visited[from] = true;
110 | for (auto edge : graph[from])
111 | if (!visited[edge.first])
112 | countVertex(edge.first, graph, visited);
113 | }
114 |
115 | void getCondensation(const edgesLists& graph, vector& components)
116 | {
117 | int64 n = graph.size();
118 | edgesLists graphTransposed = edgesLists(n);
119 | for (int64 from = 0; from < n; ++from)
120 | for (auto edge : graph[from])
121 | graphTransposed[edge.first].emplace_back(from, edge.second);
122 | vector order;
123 | getTopSort(graph, order);
124 | int64 componentsCount = 0;
125 |
126 | for (auto from : order)
127 | {
128 | if (components[from] == 0)
129 | markComponents(from, graphTransposed, components, ++componentsCount);
130 | }
131 |
132 | for (auto& component : components)
133 | {
134 | component--;
135 | }
136 | }
137 |
138 | edgesLists getTransposed(const edgesLists& graph)
139 | {
140 | int64 n = graph.size();
141 | edgesLists graphTransposed = edgesLists(n);
142 |
143 | for (int64 from = 0; from < n; ++from)
144 | for (auto edge : graph[from])
145 | graphTransposed[edge.first].emplace_back(from, edge.second);
146 |
147 | return graphTransposed;
148 | }
149 |
150 | void getTopSort(const edgesLists& graph, vector& topSort)
151 | {
152 | int64 n = graph.size();
153 | vector visited = vector(n);
154 |
155 | for (int64 from = 0; from < n; ++from)
156 | {
157 | if (!visited[from])
158 | sortByTimeOut(from, graph, visited, topSort);
159 | }
160 |
161 | reverse(topSort.begin(), topSort.end());
162 | }
163 |
164 | void sortByTimeOut(int64 from, const edgesLists& graph, vector& visited, vector& topSort)
165 | {
166 | visited[from] = true;
167 | for (auto& edge : graph[from])
168 | if (!visited[edge.first])
169 | sortByTimeOut(edge.first, graph, visited, topSort);
170 | topSort.push_back(from);
171 | }
172 |
173 | void markComponents(int64 from, const edgesLists& graph, vector& components, int64& component)
174 | {
175 | components[from] = component;
176 | for (auto& edge : graph[from])
177 | if (components[edge.first] == 0)
178 | markComponents(edge.first, graph, components, component);
179 | }
180 |
181 |
182 |
183 | int solve()
184 | {
185 | ifstream fin("chinese.in");
186 | ofstream fout("chinese.out");
187 | int64 n, m;
188 | fin >> n;
189 | fin >> m;
190 |
191 | edgesLists graph = edgesLists(n);
192 | int64 from;
193 | pair edge;
194 | for (int64 i = 0; i < m; ++i)
195 | {
196 | fin >> from >> edge.first >> edge.second;
197 | graph[from - 1].emplace_back(edge.first - 1, edge.second);
198 | }
199 |
200 | if (checkAvailability(0, graph))
201 | {
202 | fout << "YES\n";
203 | fout << getMst(0, graph) << "\n";
204 | }
205 | else
206 | {
207 | fout << "NO\n";
208 | }
209 | return 0;
210 | }
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/Quack/QuackInterpreter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace AlgorithmsAndStructures.Quack
7 | {
8 | class QuackInterpreter
9 | {
10 | private Queue queue;
11 | private Dictionary labels;
12 | private Dictionary registers;
13 | private readonly List commands;
14 |
15 | public QuackInterpreter(List commands)
16 | {
17 | queue = new Queue();
18 | labels = new Dictionary();
19 | registers = new Dictionary();
20 | for (int i = 0; i < 26; ++i)
21 | {
22 | registers[(char) ('a' + i)] = 0;
23 | }
24 | this.commands = commands;
25 | for (int i = 0; i < commands.Count; ++i)
26 | {
27 | string command = commands[i];
28 | if (command[0] == ':')
29 | labels[command.Substring(1)] = i + 1;
30 | }
31 |
32 |
33 | }
34 | public void Start()
35 | {
36 | int i = 0;
37 | while (i < commands.Count)
38 | {
39 | string command = commands[i];
40 | UInt16 a;
41 | UInt16 b;
42 | command = command.Trim();
43 | if (command == string.Empty)
44 | continue;
45 | switch (command[0])
46 | {
47 | case '+':
48 | a = queue.Dequeue();
49 | b = queue.Dequeue();
50 | queue.Enqueue((UInt16)((a + b)));
51 |
52 | i++;
53 | break;
54 | case '-':
55 | a = queue.Dequeue();
56 | b = queue.Dequeue();
57 | queue.Enqueue((UInt16)((a - b)));
58 |
59 | i++;
60 | break;
61 | case '*':
62 | a = queue.Dequeue();
63 | b = queue.Dequeue();
64 | queue.Enqueue((UInt16) (a * b));
65 |
66 | i++;
67 | break;
68 | case '/':
69 | a = queue.Dequeue();
70 | b = queue.Dequeue();
71 | queue.Enqueue((UInt16) (b == 0 ? 0 : a / b));
72 |
73 | i++;
74 | break;
75 | case '%':
76 | a = queue.Dequeue();
77 | b = queue.Dequeue();
78 | queue.Enqueue((UInt16) (b == 0 ? 0 : a % b));
79 |
80 | i++;
81 | break;
82 | case '>':
83 | registers[command[1]] = queue.Dequeue();
84 |
85 | i++;
86 | break;
87 | case '<':
88 | queue.Enqueue(registers[command[1]]);
89 |
90 | i++;
91 | break;
92 | case 'P':
93 | if (command.Length == 1)
94 | {
95 | Console.WriteLine(queue.Dequeue().ToString());
96 | }
97 | else
98 | {
99 | Console.WriteLine(registers[command[1]]);
100 | }
101 |
102 | i++;
103 | break;
104 | case 'C':
105 | if (command.Length == 1)
106 | {
107 | Console.Write((char) (queue.Dequeue() % 256));
108 | }
109 | else
110 | {
111 | Console.Write((char) (registers[command[1]] % 256));
112 | }
113 |
114 | i++;
115 | break;
116 | case 'J':
117 | i = labels[command.Substring(1)];
118 | break;
119 | case 'Z':
120 | if (registers[command[1]] == 0)
121 | i = labels[command.Substring(2)];
122 | else
123 | i++;
124 | break;
125 | case 'E':
126 | if (registers[command[1]] == registers[command[2]])
127 | i = labels[command.Substring(3)];
128 | else
129 | i++;
130 | break;
131 | case 'G':
132 | if (registers[command[1]] > registers[command[2]])
133 | i = labels[command.Substring(3)];
134 | else
135 | i++;
136 | break;
137 | case 'Q':
138 | return;
139 | case ':':
140 | i++;
141 | break;
142 | default:
143 | if (UInt16.TryParse(command, out a))
144 | queue.Enqueue(a);
145 | i++;
146 | break;
147 | }
148 | }
149 | }
150 | }
151 |
152 | class SolutionQuack
153 | {
154 | public static void Solve()
155 | {
156 | List commands = new List();
157 | while (true)
158 | {
159 | string inp = Console.ReadLine();
160 | if (inp == null)
161 | break;
162 | commands.Add(inp);
163 | }
164 | QuackInterpreter qi = new QuackInterpreter(commands);
165 |
166 | qi.Start();
167 |
168 | }
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures.cpp/AlgorithmsAndStructures.cpp.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | Win32
7 |
8 |
9 | Release
10 | Win32
11 |
12 |
13 | Debug
14 | x64
15 |
16 |
17 | Release
18 | x64
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | 16.0
38 | {508C3440-B04C-4A1F-8E4B-9538699AB86A}
39 | AlgorithmsAndStructurescpp
40 | 10.0
41 |
42 |
43 |
44 | Application
45 | true
46 | v142
47 | MultiByte
48 |
49 |
50 | Application
51 | false
52 | v142
53 | true
54 | MultiByte
55 |
56 |
57 | Application
58 | true
59 | v142
60 | MultiByte
61 |
62 |
63 | Application
64 | false
65 | v142
66 | true
67 | MultiByte
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | Level3
91 | Disabled
92 | true
93 | true
94 |
95 |
96 | Console
97 |
98 |
99 |
100 |
101 | Level3
102 | Disabled
103 | true
104 | true
105 |
106 |
107 | Console
108 |
109 |
110 |
111 |
112 | Level3
113 | MaxSpeed
114 | true
115 | true
116 | true
117 | true
118 |
119 |
120 | Console
121 | true
122 | true
123 |
124 |
125 |
126 |
127 | Level3
128 | MaxSpeed
129 | true
130 | true
131 | true
132 | true
133 |
134 |
135 | Console
136 | true
137 | true
138 |
139 |
140 |
141 |
142 |
143 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/GraphAlgorithms/TwoChinese.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading;
6 |
7 | namespace AlgorithmsAndStructures.GraphAlgorithms
8 | {
9 | class TwoChinese
10 | {
11 | private static Int64 GetMst(int root, List[] graph)
12 | {
13 | Int64 result = 0;
14 | int n = graph.Length;
15 | int[] minInEdge = Enumerable.Repeat(int.MaxValue, n).ToArray();
16 |
17 | for (int from = 0; from < n; from++)
18 | {
19 | foreach (var edge in graph[from])
20 | {
21 | minInEdge[edge.To] = Math.Min(minInEdge[edge.To], edge.Weight);
22 | }
23 | }
24 |
25 | for (int i = 0; i < n; i++)
26 | if (i != root)
27 | result += (Int64)(minInEdge[i]);
28 |
29 | List[] zeroGraph = new List[n];
30 | for (int from = 0; from < n; from++)
31 | {
32 | zeroGraph[from] = new List();
33 | foreach (var edge in graph[from])
34 | {
35 | if (edge.Weight == minInEdge[edge.To])
36 | {
37 | edge.Weight = 0;
38 | zeroGraph[from].Add(edge);
39 | }
40 | }
41 | }
42 |
43 | if (CheckAvailability(root, zeroGraph))
44 | return result;
45 |
46 | int[] components = GetCondensation(zeroGraph);
47 | int componentsCount = components.Max() + 1;
48 | List[] newGraph = new List[componentsCount];
49 | for (int i = 0; i < componentsCount; i++)
50 | {
51 | newGraph[i] = new List();
52 | }
53 |
54 | for (int from = 0; from < n; from++)
55 | {
56 | foreach (var edge in graph[from]
57 | .Where(edge => components[from] != components[edge.To]))
58 | {
59 | newGraph[components[from]].Add(new Edge(components[edge.To], edge.Weight - minInEdge[edge.To]));
60 | }
61 | }
62 |
63 | result += GetMst(components[root], newGraph);
64 | return result;
65 | }
66 |
67 | private static bool CheckAvailability(int from, List[] graph)
68 | {
69 | int n = graph.Length;
70 | bool[] visited = new bool[n];
71 | Queue queue = new Queue();
72 | queue.Enqueue(from);
73 | visited[from] = true;
74 | while (queue.Any())
75 | {
76 | from = queue.Dequeue();
77 | foreach (var edge in graph[from]
78 | .Where(edge => !visited[edge.To]))
79 | {
80 | queue.Enqueue(edge.To);
81 | visited[edge.To] = true;
82 | }
83 | }
84 |
85 | return visited.All(v => v);
86 | }
87 |
88 | private static List GetTopSort(List[] graph)
89 | {
90 | int n = graph.Length;
91 | bool[] visited = new bool[n];
92 |
93 | List topSort = new List(n);
94 |
95 | void Dfs(int from)
96 | {
97 | visited[from] = true;
98 | foreach (var edge in graph[from]
99 | .Where(edge => !visited[edge.To]))
100 | {
101 | Dfs(edge.To);
102 | }
103 |
104 | topSort.Add(from);
105 | }
106 |
107 | for (int i = 0; i < n; i++)
108 | {
109 | if (!visited[i])
110 | {
111 | Dfs(i);
112 | }
113 | }
114 |
115 | topSort.Reverse();
116 | return topSort;
117 | }
118 |
119 | private static int[] GetCondensation(List[] graph)
120 | {
121 | int n = graph.Length;
122 | List[] graphTransposed = GetTransposed(graph);
123 | List order = GetTopSort(graph);
124 | bool[] visited = new bool[n];
125 | int componentCount = 0;
126 | int[] components = new int[n];
127 |
128 | void Dfs(int from)
129 | {
130 | visited[from] = true;
131 | components[from] = componentCount;
132 | foreach (var edge in graphTransposed[from]
133 | .Where(edge => !visited[edge.To]))
134 | {
135 | Dfs(edge.To);
136 | }
137 | }
138 |
139 | foreach (var from in order)
140 | {
141 | if (!visited[from])
142 | {
143 | componentCount++;
144 | Dfs(from);
145 | }
146 | }
147 |
148 | return components.Select(c => c - 1).ToArray();
149 | }
150 |
151 | private static List[] GetTransposed(List[] graph)
152 | {
153 | int n = graph.Length;
154 | List[] graphTransposed = new List[n];
155 | for (int i = 0; i < n; i++)
156 | {
157 | graphTransposed[i] = new List();
158 | }
159 |
160 | for (int from = 0; from < n; from++)
161 | {
162 | foreach (var edge in graph[from])
163 | {
164 | graphTransposed[edge.To].Add(new Edge(from, edge.Weight));
165 | }
166 | }
167 |
168 | return graphTransposed;
169 | }
170 |
171 | private static void Program()
172 | {
173 | int n, m;
174 | var input = Console.ReadLine().Split().Select(c => int.Parse(c)).ToArray();
175 | n = input[0];
176 | m = input[1];
177 |
178 | List[] graph = new List[n];
179 | for (int i = 0; i < n; i++)
180 | {
181 | graph[i] = new List();
182 | }
183 |
184 | for (int i = 0; i < m; i++)
185 | {
186 | input = Console.ReadLine().Split().Select(c => int.Parse(c)).ToArray();
187 | graph[input[0] - 1].Add(new Edge(input[1] - 1, input[2]));
188 | }
189 |
190 | if (CheckAvailability(0, graph))
191 | {
192 | Console.WriteLine("YES");
193 | Console.WriteLine(GetMst(0, graph));
194 | }
195 | else
196 | {
197 | Console.WriteLine("NO");
198 | }
199 | }
200 |
201 | public static void Solve()
202 | {
203 | var stackSize = 100000000;
204 | Thread thread = new Thread(new ThreadStart(Program), stackSize);
205 | thread.Start();
206 | }
207 | }
208 |
209 | internal class Edge
210 | {
211 | public int To { get; private set; }
212 | public int Weight { get; set; }
213 |
214 | public Edge(int to, int weight)
215 | {
216 | To = to;
217 | Weight = weight;
218 | }
219 | }
220 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
341 | /AlgorithmsAndStrutures.sln.DotSettings
342 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/HashTables/MyMultiMap.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text.RegularExpressions;
5 |
6 |
7 | namespace AlgorithmsAndStructures.HashTables
8 | {
9 |
10 | class LinkedSetItem
11 | {
12 | public readonly string Value;
13 | public LinkedSetItem Prev;
14 | public LinkedSetItem Next;
15 |
16 | public LinkedSetItem(string value, LinkedSetItem prev, LinkedSetItem next = null)
17 | {
18 | Value = value;
19 | Prev = prev;
20 | Next = next;
21 | }
22 | }
23 | class LinkedSet
24 | {
25 | private const int MaxHashSize = 107;
26 | private const int HashHelper = 37;
27 |
28 | public readonly string Key;
29 | private List[] Elements;
30 | public LinkedSetItem Begin;
31 | private LinkedSetItem _last;
32 | public int Size;
33 |
34 | public LinkedSet(string key)
35 | {
36 | this.Key = key;
37 | this.Elements = new List[MaxHashSize];
38 | Begin = null;
39 | _last = null;
40 | Size = 0;
41 | }
42 |
43 | public static int Hash(string value)
44 | {
45 | Int64 hashCode = 0;
46 | Int64 helper = 1;
47 | foreach (var ch in value.ToLower())
48 | {
49 | hashCode += (Int64)(ch - 'a') * helper % MaxHashSize;
50 | hashCode %= MaxHashSize;
51 | helper *= HashHelper;
52 | helper %= MaxHashSize;
53 | }
54 | return Math.Abs((int)hashCode);
55 | }
56 |
57 | public void DeleteAll()
58 | {
59 | Elements = new List[MaxHashSize];
60 | _last = null;
61 | Begin = null;
62 | Size = 0;
63 | }
64 |
65 | public void Push(string value)
66 | {
67 | int hashCode = Hash(value);
68 | // Console.WriteLine(value);
69 | LinkedSetItem item = new LinkedSetItem(value, _last);
70 | if (Elements[hashCode] == null)
71 | Elements[hashCode] = new List();
72 | if (!Elements[hashCode].Exists(i => i.Value == item.Value))
73 | {
74 | Elements[hashCode].Add(item);
75 | Size++;
76 | if (_last != null)
77 | {
78 | _last.Next = item;
79 | }
80 |
81 | _last = item;
82 |
83 | if (Begin == null)
84 | {
85 | Begin = item;
86 | }
87 | }
88 |
89 | }
90 |
91 | public void Delete(string value)
92 | {
93 | try
94 | {
95 | int hashCode = Hash(value);
96 | if (Elements[hashCode].Exists(i => i.Value == value))
97 | {
98 | LinkedSetItem item = Elements[hashCode].Find(i => i.Value == value);
99 | Size--;
100 | Elements[hashCode].RemoveAll(i => i.Value == value);
101 | if (item.Prev != null)
102 | {
103 | item.Prev.Next = item.Next;
104 | }
105 |
106 | if (item.Next != null)
107 | {
108 | item.Next.Prev = item.Prev;
109 | }
110 |
111 | if (item.Value == _last?.Value)
112 | {
113 | _last = item.Prev;
114 | }
115 |
116 | if (item.Value == Begin?.Value)
117 | {
118 | Begin = item.Next;
119 | }
120 | }
121 | }
122 | catch
123 | {
124 |
125 | }
126 | }
127 | }
128 |
129 | class MyMultiMap
130 | {
131 | private const int MaxHashSize = 107;
132 | private const int HashHelper = 37;
133 | readonly List[] _hashTable = new List[MaxHashSize];
134 |
135 | private static int Hash(string value)
136 | {
137 | Int64 hashCode = 0;
138 | Int64 helper = 1;
139 | foreach (var ch in value.ToLower())
140 | {
141 | hashCode += (Int64)(ch - 'a') * helper % MaxHashSize;
142 | hashCode %= MaxHashSize;
143 | helper *= HashHelper;
144 | helper %= MaxHashSize;
145 | }
146 | return Math.Abs((int)hashCode);
147 | }
148 |
149 | public void Put((string, string) item)
150 | {
151 | int hashCode = Hash(item.Item1);
152 | if (_hashTable[hashCode] == null)
153 | _hashTable[hashCode] = new List();
154 | if (!_hashTable[hashCode].Exists(i => i.Key == item.Item1))
155 | {
156 | _hashTable[hashCode].Add(new LinkedSet(item.Item1));
157 | }
158 | _hashTable[hashCode].Find(i => i.Key == item.Item1).Push(item.Item2);
159 | }
160 |
161 | public void Delete((string, string) item)
162 | {
163 | int hashCode = Hash(item.Item1);
164 | if (_hashTable[hashCode] == null)
165 | return;
166 | if (!_hashTable[hashCode].Exists(i => i.Key == item.Item1))
167 | return;
168 | _hashTable[hashCode].Find(i => i.Key == item.Item1).Delete(item.Item2);
169 | }
170 |
171 | public void DeleteAll(string key)
172 | {
173 | int hashCode = Hash(key);
174 | if (_hashTable[hashCode] == null)
175 | return;
176 | if (!_hashTable[hashCode].Exists(i => i.Key == key))
177 | return;
178 | _hashTable[hashCode].Find(i => i.Key == key).DeleteAll();
179 | }
180 |
181 | public LinkedSet Get(string key)
182 | {
183 | int hashCode = Hash(key);
184 | if (_hashTable[hashCode] == null)
185 | return null;
186 | if (!_hashTable[hashCode].Exists(i => i.Key == key))
187 | return null;
188 | LinkedSet res = _hashTable[hashCode].Find(i => i.Key == key);
189 | return res;
190 | }
191 | }
192 | class SolutionMultiMap
193 | {
194 | public static void Solve()
195 | {
196 | using (var input = new StreamReader("multimap.in"))
197 | {
198 | using (var output = new StreamWriter("multimap.out"))
199 | {
200 | MyMultiMap map = new MyMultiMap();
201 | while (true)
202 | {
203 | string inp = input.ReadLine()?.Trim();
204 | if (null == inp)
205 | break;
206 | string[] line = Regex.Replace(inp, @"\s+", " ").Split();
207 |
208 | switch (line[0])
209 | {
210 |
211 | case "put":
212 | map.Put((line[1], line[2]));
213 | break;
214 | case "delete":
215 | map.Delete((line[1], line[2]));
216 | break;
217 | case "deleteall":
218 | map.DeleteAll(line[1]);
219 | break;
220 | case "get":
221 | LinkedSet res = map.Get(line[1]);
222 | if (res == null)
223 | {
224 | output.WriteLine('0');
225 | }
226 | else
227 | {
228 | output.Write(res.Size);
229 | output.Write(" ");
230 | LinkedSetItem el = res.Begin;
231 | while (el != null)
232 | {
233 | output.Write(el.Value);
234 | output.Write(" ");
235 | el = el.Next;
236 | }
237 |
238 | output.WriteLine();
239 | }
240 |
241 | break;
242 | }
243 | }
244 | }
245 | }
246 | }
247 | }
248 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Алгоритмы и структуры данных
2 |
3 | Здесь размещены решения задач для **PCMS2**. Все решения получили вердикт **OK** во воремя тестирования.
4 | Все задачи за исключением отмеченных выполнены на **C#**/
5 |
6 | Чтобы сдать задачу в систему, необходимо:
7 | * *C#*: в файле с классом решения переименовать метод с **Solve** на **Main**.
8 | * *C++*: в файле с решение переименовать функцию с **solve** на **main**.
9 |
10 | ## Первый семестр
11 |
12 | ### [Лабораторная работа №1](http://neerc.ifmo.ru/teaching/disalgo/problems/problems1.pdf)
13 |
14 | 1. [a + b](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SimpleTasks/AplusB.cs)
15 | 2. [a + b^2](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SimpleTasks/AplusBB.cs)
16 | 3. [Черепашка](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SimpleTasks/Turtle.cs)
17 | 4. [Простая сортировка](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SimpleTasks/SimpleSort.cs)
18 | 5. [Знакомство с жителями Сортленда](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SimpleTasks/SorlLand.cs)
19 |
20 | ### [Лабораторная работа №2](http://neerc.ifmo.ru/teaching/disalgo/problems/problems2.pdf)
21 |
22 | 1. [Сортировка](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SortingAlgorithms/MergeSort.cs)
23 | 2. [Соревнования по бегу](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SortingAlgorithms/SortForRunners.cs)
24 | 3. [Число инверсий](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SortingAlgorithms/InversionsCount.cs)
25 | 4. [Анти-QuickSort](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SortingAlgorithms/AntiQuickSort.cs)
26 | 5. [К-ая порядковая статистика](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SortingAlgorithms/KStaticstic.cs)
27 |
28 | ### [Лабораторная работа №3](http://neerc.ifmo.ru/teaching/disalgo/problems/problems3.pdf)
29 |
30 | 1. [Двоичный поиск](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/BinarySearch/BinarySearch.cs)
31 | 2. [~Гирлянда~](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/BinarySearch/Garland.cs) [*(C++)*](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/Garland.cpp)
32 | 3. [Пирамида ли?](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/DataStructures/IsHeap.cs)
33 | 4. [Пирамидальная сортировка](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SortingAlgorithms/HeapSort.cs)
34 | 5. [Цифровая сортировка](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/SortingAlgorithms/RadixSort.cs)
35 |
36 | ### [Лабораторная работа №4](http://neerc.ifmo.ru/teaching/disalgo/problems/problems4.pdf)
37 |
38 | 1. [Стек](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/DataStructures/Stack.cs)
39 | 2. [Очередь](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/DataStructures/Queue.cs)
40 | 3. [Правильная скобочная последовательность](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/DataStructures/CorrectBracketSequence.cs)
41 | 4. [Постфиксная запись](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/DataStructures/PostfixNotation.cs)
42 | 5. [Приоритетная очередь](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/DataStructures/PriorityQueue.cs)
43 |
44 | ### [Лабораторная работа №5](http://neerc.ifmo.ru/teaching/disalgo/problems/problems5.pdf)
45 |
46 | 1. [Set](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/HashTables/MySet.cs)
47 | 2. [Map](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/HashTables/MyMap.cs)
48 | 3. [LinkedMap](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/HashTables/MyLinkedMap.cs)
49 | 4. [MultiMap](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/HashTables/MyMultiMap.cs)
50 |
51 | ### [Лабораторная работа №6](http://neerc.ifmo.ru/teaching/disalgo/problems/problems6.pdf)
52 |
53 | 1. [Высота дерева](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/BST/BstHeight.cs)
54 | 2. [Проверка корректности](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/BST/IsBst.cs)
55 | 3. [Простое двоичное дерево поиска](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/BST/Bst.cs)
56 | 4. [Интерпретатор языка Quack](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/Quack/QuackInterpreter.cs)
57 |
58 | ## Второй семестр
59 |
60 | ### [Лабораторная работа №8](http://neerc.ifmo.ru/teaching/disalgo/problems/problems8.pdf)
61 |
62 | 1. [От списка ребер к матрице смежности](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/EdgeListsToMatrix.cs)
63 | 2. [Проверка на неориентированность](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/CheckOriented.cs)
64 | 3. [Проверка на наличие параллельных ребер](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/CheckParallelEdges.cs)
65 | 4. [Компоненты связнности](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/Components.cs)
66 | 5. [Кратчайшие пути в невзвешенном графе](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/Distances.cs)
67 | 6. [Лабиринт](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/Labyrinth.cs)
68 |
69 | ### [Лабораторная работа №9](http://neerc.ifmo.ru/teaching/disalgo/problems/problems9.pdf)
70 |
71 | 1. [Топологическая сортировка](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/TopSort.cs)
72 | 2. [Поиск цикла](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/Cycle.cs)
73 | 3. [Двудольный граф](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/BipartiteGraph.cs)
74 | 4. [Конденсация графа](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/Condensation.cs)
75 | 5. [Гамильтонов путь](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/HamiltonianPath.cs)
76 | 6. [Игра](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/Game.cs)
77 |
78 | ### [Лабораторная работа №10](http://neerc.ifmo.ru/teaching/disalgo/problems/problems10.pdf)
79 |
80 | 1. [Степени вершин](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/VertexDegree.cs)
81 | 2. [Остовное дерево](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/MstPoints.cs)
82 | 3. [Остовное дерево 3](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/Mst.cs)
83 | 4. [~Алгоритм двух китайцев~](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures/GraphAlgorithms/TwoChinese.cs) [*(C++)*](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/TwoChinese.cpp)
84 |
85 | ### [Лабораторная работа №11](http://neerc.ifmo.ru/teaching/disalgo/problems/problems11.pdf) (С++)
86 |
87 | 1. [Кратчайший путь](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/DijkstraMatrix.cpp)
88 | 2. [Кратчайший путь от каждой вершины до каждой](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/Floyd.cpp)
89 | 3. [Кратчайший путь](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/Dijkstra.cpp)
90 | 4. [~Кратчайшие пути и прочее~](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/Ford.cpp) *(tests upd)*
91 | 5. [Цикл отричательного веса](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/NegativeCycle.cpp)
92 |
93 | ### [Лабораторная работа №13](http://neerc.ifmo.ru/teaching/disalgo/problems/problems13.pdf) (С++)
94 |
95 | 1. [Наивный поиск подстроки в строке](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/SubStringSearch.cpp)
96 | 2. [Быстрый поиск подстроки в строке](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/SubStringSearch.cpp)
97 | 3. [Префикс-функция](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/PrefixFunction.cpp)
98 | 4. [Автомат КМП](https://github.com/s4xack/AlgorithmsAndStructures/blob/master/AlgorithmsAndStructures.cpp/KmpMachine.cpp)
99 |
--------------------------------------------------------------------------------
/AlgorithmsAndStructures/BST/Bst.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace AlgorithmsAndStructures.BST
5 | {
6 | class Bst
7 | {
8 | public class Node
9 | {
10 | public long Value { get; set; }
11 | public Node Parent { get; set; }
12 | public Node LeftChild { get; set; }
13 | public Node RightChild { get; set; }
14 |
15 | public Node(long value)
16 | {
17 | Value = value;
18 | }
19 | }
20 |
21 | private Node root;
22 |
23 | public Bst()
24 | {
25 | root = null;
26 | }
27 |
28 | public void Insert(long value)
29 | {
30 | Node node = root;
31 | Node newNode = new Node(value);
32 | while (node != null)
33 | {
34 | newNode.Parent = node;
35 | if (node.Value > newNode.Value)
36 | {
37 | node = node.LeftChild;
38 | }
39 | else if (node.Value < newNode.Value)
40 | {
41 | node = node.RightChild;
42 | }
43 | else
44 | {
45 | return;
46 | }
47 | }
48 |
49 | if (newNode.Parent == null)
50 | root = newNode;
51 | else if (newNode.Parent.Value > newNode.Value)
52 | newNode.Parent.LeftChild = newNode;
53 | else if (newNode.Parent.Value < newNode.Value)
54 | newNode.Parent.RightChild = newNode;
55 | }
56 |
57 | public void Delete(long value)
58 | {
59 | Node node = root;
60 | while (node != null)
61 | {
62 | if (node.Value > value)
63 | {
64 | node = node.LeftChild;
65 | }
66 | else if (node.Value < value)
67 | {
68 | node = node.RightChild;
69 | }
70 | else
71 | {
72 | break;
73 | }
74 | }
75 |
76 | if (node == null)
77 | return;
78 |
79 | if (node.LeftChild == null && node.RightChild == null)
80 | {
81 | Node parent = node.Parent;
82 | if (node.Parent == null)
83 | {
84 | root = null;
85 | }
86 | else if(parent.Value > value)
87 | {
88 | parent.LeftChild = null;
89 | }
90 | else
91 | {
92 | parent.RightChild = null;
93 | }
94 | }
95 | else if (node.LeftChild == null || node.RightChild == null)
96 | {
97 | Node child = node.LeftChild ?? node.RightChild;
98 | Node parent = node.Parent;
99 | if (node.Parent == null)
100 | {
101 | root = child;
102 | }
103 | else if (node.Parent.Value > value)
104 | {
105 | parent.LeftChild = child;
106 | }
107 | else
108 | {
109 | parent.RightChild = child;
110 | }
111 |
112 | child.Parent = parent;
113 | }
114 | else
115 | {
116 | Node leastNode = node.RightChild;
117 | while (leastNode.LeftChild != null)
118 | leastNode = leastNode.LeftChild;
119 | node.Value = leastNode.Value;
120 | if (leastNode.Parent.LeftChild == leastNode)
121 | {
122 | leastNode.Parent.LeftChild = leastNode.RightChild;
123 | }
124 | else
125 | {
126 | leastNode.Parent.RightChild = leastNode.RightChild;
127 | }
128 | }
129 | }
130 |
131 | public bool Exists(long value)
132 | {
133 | Node node = root;
134 | while(node != null)
135 | {
136 | if (node.Value > value)
137 | {
138 | node = node.LeftChild;
139 | }
140 | else if (node.Value < value)
141 | {
142 | node = node.RightChild;
143 | }
144 | else
145 | {
146 | return true;
147 | }
148 | }
149 |
150 | return false;
151 | }
152 |
153 | public void Elements(Node node)
154 | {
155 | if (node == null)
156 | return;
157 | Elements(node.LeftChild);
158 | Console.WriteLine(node.Value);
159 | Elements(node.RightChild);
160 | }
161 |
162 | public Node Next(long value)
163 | {
164 | Node node = root;
165 | if (node == null)
166 | return null;
167 | while (true)
168 | {
169 | if (node.Value > value && node.LeftChild != null)
170 | node = node.LeftChild;
171 | else if (node.Value < value && node.RightChild != null)
172 | node = node.RightChild;
173 | else
174 | break;
175 |
176 | }
177 |
178 | if (node.Value > value)
179 | {
180 | return node;
181 | }
182 |
183 | if (node.RightChild != null)
184 | {
185 | Node leastNode = node.RightChild;
186 | while (leastNode.LeftChild != null)
187 | leastNode = leastNode.LeftChild;
188 | return leastNode;
189 | }
190 |
191 | while (node != null && node.Value <= value)
192 | node = node.Parent;
193 | return node;
194 | }
195 |
196 | public Node Prev(long value)
197 | {
198 | Node node = root;
199 | if (node == null)
200 | return null;
201 | while (true)
202 | {
203 | if (node.Value > value && node.LeftChild != null)
204 | node = node.LeftChild;
205 | else if (node.Value < value && node.RightChild != null)
206 | node = node.RightChild;
207 | else
208 | break;
209 |
210 | }
211 |
212 | if (node.Value < value)
213 | {
214 | return node;
215 | }
216 |
217 | if (node.LeftChild != null)
218 | {
219 | Node leastNode = node.LeftChild;
220 | while (leastNode.RightChild != null)
221 | leastNode = leastNode.RightChild;
222 | return leastNode;
223 | }
224 |
225 | while (node != null && node.Value >= value)
226 | node = node.Parent;
227 | return node;
228 | }
229 | }
230 |
231 | class SolutionBst
232 | {
233 | private static void Test()
234 | {
235 | Bst bst = new Bst();
236 | bst.Insert(2);
237 | bst.Insert(5);
238 | bst.Insert(3);
239 | Console.WriteLine(bst.Exists(2) ? "true" : "false");
240 | Console.WriteLine(bst.Exists(4) ? "true" : "false");
241 | Console.WriteLine(bst.Next(4)?.Value.ToString() ?? "none");
242 | Console.WriteLine(bst.Prev(4)?.Value.ToString() ?? "none");
243 | bst.Delete(5);
244 | Console.WriteLine(bst.Next(4)?.Value.ToString() ?? "none");
245 | Console.WriteLine(bst.Prev(4)?.Value.ToString() ?? "none");
246 |
247 | }
248 |
249 | public static void Solve()
250 | {
251 | using (var input = new StreamReader("bstsimple.in"))
252 | {
253 | using (var output = new StreamWriter("bstsimple.out"))
254 | {
255 | Bst bst = new Bst();
256 | while (true)
257 | {
258 | string[] line = input.ReadLine()?.Trim().Split();
259 | if (line == null)
260 | break;
261 | switch (line[0])
262 | {
263 | case "insert":
264 | bst.Insert(long.Parse(line[1]));
265 | break;
266 | case "delete":
267 | bst.Delete(long.Parse(line[1]));
268 | break;
269 | case "exists":
270 | output.WriteLine(bst.Exists(long.Parse(line[1])) ? "true" : "false");
271 | break;
272 | case "next":
273 | output.WriteLine(bst.Next(long.Parse(line[1]))?.Value.ToString() ?? "none");
274 | break;
275 | case "prev":
276 | output.WriteLine(bst.Prev(long.Parse(line[1]))?.Value.ToString() ?? "none");
277 | break;
278 | }
279 | }
280 | }
281 | }
282 | }
283 | }
284 | }
285 |
--------------------------------------------------------------------------------