vector<string> wordBreak(string s, unordered_set<string> &dict) { string result; vector<string> solutions; int len = s.size(); vector<bool> possible(len + 1, true); GetAllSolution(0, s, dict, len, result, solutions, possible); return solutions; }
vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector<string> sentences; vector<string> sol; vector<int> possible(s.length()+1, true); findWordBreak(s, wordDict, 0, sol, sentences, possible); return sentences; }
void movement(roomGrid *room_grid, progress *puzzle, char *instructions_list[NUM_INSTRUCTIONS], Chicken *hen) { SDL_Delay(20); SDL_Event event; // call SDL_Event if (SDL_PollEvent(&event)) // If there is an event { // HandleEvent(event, rcSrc, rcSprite); //Run the HandleEvent function switch (event.type) { case SDL_QUIT: room_grid -> gamerunning = false; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_q: room_grid -> gamerunning = false; break; case SDLK_LEFT: room_grid -> direction = left; (!((room_grid -> rcSprite.x) % TILE_SIZE)) ? possible(room_grid, puzzle): move(room_grid, puzzle); break; case SDLK_RIGHT: room_grid -> direction = right; (!((room_grid -> rcSprite.x) % TILE_SIZE)) ? possible(room_grid, puzzle): move(room_grid, puzzle); break; case SDLK_UP: room_grid -> direction = up; (!((room_grid -> rcSprite.y) % TILE_SIZE)) ? possible(room_grid, puzzle): move(room_grid, puzzle); break; case SDLK_DOWN: room_grid -> direction = down; (!((room_grid -> rcSprite.y) % TILE_SIZE)) ? possible(room_grid, puzzle): move(room_grid, puzzle); break; case SDLK_SPACE: interactProbe(room_grid, puzzle, instructions_list, hen); break; case SDLK_9: sound_on_off(room_grid); break; } break; } } }
std::vector<std::string> wordBreak2(std::string s, std::unordered_set<std::string>& dict) { std::string result; std::vector<std::string> solutions; int len = s.size(); std::vector<bool> possible(len, true); //possible[i]为true表示[i, n - 1]有解 GetAllSolution(0, s, dict, len, result, solutions, possible); return solutions; }
bool judge() { for(int i=0;i<n;++i) { if(possible(i)) { return true; } } return false; }
vector<string> wordBreak(const string& s, const unordered_set<string>& wordDict) { vector<string> result; if (wordDict.empty() || s.empty()) { return std::move(result); } vector<bool> possible(s.size() + 1, true); vector<string> stack; this->recursiveSolve(result, stack, possible, s.cbegin(), s, wordDict); return std::move(result); }
void possible( int M, int m, int cnt ) { if ( m == 1 && M == 1 ) { large_valid = 1; } else { if ( m == 1 ) { small_valid = 1; } while( cnt > 0 ) { if ( M % cnt == 0 ) possible( M/cnt, m, cnt-1 ); if ( m % cnt == 0 ) possible( M, m/cnt, cnt-1 ); cnt --; } } }
int smallestDistancePair(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); int left = 0, right = nums.back() - nums.front() + 1; while (left < right) { const auto mid = left + (right - left) / 2; if (possible(mid, nums, k)) { right = mid; } else { left = mid + 1; } } return left; }
int main(void){ while(scanf("%d%d", &n, &v) == 2){ int min_cap = 0, u, v, w; FOR(i, n) scanf("%d", z + i), min_cap = max(min_cap, z[i]); for(u = min_cap, v = MAXC; u < v; ){ w = (u + v) >> 1; if(!possible(w)) u = w + 1; else v = w; } printf("%d\n", u); } return 0; }
double minmaxGasDist(vector<int>& stations, int K) { double left = 0.0; double right = 1e8; while (right - left > 1e-6) { const auto mid = left + (right - left) / 2.0; if (possible(stations, K, mid)) { right = mid; } else { left = mid; } } return left; }
bool wordBreak(string s, unordered_set<string> &dict) { string s2 = '#' + s; int len = s2.size(); vector<bool> possible(len, 0); possible[0] = true; for(int i =1; i< len; ++i) { for(int k=0; k<i; ++k) { possible[i] = possible[k] && dict.find(s2.substr(k+1, i-k)) != dict.end(); if(possible[i]) break; } } return possible[len-1]; }
void search(char *begin) { #ifdef _DEBUG printf("# Search: %s\tLongest: %s\n",begin,longestWord); #endif for(int i=0; i<dictionarySize; i++) { if(visited[i]) continue; if(!possible(begin,dictionary[i])) continue; if(strlen(longestWord)<strlen(dictionary[i])) longestWord=dictionary[i]; visited[i]=true; search(dictionary[i]); } }
int main(){ int a, b, c; scanf("%d %d %d\n", &a, &b, &c); std::vector<bool> possible(c + 1, 0); possible[0] = 1; for(int p = 0; p <= c; p++){ if(!possible[p]){continue;} if(p + a <= c){possible[p + a] = 1;} if(p + b <= c){possible[p + b] = 1;} } puts(possible[c] ? "Yes" : "No"); return 0; }
bool wordBreak(string s, unordered_set<string>& wordDict) { string s2 = '#' + s; int size = s2.size(); vector<bool> possible(size, false); possible[0] = true; for (int i = 1; i < size; i++) { for (int k = 0; k < i; k++) { possible[i] = possible[k] && wordDict.find(s2.substr(k + 1, i - k)) != wordDict.end(); if (possible[i]) { break; } } } return possible[size - 1]; }
int input_move(STONE board[N][N], int turn){ int X, Y; if (!possible(board, turn)){ printf("You can't set a stone anywhere.\nYou will pass.\n"); return 0; } while(1){ printf("input your move.(1~8): "); scanf("%d %d", &X, &Y); X--; Y--; // 1~8 -> 0~7 } return set(board, X, Y, turn); }
vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<string> res; unordered_map<char,vector<string> > capnum; for_each(dict.begin(), dict.end(), [&](const string& str){capnum[str[0]].push_back(str);}); vector<bool> possible(s.length()+1,true); auto startwith =[](const string& str, int pos, const string& head){ for (int i = 0; i < head.length(); ++i) { if(pos+i >= str.length() || str[pos+i] != head[i] ) return false; } return true; }; function<bool(int, vector<string>& )> f = [&](int pos, vector<string>& vv){ if(pos >= s.length()){ string rs = vv[0]; for (int i = 1; i < vv.size(); ++i) { rs += " " + vv[i]; } res.push_back(move(rs)); return true; } if(capnum.count(s[pos]) == 0) return false; const auto& canv = capnum[s[pos]]; bool br = false; for (auto ss:canv) { int len = ss.length(); if(pos+len <=s.length() && possible[pos+len] && dict.count(ss) && startwith(s, pos, ss)){ vv.push_back(ss); bool b = f(pos+len,vv); possible[pos+len] = b; br |= b; vv.pop_back(); } } return br; }; vector<string> vv; f(0, vv); return res; }
int main() { ull i; for(i=0;i<=N;++i) squares[i]=i*i; int t; scanf("%d",&t); ull n; for(i=0;i<t;++i) { scanf("%lld",&n); if(possible(n)) printf("Yes\n"); else printf("No\n"); } return 0; }
void move(int r, int c, int p) { int d, t, o = (p == 'B') ? 'W' : 'B'; assert(possible(r, c, p)); a[r][c] = p; for (d = 0; d < 8; d++) { for (t = 1; valid(r + t * dr[d], c + t * dc[d]); t++) if (a[r + t * dr[d]][c + t * dc[d]] != o) break; if (t < 2 || !valid(r + t * dr[d], c + t * dc[d])) continue; if (a[r + t * dr[d]][c + t * dc[d]] != p) continue; for (t = 1; valid(r + t * dr[d], c + t * dc[d]); t++) { if (a[r + t * dr[d]][c + t * dc[d]] != o) break; a[r + t * dr[d]][c + t * dc[d]] = p; } } }
bool PackingRects::pack(const Size& size) { m_bounds = Rect(size).shrink(m_borderPadding); // We cannot sort m_rects because we want to std::vector<Rect*> rectPtrs(m_rects.size()); int i = 0; for (auto& rc : m_rects) rectPtrs[i++] = &rc; std::sort(rectPtrs.begin(), rectPtrs.end(), by_area); gfx::Region rgn(m_bounds); for (auto rcPtr : rectPtrs) { gfx::Rect& rc = *rcPtr; // The rectangles are treated as its original size during placement, // but occupies an extra border of <shapePadding> pixels once its // position has been determined. // This ensures that all rectangles are padded by <sp> pixels, // and are still placed correctly near edges, e.g. when remaining // horizontal space is between <width> and <width>+<shapePadding>. for (int v=0; v<=m_bounds.h-rc.h; ++v) { for (int u=0; u<=m_bounds.w-rc.w; ++u) { gfx::Rect possible(m_bounds.x + u, m_bounds.y + v, rc.w, rc.h); Region::Overlap overlap = rgn.contains(possible); if (overlap == Region::In) { rc = possible; rgn.createSubtraction( rgn, gfx::Region(Rect(rc).inflate(m_shapePadding)) ); goto next_rc; } } } return false; // There is not enough room for "rc" next_rc:; } return true; }
void Connect4::computerPlay() { int score, bestMove, bestScore; int nply = difficulty; int *pMoves = possible(); printf("nply: %d \nScores :", nply); if (player == 1) { bestScore = -1000000000; for (int k=0; k<NB_COLUMNS; k++) { if (pMoves[k]==1) { playAtColumn(k); score = abPruning(1000000000, -1000000000, nply); printf("%d ", score); if ( score > bestScore) { bestScore = score; bestMove = k; } unplayAtColumn(k); } } printf("\n"); } if (player == -1) { bestScore = 1000000000; for (int k=0; k<NB_COLUMNS; k++) { if (pMoves[k]==1) { playAtColumn(k); score = abPruning(1000000000, -1000000000, nply); printf("%d ", score); if ( score < bestScore) { bestScore = score; bestMove = k; } unplayAtColumn(k); } } printf("\n"); } playAtColumn(bestMove); }
void randomTree(Graph &G, int n, int maxDeg, int maxWidth) { G.clear(); if (n <= 0) return; if (maxDeg <= 0) maxDeg = n; if (maxWidth <= 0) maxWidth = n; int max = 0; Array<node> possible(n); Array<int> width(0,n,0); NodeArray<int> level(G,0); level[possible[0] = G.newNode()] = 0; --n; while(n > 0) { int i = randomNumber(0,max); node v = possible[i]; if (width[level[v]+1] == maxWidth) { possible[i] = possible[max--]; continue; } if (v->outdeg()+1 == maxDeg) possible[i] = possible[max--]; node w = G.newNode(); possible[++max] = w; G.newEdge(v,w); width[level[w] = level[v]+1]++; --n; } }
} } } /* * Outputs usage information. Invoked by -h or when an erroneous argument is * given */ void usage (char *self) { printf (_ ("Usage: %s [OPTION]... [FILE]...\n\ --mean, -m\t\t\tPrint mean only\n\ --stdev, -s\t\t\tPrint standard deviation only\n\ --stdev-variance -V\t\tPrint variance (standard deviation) only\n\ --population-stdev, -S\tPrint population standard deviation only\n\ --population-variance, -w\tPrint variance (population standard deviation) only\n\ --median, -M\t\t\tPrint median only\n\ --mode, -f\t\t\tPrint mode only\n"), self); /* Broken into two because of the 510 byte "limit" in c89 */ printf (_ (" --num-elements, -e\t\tPrint number of elements only\n\ --print-values, -p\t\tPrint out sorted values (not printed in normal output if omitted)\n\ --maxmin, -o\t\t\tPrint max and min values only\n\ --sum, -t\t\t\tPrint sum only\n")); printf (_ (" --assume-sorted, -a\t\tAssume sorted input - avoids sorting overhead\n\ --ignore-noise, -i\t\tIgnore lines with garbage input as much as possible (ie. tolerate 5M and ignore lines not beginning with numbers)\n\ --help, -h\t\t\tPrint this help text and exit\n\ --version, -v\t\t\tPrint version information and exit\n")); exit (EXIT_FAILURE); }
// we have a segment, in NFD. Find all the strings that are canonically equivalent to it. UnicodeString* CanonicalIterator::getEquivalents(const UnicodeString &segment, int32_t &result_len, UErrorCode &status) { Hashtable result(status); Hashtable permutations(status); Hashtable basic(status); if (U_FAILURE(status)) { return 0; } result.setValueDeleter(uprv_deleteUObject); permutations.setValueDeleter(uprv_deleteUObject); basic.setValueDeleter(uprv_deleteUObject); UChar USeg[256]; int32_t segLen = segment.extract(USeg, 256, status); getEquivalents2(&basic, USeg, segLen, status); // now get all the permutations // add only the ones that are canonically equivalent // TODO: optimize by not permuting any class zero. const UHashElement *ne = NULL; int32_t el = UHASH_FIRST; //Iterator it = basic.iterator(); ne = basic.nextElement(el); //while (it.hasNext()) while (ne != NULL) { //String item = (String) it.next(); UnicodeString item = *((UnicodeString *)(ne->value.pointer)); permutations.removeAll(); permute(item, CANITER_SKIP_ZEROES, &permutations, status); const UHashElement *ne2 = NULL; int32_t el2 = UHASH_FIRST; //Iterator it2 = permutations.iterator(); ne2 = permutations.nextElement(el2); //while (it2.hasNext()) while (ne2 != NULL) { //String possible = (String) it2.next(); //UnicodeString *possible = new UnicodeString(*((UnicodeString *)(ne2->value.pointer))); UnicodeString possible(*((UnicodeString *)(ne2->value.pointer))); UnicodeString attempt; nfd.normalize(possible, attempt, status); // TODO: check if operator == is semanticaly the same as attempt.equals(segment) if (attempt==segment) { //if (PROGRESS) printf("Adding Permutation: %s\n", UToS(Tr(*possible))); // TODO: use the hashtable just to catch duplicates - store strings directly (somehow). result.put(possible, new UnicodeString(possible), status); //add(possible); } else { //if (PROGRESS) printf("-Skipping Permutation: %s\n", UToS(Tr(*possible))); } ne2 = permutations.nextElement(el2); } ne = basic.nextElement(el); } /* Test for buffer overflows */ if(U_FAILURE(status)) { return 0; } // convert into a String[] to clean up storage //String[] finalResult = new String[result.size()]; UnicodeString *finalResult = NULL; int32_t resultCount; if((resultCount = result.count())) { finalResult = new UnicodeString[resultCount]; if (finalResult == 0) { status = U_MEMORY_ALLOCATION_ERROR; return NULL; } } else { status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } //result.toArray(finalResult); result_len = 0; el = UHASH_FIRST; ne = result.nextElement(el); while(ne != NULL) { finalResult[result_len++] = *((UnicodeString *)(ne->value.pointer)); ne = result.nextElement(el); } return finalResult; }
int main(int argc, char *argv[]) { SDL_Surface *ecran = NULL; //surface affichée à l'ecran SDL_Event event; //stock l'evenement Case plateau[TAILLE_PLATEAU][TAILLE_PLATEAU]; //le plateau Case precedent[TAILLE_PLATEAU][TAILLE_PLATEAU]; //le plateau precedent (pour annuler) Joueur joueur; //à qui le tour ? bool continuer = true; //booléen pour rester dans la boucle bool fin = false; //booléen declenchant la fin du programme bool appuiAbandon = false, appuiAnnuler = false;//les boutons bool peutAnnuler; //si on peut appuyer sur annuler bool selection; //une case est-elle selectionnée int cliqueeX = 0, cliqueeY = 0; //si oui : quelles sont ces coordonnées ? char cause[10]; //chaine pour la fin... // Démarrage de la SDL, et de la bibliotheque de police. SDL_Init(SDL_INIT_VIDEO); TTF_Init(); //Ouverture de la fenetre #ifdef FULLSCREEN ecran = SDL_SetVideoMode(ECRAN_X, ECRAN_Y, NB_COULEURS, SDL_HWSURFACE|SDL_FULLSCREEN); #else ecran = SDL_SetVideoMode(ECRAN_X, ECRAN_Y, NB_COULEURS, SDL_HWSURFACE); #endif // On change le titre SDL_WM_SetCaption(TITRE_FENETRE, NULL); do { //initialisation des variables selection = false; // aucune case ne doit etre cliquee (securite) joueur = blanc; // les blancs commencent toujours //On initialise le plateau reinitialiser(plateau); peutAnnuler = false; do { //Affichage afficher(plateau, joueur, ecran, selection, cliqueeX, cliqueeY, appuiAbandon, appuiAnnuler); //Entree SDL_WaitEvent(&event); //Gestion (selon le type de l'evenement) //appui sur la croix (fenetre) if(event.type == SDL_QUIT) fin = true; //on s'en va... //appui sur une touche else if(event.type == SDL_KEYDOWN) { //la touche etant Echap if(event.key.keysym.sym == SDLK_ESCAPE) fin = true; //on s'en va... } //bouton de la souris relaché else if(event.type == SDL_MOUSEBUTTONUP) { //c'etait un clic gauche if(event.button.button == SDL_BUTTON_LEFT) { //on avais cliqué sur annuler if(appuiAnnuler) { //si on peut annuler if(peutAnnuler) { //on ne le peut plus peutAnnuler = false; //le plateau actuel est le plateau d'avant egalPlateau(plateau, precedent); //on redonne la main au joueur precedent joueur = (joueur == noir) ? blanc : noir; //aucune case cliquee selection = false; } //bouton annuler : relaché appuiAnnuler = false; } //on avais cliqué sur abandon else if(appuiAbandon) { //c'est l'autre joueur qui gagne joueur = (joueur == blanc) ? noir : blanc; //bouton abandon : relaché appuiAbandon = false; //fin de la partie continuer = false; //la cause etant l'abandon sprintf(cause, "abandon"); } } } //appui sur un bouton de la souris else if(event.type == SDL_MOUSEBUTTONDOWN) { //clic gauche if(event.button.button == SDL_BUTTON_LEFT) { //on appuie sur le bouton annuler if(event.button.x > BOUTON_ANNULER_X && event.button.x < BOUTON_ANNULER_X+TAILLE_BOUTON_X && event.button.y > BOUTON_ANNULER_Y && event.button.y < BOUTON_ANNULER_Y+TAILLE_BOUTON_Y) appuiAnnuler = true; //on appuie sur le bouton abandon else if(event.button.x > BOUTON_ABANDON_X && event.button.x < BOUTON_ABANDON_X+TAILLE_BOUTON_X && event.button.y > BOUTON_ABANDON_Y && event.button.y < BOUTON_ABANDON_Y+TAILLE_BOUTON_Y) appuiAbandon = true; //on clique dans la zone de jeu else if(event.button.x > ZDJ_X && event.button.x < ZDJ_X+ZDJ && event.button.y > ZDJ_Y && event.button.y < ZDJ_Y+ZDJ) { //si on avais dejà selectionné quelque chose if(selection) { //si le deplacement est autorise if(possible(plateau, cliqueeX, cliqueeY, ((event.button.x-ZDJ_X)/TAILLE_CASES), ((event.button.y-ZDJ_Y)/TAILLE_CASES))) { //(se deplacer), et si quelque chose a été mangé if(manger(plateau, cliqueeX, cliqueeY, ((event.button.x-ZDJ_X)/TAILLE_CASES), ((event.button.y-ZDJ_Y)/TAILLE_CASES))) { //le pion est toujours selectionnable, mais à son nouvel //emplacement cliqueeX = ((event.button.x-ZDJ_X)/TAILLE_CASES); cliqueeY = ((event.button.y-ZDJ_Y)/TAILLE_CASES); //a t-on gagne par victoire totale ? //si oui, on sort de la partie continuer = !gagner(plateau, joueur); if(!continuer) sprintf(cause, "victoire totale"); //sinon, si on ne peut plus manger --> au joueur suivant ! else if(!peutManger(plateau, cliqueeX, cliqueeY)) { //on deselectionne le pion selection = false; //on change de joueur joueur = (joueur == blanc) ? noir : blanc; //on peut revenir en arriere peutAnnuler = true; //sommes-nous bloqué ? continuer = !bloque(plateau, joueur); if(!continuer) { sprintf(cause, "blocage"); //si oui, c'est l'autre joueur, //celui qui vient de jouer, qui gagne ! joueur = (joueur == blanc) ? noir : blanc; } } } //rien a été mangé : au joueur suivant ! else { //on deselectionne le pion selection = false; //on change de joueur joueur = (joueur == blanc) ? noir : blanc; //on peut revenir en arriere peutAnnuler = true; } } } //sinon, si on clique sur un pion else if(plateau[(event.button.x-ZDJ_X)/TAILLE_CASES][(event.button.y-ZDJ_Y)/TAILLE_CASES].pion != non) { //coordonnees du pion en question cliqueeY = (event.button.y-ZDJ_Y)/TAILLE_CASES; cliqueeX = (event.button.x-ZDJ_X)/TAILLE_CASES; //si on peut selectionner ce pion if(plateau[cliqueeX][cliqueeY].joueur == joueur && selectionnable(plateau, cliqueeX, cliqueeY)) { //le prochain plateau precedent est le plateau actuel egalPlateau(precedent, plateau); //le pion est selectionné selection = true; //on ne peut plus annuler (il faudra d'abord cliquer sur une case) peutAnnuler = false; } } } } } //Gestion terminée //repeter ceci tant que la partie nest pas terminée, et que l'on ne veut pas s'en aller }while (continuer && !fin); //securité... appuiAbandon = false; appuiAnnuler = false; //considerons ici abandon <-> quitter et annuler <-> recommencer //tant que l'on a pas choisi... while(!continuer && !fin) { //on affiche le message de fin affichageFin(plateau, ecran, appuiAnnuler, appuiAbandon, joueur, cause); //si il y a un evenement SDL_WaitEvent(&event); //de type : "boutton de sourie relaché" if(event.type == SDL_MOUSEBUTTONUP) { //si le bouton en question est le gauche if(event.button.button == SDL_BUTTON_LEFT) { //si on avais appuyé sur recommencer if(appuiAnnuler) { //on relache le bouton appuiAnnuler = false; //on recommence une partie continuer = true; } //sinon si on avais appuyé sur arreter else if(appuiAbandon) { //on relache le bouton appuiAbandon = false; //on s'en va fin = true; } } } //de type : "appui sur une bouton de la souris" else if(event.type == SDL_MOUSEBUTTONDOWN) { //clic gauche if(event.button.button == SDL_BUTTON_LEFT) { //sur le bouton "oui" (recommencer (annuler)) if(event.button.x > FIN_BOUTON_OUI_X && event.button.x < FIN_BOUTON_OUI_X+TAILLE_BOUTON_X && event.button.y > FIN_BOUTON_OUI_Y && event.button.y < FIN_BOUTON_OUI_Y+TAILLE_BOUTON_Y) appuiAnnuler = true; //sur le bouton "non" (arreter (abandon)) else if(event.button.x > FIN_BOUTON_NON_X && event.button.x < FIN_BOUTON_NON_X+TAILLE_BOUTON_X && event.button.y > FIN_BOUTON_NON_Y && event.button.y < FIN_BOUTON_NON_Y+TAILLE_BOUTON_Y) appuiAbandon = true; } } //de type : "appui sur la croix de la fenetre" else if(event.type == SDL_QUIT) fin = true; //de type : "appui sur une touche" else if(event.type == SDL_KEYDOWN) { //la touche Echap if(event.key.keysym.sym == SDLK_ESCAPE) fin = true; } } //tant que l'on ne veut pas s'en aller }while(!fin); //arret de la SDL et de la biblio des polices TTF_Quit(); SDL_Quit(); //tout s'est bien passé return EXIT_SUCCESS; }
int main(int argc, char **argv) { mint maxLen = 0; mint nNodes = 0; mint ** coords; mdouble ** dists; string file = "../examples/pub02"; string s; char buff[6]; stringstream ss; #if DBG string inadr = file; ifstream inFile (inadr.append(".in").data()); getline(inFile,s); #else getline(cin,s); #endif ss << s; ss.getline(buff,6,' '); nNodes = (mint)(atoi(buff)); // TODO buff se mozna musi po pouziti zas smazat ss.getline(buff,6,' '); maxLen = (mint)(atoi(buff)); //scout << nNodes << " " << maxLen << endl; coords = new mint * [nNodes]; for(mint i=0;i<nNodes;i++){ coords[i] = new mint[2]; } dists = new mdouble * [nNodes]; for(mint i=0;i<nNodes;i++){ dists[i] = new mdouble[nNodes]; } #if DBG for(mint i=0;i<nNodes;i++){ s.clear(); ss.clear(); getline(inFile,s); ss << s; ss.getline(buff,6,' '); coords[i][0] = (mint)(atoi(buff)); ss.getline(buff,6,' '); coords[i][1] = (mint)(atoi(buff)); } inFile.close(); #else for(mint i=0;i<nNodes;i++){ s.clear(); ss.clear(); getline(cin,s); ss << s; ss.getline(buff,6,' '); coords[i][0] = (mint)(atoi(buff)); ss.getline(buff,6,' '); coords[i][1] = (mint)(atoi(buff)); } #endif #if DBG ifstream fileStream (file.append(".out").data()); s.clear(); getline(fileStream,s); cout << "Correct result: " << s << endl; fileStream.close(); #endif /*/ for(mint i=0;i<nNodes;i++){ for(mint j=0;j<2;j++){ cout << coords[i][j] << " "; } cout << endl; } /**/ for(mint i=0;i<nNodes;i++){ for(mint j=0;j<nNodes;j++){ if(j>i){ dists[i][j]=dist(coords[i][0],coords[i][1],coords[j][0],coords[j][1]); } else if (j<i) { dists[i][j] = dists[j][i]; } else { dists[i][i]=0; } } } mint **** conflicts = new mint *** [nNodes]; for(mint i=0;i<nNodes;i++){ conflicts[i] = new mint ** [nNodes]; for(mint j=0;j<nNodes;j++){ conflicts[i][j] = new mint * [nNodes]; for(mint k=0;k<nNodes;k++){ conflicts[i][j][k] = new mint[nNodes]; for(mint l=0;l<nNodes;l++){ conflicts[i][j][k][l]=intersects(coords[i],coords[j],coords[k],coords[l]); } } } } /*for(mint i=0;i<nNodes;i++){ for(mint j=0;j<nNodes;j++){ cout << dists[i][j] << " "; } cout << endl; }/**/ list<Node *> * oldGen = new list<Node *>(); list<Node *> * newGen = new list<Node *>(); list<Node *>::iterator it; mint level = 0; // bit mask of available vertices mint avVertices = pow(2,nNodes) - 1; for(mint i = 0;i<nNodes;i++){ Node * n = new Node(0); n->avNodesMask = avVertices xor 1 << i; // cout <<"Node #: " << i << " AvNodeMask: " << (bitset<16>) n->avNodesMask << endl; n->nodes->push_back(i); oldGen->push_back(n); } for(it=oldGen->begin();it!=oldGen->end();++it){ // cout << "next from old: " << endl; // (*it)->printNode(); for(mint i=0;i<nNodes;i++){ // cout << "next to add: " << i << endl; if((*it)->avNodesMask & 1 << i){ mdouble len = (*it)->len + dists[(*it)->nodes->back()][i]; Node * n = new Node(len); list<mint>::iterator ns; ns = (*it)->nodes->begin(); for(ns;ns!=(*it)->nodes->end();++ns){ n->nodes->push_back(*ns); //cout << *ns << endl; } n->nodes->push_back(i); n->avNodesMask = (*it)->avNodesMask xor 1 << i; // cout << "added: " << i << endl; newGen->push_back(n); //break; } } newGen->pop_back(); } deleteNodeList(oldGen); oldGen->clear(); delete oldGen; oldGen=newGen; level++; /**/ while(level<nNodes){ // oldGenSize = oldGen->size(); newGen = new list<Node *>(); for(it=oldGen->begin();it!=oldGen->end();++it){ // cout << "next from old: " << endl; // (*it)->printNode(); for(mint i=0;i<nNodes;i++){ // cout << "next to add: " << i << endl; if((*it)->avNodesMask & 1 << i){ if(possible(conflicts,(*it)->nodes,i)){ mdouble addedToFirstDist = dists[i][(*it)->nodes->front()]; mdouble len = (*it)->len + dists[(*it)->nodes->back()][i]; if (len + addedToFirstDist <= maxLen) { Node * n = new Node(len); list<mint>::iterator ns; ns = (*it)->nodes->begin(); for(ns;ns!=(*it)->nodes->end();++ns){ n->nodes->push_back(*ns); //cout << *ns << endl; } n->nodes->push_back(i); n->avNodesMask = (*it)->avNodesMask xor 1 << i; // cout << "added: " << i << endl; newGen->push_back(n); //break; } } } } } if(newGen->empty() || level+1 == nNodes){ it = oldGen->begin(); list<mint>::iterator iter; Node * chosen = *it; mdouble mLen = (*it)->len + dists[chosen->nodes->front()][chosen->nodes->back()]; mint n = (*it)->nodes->size(); for(it;it!=oldGen->end();++it){ mdouble tmp = (*it)->len + dists[(*it)->nodes->front()][(*it)->nodes->back()]; if (tmp < mLen){ mLen = tmp; chosen = *it; } } cout << (int)ceil(mLen) << endl; break; } deleteNodeList(oldGen); oldGen->clear(); delete oldGen; oldGen=newGen; level++; }/**/ for(mint i=0;i<nNodes;i++) delete [] coords[i]; for(mint i=0;i<nNodes;i++) delete [] dists[i]; for(mint i=0;i<nNodes;i++){ for(mint j=0;j<nNodes;j++){ for(mint k=0;k<nNodes;k++){ delete [] conflicts[i][j][k]; } delete [] conflicts[i][j]; } delete [] conflicts[i]; } delete [] dists; delete [] coords; delete [] conflicts; deleteNodeList(oldGen); delete oldGen; // deleteNodeList(newGen); // delete newGen; return 0; }
// the overall motion of ghost void motion(int &xg,int &yg,int x,int y,char &cg,int blackSquare[][28],int &ig,int &v){ int p=xg-44;int q=yg-50; //v is used to make ghost follow pac only for particular time interval if(((ab((x-xg))+ab((y-yg)))<200)&&(v<=3)){v++; if(cg=='w'){if((p%20==0)&&(q%20==0)&&((blackSquare[(q/20)][(p/20)-1]==1)||(blackSquare[(q/20)][(p/20)+1]==1))) {shortestPath(xg,yg,x,y,cg,blackSquare);return;} else{yg=yg-5;return;}}; if(cg=='a'){if((p%20==0)&&(q%20==0)&&((blackSquare[(q/20)-1][(p/20)]==1)||(blackSquare[(q/20)+1][(p/20)]==1))) {shortestPath(xg,yg,x,y,cg,blackSquare);return;} else{{xg=xg-5;return;}};} if(cg=='s'){if((p%20==0)&&(q%20==0)&&((blackSquare[(q/20)][(p/20)-1]==1)||(blackSquare[(q/20)][(p/20)+1]==1))) {shortestPath(xg,yg,x,y,cg,blackSquare);return;} else{yg=yg+5;return;}}; if(cg=='d'){if((p%20==0)&&(q%20==0)&&((blackSquare[(q/20)-1][(p/20)]==1)||(blackSquare[(q/20)+1][(p/20)]==1))) {shortestPath(xg,yg,x,y,cg,blackSquare);return;} else{xg=xg+5;return;}}}; v=0; if(ig%5==1){ if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}}; if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}}; if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}}; if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}}; }; if(ig%5==2){ if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}}; if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}}; if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}}; if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}}; }; if(ig%5==3){ if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}}; if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}}; if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}}; if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}};}; if(ig%5==4){ if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}}; if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}}; if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}}; if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}};}; if(ig%5==0){ if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}}; if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}}; if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}}; if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}};}; }
bool isUnivalTree(TreeNode* root) { if( root == NULL ) return true; int val = root -> val; return possible(root, val); }
void shortestPath(int &xg,int &yg,int x,int y,char &cg,int blackSquare[][28]){ //ghosts finds the shortest path to pac man and follows it if(((x-xg)>0)&&((y-yg)>0)){ if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){xg=xg+5;cg='d';return;}}; if(cg!='w'){ if(possible(xg,yg,cg,'s',blackSquare)){yg=yg+5;cg='s';return;}}; if(cg!='d') {if(possible(xg,yg,cg,'a',blackSquare)){xg=xg-5;cg='a';return;}}; if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){yg=yg-5;cg='w';return;}}; }; if(((x-xg)<0)&&((y-yg)>0)){ if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){xg=xg-5;cg='a';return;}}; if(cg!='w') {if(possible(xg,yg,cg,'s',blackSquare)){yg=yg+5;cg='s';return;}}; if(cg!='s'){ if(possible(xg,yg,cg,'w',blackSquare)){yg=yg-5;cg='w';return;}}; if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){xg=xg+5;cg='d';return;}}; }; if(((x-xg)<0)&&((y-yg)<0)){ if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){xg=xg-5;cg='a';return;}}; if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){yg=yg-5;cg='w';return;}}; if(cg!='a') { if(possible(xg,yg,cg,'d',blackSquare)){xg=xg+5;cg='d';return;}}; if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){yg=yg+5;cg='s';return;}}; }; if(((x-xg)>0)&&((y-yg)<0)){ if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){yg=yg-5;cg='w';return;}}; if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){xg=xg+5;cg='d';return;}}; if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){yg=yg-5;cg='s';return;}}; if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){xg=xg-5;cg='a';return;}}; }; if(((x-xg)==0)&&((y-yg)>0)){ if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){yg=yg+5;cg='s';return;}}; if(cg!='a') {if(possible(xg,yg,cg,'d',blackSquare)){xg=xg+5;cg='d';return;}}; if(cg!='d') { if(possible(xg,yg,cg,'a',blackSquare)){xg=xg-5;cg='a';return;}}; if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){yg=yg-5;cg='w';return;}}; } if(((x-xg)==0)&&((y-yg)<0)){ if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){yg=yg-5;cg='w';return;}}; if(cg!='d') { if(possible(xg,yg,cg,'a',blackSquare)){xg=xg-5;cg='a';return;}}; if(cg!='a') {if(possible(xg,yg,cg,'d',blackSquare)){xg=xg+5;cg='d';return;}}; if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){yg=yg+5;cg='s';return;}}; } if(((y-yg)==0)&&((x-xg)<0)){ if(cg!='d') { if(possible(xg,yg,cg,'a',blackSquare)){xg=xg-5;cg='a';return;}}; if(cg!='s') {if(possible(xg,yg,cg,'w',blackSquare)){yg=yg-5;cg='w';return;}}; if(cg!='w') { if(possible(xg,yg,cg,'s',blackSquare)){yg=yg+5;cg='s';return;}}; if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){xg=xg+5;cg='d';return;}}; }; if(((y-yg)==0)&&((x-xg)>0)){ if(cg!='a') { if(possible(xg,yg,cg,'d',blackSquare)){xg=xg+5;cg='d';return;}}; if(cg!='w') { if(possible(xg,yg,cg,'s',blackSquare)){yg=yg+5;cg='s';return;}}; if(cg!='s') { if(possible(xg,yg,cg,'w',blackSquare)){yg=yg-5;cg='w';return;};} if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){xg=xg-5;cg='a';return;}}; };}
bool possible(TreeNode* root, int val){ if( root == NULL ) return true; if( root -> val != val ) return false; return possible(root -> left, val) & possible(root -> right, val); }