コード例 #1
0
ファイル: main.cpp プロジェクト: rusucosmin/cplusplus
inline bool Check(int D) {
    deque <int>().swap(dq);
    for(int i = 1 ; i <= N ; ++ i)
        for(int j = 0 ; j <= d[N] ; ++ j)
            dp[i][j] = oo;
    dp[1][0] = 0;
    for(int i = 2 ; i <= N ; ++ i) {
        for(int j = 0 ; j <= d[N] ; ++ j) {
            while(!dq.empty() && abs(j - dq.front()) > D)
                dq.pop_front();
            while(!dq.empty() && dp[i - 1][dq.back()] >= dp[i - 1][j])
                dq.pop_back();
            dq.push_back(j);
            dp[i][j] = dp[i - 1][dq.front()] + abs(d[i] - j);
        }
    }
    return dp[N][d[N]] <= E;
}
コード例 #2
0
int main() {
	int	X,	Y,	T = 0;
	char	input[2];
	while( scanf( "%d%d", &M, &N ) != EOF ) {
		if( T++ ) putchar( '\n' );
		for( int i = 0; i < M; i++ )
			scanf( "%s", grid[i] );
		scanf( "%d%d%s", &X, &Y, input );
		Force.resize( 0 );
		Force.push_back( oper( X - 1, Y - 1, *input ) );
		while( !Force.empty() ) {
			knockDown( Force[0].x, Force[0].y, Force[0].c );
			Force.pop_front();
		}
		for( int i = 0; i < M; i++ )
			printf( "%s\n", grid[i] );
	}
}
コード例 #3
0
ファイル: permutations-ii.cpp プロジェクト: Rand3/leetcode
	void help(vector<int> &num, int step) {
		int size = (int)num.size() - step;
		if (size == 0) {
			result.push_back(path);
			return;
		}
		int prev = q.front() - 1;
		for (int i = 0; i < size; i++) {
			int x = q.front();
			q.pop_front();
			if (x != prev) {
				path[step] = x;
				help(num, step + 1);
			}
			q.push_back(x);
			prev = x;
		}
	}
コード例 #4
0
void contract(int u,int v,int n)
{
        int anc=findancestor(u,v);
        SET(inblossom,0);
        reset(u,anc);reset(v,anc);
        if(base[u]!=anc)pre[u]=v;
        if(base[v]!=anc)pre[v]=u;
        for(int i=1;i<=n;i++)
                if(inblossom[base[i]])
                {
                        base[i]=anc;
                        if(!inque[i])
                        {
                                Q.push_back(i);
                                inque[i]=1;
                        }
                }
}
コード例 #5
0
    void inorder(TreeNode* &root, stack<pair<int, int>> &stk, int &cnt, deque<int> &dq) {
        if (!root) return; 

        inorder(root->left, stk, cnt, dq);
        dq.push_back(root->val);
        if (dq.size() > 2) dq.pop_front(); // trim deque when its length goes beyong 2     

        if (dq.front() == root->val) cnt++;
        else {
            if (dq.front() != INT_MIN && dq.front() != root->val && (stk.empty() || cnt >= stk.top().second)) {
                if (!stk.empty() && cnt > stk.top().second) while (!stk.empty()) stk.pop(); // when we meet better solution, clear the old one
                stk.push(pair<int, int>(dq.front(), cnt));
            }
            cnt = 1; // put it outside the above loop
        }

        inorder(root->right, stk, cnt, dq);
    }
コード例 #6
0
ファイル: copy1.cpp プロジェクト: riteme/test
    void process(int u, int p) {
        while (u != p) {
            int a = match[u];
            int b = link[a];

            if (uf.find(b) != p)
                link[b] = a;

            if (type[a] == ODD) {
                type[a] = EVEN;
                q.push_back(a);
            }

            uf.link(u, a);
            uf.link(a, b);
            u = b;
        }
    }
コード例 #7
0
ファイル: main.cpp プロジェクト: amoshyc/sfml-snake
    void restart() {
        // clean data
        data.clear();
        snake.clear();

        game_state = PLAYING;

        // construct data
        for (int i = 0; i < N; i++) {
            data.push_back(vector<int>(N, EMPTY));
        }

        // find some random, non-overlapping position
        vector<pii> v;
        for (int r = 0; r < N; r++) {
            for (int c = 0; c < N; c++) {
                v.push_back(pii(r, c));
            }
        }
        for (int i = 1; i < N * N; i++) { // shuffle
            int idx = randint(0, i);
            swap(v[i], v[idx]);
        }

        // init stones
        int stones_num = randint(0, 3);
        for (int i = 0; i < stones_num; i++) {
            int r = v.back().first;
            int c = v.back().second;
            data[r][c] = STONE;
            v.pop_back();
        }

        // init snake
        this->dir = randint(0, 3);
        int snake_init_r = v.back().first;
        int snake_init_c = v.back().second;
        data[snake_init_r][snake_init_c] = BODY;
        snake.push_back(pii(snake_init_r, snake_init_c));
        v.pop_back();

        // init first food
        this->generate_thing(FOOD);
    }
