74 lines
1.5 KiB
C++

#ifndef SIMULATED_ANNEALING_HEADER_12647_H
#define SIMULATED_ANNEALING_HEADER_12647_H
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
namespace sa {
class solution {
std::vector<long long> items;
std::default_random_engine gen;
int capacity;
int fitness;
auto calculate_boxes()->int {
int count = 0;
long long now = 0;
for (auto i : items) {
if (now + i > capacity) {
count++;
now = i;
continue;
}
now += i;
}
return count;
}
public:
solution() = default;
solution(const std::vector<long long> &items, int capacity): // Gera a solução inicial
items(items), gen(std::random_device()()), capacity(capacity),
fitness(calculate_boxes()) {}
void setneighbor() { // Gera um vizinho da solução
std::uniform_int_distribution<> dist(0, items.size() - 1);
int first = dist(gen);
int second = 0;
while ((second = dist(gen)) == first) {}
std::swap(items[first], items[second]);
fitness = calculate_boxes();
}
void randomize() {
std::shuffle(items.begin(), items.end(), gen);
fitness = calculate_boxes();
}
void swap(solution &other) {
std::swap(fitness, other.fitness);
std::swap(items, other.items);
std::swap(capacity, other.capacity);
std::swap(gen, other.gen);
}
void print_sol() {
std::cout << "Número de caixas: " << fitness << '\n';
}
static auto simulated_annealing(int cap, const std::vector<long long> &initial,
double alpha, double temp)->solution;
};
} // namespace sa
#endif