示例#1
0
 string topoSort(unordered_map<char, unordered_set<char>>& graph, unordered_map<char, int>& mp) {
     // For chars without any incoming edges, we output it as the start of the string.
     string res = "";
     while (!mp.empty()) {
         bool found = false;
         
         for (auto& pair : mp) {
             if (pair.second == 0) {
                 res.push_back(pair.first);
                 for (auto& nn : graph[pair.first]) {
                     mp[nn]--;
                 }
                 graph.erase(pair.first);
                 mp.erase(pair.first);
                 found = true;
                 break;
             }
         }
         
         if (!found) {
             res.clear();
             return res;
         }
     }
     return res;
 }
示例#2
0
文件: MidiDevice.hpp 项目: analoq/seq
  shared_ptr<Event> read()
  {
    uint8_t buffer_in[3];
    snd_rawmidi_read(handle_in, &buffer_in, 3);

    shared_ptr<NoteOnEvent> note_on, note_off;

    switch ( buffer_in[0] & 0xF0 )
    {
      case MIDI_NOTE_ON:
        if ( buffer_in[2] )
        {
          note_on = shared_ptr<NoteOnEvent>(new NoteOnEvent { buffer_in[1], buffer_in[2] });
          open_notes.emplace(buffer_in[1], note_on);
          return note_on;
        }
        else
        {
          note_on = open_notes.at(buffer_in[1]);
          open_notes.erase(buffer_in[1]);
          return shared_ptr<Event>(new NoteOffEvent { note_on });
        }

      case MIDI_NOTE_OFF:
        note_on = open_notes.at(buffer_in[1]);
        open_notes.erase(buffer_in[1]);
        return shared_ptr<Event>(new NoteOffEvent { note_on });

      case MIDI_CONTROL:
        return shared_ptr<Event>(new ControlEvent { static_cast<ControlEvent::Controller>(buffer_in[1]), buffer_in[2] });
      
      default:
        return shared_ptr<Event>(new Event {});
    }
  }
示例#3
0
 bool dfs(string& pattern, int pstart, unordered_map<char, string>& p2s, string& str, int sstart, unordered_map<string, char>& s2p) {
     if (pstart == pattern.size() || sstart == str.size()) {
         return pstart == pattern.size() && sstart == str.size();
     }
     char ch = pattern[pstart];
     if (p2s.find(ch) != p2s.end()) {
         int len = p2s[ch].size();
         string temp = str.substr(sstart, len);
         if (temp == p2s[ch] && s2p.find(temp) != s2p.end() && s2p[temp] == ch)
             return dfs(pattern, pstart+1, p2s, str, sstart+len, s2p);
         else
             return false;
     } else {
         for (int i = sstart; i < str.size(); i++) {
             string temp = str.substr(sstart, i - sstart + 1);
             if (s2p.find(temp) != s2p.end())
                 continue;
             p2s[ch] = temp;
             s2p[temp] = ch;
             if (dfs(pattern, pstart+1, p2s, str, i+1, s2p))
                 return true;
             p2s.erase(ch);
             s2p.erase(temp);
         }
         return false;
     }
 }
示例#4
0
文件: plain.cpp 项目: exi/plainfs
static int plain_release (const char *path, struct fuse_file_info *fi) {
    boost::mutex::scoped_lock lock(io_mutex);
    if (tempFiles.find(string(path))!=tempFiles.end()) { // not already in temp list
        TempFile* file = tempFiles.find(string(path))->second;

        if (file == NULL) {
            tempFiles.erase(string(path));
        } else {
            if (file->written) {
                struct stat stats;
                stats.st_mode = S_IFREG | 0444;
                stats.st_nlink = 1;
                stats.st_size = file->data.size();

                // evil hack, use the underlying c array pointer...
                store->addFile(file->name.substr(1), stats, &(file->data[0]));

                delete file;
                tempFiles.erase(string(path));
            } else {
                cout<<"release file was not written"<<endl;
            }
        }
    } else {
        return -ENOENT;
    }

    return 0;
};
 bool isMatch(string & pattern, string & str, 
             int start_pattern_idx, int start_str_idx,
             unordered_map<char, string> forward_mapping,
             unordered_map<string, char> backward_mapping){
     if(start_pattern_idx >= pattern.length() && start_str_idx>= str.length())
         return true;
     if(start_pattern_idx >= pattern.length() || start_str_idx >= str.length())
         return false;
     char pc = pattern[start_pattern_idx];
     bool inserted_forward = false, inserted_backward = false;
     for(int len=1; len<=str.length()-start_str_idx; len++){
         string s = str.substr(start_str_idx, len);
         if(forward_mapping.find(pc)==forward_mapping.end()){
             forward_mapping[pc] = s;
             inserted_forward = true;
         }else{
             if(forward_mapping[pc]!=s) continue;
         }
         if(backward_mapping.find(s)==backward_mapping.end()){
             backward_mapping[s] = pc;
             inserted_backward = true;
         }else{
             if(backward_mapping[s]!=pc) return false;
         }
         if(isMatch(pattern, str, start_pattern_idx+1, start_str_idx+len, forward_mapping, backward_mapping)){
             return true;
         }
         if(inserted_forward) forward_mapping.erase(pc);
         if(inserted_backward) backward_mapping.erase(s);
     }
     return false;
 }
示例#6
0
文件: 146.LRU.cpp 项目: wxn7/Leetcode
 void set(int key, int value) {
     t++;
     
     //already in cache, just update timestamp and value
     if (key_value.count(key)) {
         key_time[key] = t;
         key_value[key] = value;
     }
     else {
         if (pq.size() >= cap) {
             while (pq.top().time != key_time[pq.top().key]) { 
                 Elem x = pq.top();
                 x.time = key_time[x.key];
                 pq.pop();
                 pq.push(x);
             }
             
             int oldKey = pq.top().key;
             key_value.erase(oldKey);
             key_time.erase(oldKey);
             pq.pop();
         }
         
         //insert
         key_value[key] = value;
         key_time[key] = t;
         pq.push(Elem{t, key});
     }
 }
示例#7
0
    void put(int key, int value) {

        auto it = db.find(key);
        auto iter = itcache.find(key);
        if(it!=db.end()) {

            (it->second.second)++;
            it->second.first = value;
            int newfreq = it->second.second;
            int curfreq = newfreq-1;
            cache[curfreq].erase(iter->second);
            cache[newfreq].push_front(key);
            itcache[key] = cache[newfreq].begin();
            return;
        }

        if(itcache.size() == n) {

            if(cache[minfreq].size() == 0)
                return;

            int keytodel = cache[minfreq].back();
            cache[minfreq].pop_back();
            itcache.erase(keytodel);
            db.erase(keytodel);

        }

        minfreq = 1;
        db[key] = make_pair(value, 1);
        cache[1].push_front(key);
        itcache[key] = cache[1].begin();
    }
 bool match(string &pattern, int i, string &str, int j) {
     int m = pattern.size(), n = str.size();
     if (i == m && j == n) {
         return true;
     } else if (i == m || j == n) {
         return false;
     }
     
     bool pairFound = false;
     for (int k = j; k < n; k++) {
         string word = str.substr(j, k-j+1);
         char p = pattern[i];
         
         if (p2w.find(p) != p2w.end()) {
             if (p2w[p] != word) continue;
         } else if (w2p.find(word) != w2p.end()) {
             if (w2p[word] != p) continue;
         } else {
             p2w[p] = word;
             w2p[word] = p;
             pairFound = true;
         }
         
         // DFS
         if (match(pattern, i+1, str, k+1)) return true;
         
         // backtrack
         if (pairFound) {
             p2w.erase(p);
             w2p.erase(word);
         }
     }
     
     return false;
 }
示例#9
0
uint16_t update_window(const Packet &p, unordered_map<uint16_t, Packet_info> &window, uint16_t &base_num, RTO &rto)
{
    uint16_t n_removed = 0;

    while (base_num > p.ack_num())
    {
        auto found = window.find(base_num);
        if (found == window.end())
        {
            cerr << "could not find base_num packet with base_num " << base_num << " and ack num " << p.ack_num() << " in window, update_window" << endl;
            exit(1);
        }
        rto.update_RTO(found->second.get_time_sent());
        uint16_t len = found->second.data_len();
        window.erase(base_num);
        n_removed += len;
        base_num = (base_num + len) % MSN;
    }
    while (base_num < p.ack_num())
    {
        auto found = window.find(base_num);
        if (found == window.end())
        {
            cerr << "could not find base_num packet with base_num " << base_num << " and ack num " << p.ack_num() << " in window, update_window" << endl;
            exit(1);
        }
        rto.update_RTO(found->second.get_time_sent());
        uint16_t len = found->second.data_len();
        window.erase(base_num);
        n_removed += len;
        base_num = (base_num + len) % MSN;
    }

    return n_removed;
}
示例#10
0
 void erase_last()
 {
     if(lru.size()>cap)
     {
         int temp = lru.back();
         lru.pop_back();
         dic.erase(temp);
         key_loc.erase(temp);
     }
 }
 int longestConsecutivex(vector<int>& nums) {
     int maxLength = 0;
     
     
     for(int i = 0; i < nums.size(); i++){
         int startRange = nums[i] + 1;
         int endRange = nums[i]-1;
         
         if(startMap[nums[i]] || endMap[nums[i]])
             continue;
         
         if(startMap[startRange] || endMap[endRange]){
             Range* pSr = startMap[startRange];
             Range* pEr = endMap[endRange];
             if(pSr){
                 pSr->start = nums[i];
                 pSr->count++;
                 startMap.erase(startRange);
                 startMap[nums[i]] = pSr;
                 maxLength = max(maxLength, pSr->count);
             }
             
              if(pEr){
                 pEr->end = nums[i];
                 pEr->count++;
                 endMap.erase(endRange);
                 endMap[nums[i]] = pEr;
                 maxLength = max(maxLength, pEr->count);
             }
             
             if(pSr && pEr){
                 pEr->end = pSr->end;
                 pEr->count = pEr->count + pSr->count - 1;
                 startMap.erase(nums[i]);
                 endMap.erase(nums[i]);
                 endMap[pEr->end] = pEr;
                 delete pSr;
                 maxLength = max(maxLength, pEr->count);
             }
         }
         else{
             Range* pR = new Range;
             pR->start = nums[i];
             pR->end = nums[i];
             pR->count = 1;
             maxLength = max(maxLength, pR->count);
             
             startMap[nums[i]] = pR;
             endMap[nums[i]] =  pR;
         }
     }
     
     return maxLength;
 }
示例#12
0
 void set(int key, int value) {
     if (key2value.count(key) == 0 && capacity == key2value.size()){
         key2value.erase(time2key.begin()->second);
         key2time.erase(time2key.begin()->second);
         time2key.erase(time2key.begin());
     }
     if (key2value.count(key) > 0){
         time2key.erase(key2time[key]);
     }
     key2value[key] = value;
     time2key[id] = key;
     key2time[key] = id;
     id++;
 }
示例#13
0
 bool helper(string &pat, int i, string &str, int j, unordered_map<char,string> &m1, unordered_map<string,char> &m2){
     if(i==pat.size() && j==str.size()){
         return true;
     }
     
     if(i==pat.size() || j==str.size()){
         return false;
     }
     
     
     char c = pat[i];
     
     if(m1.find(c)!=m1.end()){
         //pattern c is already exist
         string s=m1[c];
         
         if(s!=str.substr(j,s.size())){
             return false;
         }
         
         // match c, yeah , go forward
         return helper(pat,i+1,str,j+s.size(),m1,m2);
         
     }else{
         // pattern c is not exist
         // try to match it with str[i...end] use backtracking
         for(int k=j; k<str.size(); k++){
             string s = str.substr(j,k-j+1);
             
             if(m2.find(s)!=m2.end()){
                 if(m2[s]!=c){
                     continue;
                 }
             }
             
             //use it as a match 
             m1[c]=s;
             m2[s]=c;
             if(helper(pat,i+1,str,k+1,m1,m2)){
                 return true;
             }
             
             //backtracking
             m1.erase(c);
             m2.erase(s);
         }
     }
    
     return false;
 }
示例#14
0
 void put(int key, int value) {
     if (hash.find(key) == hash.end()) {
         if (hash.size() == n) {
             hash.erase(order.front());
             iters.erase(order.front());
             order.pop_front();
         }
     } else {
         order.erase(iters[key]);
     }
     order.push_back(key);
     iters[key] = --(order.end());
     hash[key] = value;
 }
示例#15
0
void Buildings::updateBuildings(color_ostream& out, void* ptr)
{
    int32_t id = (int32_t)ptr;
    auto building = df::building::find(id);

    if (building)
    {
        // Already cached -> weird, so bail out
        if (corner1.count(id))
            return;
        // Civzones cannot be cached because they can
        // overlap each other and normal buildings.
        if (!building->isSettingOccupancy())
            return;

        df::coord p1(min(building->x1, building->x2), min(building->y1,building->y2), building->z);
        df::coord p2(max(building->x1, building->x2), max(building->y1,building->y2), building->z);

        corner1[id] = p1;
        corner2[id] = p2;

        for ( int32_t x = p1.x; x <= p2.x; x++ ) {
            for ( int32_t y = p1.y; y <= p2.y; y++ ) {
                df::coord pt(x,y,building->z);
                if (containsTile(building, pt, false))
                    locationToBuilding[pt] = id;
            }
        }
    }
    else if (corner1.count(id))
    {
        //existing building: destroy it
        df::coord p1 = corner1[id];
        df::coord p2 = corner2[id];

        for ( int32_t x = p1.x; x <= p2.x; x++ ) {
            for ( int32_t y = p1.y; y <= p2.y; y++ ) {
                df::coord pt(x,y,p1.z);

                auto cur = locationToBuilding.find(pt);
                if (cur != locationToBuilding.end() && cur->second == id)
                    locationToBuilding.erase(cur);
            }
        }

        corner1.erase(id);
        corner2.erase(id);
    }
}
示例#16
0
		void set(int key, int value) {
			auto temp_iter = page_map.find(key);
			if(temp_iter != page_map.end()){
				virtual_page.erase(temp_iter->second);
				page_map.erase(key);
			}else if(list_length == capacity){
				page_map.erase(virtual_page.back().first);
				virtual_page.pop_back();
			}else{
				list_length++;
			}
			// update the list
			virtual_page.insert(virtual_page.begin(), pair<int, int>(key, value));
			page_map[key] = virtual_page.begin();
		} 
void MatchingEngine::remove_node(Order * const order)
{
				// if *order is tail or head
				if (order == _head)
				{
								_head = order->next;
								if ( _head != NULL)
								{
									_head->prev = NULL;
								}
				}
				else if (order == _tail)
				{
								_tail = order->prev;
								_tail->next = NULL;
				}else{
					order->prev->next = order->next;
					order->next->prev = order->prev;
				};
				delete order;
				// remove order_lookup
				order_lookup.erase(order_lookup.find(order->oid));
				return;

};
示例#18
0
int simplifyTree(vector<Node*>& tree,
                 int nodeindex,
                 unordered_map<int,bool>& pred_res) {
    Node* node = tree[nodeindex];

    if (!node->isChoice) {
        return nodeindex;
    }

    ChoiceNode* curr = (ChoiceNode*) node;

    // lift subtree
    if (pred_res.count(curr->pred) != 0) {
        if (pred_res[curr->pred] == true) {
            return simplifyTree(tree, curr->r, pred_res);
        } else {
            return simplifyTree(tree, curr->l, pred_res);
        }
    }

    pred_res[curr->pred] = false;
    int indL = simplifyTree(tree, curr->l, pred_res);
    pred_res[curr->pred] = true;
    int indR = simplifyTree(tree, curr->r, pred_res);
    pred_res.erase(curr->pred);

    curr->l = indL;
    curr->r = indR;
    return nodeindex;
}
 ~trieNode() {
     auto node = children.begin();
     while(node != children.end()) {
         delete node->second;
         node = children.erase(node);
     }
 }
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        if (numIdxMap.find(val) == numIdxMap.end())
            return false;

        int idx = numIdxMap[val].back();
        if (idx != (int)nums.size() - 1) {
            int back = nums.back();
            nums[idx] = back;

            vector<int> &backIdxes = numIdxMap[back];
            for (int i = (int)backIdxes.size() - 1; i >= 0; --i) { // cannot use a heap here, because the insert op will be O(logn). But on average it is still O(n)
                if (backIdxes[i] == (int)nums.size() - 1) {
                    backIdxes[i] = idx;
                    break;
                }
            }
        }

        nums.pop_back();
        numIdxMap[val].pop_back();
        if (numIdxMap[val].empty())
            numIdxMap.erase(val);

        return true;
    }
