int main() { while(~scanf("%d %d",&n,&m)) { for(int i = 1;i<=n;i++) scanf("%d",&a[i]); GetRmq(); Bo = (int)sqrt(n); for(int i = 1;i <= m; i++) scanf("%d %d",&S[i].L,&S[i].R),S[i].Id = i; sort(S+1,S+m+1); St.push(0); for(int i = 1;i <= n;i++) { while(St.size() > 1 && a[St.top()] > a[i]) St.pop(); R[i] = St.top(); St.push(i); } while(!St.empty()) St.pop(); St.push(n+1); for(int i = n;i>=1;i--) { while(St.size() > 1 && a[St.top()] > a[i]) St.pop(); L[i] = St.top(); St.push(i); } while(!St.empty()) St.pop(); memset(sumL,0,sizeof(sumL)); memset(sumR,0,sizeof(sumR)); sumR[1] =a[1]; for(int i = 2;i<=n;i++) sumR[i] = sumR[R[i]]+(1LL)*(i-R[i])*a[i]; sumL[n] = a[n]; for(int i = n-1;i >= 1;i--) sumL[i] = sumL[L[i]]+(1LL)*(L[i]-i)*a[i]; LL sum = 0; int l = 0,r = 1; for(int i = 1;i<=m;i++) { while(r <= S[i].R) sum +=Rcal(l,r),r++; while(r > S[i].R+1) r --,sum-=Rcal(l,r); while(l < S[i].L-1) l++,sum-=Lcal(l,r); while(l >= S[i].L) sum+=Lcal(l,r),l--; ans[S[i].Id] =sum; } for(int i = 1;i<=m;i++) printf("%lld\n",ans[i]); } return 0; }
// Removes the element from in front of queue. void pop(void) { pushIntoQueue(); if (!queue.empty()) queue.pop(); }
vector<Tuple> Qtree::exec(bool print, string *table_name){ vector<Tuple> ret ; #ifdef DEBUG this->print(0); #endif if(this->type == INS){ vector<Tuple> temp = this->left->exec( false, NULL ) ; if(temp.size() != 0){ Schema sins_from = temp[0].getSchema() ; vector<enum FIELD_TYPE> field_types_from = sins_from.getFieldTypes() ; vector<string> field_names_from = sins_from.getFieldNames() ; if(field_types_from.size() == this->info.size() - 1){ Schema sins_to = p->schema_manager.getSchema( this->info[0] ) ; vector<enum FIELD_TYPE> field_types_to ; vector<union Field> fields ; vector<string>::iterator it0 = this->info.begin() ; vector<enum FIELD_TYPE>::iterator it1 = field_types_from.begin(); vector<string>::iterator it2 = field_names_from.begin(); vector<string> STRv; vector<int> INTv ; string table_n = (*it0) ; vector<string> field_names_to ; it0 ++ ; for( ; it0 != this->info.end() ; it0 ++, it1++){ unsigned long found = it0->rfind('.') ; string s_table ; if(found == std::string::npos){ s_table = string( table_n + "." + (*it0) ) ; }else{ s_table = string( it0->substr( it0->rfind('.') + 1 ) ) ; } if( sins_to.fieldNameExists( *it0 ) ){ field_names_to.push_back(string( *it0) ) ; if(sins_to.getFieldType( *it0) == *it1 ){ }else{ perror( ": Type mismatch"); return ret; } }else{ if(sins_to.fieldNameExists(s_table) ) { field_names_to.push_back(string( s_table ) ) ; if(sins_to.getFieldType( s_table) == *it1 ){ }else{ perror( ": Type mismatch"); return ret; } } else{ perror( "exec: No such field"); } } } for(vector<Tuple>::iterator it_tuple = temp.begin(); it_tuple != temp.end(); it_tuple ++) { for(it1 = field_types_from.begin(), it2 = field_names_from.begin() ; it1 != field_types_from.end() ; it1++, it2++){ if(*it1 == INT){ INTv.push_back( it_tuple->getField( *it2).integer ) ; }else{ STRv.push_back( *(it_tuple->getField( *it2).str) ) ; } } p->insert(table_n, field_names_to, STRv, INTv) ; INTv.clear(); STRv.clear() ; } }else{ perror("Size mismatch"); return ret; } }else{ return ret; } }else if(this->type == TAU){ string table_n; if(this->left->type == TABLE && (output_s.empty() || output_s.top() == NULL) ){ Schema s = p->schema_manager.getSchema( this->left->info[0] ) ; string s_table ; unsigned long found = this->info[0].rfind('.') ; table_n = this->left->info[0] ; if(found == std::string::npos){ s_table = string( table_n + "." + this->info[0] ) ; }else{ s_table = string( this->info[0].substr( this->info[0].rfind('.') + 1 ) ) ; } if( s.fieldNameExists( this->info[0] ) ){ ret = p->SortTwoPass(table_n, this->info[0]) ; }else if(s.fieldNameExists(s_table) ) { ret = p->SortTwoPass(table_n, s_table) ; }else{ perror("No such field"); return ret ; } }else{ vector<Tuple> temp = this->left->exec( false, &table_n ) ; if(table_name != NULL) { (*table_name ) = string( this->info[0] ) ;} if(temp.size() != 0){ Schema s = temp[0].getSchema() ; string temp_table_name = "temp_table" ; while(p->schema_manager.relationExists(temp_table_name) ){ temp_table_name += "-a" ; } p->CreateTable(temp_table_name, temp ) ; temp_relations.push_back( temp_table_name ) ; unsigned long found = this->info[0].rfind('.') ; string s_table ; if(found == std::string::npos){ s_table = string( table_n + "." + this->info[0] ) ; }else{ s_table = string( this->info[0].substr( this->info[0].rfind('.') + 1 ) ) ; } if( s.fieldNameExists( this->info[0] ) ){ ret = p->SortTwoPass(temp_table_name, this->info[0]) ; }else if(s.fieldNameExists(s_table) ) { ret = p->SortTwoPass(temp_table_name, s_table) ; }else{ perror("No such field"); return ret ; } }else{ return ret; } } }else if(this->type == DELTA ){ string table_n; if(this->left->type == TABLE){ table_n = this->left->info[0] ; ret = p->dupTwoPass(table_n) ; }else{ vector<Tuple> temp = this->left->exec( false , &table_n) ; if(table_name != NULL) { (*table_name ) = string( this->info[0] ) ;} if(temp.size() != 0){ Schema s = temp[0].getSchema() ; string temp_table_name = "temp_table" ; while(p->schema_manager.relationExists(temp_table_name) ){ temp_table_name += "-a" ; } p->CreateTable(temp_table_name, temp ); temp_relations.push_back(temp_table_name ) ; ret = p->dupTwoPass(temp_table_name) ; }else{ return ret; } } }else if(this->type == PI ){ string table_n; vector<Tuple> temp = this->left->exec( false, &table_n ) ; if(table_name != NULL) { (*table_name ) = string( this->info[0] ) ;} if(temp.size() != 0){ Schema s = temp[0].getSchema() ; vector<string> field_names ; vector<enum FIELD_TYPE> field_types ; for(vector<string>::iterator it= this->info.begin(); it != this->info.end(); it++){ unsigned long found = it->rfind('.') ; string s_table ; if(found == std::string::npos){ s_table = string( table_n + "." + (*it) ) ; }else{ s_table = string( it->substr( it->rfind('.') + 1 ) ) ; } if( s.fieldNameExists( *it ) ){ field_names.push_back(string(*it) ) ; field_types.push_back(s.getFieldType( *it) ) ; }else{ if(s.fieldNameExists(s_table) ) { field_names.push_back(string( s_table ) ) ; field_types.push_back( s.getFieldType( s_table ) ); } else{ perror( "exec: No such field"); } } } string temp_table_name = "temp_table" ; Relation *rlt = NULL; while(p->schema_manager.relationExists(temp_table_name) ){ temp_table_name += "-a" ; } rlt = p->CreateTable(temp_table_name, field_names, field_types) ; temp_relations.push_back(temp_table_name ) ; for(vector<Tuple>::iterator tit = temp.begin(); tit != temp.end(); tit++){ Tuple t = rlt->createTuple() ; for(vector<string>::iterator it = field_names.begin(); it != field_names.end() ; it++){ union Field f= tit->getField(*it) ; if( s.getFieldType(*it) == INT ){ t.setField( *it, f.integer ) ; }else{ t.setField( *it, *(f.str)) ; } } ret.push_back( t ) ; } }else{ return ret; } }else if(this->type == PRODUCT){ vector<string> ptables; vector<Relation *> relations ; map<string, Qexpression *> sigma_operation ; vector<string> commons ; map<string, bool> joined_keys; vector<string>::iterator it = ptables.begin(); ptables.insert(ptables.end(), this->info.begin(), this->info.end() ); if(output_s.empty() ){ }else if(output_s.top()->type == INTEGER || output_s.top()->type == LITERAL ){ Tuple *t = NULL; if(output_s.top()->judge(*t) ){ /* WHERE clasuse always true */ while(! output_s.empty() ){ output_s.top()->free() ;output_s.pop();} }else{ /* empty results */ return ret; } }else{ Qexpression *optimized = output_s.top()->optimize_sigma(&sigma_operation) ; output_s.pop(); if(optimized != NULL){ output_s.push(optimized) ;} #ifdef DEBUG for(map<string, Qexpression *>::iterator it = sigma_operation.begin(); it != sigma_operation.end(); it ++){ cout << it->first << "->" << endl; it->second->print(0); } #endif if( ! output_s.empty() ){ optimized = output_s.top()->optimize_join(commons, joined_keys) ; output_s.pop(); if(optimized != NULL){ output_s.push(optimized) ; }else{ while(! output_s.empty() ){output_s.top()->free() ; output_s.pop();} } if(! output_s.empty()){ #ifdef DEBUG output_s.top()->print(0); #endif } } #ifdef DEBUG cerr << "commons: "; for(vector<string>::iterator it = commons.begin(); it != commons.end(); it++){ cerr<< *it << " " ; } cerr << endl ; #endif } vector<string> to_drop ; for(vector<string>::iterator it = ptables.begin(); it != ptables.end(); ){ if(sigma_operation[*it] == NULL){ it++; }else{ Relation *temp_relation; vector<Tuple> tuples = p->singleTableSelect( *it , sigma_operation[*it] ) ; if(tuples.size() != 0){ temp_relation = p->CreateTable( ( *it) + "-SIGMA", tuples) ; }else{ vector<string> field_names = p->schema_manager.getRelation(*it)->getSchema().getFieldNames(); vector<enum FIELD_TYPE> field_types = p->schema_manager.getRelation(*it)->getSchema().getFieldTypes() ; temp_relation = p->CreateTable( (*it) + "-SIGMA" , field_names, field_types ) ; } to_drop.push_back( temp_relation->getRelationName() ) ; it = ptables.erase(it) ;ptables.insert( it, temp_relation->getRelationName() ) ; } } if(ptables.size() == 2){ if(ptables[0] <= ptables[1]){ ret = p->JoinTwoPass(ptables[0], ptables[1], commons ) ; }else{ ret = p->JoinTwoPass(ptables[1], ptables[0], commons ) ; } }else{ ret = p->JoinTables(ptables, commons) ; } for(vector<string>::iterator it = to_drop.begin(); it != to_drop.end(); it++){ p->DropTable(*it) ; } if(output_s.empty() ){ }else{ string temp_table_name = "temp_table"; while(p->schema_manager.relationExists(temp_table_name)) { temp_table_name += "-a"; } p->CreateTable( temp_table_name, ret ) ; temp_relations.push_back(temp_table_name) ; ret = p->singleTableSelect(temp_table_name, output_s.top() ) ; } }else if(this->type == TABLE){ if(table_name != NULL) { (*table_name ) = string( this->info[0] ) ;} ret = p->singleTableSelect(this->info[0], output_s.empty() ? NULL : output_s.top() ); }else{ return ret; } if(ret.size() != 0 && print){ vector<string> field_names = ret[0].getSchema( ).getFieldNames() ; cout << "-----------------" << endl ; for(vector<string>::iterator it = field_names.begin(); it != field_names.end(); it++){ cout<< *it << ' ' ; } cout << endl << "-----------------" << endl ; for(vector<Tuple>::iterator it = ret.begin(); it != ret.end(); it ++ ){ cout << (*it) << endl; }cout << "-----------------" << endl ; } return ret; }
int main() { freopen("input.txt","r",stdin); int N, M; string tmpStatus; while ( cin >> N >> M, N!=0 && M!=0 ) { // 初始化 while ( !oldStates.empty() ) oldStates.pop(); for ( int i = 0; i < 50; i++ ) { target[i] = false; for ( int j = 0; j < 27; j++ ) states[i][j].clear(); } // 读取转化表 for ( int i = 0; i < N; i++ ) { for ( int j = 0; j < M; j++ ) { cin >> tmpStatus; stringToVector( tmpStatus, states[i][j] ); } } STATUS tmp; while ( cin >> tmp, tmp != -1 ) { target[tmp] = true; } while ( cin >> str, str != "#" ) { idx = 0; // 把开始状态压进oldStates中,开始搜索 oldStates.push( 0 ); moveOneStepAndClosure( 'E' ); char c = nextChar(); while( idx != str.length()+1 ) { // 实现:S = e_closure( move( S, c ) ); moveOneStepAndClosure( c ); c = nextChar(); } if ( isInTarget( oldStates ) ) cout << "YES" << endl; else cout << "NO" << endl; } } return 0; }
int main(int argc, char** argv) { // Shutdown automatically. atexit(Shutdown); // Enable debugging output. PosixSerial::debugging(false); Surveyor::debugging(false); // To which Surveyor are we connecting? string devName = "/dev/ttyUSB0"; if (argc > 1) { devName = argv[1]; } // Connect to the Surveyor. // WARNING: Camera resolution MUST be 160x128 for blob finding to work. // I was puzzled for hours until I figured this out. if ((srv = CreateSurveyor(devName, Surveyor::CAMSIZE_160x128, 5)) == 0) { cerr << "Failed to connect to the Surveyor." << endl; exit(-1); } // Initialize SDL. if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { cerr << "Failed to initialize SDL: " << SDL_GetError(); exit(-1); } screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, SDL_DOUBLEBUF); if (screen == 0) { cerr << "Failed to set video mode: " << SDL_GetError(); exit(-1); } SDL_WM_SetCaption(APP_TITLE, 0); // Create our mutexes. if ((srvMutex = SDL_CreateMutex()) == 0 || (jpegImageMutex = SDL_CreateMutex()) == 0 || (blobImageMutex = SDL_CreateMutex()) == 0) { cerr << "Failed to create mutex: " << SDL_GetError(); exit(-1); } if ((blobThread = SDL_CreateThread(BlobFinder, 0)) == 0) { cerr << "Failed to start blob finder: " << SDL_GetError() << endl; exit(-1); } // Enter main loop. bool fQuitApplication = false; while (!fQuitApplication) { // Handle all events. SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: { fQuitApplication = true; } break; case SDL_KEYDOWN: { switch (event.key.keysym.sym) { case SDLK_ESCAPE: { fQuitApplication = true; } break; case SDLK_i: { // Image if (!fUpdatingImage) { if ((imageThread = SDL_CreateThread(UpdateImage, 0)) == 0) { cerr << "Failed to get image: " << SDL_GetError() << endl; } else { fUpdatingImage = true; } } } break; case SDLK_u: { // Undo if (!undoList.empty()) { currentRange = newRange = undoList.top(); undoList.pop(); fYUVRangeChange = true; } } break; case SDLK_r: { // Reset currentRange = newRange = YUVRange("FF00FF00FF00"); fYUVRangeChange = true; } break; case SDLK_p: { // Print cout << endl; cout << "Hex: " << currentRange.toHexString() << '\n' << "Y-range: " << setw(5) << currentRange.getYMin() << " - " << setw(3) << currentRange.getYMax() << '\n' << "U-range: " << setw(5) << currentRange.getUMin() << " - " << setw(3) << currentRange.getUMax() << '\n' << "V-range: " << setw(5) << currentRange.getVMin() << " - " << setw(3) << currentRange.getVMax() << '\n'; cout << endl; } break; default: { } break; } } break; case SDL_MOUSEBUTTONDOWN: { if (event.button.button == SDL_BUTTON_LEFT) { mouseX1 = mouseX2 = event.button.x; mouseY1 = mouseY2 = event.button.y; if (mouseX1 >= 0 && mouseX1 < IMAGE_WIDTH && mouseY1 >= 0 && mouseY1 < IMAGE_HEIGHT) { fMouseDown = true; } } } break; case SDL_MOUSEBUTTONUP: { if (event.button.button == SDL_BUTTON_LEFT) { if (fMouseDown) { fMouseDown = false; mouseX2 = event.button.x; mouseY2 = event.button.y; // Clip if (mouseX2 < 0) mouseX2 = 0; if (mouseX2 >= IMAGE_WIDTH) mouseX2 = IMAGE_WIDTH-1; if (mouseY2 < 0) mouseY2 = 0; if (mouseY2 >= IMAGE_HEIGHT) mouseY2 = IMAGE_HEIGHT-1; // Flip Y-coordinate mouseY1 = SCREEN_HEIGHT - mouseY1 - 1; mouseY2 = SCREEN_HEIGHT - mouseY2 - 1; // Compute BBox int xmin = min(mouseX1, mouseX2) * (80.0/IMAGE_WIDTH); int xmax = max(mouseX1, mouseX2) * (80.0/IMAGE_WIDTH); int ymin = min(mouseY1, mouseY2) * (64.0/IMAGE_HEIGHT); int ymax = max(mouseY1, mouseY2) * (64.0/IMAGE_HEIGHT); Rect blobWin(xmin, xmax, ymin, ymax); if (!fUpdatingBlobWindow) { if ((blobWindowThread = SDL_CreateThread(UpdateBlobWindow, &blobWin)) == 0) { cerr << "Failed to update blob window: " << SDL_GetError() << endl; } else { fUpdatingBlobWindow = true; } } } } } break; case SDL_MOUSEMOTION: { if (fMouseDown) { mouseX2 = event.motion.x; mouseY2 = event.motion.y; if (mouseX2 < 0) mouseX2 = 0; if (mouseX2 >= IMAGE_WIDTH) mouseX2 = IMAGE_WIDTH-1; if (mouseY2 < 0) mouseY2 = 0; if (mouseY2 >= IMAGE_HEIGHT) mouseY2 = IMAGE_HEIGHT-1; } } break; default: { } break; } } // Update YUV range. if (!fUpdatingYUVRange && fYUVRangeChange) { if ((updateRangeThread = SDL_CreateThread(UpdateYUVRange, &newRange)) == 0) { cerr << "Failed to update yuv range: " << SDL_GetError() << endl; } else { fUpdatingYUVRange = true; } } // Update image. if (fUpdatedImage) { SDL_mutexP(jpegImageMutex); double scaleFactorX = IMAGE_WIDTH / (double)jpegImage->w; double scaleFactorY = IMAGE_HEIGHT / (double)jpegImage->h; if ((jpegImageScaled = zoomSurface(jpegImage, scaleFactorX, scaleFactorY, 0)) == 0) { cerr << "Failed to scale image: " << SDL_GetError() << endl; } SDL_mutexV(jpegImageMutex); fUpdatedImage = false; } // Update blobs. if (fUpdatedBlobs) { SDL_mutexP(blobImageMutex); double scaleFactorX = IMAGE_WIDTH / (double)blobImage->w; double scaleFactorY = IMAGE_HEIGHT / (double)blobImage->h; if ((blobImageScaled = zoomSurface(blobImage, scaleFactorX, scaleFactorY, 0)) == 0) { cerr << "Failed to scale image: " << SDL_GetError() << endl; } SDL_mutexV(blobImageMutex); fUpdatedBlobs = false; } // Clear screen. SDL_FillRect(screen, 0, 0); // Draw image. if (jpegImageScaled != 0) { SDL_BlitSurface(jpegImageScaled, 0, screen, 0); } // Draw blobs. SDL_Rect blobPos; blobPos.x = IMAGE_WIDTH; blobPos.y = 0; if (blobImageScaled != 0) { SDL_BlitSurface(blobImageScaled, 0, screen, &blobPos); } // Draw mouse selection. if (fMouseDown) { rectangleColor(screen, mouseX1, mouseY1, mouseX2, mouseY2, SDL_MapRGB(screen->format, 255, 0, 255)); } SDL_Flip(screen); } return 0; }
bool Sphere::intersect(Ray& r,HitRecord& h,stack<glm::mat4>& modelview) { bool result; glm::mat4 objToView,viewToObj; result = false; modelview.push(modelview.top()); modelview.top() = modelview.top() * animation * transform; objToView = modelview.top(); viewToObj = glm::inverse(objToView); Ray objectRay; objectRay.start = viewToObj * r.start; objectRay.dir = viewToObj * r.dir; float phi, theta; float texS = 0; float texT = 0; double a,b,c; double pi = 3.141592; a = glm::dot(objectRay.dir,objectRay.dir); b = 2*glm::dot(objectRay.dir,objectRay.start); c = glm::dot(glm::vec3(glm::swizzle<glm::X,glm::Y,glm::Z>(objectRay.start)),glm::vec3(glm::swizzle<glm::X,glm::Y,glm::Z>(objectRay.start))) - 1; double disc = b*b - 4*a*c; if (disc<0) { result = false; } else { float t1,t2,t; t1 = (-b+sqrt(disc))/(2*a); t2 = (-b-sqrt(disc))/(2*a); if (t1>t2) { float temp = t1; t1 = t2; t2 = temp; } //now always t1<t2 if (t2<0) //both of them are negative { result = false; } else { result = true; if (t1<0) { t = t2; } else { t = t1; } if ((h.time<0) || (h.time>t)) { glm::vec4 ptIntersect; ptIntersect = objectRay.start + objectRay.dir*t; h.time = t; h.point = objToView * ptIntersect; h.normal = glm::transpose(viewToObj) * glm::vec4(ptIntersect.x,ptIntersect.y,ptIntersect.z,0); h.normal = glm::normalize(h.normal); h.mat = material; h.tex = this->getTexture(); //bound x and y to be bewtween 1 and -1 if(ptIntersect.x > 1) { ptIntersect.x = 1; } else if(ptIntersect.x < -1) { ptIntersect.x = -1; } if(ptIntersect.y > 1) { ptIntersect.y = 1; } else if(ptIntersect.y < -1) { ptIntersect.y = -1; } //y = sin(theta), use to find theta theta = asin(fabs(ptIntersect.y)); //other side of sphere if(ptIntersect.y < 0 ) { theta = -theta; } phi = acos(fabs(ptIntersect.x) / cos(theta)); if(ptIntersect.z < 0) { if(ptIntersect.x < 0) { phi = pi - phi; } } else if(ptIntersect.x < 0) { phi = pi + phi; } else phi = 2*pi - phi; texS = phi / (2*pi); texT = 1-((theta + (pi/2)) / pi); h.textCoords = glm::vec4(texS,texT,0,1); } } } modelview.pop(); return result; }
void chdl::hierarchy_exit() { hstack.pop(); }
//中缀转前缀 char *qianzhui(char *ss,int n) { int i,j,m=0; char swap; char t; n++; char *temp=new char[n]; char *a=new char[n]; a[0]='#'; a[1]='\0'; strcat(a,ss); for (i=n-1;i>=0;i--) { if (isdigit(a[i])) { temp[m]=a[i]; m++; } else { if (a[i]==')') expe.push(')'); else if (a[i]=='(') { while (expe.top()!=')') { temp[m]=expe.top(); m++; expe.pop(); } expe.pop(); } else { while ((!expe.empty())&&(pri[expe.top()]>pri[a[i]])) { temp[m]=expe.top(); m++; expe.pop(); } expe.push(a[i]); } } } temp[m]='\0'; m++; for (i=0;i<m/2;i++) { swap=temp[i]; temp[i]=temp[m-i-2]; temp[m-i-2]=swap; } return temp; }
void pop() { if (s.top() == min.top()) { min.pop(); } s.pop(); }
// 深さ優先探索 bool dfs(string& result, STATE state, STATE goal, stack<STATE> dfs_stack, HASH<string, unsigned int> hs, char** adjacent) { int n; // スワップ対象の位置 string b = ""; // 局面状態の一次保存用 char panel; // パネル int cost; // コスト int diff_ID; // 転倒距離の差分 int diff_MD; // マンハッタン距離の差分 list<Cost_Attribute>buff; list<Cost_Attribute>::iterator it; // 解を発見した場合 if(state->board == goal->board) { // 検索結果を出力 output(result, state, board_width, board_height); return true; } else { // 次の手で移動可能な全ての局面に対して for(int i = 0; (n = adjacent[state->space][i]) != -1; i++) { b = state->board; panel = b[n]; // スワップの対象が壁でない場合 if(state->block[n] != '=') { // スワップ b[state->space] = b[n]; b[n] = '0'; // 既に登録された局面の場合 if(hs.find(b) != NULL) { continue; } // 登録されていない新しい局面の場合 else { // 動かしたパネルの差分だけ計算 diff_ID = invert_distance(state->board) - invert_distance(b); diff_MD = manhattan_distance(panel, state->space+1) - manhattan_distance(panel, n+1); // より大きい(厳しい)値を採用する //if(diff_MD > diff_ID) cost = state->cost + diff_MD; // コストの更新 //else //cost = state->cost + diff_ID; // コストの更新 // 移動可能な局面状態をリストに追加 buff.push_front(Cost_Attribute(cost, Options(b, state))); } } } // もしリストに追加されていた場合 if(buff.size() > 0) { // コストの最も小さい局面から選択されるように並び替え buff.sort(); for(it = buff.begin(); it != buff.end(); it++) { /* // クラスメンバへのポインタの定義 int Cost_Attribute::* mp_cost; Options Cost_Attribute::* mp_attribute; string Options::* mp_board; STATE Options::* mp_state; int candidate_cost = (*it).*mp_cost; string candidate_board = (*it).*mp_attribute.*mp_board; STATE candidate_state = (*it).*mp_attribute.*mp_state; string candidate_block = ((*it).*mp_attribute.*mp_state)->block; int candidate_space; */ int candidate_cost = (*it).first; string candidate_board = (*it).second.first; STATE candidate_state = (*it).second.second; string candidate_block = (*candidate_state).block; int candidate_space; // 空白の位置 for(int i = 0; i < candidate_board.size(); i++) { if(candidate_board[i] == '0') candidate_space = i; } STATE c = new struct State; c->board = candidate_board; c->space = candidate_space; c->block = candidate_block; c->prev_state = candidate_state; c->cost = candidate_cost; // 局面状態の先頭への追加 dfs_stack.push(c); hs.addPair(c->board); // 再帰 if(dfs(result, c, goal, dfs_stack, hs, adjacent)) { delete c; return true; } else // 先頭からの局面状態の取り出し dfs_stack.pop(); }// for }// if } return false; }
void pop() { stk.pop(); minEle.pop(); }
void pop(void) { peek(); output.pop(); }
void showstack(stack s) { cout << "show stack:\n"; int i; for(i=0; i<SIZE; i++) cout << s.pop() << "\n"; }
void pop() { move(); s2.pop(); }
int main() { #ifdef fn freopen(fn ".in", "r", stdin); freopen(fn ".out", "w", stdout); #endif scanf("%s", s + 1); n = strlen(s + 1); for (int i = 1; i <= n; i++) { if (s[i] == '(' || s[i] == '[') st.push(i); if (s[i] == ')') { if (!st.empty() && s[st.top()] == '(') { pr[i] = st.top(), st.pop(); pr[pr[i]] = i; } else { while (!st.empty()) pr[st.top()] = -1, st.pop(); pr[i] = -1; } } if (s[i] == ']') { if (!st.empty() && s[st.top()] == '[') { pr[i] = st.top(), st.pop(); pr[pr[i]] = i; } else { while (!st.empty()) pr[st.top()] = -1, st.pop(); pr[i] = -1; } } } while (!st.empty()) pr[st.top()] = -1, st.pop(); // for (int i = 1; i <= n; i++) // printf("%d ", pr[i]); // puts(""); for (int i = 1; i <= n; i++) a[i] = a[i - 1] + (s[i] == '['); int L = 0, R = -1, l = -1, r = -1, ans = 0; for (int i = 1; i <= n;) { if (pr[i] == -1) { if (l != -1 && umax(ans, a[r] - a[l - 1])) L = l, R = r; l = -1, r = -1; i++; } else { if (l == -1) l = i; r = pr[i]; i = pr[i] + 1; } } if (l != -1 && umax(ans, a[r] - a[l - 1])) L = l, R = r; printf("%d\n", ans); for (int i = L; i <= R; i++) putchar(s[i]); }
void print(stack<int> my_tour) { while (!my_tour.empty()) { int top = my_tour.top(); cout << top << ' '; my_tour.pop(); } }
void NFA::handleOp(char op,stack<char>& opstack,stack<NFAFrag>& stateStack) { switch(op) { case '.': { NFAState* start=newState(); NFAState* end=newState(); // todo: a special node for(int symbol=SYMBOL_BASE;symbol<'\n';symbol++) start->cedges[symbol]=end; for(int symbol='\n'+1;symbol<=SYMBOL_LAST;symbol++) start->cedges[symbol]=end; stateStack.push(NFAFrag(start,end)); } break; // check? // case '?': // { // NFAState* startStateA=stateStack.top();stateStack.pop(); // NFAState* endStateA=stateStack.top();stateStack.pop(); // // //a?* // if(startStateA!=endStateA) // elinkNFAState(startStateA,endStateA); // // stateStack.push(endStateA);stateStack.push(startStateA); // } // break; // case '+': // { // NFAState* startStateA=stateStack.top();stateStack.pop(); // NFAState* endStateA=stateStack.top();stateStack.pop(); // // //a+* // if(startStateA!=endStateA) // elinkNFAState(endStateA,startStateA); // // stateStack.push(endStateA);stateStack.push(startStateA); // } // break; case '?': { // NFAState* startStateA=stateStack.top();stateStack.pop(); // NFAState* endStateA=stateStack.top();stateStack.pop(); NFAFrag operand=stateStack.top();stateStack.pop(); //thompsonClosure NFAState* startState=newState(); NFAState* endState=newState(); patch(startState,operand.start); patch(operand.out,endState); patch(startState,endState); stateStack.push(NFAFrag(startState,endState)); // elinkNFAState(startState,startStateA); // elinkNFAState(startState,endState); // elinkNFAState(endStateA,endState); // // stateStack.push(endState);stateStack.push(startState); } break; case '+': { NFAFrag operand=stateStack.top();stateStack.pop(); patch(operand.out,operand.start); stateStack.push(operand); } break; case '|': { NFAFrag operand1=stateStack.top();stateStack.pop(); NFAFrag operand2=stateStack.top();stateStack.pop(); //NFAState* start=newState(); NFAState* end=newState(); //patch(start,operand1.start); //patch(start,operand2.start); patch(operand1.start,operand2.start); patch(operand1.out,end); patch(operand2.out,end); stateStack.push(NFAFrag(operand1.start,end)); } break; case '{': { NFAFrag operand=stateStack.top();stateStack.pop(); //if(countl>counth){int temp=counth;counth=countl;countl=temp;} // if(startStateA==endStateA) // { // stateStack.push(endStateA);stateStack.push(startStateA); // break; // } int counth=opstack.top();opstack.pop(); int countl=opstack.top();opstack.pop(); if(counth==0)//infinite { if(countl==0) //* { patch(operand.start,operand.out); patch(operand.out,operand.start); stateStack.push(operand); break; } else if(countl==1) // + { patch(operand.out,operand.start); stateStack.push(operand); break; } else { NFAState * start=operand.start, *end=operand.out; for(int i=1;i<countl;i++) { NFAFrag new_frag=cloneFrag(operand); patch(end,new_frag.start); end=new_frag.out; } ///////////check patch(end,start); stateStack.push(NFAFrag(start,end)); break; } } else if(counth==1) { if(countl==0) // ? { patch(operand.start,operand.out); stateStack.push(operand); break; } else if(countl==1) { stateStack.push(operand); break; } //no else,countl<=counth } else//counth>1 { int startindex=countl; NFAState* lend; // countl end NFAState* lastend=operand.out; // for concate if(countl==0) { lend=operand.start; patch(lend,lastend); } else { for(int i=1;i<countl;i++) { NFAFrag new_frag=cloneFrag(operand); patch(lastend,new_frag.start); lastend=new_frag.out; } lend=lastend; } for(int i=max(1,countl);i<counth;i++) { NFAFrag new_frag=cloneFrag(operand); patch(lastend,new_frag.start); lastend=new_frag.out; patch(lend,lastend); } operand.out=lastend; stateStack.push(operand); break; } } break; case '&': { NFAFrag operand1=stateStack.top();stateStack.pop(); NFAFrag operand2=stateStack.top();stateStack.pop(); patch(operand2.out,operand1.start); stateStack.push(NFAFrag(operand2.start,operand1.out)); } break; case '*': { NFAFrag operand=stateStack.top();stateStack.pop(); //NFAState* end=newState(); patch(operand.start,operand.out); patch(operand.out,operand.start); //patch(operand.out,end); //stateStack.push(operand.start,end)); stateStack.push(operand); } break; default: { NFAState* start=newState(); NFAState* end=newState(); start->cedges[op]=end; stateStack.push(NFAFrag(start,end)); } break; } }
int do_pop() { int tmp=_stack.top(); _stack.pop(); return tmp; }
//中缀转后缀 char *houzhui(char *ss,int n) { int i,j,m=0; char t; n++; char *a=new char[n]; strcpy(a,ss); //用#作为表达式结束标志 a[n-1]='#'; char *temp=new char[n]; expe.push('\0'); //处理表达式 for (i=0;i<n;i++) { //如果是数字直接输出 if (isdigit(a[i])) { temp[m]=a[i]; m++; } else { //如果是(,直接入展 if (a[i]=='(') expe.push('('); else //如果是),出栈直到弹出第一个( if (a[i]==')') { while (expe.top()!='(') { temp[m]=expe.top(); m++; expe.pop(); } expe.pop(); } //如果是其他运算符,根据运算符优先级确定是否进栈 else { //如果非空且栈顶元素优先级大于当前符号,出栈 while ((!expe.empty())&&(pri[expe.top()]>=pri[a[i]])) { temp[m]=expe.top(); m++; expe.pop(); } expe.push(a[i]); } } } return temp; }
inline int spop(stack<int> &s) { int x = s.top(); s.pop(); return x; }
void clear_stack(stack<int> &s) { while (!s.empty()) s.pop(); }
char not(stack<char> & operand) { char c; operand.pop(c); return c == 'f' ? 't' : 'f'; }
int main() { int thread_id, threads_num; #pragma omp master { // Compute the distance matrix for classrooms compute_distance_matrix(); for(int i = room_num-1; i > 0; i--){ Node* new_node = new Node(i); new_node->level = 1; //second level actually new_node->local_cost = distance_matrix[0][i]; new_node->local_path.push_back(0); new_node->local_path.push_back(i); new_node->flag[0] = true; new_node->flag[i] = true; traverse_stack.push(new_node); } } #pragma omp barrier #pragma omp parallel { thread_id = omp_get_thread_num(); if (thread_id==0){ start_time = omp_get_wtime(); // Get start time } while(true){ stack_lock.lock(); if(traverse_stack.empty()){ stack_lock.unlock(); break; } Node* top_node = traverse_stack.top(); traverse_stack.pop(); //cout << s.size() << ", " << n->level << endl; if(top_node->level < 4){ for(int i = room_num-1; i > 0; i--){ if(top_node->flag[i]) continue; Node* temp_node = new Node(i); temp_node->local_cost += top_node->local_cost+distance_matrix[top_node->local_path.back()][i]; temp_node->local_path = top_node->local_path; temp_node->flag = top_node->flag; temp_node->local_path.push_back(i); temp_node->flag[i] = true; temp_node->level = top_node->level+1; traverse_stack.push(temp_node); } } stack_lock.unlock(); if(top_node->level >= 4) graph_traverse(top_node->local_path, top_node->flag, top_node->local_cost, top_node->local_path.back()); } } #pragma omp barrier if (thread_id==0){ end_time = omp_get_wtime(); // Get end time } #pragma omp master { //threads_num = omp_get_num_threads(); //cout << "Number of threads: " << threads_num << '\n'; end_time = omp_get_wtime(); cout << "Best path cost: " << bound_cost << endl; cout << "Best path: "; for(int i = 0; i < best_path.size(); i++){ cout << best_path[i] << "->"; } cout << 0 << endl; cout << "Elapsed time: " << end_time-start_time << endl;; } return 0; }
void guiyue9() { stateStack.pop(); }
int main() { char *ss="1+12*3+4"; cin>>str>>query; len=strlen(str); for(int i=0;i<len;i++) { if(str[i]=='+'||str[i]=='*') { op1.push(str[i]); }else { LL num=0; while(isdigit(str[i])) { num+=str[i]-'0';i++; }i--; if(!op1.empty()) { char op=op1.top(); if(op=='*') { int t=st1.top();st1.pop(); st1.push(t*num); op1.pop(); }else st1.push(num); }else st1.push(num); } } while(!st1.empty()) { LL t=st1.top();st1.pop(); M+=t; } for(int i=0;i<len;i++) { if(isdigit(str[i])) { LL num=0; while(isdigit(str[i])) { num+=str[i]-'0';i++; }i--; if(!op2.empty()) { char op=op2.top();op2.pop(); LL t=st2.top();st2.pop(); if(op=='+') { st2.push(num+t); }else if(op=='*') { st2.push(num*t); } }else st2.push(num); }else if(str[i]=='+'||str[i]=='*') { op2.push(str[i]); } } L=st2.top(); //cout<<L<<" "<<M<<endl; if(M==query&&L!=query) { printf("M\n"); }else if(M!=query&&L==query) { printf("L\n"); }else if(M==query&&L==query) { printf("U\n"); }else if(M!=query&&L!=query) { printf("I\n"); } return 0; }
void guiyue10() { stateStack.pop(); }
int main(){ int p; char ch; cin>>ch; p=ch-'0'; for(int i=0;i<p;i++){ pro.clear(); string g=""; cin>>g; while(g[0]!='~'){ pro.push_back(g); cin>>g; } grammar.push_back(pro); } int it=grammar.size(); for(int i=0;i<it;i++){ pro.clear(); pro=grammar[i]; int it1=pro.size(); cout<<pro[0]<<"->"; for(int j=1;j<it1;j++){ cout<<pro[j]<<"|"; } cout<<endl; } int n=6; string op[6]={"i","*","/","+","-","$"}; ops['i']=0; ops['*']=1; ops['/']=2; ops['+']=3; ops['-']=4; ops['$']=5; int prec[6][6]; string s; int matched; cout<<"Enter the input string \n"; cin>>s; cout<<s<<endl; //return 0; int len=s.length(); string sss="_"; cout<<len<<endl; for(int i=0;i<len;i++){ //cout<<"in loop"; news.push_back(sss); } cout<<s<<endl; int ipt,pt=0; int max=s.length(); for(int i=0;i<n;i++){ char val; for(int j=0;j<n;j++){ cin>>val; prec[i][j]=val-'0'; } } cout<<" "; for(int i=0;i<n;i++){ cout<<op[i]<<" "; } cout<<endl; for(int i=0;i<n;i++){ cout<<op[i]<<" "; for(int j=0;j<n;j++){ int x=prec[i][j]; if(x==0) cout<<"E "; else if(x==1) cout<<"L "; else if(x==2) cout<<"G "; else if(x==3) cout<<"W "; else cout<<"A "; } cout<<endl; } cout<<"parse tree is printed as a string where '_' means blank and otherwise the productions used till now\n"; mp=make_pair('$',1000); pt=0,ipt=-1; st.push(mp); while(!(st.top().first=='$' && s[pt]=='$')){ //cout<<st.top().first<<" "<<char(s[pt])<<endl; int preval=prec[ops[st.top().first]][ops[char(s[pt])]]; // cout<<"value"<<preval<<"\n "; if(preval==1 || preval==0){ // cout<<"Pushed "; mp=make_pair(char(s[pt]),pt); pt++; st.push(mp); // cout<<mp.first<<endl; } else if(preval==2){ mp=st.top(); st.pop(); //string temp1=string(mp.first); news[mp.second]=""; news[mp.second]+=mp.first; // cout<<"mp.second "<<mp.second<<" "<<news[mp.second]<<" "<<endl; string ret=findPro(mp.second); // cout<<"production found is "<<ret<<endl; } else if(preval==3){ cout<<"Error while parsing breaking bad...!\n"; break; } else if(preval==4){ cout<<"Congrats string is Accepted...!\n"; } } return 0; }
void guiyue3() { stateStack.pop(); return; }
static bigpair popstack (stack <bigpair> &egyptstack) { bigpair result = egyptstack.top (); egyptstack.pop(); return result; }
void findnearest(FILE *fout) { int x = root; int nearest = -1; double mind = 0x7FFFFFFF; dfs2(x, nearest, mind); if (nearest == -1) { nearest = stk.top(); mind = dist(kd[nearest].d, target); } while (!q.empty()) q.pop(); q.push(T(kd[nearest].d[0], kd[nearest].d[1], mind)); used[nearest] = nowi; nown = 1; while (!stk.empty()) { int bp = stk.top(); stk.pop(); double maxd = q.top().dis; if (kd[bp].lc == 0 && kd[bp].rc == 0) { if (used[bp]!=nowi && (nown < kmin || cmps(dist(kd[bp].d, target) - maxd) < 0)) { used[bp] = nowi; if (nown == kmin) q.pop(); q.push(T(kd[bp].d[0], kd[bp].d[1], dist(kd[bp].d, target))); if (nown<kmin) nown++; } } else { int s = kd[bp].split; int psearch; if (target[s] <= kd[bp].d[s]) { psearch = kd[bp].lc; if (psearch && vis[psearch] != nowi) stk.push(psearch); if ( (nown<kmin || cmps(abs(kd[bp].d[s] - target[s]) - maxd) < 0)) { psearch = kd[bp].rc; if (psearch && vis[psearch] != nowi) stk.push(psearch); } } else { psearch = kd[bp].rc; if (psearch && vis[psearch] != nowi) stk.push(psearch); if ( (nown<kmin || cmps(abs(kd[bp].d[s] - target[s]) - maxd) < 0)) { psearch = kd[bp].lc; if (psearch && vis[psearch] != nowi) stk.push(psearch); } } if (used[bp]!=nowi && (nown<kmin || cmps(dist(kd[bp].d, target) - maxd) < 0)) { used[bp] = nowi; if (nown == kmin) q.pop(); q.push(T(kd[bp].d[0], kd[bp].d[1], dist(kd[bp].d, target))); if (nown<kmin) nown++; } } } int cnt = 0; while (!q.empty()) { ans[++cnt] = q.top(); q.pop(); } fprintf(fout, "%d\n",cnt); fprintf(fout, "%d %d\n", target[0], target[1]); for (int i = cnt; i >= 1; i--) { fprintf(fout, "%d %d %.8f\n", ans[i].d[0], ans[i].d[1], ans[i].dis); } }