pair<char, char> firstFirstUnMatchChars(string s, string t, unordered_set<char> &letters) { int len = min(s.size(), t.size()); int i = 0; while (i < len && s[i] == t[i]) { letters.insert(s[i++]); } if (i == len) { // s is a prefix of t, or vice versa if (s.size() > len) { while (i < s.size()) { letters.insert(s[i++]); } } else if (t.size() > len) { while (i < t.size()) { letters.insert(t[i++]); } } return make_pair('A', 'A'); } // neither s nor t is fully traversed int iCopy = i; if (s.size() > i) { while (i < s.size()) { letters.insert(s[i++]); } } i = iCopy; if (t.size() > i) { while (i < t.size()) { letters.insert(t[i++]); } } i = iCopy; return make_pair(s[i], t[i]); }
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { for(int i = 0; i < words.size(); i++) { dict.insert(words[i]); for(int j = 1; j <= words[i].length(); j++) { prefix.insert(words[i].substr(0, j)); } } vector<string> ans; m = board.size(); if(m == 0) return ans; n = board.front().size(); vector<vector<bool> > visited(m, vector<bool>(n, false)); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { string candidate = ""; candidate += board[i][j]; visited[i][j] = true; dfs(board, i, j, candidate, visited, ans); visited[i][j] = false; } } sort(ans.begin(), ans.end()); ans.resize(unique(ans.begin(), ans.end()) - ans.begin()); return ans; }
bool hasCycleUtil(int parent,Vertex *curr,unordered_set<int> &visited, unordered_set<int> &recurStack) { visited.insert(curr->key); recurStack.insert(curr->key); cout<<"visiting "<<curr->key<<endl; for(auto cn:curr->_neighbours) { if(cn==parent) continue; if(recurStack.find(cn) != recurStack.end()) { cout<<"already visited "<<cn<<endl; return true; } if(visited.find(cn) == visited.end()) { Vertex *neighbour = _graph[cn]; if(hasCycleUtil(curr->key,neighbour,visited,recurStack)) { return true; } } } recurStack.erase(curr->key); cout<<"removing from stack"<<curr->key<<endl; return false; }
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { wordDict.insert(beginWord); wordDict.insert(endWord); unordered_map<string, int> depth; unordered_map<string, bool> accessed; for (string w: wordDict) { depth[w] = INT_MAX; accessed[w] = false; } depth[beginWord] = 1; queue<string> q({beginWord}); while (!q.empty()) { string cur = q.front(); q.pop(); if (accessed[cur]) { continue; } auto next_names = nextNames(cur, wordDict); for (string name: next_names) { if (!accessed[name]) { depth[name] = min(depth[name], depth[cur] + 1); q.push(name); } } accessed[cur] = true; } return depth[endWord]%INT_MAX; }
void MMSBModel::SampleMinibatch(unordered_set<VIndex>& vertex_batch, set<pair<VIndex, VIndex> >& link_batch, const Count batch_size) { vertex_batch.clear(); for (int i = 0; i < batch_size; ++i) { while (true) { // randomly sample a vertex from the map<.,.> vertices_ auto it = vertices_.begin(); uint32 nstep = Context::randUInt64() % vertices_.size(); std::advance(it, nstep); VIndex v = it->first; if (vertex_batch.find(v) == vertex_batch.end()) { // to avoid duplicate vertex_batch.insert(v); break; } } } CollectLinks(link_batch, vertex_batch); for (const auto& link : link_batch) { vertex_batch.insert(link.first); vertex_batch.insert(link.second); } //LOG(INFO) // << "iter " << iter_ << ", " // << vertex_batch.size() << " vertexes, " // << link_batch.size() << " links"; }
bool findOrderIHelper(int node,unordered_map<int,vector<int> >& graph, unordered_set<int>& visited,unordered_set<int>& tmpVisited,vector<int>& sortedOrder) { if(tmpVisited.find(node) != tmpVisited.end()) return false; if(visited.find(node) == visited.end()) { tmpVisited.insert(node); for(int i = 0; i < graph[node].size(); i++) { if(findOrderIHelper(graph[node][i],graph,visited,tmpVisited,sortedOrder) == false) { return false; } } visited.insert(node); tmpVisited.erase(node); sortedOrder.push_back(node); } return true; }
void process_incoming(multiset<order, IN> &incoming, multiset<order, WAIT> &waiting, int seq) { int size, price; cin >> size >> price; auto top_waiting = waiting.begin(); for ( ; size && top_waiting != waiting.end(); ++top_waiting) { if (can_trade(price, top_waiting, waiting)) { int trade_price = top_waiting->price; int trade_size = min(top_waiting->size, size); cout << "TRADE " << trade_size << " " << trade_price << '\n'; size -= trade_size; top_waiting->size -= trade_size; price2size[trade_price] -= trade_size; if (!top_waiting->size) gone.insert(top_waiting->seq); else break; } else break; } waiting.erase(waiting.begin(), top_waiting); if (size) { auto p2s_pit = price2size.insert({price, size}); if (!p2s_pit.second) p2s_pit.first->second += size; auto it = incoming.insert(incoming.begin(), {price, seq, size}); add_seq2iter_map(seq, it, &incoming); } else gone.insert(seq); }
// _____________________________________________________________________________ void QueryPlanner::getVarTripleMap( const ParsedQuery& pq, unordered_map<string, vector<SparqlTriple>>& varToTrip, unordered_set<string>& contextVars) const { for (auto& t: pq._whereClauseTriples) { if (isVariable(t._s)) { varToTrip[t._s].push_back(t); } if (isVariable(t._p)) { varToTrip[t._p].push_back(t); } if (isVariable(t._o)) { varToTrip[t._o].push_back(t); } if (t._p == IN_CONTEXT_RELATION) { if (isVariable(t._s) || isWords(t._o)) { contextVars.insert(t._s); } if (isVariable(t._o) || isWords(t._s)) { contextVars.insert(t._o); } } } }
// Utility function to store prime factors of a number void findPrimefactors(unordered_set<int> &s, int n) { // Print the number of 2s that divide n while (n%2 == 0) { s.insert(2); n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, print i and divide n while (n%i == 0) { s.insert(i); n = n/i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) s.insert(n); }
void insertEdge(char start, char end, int weight){ vertices.insert(start); vertices.insert(end); string string1, string2; if (edges.find(string1.append(1, start).append(1, end)) == edges.end() && edges.find(string2.append(1, end).append(1, start)) == edges.end()) edges.insert(make_pair(string1, weight)); }
void gen_primes(long long n, unordered_set<long long> &primes){ if(n>= 2){ primes.insert(2); for(long long i = 3; i <=n; i += 2){ if(is_prime(i)) primes.insert(i); } } }
// create a queue to track the distance of each word in wordList from beginWord void bfs(unordered_map<string, vector<string>> &transMap, unordered_map<string, int> &distMap, string &beginWord, string &endWord, unordered_set<string> &wordList) { queue<string> q; q.push(beginWord); // make sure beginWord and endWord is in wordList wordList.insert(beginWord); wordList.insert(endWord); // start from the beginWord distMap[beginWord] = 0; while (!q.empty()) { int count = q.size(); bool isEndFound = false; // flag if found the endWord for (int i = 0; i < count; i++) // bfs by level { string word = q.front(); q.pop(); vector<string> transList = transform(word, wordList); vector<string> *curList = &transMap[word]; for (int j = 0; j < transList.size(); j++) { string str(transList[j]); // update possible transformations for each word in transList curList->push_back(str); // update distance for each word in transList if it is not in distMap if (distMap.find(str) == distMap.end()) { distMap[str] = distMap[word] + 1; if (str == endWord) { // set flag isEndFound = true; } else { q.push(str); } } } if (isEndFound) { // quit current level, go to next level break; } } } return; }
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string>> ret; dict.insert(start); dict.insert(end); build(dict); bfs(ID[start] , ID[end]); vector<int> temp; gen(ID[start] , ID[end] , ret , temp); return ret; }
/**** start = "hit" **** end = "cog" ******dict = ["hot", "dot", "dog", "lot", "log"] */ void splitdata(string temp, unordered_set<string>& dict) { int pos = -1; while ((pos = temp.find(",")) != -1) { string tempsub = temp.substr(0,pos); temp = temp.substr(pos + 1, temp.length() - pos - 1); dict.insert(tempsub); } dict.insert(temp); }
/** * @param start, a string * @param end, a string * @param dict, a set of string * @return a list of lists of string */ vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) { ans.clear(); bt.clear(); dict.insert(start); dict.insert(end); vector<vector<string> > a(2); string s1, s2; int f, nf; a[0].push_back(start); f = 1; nf = !f; int i, j, k, n, len; char ch; while (true) { a[f].clear(); n = a[nf].size(); for (i = 0; i < n; ++i) { dict.erase(a[nf][i]); } for (i = 0; i < n; ++i) { s1 = s2 = a[nf][i]; len = s1.length(); for (j = 0; j < len; ++j) { ch = s1[j]; for (k = 0; k < 26; ++k) { if (ch == 'a' + k) { continue; } s1[j] = 'a' + k; if (dict.find(s1) == dict.end()) { continue; } a[f].push_back(s1); bt[s1].insert(s2); } s1[j] = ch; } } if (a[f].empty() || bt.find(end) != bt.end()) { break; } f = !f; nf = !f; } if (bt.find(end) == bt.end()) { return ans; } res.clear(); backTrace(end); return ans; }
void dfs(UndirectedGraphNode* node, unordered_set<UndirectedGraphNode*>& visited, vector<int>& result) { visited.insert(node); result.push_back(node->label); for (UndirectedGraphNode* child : node->neighbors) { if (visited.find(child) != visited.end()) { continue; } visited.insert(child); dfs(child, visited, result); } }
void SESELoop::buildLoopMemberSet(BasicBlock& backEdgeDestination, const unordered_multimap<BasicBlock*, BasicBlock*>& destToOrigin, unordered_set<BasicBlock*>& members, unordered_set<BasicBlock*>& entries, unordered_set<BasicBlock*>& exits) { // Build paths to back-edge start nodes. unordered_set<BasicBlock*> sinkNodeSet; auto range = destToOrigin.equal_range(&backEdgeDestination); for (auto iter = range.first; iter != range.second; iter++) { sinkNodeSet.insert(iter->second); } auto pathsToBackNodes = findPathsToSinkNodes(&backEdgeDestination, sinkNodeSet); // Build initial loop membership set for (const auto& path : pathsToBackNodes) { members.insert(path.begin(), path.end()); } // The path-to-sink-nodes algorithm won't follow back edges. Because of that, if the cycle contains a // sub-cycle, we need to add its member nodes. This is probably handled by the loop membership refinement // step from the "No More Gotos" paper, but as noted below, we don't use that step. unordered_set<BasicBlock*> newMembers; for (BasicBlock* bb : members) { auto range = loopMembers.equal_range(bb); for (auto iter = range.first; iter != range.second; iter++) { newMembers.insert(iter->second); } } members.insert(newMembers.begin(), newMembers.end()); for (BasicBlock* member : members) { loopMembers.insert({&backEdgeDestination, member}); for (BasicBlock* pred : predecessors(member)) { if (members.count(pred) == 0) { entries.insert(member); } } for (BasicBlock* succ : successors(member)) { if (members.count(succ) == 0) { exits.insert(succ); } } } }
vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) { unordered_set<string> qStr[2]; //we should not erase the word when it being inserted to the qStr, because it may turn up twice or more times at the same level. Instead, we should erase the whole level of qStr at the same time. k = 0; qStr[k % 2].insert(start); found = false; dict.insert(start); dict.insert(end); dict.erase(dict.find(start)); while(!qStr[k % 2].empty()) { unordered_set<string>::iterator ite = qStr[k % 2].begin(); string str = *ite; qStr[k % 2].erase(ite); if(str == end) { found = true; continue; } if(!found) { for(int i = 0; i < str.length(); i++) { string tmp = str; for(int j = 0; j < 26; j++) { tmp[i] = 'a' + j; if(inDict(tmp, dict)) { childToParent[tmp].push_back(str); qStr[(k + 1) % 2].insert(tmp); } } } } if(qStr[k % 2].empty() && !found) { k++; //erase the whole level from dict for(unordered_set<string>::iterator ite = qStr[k % 2].begin(); ite != qStr[k % 2].end(); ite++) { dict.erase(dict.find(*ite)); } } } findPath(end, start); return result; }
void genFac() { vec[0] = 0; vec[1] = 1; facSet.insert(vec[0]); facSet.insert(vec[1]); for (int i = 2; i < 1002; ++i) { vec[i] = vec[i-1] + vec[i-2]; facSet.insert(vec[i]); } }
int main() { int n; bool blank = false; while(cin >> n && n) { num=0; if(blank) cout << endl; blank=true; configs.clear(); corpus.clear(); in_stack.clear(); ssc_stack.clear(); memset(matr,0,sizeof matr); memset(dfs_num,-1,sizeof dfs_num); memset(dfs_low,-1,sizeof dfs_low); char c1,c2,c3,c4,c5,c6; for(int i =0; i < n; ++i) { cin >> c1 >> c2 >> c3 >> c4 >> c5 >> c6; if(c1 != c6)matr[c6-'A'][c1-'A'] = 1; if(c2 != c6)matr[c6-'A'][c2-'A'] = 1; if(c3 != c6)matr[c6-'A'][c3-'A'] = 1; if(c4 != c6)matr[c6-'A'][c4-'A'] = 1; if(c5 != c6)matr[c6-'A'][c5-'A'] = 1; corpus.insert(c1-'A'); corpus.insert(c2-'A'); corpus.insert(c3-'A'); corpus.insert(c4-'A'); corpus.insert(c5-'A'); corpus.insert(c6-'A'); } for(const auto& x : corpus) { if(dfs_num[x] == -1) tarjan_ssc(x); } sort(configs.begin(),configs.end()); for(int i =0 ; i < configs.size(); ++i) { cout << configs[i][0]; for(int q =1; q < configs[i].length(); ++q) { cout << " " << configs[i][q]; } cout << endl; } } return 0; }
int ladderLength(string start, string end, unordered_set<string>& dict) { dict.insert(start); dict.insert(end); vector<vector<string> > adj; vector<string> item; int i = 0; unordered_map<string, int> index; for(unordered_set<string>::iterator iter = dict.begin(); iter != dict.end(); iter++, i++) { string str = *iter; index[str] = i; item.clear(); for(int j = 0; j < str.length(); j++) { for(char a = 'a'; a <= 'z'; a++) { str[j] = a; if(str != *iter && dict.count(str) != 0) item.push_back(str); } str = *iter; } adj.push_back(item); } int path_len = 0, result = 0; list<string> queue; queue.push_back(start); unordered_set<string> visited; visited.insert(start); string tail = start; while(!queue.empty()) { string curr = queue.front(); queue.pop_front(); if(curr == end) { result = path_len+1; break; } for(auto &next : adj[index[curr]]) { if(visited.count(next) == 0) { visited.insert(next); queue.push_back(next); } } if(curr == tail) { path_len++; if(!queue.empty()) tail = queue.back(); } } return result; }
bool dfs(char node, unordered_set<char> &visited, stack<char> &stk, unordered_map<char, unordered_set<char>> &links, unordered_set<char> path) { visited.insert(node); path.insert(node); for(auto nb:links[node]) { if(path.count(nb)==1) return false; if(visited.count(nb)==0) if(!dfs(nb, visited, stk, links, path)) return false; } stk.push(node); return true; }
void values(unordered_set<int> &s,int a,int b) { s.insert(a); s.insert(b); if(s.size()==1) return; int n; std::vector<int> src,dst; std::vector<int>::iterator iti,itj; std::unordered_set<int> v; size_t lastsz=0; while(true){ copy(s.begin(),s.end(),std::back_inserter(src)); for(iti=src.begin();iti!=src.end();++iti){ for(itj=src.begin();itj!=src.end();++itj){ n = *iti-*itj; if(n>0) v.insert(n); } } /* cout<<"差值[原始]:"; std::for_each(v.begin(),v.end(),[](int n){cout<<n<<'\t';}); cout<<endl; */ src.clear(); copy(v.begin(),v.end(),std::back_inserter(dst)); copy(s.begin(),s.end(),std::back_inserter(src)); std::sort(dst.begin(),dst.end()); std::sort(src.begin(),src.end()); //unordered_set difference std::vector<int> tmp(a/(a-b)+1); iti = std::set_difference(dst.begin(),dst.end(),src.begin(),src.end(),tmp.begin()); tmp.resize(iti-tmp.begin()); /* cout<<"差值:"; std::for_each(tmp.begin(),tmp.end(),[](int n){cout<<n<<'\t';}); cout<<endl; */ if(tmp.empty()) break; s.insert(*tmp.begin()); if(s.size()==lastsz) break; lastsz = s.size(); //std::for_each(v.begin(),v.end(),[&s](int n){cout<<n<<'\t';s.insert(n);}); v.clear(); src.clear(); dst.clear(); } }
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string> > paths; unordered_map<string, vector<string> > prevs; prevs[start] = vector<string>(); unordered_map<string, int> dists; dists[start] = 1; queue<string> q; q.push(start); dict.insert(start); dict.insert(end); while(!q.empty()) { string head = q.front(); q.pop(); int dist = dists[head]; for(int i = 0; i < head.length(); i++) { for(int j = 0; j < 26; j++) { if(j + 'a' == head[i]) continue; string temp = head; temp[i] = j + 'a'; if(dict.find(temp) == dict.end()) continue; if(dists.find(temp) == dists.end()) { q.push(temp); dists[temp] = dist + 1; } if(dists[temp] > dist) { if(prevs.find(temp) == prevs.end()) prevs[temp] = vector<string>(); prevs[temp].push_back(head); } } } } if(prevs[end].empty()) return paths; vector<string> path; buildpath(prevs, end, path, paths); return paths; }
void dfs(int v, vector<int>& rslt, unordered_map<int, vector<int>>& adjList, unordered_set<int>& visited, unordered_set<int>& onStack){ if(hasCycle) return ; if(visited.find(v) == visited.end()){ visited.insert(v); onStack.insert(v); for(auto w:adjList[v]) dfs(w, rslt, adjList, visited, onStack); rslt.push_back(v); onStack.erase(v); } else if(onStack.find(v) != onStack.end()) hasCycle = true; }
void getNext(string s, unordered_set<string> &dict, unordered_set<string> &isVisited, unordered_set<string> &nextStrs) { for(int i = 0; i < s.length(); ++i) { string nextStr(s); for(char c = 'a'; c <= 'z'; ++c) { if(c != nextStr[i]) { swap(c, nextStr[i]); if(dict.count(nextStr) && !isVisited.count(nextStr)) { nextStrs.insert(nextStr); isVisited.insert(nextStr); } swap(c, nextStr[i]); } } } }
int ladderLength(string beginWord, string endWord, unordered_set<string> &wordList) { queue<string> q; //将endWord加入wordList wordList.insert(endWord); //从wordList中删除beginWord,避免重复使用词beginWord wordList.erase(beginWord); //BFS helper(beginWord, wordList, q); int ret = 2; while (!q.empty()) { int size = q.size(); //处理这一层的所有节点 for (int i = 0; i < size; i++) { string word = q.front(); q.pop(); //get end word if (word == endWord) return ret; //BFS helper(word, wordList, q); } //节点全部处理完毕,层数加1 ret++; } //没有找到结果,返回0 return 0; }
void find(vector<node>&tree,vector<vector<char>>& board, unordered_set<string>&found,string&buf, int cur, int r, int c, int idx){ node&nd = tree[cur]; if (nd.end){ found.insert(buf); } if (r < 0 || c < 0 || r >= board.size() || c >= board[0].size()||board[r][c]==0) return; char ch=board[r][c]; int cidx = ch-'a'; int next = nd.children[cidx]; if (next==0) return; buf.append(1,ch); int bufSize=buf.size(); board[r][c]=0; find(tree,board,found,buf,next,r+1,c,idx+1); buf.resize(bufSize); find(tree,board,found,buf,next,r-1,c,idx+1); buf.resize(bufSize); find(tree,board,found,buf,next,r,c+1,idx+1); buf.resize(bufSize); find(tree,board,found,buf,next,r,c-1,idx+1); buf.resize(bufSize-1); board[r][c]=ch; }
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) { UnionFind uni; vector<int> res; for (int i=0; i<positions.size(); ++i) { auto pos = positions[i]; int r = pos.first; int c = pos.second; S.insert(positions[i]); uni.add(positions[i]); if (S.find(pair<int,int>(r-1, c)) != S.end()) { uni.merge(pair<int,int>(r-1,c), pair<int,int>(r,c)); } if (S.find(pair<int,int>(r, c+1)) != S.end()) { uni.merge(pair<int,int>(r,c+1), pair<int,int>(r,c)); } if (S.find(pair<int,int>(r+1, c)) != S.end()) { uni.merge(pair<int,int>(r+1,c), pair<int,int>(r,c)); } if (S.find(pair<int,int>(r, c-1)) != S.end()) { uni.merge(pair<int, int>(r, c - 1), pair<int, int>(r, c)); } res.push_back(uni.countSet()); } return res; }
bool dfs(int mask, int left, pfunc P, int depth){ // for (int i = 0 ; i < depth; i++) printf("%d\t",path[i]); printf("\n"); if (mask==0) return true; if (needprejudge) if (bitcount(mask)<=prejudgesize) if (!prejudge(mask,left)) return false; visitedmaskset.insert(mask); if (totcnt > MAXX) return false; if (left ==0) return false; int buf[32]; int n_buf; memset(buf,0,sizeof(buf)); P(buf,n_buf,mask); for (int i = 0 ; i < n_buf; i++) { int todel; todel=path[depth]=buf[i]; int backdegree= degree[todel]; degree[todel] = 0; for (int j = 0 , jm=1; j<map_n; j++, jm<<=1) if ((jm & mask) && graph[todel][j]) degree[j]--; int newmask = 0 ; for (int j = 0 , jm=1; j<map_n; j++, jm<<=1) if (degree[j]) newmask += jm; if (visitedmaskset.count(newmask)==0) { if (dfs(newmask,left-1,P,depth+1)) return true; totcnt++; } degree[todel] = backdegree; for (int j = 0 , jm=1; j<map_n; j++, jm<<=1) if ((jm & mask) && graph[todel][j]) degree[j]++; } }