Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- typedef struct{
- float valor;
- int peso;
- }item;
- float mat[1000][1000];
- int contador = 0;
- void iniciar_matriz();
- void imprimir(int n, int m);
- void cadastrar_itens(int n, item v[]);
- float maior(float a, float b);
- float mochila(int n, item v[], int peso_max);
- int main()
- {
- item v[1000];
- int n;
- int peso_max;
- iniciar_matriz();
- printf("Informe a qtd de itens: ");
- scanf("%d", &n);
- cadastrar_itens(n, v);
- printf("Informe o peso maximo da mochila: ");
- scanf("%d", &peso_max);
- printf("O maior valor que a mochila suporta vale: %f\n", mochila(n, v, peso_max));
- imprimir(n, peso_max);
- printf("Contador: %d\n", contador);
- }
- void iniciar_matriz()
- {
- for(int i = 0; i < 1000; i++)
- {
- for(int j = 0; j < 1000; j++)
- {
- mat[i][j] = 0;
- }
- }
- }
- void imprimir(int n, int m)
- {
- for(int i = 0; i <= n; i++)
- {
- for(int j = 0; j <= m; j++)
- {
- printf("%.2f\t", mat[i][j]);
- }printf("\n");
- }
- }
- void cadastrar_itens(int n, item v[])
- {
- for(int i = 1; i <= n; i++)
- {
- printf("Informe o peso do item: ");
- scanf("%d", &v[i].peso);
- printf("Informe o valor do item: ");
- scanf("%f", &v[i].valor);
- }
- }
- float maior(float a, float b)
- {
- if(a > b)
- {
- return(a);
- }
- else
- {
- return(b);
- }
- }
- float mochila(int n, item v[], int peso_max)
- {
- contador = contador + 1;
- if(n <= 0)
- {
- return(0);
- }
- else
- {
- mat[n-1][peso_max] = mochila(n-1, v, peso_max);
- if(v[n].peso <= peso_max)
- {
- mat[n-1][peso_max - v[n].peso] = v[n].valor + mochila(n - 1, v, peso_max - v[n].peso);
- mat[n][peso_max] = maior(mat[n-1][peso_max - v[n].peso], mat[n-1][peso_max]);
- return( mat[n][peso_max] );
- }
- else
- {
- return(mat[n-1][peso_max]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement