Untitled

 avatar
unknown
plain_text
a year ago
1.6 kB
15
Indexable
#include <iostream>
#include <unordered_map>
#include <vector>
#include <sstream>

using namespace std;

unordered_map<string, pair<int, int>> tokens;  // Stores token_id, {expiration_time, renewal_time}

vector<int> getUnexpiredTokens(int time_to_live, vector<string> queries) {
    vector<int> result;
    for (const string& query : queries) {
        stringstream ss(query);
        string action, token_id;
        int current_time;
        ss >> action >> token_id >> current_time;

        if (action == "generate") {
            tokens[token_id] = {current_time + time_to_live, current_time};
        } else if (action == "renew") {
            if (tokens.find(token_id) != tokens.end() && tokens[token_id].first > current_time) {
                // Token exists and is unexpired, renew it.
                tokens[token_id].first = current_time + time_to_live;
                tokens[token_id].second = current_time;
            }
        } else if (action == "count") {
            int count = 0;
            for (const auto& token : tokens) {
                if (token.second.first > current_time) {
                    count++;
                }
            }
            result.push_back(count);
        }
    }
    return result;
}

int main() {
    int time_to_live = 5;
    vector<string> queries = {"generate aaa 1", "renew aaa 2", "count 6", "generate bbb 7", "renew aaa 8", "renew bbb 10", "count 15"};
    vector<int> result = getUnexpiredTokens(time_to_live, queries);
    
    for (int count : result) {
        cout << count << " ";
    }
    cout << endl;

    return 0;
}