示例#1
0
文件: 146.LRU.cpp 项目: wxn7/Leetcode
 void set(int key, int value) {
     if (dict.count(key) != 0) {// found
         touch(key);
         dict[key] = value;
         ht[key] = keys.end();
         return;
     }
     
     //if not found
     if (keys.size() == cap) {
         //remove oldest one
         dict.erase(keys.front());
         ht.erase(keys.front());
         keys.pop_front();
     }
     keys.push_back(key);
     ht[key] = keys.end();
     dict[key] = value;
 }
示例#2
0
int bSearch(int x)
{
	int lo = 0;
	int hi = dq.size();
	int mid;
	int ans;
	while(lo <= hi)
	{
		mid = (lo+hi)/2;
		if(x <= dq[mid])
		{
			hi = mid - 1;
			ans = mid;
		}
		else lo = mid + 1;
	}
	
	return ans;
}
示例#3
0
void DisplayCpp()
{
	size_t i;
	cin.get();
	cout << endl;
	cout << "****************************************************" << endl;
	cout << "*               Display   C++    vip               *" << endl;
	cout << "****************************************************" << endl;
	cout << endl;

    if(vip.empty())
    {
    	cout << endl;
		cout << " There is no C++ vip info." <<endl;
       	cout << endl;
    }


	for(i = 0; i < vip.size(); i++)
	{
		pVip = vip[i];

		if(typeid(*pVip) == typeid(CPP))
		{
            cout << endl;
            cout << "****************************************************" << endl;
            cout << "*                  Press enter key                 *" << endl;
            cout << "****************************************************" << endl;
            cin.get();
			cout<<endl;

			pVip->DisplayInfo();
			pVip->DisplayOtherInfo();
		}
	}

	cout << endl;
	cout << "****************************************************" << endl;
	cout << "*            Press ENTER to back to menu           *" << endl;
	cout << "****************************************************" << endl;
	cin.get();
	cout<<endl;
}
示例#4
0
void SearchVip(const string& studentId)
{
	size_t i;

	for(i = 0; i < vip.size(); i++)
	{
		pVip = vip[i];
		if(0 == studentId.compare(pVip->GetStudentId()))
		{
			cout << endl;
			pVip->DisplayInfo();
			pVip->DisplayOtherInfo();
			return;
		}
	}
    cout << "********************************************************" <<endl;
    cout << "*                 Can't find vip...                    *" <<endl;
    cout << "********************************************************" <<endl;
}
示例#5
0
bool isDivByThree(const deque<unsigned int>& number){

  if (number.size() == 1){
    if (number[0] == 3 || number[0] == 6 || number[0] == 9)
      return true;
    else
      return false;
  }

  deque<unsigned int> total;

  for (deque<unsigned int>::const_iterator itr = number.begin(), endItr = number.end() ; itr != endItr; itr++)
    vecSum(total, *itr);
     
  if (isDivByThree(total))
    return true;

  return false;
}
示例#6
0
void deque::__copy(deque const &other) {
    iterator tmp = __reserve(other.sz);
    size_t r = 0;
    try {
        for (int i = 0; i < other.size(); i++) {
            new((void *) (&*(tmp + i))) value_type(other[i]);
            r++;
        }
        operator delete(&*a);
        a = tmp;
        head =a;
        tail = a+(sz-1);
    } catch (...) {
        for (int i = 0; i <= r; i++) {
            (&*(tmp + i))->~basic_string();
        }
        operator delete(&*tmp);
    }
}
示例#7
0
    void aux(int s, int e) {
        stk.push_front(s);
        if (s == 0) {
            now.clear();
            now += cs.substr(stk[0], stk[1]);
            for (int j = 1; j < stk.size() - 1; j++) {
                now.push_back(' ');
                int t1 = stk[j], t2 = stk[j + 1] - t1;
                now += cs.substr(t1, t2);
            }
            res.push_back(now);
        } else {
            for (auto& i : vec[s]) {
                aux(i, s);
            }
        }

        stk.pop_front();
    }