/*Sets the key x with value y in the LRU cache */
void LRUCache::set(int x, int y) 
{
    if(m.count(x)==1)
    {
        node *temp = m[x];
        temp->value = y;
        remove(temp);
        setHead(temp);
    }
    else
    {
        node* n = new node();
        n->key = x;
        n->value = y;
        n->next = n->prev = NULL;
        if(m.size()>=cap)
        {
            m.erase(last->key);
            remove(last);
            setHead(n);
        }
        else
        {
            setHead(n);
        }
        m[x] = n;
    }
}
    /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
    void dec(string key) {
        if (strmap.find(key) == strmap.end()) {
            return;
        } else {
            auto row = strmap[key].first;
            auto col = strmap[key].second;
            if (row->val == 1) {
                row->strs.erase(col);
                if (row->strs.empty()) {
                    matrix.erase(row);
                    strmap.erase(key);
                }
                return;
            }

            auto nextrow = row;
            ++nextrow;
            if (nextrow == matrix.end() || nextrow->val != row->val - 1) {
                auto newrow = matrix.emplace(nextrow, key, row->val - 1);
                strmap[key] = make_pair(newrow, newrow->strs.begin());
            } else {
                auto newrow = nextrow;
                newrow->strs.push_front(key);
                strmap[key] = make_pair(newrow, newrow->strs.begin());
            }
            row->strs.erase(col);
            if (row->strs.empty())
                matrix.erase(row);
        }
    }
示例#23
0
文件: 460.cpp 项目: cenhao/coding
    void put(int key, int value) {
		if (get(key) != -1) {
			auto it = hm.find(key);
			it->second->val = value;
			return;
		}
		if (cap == 0) { return; }
		if (tot == cap) {
			--tot;
			auto *lf = mnf->high;
			auto *lf_i = lf->tail->pre;
			remove_item(lf_i);
			hm.erase(lf_i->key);
			delete lf_i;
		}

		++tot;
		auto *low = mnf->high;
		if (low->f != 1) {
			auto *tmp = new Freq(1);
			add_freq(low, tmp);
			low = tmp;
		}

		auto *item = new Item();
		item->val = value;
		item->key = key;
		add_item(low->head, item);
		hm[key] = item;
    }
示例#24
0
 void set(int key, int value) {
     if (cache.empty()){
         o_key=key;
         y_key=key;
         cache[key].value=value;
         if (debug) print();
         return;
     }
     if (cache.count(key)>0){ //already present
         cache[key].value=value;  //update value
         bool temp_debug=debug;
         debug=0;
         get(key);
         debug=temp_debug;
     }else{
         cache[key].value=value;  //insert entry
         cache[key].older=y_key;
         cache[y_key].younger=key;
         y_key=key;
         if (cache.size()>capacity){ //delete the oldest one
             o_key=cache[o_key].younger;
             cache.erase(cache[o_key].older);
         }
     }
     if (debug) print();
 }
