Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.5 kB
1
Indexable
Never
using namespace std;
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
 
#define MAX     12005   // MAX Bacteria
 
struct node {
    string name;
    int parent;
    int firstday;
    int lastday;
    int level;
 
    void init( string _name, int _parent, int _first, int _last )
    {
        this-> name = _name;
        this-> parent = _parent;
        this-> firstday = _first;
        this-> lastday = _last;
    }
}Bacteria[MAX];
int idx;
 
unordered_map <string, int> umap;         // name - idx
vector <int> first_list;
vector <int> last_list;
 
void init(char mAncestor[], int mDeathday)
{
    umap.clear();
    last_list.clear();
    first_list.clear();
 
    string ancestor = mAncestor;
    idx = 1;
    umap[ancestor] = idx;
    Bacteria[idx].init(ancestor, -1, 0, mDeathday);
    Bacteria[idx].level = 0;
 
    first_list.push_back(0);
    last_list.push_back(mDeathday);
    return;
}
 
int add(char mName[], char mParent[], int mBirthday, int mDeathday)
{
    string name = mName;
    string parent = mParent;
    int id_parent = umap[parent];
 
    idx++;
    umap[name] = idx;
    Bacteria[idx].init(name, id_parent, mBirthday, mDeathday);
    Bacteria[idx].level = Bacteria[id_parent].level + 1;
 
    auto first_it = upper_bound(first_list.begin(), first_list.end(), mBirthday);
    first_list.insert(first_it, mBirthday);
 
    auto last_it = upper_bound(last_list.begin(), last_list.end(), mDeathday);
    last_list.insert(last_it, mDeathday);
 
    return Bacteria[idx].level;
}
 
int distance(char mName1[], char mName2[])
{
    int id1 = umap[mName1];
    int id2 = umap[mName2];
 
    int rs = 0;
    while (id1 != id2)
    {
        if (Bacteria[id1].level > Bacteria[id2].level) {
            id1 = Bacteria[id1].parent;
        } else {
            id2 = Bacteria[id2].parent;
        }
         rs++;
    }
    return rs;
}
 
int count(int mDay)
{
    int after = upper_bound(first_list.begin(), first_list.end(), mDay ) - first_list.begin();      // <
    int before = lower_bound(last_list.begin(), last_list.end(), mDay ) - last_list.begin();        // <=
    return after - before;
}