vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { dict.insert(end); pre.clear(); len.clear(); queue<string> q; q.push(start); len[start] = 0; while(!q.empty()) { string s = q.front(), t = s; int d = len[s]; q.pop(); if (t == end) break; for(int i = 0; i < s.length(); i++) { int k = s[i]-'a'; for(int j = 0; j < 26; j++) { if( j != k) { s[i] = 'a'+j; if (dict.count(s)>0) { if (len.count(s) == 0) { len[s] = d+1; pre[s].push_back(t); q.push(s); } else if(len[s] == d+1) { pre[s].push_back(t); } } } } s[i] = 'a'+k; } } ans.clear(); tmp.assign(1, end); build(start, end); return ans; }
/* * Recursivly explores the game board and add any solutions to validWords collection. */ void Boggle::explore(string word, int x, int y, unordered_set<int>& visited){ //Add letter contained in this cell to word. word.push_back(board.get(y, x)); //If our word is a valid prefix it is worth to continue, otherwise we return. if(lexicon.containsPrefix(word)){ //If word is acceptable we add it to validWords collection. if(word.length() >= MIN_WORD_LENGTH && !alreadyFound(word) && lexicon.contains(word)){ cpuScore += scoreFor(word); cpuWords.insert(word); } //Convert coordinates to index in order to more easily store them as visited. int currentIndex = x + y * BOARD_WIDTH; visited.insert(currentIndex); //Check all possible neighbours, exploring those who are withing bounds. for(int ny = y - 1; ny <= y + 1; ny++){ for(int nx = x - 1; nx <= x + 1; nx++){ if(board.inBounds(ny, nx)){ if(visited.count(nx + ny * BOARD_WIDTH) == 0){ explore(word, nx, ny, visited); } } } } //Erase cell from visited collection as we are backtracking. visited.erase(currentIndex); } return; }
int ladderLength(string start, string end, unordered_set<string> &dict) { deque<string> pop_from; deque<string> push_to; int total_dist = 1; // init pop_from.push_back(start); while(!pop_from.empty()) { while (!pop_from.empty()) { string& orig = pop_from.front(); string node = pop_from.front(); int dist = 0; for (int i = 0; i < node.length() && dist < 2; i++) { if (node[i] != end[i]) { ++dist; } } if (dist <= 1) { return total_dist + dist; } for (int i = 0; i < orig.length(); ++i) { node = orig; for (char j = 'a'; j <= 'z'; ++j) { node[i] = j; if (dict.count(node) > 0) { push_to.push_back(node); dict.erase(node); } } } pop_from.pop_front(); } pop_from.swap(push_to); ++total_dist; } return 0; }
/** Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ int move(string direction) { if (game_over) { return -1; } auto next = snake.back(); switch(direction[0]) { case 'U': --next.first; break; case 'D': ++next.first; break; case 'R': ++next.second; break; case 'L': --next.second; break; default: break; } if (next.first < 0 || next.first >= height || next.second < 0 || next.second >= width) { game_over = true; return -1; } if (fidx < food.size() && food[fidx].first == next.first && food[fidx].second == next.second) { ++fidx; } else { board.erase(snake[0]); snake.erase(snake.begin()); } if (board.count(next)) { game_over = true; return -1; } snake.push_back(next); board.insert(next); return snake.size() - 1; }
bool wordBreak(string s, unordered_set<string> &dict) { int len = (int)s.size(); int *st = new int[len+1]; /* printf("%s\n", s.c_str()); for (unordered_set<string>::iterator usit = dict.begin(); usit != dict.end(); ++usit) { printf("%s\n", usit->c_str()); } */ memset(st, 0, sizeof(int) * (len+1)); st[0] = 1; unordered_set<string>::iterator usit = dict.begin(); for (int i = 1; i <= len; ++i) { for (usit = dict.begin(); usit != dict.end(); ++usit) { int cur_len = (int)usit->size(); int dis = i - cur_len; if (dis < 0) continue; //too short, impossible const char *start = s.c_str() + dis; if (st[dis] == 1 && strncmp(start, usit->c_str(), cur_len) == 0) { st[i] = 1; break; } } } bool res = st[len] == 1; delete[] st; return res; }
void WordBreak(string s, string curStr, unordered_set<string> & dict, unordered_set<string>& cache, vector<string> & res) { if (s.length() == 0) { res.push_back(curStr); return; } else { for (int i = 1; i <= s.length(); i++) { string str = s.substr(0, i); if (dict.count(str) != 0 && cache.count(s.substr(i)) == 0) { int size = res.size(); WordBreak(s.substr(i), curStr.length() > 0 ? curStr + " " + str : str, dict, cache, res); if (res.size() == size) { cache.insert(s.substr(i)); } } } } }
vector<string> wordBreak(string s, unordered_set<string>& wordDict) { int len = s.size(); vector<bool> canBreak(len+1); vector<int> idxes; idxes.push_back(0); canBreak[0] = true; for (int i=1; i<=len; ++i) for (int j=i-1; j>=0; --j) if (canBreak[j] && wordDict.count(s.substr(j, i-j))) { canBreak[i] = true; idxes.push_back(i); break; } if (!canBreak[len]) return {}; int idxLen = idxes.size(); vector<vector<string>> breaks(idxLen+1); breaks[0].push_back({""}); string word; int idx1, idx2; for (int i=1; i<=idxLen; ++i) { for (int j=0; j<i; ++j) { idx1 = idxes[j]; idx2 = idxes[i]; word = s.substr(idx1, idx2-idx1); if (wordDict.count(word)) for (auto &w : breaks[j]) breaks[i].push_back(w + word + ' '); } } vector<string> res; for (auto &w : breaks[idxLen]) { res.push_back(w.substr(0, w.size()-1)); } return res; }
int main() { scanf("%d",&n); for (int i = 0; i < n; ++ i) { scanf("%d",&s[i]); } scanf("%d",&m); for (int i = 0; i < m; ++ i) { int v; scanf("%d",&v); q.insert(v); } bool isfirst = true; for (int i = 0; i < n; ++ i) { if (q.find(s[i]) != q.end()) { if (!isfirst) { printf(" "); } printf("%d", s[i]); isfirst = false; } } puts(""); return 0; }
void PrintLongestWord(string word[], int n){ for(int i=0; i<n; ++i) { //hash.insert((char*)&word[i][0]); hashset.insert(word[i]); } sort(word, word+n, cmp); for(int i=0; i<n; ++i){ if(MakeOfWords(word[i], word[i].length())){ cout<<"Longest Word: "<<word[i]<<endl; return; } } }
bool wordBreak(string s, unordered_set<string> &dict) { if( s.length() == 0 ){ return true; } bool flag[1000]; memset(flag, false,sizeof(flag)); flag[0] = true; for( int i = 0 ; i < s.length(); i++){ for( int j = 0; j <= i; j++){ if( flag[j] && ( dict.find( s.substr(j,i +1 - j)) != dict.end())){ flag[i + 1] = true; } } } return flag[s.length()]; }
bool wordBreak(string s, unordered_set<string>& wordDict) { int n = s.size(); if (n == 0) return false; vector<bool> dp(n + 1, false); // dp[i+1] : 0~i is true dp[0] = true; for (int i = 0; i < n; i++) { for (int j = i; j >= 0; j--) { if (dp[j] && wordDict.count(s.substr(j, i-j+1)) > 0) { dp[i+1] = true; break; // no need for further steps } } } return dp[n]; }
int bfs(string start, string end, unordered_set<string> &dict, unordered_map<string,int> &level) { int n = dict.size(); queue<string> q; q.push(start); int dist = 0; queue<string> q1; level[start] = 0; while(q.size() || q1.size()) { if (q.size() == 0) { dist++; q = q1; q1 = queue<string>(); } string str = q.front(); q.pop(); if (str == end) return dist; for ( int i = 0; i < str.size(); i++) for ( char c = 'a'; c <= 'z'; c++) { if (str[i] == c) continue; string str1 = str; str1[i] = c; if ( (dict.count(str1) || str1 == end ) && !level.count(str1)) { q1.push(str1); level[str1] = dist + 1; } } } return 0; }
vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string> > result; map<string,Node*> nodes; Node nStart; nStart.name = start; Node nEnd; nEnd.name = end; nodes[start] = &nStart; for (std::unordered_set<string>::iterator i = dict.begin(); i != dict.end(); ++i) { Node* tmp = new Node(); tmp->name = *i; nodes[*i] = tmp; } nodes[end] = &nEnd; dict.insert(end); dict.insert(start); nodes[start]->val = 1; innerSearch(nodes[start],dict,nodes); int minValue = nodes[start]->val == INT_MAX ? 0 : nodes[end]->val; if ( minValue > 0 ) { //printf("size:%ld\n", nodes[start]->nexts.size()); vector<string> parent; parent.push_back(start); innerCreate(nodes[start],1,minValue,parent,result); } return result; }
void _gameData::addEnemyMaskPlus1(unordered_set<pos>& poses, pos rc){ float sqrtfar2=sqrt(ar2); int maskcnt=0; for(int row=-4; row<=4; row++){ for(int col=-4; col<=4; col++){ float oedist=sqrt(euclideanDist2(0,0,row,col,rows,cols)); //if(sqrtfar2+1<oedist and oedist<=sqrtfar2+2){ if(oedist<=sqrtfar2+2){ poses.insert(pos(wrap(rc.row+row, rows), wrap(rc.col+col,cols))); maskcnt++; } } } //LOG("added " << maskcnt << " mask tiles"); };
bool wordBreak(string s, unordered_set<string> &dict) { if (s.empty()) return false; int N = s.size(); vector<bool> dp(N + 1, false); dp[0] = true; for (int j = 1; j <= N; j++) { for (int i = 0; i < j; i++) { if (dict.count(s.substr(i, j - i)) && dp[i]) { dp[j] = true; break; } } } return dp[N]; }
void buildMap(const unordered_set<string>& dict) { vdict.clear(); unordered_map<string, int> unmap; for (auto iter = dict.begin(); iter != dict.end(); iter++) { unmap[*iter] = vdict.size(); vdict.push_back(*iter); } map.clear(); map.resize(vdict.size()); for (size_t i = 0; i < vdict.size(); i++) { string word = vdict[i]; for (size_t j = 0; j < word.size(); j++) { for (char c = 'a'; c <= 'z'; c++) { if (c == vdict[i][j]) continue; word[j] = c; if (unmap.count(word)) { map[i].push_back(unmap[word]); } word[j] = vdict[i][j]; } } } }
void dfs(string s, int index, vector<string> &result, string &eachResult, vector<bool> &possible, unordered_set<string> &dict) { if (index == s.size()) { eachResult.resize(eachResult.size() - 1); result.push_back(eachResult); return; } for (int i = 1; i <= (int)s.size() - index; i++) { string tmp = s.substr(index, i); if (dict.find(tmp) != dict.end() && possible[index + i]) { string origin = eachResult; eachResult.append(tmp).append(" "); int beforeDFS = (int)result.size(); dfs(s, index + i, result, eachResult, possible, dict); if (result.size() == beforeDFS) { possible[index + i] = false; } eachResult = origin; } } return; }
/* remove overlaps that are duplicated in vector left, and spot sequences that should be remove in next pass because they reached their best overlap with a duplicated sequence */ vector<edge> removeNotSinglesInLeft(const vector<edge>& vect, unordered_set<string>& seqsToRemoveInPref, unordered_set<string>& seqsToRemoveInSuff){ vector<edge> vectResult; uint i(0); bool remove(false); while (i < vect.size()){ if (i == 0){ if (vect[i].sequence != vect[i+1].sequence){ vectResult.push_back(vect[i]); } else { remove = true; } } else if (i == vect.size()-1){ if (vect[i].sequence != vect[i-1].sequence){ vectResult.push_back(vect[i]); } else { remove = true; } } else { if (vect[i].sequence != vect[i+1].sequence and vect[i].sequence != vect[i-1].sequence){ vectResult.push_back(vect[i]); } else { remove = true; } } if (remove == true){ if (vect[i].canonical == true){ seqsToRemoveInSuff.insert(vect[i].sequence); } else { seqsToRemoveInPref.insert(vect[i].sequence); } } ++i; remove = false; } return vectResult; }
void helper(string beginWord, string endWord, unordered_set<string> wordList, int& minLength, vector<string>& ladder, vector<vector<string>>& res) { if (beginWord == endWord || isIntermediate(beginWord, endWord)) { if (isIntermediate(beginWord, endWord)) { ladder.push_back(endWord); } if (ladder.size() == minLength) { res.push_back(ladder); } else if (ladder.size() < minLength) { res.clear(); res.push_back(ladder); minLength = ladder.size(); } return; } for (auto it = wordList.begin(); it != wordList.end(); ++it) { if (isIntermediate(beginWord, *it)) { ladder.push_back(*it); unordered_set<string> newWordList = wordList; newWordList.erase(newWordList.find(*it)); helper(*it, endWord, newWordList, minLength, ladder, res); } } return; }
bool StringProduction(string src, string dst, unordered_set<string> dico, list<string>* prod_seq) { if (dico.find(src) == dico.end() || dico.find(dst) == dico.end()) return false; map<string, string> parents; unordered_set<string> processed; queue<string> discovered; //init the bfs discovered.push(src); parents[src] = ""; while (!discovered.empty()) { string current = discovered.front();discovered.pop(); processed.insert(current); list<string> neighbours = GetNeighbours(current, dico); for (string s : neighbours) { if (processed.find(s) == processed.end()) { parents[s] = current; discovered.push(s); } } } if (processed.find(dst) == processed.end()) return false; while (dst!="") { prod_seq->push_front(dst); dst = parents[dst]; } return true; }
int ladderLength(string start, string end, unordered_set<string> &dict) { int length = 2, count = 1, neighb = 0; unordered_set<string> visited; queue<string> level; level.push(start); visited.insert(start); while(!level.empty()) { string curr = level.front(); level.pop(); --count; for(int i = 0; i < curr.size(); ++i) { for(int j = 0; j < 26; ++j) { string next = curr; next[i] = 'a' + j; if(next == end) return length; if(dict.find(next) != dict.end() && visited.find(next) == visited.end()) { ++neighb; level.push(next); visited.insert(next); } } } if(count == 0) // new level starts { ++length; count = neighb; neighb = 0; } } return 0; }
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) { queue<string> q; int s = beginWord.size(); int r = 1; q.push(beginWord); while (!q.empty()) { cout << " -+-+-+-+-+-+-+ " << endl; int num = q.size(); bool found = false; for (int i = 0; i < num; i++) { string tmp = q.front(); cout << "tmp:" << tmp << endl; q.pop(); for (int k = 0; k != s; k++) { char c = tmp[k]; for (int l = 0; l < 26; l++) { tmp[k] = 'a'+l; unordered_set<string>::iterator it; it = wordList.find(tmp); if (it != wordList.end()) { if (*it == endWord) { cout << *it << ","; return r+1; } else { q.push(tmp); wordList.erase(it); } } } tmp[k] = c; } } r++; } return 0; }
int ladderLength(string start, string end, unordered_set<string> &dict) { dict.insert(end); queue<pair<string,int>> q; q.push(make_pair(start,1)); while(!q.empty()) { string s = q.front().first; int len = q.front().second; if(s==end) return len; q.pop(); vector<string> neighbors = findNeighbors(s, dict); for(int i=0; i<neighbors.size(); i++) q.push(make_pair(neighbors[i],len+1)); } return 0; }
vector <string> get_Next_Level(string & word,const string &end ,unordered_set <string> &dict) { vector <string> result; for (int i = 0; i < word.size(); i++) { for (char c = 'a'; c <= 'z'; c++) { if (c == word[i])continue; swap(c, word[i]); if ((dict.count(word) > 0 || word == end)&& visted.find(word) == visted.end()){ result.push_back(word); visted.insert(make_pair(word, true)); } swap(c, word[i]); } } return result; }
CharacterVector tag(CharacterVector& x) { const char *const test_lines = x[0]; vector<pair<string, string> > res; taggerseg.tag(test_lines, res); //unsigned int it; vector<string> m; m.reserve(res.size()); vector<string> atb; atb.reserve(res.size()); if(stopWords.size()>0){ for (vector<pair<string, string> >::iterator it = res.begin(); it != res.end(); it++) { if (stopWords.end() == stopWords.find((*it).first)) { m.push_back((*it).first); atb.push_back((*it).second); } } } else { for (vector<pair<string, string> >::iterator it = res.begin(); it != res.end(); it++) { m.push_back((*it).first); atb.push_back((*it).second); } } CharacterVector m_cv(m.begin(),m.end()); CharacterVector atb_cv(atb.begin(),atb.end()); m_cv.attr("names") = atb_cv; return wrap(m_cv); }
bool wordBreak(string s, unordered_set<string> &dict) { //unordered_map<char, int> keytable; int keytable[60] = {0}; int len; unordered_set<string>::iterator it; int i; for (it = dict.begin(); it != dict.end(); it++) { len = it->size(); for (i = 0; i < len; i++) { if (keytable[(it->at(i))-'a'] == 0) keytable[it->at(i)-'a'] = 1; } } len = s.size(); for (i = 0; i < len; i++) { if (keytable[s[i]-'a'] == 0) { return false; } } if (judge(s,dict,0)) { return true; } return false; }
//跟word break区别:用prev记录下哪些位置可以分词出来 vector<string> wordBreak(string s, unordered_set<string> &dict) { // 长度为n 的字符串有n+1 个隔板 vector<bool> f(s.length() + 1, false); // prev[i][j] 为true,表示s[j, i) 是一个合法单词,可以从j 处切开 // 第一行未用 vector<vector<bool> > prev(s.length() + 1, vector<bool>(s.length())); /*DP, 设状态为f(i),表示字符串s从第0个到第i个字符之前那个位置是否可以分词, 状态转移方程为: f(i) = any_of(f(j)&&s[j, i) 在 dict 中); 0 <= j < i */ f[0] = true; // 空字符串 for (size_t i = 1; i <= s.length(); ++i) { //从第一个分隔到尾后元素 for (int j = i - 1; j >= 0; --j) { if (f[j] && dict.find(s.substr(j, i - j)) != dict.end()) { f[i] = true; //发现第i个位置前能分词仍然要试探其他的位置 prev[i][j] = true; //从j到i前的位置是一个dict中的单词 } } } vector<string> result; vector<string> path; gen_path(s, prev, s.length(), path, result); return result; }
/* * The function returns the vector of local access nodes for the specific node (iFrom) given * a set of access nodes. A neighborhood of the node is also returned via output parameter. * For an access node, a set of local access nodes and its neighborhood is also returned. * * Local access nodes for a node x is the smallest set of access nodes such that in * order to reach the remaining of the graph, we must go through at least one of these nodes * * A neighborhood are all nodes reachable NOT via access nodes. Thus the starting node as well * as local access nodes are part of this neighborhood. */ unordered_set<int> fGetLANsForNode(UgGraph *iGraph, int iFrom, unordered_set<int> &iANs, unordered_set<int> *oNeighborhood) { unordered_set<int> lLANs; //we need to have a valid neighborhood set for fSearchNeighborhood unordered_set<int> *lNeighborhood; if (oNeighborhood == NULL) { lNeighborhood = new unordered_set<int>(); } else { oNeighborhood->clear(); lNeighborhood = oNeighborhood; } //we want to find access nodes also for access nodes //thus erase iFrom from the set of ANs as the search would stop immediately bool lErased = false; if (iANs.count(iFrom) != 0) { iANs.erase(iFrom); lErased = true; } //recursive searching in the neighborhood - up to access nodes fSearchNeighborhood(iGraph, iFrom, iANs, &lLANs, lNeighborhood); //put iFrom back to the set of access nodes if (lErased) { iANs.insert(iFrom); } if (oNeighborhood == NULL) { delete lNeighborhood; } return lLANs; }
Status _checkNoExtraFields(const BSONObj& cmdObj, const StringData& cmdName, const unordered_set<std::string>& validFieldNames) { // Iterate through all fields in command object and make sure there are no unexpected // ones. for (BSONObjIterator iter(cmdObj); iter.more(); iter.next()) { StringData fieldName = (*iter).fieldNameStringData(); if (!validFieldNames.count(fieldName.toString())) { return Status(ErrorCodes::BadValue, mongoutils::str::stream() << "\"" << fieldName << "\" is not " "a valid argument to " << cmdName); } } return Status::OK(); }
int ladderLength(string start, string end, unordered_set<string> &dict) { // Start typing your C/C++ solution below // DO NOT write int main() function unordered_set<string>::iterator it = dict.begin(); vector<string> dict_array; vector<bool> status; dict_array.push_back(start); for (; it!= dict.end(); ++it) { if(!start.compare(*it) || !end.compare(*it)) { continue; } dict_array.push_back(*it); } dict_array.push_back(end); if (start.length() < 1 || start.length() < 1 || dict.size()<1 || !start.compare(end)) { return 0; } int len = start.length(); int count = dict_array.size(); bool* p_m = new bool[count*count]; bool** pp_m = (bool**)malloc(count*sizeof(bool*)); for (int i=0; i< count; ++i) { pp_m[i] = p_m + count*i; } vector<vector<int> > vv_m ; if (!transformer_matrix(pp_m, vv_m, start, end, dict_array)) { return 0; } unordered_set<int> sequence; sequence.insert(0); int result = rec_transformer(pp_m, vv_m,sequence, 0, count-1); free(pp_m); delete[] p_m; return result; }