コード例 #8
0
  bool sendToServer(const std::string& a) 
  {
    cout<<endl<<"Request for -- "<<a<<"\t";
    unordered_map<string,string>::iterator it_map=FIFO_cache.find(a); 
    valueToReturn.clear();

    if(it_map==FIFO_cache.end()) /*Entry doesn't exist*/
    {
        valueToReturn=getBody(a);
        if (valueToReturn.length()>maximumCacheSize_FIFO)
        {
          cout<<"The requested content is much larger than cache size!"<<endl;
          valueToReturn="";
          return false;
        }

        cout<<"Cache Miss!"<<endl;

        int requiredSize=valueToReturn.length()+currentCacheSize_FIFO;

        if(requiredSize>=maximumCacheSize_FIFO)
          cout<<endl<<"Cache requires flushing now!"<<endl;

        for(deque<string>::iterator it_deque=FIFOref.begin();it_deque!=FIFOref.end() && requiredSize>=maximumCacheSize_FIFO;it_deque=FIFOref.begin())
          {
                cout<<"Removing "<<*it_deque<<endl;
                int temp=FIFO_cache[*it_deque].length();
                currentCacheSize_FIFO-=temp;
                requiredSize-=temp;
                FIFO_cache.erase(*it_deque);
                FIFOref.pop_front();
          }

        FIFO_cache.insert(pair<string,string>(a,valueToReturn));
        FIFOref.push_back(a);
        currentCacheSize_FIFO+=valueToReturn.length();
    }
    else
    {
      cout<<"Cache Hit!"<<endl;
      valueToReturn=FIFO_cache[it_map->first];
    }
    return true;
  }
コード例 #9
0
int main ( int argc, char* argv[] )
{
	ticket *task = new ticket();
	thread send_thread;

	try
	{
		// Create the socket
		ServerSocket r_server ( 30000 );

		active = true;
		send_thread = thread(send_th);

		ServerSocket r_sock;
		r_server.accept ( r_sock );
		cout << "Writer connacted" << endl;

		try
		{
			while ( true )
			{
				r_sock >> task;
				cout << "recv from 30000\n";
				// new_sock << task;

				// queue_mutex.lock();
				if (queue.size() < 10)
				{
					queue.push_back(task);
				}
				// queue_mutex.unlock();
			}
		} catch ( SocketException& e) {
			cout << e.description() << endl;
		}
	} catch ( SocketException& e ) {
		std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";
	}

	active = false;
	send_thread.join();

	return 0;
}
コード例 #10
0
ファイル: styler_syntax.cpp プロジェクト: baguatuzi/e
void Styler_Syntax::GetSubScopeIntervals(unsigned int pos, unsigned int offset, const submatch& sm, deque<interval>& scopes) const {
	for (auto_vector<stxmatch>::const_iterator p = sm.matches.begin(); p != sm.matches.end(); ++p) {
		const stxmatch& m = *(*p);

		if (pos >= m.start && pos < m.end) {
			if (!m.m_name.empty()) {
				scopes.push_back(interval(offset+m.start, offset+m.end));
			}

			// Check if there are submatches
			if (m.subMatch.get()) {
				wxASSERT(pos >= m.start);
				GetSubScopeIntervals(pos - m.start, offset+m.start, *m.subMatch, scopes);
			}
			return;
		}
		else if (m.start > pos) break;
	}
}
コード例 #11
0
bool appendTxtToOutput(string content){
	if (outputPath.compare("") == 0){
		MessageBox(hWnd, "Save log failed. Please set up output file and try to save again!", "WARNING", MB_OK);
		return false;
	}

	outputStream << content << endl;
	outputLog.push_back(content);
	while (outputLog.size() > SHOW_LOG_SIZE){
		outputLog.pop_front();
	}

	string log = "";
	for (int i = 0; i < outputLog.size(); i++){
		log += " " + outputLog.at(i) + "\n";
	}
	Set_Text(result_handle, (char*)log.c_str());
	return true;
}
コード例 #12
0
/**
 * Method name: addToHPRQueue
 * Description: goes through the processes vector and adds all unstarted processes to ready queue 
 * and sorts the queue by penalty ratio.
 * Parameters: processes vector, cpu object, and ready deque
 */
deque<int> addToHPRQueue(cpu cpu, deque<int> deque){
    
    vector<process> processesCopy = processes;
    sort(processesCopy.begin(), processesCopy.end(), comparePenalty);
    
    for(int i = 0; i < processesCopy.size(); i++){
        
        if(processesCopy[i].A <= cpu.time &&
           (processesCopy[i].state == process::UNSTARTED || processesCopy[i].state == process::READY) &&
           processesCopy[i].onQueue == false){
            
            int x = processesCopy[i].processID - 1;
            processes[x].onQueue = true;
            processes[x].state = process::READY;
            deque.push_back(x);
        }
    }
    return deque;
}
コード例 #13
0
ファイル: 1005_1.cpp プロジェクト: gemire/code
 int main(int argc, char *argv[])
 {
     while(cin>>ica>>icb>>cr)
     {
         travel.clear();
         result.clear();
         minStepNum=-1;
         
         seach(0,0);
         output.push_back(success);
         
         for(Iter iter=output.begin();iter!=output.end();++iter)
         {
             cout<<def[*iter]<<endl;      
         }                     
     }
   //  system("PAUSE");
     return EXIT_SUCCESS;
}
コード例 #14
0
void initVariables()
{
    interoculardistance = str2num<double>(parameters.find("IOD"));
    trial.init(parameters);
    factors = trial.getNext(); // Initialize the factors in order to start from trial 1

    redDotsPlane.setNpoints(75);  //XXX controllare densita di distribuzione dei punti
    redDotsPlane.setDimensions(50,50,0.1);

    redDotsPlane.compute();
    //stimDrawer.drawSpecialPoints();
    stimDrawer.setSpheres(true);
    stimDrawer.setStimulus(&redDotsPlane);
    stimDrawer.initList(&redDotsPlane);
    /** Bound check things **/
    signs.push_back(false);
    signs.push_back(false);
    rythmMaker.start();
}
コード例 #15
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;
 }
コード例 #16
0
ファイル: main.cpp プロジェクト: ekuri/Sicily
inline void BOperation(deque<string> &operationDeque, map<string, bool> &visitedMap, string currentMatrix) {
    char row1temp1 = currentMatrix[MATRIX_SIZE / 2 - 1];
    char row2temp1 = currentMatrix[MATRIX_SIZE - 1];
    char row1temp2, row2temp2;
    for (int count = 0; count < MATRIX_SIZE / 2; count++) {
        row1temp2 = currentMatrix[count];
        row2temp2 = currentMatrix[count + (MATRIX_SIZE / 2)];
        currentMatrix[count] = row1temp1;
        currentMatrix[count + (MATRIX_SIZE / 2)] = row2temp1;
        row1temp1 = row1temp2;
        row2temp1 = row2temp2;
    }
    string currentState = currentMatrix.substr(0, MATRIX_SIZE);
    if (visitedMap.find(currentState) != visitedMap.end()) {
        return;
    }
    visitedMap[currentState] = true;
    operationDeque.push_back(currentMatrix + 'B');
}
コード例 #17
0
bool contains(deque<T> &q, T sent) {
    deque<T> hold;
    bool holder = false;
    
    while(!q.empty()) {
        T t = q.front();
        hold.push_front(t);
        
        if(hold.front() == sent) {
            holder = true;
            while(!hold.empty()) {
                q.push_back(hold.back());
                hold.pop_back();
            }
            return holder;
        } else
            q.pop_front();
    
}
}
コード例 #18
0
ファイル: combinatorics.cpp プロジェクト: Aleyasen/Alaki
int powerlaw (int n, int min, double tau, deque<double> &cumulative) {
	
	cumulative.clear();
	double a=0;			

	for (double h=min; h<n+1; h++)
		a+= pow((1./h),tau);
	
	
	double pf=0;
	for(double i=min; i<n+1; i++) {
	
		pf+=1/a*pow((1./(i)),tau);
		cumulative.push_back(pf);
	
	}
	
	return 0;	
	
}
コード例 #19
0
void RNAProfileAlignment::getSequenceAlignment(deque<BaseProbs> &baseprob) const
{
	BaseProbs bp;

	// generate base strings
	for(size_type i=0;i<size();i++)
	{
		if(isBase(i))
		{	
			bp.a=label(i).p[ALPHA_PRO_BASE_A];
			bp.c=label(i).p[ALPHA_PRO_BASE_C];
			bp.g=label(i).p[ALPHA_PRO_BASE_G];
			bp.u=label(i).p[ALPHA_PRO_BASE_U];
			bp.gap=label(i).p[ALPHA_PRO_GAP];
			bp.base=bp.a+bp.c+bp.g+bp.u;

			baseprob.push_back(bp);
		}
	} 
}
コード例 #20
0
ファイル: turing.cpp プロジェクト: pbscrimmage/daily_prog
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 '^'
    }
}
コード例 #21
0
int compute_internal_degree_per_node(int d, int m, deque<int> & a) {
	
	
	// d is the internal degree
	// m is the number of memebership 
	
	a.clear();
	int d_i= d/m;
	for (int i=0; i<m; i++)
		a.push_back(d_i);
    
	for(int i=0; i<d%m; i++)
		a[i]++;
	
	
	
    
	return 0;
    
}
コード例 #22
0
void Solver::minimizeAndStoreUIPClause(LiteralID uipLit,
		vector<LiteralID> & tmp_clause, bool seen[]) {
	static deque<LiteralID> clause;
	clause.clear();
	assertion_level_ = 0;
	for (auto lit : tmp_clause) {
		if (existsUnitClauseOf(lit.var()))
			continue;
		bool resolve_out = false;
		if (hasAntecedent(lit)) {
			resolve_out = true;
			if (getAntecedent(lit).isAClause()) {
				for (auto it = beginOf(getAntecedent(lit).asCl()) + 1;
						*it != SENTINEL_CL; it++)
					if (!seen[it->var()]) {
						resolve_out = false;
						break;
					}
			} else if (!seen[getAntecedent(lit).asLit().var()]) {
				resolve_out = false;
			}
		}

		if (!resolve_out) {
			// uipLit should be the sole literal of this Decision Level
			if (var(lit).decision_level >= assertion_level_) {
				assertion_level_ = var(lit).decision_level;
				clause.push_front(lit);
			} else
				clause.push_back(lit);
		}
	}

	if(uipLit.var())
	 assert(var(uipLit).decision_level == stack_.get_decision_level());

	//assert(uipLit.var() != 0);
	if (uipLit.var() != 0)
		clause.push_front(uipLit);
	uip_clauses_.push_back(vector<LiteralID>(clause.begin(), clause.end()));
}
コード例 #23
0
ファイル: main.cpp プロジェクト: xufango/contrib_bk
    void localize(Bottle *bClassifier, vector<Blob> &blobs, deque<vector<CvPoint> > &matchedHistory)
    {
        string obj_name=bClassifier->get(0).asString().c_str();

        vector<CvPoint> tmpMatch;
        matchedHistory.push_back(tmpMatch);
        for(int i=2; i<bClassifier->size(); i+=2)
        {
            /*
            bool insert=true;
            for(unsigned int j=0; j<matchedHistory.back().size() && insert; j++)
                if(matchedHistory.back()[j].x==b->get(i).asInt() && matchedHistory.back()[j].y==b->get(i+1).asInt())
                    insert=false;
        
            if(insert)*/
                matchedHistory.back().push_back(cvPoint(bClassifier->get(i).asInt(),bClassifier->get(i+1).asInt()));
        }

        if(matchedHistory.size()>matched_max_size)
            matchedHistory.pop_front();

        //vector<CvPoint> matched;
        for(unsigned int n=0; n<matchedHistory.size(); n++)
        {
            for(unsigned int i=0; i<matchedHistory[n].size(); i++)
            {
                /*bool insert=true;
                for(unsigned int j=0; j<matched.size(); j++)
                {
                    if(abs(matchedHistory[n].at(i).x-matched[j].x)<1 && abs(matchedHistory[n].at(i).y-matched[j].y)<1)
                        insert=false;
                }

                if(insert)
                    matched.push_back(matchedHistory[n].at(i));*/

                for(unsigned int bl=0; bl<blobs.size(); bl++)
                    blobs[bl].vote(obj_name,matchedHistory[n].at(i));
            }
        }
    }
コード例 #24
0
ファイル: Background.cpp プロジェクト: KingMew/stepmania
void BackgroundImpl::LoadFromSong( const Song* pSong )
{
	Init();
	Unload();
	m_pSong = pSong;
	m_StaticBackgroundDef.m_sFile1 = SONG_BACKGROUND_FILE;

	if( g_fBGBrightness == 0.0f )
		return;

	// Choose a bunch of backgrounds that we'll use for the random file marker
	{
		vector<RString> vsThrowAway, vsNames;
		switch( g_RandomBackgroundMode )
		{
		default:
			ASSERT_M( 0, ssprintf("Invalid RandomBackgroundMode: %i", int(g_RandomBackgroundMode)) );
			break;
		case BGMODE_OFF:
			break;
		case BGMODE_ANIMATIONS:
			BackgroundUtil::GetGlobalBGAnimations( pSong, "", vsThrowAway, vsNames );
			break;
		case BGMODE_RANDOMMOVIES:
			BackgroundUtil::GetGlobalRandomMovies( pSong, "", vsThrowAway, vsNames, true, true );
			break;
		}

		// Pick the same random items every time the song is played.
		RandomGen rnd( GetHashForString(pSong->GetSongDir()) );
		random_shuffle( vsNames.begin(), vsNames.end(), rnd );
		int iSize = min( (int)g_iNumBackgrounds, (int)vsNames.size() );
		vsNames.resize( iSize );

		FOREACH_CONST( RString, vsNames, s )
		{
			BackgroundDef bd;
			bd.m_sFile1 = *s;
			m_RandomBGAnimations.push_back( bd );
		}
	}
コード例 #25
0
int main(int argc , char **argv)
{
	if(argc>1 && strcmp(argv[1],"DEBUG")==0) debug=true;
	pthread_t thread;
	cout<<"Welcome. Use the following commands to control sessions."<<endl;
	cout<<"open xyz    : open a new session on file xyz"<<endl;
	cout<<"show        : show all active sessions"<<endl;
	cout<<"exit        : exit from process"<<endl;
	cout<<"zoom in xyz : zoom in display associated with session id xyz"<<endl;
	cout<<"zoom out xyz: zoom out display associated with session id xyz"<<endl;
	cout<<"page up xyz      : scroll up display associated with session id xyz"<<endl;
	cout<<"page down xyz    : scroll down display associated with session id xyz"<<endl;
	int rc = pthread_create(&thread, NULL, listen, (void *)0);
	string cmd,arg;
	int nSessions,base=BASEPORT+1,pid[MAXPID],index=0;
	int id;
	char sys[1000];
	while(true){
		cin>>cmd;
		if(cmd=="show"){
			cout<<">>"<<show_all();
		}
		else if(cmd=="exit")break;
		else if(cmd=="open"){
			cin>>arg;
			sessions.push_back(make_pair(base++,arg));
			if(index==MAXPID){
				cout<<"cannot open more files"<<endl;
				continue;
			}
			pid[index++]=fork();
			if(pid[index-1]==0){
				idx=base-BASEPORT-2;
				signal(SIGHUP , zoomin);
				signal(SIGINT , zoomout);
				signal(SIGUSR1 , pageup);
				signal(SIGUSR2 , pagedown);
				broadcast(base-1);
			}
		}
		else if(cmd=="zoom"){
コード例 #26
0
ファイル: main.cpp プロジェクト: havluj/forex
void* CArbitrageProducer(Functions* atr)
{
	while(true) {
		CArbitrage* ptr = atr->cArb();
		if(ptr == NULL) {
			break;
		} else {
			Data data;
			data.isExchange = false;
			data.cAr_ptr = ptr;

			sem_wait(&SemFree);
			pthread_mutex_lock(&CConsultantMutex);
			buffer.push_back(data);
			pthread_mutex_unlock(&CConsultantMutex);
			sem_post(&SemFull);
		}
	}

	return NULL;
}
コード例 #27
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;
}
コード例 #28
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;
}
コード例 #29
0
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;
	
}
コード例 #30
0
bool ParseClassPath(const string& pathString, deque<string>& pathList)
{
  string::size_type startPosition = 0;
  string::size_type colonPosition;
  do {
    colonPosition = pathString.find(PATHSEPCHAR, startPosition);
    if (colonPosition > pathString.size()) {
      colonPosition = pathString.size();
    }
    string directoryName(pathString, startPosition,
			 colonPosition - startPosition);
    CJavaDirectory path(directoryName);
    if (path.IsValid()) {
      pathList.push_back(directoryName);
    } else {
      cerr << ">> Warning: Invalid classpath entry " << directoryName << endl;
    }
    startPosition = colonPosition + 1;
  } while(colonPosition < pathString.size());
  return !pathList.empty();
}