Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- #include<math.h>
- typedef struct {
- int cost;
- int weight;
- char description[19];
- }Bag;
- typedef struct Node {
- Bag bag;
- Node *link;
- }Node;
- Node *myStack[1000];
- void push(Bag inBag, int location) {
- Node *ptr = new Node;
- ptr->bag = inBag;
- if (myStack[location] != NULL) {
- ptr->link = myStack[location];
- myStack[location] = ptr;
- }
- else {
- myStack[location] = ptr;
- }
- }
- void pop(int location) {
- if (myStack[location] == NULL) {
- printf("Stack is empty at location %d", location);
- }
- else {
- Node *ptr = myStack[location];
- myStack[location] = myStack[location]->link;
- free(ptr);
- ptr = NULL;
- }
- }
- int main() {
- while (true) {
- //-1 = add a bag
- //0 = exit
- //1 = buy a bag
- int updateType;
- scanf("%d", &updateType);
- if (updateType == -1) {
- // if -1, customer is buying
- // Take 3 positive ints k, m, c
- // k = location
- // m = cost
- // c = carrying capacity
- int k, m, c;
- scanf("%d %d %d", &k, &m, &c);
- // Look at the top of the stack and see if
- // customer can carry and afford top bag
- // if so, take the top bag
- int p = 0;
- while (myStack[k] != NULL) {
- Bag myBag = myStack[k]->bag;
- if (myBag.cost < m && myBag.weight < c) {
- push(myBag, -1); //use -1 for temp storage
- p += myBag.cost;
- m -= myBag.cost;
- c -= myBag.weight;
- pop(k);
- }
- else {
- break;
- }
- }
- printf("%d ", p);
- while (myStack[-1] != NULL) {
- printf("%s ", myStack[-1]->bag.description);
- pop(-1);
- }
- }
- else if (updateType == 1) {
- //if 1, customer is dropping off
- // Take 2 positive ints k and n
- // k = location
- // n = # of bags
- int k, n;
- scanf("%d %d", &k, &n);
- // for n # of times, get ints m and w and string description
- // m = cost
- // w = weight
- // for each bag, add to stack
- for (int i = 0; i < n; i++) {
- int m = 0, w = 0;
- char desc[19];
- scanf("%d %d %s", &m, &w, &desc);
- Bag newBag;
- newBag.cost = m;
- newBag.weight = w;
- strcpy(newBag.description, desc);
- push(newBag, k);
- }
- }
- else if (updateType == 0) {
- break;
- }
- else {
- printf("Input can only be -1,0,1");
- }
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement