Skip to content

Feedback #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: feedback
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

## 1. Информация о студенте

**Номер группы**: 00-000
**Номер группы**: 11-101

**Фамилия и Имя**: Иванов Иван
**Фамилия и Имя**: Вергасов Шамиль

## 2. Описание задания

Expand Down
6 changes: 3 additions & 3 deletions src/bits.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
namespace assignment {

bool is_bit_set(int mask, int pos) {
assert(mask >= 0 && pos >= 0 && pos < 30);
return false;
assert(mask >= 0 && pos >= 0 && pos < 30); // pos < макс. кол-ва бит в маске
return ((mask & (1 << pos)) != 0);
}

int set_bit(int mask, int pos) {
assert(mask >= 0 && pos >= 0 && pos < 30);
return 0;
return (mask | (1 << pos));
}

std::vector<int> mask2indices(const std::vector<int>& elems, int mask) {
Expand Down
8 changes: 6 additions & 2 deletions src/knapsack/backtracking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,17 @@ namespace assignment {

// ... если текущая "польза" максимальна, обновляем наилучшую "пользу"
if (profit > best_profit) {
// ...
best_profit_mask = mask;
best_profit = profit;
}

// рассматриваем следующий элемент
index += 1;
solve(profits, weights, capacity, index, set_bit(mask, index), weight + weights[index], profit + profits[index],
best_profit, best_profit_mask);
solve(profits, weights, capacity, index, mask, weight, profit, best_profit, best_profit_mask);

// ... рекурсивные вызовы со включением/исключением следующего элемента
}

} // namespace assignment
} // namespace assignment
9 changes: 8 additions & 1 deletion src/knapsack/bit_masking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ namespace assignment {
const int curr_weight = sum_helper(masked_weights);

// ... обработка случая превышения емкости рюкзака
if (curr_weight > capacity) {
continue;
}

// массив из "пользы" рассматриваемых элементов
const auto masked_profits = mask2elems(profits, mask);
Expand All @@ -42,11 +45,15 @@ namespace assignment {
const int curr_profit = sum_helper(masked_profits);

// ... обработка случая нахождения большего значения "пользы"
if (curr_profit > best_profit) {
best_profit = curr_profit;
best_profit_mask = mask;
}
}

// ... возвращение итогового результата: используйте mask2indices;

return {};
return mask2indices(profits, best_profit_mask);
}

} // namespace assignment
8 changes: 6 additions & 2 deletions src/subset_sum/backtracking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ namespace assignment {
}

// Ограничение 1: текущая сумма должна быть меньше целевой
if (true /* ... */) {
if (sum > target_sum) {
// если превысили целевую сумму, то сделать ее меньше уже не получится (все элементы множества положительные)
return;
}

// Ограничение 2: "остаточная сумма" + "текущая сумма" должны быть больше или равны "целевой сумме"
if (true /* ... */) {
if (sum + residual < target_sum) {
// сумму невозможно будет набрать с оставшимися элементами множества
return;
}
Expand All @@ -47,6 +47,8 @@ namespace assignment {
if (sum == target_sum) {
// ... сохранение в результат
// ... нужно ли в этой ветке рекурсии рассматривать следующие элементы?
indices.push_back(mask2indices(set, mask));
return;
}

// рассматриваем следующий элемент
Expand All @@ -56,6 +58,8 @@ namespace assignment {
residual -= set[index];

// рекурсивный вызов со включением/исключением элемента с текущим индексом ...
search(set, index, set_bit(mask, index), sum + set[index], residual, target_sum, indices);
search(set, index, mask, sum, residual, target_sum, indices);
}

} // namespace assignment
16 changes: 16 additions & 0 deletions src/subset_sum/bit_masking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,22 @@ namespace assignment {
// 2. Внутренний цикл: проверка разрядов битовой маски и генерация подмножества, ассоциирующегося с этой маской
// 3. Подсчет суммы текущего подмножества, сохранение индексов подмножества с целевой суммой в результат
// Tips: можно пропустить итерацию, если сумма текущего подмножества стала больше целевой суммы
int sum;

for (int mask = 0; mask < num_subsets; mask++) {
sum = 0;
for (int pos = 0; pos < num_elems; pos++) {
if (is_bit_set(mask, pos)) {
sum += set[pos];
if (sum > target_sum) {
break;
}
}
}
if (sum == target_sum) {
indices.push_back(mask2indices(set, mask));
}
}

return indices;
}
Expand Down
4 changes: 3 additions & 1 deletion src/subsets/backtracking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ namespace assignment {
// Ограничение: рассмотрены все элементы множества
if (index == static_cast<int>(set.size()) - 1) {

// ... сохранение полученного подмножества
subsets.push_back(mask2indices(set, mask));

return; // возвращаемся по дереву рекурсии
}
Expand All @@ -37,6 +37,8 @@ namespace assignment {

// здесь должны быть рекурсивные вызовы ...
// включаем или не включаем элемент с текущим индексом в подмножество (используя битовую маску)
generate(set, index, mask, subsets);
generate(set, index, set_bit(mask, index), subsets);
}

} // namespace assignment
10 changes: 7 additions & 3 deletions src/subsets/bit_masking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ namespace assignment {
// выделяем память
auto subsets = std::vector<std::vector<int>>(num_subsets);

// 1. Внешний цикл: пробегаемся по всем битовым маскам от 0..00 до 1..11
// 2. Внутренний цикл: проверка разрядов битовой маски и генерация подмножества, ассоциирующегося с этой маской
// Tips: для проверки разряда бита на 1 (единицу) используйте функцию is_bit_set
for (int mask = 0; mask < num_subsets; mask++) {
for (int pos = 0; pos < num_elems; pos++) {
if (is_bit_set(mask, pos)) {
subsets[mask].push_back(pos);
}
}
}

return subsets;
}
Expand Down