Реализация пересечения со стеками связанных списков. - PullRequest
0 голосов
/ 28 марта 2012

Привет, у меня есть домашнее задание, где мне нужно в течение двух часов пересечь две улицы с одной полосой движения. Мне нужно отрегулировать фазировку, чтобы в идеале получалось менее 5 машин в очередь, 9 тоже приемлемо.

Все это работает, за исключением того, что что-то не так с тем, как реализована моя поэтапность, и я просто не могу разобраться в проблеме. Абсолютно лучшее, что я могу получить - это одна очередь 0 или 1, а другая 40+. Кажется, я не могу получить их обоих до 9. У меня проблема с фазовыми проверками, но я не могу придумать, как это исправить. Я понимаю, что хочу немного отдать предпочтение Q1, так как машины прибывают на него немного быстрее, чем Q2.

Заранее спасибо за любую помощь.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

struct Node {
    int data;
    Node *next;
};

class Queue {
private:                         
    Node *listpointer;
public:                          
    Queue();
    ~Queue();
    void push(int newthing);
    void pop();
    int top();
    bool isEmpty();
    int queueCount();
    void Queue::popTwo();
    bool Queue::twoOrMore();
};

Queue::Queue() {
//constructor
    listpointer = NULL;
}

Queue::~Queue() {
//destructor

}

void Queue::push(int newthing) {
//place the new thing on top of the Queue
    Node *temp;
    temp = new Node;             
    temp->data = newthing;
    temp->next = listpointer;
    listpointer = temp;
}

void Queue::pop() {
//remove top item from the Queue
    Node *p;
    p = listpointer;
    if (listpointer != NULL) {
        listpointer = listpointer->next;
        delete p;  
  }
}

int Queue::top() {
//return the value of the top item
    return listpointer->data;
}

bool Queue::isEmpty() {
//returns true if the Queue is empty
    if (listpointer == NULL) {
        return true;
    }
    return false;
}

int Queue::queueCount() {
    Node *temp;
    int count = 0;
    temp = listpointer;
    while (temp != NULL) {
        ++count;
        temp = temp->next;
    }
    return count;
    delete temp;
}

void Queue::popTwo() {
// remove the 2 top items from the stack
    Node *p;
    p = listpointer;
    if (listpointer != NULL) {
        listpointer = listpointer->next;
        delete p;
    }
    p = listpointer;
    if (listpointer != NULL) {
        listpointer = listpointer->next;
        delete p;                
    }
}

bool Queue::twoOrMore() {
// return true if the stack has at least two items
    if(listpointer==NULL || listpointer->next==NULL) return false;
    else return true;
}

//implement/copy your queue structure and functions above
//then, declare two instances:
//Queue Q1, Q2;
//if you want, make a separate function to change the 
//signals between the queues (either green or red)
//When the signal changes, one queue only is allowed to delete elements

Queue Q1, Q2;

int Q1phase = 30; //initial attempt
int Q2phase = 60; //initial attempt
const int Q1arrive = 18; //fixed 
const int Q2arrive = 22; //fixed
const int leave_rate = 10; //fixed, one car leaves either queue every 10 seconds

int car_id=0;
int clock=0;
bool Q1_green, Q2_green; //indicates which queue is opened, only one at a time

int main(int argc, char **argv) {
    //if(argc!=3) {printf("needs: Q1phase Q2phase\n"); exit(0); }
    //Q1phase=atoi(argv[1]);
    //Q2phase=atoi(argv[2]);
    if(Q1phase < 30 || Q2phase < 30) {printf("Minimum time for each queue to be closed is 30 seconds\n"); exit(0);}
    clock = 0;
    car_id = 0;
    Q1_green = true;
    Q2_green = false;
    int length_Q1, length_Q2;
    length_Q1 = 0;
    length_Q2 = 0;

    while (clock < 7200) {
        clock++;
        if (clock % Q1arrive == 0) {
            car_id++;
            //car_id join Q1
            Q1.push(car_id);
            length_Q1 = Q1.queueCount();
        }
        if (clock % Q2arrive == 0) {
            car_id++;
            //or car_id join Q2
            Q2.push(car_id);
            length_Q2 = Q2.queueCount();
        }

        if ((clock % Q1phase == 0) || (clock % Q2phase == 0)) {
            if (Q1_green == true) {
                Q1_green = false;
                Q2_green = true;
            } else {
                Q1_green = true;
                Q2_green = false;
            }
        }

        if (clock % leave_rate == 0) {
            if (Q1_green == true) {
                Q1.pop();
                length_Q1 = Q1.queueCount();
            }

            if (Q2_green == true) {
                Q2.pop();
                length_Q2 = Q2.queueCount();
            }
        }

    //ChangeSignal();//every second, check if it is time to change signals (phasing is important!)
    //After the signal change:
    //verify which queue is opened
    //either Q1 or Q2 will have the chance to delete one element (Q.Leave())
    //
    printf("at time %d:\nthe current length of Q1 is %d\n",clock,length_Q1);
    printf("the current length of Q2 is %d\n", length_Q2);
    //at the end of the simulation, both queues should have few cars
  }
}

1 Ответ

0 голосов
/ 28 марта 2012

Ваша общая норма прибытия превышает норму отпуска, поэтому автомобили должны будут отставать.

Общая скорость прибытия составляет 1/22 + 1/18 =~ 0.1010 машины / сек.Это превышает скорость отпуска 0.1 автомобилей в секунду.

Свет меняется каждые 30 секунд (Q1phase), потому что Q2phase кратно Q1phase.Таким образом, в основном очереди имеют одинаковый рабочий цикл.

Автомобили сливаются из каждой очереди с половиной общей скорости: 0,05 из одной очереди, 0,05 из другой (1/20).

Обратите внимание, что коэффициент отпуска 1/20 меньше 1/18.Таким образом, очередь с прибытием 1/18 будет отставать.Процент отпусков 1/20 больше, чем 1/22, поэтому очередь с коэффициентом прибытия 1/22 не будет отставать.

Эта небольшая разница на самом деле невелика!Существует большая разница между частотой прибытия, превышающей отпуск или не превышающей отпуск.


О, и вот как рассчитать количество автомобилей в очереди отставания:

Скорость прибытия: 1/18.Норма отпуска: 1/20 (половина от 1/10) Общее время: 7200 секунд:

7200 * (1/18) - 7200 * (1/20) == ????

:)

...