void run() {
  scanf("%d%d", &n, &m);
  last.clear(); last[m] = 1;
  for (int i = 0; i < n; ++i) {
    int x, s = 0; scanf("%d", &x);
    auto it = last.lower_bound(x);
    for (; it != last.end(); ) {
      last[it->first % x] += it->second;
      s += it->second * (it->first / x);
      it = last.erase(it);
    }
    if (s) last[x - 1] += s;
  }
  int s = 0;
  for (auto it = last.rbegin(); it != last.rend(); ++it) {
    it->second += s; s = it->second;
  }
  int q, ret = 0; scanf("%d", &q);
  for (int i = 1; i <= q; ++i) {
    int x; scanf("%d", &x);
    auto it = last.lower_bound(x);
    if (it != last.end()) ret += 1ll * it->second * i % M;
    if (ret >= M) ret -= M;
  }
  printf("%d\n", ret);
}
Example #2
0
int main() {
    scanf("%d",&n);
    for (int i=0; i<n; i++) {
        scanf("%d %d",&q[i].first,&q[i].second);
    }
    sort(q,q+n);
    for (int i=0; i<n; i++) {
        int h = q[i].second;
        mp[q[i].first]--;
        int piv = q[i].first-h;
        aauto it = mp.lower_bound(piv);
        pi t = *it;
        mp.erase(it);
        int gap = t.first - piv;
        if(t.second != -1) mp.insert(pi(t.first,t.second + 1));
        it = mp.lower_bound(piv);
        if(it == mp.begin()) {
            mp[gap]--;
        }
        else {
            it--;
            t = *it;
            mp.erase(it);
            if(t.second != -1) mp.insert(pi(t.first,t.second + 1));
            mp[t.first + gap]--;
        }
    }
    long long ret = 0, cnts = 0;
    for (int i=q[n-1].first; i>=0; i--) {
        ret += cnts * (cnts - 1) / 2;
        cnts -= mp[i];
    }
    printf("%lld",ret);
}
Example #3
0
bool query(int sx, int ex, int sy, int ey){
    auto itl = mp1.lower_bound(sx);
    auto itr = mp1.upper_bound(ex);
    if(itl == mp1.end() || itl->first > ex) return 0;
    if(itl->second > ey) return 0;
    itr--;
    if(itr->second < sy) return 0;
    auto ity = mp2.lower_bound(sy);
    if(ity == mp2.end() || ity->first > ey) return 0;
    return 1;
}
 string get(string key) {
    if (circle.empty()) {
      return "";
    }

    int code = hash<string>()(key);
    if (circle.find(code) ==circle.end()) {
      if(circle.lower_bound(code) != circle.end()) return circle.lower_bound(code)->second;
      else return circle.begin()->second;
    }
    return circle.find(code)->second;
  } 
Example #5
0
 void scanAscending(RecordListResponse& _return, const map<string, string>& mymap,
           const string& startKey, const bool startKeyIncluded,
           const string& endKey, const bool endKeyIncluded,
           const int32_t maxRecords, const int32_t maxBytes) {
     map<string, string>::const_iterator itr = startKeyIncluded ? 
         mymap.lower_bound(startKey):
         mymap.upper_bound(startKey);
     int numBytes = 0;
     while (itr != mymap.end()) {
         if (!endKey.empty()) {
             if (endKeyIncluded && endKey < itr->first) {
               break;
             }
             if (!endKeyIncluded && endKey <= itr->first) {
               break;
             }
         }
         Record record;
         record.key = itr->first;
         record.value = itr->second;
         numBytes += record.key.size() + record.value.size();
         _return.records.push_back(record);
         if (_return.records.size() >= (uint32_t)maxRecords || numBytes >= maxBytes) {
             _return.responseCode = ResponseCode::Success;
             return;
         }
         itr++;
     }
     _return.responseCode = ResponseCode::ScanEnded;
 }