示例#8
0
void draw_features( IplImage* img, feature* feat, const deque<int>& kids)
{
	CvScalar color = CV_RGB( 255, 255, 255 );
	int i;

	if( img-> nChannels > 1 )
	{
		color = FEATURE_LOWE_COLOR;
	}
	for( i = 0; i < kids.size(); i++ )
	{
		//draw_lowe_feature( img, feat + i, color );
		int len, hlen, blen, start_x, start_y, end_x, end_y, h1_x, h1_y, h2_x, h2_y;
		double scl, ori;
		double scale = 5.0;
		double hscale = 0.75;
		CvPoint start, end, h1, h2;

		/* compute points for an arrow scaled and rotated by feat's scl and ori */
		start_x = cvRound( feat[kids[i]].x );
		start_y = cvRound( feat[kids[i]].y );
		scl = feat[kids[i]].scl;
		ori = feat[kids[i]].ori;
		len = cvRound( scl * scale );
		hlen = cvRound( scl * hscale );
		blen = len - hlen;
		end_x = cvRound( len *  cos( ori ) ) + start_x;
		end_y = cvRound( len * -sin( ori ) ) + start_y;
		h1_x = cvRound( blen *  cos( ori + CV_PI / 18.0 ) ) + start_x;
		h1_y = cvRound( blen * -sin( ori + CV_PI / 18.0 ) ) + start_y;
		h2_x = cvRound( blen *  cos( ori - CV_PI / 18.0 ) ) + start_x;
		h2_y = cvRound( blen * -sin( ori - CV_PI / 18.0 ) ) + start_y;
		start = cvPoint( start_x, start_y );
		end = cvPoint( end_x, end_y );
		h1 = cvPoint( h1_x, h1_y );
		h2 = cvPoint( h2_x, h2_y );

		cvLine( img, start, end, color, 1, 8, 0 );
		cvLine( img, end, h1, color, 1, 8, 0 );
		cvLine( img, end, h2, color, 1, 8, 0 );
	}

}
示例#9
0
//----------------------------------------------------------
void ofPushView() {
	
	GLint viewport[4];
	glGetIntegerv(GL_VIEWPORT, viewport);
	
	ofRectangle currentViewport;
	currentViewport.set(viewport[0], viewport[1], viewport[2], viewport[3]);
	viewportHistory.push_front(currentViewport);
	
	if( viewportHistory.size() > OF_MAX_VIEWPORT_HISTORY ){
		viewportHistory.pop_back();
		//should we warn here?
		//ofLog(OF_LOG_WARNING, "ofPushView - warning: you have used ofPushView more than %i times without calling ofPopView - check your code!", OF_MAX_VIEWPORT_HISTORY);
	}
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
}
示例#10
0
void Machine::process()
{
    int pos = 0;
    while(_state != _accept) {
        if (pos < 0) {
            _tape.push_front('_');
            pos = 0;
            _start_pos += 1; //Update for printing '|'
        } else if (pos == _tape.size()) {
            _tape.push_back('_');
        }
        char symbol = _tape[pos];
        tuple<string, char> before = make_tuple(_state, symbol);
        tuple<string, char, char> after = _rules[before];
        _state = get<0>(after);
        _tape[pos] = get<1>(after);
        pos += (get<2>(after) == '>') ? 1 : -1;
        _head_pos = max(pos,0); //Update for printing '^'
    }
}
示例#11
0
void updateDeque(deque<int> &dq, int k, int newNumber, bool keepSize=true) {
    int poppedCount = 0;
    int initialSize=dq.size();
    for(int i=0; i<k && i<initialSize; i++) {
        if(dq.back()<newNumber) {
            dq.pop_back();
            poppedCount++;
        } else {
            break;
        }
    }

    for(int i=0; i<poppedCount; i++)
        dq.push_back(newNumber);

    if(keepSize) {
        dq.pop_front();
    }
    dq.push_back(newNumber);
}
示例#12
0
 void dualOperands(string& opCode)
 {
   if(s.size() >= 2) {
     double a = s.front(); s.pop_front();
     double b = s.front(); s.pop_front();
     double result;
          if(opCode == "+")  result = a + b;
     else if(opCode == "-")  result = a - b;
     else if(opCode == "*")  result = a * b;
     else if(opCode == "/")  result = a / b;
     else if(opCode == "**") result = exp(b*log(a));
     else {
       cout << "unknown operator " << opCode.c_str() << endl;
       return;
     }
     cout << result << endl;
     s.push_front(result);
   } else
     cout << "need two numbers\n";
 }
示例#13
0
	void TriResMultiHalfTone::apply(deque<double>& buff)
	{
		if(buff.size()<m_convolutions[0][0]->size()) return;

		for(size_t h=0; h<m_convolutions.size(); h++)
		{
			m_convolutions[h][0]->apply(buff);
			Math::polar<double> sol = m_convolutions[h][0]->m_trans;

			for(size_t i=1; i<m_convolutions[h].size(); i++)
			{
				m_convolutions[h][i]->apply(buff, 0);
				sol.mod = min(sol.mod, sqrt(norm(m_convolutions[h][i]->m_trans)));
				m_convolutions[h][i]->apply(buff, m_convolutions[h][0]->size()-m_convolutions[h][i]->size());
				sol.mod = min(sol.mod, sqrt(norm(m_convolutions[h][i]->m_trans)));
			}

			m_components[h] = Math::make_complex(sol);
		}
	}
示例#14
0
    virtual void AddPacket(BYTE *data, UINT size, DWORD timestamp, DWORD pts, PacketType type) override
    {
        packets.emplace_back(make_shared<packet_t>(type, timestamp, pts, vector<BYTE>(data, data + size)));

        if (data[0] != 0x17)
            return;

        HandleSaveTimes(pts);

        keyframes.emplace_back(timestamp, --end(packets));

        while (keyframes.size() > 2)
        {
            if (((long long)timestamp - keyframes[0].first) < (seconds * 1000) || ((long long)timestamp - keyframes[1].first) < (seconds * 1000))
                break;

            packets.erase(begin(packets), keyframes[1].second);
            keyframes.erase(begin(keyframes));
        }
    }
示例#15
0
void File::insert_lines( const unsigned int& line, deque<string> d, bool break_lines ) {
  unsigned int temp = fun::bound( line, (unsigned int) 0, get_num_lines() );

  if ( break_lines ) {
    deque<string> ready;
    vector<string> lines;
    
    // Break each line in d on \n if specified, before putting into file contents
    for ( unsigned int i = 0; i < d.size(); i++ ) {
      lines = str_breakup( d[i], "\n" );      
      ready.insert( ready.end(), lines.begin(), lines.end() );
    }
    
    d = ready;
  }
  
  m_file.insert( m_file.begin() + line, d.begin(), d.end() );
  
  return;
}
示例#16
0
/*This function sends multiple packets(inside the window) in Bulk
 * */
void sendPacketsinBulk(){
	bool flag=true;
	/*	int count=0; */
	timerPacket* senderPacket=NULL;
	while((a_nextseqnum < senderBuffer.size())&&(a_nextseqnum < a_base + a_windowSize)){
		if(flag){
			flag=false;
			cout<<"A->Sending packets in Bulk."<<endl;
		}

		senderPacket=senderBuffer.at(a_nextseqnum);
		senderPacket->timeOffset=time_local+getTimeout();
		senderPacket->start_time=time_local;
		a_nextseqnum++;
		tolayer3(0,*(senderPacket->packet));
		cout<<"A->Packet with Sequence number "<<senderPacket->packet->seqnum<<". checksum:"<<senderPacket->packet->checksum<<" sent from A time:"<<time_local<<endl;
		fflush(stdout);
		a_totalPacketsSentFromTran++;
	}
}
示例#17
0
int FluxTensorMethod::apply_averaging_filters(const Mat & input, Mat & result)
{
	static deque<Mat> axay_fifo;

	result = input.clone();

	Mat ax_result;
	filter2D(input, ax_result, -1, ax_filter);

	Mat ax_ay_result;
	filter2D(ax_result, ax_ay_result, -1, ay_filter);

	axay_fifo.push_back(ax_ay_result);
	if(axay_fifo.size() < (unsigned int)nAt)
		return 1;

	apply_temporal_filter(&axay_fifo, at_filter, nAt, result);

	axay_fifo.pop_front();
	return 0;
}
示例#18
0
void detectCollision()
{
	Point3D playerPos = theCamera->getLocation();
	Point3D itemPos;
	double xd, yd, zd;

	for(unsigned int i = 0; i < theWorld.size(); i++){
		itemPos = theWorld[i];
		xd = playerPos.x - itemPos.x;
		yd = playerPos.y - itemPos.y;
		zd = playerPos.z - itemPos.z;

		//distance between two points formula
		if(xd*xd + yd*yd + zd*zd < 1.5*1.5){
			theWorld.erase(theWorld.begin() + i);
			FSOUND_PlaySound(FSOUND_FREE, coinBuffer);
			orbsCaptured++;
			updateScore();
		}
	}
}
示例#19
0
 void singleOperand(string& opCode)
 {
   if(s.size() >= 1) {
     double a = s.front(); s.pop_front();
     double result;
          if(opCode == "sin")  result = sin(a);
     else if(opCode == "cos")  result = cos(a);
     else if(opCode == "tan")  result = tan(a);
     else if(opCode == "sqrt") result = sqrt(a);
     else if(opCode == "abs")  result = abs(a);
     else if(opCode == "log")  result = log(a);
     else if(opCode == "exp")  result = exp(a);
     else {
       cout << "unknown operator " << opCode.c_str() << endl;
       return;
     }
     cout << result << endl;
     s.push_front(result);
   } else
     cout << "need at least one number\n";
 }
示例#20
0
int FluxTensorMethod::compute_Itt(const Mat & input, Mat & result)
{
	static deque<Mat> isxsy_fifo;

	result = input.clone();

	Mat sx_result;
	filter2D(input, sx_result, -1, sx_filter);

	Mat sx_sy_result;
	filter2D(sx_result, sx_sy_result, -1, sy_filter);

	isxsy_fifo.push_back(sx_sy_result);
	if(isxsy_fifo.size() < (unsigned int)nDt)
		return 1;

	apply_temporal_filter(&isxsy_fifo, dtt_filter, nDt, result);

	isxsy_fifo.pop_front();
	return 0;
}
示例#21
0
文件: Game.cpp 项目: aimango/xshooter
/**
 * create new building and catcher when the last building moves far enough.
 * delete building when off screen.
 */
void handleBuildingsAndCatchers(XInfo &xInfo) {
	int lastElt = dBuildingList.size()-1;
	if (dBuildingList.empty() || dBuildingList[lastElt]->getX() < 825 ) {
		double positionX = dBuildingList.empty() ? xInfo.width : dBuildingList[lastElt]->getX() + 50;
		Building *b = new Building(positionX);
		dBuildingList.push_back(b);
	
		// spawn an enemy
		if (rand() % 5 == 1) {
			Catcher *c = new Catcher(positionX + 20, b->getY());
			dCatcherList.push_back(c);
		}
	} else if (!dBuildingList.empty() && dBuildingList[0]->getX() < -50) {
		delete dBuildingList[0];
		dBuildingList.pop_front();
	}
	if (!dCatcherList.empty() && dCatcherList[0]->getX() < -100){
		delete dCatcherList[0];
		dCatcherList.pop_front();
	}
}
int matrix_time_vector(deque<deque<double> > & Q, deque<double> & v, deque<double> & new_s) {

	
	new_s.clear();
	
	for(int i=0; i<Q.size(); i++) {
		
		double n=0;
		for(int j=0; j<Q[i].size(); j++)
			n+=Q[i][j] * v[j];
		
		new_s.push_back(n);
	
	
	
	}


	return 0;
	
}
double scalar_product(deque<double> & a, deque<double> & b) {

	
	
	



	double norm=0;
	for(int i=0; i<a.size(); i++) {
		norm+=a[i]*b[i];
	}
	
	

	return norm;




}
示例#24
0
void Renderer::NormalizeVertices(deque<Point> vertices, deque<float> *normX, deque<float> *normY, float min, float max)
{
    
    long n = vertices.size();
    //Find normalized points
    for(int i = 0; i < n; i++)
    {
        float x = vertices[i].X(), y = vertices[i].Y();
        
        x = (float)(x - min) / (float)(max - min);
        y = (float)(y - min) / (float)(max - min);
        
        if(x < 0 || x > 1 || y < 0 || y > 1)
        {
            throw exception();
        }
        
        normX->push_back(x);
        normY->push_back(y);
    }
}
    void storeInterestingPoint()
    {
        if (t-t3>=STORE_POI_PER)
        {
            Vector ang;

            // we store the current azimuth, elevation
            // and vergence wrt the absolute reference frame
            // The absolute reference frame for the azimuth/elevation couple
            // is head-centered with the robot in rest configuration
            // (i.e. torso and head angles zeroed). 
            igaze->getAngles(ang);            

            fprintf(stdout,"Storing POI #%d ... %s [deg]\n",
                    poiList.size(),ang.toString().c_str());

            poiList.push_back(ang);

            t3=t;
        }
    }
示例#26
0
void GameLogic()
{
	static int cnt = 0 ;
	float dt = (float)time_interval * 0.001 ;
	current_time = glutGet( GLUT_ELAPSED_TIME ) ;

	//update particles
	for( size_t i = 0 ; i < particles.size() ; ++i )
	{
		//update position
		Particle& p = particles[i] ;
		p.pos += dt * p.vel ;
		p.vel += dt * gravity ;

		//update intensity
		p.intensity = std::max( 0.0f, (max_life - LifeTime(p))/max_life ) ;
		
		//update trail
		if( cnt > 5 ) {
			p.trail.push_back( p.pos ) ;
		}

		if( p.trail.size() > max_trail ) {
			p.trail.pop_front() ;
		}
		
		//kick old particle
		if( LifeTime(p) > max_life ) {
			particles.erase( particles.begin()+i ) ;		
		}

		//explode
		if( p.exploded == false && p.vel[1] < 0.5 ) {
			Explode(p) ;
			particles.erase( particles.begin()+i ) ;    //father died
		}
	}

	cnt > 5? cnt=0 : cnt++ ;
}
示例#27
0
static void timeout_cb(evutil_socket_t fd, short event, void *arg)
{
    struct timeval newtime;
    struct event *timeout = (struct event *)arg;
    
    evutil_gettimeofday(&newtime, NULL);

    if (g_count % 10 == 0)
    {
        g_last_time = newtime;
        g_last_flow = g_new_flow;
    }

    g_count++;

    int deque_len = g_send_conn_deque.size();
    int count = 0;
    while (count <= deque_len / 100)
    {
        if (!g_send_conn_deque.empty())
        {
            int fd = *(g_send_conn_deque.begin());

            map<int, server_conn *>::iterator it = g_conns.find(fd);
            if (it != g_conns.end())
            {
                server_conn *nlc = it->second;
                event_add(nlc->get_ev_write(), NULL);
            }
            g_send_conn_deque.pop_front();
        }
        count++;
    }

    struct timeval tv;
    evutil_timerclear(&tv);
    tv.tv_sec = 0;
    tv.tv_usec = 10000;
    event_add(timeout, &tv);
}
int main() {
    
    while( cin >> N >> S >> T >> M ) {

        build();

        total = 0;
        
        while( true ) {
            
            memset( fwd, 0, sizeof( fwd ) );
            Q.clear();
            fwd[s] = E - 1;
            Q.push_back( s );
            
            while( !Q.empty() && !fwd[t] ) {
                int pos = rand() % Q.size();
                int v = Q[pos];
                swap( Q[pos], Q.back() );
                Q.pop_back();
                for( int i = 0; i < V[v].size(); ++i ) {
                    if( !fwd[V[v][i] -> next( v )] &&
                             V[v][i] -> remain( v ) ) {
                        fwd[V[v][i] -> next( v )] = V[v][i];
                        Q.push_back( V[v][i] -> next( v ) );
                    }
                }
            }
            
            if( !fwd[t] )   break;
            
            total += addFlow( t, 0x7FFFFFF );

        }
        
        cout << total << endl;
  
    }
    
}
int findMax(deque<int> &arr){
    
    int first = 0, second = 0, maxOf2 = 0;
    
    while(!arr.empty() && arr.size()>1){
        
        // take 2 out
        first = arr.front();
        arr.pop_front();
        maxOf2 = first;
        
        if(!arr.empty()){
            second = arr.front();
            arr.pop_front();
            maxOf2 = findBigger(first, second);
        }
        
        arr.push_back(maxOf2);
    }
    
    return maxOf2;
}
void Reptation_method::get_avg(deque <Reptile_point> & reptile, 
			       Properties_point & pt) {
  int size=reptile.size();
  int nwf=reptile[0].prop.kinetic.GetDim(0);
  if(nwf >1) error("nwf > 0 not supported yet");

  pt.setSize(nwf);
  
  Reptile_point & last(reptile[size-1]);

  //How to do averaging at either end.  Not doing this right
  //now because of correlated sampling..if we really want energies,
  //usually DMC is a better choice.
  pt=last.prop;
  //Reptile_point & first(reptile[0]);  
  //pt.kinetic(0)=.5*(first.prop.kinetic(0)+last.prop.kinetic(0));
  //pt.nonlocal(0)=.5*(first.prop.nonlocal(0)+last.prop.nonlocal(0));
  //pt.potential(0)=.5*(first.prop.potential(0) + last.prop.potential(0));
  pt.count=1;
  pt.weight=1;
  
}