#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define POP_SIZE 60
#define MAX_ITER 2000
#define DIM 6
#define MAX_K 10
int w[DIM] = {2, 2, 3, 1, 5, 2};
int v[DIM] = {2, 3, 1, 5, 4, 3};
int k = 10;
typedef struct {
int position[DIM];
int velocity[DIM];
int best_position[DIM];
int best_value;
} Particle;
int fitness(int position[DIM]) {
int total_weight = 0;
int total_value = 0;
for (int i = 0; i < DIM; i++) {
if (position[i] == 1) {
total_weight += w[i];
total_value += v[i];
}
}
if (total_weight > k) {
return 0;
}
return total_value;
}
void pso() {
Particle particles[POP_SIZE];
int global_best_position[DIM];
int global_best_value = 0;
srand(time(NULL));
for (int i = 0; i < POP_SIZE; i++) {
for (int j = 0; j < DIM; j++) {
particles[i].position[j] = rand() % 2;
particles[i].velocity[j] = rand() % 2 - 1;
}
particles[i].best_value = fitness(particles[i].position);
for (int j = 0; j < DIM; j++) {
particles[i].best_position[j] = particles[i].position[j];
}
if (particles[i].best_value > global_best_value) {
global_best_value = particles[i].best_value;
for (int j = 0; j < DIM; j++) {
global_best_position[j] = particles[i].best_position[j];
}
}
}
for (int iter = 0; iter < MAX_ITER; iter++) {
for (int i = 0; i < POP_SIZE; i++) {
for (int j = 0; j < DIM; j++) {
particles[i].velocity[j] = (rand() % 2 - 1) + (rand() % 2 - 1);
particles[i].position[j] = particles[i].position[j] + particles[i].velocity[j];
if (particles[i].position[j] < 0) particles[i].position[j] = 0;
if (particles[i].position[j] > 1) particles[i].position[j] = 1;
}
int current_value = fitness(particles[i].position);
if (current_value > particles[i].best_value) {
particles[i].best_value = current_value;
for (int j = 0; j < DIM; j++) {
particles[i].best_position[j] = particles[i].position[j];
}
}
if (particles[i].best_value > global_best_value) {
global_best_value = particles[i].best_value;
for (int j = 0; j < DIM; j++) {
global_best_position[j] = particles[i].best_position[j];
}
}
}
}
printf("最优解:\n");
printf("选择的箱子: ");
for (int i = 0; i < DIM; i++) {
if (global_best_position[i] == 1) {
printf("%d ", i + 1);
}
}
printf("\n总价值: %d\n", global_best_value);
}
int main() {
pso();
return 0;
}