bool work(int t, int m) {
	int x = max_x[0];
	rep(i, m) {
		auto next = yc.upper_bound(max_y[xc.lower_bound(x - t)->snd] + t);
		if(next == yc.end()) return true;
		x = max_x[next->snd];
	}
Example #7
0
    /***
     * Inserts a key if not present, or bumps it to the front of the LRU if
     * it is, and then gives you a reference to the value. If the key already
     * existed, you are responsible for deleting the new value you tried to
     * insert.
     *
     * @param key The key to insert
     * @param value The value that goes with the key
     * @param existed Set to true if the value was already in the
     * map, false otherwise
     * @return A reference to the map's value for the given key
     */
    VPtr add(const K& key, V *value, bool *existed = NULL)
    {
        VPtr val;
        list<VPtr> to_release;
        {
            Mutex::Locker l(lock);
            typename map<K, pair<WeakVPtr, V*>, C>::iterator actual =
                weak_refs.lower_bound(key);
            if (actual != weak_refs.end() && actual->first == key)
            {
                if (existed)
                    *existed = true;

                return actual->second.first.lock();
            }

            if (existed)
                *existed = false;

            val = VPtr(value, Cleanup(this, key));
            weak_refs.insert(actual, make_pair(key, make_pair(val, value)));
            lru_add(key, val, &to_release);
        }
        return val;
    }
Example #8
0
void computeCost(int node , stack<Pair> st , map<lli , lli> mp)
{
    ///Pair : (cost from that node , level of that node) -->
    ///       (cost , level)
    ///mp[level]= cost ---> for easy searching

    //cout<<"At node "<<node<<endl;
    if(node==0)
    {
        st.push(make_pair(0,0));
        mp[0]=0;
        cost[0] =0;
    }
    else
    {
        int i;
        int currentlevel = st.top().second + 1;
        lli tmpcost , mincost= inf;
        for(i=0;i<tickets[node].size();i++)
        {
            Pair t = tickets[node][i];
            lli t_k = t.first;
            lli t_w = t.second;

            if(t_k>=currentlevel)
                tmpcost = t_w ;

            else
            {
                tmpcost = t_w + (mp.lower_bound(currentlevel - t_k)->second) ;
            }

            if(tmpcost<mincost) mincost = tmpcost ;

        }

        lli top_cost = st.top().first ;
        lli top_level = st.top().second ;

        while(top_cost >= mincost)
        {
            st.pop();
            mp.erase(mp.find(top_level));

            top_cost = st.top().first ;
            top_level = st.top().second ;
        }

        st.push(make_pair(mincost,currentlevel));
        mp[currentlevel] = mincost ;
        cost[node]=mincost;
    }

    int i,v;
    for(i=0;i<children[node].size();i++)
    {
        v = children[node][i];
        computeCost(v, st , mp);
    }
}
Example #9
0
pair<int, int> next(const map<int, int>& mp, int k) {
  map<int, int>::const_iterator it = mp.lower_bound(k);
  if (it == mp.end()) {
    it = mp.begin();
  }
  return *it;
}
Example #10
0
void update_bp(pos & a, pos & b) {

    if (a>b) {
        pos t = a;
        a=b;
        b=t;
    }

    if (a>b || a.chr!=b.chr) {
        cerr << " Failed pre condition " << endl;
        exit(1);
    }


    //find the nearest bp
    map<pos, bp>::iterator it= bps.lower_bound(a);
    while (it!=bps.end() && it->first.chr==a.chr && it->first.coord>=a.coord && it->first.coord<=b.coord) {
        if (a.marked) {
            it->second.lefts++;
        }
        if (b.marked) {
            it->second.rights++;
        }
        it++;
    }

    return ;

}
Example #11
0
bool work() {
	if(cntn==0)return false;
	for(int i=1;i<=n;i++)
		if(a[i]==n &&degn[i]<=1){
			newcntn=0;
			dfs1(i,0);
			break;
		}
	if(cntn!=newcntn)return false;
	memset(acer,0,sizeof(acer));
	int root=n+1;
	for(int i=1;i<=n;i++)
		if(a[i]==n && degn[i]<=1){
			root=i;
			break;
		}
	if((!dfs(root,0)))
		return false;
	for(int i=n;i>=1;i--) {
		if(acer[i])continue;
		map<int,bool>::iterator it=ma.lower_bound(n+1-a[i]);
		if(it==ma.end()) return false;
		a[i]=n+1-it->first;
		ma.erase(n+1-a[i]);
	} 
	return true;
}
int invertParity(int n){
  int extra_shifts = 0;
  if ((n & 1) == 1){
    return n<<1;
  }else {
    unsigned int inverted = n;
    int shift = 1; // for 2
    while ((inverted & 1) == 0){
      if (shiftFor.count(inverted) == 1){
        shift = shiftFor[inverted];
        if (extra_shifts > 0){
            extra_shifts += shift;
            shiftFor[n] = extra_shifts;
            extra_shifts = 0;
        }
        return inverted>>shift;
      }else{
        it = shiftFor.lower_bound(inverted);
        if (it != shiftFor.begin()){
          --it;
        }
        shift = shiftFor[inverted % it->first];
        extra_shifts += shift;
      }
      inverted>>=shift;
    }
void findSongPrefixes(string prefix) {
    map<string,songData*>::const_iterator it = songList.lower_bound(prefix); // looks for song that starts with prefix
    int prefixLength = prefix.size();
    string songMatch;
    multimap<int,string> songsWithPrefix;	// list of songs that has the prefix sorted by popularity

    if( it != songList.end() ){ 			//if there is a song that starts with the prefix
	    do{
	        songMatch = it->first;
	        if (songMatch.compare(0, prefixLength, prefix) == 0){ 			// check to see it if it a prefix
	            if(playlistChange) updateSongPopularity(it -> first);		// update song's popularity if there was a change to the playlist databse
	            songsWithPrefix.insert( std::pair<int,string>(it -> second->popularity, it -> first) );	// add song to map sorted by popularity
	        }
	        it++;
	    }while(songMatch.compare(0, prefixLength, prefix) == 0); // check if there is anymore songs with prefix
	}

	playlistChange = false;				// update to show changes in playlist database has been taken into account

	multimap<int, string>:: iterator iter = songsWithPrefix.end();
	for( int count = 0; count < 4 && iter != songsWithPrefix.begin() ; count++){ /*** O(n) where n is 8 ***/
		iter--;
		cout<< iter -> second<<endl;	// print out songs sorted by popularity
	}
}
Example #14
0
/**
 * ByteRangeIndex::trunc_map: truncate a C++ index map (low-level helper fn)
 *
 * @param mymap the map to truncate
 * @param nzo non-zero offset to truncate to
 */
void
ByteRangeIndex::trunc_map(map<off_t,ContainerEntry> &mymap, off_t nzo) {
    map<off_t,ContainerEntry>::iterator itr, prev;
    bool first;

    if (mymap.size() == 0) {   /* no entries? then nothing to do... */
        return;
    }
    
    /* use stab query to find first element with offset >= nzo */
    itr = mymap.lower_bound(nzo);
    first = ( itr == mymap.begin() );

    /* remove everything past nzo */
    mymap.erase(itr, mymap.end());
    
    /* see if previous entry (if any) needs to be internally truncated */
    if (!first) {
        prev = itr;
        prev--;

        if (prev->second.logical_offset + (off_t)prev->second.length > nzo) {

            prev->second.length = nzo - prev->second.logical_offset;
        }
    }
}   
Example #15
0
  VPtr lower_bound(const K& key) {
    VPtr val;
    list<VPtr> to_release;
    {
      Mutex::Locker l(lock);
      bool retry = false;
      do {
	retry = false;
	if (weak_refs.empty())
	  break;
	typename map<K, WeakVPtr>::iterator i = weak_refs.lower_bound(key);
	if (i == weak_refs.end())
	  --i;
	val = i->second.lock();
	if (val) {
	  lru_add(i->first, val, &to_release);
	} else {
	  retry = true;
	}
	if (retry)
	  cond.Wait(lock);
      } while (retry);
    }
    return val;
  }
Example #16
0
	void add(int x,int y)
	{
		map<int,int>::iterator lb=M.lower_bound(x),i2;
		i2=lb;
		while (i2!=M.end()&&i2->second>=y)
			i2++;
		M.erase(lb,i2);
		M.insert(pair<int,int>(x,y));
	}
Example #17
0
int main()
{
	#ifdef fn
		freopen(fn ".in", "r", stdin);
		freopen(fn ".out", "w", stdout);
	#endif
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		scanf("%d%d", x + i, h + i);
	for (int i = 1; i <= n; i++)
	{
		printf("%d %d: ", x[i], h[i]);
		if (!dp.count(x[i]))
			dp[x[i]] = 1;
		if (!dp.count(x[i] + h[i]))
			dp[x[i] + h[i]] = 1;
		auto it = dp.lower_bound(x[i] - h[i]);
		if (!dp.empty())
		{
			if (it != dp.begin())
				it--;
			printf("+%d", it -> F);
			if (it -> F < x[i] - h[i])
				umax(dp[x[i]], it -> S + 1);
			if (it -> F < x[i])
				umax(dp[x[i]], it -> S);
		}
		it = dp.lower_bound(x[i]);
		if (!dp.empty())
		{
			if (it != dp.begin())
				it--;
			printf(" %d:", it -> F);
			if (it -> F < x[i])
				umax(dp[x[i]], it -> S + 1),
				umax(dp[x[i] + h[i]], it -> S + 1);
		}
		for (pii y : dp)
			printf("(%d %d) ", y.F, y.S);
		puts("");
	}
	auto it = dp.end(); it--;
	printf("%d", it -> S);
}
Example #18
0
int main() {
	int q;
	cin >> q;
	
	char c;
	int x, l, h, t, b;
	while (q--) {				
		// cin >> c >> x;
		scanf(" %c %d", &c, &x); // faster than cin
		if (c == '+') {
			hmap[x]++;
		} else if (c == '-'){
			hmap[x]--;
			if (hmap[x] == 0)
				hmap.erase(x);			
		} else { // find max value
			l = 0;
			h = ((ll)1 << 31) - 1;
			t = h ^ x; // this is the target we want to find in A

			for (int i = 30; i >= 0; i--) {
				b = t & (1 << i);
				if (b) { // i th target bit is 1
					h = h | (1 << i);
					l = l | (1 << i);
					if (hmap.lower_bound(l) == hmap.upper_bound(h)) { // no value between l and h
						// reverse
						h = h & (~(1 << i));
						l = l & (~(1 << i));
					}
				} else {
					h = h & (~(1 << i));
					l = l & (~(1 << i));
					if (hmap.lower_bound(l) == hmap.upper_bound(h)) { // no value between l and h
						h = h | (1 << i);
						l = l | (1 << i);
					}
				}
			}
			cout << max(x, l^x) << endl;
		}		
	}	
	return 0;
}
Example #19
0
int main(){
    scanf("%d %d",&n,&m);
    low.insert(0);
    low.insert(n);
    high.insert(n);
    high.insert(2*n);
    for(int i=0; i<m; i++){
        char b[5];
        int x, y;
        scanf("%s %d %d",b,&x,&y);
        if(*b == 'B'){
            if(x > y) swap(x, y);
            if(y <= n){
                low.insert(x);
            }
            else{
                high.insert(x);
            }
        }
        if(*b == 'Q'){
            if((x-1) / n == (y-1) / n){
                if(x <= n && x > y){
                    auto u = mp1.lower_bound(x);
                    auto v = low.lower_bound(x);
                    if(u == mp1.end() || (v != low.end() && *v < u->first)) puts("NE");
                    else move(u->second, y);
                }
                else if(x <= n && x <= y){
                    auto t = low.lower_bound(x);
                    puts(y <= *t ? "DA" : "NE");
                }
                else if(x > n && x >= y){
                    auto t = --high.lower_bound(x);
                    puts(*t+1 <= y ? "DA" : "NE");
                }
                else{
                    auto u = mp2.upper_bound(x);
                    auto v = high.lower_bound(x);
                    if(u == mp2.begin()) puts("NE");
                    else{
                        u--;
                        if(v != high.begin() && *--v >= u->first){
                            puts("NE");
                        }
                        else move(u->second, y);
                    }
                }
            }
            else move(x, y);
        }
        if(*b == 'A'){
            if(x > y) swap(x, y);
            ins(x, y);
        }
    }
}
pair<size_t, size_t> FluxesReader::GetInterval(double value, const map<double, int>&lut) const{
  map<double, int>::const_iterator lower_bound = lut.lower_bound(value);
  assert(lower_bound!=lut.end());

  map<double, int>::const_iterator upper_bound = lower_bound;
  if(lower_bound!=lut.begin())
    lower_bound--;

  return pair<size_t, size_t>(lower_bound->second, upper_bound->second);
}
Example #21
0
    vector<int> retrieve(string s, string e, string gra) {
		int64_t stop = mm[gra];
		int64_t sts = read_ts(s, stop);
		int64_t ets = read_ts(e, stop) + stop;
		vector<int> ans;
		for (auto it=idm.lower_bound(sts); it!=idm.end() && it->first<ets; ++it) {
			ans.push_back(it->second);
		}
		return ans;
    }
Example #22
0
File: jz.cpp Project: eagle9/palgo
    // @param hashcode an integer
    // @return a machine id which has a shard >= hashcode and closest to hashcode
    int getMachineIdByHashCode(int hashcode) {
		//lowerbound, >= but minimized, sorted, it whose value is >=
		//hashcode as lower bound 
        map<int, int>::iterator it = shards.lower_bound(hashcode);
		
        if (it == shards.end()) //all before hashcode, hashcode can not be lowerbound
            return shards.begin()->second;
        else
            return it->second; //it >= hashcode, first such 
    }
Example #23
0
int main(){
	scanf("%d%d",&n,&q);
	for(int i=1;i<=n;i++) {
		hh.insert(make_pair(an,i));
		int b;
		scanf("%d",&b);
		an+=b;
	}
	hh.insert(make_pair(an,n+1));
	for(int i=0;i<q;i++) {
		int b;
		scanf("%d",&b);
		if((hh.lower_bound(b)->first)==b){
		    printf("%d\n",hh.lower_bound(b)->second);
            continue;
		}
		printf("%d\n",(hh.upper_bound(b))->second-1);
	}
}
Example #24
0
	bool find(int x,int y)
	{
		map<int,int>::iterator lb=M.lower_bound(x);
		if (lb==M.begin())
			return false;
		lb--;
		if (lb->second<y)
			return true;
		else
			return false;
	}
Example #25
0
int find_prime_factor_val(const IntPair& np, const map<IntPair, int, IntPairLess>& factorMap )
{
    if(np.first > root){
        assert(np.second == 1);
        return np.first;
    }
    auto iter = factorMap.lower_bound(np); //some of the power are missing, 
    //so change find to lower_bound
    assert(iter != factorMap.end());
    return iter->second;
}
Example #26
0
bool gao()
{
	int a,b;
	map<int,int>::iterator it;
	scanf("%d%d",&a,&b);
	it=mp0.lower_bound(a);
	if(b<it->second) return 0;
	it=mp1.upper_bound(a);
	--it;
	if(b>it->second) return 0;
	return 1;
}
int main(){
  pre();
  LL t,n,ans;
  scanf("%lld",&t);
  while(t--){
    scanf("%lld",&n);
    auto it= M.lower_bound(n);
    if(it->first!=n)it--;
    printf("%lld\n",it->second);
  }
  return 0;
}
Example #28
0
void addancestry(snp &asnp)
{
  int64_t index;
  map<int64_t,interval>::iterator i;
  index=((int64_t)asnp.chromosome<<56)+((int64_t)asnp.position<<28)+((int64_t)asnp.position^0xfffffff);
  i=diploid.lower_bound(index);
  if (i==diploid.end() || !i->second.in(asnp.chromosome,asnp.position))
    i--;
  if (i->second.in(asnp.chromosome,asnp.position))
    memmove(asnp.ethnicity,i->second.ethnicity,sizeof(asnp.ethnicity));
  cout<<snpstring(asnp.snpname)<<"\t"<<chromstring(asnp.chromosome)<<"\t"<<posstring(asnp.position)<<"\t"<<allelestring(asnp.allele)<<"\t"<<ethstr(asnp.ethnicity[0])<<":"<<ethstr(asnp.ethnicity[1])<<endl;
}
Example #29
0
void decideNerd(int now,int p, int q)
{
	MAP.insert(pair<int,int>(p,now));
	int value =MAP.lower_bound(p);
	printf("%d\n",value);
/*	map<int,int> MAP2;
	MAP2 =MAP;
	map<int,int>::iterator iter;

	MAP.insert(pair<int,int>(p,now));
	qList[now]=q;

	int flag =0;
	int temp = sum+1;

	for(iter=MAP.begin(); iter != MAP.end(); ++iter)
	{
		map<int,int>::iterator now_iter;

		if((*iter).second==now)
		{
			flag=1;
			now_iter = iter;
		}
		if(flag==0 && qList[(*iter).second]<qList[now])
		{
			temp--;
//			printf("qwer\n");
			MAP.erase(iter);
		}
		else if(flag==1 && qList[(*iter).second]>qList[now])
		{
			temp--;
//			printf("qwdder\n");
			//MAP.erase(now_iter);
			MAP =MAP2;
			break;
		}
	}

	int size = MAP.size();
	printf("%d\n",size);
	map<int,int>::iterator iter_map;
		for(iter_map=MAP.begin(); iter_map != MAP.end(); ++iter_map)
			printf("%d ",(*iter_map).second);
	printf("tempi: %d\n",temp);
	sum = temp;
	total = total+temp;
*/}
void PressSimuHandler::DoIt()
{
	while(true)
	{
		//随机一个命令字。处理。如果处理完后,限速未到,usleep一段。否则继续while
		
		static unsigned random_num = ns_pplive::PubApi::GenRandom();		
		random_num += ns_pplive::PubApi::GenRandom();
		double d_random_num = random_num % 10000 * 0.0001;
		map<double,uint8_t>::const_iterator it = percent_cmd_.lower_bound(d_random_num);
		//因为认为random_num是小于1.0的,而percent_cmd_的最后一个key是1.0
		assert(it != percent_cmd_.end());
		ProcessCmd(it->second);
		SpeedLimit();
	}
}