summaryrefslogtreecommitdiff
path: root/Year_2
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2023-01-21 19:22:56 +0100
committerSanto Cariotti <santo@dcariotti.me>2023-01-21 19:22:56 +0100
commit9cb77bf8a8d9e8bcb04a9d7fadd85329539113b8 (patch)
treea0aedea09f9f7940f2af0affe584377397a8dcd2 /Year_2
parent2088bf7f12f583b37615969bed9747c6c2678e69 (diff)
add knapsack
Diffstat (limited to 'Year_2')
-rw-r--r--Year_2/Algorithms/greedy-knapsack.cc40
1 files changed, 40 insertions, 0 deletions
diff --git a/Year_2/Algorithms/greedy-knapsack.cc b/Year_2/Algorithms/greedy-knapsack.cc
new file mode 100644
index 0000000..c385499
--- /dev/null
+++ b/Year_2/Algorithms/greedy-knapsack.cc
@@ -0,0 +1,40 @@
+#include <iostream>
+#include <fstream>
+#include <vector>
+#include <algorithm>
+
+using namespace std;
+
+int
+main(int argc, char** argv)
+{
+ int ts = (argc > 1) ? stoi(argv[1]) : 100;
+ ifstream fin("input.txt");
+ ofstream fout("output.txt");
+
+ for (int i = 0; i < ts; ++i) {
+ int n, target;
+ vector<int> v;
+ fin >> n >> target;
+ v.resize(n);
+
+ for (int j = 0; j < n; ++j) {
+ fin >> v[j];
+ }
+
+ sort(v.begin(), v.end(), [](int a, int b) {
+ return a > b;
+ });
+
+ int result { 0 };
+ for (int j = 0; j < min(target, n); ++j)
+ result += v[j];
+
+ fout << result << endl;
+ }
+
+ fin.close();
+ fout.close();
+
+ return 0;
+}