Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<conio.h>
- #include<process.h>
- int n, w[10],p[10],M;
- void knapsack();
- int max(int, int);
- void main()
- {
- int i,j;
- clrscr();
- printf("Enter no. of items \n(How many items do you wnt to get recharged for ?)");
- scanf("%d",&n);
- printf("Enter the weigths \n(Supply the recharge plans here to the program)")
- for(i=1;i<=n;i++)
- {
- scanf("%d", &w[i]);
- }
- printf("Enter profit for each item \n(enter the validity or how much ever talktime you get by the plan)");
- for(i=1;i<=n;i++)
- {
- scanf("%d", &p[i]);
- }
- printf("Enter the knapsack's capacity(User budget)");
- scanf("%d", &M);
- knpasck();
- getch();
- }
- void knapsack()
- {
- int v[10][10],i,j;
- for(i=0; i<=n;i++)
- {
- for(j=0;j<M;j++)
- {
- if(i==0||j==0)
- {
- v[i][j]=0;
- }
- else if(j-w[i]<0)
- {
- v[i][j]=v[i-1][j];
- }
- else
- {
- v[i][j]=max(v[i-1][j],p[i]+v[i-1][j-w[i]]);
- }
- }
- }
- printf("Matrix is \n ");
- for(i=0;i<=n;i++)
- {
- for(j=0;j<=M;j++)
- {
- printf("%d\t",v[i][j]);
- }
- printf("\n");
- }
- printf("Optimal solution is =%d",v[n][m]);//the last element shown in the matrix i.e. the total amount used from the given budget
- }
- int max(int x, int y)
- {
- if(x>y)
- {
- return x;
- }
- else
- {
- return y;
- }
- }
- /* Give this as input
- Obtain optimal solution of the given table
- _______________________
- |item | weight |profit|
- -----------------------
- 1 | 2 |12 |
- 2 | 1 |10 |
- 3 | 3 |20 |
- 4 | 2 |15 |
- -----------------------
- Your input to the program should be a 2 dimensional maxtrix:-
- 0 0 0 0 0 0
- 0 0 12 12 12 12
- 0 10 12 22 22 22
- 0 10 12 22 30 32
- 0 10 15 25 30 37
- (Last element of this matrix here is the used up budget from the given budget)
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement