int main() { //freopen ("maze1.txt","r",stdin); freopen ("maze1.in","r",stdin); freopen ("maze1.out","w",stdout); int r, c, i, j, k; cin >> c >> r; gets (s[0]); for (i = 0; i <= 2*r; i++) gets (s[i]); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { if (s[2*i][2*j+1] == ' ') v[i][j][0] = 1; if (s[2*i+1][2*j+2] == ' ') v[i][j][1] = 1; if (s[2*i+2][2*j+1] == ' ') v[i][j][2] = 1; if (s[2*i+1][2*j] == ' ') v[i][j][3] = 1; } } //for (i = 0; i <= 2*r; i++) //for (j = 0; j <= 2*c; j++) PII now, e[2]; pair <PII,int> cur; j = 0; for (i = 0; i < r; i++) { if (v[i][0][3]) { v[i][0][3] = 0; e[j] = make_pair (i,0); j++; } } for (i = 0; i < c; i++) { if (v[0][i][0]) { e[j] = make_pair (0,i); v[0][i][0] = 0; j++; } } for (i = 0; i < r; i++) { if (v[i][c-1][1]) { e[j] = make_pair (i,c-1); v[i][c-1][1] = 0; j++; } } for (i = 0; i < c; i++) { if (v[r-1][i][2]) { e[j] = make_pair (r-1,i); v[r-1][i][2] = 0; j++; } } //cout << j << endl; q.push (make_pair (e[0], 1)); q.push (make_pair (e[1], 1)); int ans = 0; while (!q.empty()){ cur = q.front(); q.pop(); now = cur.x; if (a[now.x][now.y]) continue; a[now.x][now.y] = 1; //cout << now.x << " " << now.y << endl; ans = max (ans, cur.y); for (i = 0; i < 4; i++) { if (now.x + X[i] < 0 || now.x + X[i] >= r) continue; if (now.y + Y[i] < 0 || now.y + Y[i] >= c) continue; if (!v[now.x][now.y][i]) continue; if (a[now.x+X[i]][now.y+Y[i]]) continue; q.push (make_pair (make_pair (now.x+X[i],now.y+Y[i]),cur.y+1)); } } cout << ans << endl; return 0; }
int main() { //ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("000.txt","r",stdin); //freopen("output.txt", "w", stdout); #endif /// MAIN int i, t, j, k, l, keis=0, a, b, d, x, y; takei(t); while(t--) { takei(r); takei(c); //getchar(); for(i=0; i<r; i++) scanf("%s", mat[i]); for(i=0; i<r; i++) for(j=0; j<c; j++) level[0][i][j] = level[1][i][j] = 1000006; while(qu1.size()) qu1.pop(); while(qu2.size()) qu2.pop(); for(i=0; i<r; i++) for(j=0; j<c; j++) if(mat[i][j]=='J') { qu1.push(i); qu1.push(j); level[0][i][j]=0; i = j = r*c; } for(i=0; i<r; i++) for(j=0; j<c; j++) if(mat[i][j]=='F') { qu2.push(i); qu2.push(j); level[1][i][j] = 0; } BFS1(); BFS2(); int ans = 1000006; for(i=0; i<c; i++) for(j=0; j<c; j++) { if(i==0 or j==0 or i==r-1 or j==c-1) { if(level[0][i][j]<level[1][i][j]) ans = min(ans, level[0][i][j]); } } if(ans < 1000006) pf("%d\n", ans+1); else pf("IMPOSSIBLE\n"); } /* Coding is FUN */ /// ENDD return 0; }
int main( ) { freopen( "ttwo.in", "r", stdin ); freopen( "ttwo.out", "w", stdout ); for ( int i = 1; i < MAXN; ++i ) { for ( int j = 1; j < MAXN; ++j ) { scanf( " %c", &maze[i][j] ); } } for ( int i = 0; i <= MAXN; ++i ) { maze[0][i] = '*'; maze[MAXN][i] = '*'; maze[i][0] = '*'; maze[i][MAXN] = '*'; } state start; for ( int i = 1; i <= MAXN; ++i ) for ( int j = 1; j <= MAXN; ++j ) { if ( maze[i][j] == 'F' ) { start.john_x = i; start.john_y = j; start.john_dir = NORTH; maze[i][j] = '.'; }else if ( maze[i][j] == 'C' ) { start.cow_x = i; start.cow_y = j; start.cow_dir = NORTH; maze[i][j] = '.'; } } start.cost = 0; q.push( start ); s.insert( vstate( start ) ); if ( check( start ) ) { printf( "0\n" ); return 0; } while ( !q.empty() ) { state top = q.front(); q.pop(); ++top.cost; state tmp = top; if ( valid( top.cow_x + dx[ top.cow_dir ], top.cow_y + dy[ top.cow_dir ] ) ) { if ( maze[ top.cow_x + dx[ top.cow_dir ] ][ top.cow_y + dy[ top.cow_dir ] ] == '*' ) { tmp.cow_dir += 1; tmp.cow_dir %= MODN; }else { tmp.cow_x += dx[ tmp.cow_dir ]; tmp.cow_y += dy[ tmp.cow_dir ]; } }else { tmp.cow_dir += 1; tmp.cow_dir %= MODN; } if ( valid( top.john_x + dx[ top.john_dir ], top.john_y + dy[ top.john_dir ] ) ) { if ( maze[ top.john_x + dx[ top.john_dir ] ][ top.john_y + dy[ top.john_dir ] ] == '*' ) { tmp.john_dir += 1; tmp.john_dir %= MODN; }else { tmp.john_x += dx[ tmp.john_dir ]; tmp.john_y += dy[ tmp.john_dir ]; } }else { tmp.john_dir += 1; tmp.john_dir %= MODN; } if ( s.find( vstate( tmp ) ) == s.end( ) ) { q.push( tmp ); s.insert( vstate( tmp ) ); if ( check( tmp ) ) { printf( "%d\n", tmp.cost ); found = true; break; } } } if ( !found ) { printf( "0\n" ); } return 0; }
/** @return the next smallest number */ int next() { int ret = q.front(); q.pop(); return ret; }
/* tournamentResults() outputs the results of the tournament. It first gets the name of the team that still has living fighters. It then copies all fighters to a vector and adds the team points together, and then sorts the vector in descending order based on points. The function outputs the team with the last member(s) standing, then the winning team points, then the individual winners. Input: first team's queue of Creature pointers, first team's stack of loser Creature pointers, second team's queue of Creature pointers, second team's stack of loser Creature pointers Output: none */ void tournamentResults(queue<Creature*>& lineup1, stack<Creature*>& loser1, queue<Creature*>& lineup2, stack<Creature*>& loser2) { vector<Creature*> standings; // store team with members still in queue // last team standing string lastTeam; if (!lineup1.empty()) { lastTeam = lineup1.front()->showTeam(); } else { lastTeam = lineup2.front()->showTeam(); } // get team names before putting fighters into the vector string team1; if (!lineup1.empty()) { team1 = lineup1.front()->showTeam(); } else { team1 = loser1.top()->showTeam(); } string team2; if (!lineup2.empty()) { team2 = lineup2.front()->showTeam(); } else { team2 = loser2.top()->showTeam(); } // get team points while putting fighters into vector int teamPts1 = 0; // copy all Creatures to a vector while (!lineup1.empty()) { teamPts1 += lineup1.front()->showPoints(); standings.push_back(lineup1.front()); lineup1.pop(); } while (!loser1.empty()) { teamPts1 += loser1.top()->showPoints(); standings.push_back(loser1.top()); loser1.pop(); } int teamPts2 = 0; while (!lineup2.empty()) { teamPts2 += lineup2.front()->showPoints(); standings.push_back(lineup2.front()); lineup2.pop(); } while (!loser2.empty()) { teamPts2 += loser2.top()->showPoints(); standings.push_back(loser2.top()); loser2.pop(); } // sort in descending order by points the fighters // bubble sort Creature* temp; bool swap; do { swap = false; for (unsigned int i = 0; i < (standings.size() - 1); i++) { if (standings.at(i)->showPoints() < standings.at(i + 1)->showPoints()) { temp = standings.at(i); standings.at(i) = standings.at(i + 1); standings.at(i + 1) = temp; swap = true; } } } while (swap); // // debugging // for (unsigned int i = 0; i < standings.size(); i++) // { // cout << standings.at(i)->showPoints() << endl; // } // cout << teamPts1 << " " << teamPts2 << endl; cout << "Team results: " << endl; cout << "The team with the last member(s) standing: " << lastTeam << "!" << endl; if (teamPts1 > teamPts2) { cout << team1 << " wins with a total of " << teamPts1 << " points!" << endl; cout << team2 << " had " << teamPts2 << " points." << endl << endl; } else if (teamPts2 > teamPts1) { cout << team2 << " wins with a total of " << teamPts2 << " points!" << endl; cout << team1 << " had " << teamPts1 << " points." << endl << endl; } else { cout << team1 << " and " << team2 << " tied with " << teamPts1 << " points each!" << endl << endl; } cout << "Individual results: " << endl; // if less than 3 total fighters // program does not allow for 0 fighters, technically shouldn't allow for // just 1, either, but just in case... if (standings.size() < 3) { cout << "Something's wrong. You should have at least 4 total fighers." << endl; exit(1); } else { // ignoring ties cout << "First place: " << standings.at(0)->showTeam() << "'s " << standings.at(0)->showName() << " the " << standings.at(0)->showType() << ", with " << standings.at(0)->showPoints() << " points!" << endl; cout << "Second place: " << standings.at(1)->showTeam() << "'s " << standings.at(1)->showName() << " the " << standings.at(1)->showType() << ", with " << standings.at(1)->showPoints() << " points!" << endl; cout << "Third place: " << standings.at(2)->showTeam() << "'s " << standings.at(2)->showName() << " the " << standings.at(2)->showType() << ", with " << standings.at(2)->showPoints() << " points!" << endl; } cout << endl << endl; // deleting objects from memory, not just the pointers to the objects // the pop operations earlier just deleted pointers for (unsigned int i = 0; i < standings.size(); i++) { Creature* temp2 = standings.at(i); delete temp2; // if the destructor in creature.cpp and creature.h is commented out // you can see the confirmation messages } standings.clear(); // removes all elements from the vector and destroys them // (according to STL documentation) // the vector is actually a vector of pointers, not objects }
template<class T> inline void CLR(queue<T> &Q){while (!Q.empty()) Q.pop();}
/** * @brief This function is called by the XF when an event must be handled. */ EventStatus processEvent() { IXFEvent *e = getCurrentEvent(); _oldState = _state; _oldAdvertiseSubstate = _advertiseSubstate; _oldEstablishConnectionSubstate = _establishConnectionSubstate; _oldConnectedSubstate = _connectedSubstate; switch( _state ) { case Initialize: if ( e->getEventType() == XFEvent::Initial ) _state = Idle; break; case Idle: if ( e->getEventType() == XFEvent::Event && e->getId() == StartAdvertiseRequestEvent::Id ){ _state = Advertise; _advertiseSubstate = WaitForAdvertiseData; } break; case Advertise: SubMachineAdvertise(e); if ( e->getEventType() == XFEvent::Event && e->getId() == ConnectionRequestEvent::Id ) _state = EstablishConnection; else if ( e->getEventType() == XFEvent::Event && e->getId() == ConnectionIndicationEvent::Id ) _state = AcceptConnection; else if ( e->getEventType() == XFEvent::Event && e->getId() == StopAdvertiseRequestEvent::Id ) _state = Idle; break; case EstablishConnection: SubMachineEstablishConnection(e); // if we request the connection, we are master role = MASTER; if ( e->getEventType() == XFEvent::Timeout && e->getId() == EstablishConnectionTimeout::Id ) // timeout _state = Advertise; else if ( e->getEventType() == XFEvent::Event && e->getId() == ConnectionConfirmationEvent::Id ) _state = Connected; break; case AcceptConnection: //TODO Send accept connection data // create AdvPdu with type Connect // create frame with AdvPdu // send frame with transceiver // get ack from phy layer about // if we didn't requested the connection, we are slave role = SLAVE; _state = Connected; break; case Connected: // call the "Connected" submachine and test if it returns a disconnection switch( SubMachineConnected(e) ) { case LINK_LOSS: // in case of link loss, restart connection _state = Advertise; break; case DISCONNECT: // if peer (or local) asked for disconnection, go idle _state = Idle; break; default: break; } break; } /* MEALY * Some actions requires to be done only on state transition, * and not when staying in same state. */ /* Action on entry */ if( _state != _oldState ) { switch( _state ) { case Initialize: Trace::out("->[Initialize global state machine]"); break; case Idle: Trace::out("->[Idle]"); break; case Advertise: Trace::out("->[Advertise]"); break; case EstablishConnection: Trace::out("->[EstablishConnection]"); getThread()->scheduleTimeout(EstablishConnectionTimeout::Id, ESTABLISH_CONNECTION_TIMEOUT, this); break; case AcceptConnection: Trace::out("->[AcceptConnection]"); pushEvent( new XFNullTransition( WaitNullTransition::Id ) ); break; case Connected: Trace::out("->[Connected]"); break; default: Trace::out("->[undefined state error]"); break; } } if( _advertiseSubstate != _oldAdvertiseSubstate ) { switch( _advertiseSubstate ) { case AdvertiseInitialize: Trace::out("->[Initialize advertisement phase state machine]"); break; case WaitForAdvertiseData: Trace::out("\t- WaitForAdvertiseData"); getThread()->scheduleTimeout(AdvertiseIntervalTimeout::Id, ADVERTISE_INTERVAL_TIMEOUT, this); break; case SendAdvertise: Trace::out("\t- sending my advertise"); pushEvent( new XFNullTransition( WaitNullTransition::Id ) ); break; case ProcessAdvertiseData: Trace::out("\t- processing advertise received"); pushEvent( new XFNullTransition( WaitNullTransition::Id ) ); break; default: Trace::out("\t- undefined state error"); break; } } if( _establishConnectionSubstate != _oldEstablishConnectionSubstate ) { switch( _establishConnectionSubstate ) { case EstablishConnectionInitialize: Trace::out("->[Initialize connection establishment state machine]"); break; case WaitForConnectionData: Trace::out("\t- wait for connection data"); break; case ProcessConnectionData: Trace::out("\t- process connection data"); pushEvent( new XFNullTransition( WaitNullTransition::Id ) ); break; default: Trace::out("\t- undefined state error"); break; } } if( _connectedSubstate != _oldConnectedSubstate ) { switch( _connectedSubstate ) { case ConnectedInitialize: Trace::out("\t- initialize data transfer (alias 'connected') state machine"); break; case SendQueuedDataPdu: Trace::out("\t- send queued data pdu"); if(!txQueue.empty()) { _transceiver->send(txQueue.front()); txQueue.pop(); } break; case WaitDataPdu: Trace::out("\t- wait data pdu"); getThread()->scheduleTimeout(ConnectionPduMaxTimeout::Id, CONNECTION_PDU_MAX_TIMEOUT, this); break; case ProcessDataPdu: Trace::out("\t- process data pdu"); pushEvent( new XFNullTransition( WaitNullTransition::Id ) ); break; case CloseConnection: Trace::out("\t- close connection"); break; case WaitForNextConnectionEvent: Trace::out("\t- wait for connection"); getThread()->scheduleTimeout(ConnectionIntervalTimeout::Id, CONNECTION_INTERVAL_TIMEOUT, this); break; case EnableTransceiver: Trace::out("\t- enable transceiver"); break; default: Trace::out("\t- undefined state error"); break; } } /* Actions on exit */ if( _oldState != _state) { switch( _oldState ) { case EstablishConnection: getThread()->unscheduleTimeout(EstablishConnectionTimeout::Id, this); break; default: break; } } if( _oldAdvertiseSubstate != _advertiseSubstate ) { switch( _oldAdvertiseSubstate ) { case WaitForAdvertiseData: getThread()->unscheduleTimeout(AdvertiseIntervalTimeout::Id, this); break; default: break; } } if( _oldConnectedSubstate != _connectedSubstate) { switch( _oldConnectedSubstate ) { case WaitDataPdu: getThread()->unscheduleTimeout(ConnectionPduMaxTimeout::Id, this); break; case WaitForNextConnectionEvent: getThread()->unscheduleTimeout(ConnectionIntervalTimeout::Id, this); break; default: break; } } return EventStatus::Consumed; //TODO : not necessary consumed... }
int main(void) { freopen("holstein.in", "r", stdin); freopen("holstein.out", "w", stdout); cin >> V; for (int i=1;i<=V;i++) cin >> v[i]; cin >> G; for (int i=1;i<=G;i++) for (int j=1;j<=V;j++) cin >> g[i][j]; for (int i=1;i<=G;i++) { bool flag=true; for (int j=1;j<=V;j++) { if (g[i][j]<v[j]) { flag=false; break; } } if (flag==true) { cout << 1 << " " << i << endl; return 0; } } State t; for (int i=1;i<=G;i++) t.s[i]=false; for (int i=1;i<=V;i++) t.c[i]=0; search(t, G); State s=t; int minimum=G+1; while(!q.empty()) { State st=q.front(); q.pop(); int leng=length(st); if (leng!=0) { if (leng<minimum) { minimum=leng; s=st; } } } int path[16]={0}; int sum=0; for (int k=1;k<=G;k++) if (s.s[k]==true) { sum++; path[sum]=k; } cout << sum << " "; for (int k=1;k<sum;k++) cout << path[k] << " "; cout << path[sum] << endl; return 0; }
void phasepoints(Parameter& xi, Parameters params, queue<Point>& points, vector<PointResults>& pres, progress_display& progress) { int ndim = 2 * L * dim; boost::random::mt19937 xrng; boost::random::uniform_real_distribution<> xuni(0, 1); vector<double> xrand(ndim); for (int i = 0; i < ndim; i++) { xrand[i] = xuni(xrng); } vector<double> x(ndim); vector<complex<double>*> f(L); for (int i = 0; i < L; i++) { f[i] = reinterpret_cast<complex<double>*> (&x[2 * i * dim]); } vector<double> U(L), J(L), dU(L); vector<double> x0(ndim), xth(ndim), x2th(ndim); vector<complex<double>*> f0(L); for (int i = 0; i < L; i++) { f0[i] = reinterpret_cast<complex<double>*> (&x0[2 * i * dim]); } vector<vector<double> > fabs(L, vector<double>(dim)); vector<double> fn0(L); vector<double> fmax(L); vector<double> norms(L); double theta = params.theta; double scale = 1; GroundStateProblem* prob; opt lopt(LD_LBFGS, ndim); opt gopt(GN_DIRECT, ndim); // energyprob eprob(ndim); // pagmo::algorithm::de_1220 algo(100); // int npop = 20; { boost::mutex::scoped_lock lock(problem_mutex); prob = new GroundStateProblem(); lopt.set_lower_bounds(-1); lopt.set_upper_bounds(1); lopt.set_min_objective(energyfunc, prob); gopt.set_lower_bounds(-1); gopt.set_upper_bounds(1.1); gopt.set_min_objective(energyfunc, prob); gopt.set_maxtime(120); // lopt.set_maxtime(120); // lopt.set_ftol_abs(1e-17); // lopt.set_ftol_rel(1e-17); // eprob.setProblem(prob); } for (;;) { Point point; { boost::mutex::scoped_lock lock(points_mutex); if (points.empty()) { break; } point = points.front(); points.pop(); } PointResults pointRes; pointRes.W = point.x; pointRes.mu = point.mu; vector<double> W(L); for (int i = 0; i < L; i++) { W[i] = xi[i] * point.x; } double U0 = 1 / scale; // for (int i = 0; i < L; i++) { // U[i] = UW(W[i]) / UW(point.x) / scale; // U0 += U[i] / L; // } for (int i = 0; i < L; i++) { U[i] = UW(W[i]) / UW(point.x) / scale; // U[i] = 1 / scale; dU[i] = U[i] - U0; J[i] = JWij(W[i], W[mod(i + 1)]) / UW(point.x) / scale; // J[i] = JWij(point.x, point.x) / UW(point.x) / scale; } pointRes.Ux = UW(point.x); pointRes.Jx = JWij(point.x, point.x); pointRes.J = J; pointRes.U = U; // fill(x0.begin(), x0.end(), 0.5); // fill(xth.begin(), xth.end(), 0.5); // fill(x2th.begin(), x2th.end(), 0.5); // generate(x0.begin(), x0.end(), randx); // generate(xth.begin(), xth.end(), randx); // generate(x2th.begin(), x2th.end(), randx); x0 = xrand; xth = xrand; x2th = xrand; prob->setParameters(U0, dU, J, point.mu / scale); // generate(x0.begin(), x0.end(), randx); // generate(xth.begin(), xth.end(), randx); // generate(x2th.begin(), x2th.end(), randx); prob->setTheta(0); double E0; string result0; try { prob->start(); // population pop0(eprob, npop); // algo.evolve(pop0); // E0 = pop0.champion().f[0]; // x0 = pop0.champion().x; // result gres = gopt.optimize(x0, E0); result res = lopt.optimize(x0, E0); prob->stop(); result0 = to_string(res); // E0 = prob->solve(x0); } catch (std::exception& e) { prob->stop(); result res = lopt.last_optimize_result(); result0 = to_string(res) + ": " + e.what(); printf("Ipopt failed for E0 at %f, %f\n", point.x, point.mu); cout << e.what() << endl; E0 = numeric_limits<double>::quiet_NaN(); } pointRes.status0 = result0; // pointRes.status0 = prob->getStatus(); pointRes.runtime0 = prob->getRuntime(); norms = norm(x0); for (int i = 0; i < L; i++) { for (int n = 0; n <= nmax; n++) { x0[2 * (i * dim + n)] /= norms[i]; x0[2 * (i * dim + n) + 1] /= norms[i]; } transform(f0[i], f0[i] + dim, fabs[i].begin(), std::ptr_fun<const complex<double>&, double>(abs)); fmax[i] = *max_element(fabs[i].begin(), fabs[i].end()); fn0[i] = fabs[i][1]; } pointRes.fmin = *min_element(fn0.begin(), fn0.end()); pointRes.fn0 = fn0; pointRes.fmax = fmax; pointRes.f0 = x0; pointRes.E0 = E0; theta = params.theta; double count = 0; for (int j = 0; j < 1; j++) { count = j; // for (int thi = 0; thi < 10; thi++) { // generate(xth.begin(), xth.end(), randx); // generate(x2th.begin(), x2th.end(), randx); if (j == 1) { copy(x0.begin(), x0.end(), xth.begin()); copy(x0.begin(), x0.end(), x2th.begin()); } prob->setTheta(theta); double Eth; string resultth; try { prob->start(); // population popth(eprob, npop); // algo.evolve(popth); // Eth = popth.champion().f[0]; // xth = popth.champion().x; // result gres = gopt.optimize(xth, Eth); result res = lopt.optimize(xth, Eth); prob->stop(); resultth = to_string(res); // Eth = prob->solve(xth); } catch (std::exception& e) { prob->stop(); result res = lopt.last_optimize_result(); resultth = to_string(res) + ": " + e.what(); printf("Ipopt failed for Eth at %f, %f\n", point.x, point.mu); cout << e.what() << endl; Eth = numeric_limits<double>::quiet_NaN(); } pointRes.statusth = resultth; // pointRes.statusth = prob->getStatus(); pointRes.runtimeth = prob->getRuntime(); norms = norm(xth); for (int i = 0; i < L; i++) { for (int n = 0; n <= nmax; n++) { xth[2 * (i * dim + n)] /= norms[i]; xth[2 * (i * dim + n) + 1] /= norms[i]; } } pointRes.fth = xth; pointRes.Eth = Eth; // prob->setTheta(2 * theta); // // double E2th; // string result2th; // try { // prob->start(); //// population pop2th(eprob, npop); //// algo.evolve(pop2th); //// E2th = pop2th.champion().f[0]; //// x2th = pop2th.champion().x; //// result gres = gopt.optimize(x2th, E2th); // result res = lopt.optimize(x2th, E2th); // prob->stop(); // result2th = to_string(res); // // E2th = prob->solve(x2th); // } catch (std::exception& e) { // prob->stop(); // result res = lopt.last_optimize_result(); // result2th = to_string(res) + ": " + e.what(); // printf("Ipopt failed for E2th at %f, %f\n", point.x, point.mu); // cout << e.what() << endl; // E2th = numeric_limits<double>::quiet_NaN(); // } // pointRes.status2th = result2th; // // pointRes.status2th = prob->getStatus(); // pointRes.runtime2th = prob->getRuntime(); // // norms = norm(x2th); // for (int i = 0; i < L; i++) { // for (int n = 0; n <= nmax; n++) { // x2th[2 * (i * dim + n)] /= norms[i]; // x2th[2 * (i * dim + n) + 1] /= norms[i]; // } // } // // pointRes.f2th = x2th; // pointRes.E2th = E2th; // // pointRes.fs = (E2th - 2 * Eth + E0) / (L * theta * theta); pointRes.fs = (Eth - E0) / (L * theta * theta); if (pointRes.fs > -1e-5) { break; } else { // theta *= 0.4641588833612779; } } pointRes.theta = count;//theta; { boost::mutex::scoped_lock lock(points_mutex); pres.push_back(pointRes); } { boost::mutex::scoped_lock lock(progress_mutex); ++progress; } } { boost::mutex::scoped_lock lock(problem_mutex); delete prob; } }
int main() { ios_base::sync_with_stdio(false); cin >> n >> m >> k; for (ll i=0,u,v,w; i<m; ++i) { cin >> u >> v >> w; e[u].push_back(edge(v, w, i+1)); e[v].push_back(edge(u, w, i+1)); } for (ll i=0,s,y; i<k; ++i) { cin >> s >> y; e[1].push_back(edge(s, y, m+i+1)); e[s].push_back(edge(1, y, m+i+1)); } memset(d, 0x3f, sizeof(d)); memset(can_change, true, sizeof(can_change)); d[1] = 0; q.push(1); inq[1] = true; while (!q.empty()) { ll x = q.front(); q.pop(); inq[x] = false; for (auto &ed: e[x]) { ll y = ed.to, w = ed.cost, id = ed.id; if (d[y] > d[x] + w) { d[y] = d[x] + w; p[y].clear(); if (id > m) { can_change[y] = true; p[y].push_back(id); } else { can_change[y] = false; } if (!inq[y]) { inq[y] = true; q.push(y); } } else if (d[y] == d[x] + w) { if (id > m) { if (can_change[y]) p[y].push_back(id); } else { can_change[y] = false; p[y].clear(); } } } } // for (ll i=1; i<=n; ++i) cout << d[i] << " "; cout << endl; for (ll i=1; i<=n; ++i) if (!p[i].empty()) { bool skip = false; for (auto id: p[i]) { if (v[id-m]) { skip = true; break; } } if (!skip) v[p[i].front()-m] = true; } ll cnt = 0; // for (ll i=1; i<=k; ++i) if (!v[i]) cout << m+i << " "; cout << endl; for (ll i=1; i<=k; ++i) if (!v[i]) ++cnt; cout << cnt << endl; return 0; }
void testcase() { while(!q.empty()) { q.pop(); } memset(dp, -1, sizeof(dp)); target_x = start_x = target_y = start_y = -1; for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { scanf("%c", &board[j][i]); if(board[j][i] == 'S') { start_x = j; start_y = i; board[j][i] = '.'; } else if(board[j][i] == 'T') { target_x = j; target_y = i; board[j][i] = '.'; } // printf("%c", board[j][i]); } scanf("\n"); // printf("\n"); } if(start_x == -1 || start_y == -1 || target_x == -1 || target_y == -1) { printf("destination not reachable\n"); return; } state tmp; tmp.x = start_x; tmp.y = start_y; tmp.facing = 0; tmp.color = 0; tmp.time = 0; q.push(tmp); while(!q.empty()) { state f = q.front(); // printf("S x%d y%d f%d c%d t%d\n", f.x, f.y, f.facing, f.color, f.time); q.pop(); f.time++; // turn left TURN_LEFT(f); if(!EXISTS(f)) { SETDP(f); q.push(f); } // turn right TURN_RIGHT(f); TURN_RIGHT(f); if(!EXISTS(f)) { SETDP(f); q.push(f); } TURN_LEFT(f); // move fwd switch(f.facing) { // N case 0: f.y--; break; // E case 1: f.x++; break; // S case 2: f.y++; break; // W case 3: f.x--; break; } CYCLE_COLOR(f); // check if we can move fwd if(f.x >= 0 && f.x < N && f.y >= 0 && f.y < M && board[f.x][f.y] != '#') { if(f.x == target_x && f.y == target_y && f.color == 0) { // printf("S x%d y%d f%d c%d t%d\n", f.x, f.y, f.facing, f.color, f.time); printf("minimum time = %d sec\n", f.time); return; } if(!EXISTS(f)) { SETDP(f); q.push(f); } } } printf("destination not reachable\n"); }
void QueueSequence::queue2_sequence(int queue2_element1,int queue2_element2){ int step1_counter=0,swap=0,step2_counter,step3_counter,manage_queue2; step3_counter=queue2_operator1.size(); while(!(queue2_operator1.front()==queue2_element1 || queue2_operator1.front()==queue2_element2)) { exchange_temp3=queue2_operator1.front(); queue2_operator1.pop(); queue2_operator1.push(exchange_temp3); step1_counter++; } exchange_temp3=queue2_operator1.front(); queue2_operator1.pop(); queue2_operator2.push(exchange_temp3); swap=1; while(!(queue2_operator1.front()==queue2_element1 || queue2_operator1.front()==queue2_element2)) { if(swap==1){ queue2_operator3.push(queue2_operator1.front()); queue2_operator1.pop(); while(!queue2_operator2.empty()){ queue2_operator3.push(queue2_operator2.front()); queue2_operator2.pop(); } swap=0; } else{ queue2_operator2.push(queue2_operator1.front()); queue2_operator1.pop(); while(!queue2_operator3.empty()){ queue2_operator2.push(queue2_operator3.front()); queue2_operator3.pop(); } swap=1; } } if(swap==1){ queue2_operator3.push(queue2_operator1.front()); queue2_operator1.pop(); while(!queue2_operator2.empty()){ queue2_operator3.push(queue2_operator2.front()); queue2_operator2.pop(); } step2_counter=queue2_operator3.size(); while(!queue2_operator3.empty()){ queue2_operator1.push(queue2_operator3.front()); queue2_operator3.pop(); } } else{ queue2_operator2.push(queue2_operator1.front()); queue2_operator1.pop(); while(!queue2_operator3.empty()){ queue2_operator2.push(queue2_operator3.front()); queue2_operator3.pop(); } step2_counter=queue2_operator2.size(); while(!queue2_operator2.empty()){ queue2_operator1.push(queue2_operator2.front()); queue2_operator2.pop(); } } manage_queue2=step3_counter-(step2_counter+step1_counter); while(manage_queue2--) { exchange_temp3=queue2_operator1.front(); queue2_operator1.pop(); queue2_operator1.push(exchange_temp3); } }
Relation* Insert(vector<string> &words, string &line, SchemaManager &schema_manager, MainMemory &mem){ Relation* relation_ptr = schema_manager.getRelation(words[2]); vector<string>::iterator it = find(words.begin(), words.end(), "SELECT"); // no select if (it == words.end()){ // get insert vals vector<string> content = splitBy(line, "()"); vector<string> fields = splitBy(content[1], ", "); vector<string> vals = splitBy(content[3], ","); //preProcess(vector<string>(1, words[2]), fields, schema_manager); preProcess(vector<string>(1, words[2]), vals, schema_manager); assert(fields.size() == vals.size()); Tuple tuple = relation_ptr->createTuple(); // standard insert doesn't have table names vector<string> col_names = nakedFieldNames(relation_ptr); // comparing for (int i = 0; i < fields.size(); i++){ for (int j = 0; j < col_names.size(); j++){ // this is a match if (fields[i] == col_names[j]){ if (tuple.getSchema().getFieldType(j) == INT){ tuple.setField(j, atoi(vals[i].c_str())); } else{ tuple.setField(j, vals[i]); } break; } } } appendTupleToRelation(relation_ptr, mem, tuple); } // with SELECT else{ vector<string> SFW(it, words.end()); Relation* new_relation = Select(SFW, schema_manager, mem); assert(new_relation); vector<string> new_field_names = nakedFieldNames(new_relation); vector<string> field_names = nakedFieldNames(relation_ptr); // mapping: index of new_field_names to field_names vector<int> mapping(new_field_names.size(), -1); for (int i = 0; i < new_field_names.size(); i++){ for (int j = 0; j < field_names.size(); j++){ if (new_field_names[i] == field_names[j]){ mapping[i] = j; break; } } } int new_field_size = new_relation->getSchema().getNumOfFields(); // warning: new_relation and relation_ptr might be the same! // get all tuples from the new_relation in one run vector<Tuple> new_tuples; for (int i = 0; i < new_relation->getNumOfBlocks(); i++){ assert(!free_blocks.empty()); int memory_block_index = free_blocks.front(); free_blocks.pop(); // read the relation block by block new_relation->getBlock(i, memory_block_index); Block* block_ptr = mem.getBlock(memory_block_index); assert(block_ptr); vector<Tuple> block_tuples = block_ptr->getTuples(); new_tuples.insert(new_tuples.end(), block_tuples.begin(), block_tuples.end()); if(new_tuples.empty()){ cerr<<"Warning: Insert from SFW, No tuples in the current mem block!"<<endl; } free_blocks.push(memory_block_index); } for (int j = 0; j < new_tuples.size(); j++){ Tuple tuple = relation_ptr->createTuple(); for (int k = 0; k < new_field_size; k++){ if (mapping[k] != -1){ int idx = mapping[k]; assert(idx < relation_ptr->getSchema().getNumOfFields() && idx >= 0); if (tuple.getSchema().getFieldType(idx) == INT){ int val = new_tuples[j].getField(k).integer; tuple.setField(field_names[idx], val); } else{ string *str = new_tuples[j].getField(k).str; tuple.setField(field_names[idx], *str); } } } appendTupleToRelation(relation_ptr, mem, tuple); } cout<<*relation_ptr<<endl; } return relation_ptr; }
bool CvTest3DPoseEstimate::testVideo4OneFrame(queue<StereoFrame> inputImageQueue, FrameSeq& frameSeq, CamTracker& tracker) { bool insertNewKeyFrame = false; TIMERSTART(Total); // currFrame is a reference to frameSeq.mCurrentFrame; PoseEstFrameEntry*& currFrame = frameSeq.mCurrentFrame; bool gotCurrFrame = false; bool stop = false; if (frameSeq.mNextFrame.get()){ // do not need to load new images nor compute the key points again frameSeq.mCurrentFrame = frameSeq.mNextFrame.release(); gotCurrFrame = true; } else { int numWaits; // wait at most for 30 seconds const int maxNumWaits = 30*30; for (numWaits=0; numWaits<maxNumWaits && inputImageQueue.size()==0; numWaits++){ // wait for 33 milliseconds usleep(33000); } if (numWaits>=maxNumWaits) { stop = true; } else { // process the next stereo pair of images. StereoFrame stereoFrame = inputImageQueue.front(); if (stereoFrame.mFrameIndex == -1) { // done stop = true; gotCurrFrame = false; } else { currFrame = new PoseEstFrameEntry(stereoFrame.mFrameIndex); currFrame->mImage = stereoFrame.mImage; currFrame->mRightImage = stereoFrame.mRightImage; currFrame->mDispMap = stereoFrame.mDispMap; // compute disparity map TIMERSTART2(DisparityMap); currFrame->mDispMap = new WImageBuffer1_16s( currFrame->mImage->Width(), currFrame->mImage->Height()); tracker.getPoseEstimator()->getDisparityMap(*currFrame->mImage, *currFrame->mRightImage, *currFrame->mDispMap); TIMEREND2(DisparityMap); #if SAVEDISPMAP { char dispfilename[256]; char dispname[256]; sprintf(dispfilename, "Output/indoor1/dispmap-%04d.xml", currFrame->mFrameIndex); sprintf(dispname, "dispmap-%04d.xml", currFrame->mFrameIndex); cvSave(dispfilename, currFrame->mDispMap, dispname, "disparity map 16s"); } #endif // counting how many frames we have processed frameSeq.mNumFrames++; TIMERSTART2(FeaturePoint); tracker.goodFeaturesToTrack(*currFrame->mImage, currFrame->mDispMap, currFrame->mKeypoints); TIMEREND2(FeaturePoint); // if (mVisualizer) mVisualizer->drawDispMap(*currFrame); } inputImageQueue.pop(); } } KeyFramingDecision kfd = KeyFrameBackTrack; if (stop == false) { if (frameSeq.mNumFrames==1) { // First frame ever, do not need to do anything more. frameSeq.mStartFrameIndex = currFrame->mFrameIndex; kfd = KeyFrameUse; } else { // // match the good feature points between this iteration and last key frame // vector<pair<CvPoint3D64f, CvPoint3D64f> > trackablePairs; if (currFrame->mTrackableIndexPairs == NULL) { currFrame->mTrackableIndexPairs = new vector<pair<int, int> >(); } else { currFrame->mTrackableIndexPairs->clear(); } tracker.matchKeypoints(&trackablePairs, currFrame->mTrackableIndexPairs); assert(currFrame->mTrackableIndexPairs->size() == trackablePairs.size()); #ifdef DEBUG cout << "Num of trackable pairs for pose estimate: "<<trackablePairs.size() << endl; #endif // if applicable, pass a reference of the current frame for visualization // if (mVisualizer) mVisualizer->drawKeypoints(*getLastKeyFrame(), *currFrame, trackablePairs); if (currFrame->mNumTrackablePairs< defMinNumTrackablePairs) { #ifdef DEBUG cout << "Too few trackable pairs" <<endl; #endif // shall backtrack kfd = KeyFrameBackTrack; } else { // pose estimation given the feature point pairs // note we do not do Levenberg-Marquardt here, as we are not sure if // this is key frame yet. TIMERSTART2(PoseEstimateRANSAC); currFrame->mNumInliers = tracker.getPoseEstimator()->estimate(*currFrame->mKeypoints, *tracker.getLastKeyFrame()->mKeypoints, *currFrame->mTrackableIndexPairs, currFrame->mRot, currFrame->mShift, false); TIMEREND2(PoseEstimateRANSAC); // mStat.mHistoInliers.push_back(currFrame->mNumInliers); currFrame->mInliers0 = NULL; currFrame->mInliers1 = NULL; tracker.fetchInliers(currFrame->mInliers1, currFrame->mInliers0); currFrame->mInlierIndices = tracker.fetchInliers(); currFrame->mLastKeyFrameIndex = tracker.getLastKeyFrame()->mFrameIndex; #ifdef DEBUG cout << "num of inliers: "<< currFrame->mNumInliers <<endl; #endif assert(tracker.getLastKeyFrame()); // if (mVisualizer) mVisualizer->drawTracking(*getLastKeyFrame(), *currFrame); // Decide if we need select a key frame by now kfd = tracker.keyFrameEval(currFrame->mFrameIndex, currFrame->mKeypoints->size(), currFrame->mNumInliers, currFrame->mRot, currFrame->mShift); // key frame action // insertNewKeyFrame = keyFrameAction(kfd, frameSeq); } } // not first frame; } // stop == false insertNewKeyFrame = tracker.keyFrameAction(kfd, frameSeq); TIMEREND(Total); return insertNewKeyFrame; }
void popo(queue<int>& from, queue<int>&to) { while(!from.empty()) { to.push(from.front()); from.pop(); } }
int main() { int tcase = 0; cin >> nNodes; while(nNodes != 0) { for(int i = 1; i <= nNodes; ++i) adjList[i].clear(); memset(adjMat, 0, sizeof(adjMat)); cin >> start >> sink >> nEdges; int na, nb, cap; for(int e = 0; e < nEdges; ++e) { scanf("%i %i %i", &na, &nb, &cap); adjMat[na][nb] += cap; adjMat[nb][na] += cap; adjList[na].insert(nb); adjList[nb].insert(na); } maxFlow = 0; while(true) { while(!bfsQ.empty()) bfsQ.pop(); for(int i = 1; i <= nNodes; ++i) dist[i] = INF; memset(parent, 0, sizeof(parent)); tFlow = 0; bfsQ.push(start); dist[start] = 0; while(!bfsQ.empty()) { int tn = bfsQ.front(); bfsQ.pop(); if(tn == sink) break; for(vi_it e = adjList[tn].begin(); e != adjList[tn].end(); ++e) { if(adjMat[tn][*e] > 0 && dist[*e] == INF) { dist[*e] = dist[tn] + 1; bfsQ.push(*e); parent[*e] = tn; } } } augmentPath(sink, INF); if(tFlow == 0) break; maxFlow += tFlow; } printf("Network %i\nThe bandwidth is %i.\n\n", ++tcase, maxFlow); cin >> nNodes; } return 0; }
void petqueue::dequeuecat(){ cout << "\nThe cat \"" << cat.front() << "\" has been adopted!"; both.remove(cat.front()); cat.pop(); }
void bfs() { while(!qu.empty()) { st=qu.front(); str=((st[0]-97)*10*10*10*10)+((st[1]-97)*10*10)+((st[2]-97)); qu.pop(); if(st[0]=='z') s='a'; else s=st[0]+1; drv=((s-97)*10*10*10*10)+((st[1]-97)*10*10)+((st[2]-97)); dr[0]=s,dr[1]=st[1],dr[2]=st[2],dr[3]=NULL; if(mp1[i][drv]==0&&mp1[i][drv]==0) { mp1[i][drv]=1; cst[i][drv]=cst[i][str]+1; if(drv==dst) break; qu.push(dr); } if(st[0]=='a') s='z'; else s=st[0]-1; drv=((s-97)*10*10*10*10)+((st[1]-97)*10*10)+((st[2]-97)); dr[0]=s,dr[1]=st[1],dr[2]=st[2],dr[3]=NULL; if(mp1[i][drv]==0&&mp1[i][drv]==0) { mp1[i][drv]=1; cst[i][drv]=cst[i][str]+1; if(drv==dst) break; qu.push(dr); } if(st[1]=='z') s='a'; else s=st[1]+1; drv=((st[0]-97)*10*10*10*10)+((s-97)*10*10)+((st[2]-97)); dr[1]=s,dr[0]=st[0],dr[2]=st[2],dr[3]=NULL; if(mp1[i][drv]==0&&mp1[i][drv]==0) { mp1[i][drv]=1; cst[i][drv]=cst[i][str]+1; if(drv==dst) break; qu.push(dr); } if(st[1]=='a') s='z'; else s=st[1]-1; drv=((st[0]-97)*10*10*10*10)+((s-97)*10*10)+((st[2]-97)); dr[1]=s,dr[0]=st[0],dr[2]=st[2],dr[3]=NULL; if(mp1[i][drv]==0&&mp1[i][drv]==0) { mp1[i][drv]=1; cst[i][drv]=cst[i][str]+1; if(drv==dst) break; qu.push(dr); } if(st[2]=='z') s='a'; else s=st[2]+1; drv=((st[0]-97)*10*10*10*10)+((st[1]-97)*10*10)+(s-97); dr[2]=s,dr[0]=st[0],dr[1]=st[1],dr[3]=NULL; if(mp1[i][drv]==0&&mp1[i][drv]==0) { mp1[i][drv]=1; cst[i][drv]=cst[i][str]+1; if(drv==dst) break; qu.push(dr); } if(st[2]=='a') s='z'; else s=st[2]-1; drv=((st[0]-97)*10*10*10*10)+((st[1]-97)*10*10)+(s-97); dr[2]=s,dr[0]=st[0],dr[1]=st[1],dr[3]=NULL; if(mp1[i][drv]==0&&mp1[i][drv]==0) { mp1[i][drv]=1; cst[i][drv]=cst[i][str]+1; if(drv==dst) break; qu.push(dr); } } }
bool findPath(int st,int n){ while(!Q.empty())Q.pop(); FOR1(i,n){ color[i]=-1; path[i].clear(); }
void pop(){ if(!que.empty()){ sum -= front(); que.pop(); } }
/* * @brief This submachine contains the state machine for the main CONNECTED state. * @return the cause of disconnection */ DisconnectIndicationCause SubMachineConnected(IXFEvent *e) { DataPdu *dataPdu; DisconnectIndicationCause cause; switch(_connectedSubstate) { case ConnectedInitialize: // first state is not same for master and slave switch(role){ case MASTER: _connectedSubstate = SendQueuedDataPdu; break; case SLAVE: _connectedSubstate = WaitDataPdu; break; } case SendQueuedDataPdu: // send all data in queue if(!txQueue.empty()) { Trace::out("->[Send data pdu]"); dataPdu = (DataPdu *) txQueue.front().payloadBytes(); _transceiver->send(txQueue.front()); // get data off the queue txQueue.pop(); } if ( e->getEventType() == XFEvent::Event && e->getId() == FrameNotDeliveredEvent::Id ) { Trace::out("->[Frame not delivered]"); break; } else if ( e->getEventType() == XFEvent::Event && e->getId() == FrameDeliveredEvent::Id ) { if (*dataPdu->getPayloadBytes() == DISCONNECT_REQUEST) { // if it was a disconnection request, disconnect _connectedSubstate = CloseConnection; cause = DISCONNECT; } else if (!dataPdu->isMoreData()) { // No more datas (MMF==0 && SMF==0) _connectedSubstate = WaitForNextConnectionEvent; } else { _connectedSubstate = WaitDataPdu; } } break; case WaitDataPdu: if ( e->getEventType() == XFEvent::Timeout && e->getId() == ConnectionPduMaxTimeout::Id ) { _connectedSubstate = CloseConnection; cause = LINK_LOSS; } else if ( e->getEventType() == XFEvent::Event && e->getId() == DataIndicationEvent::Id ) { _connectedSubstate = ProcessDataPdu; } break; case ProcessDataPdu: Frame *frame; // If there is a frame in the queue if(rxQueue.empty()) break; // Get the frame *frame = rxQueue.front(); rxQueue.pop(); // Extract the data pdu DataPdu *dataPdu; *dataPdu = *((DataPdu*)(frame->payloadBytes())); // Check the data pdu informations if (*dataPdu->getPayloadBytes() == DISCONNECT_REQUEST) { // disconnection _connectedSubstate = CloseConnection; cause = DISCONNECT; } else if (!dataPdu->isMoreData()) { // No more datas (MMF==0 && SMF==0) _connectedSubstate = WaitForNextConnectionEvent; } else { _connectedSubstate = SendQueuedDataPdu; } break; case CloseConnection: Trace::out("\t-Disconnection"); // send disconnection indication to upper layer _observer->onDisconnectIndication(DISCONNECT); return cause; break; case WaitForNextConnectionEvent: // Disable transceiver _transceiver->setMode(IPhyTransceiver::Inactive); Trace::out("\t-Disable transceiver"); // Set timer until next transceiver activation if ( e->getEventType() == XFEvent::Timeout && e->getId() == ConnectionIntervalTimeout::Id ) _connectedSubstate = EnableTransceiver; break; case EnableTransceiver: // Enable transceiver Trace::out("\t-Enable transceiver"); _transceiver->setMode(IPhyTransceiver::Active); break; } return NO_DISCONNECT; }
void print_r(queue<string> &r) { while(!r.empty()) { cout << r.front() << endl; r.pop(); } }
int funkcja(int a) { visit[a]=2; wynik.push_back(a); while(true){ if(visit[a]==1){ int droga=a; for(int i=0; i<nast[a].size(); i++){ int aktnast=nast[a][i]; if(visit[aktnast]==2) continue; if(prze[aktnast]>=pre[n]&&pre[aktnast]<=pre[n]){ droga=aktnast; continue; } if(pre[aktnast]==prze[aktnast]){ visit[aktnast]=2; wynik.push_back(aktnast); } else{ Q.push(aktnast); } } if(Q.size()>0){ if(Q.size()>2){ wynik.clear(); return 0; } else{ if(Q.size()==1){ prev[Q.front()]=a; int dec=funkcja1(Q.front()); Q.pop(); if(dec==0){ wynik.clear(); return 0; } } else{ prev[Q.front()]=a; int dec=funkcja1(Q.front()); if(dec==0){ wynik.clear(); return 0; } Q.pop(); visit[a]=2; wynik.push_back(a); prev[Q.front()]=a; dec=funkcja2(Q.front()); if(dec==0){ wynik.clear(); return 0; } visit[droga]=2; wynik.push_back(droga); Q.pop(); } } } if(visit[a]!=2) wynik.push_back(a); visit[a]=2; a=droga; if(a==n){ wynik.push_back(a); return 1; } } else{ int droga=a; bool dalej=false; for(int i=0; i<nast[a].size(); i++){ int aktnast=nast[a][i]; if(visit[aktnast]==2) continue; if(prze[aktnast]>=pre[n]&&pre[aktnast]<=pre[n]){ droga=aktnast; continue; } if(pre[aktnast]==prze[aktnast]){ Q2.push(aktnast); } else{ Q.push(aktnast); } } if(Q.size()>0){ if(Q.size()>1){ wynik.clear(); return 0; } else{ prev[Q.front()]=a; int dec=funkcja2(Q.front()); if(dec==0){ wynik.clear(); return 0; } while(!Q2.empty()){ wynik.push_back(Q2.front()); visit[Q2.front()]=2; Q2.pop(); } visit[droga]=2; wynik.push_back(droga); Q.pop(); } } while(!Q2.empty()){ dalej=true; wynik.push_back(Q2.front()); visit[Q2.front()]=2; Q2.pop(); } if(visit[a]!=2) wynik.push_back(a); visit[a]=2; a=droga; if(dalej==true){ wynik.push_back(a); visit[a]=2; } if(a==n){ wynik.push_back(a); return 1; } } } }
int solveRushHour( int numCars, GameState initial, queue< GameState > statesToEvaluate, map< string, int > observedStates ) { // variables int numMoves = 0; int carNum = 0; GameState currentWork; string temp = initial.stringify(); // prime the search loop statesToEvaluate.push( initial ); observedStates.insert( pair< string, int >( temp, 0 ) ); // search until a solution is found or there are no possibilities left while( !statesToEvaluate.empty() ) { // pull a game state out of the queue currentWork = statesToEvaluate.front(); statesToEvaluate.pop(); // retrieve the number of moves up to that point temp = currentWork.stringify(); numMoves = (*observedStates.find( temp )).second; // check to see if that state is a winning one if( currentWork.isWin() ) { // if so, return the number of moves it took to find it the solution return numMoves; } // otherwise, make another round of moves numMoves++; for( carNum = 0; carNum < numCars; carNum++ ) { // case: a forward movement attempt was successful if( currentWork.move( carNum, FORWARD ) ) { // case: the new game state is not a winning one and it has not been // encountered yet if( observedStates.find( currentWork.stringify() ) == observedStates.end() ) { // enqueue the game state, add it to the map statesToEvaluate.push( currentWork ); temp = currentWork.stringify(); observedStates.insert( pair<string, int>( temp, numMoves ) ); } // case: the new game state is not new nor a solution // do nothing // reset the game state for the next move currentWork.move( carNum, BACKWARD ); } // case: a backward movement attempt is successful if( currentWork.move( carNum, BACKWARD ) ) { // case: the new game state is not a winning one and it has not been // encountered yet if( observedStates.find( currentWork.stringify() ) == observedStates.end() ) { // enqueue the game state, add it to the map statesToEvaluate.push( currentWork ); temp = currentWork.stringify(); observedStates.insert( pair<string, int>( temp, numMoves ) ); } // case: the new game state is not new nor a solution // do nothing // reset the car's position currentWork.move( carNum, FORWARD ); } } } // if the search fails, return a designated error code return kUnsolvable; }
void bfs(int v) { // cout<<(a[0]-'a')*8+a[1]-'1'<<" "<<(b[0]-'a')*8+b[1]-'1'<<" "; // cout<<v<<" "; dis[v]=0; q.push(v); // cout<<dis[v]; vis[v]=1; while(!q.empty()) { d=q.front(); // cout<<d<<" "; // dis[d]=0; q.pop(); if(d==((b[0]-'a')*8+b[1]-'1')){ while(!q.empty()) q.pop(); break; } else { if(d/m+2 <= 7 && d%m+1 <= 7 && vis[(d/m+2)*8+d%m+1]==0) { q.push((d/m+2)*8+d%m+1); dis[(d/m+2)*8+d%m+1]=dis[d]+1; vis[(d/m+2)*8+d%m+1]=1; } if(d/m+2 <= 7 && d%m-1 >=0 && vis[(d/m+2)*8+d%m-1]==0) { q.push((d/m+2)*8+d%m-1); dis[(d/m+2)*8+d%m-1]=dis[d]+1; vis[(d/m+2)*8+d%m-1]=1; } if(d/m-2 >=0 && d%m+1 <=7 && vis[(d/m-2)*8+d%m+1]==0) { q.push((d/m-2)*8+d%m+1); dis[(d/m-2)*8+d%m+1]=dis[d]+1; vis[(d/m-2)*8+d%m+1]=1; } if(d/m-2 >= 0 && d%m-1 >=0 && vis[(d/m-2)*8+d%m-1]==0) { q.push((d/m-2)*8+d%m-1); dis[(d/m-2)*8+d%m-1]=dis[d]+1; vis[(d/m-2)*8+d%m-1]=1; } if(d/m+1 <= 7 && d%m+2 <=7 && vis[(d/m+1)*8+d%m+2]==0) { q.push((d/m+1)*8+d%m+2); dis[(d/m+1)*8+d%m+2]=dis[d]+1; vis[(d/m+1)*8+d%m+2]=1; } if(d/m-1 >= 0 && d%m+2 <=7 && vis[(d/m-1)*8+d%m+2]==0) { q.push((d/m-1)*8+d%m+2); dis[(d/m-1)*8+d%m+2]=dis[d]+1; vis[(d/m-1)*8+d%m+2]=1; } if(d/m+1 <= 7 && d%m-2 >=0 && vis[(d/m+1)*8+d%m-2]==0) { q.push((d/m+1)*8+d%m-2); dis[(d/m+1)*8+d%m-2]=dis[d]+1; vis[(d/m+1)*8+d%m-2]=1; } if(d/m-1 >= 0 && d%m-2 >=0 && vis[(d/m-1)*8+d%m-2]==0) { q.push((d/m-1)*8+d%m-2); dis[(d/m-1)*8+d%m-2]=dis[d]+1; vis[(d/m-1)*8+d%m-2]=1; } // cout<<" d = "<<d<<" "; // cout<<dis[d]<<" "; } } }
void get_file_and_compress() { if (files_queue.empty()) { return; } if (num_of_compress_process >= max_of_compress_process) return; struct file_to_compress ftc = files_queue.front(), ftc1; files_queue.pop(); string temp = ftc.inname.substr(root_dir.length()); files_map[temp] = 0; if (debug == "1") { cerr << endl << "QUEUE: " << files_queue.size() << " files left" << endl; cerr << "size: " << files_queue.size() << endl; } pid_t pid = fork (); if (pid < 0) { cerr << "fork() error" << endl; } else if (pid==0) { //tien trinh con string filename = ftc.inname; if (debug == "1") { cout << "Checking file:'" << ftc.inname << "'\n"; } bool get_metadata = metadata(root_dir, filename); if (get_metadata) { if (debug == "1") { cout << "get_metadata Ok" << endl; } } else { bool isSent = visqua_compress(token_input, username_input, root_dir, url_input, filename, log_file, keep_original, debug); //} if (isSent) { if (debug == "1") { cout << "Ok" << endl; } } else { if (debug == "1") { cerr << "push file: " << filename << " to queue \n" << endl; } if (files_map[temp] == 0) { files_queue.push(ftc); files_map[temp] = 1; } if (debug == "1") { cerr << endl << "QUEUE: " << files_queue.size() << " files left" << endl; cerr << "size: " << files_queue.size() << endl; } } } _exit(0); } else { for (int i=0; i<max_of_compress_process; i++) { if (pid_of_ev[i] == -1) { ev_child_init (&cw[i], child_cb, pid, 0); ev_child_start(EV_DEFAULT_ &cw[i]); pid_of_ev[i] = pid; break; } else if (pid_of_ev[i] == 0) { ev_child_set(&cw[i], pid, 0); ev_child_start(EV_DEFAULT_ &cw[i]); pid_of_ev[i] = pid; break; } } num_of_compress_process++; } }
void bfs() { int nowa,nowb,tmpa,tmpb; aa.push(0); bb.push(0); v[0][0]=true; while(1) { nowa=aa.front(); nowb=bb.front(); if(nowb==n) { makeans(nowa,nowb); break; } if(nowa<a && !v[a][nowb]) { //printf("fill a\n"); aa.push(a); bb.push(nowb); m[a][nowb].lx=nowa; m[a][nowb].ly=nowb; m[a][nowb].show=0; v[a][nowb]=true; } if(nowb<b && !v[nowa][b]) { //printf("fill b\n"); aa.push(nowa); bb.push(b); m[nowa][b].lx=nowa; m[nowa][b].ly=nowb; m[nowa][b].show=1; v[nowa][b]=true; } if(nowa>0 && nowb<b) { //printf("pour a b\n"); tmpa=nowa-(b-nowb)<0?0:nowa-(b-nowb); tmpb=nowb+nowa>b?b:nowb+nowa; if(!v[tmpa][tmpb]) { aa.push(tmpa); bb.push(tmpb); m[tmpa][tmpb].lx=nowa; m[tmpa][tmpb].ly=nowb; m[tmpa][tmpb].show=2; v[tmpa][tmpb]=true; } } if(nowb>0 && nowa<a) { //printf("pour b a\n"); tmpa=nowb+nowa>a?a:nowb+nowa; tmpb=nowb-(a-nowa)<0?0:nowb-(a-nowa); if(!v[tmpa][tmpb]) { bb.push(tmpb); aa.push(tmpa); m[tmpa][tmpb].lx=nowa; m[tmpa][tmpb].ly=nowb; m[tmpa][tmpb].show=3; v[tmpa][tmpb]=true; } } if(nowa>0 && !v[0][nowb]) { //printf("empty a\n"); aa.push(0); bb.push(nowb); m[0][nowb].lx=nowa; m[0][nowb].ly=nowb; m[0][nowb].show=4; v[0][nowb]=true; } if(nowb>0 && !v[nowa][0]) { //printf("empty b\n"); aa.push(nowa); bb.push(0); m[nowa][0].lx=nowa; m[nowa][0].ly=nowb; m[nowa][0].show=5; v[nowa][0]=true; } aa.pop(); bb.pop(); } return; }
void MapGrid::computeTargetDistance (queue<MapCell*>& dist_queue, const costmap_2d::Costmap2D& costmap) { MapCell* current_cell; MapCell* check_cell; unsigned int last_col = size_x_ - 1; unsigned int last_row = size_y_ - 1; while (!dist_queue.empty()) { current_cell = dist_queue.front(); dist_queue.pop(); if (current_cell->cx > 0) { check_cell = current_cell - 1; if (!check_cell->target_mark) { //mark the cell as visisted check_cell->target_mark = true; if (updatePathCell (current_cell, check_cell, costmap)) { dist_queue.push (check_cell); } } } if (current_cell->cx < last_col) { check_cell = current_cell + 1; if (!check_cell->target_mark) { check_cell->target_mark = true; if (updatePathCell (current_cell, check_cell, costmap)) { dist_queue.push (check_cell); } } } if (current_cell->cy > 0) { check_cell = current_cell - size_x_; if (!check_cell->target_mark) { check_cell->target_mark = true; if (updatePathCell (current_cell, check_cell, costmap)) { dist_queue.push (check_cell); } } } if (current_cell->cy < last_row) { check_cell = current_cell + size_x_; if (!check_cell->target_mark) { check_cell->target_mark = true; if (updatePathCell (current_cell, check_cell, costmap)) { dist_queue.push (check_cell); } } } } }
int Calculation::out(queue<string> que) { stack<string> digital; stack<string> cache; stack<string> character; stack<int> answer; string t; while(!que.empty()) { cache.push(que.front()); que.pop(); } while(!cache.empty()) { t = cache.top(); cache.pop(); if (t == "+"||t == "-"||t == "*"||t == "/") { if (character.empty() ) { character.push(t); } else if (character.top() == ")") { character.push(t); } else if (priority(t) >= priority(character.top())) { character.push(t); } else { digital.push(character.top()); character.pop(); continue; } } else if (t == ")") { character.push(t); } else if (t == "(") { if (character.top() == ")") { character.pop(); break; } else { digital.push(character.top()); character.pop(); } } else { digital.push(t); } } while (!character.empty()) { digital.push(character.top()); character.pop(); } string ss[101]; int i,j; for (i=0; !digital.empty(); i++) { ss[i]=digital.top(); digital.pop(); j=i; } for (i=j; i>=0; i--) { if (!isdigit(ss[i][0])) { int a,b,an; a=answer.top(); answer.pop(); b=answer.top(); answer.pop(); an=calculate(a,b,ss[i][0]); answer.push(an); } else { int f; stringstream stream(ss[i]); stream >> f; answer.push(f); } } return answer.top(); }
int main() { int a, b, c; cin >> a >> b >> c; Status t; t.x = 0; t.y = 0; t.z = 0; q.push(t); s.insert(t); while (!q.empty()) { t = q.front(); q.pop(); Status now; //加满 if (t.x < a) { now.x = a; now.y = t.y; now.z = t.z; suibian(now); } if (t.y < b) { now.x = t.x; now.y = b; now.z = t.z; suibian(now); } if (t.z < c) { now.x = t.x; now.y = t.y; now.z = c; suibian(now); } //倒空 if (t.x > 0) { now.x = 0; now.y = t.y; now.z = t.z; suibian(now); } if (t.y > 0) { now.x = t.x; now.y = 0; now.z = t.z; suibian(now); } if (t.z > c) { now.x = t.x; now.y = t.y; now.z = 0; suibian(now); } //来回倒 int dao; if (t.x != 0) { //a->b dao = min(t.x, b - t.y); now.x = t.x - dao; now.y = t.y + dao; now.z = t.z; suibian(now); //a->c dao = min(t.x, c - t.z); now.x = t.x - dao; now.y = t.y; now.z = t.z + dao; suibian(now); } if (t.y != 0) { //b->a dao = min(t.y, a - t.x); now.x = t.x + dao; now.y = t.y - dao; now.z = t.z; suibian(now); //b->c dao = min(t.y, c - t.z); now.x = t.x; now.y = t.y - dao; now.z = t.z + dao; suibian(now); } if (t.z != 0) { //c->a dao = min(t.z, a - t.x); now.x = t.x + dao; now.y = t.y; now.z = t.z - dao; suibian(now); //c->b dao = min(t.z, b - t.y); now.x = t.x; now.y = t.y + dao; now.z = t.z - dao; suibian(now); } } for (int i = 1; i <= 50; ++i) { if(bucket[i]==1){ cout<<i<<endl; } } return 0; }