Untitled
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
#include <iostream> #include <cuda_runtime.h> #define N 100 #define C 5000 __global__ void knapsack(int n, int c, int *v, int *w, int *x, int *max_value) { int i = blockIdx.x * blockDim.x + threadIdx.x; int j, k; int dp[N+1][C+1]; for (j = 0; j <= c; j++) { dp[0][j] = 0; } for (i = 1; i <= n; i++) { for (j = 0; j <= c; j++) { if (j < w[i]) { dp[i][j] = dp[i-1][j]; } else { dp[i][j] = max(dp[i-1][j], dp[i-1][j-w[i]] + v[i]); } } } *max_value = dp[n][c]; } int main() { int n = 5; // Number of items int c = 10; // Knapsack capacity int v[] = {0, 6, 3, 5, 4, 6}; // Values of items int w[] = {0, 2, 2, 6, 5, 4}; // Weights of items int x[N+1] = {0}; // Selected items int max_value = 0; // Maximum value // Allocate memory on GPU int *d_v, *d_w, *d_x, *d_max_value; cudaMalloc((void**)&d_v, (n+1)*sizeof(int)); cudaMalloc((void**)&d_w, (n+1)*sizeof(int)); cudaMalloc((void**)&d_x, (N+1)*sizeof(int)); cudaMalloc((void**)&d_max_value, sizeof(int)); // Copy data from host to device cudaMemcpy(d_v, v, (n+1)*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(d_w, w, (n+1)*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(d_x, x, (N+1)*sizeof(int), cudaMemcpyHostToDevice); // Run kernel knapsack<<<1,1>>>(n, c, d_v, d_w, d_x, d_max_value); // Copy data from device to host cudaMemcpy(&max_value, d_max_value, sizeof(int), cudaMemcpyDeviceToHost); // Print result std::cout << "Maximum value: " << max_value << std::endl; // Free memory on GPU cudaFree(d_v); cudaFree(d_w); cudaFree(d_x); cudaFree(d_max_value); return 0; }