示例#25
0
 void set(int key, int value) {
     auto i = cache.find(key);
     
     if (maxSize == 0)
         return;
     if (i != cache.end()) {
         Item *item = i->second;
         remove(item);
         insert(item);
         item->value = value;
     } else {
         if (currSize == maxSize) {
             // remove at rear
             Item *item = lru.prev;
             //cout << "remove " << item->key << " at rear" << endl;
             remove(item);
             cache.erase(item->key);
             delete item;
             currSize--;
         }
         Item *newItem = new Item(key, value);
         insert(newItem);
         cache.insert(make_pair(key, newItem));
         currSize++;
     }
 }
示例#26
0
 void set(int key, int value) {
     auto it=keymap.find(key);
     if(it!=keymap.end())
     {
         it->second->value=value;
         MoveToHead(it->second);
     }
     else if(len<maxlen)
     {
         Node P(key,value);
         keymap[key]=&P;
         InsertToHead(&P);
         len++;
     }
     else//replace
     {
         Node P(key,value);
         keymap[key]=&P;
         InsertToHead(&P);
         
         keymap.erase(tail.prev->key);
         tail.prev=tail.prev->prev;
         tail->prev->next=&tail;
     }
 }
 /**
  * Removes a value from the collection. Returns true if the collection
  * contained the specified element.
  */
 bool remove(int val) {
     auto it = d_map.find(val);
     if (d_map.end() == it) {
         return false;
     }
     auto victim = it->second.begin();
     int last    = d_vector.back();
     d_vector.pop_back();
     if (last == val) {
         victim = it->second.find(d_vector.size());
         assert(it->second.end() != victim);
     } else {
         int index = *victim;
         d_vector[index] = last;
         unordered_set<int>& set = d_map[last];
         int count = set.erase(d_vector.size());
         assert(1 == count);
         auto p = set.insert(index);
         assert(true == p.second);
     }
     if (it->second.size() == 1) {
         d_map.erase(it);
     } else {
         it->second.erase(victim);
     }
     return true;
 }
    bool wordPatternMatchHelper(const string& pattern, int patternIndex,
                                const string& word, int wordIndex,
                                unordered_map<char, string>& char2StringMap,
                                unordered_set<string>& mappedStringSet) {
        if (patternIndex == (int)pattern.size() && wordIndex == (int)word.size()) return true;
        if (patternIndex == (int)pattern.size() || wordIndex == (int)word.size()) return false;

        for (int i = wordIndex; i < (int)word.size(); ++i) {
            string subWord = word.substr(wordIndex, i-wordIndex+1);
            char p = pattern[patternIndex];
            auto it = char2StringMap.find(p);
            if (it != char2StringMap.end() && it->second == subWord) {
                if (wordPatternMatchHelper(pattern, patternIndex+1, word, i+1, char2StringMap, mappedStringSet)) {
                    return true;
                }
            } else if (it == char2StringMap.end()) {
                if (mappedStringSet.count(subWord)) continue;
                char2StringMap[p] = subWord;
                mappedStringSet.insert(subWord);
                if (wordPatternMatchHelper(pattern, patternIndex+1, word, i+1, char2StringMap, mappedStringSet)) {
                    return true;
                }
                char2StringMap.erase(p);
                mappedStringSet.erase(subWord);
            }
        }

        return false;
    }
示例#29
0
 void set(int key, int value) {
     unordered_map<int,node*>::iterator iter;
     iter=mp.find(key);
     if(iter!=mp.end()){
         node *p=iter->second;
         p->pre->next=p->next;
         p->next->pre=p->pre;
         push_top(p);
         p->val=value;
     }
     else{
         node *p=new node(key,value);
         push_top(p);
         mp[key]=p;
         size++;
         if(size>c){
             p=tail->pre;
             tail->pre=p->pre;
             p->pre->next=tail;
             iter=mp.find(p->key);
             mp.erase(iter);
             delete p;
         }
     }
     
 }
示例#30
0
//===========================================================================
// QueryTask
//===========================================================================
void QueryTask::onTask() {
    if (err && err != WSA_E_CANCELLED) {
        logMsgError() << "GetAddrInfoEx: " << err;
    }
    notify->onEndpointFound(ends.data(), (int)ends.size());
    s_tasks.erase(id);
}