text
stringlengths
49
983k
// 12:17 - 13:14 #include<iostream> #include<cmath> #include<vector> #include<algorithm> #include<cstdio> #include<cassert> #include<climits> #include<map> #include<queue> #include<set> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define IINF (INT_MAX) #define MAX_SP 15 #define MAX_LEN 60 using namespace std; typedef pair<int,int> ii; struct Data{ int cur,cost; ii info; Data(int cur=IINF,int cost=IINF,ii info=ii(IINF,IINF)):cur(cur),cost(cost),info(info){} bool operator < (const Data& a)const{ return cost > a.cost; } }; int h,w,sp,gp,P; char G[MAX_LEN][MAX_LEN]; /* next_state[index][the number of match] 0 -> empty 1 -> spell[0] 2 -> spell[1] ... */ ii next_state[MAX_SP][MAX_SP][4]; int mincost[MAX_LEN*MAX_LEN][MAX_SP][MAX_SP]; string spell[MAX_SP]; int dx[] = {+0,+1,+0,-1}; int dy[] = {-1,+0,+1,+0}; char dc[] = {'U','R','D','L'}; ii getValue(string s){ rep(i,P+1){ int cur = 0; rep(j,spell[i].size()){ if(s[cur] != spell[i][j]){ break; } cur++; if(cur >= s.size()){ return ii(i,j+1); } } } return ii(0,0); } void INIT(){ rep(i,MAX_SP)rep(j,MAX_SP)rep(k,4)next_state[i][j][k] = ii(0,0); rep(i,P+1){ rep(j,spell[i].size()+1){ rep(dir,4){ rep(k,j+1){ ii value = getValue(spell[i].substr(0,j).substr(k)+dc[dir]); if(value != ii(0,0) && next_state[i][j][dir].second < value.second){ next_state[i][j][dir] = value; } } } } } } inline bool isValid(int x,int y){ return ( 0 <= x && x < w && 0 <= y && y < h ); } void compute(){ priority_queue<Data> Q; Q.push(Data(sp,0,ii(0,0))); rep(i,h*w)rep(j,MAX_SP)rep(k,MAX_SP)mincost[i][j][k] = IINF; mincost[sp][0][0] = 0; while(!Q.empty()){ Data data = Q.top(); Q.pop(); if(data.cur == gp){ cout << data.cost << endl; return; } rep(dir,4){ int nx = data.cur % w + dx[dir]; int ny = data.cur / w + dy[dir]; if(!isValid(nx,ny))continue; if(G[ny][nx] == '#')continue; ii next = next_state[data.info.first][data.info.second][dir]; if(next.first != 0 && spell[next.first].size() == next.second)continue; if(mincost[nx+ny*w][next.first][next.second] > data.cost + 1){ mincost[nx+ny*w][next.first][next.second] = data.cost + 1; Q.push(Data(nx+ny*w,data.cost+1,next)); } } } cout << -1 << endl; } bool cmp(const string& a,const string& b){ return a.size() < b.size(); } int main(){ while(cin >> h >> w,h|w){ rep(i,h){ rep(j,w){ cin >> G[i][j]; if(G[i][j] == 'S'){ sp = j + i * w; } else if(G[i][j] == 'G'){ gp = j + i * w; } } } cin >> P; spell[0].clear(); vector<string> tmp; rep(i,P){ cin >> spell[i+1]; tmp.push_back(spell[i+1]); } sort(tmp.begin(),tmp.end(),cmp); bool out[tmp.size()]; rep(i,tmp.size())out[i] = false; rep(i,tmp.size()){ REP(j,i+1,tmp.size()){ if(tmp[j].find(tmp[i]) != string::npos){ out[j] = true; } } } vector<string> tmp2; rep(i,tmp.size())if(!out[i]){ tmp2.push_back(tmp[i]); } P = tmp2.size(); rep(i,P){ spell[i+1] = tmp2[i]; } INIT(); compute(); } return 0; }
#include <bits/stdc++.h> using namespace std; const int INF = 1e8; const int dx[] = { 1, 0, -1, 0 }; const int dy[] = { 0, 1, 0, -1 }; const int var = 4; string D = "DRUL"; struct node { node *fail; vector<node*> next; vector<int> ok; node() : fail(nullptr), next(var, nullptr) {} }; class Aho_Corasick { static int trans(char c) { switch (c) { case 'R': return 0; case 'D': return 1; case 'L': return 2; case 'U': return 3; default: break; } exit(EXIT_FAILURE); } vector<int> unite(const vector<int>& a, const vector<int>& b) { vector<int> res; set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(res)); return res; } int K; public: node *root; Aho_Corasick(const vector<string>& Ts) : K(Ts.size()), root(new node) { node *now; root->fail = root; for (int i = 0; i < K; i++) { auto &T = Ts[i]; now = root; for (auto c : T) { if (now->next[trans(c)] == nullptr) { now->next[trans(c)] = new node; } now = now->next[trans(c)]; } now->ok.push_back(i); } queue<node*> q; for (int i = 0; i < var; i++) { if (root->next[i] == nullptr) { root->next[i] = root; } else { root->next[i]->fail = root; q.push(root->next[i]); } } while (!q.empty()) { now = q.front(); q.pop(); for (int i = 0; i < var; i++) { if (now->next[i] != nullptr) { node *nx = now->fail; while (nx->next[i] == nullptr) { nx = nx->fail; } now->next[i]->fail = nx->next[i]; now->next[i]->ok = unite(now->next[i]->ok, nx->next[i]->ok); q.push(now->next[i]); } } } } node* getnext(node* p, char c) { while (p->next[trans(c)] == nullptr) p = p->fail; return p->next[trans(c)]; } }; using T = tuple<int, int, node*>; int main() { ios::sync_with_stdio(false), cin.tie(0); int n, m, p; while (cin >> n >> m, n | m) { vector<string> S(n); int sx = 0, sy = 0, gx = 0, gy = 0; for (int i = 0; i < n; i++) { cin >> S[i]; for (int j = 0; j < (int)S[i].size(); j++) { if (S[i][j] == 'S') { sx = i; sy = j; } else if (S[i][j] == 'G') { gx = i; gy = j; } } } cin >> p; vector<string> pts(p); for (int i = 0; i < p; i++) { cin >> pts[i]; } Aho_Corasick aho(pts); vector<vector<map<node*, int>>> f(n, vector<map<node*, int>>(m)); queue<T> q; q.push(make_tuple(sx, sy, aho.root)); f[sx][sy][aho.root] = 0; while (!q.empty()) { auto p = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int tx = get<0>(p) + dx[i], ty = get<1>(p) + dy[i]; node *t = aho.getnext(get<2>(p), D[i]); if (0 <= tx && tx < n && 0 <= ty && ty < m && S[tx][ty] != '#' && t->ok.empty() && f[tx][ty].count(t) == 0) { q.push(make_tuple(tx, ty, t)); f[tx][ty][t] = f[get<0>(p)][get<1>(p)][get<2>(p)] + 1; } } } int res = INF; for (auto p : f[gx][gy]) { res = min(res, p.second); } cout << (res != INF ? res : -1) << endl; } return 0; }
#include <vector> #include <string> #include <memory> #include <set> #include <map> #include <queue> #include <iostream> using namespace std; #define rep(i,n) for(int i=0,i##_len=n;i<i##_len;i++) #define all(x) begin(x),end(x) #define lim(x,r,l) (r<=x&&x<l) typedef long long ll; typedef long double ld; struct PMA { bool isRoot = false; set<int> matched; map<char, PMA*> nexts; PMA* faild; PMA() : matched() , nexts() , faild() { } ~PMA() { for(auto&& n : nexts){ delete n.second; } } static PMA build(const vector<string>& patterns) { PMA root; root.isRoot = true; root.faild = &root; for(int i = 0; i < patterns.size(); i++){ PMA* now = &root; for(int j = 0; j < patterns[i].size(); j++){ if(now->nexts.find(patterns[i][j]) == now->nexts.end()){ now->nexts[patterns[i][j]] = new PMA; } now = now->nexts[patterns[i][j]]; } now->matched.insert(i); } queue<PMA*> que; for(auto&& next : root.nexts){ next.second->faild = &root; que.push(next.second); } while(!que.empty()){ PMA* now = que.front(); que.pop(); for(auto&& next : now->nexts){ char c = next.first; PMA* nextfaild = now->faild; while(!(nextfaild->isRoot || nextfaild->nexts.find(c) != nextfaild->nexts.end())){ nextfaild = nextfaild->faild; } if(nextfaild->nexts.find(c) != nextfaild->nexts.end()){ now->nexts[c]->faild = nextfaild->nexts[c]; now->nexts[c]->matched.insert( begin(nextfaild->nexts[c]->matched), end(nextfaild->nexts[c]->matched)); }else{ now->nexts[c]->faild = &root; } que.push(now->nexts[c]); } } return root; } tuple<set<int>, PMA*> match(const string& str, int i = 0, PMA* now_ = nullptr){ set<int> res; PMA* now = now_ ? now_ : this; for(; i < str.size(); i++){ int c = str[i]; while(!(now->isRoot || now->nexts.find(c) != now->nexts.end())){ now = now->faild; } if(now->nexts.find(c) != now->nexts.end()){ now = now->nexts[c]; } res.insert(begin(now->matched), end(now->matched)); } return make_tuple(res, now); } }; const vector<int> d4x({1, 0, -1, 0}); const vector<int> d4y({0, -1, 0, 1}); const vector<string> d4c({"D", "L", "U", "R"}); int main(){ int n, m; while(cin >> n >> m, n != 0){ vector<vector<char>> bd(n, vector<char>(m)); int sx, sy, gx, gy; rep(i, n) { rep(j, m) { cin >> bd[i][j]; if(bd[i][j] == 'S'){ sx = i; sy = j;} if(bd[i][j] == 'G'){ gx = i; gy = j;} } } int p; cin >> p; vector<string> patterns(p); rep(i, p){ cin >> patterns[i]; } PMA pma = PMA::build(patterns); set<tuple<int, int, PMA*>> visited; queue<tuple<int, int, PMA*, int>> que; que.emplace(sx, sy, &pma, 0); int res = ([&]{ while(!que.empty()){ int nx, ny, c; PMA* now; tie(nx, ny, now, c) = que.front(); que.pop(); rep(d, 4){ int tx = nx + d4x[d], ty = ny+d4y[d]; tuple<set<int>, PMA*> matched = pma.match(string(d4c[d]), 0, now); if(!(tx >= 0 && tx < n && ty >= 0 && ty < m && bd[tx][ty] != '#')){ continue; } if(!get<0>(matched).empty()){ continue; } tuple<int, int, PMA*> next(tx, ty, get<1>(matched)); if(visited.find(next) != visited.end()){ continue; } visited.insert(next); if(tx == gx && ty == gy){ return c + 1; } que.emplace(tx, ty, get<1>(matched), c + 1); } } return -1; })(); cout << res << endl; } }
#include "bits/stdc++.h" #define REP(i, n) for (int i = 0; i < n; ++i) // https://onlinejudge.u-aizu.ac.jp/status/users/EtoNagisa/submissions/1/2212/judge/3966278/C++14 using namespace std; #include "bits/stdc++.h" struct lower_alphabet { static constexpr std::size_t char_size = 26; static constexpr char min_char = 'a'; }; struct upper_alphabet { static constexpr std::size_t char_size = 26; static constexpr char min_char = 'A'; }; struct general_char { static constexpr std::size_t char_size = 256; static constexpr char min_char = 0; }; template <typename character> class aho_corasick { public: static constexpr std::size_t invalid_index = -1; struct PMA { std::size_t fail; // index of state correspond to fail suffix std::vector<std::size_t> next, accept; std::set<std::size_t> r_fail; PMA() : fail(0), next(character::char_size, invalid_index) {} }; std::vector<PMA> nodes; std::size_t cnt; aho_corasick() : cnt(0) {} void build(const std::vector<std::string> &dict) { add_node(); for (std::size_t i = 0; i < dict.size(); ++i) { std::size_t now = 0; for (std::size_t j = 0; j < dict[i].size(); ++j) { std::size_t t = static_cast<size_t>(dict[i][j] - character::min_char); if (nodes[now].next[t] == invalid_index) { std::size_t next = size(); add_node(); nodes[now].next[t] = next; } now = nodes[now].next[t]; } nodes[now].accept.push_back(i); } std::queue<std::size_t> q; for (std::size_t i = 0; i < character::char_size; ++i) { if (nodes[0].next[i] == invalid_index) { nodes[0].next[i] = 0; } else { set_fail(nodes[0].next[i], 0); q.push(nodes[0].next[i]); } } while (!q.empty()) { std::size_t p = q.front(); q.pop(); for (std::size_t i = 0; i < character::char_size; ++i) { if (nodes[p].next[i] != invalid_index) { std::size_t tmp = next(nodes[p].fail, i + character::min_char); set_fail(nodes[p].next[i], tmp); for (std::size_t ac : nodes[tmp].accept) { nodes[nodes[p].next[i]].accept.push_back(ac); } q.push(nodes[p].next[i]); } } } } void add(const std::string &s) { std::size_t start = -1, now = 0; for (std::size_t i = 0; i < s.size(); ++i) { std::size_t t = static_cast<size_t>(s[i] - character::min_char); if (nodes[now].next[t] == invalid_index) { start = i; break; } now = nodes[now].next[t]; } for (std::size_t i = start; i < s.size(); ++i) { std::size_t t = static_cast<size_t>(s[i] - character::min_char); std::size_t nxt = size(); add_node(); nodes[now].next[t] = nxt; std::size_t tmp = next(nodes[now].fail, s[i]); set_fail(nxt, tmp); for (std::size_t ac : nodes[tmp]) { nodes[nxt].accept.push_back(ac); } for (std::size_t p : nodes[now].r_fail) { if (nodes[p].next[t] != invalid_index) { set_fail(nodes[p].next[t], nxt); } } now = nxt; } } std::size_t size() const { return cnt; } std::size_t next(std::size_t now, char c) const { std::size_t t = static_cast<std::size_t>(c - character::min_char); while (nodes[now].next[t] == invalid_index) now = nodes[now].fail; return nodes[now].next[t]; } std::vector<std::vector<std::size_t>> match(const std::string &s) const { std::size_t now = 0; std::vector<std::vector<std::size_t>> ret(s.size()); for (std::size_t i = 0; i < s.size(); ++i) { now = next(now, s[i]); for (auto ac : nodes[now].accept) { ret[i].push_back(ac); } } } private: void add_node() { nodes.emplace_back(); cnt++; } void set_fail(std::size_t from, std::size_t to) { nodes[nodes[from].fail].r_fail.erase(from); nodes[from].fail = to; nodes[to].r_fail.insert(from); } }; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; string mv = "DRUL"; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, m; while (cin >> n >> m, n) { vector<string> v(n); REP(i, n) cin >> v[i]; int qu; cin >> qu; vector<string> p(qu); REP(i, qu) cin >> p[i]; aho_corasick<upper_alphabet> ac; ac.build(p); int sx = -1, sy = -1, tx = -1, ty = -1; REP(i, n) REP(j, m) { if (v[i][j] == 'S') { sx = i; sy = j; } else if (v[i][j] == 'G') { tx = i; ty = j; } } int k = ac.nodes.size(); vector<vector<vector<int>>> dp(n, vector<vector<int>>(m, vector<int>(k, 1e9))); dp[sx][sy][0] = 0; queue<pair<pair<int, int>, int>> q; q.push({{sx, sy}, 0}); while (!q.empty()) { auto c = q.front(); q.pop(); int x = c.first.first, y = c.first.second, s = c.second; REP(d, 4) { int nx = x + dx[d], ny = y + dy[d], ns = ac.next(s, mv[d]); if (nx < 0 || nx >= n || ny < 0 || ny >= m || v[nx][ny] == '#' || ac.nodes[ns].accept.size() > 0) continue; if (dp[nx][ny][ns] > dp[x][y][s] + 1) { dp[nx][ny][ns] = dp[x][y][s] + 1; q.push({{nx, ny}, ns}); } } } int ans = 1e9; REP(i, k) ans = min(ans, dp[tx][ty][i]); if (ans == 1e9) cout << -1 << endl; else cout << ans << endl; } }
#include <queue> #include <string> #include <vector> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const string ds = "RDLU"; const vector<int> dx = { 0, 1, 0, -1 }; const vector<int> dy = { 1, 0, -1, 0 }; struct state { int x, y, ban, len; }; int dist[53][53][13][13]; int main() { int H, W, P; while (cin >> H >> W, H) { vector<string> S(H); int sx = -1, sy = -1, gx = -1, gy = -1; for (int i = 0; i < H; ++i) { cin >> S[i]; if (S[i].find('S') != string::npos) sx = i, sy = S[i].find('S'); if (S[i].find('G') != string::npos) gx = i, gy = S[i].find('G'); } cin >> P; vector<string> ban(P); for (int i = 0; i < P; ++i) { cin >> ban[i]; } sort(ban.begin(), ban.end()); vector<string> rban; for (int i = 0; i < P; ++i) { bool flag = true; for (int j = 0; j < P; ++j) { if (ban[i] != ban[j] && ban[i].find(ban[j]) != string::npos) { flag = false; } if (ban[i] == ban[j] && i > j) { flag = false; } } if (flag) rban.push_back(ban[i]); } ban = rban; P = ban.size(); memset(dist, -1, sizeof(dist)); queue<state> que; que.push(state{ sx, sy, P, 0 }); dist[sx][sy][P][0] = 0; int ans = -1; while (!que.empty()) { state s = que.front(); que.pop(); int di = dist[s.x][s.y][s.ban][s.len]; if (s.x == gx && s.y == gy) { if (ans == -1) ans = di; else ans = min(ans, di); } for (int i = 0; i < 4; ++i) { int tx = s.x + dx[i], ty = s.y + dy[i]; if (0 <= tx && tx < H && 0 <= ty && ty < W && S[tx][ty] != '#') { bool incr = (s.ban != P && ban[s.ban][s.len] == ds[i]); int nxt_ban = s.ban, nxt_len = s.len; if (incr) { ++nxt_len; } else { string recent = (s.ban == P ? "" : ban[s.ban].substr(0, s.len)) + ds[i]; nxt_ban = P; nxt_len = 0; for (int j = s.len + 1; j > 0; --j) { int ptr = -1; for (int k = 0; k < P; ++k) { if (recent.substr(s.len - j + 1) == ban[k].substr(0, j)) { ptr = k; } } if (ptr != -1) { nxt_ban = ptr; nxt_len = j; break; } } } if (nxt_ban != P && nxt_len == ban[nxt_ban].length()) continue; if (dist[tx][ty][nxt_ban][nxt_len] == -1) { dist[tx][ty][nxt_ban][nxt_len] = di + 1; que.push(state{ tx, ty, nxt_ban, nxt_len }); } } } } cout << ans << endl; } return 0; }
#define _USE_MATH_DEFINES #define INF 0x3f3f3f3f #include <cstdio> #include <iostream> #include <sstream> #include <cmath> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <limits> #include <map> #include <string> #include <cstring> #include <set> #include <deque> #include <bitset> #include <list> #include <cctype> #include <utility> #include <iterator> using namespace std; typedef long long ll; typedef pair <int,int> P; typedef pair <int,P > PP; int tx[] = {0,1,0,-1};//URDL int ty[] = {-1,0,1,0}; static const double EPS = 1e-8; //URDL const static char dir[4] = {'U','R','D','L'}; const static string dir_str[4] = {"U","R","D","L"}; namespace AhoCorasick{ class Node; class SearchMachine; struct MatchingResult { map<string,int> rv; long long id; }; }; class AhoCorasick::Node { private: set<string> results; map<char,AhoCorasick::Node*> transitions; vector<AhoCorasick::Node*> v_transitions; char character; AhoCorasick::Node* parent; AhoCorasick::Node* failure; public: Node() : character('\0'),parent(NULL),failure(NULL){} Node(AhoCorasick::Node* _p,char _c) : parent(_p),character(_c),failure(NULL){} const char get_char() const { return character; } AhoCorasick::Node* get_parent() const{ return parent; } AhoCorasick::Node* get_failure() const{ return failure; } void set_failure(AhoCorasick::Node* _n){ failure = _n; } AhoCorasick::Node* get_transition(const char c){ if(transitions.find(c) == transitions.end()) return NULL; return transitions[c]; } const set<string>& get_results() const{ return results; } void add_result(const string& str){ results.insert(str); } void add_transition(AhoCorasick::Node* node){ transitions[node->get_char()] = node; v_transitions.push_back(node); } long long get_id() const{ return reinterpret_cast<long long>(this); } const vector<AhoCorasick::Node*>& get_transitions() const{ return v_transitions; } }; class AhoCorasick::SearchMachine{ private: set<string> keywords; AhoCorasick::Node* root; AhoCorasick::Node* state; public: SearchMachine(set<string> _k) : keywords(_k){ _build_tree(); } SearchMachine(){ _build_tree(); } void _build_tree(){ root = new AhoCorasick::Node(); for(set<string>::iterator it = keywords.begin(); it != keywords.end(); it++){ AhoCorasick::Node* node = root; const string& keyword = *it; for(int i = 0; i < keyword.length(); i++){ AhoCorasick::Node* next_node = node->get_transition(keyword[i]); if(next_node == NULL){ next_node = new AhoCorasick::Node(node,keyword[i]); node->add_transition(next_node); } node = next_node; } node->add_result(keyword); } vector<AhoCorasick::Node*> nodes; for(int i=0;i<root->get_transitions().size();i++){ root->get_transitions()[i]->set_failure(root); vector<AhoCorasick::Node*> tmp_nodes; tmp_nodes.reserve(nodes.size() + root->get_transitions()[i]->get_transitions().size() + 1); merge(nodes.begin(), nodes.end(), root->get_transitions()[i]->get_transitions().begin(), root->get_transitions()[i]->get_transitions().end(), back_inserter<vector<AhoCorasick::Node*> >(tmp_nodes)); nodes.swap(tmp_nodes); } while(nodes.size() > 0){ vector<AhoCorasick::Node*> next_nodes; for(int i=0;i<nodes.size();i++){ AhoCorasick::Node* r = nodes[i]->get_parent()->get_failure(); const char c = nodes[i]->get_char(); while((r != NULL) && (r->get_transition(c) == NULL)){ r = r->get_failure(); } if(r == NULL){ nodes[i]->set_failure(root); } else{ AhoCorasick::Node* tc = r->get_transition(c); nodes[i]->set_failure(tc); set<string> results; if(tc != NULL) results = tc->get_results(); for(set<string>::iterator it = results.begin(); it != results.end(); it++){ nodes[i]->add_result(*it); } } vector<AhoCorasick::Node*> tmp_nodes; tmp_nodes.reserve(next_nodes.size() + nodes[i]->get_transitions().size() + 1); merge(next_nodes.begin(), next_nodes.end(), nodes[i]->get_transitions().begin(), nodes[i]->get_transitions().end(), back_inserter<vector<AhoCorasick::Node*> >(tmp_nodes)); next_nodes.swap(tmp_nodes); } nodes = next_nodes; } root->set_failure(root); state = root; } MatchingResult feed(const string& text){ MatchingResult mr; int index = 0; while(index < text.length()){ AhoCorasick::Node* trans = NULL; while(state != NULL){ trans = state->get_transition(text[index]); if(state == root || trans != NULL) break; state = state->get_failure(); } if(trans != NULL){ state = trans; } set<string> results; if(state != NULL) results = state->get_results(); for(set<string>::iterator it = results.begin(); it != results.end(); it++){ mr.rv[*it] = index - it->length() + 1; } index++; } mr.id = state->get_id(); state = root; return mr; } }; class State{ public: int cost; string route; int x; int y; State(int _x,int _y,int _c,string _r) : cost(_c), route(_r),x(_x),y(_y){} bool operator<(const State& s) const{ return cost < s.cost; } bool operator>(const State& s) const{ return cost > s.cost; } }; int main(){ int H,W; while(~scanf("%d %d",&H,&W)){ if(H==0 && W==0) break; char stage[50][50]; set<ll> dp[50][50]; int sx = 0; int sy = 0; int gx = 0; int gy = 0; for(int y=0;y<H;y++){ char line[51]; scanf("%s",line); for(int x=0;x<W;x++){ stage[y][x] = line[x]; if(line[x] == 'S'){ sx = x; sy = y; } else if(line[x] == 'G'){ gx = x; gy = y; } } } int total_prohibited_sequences; scanf("%d",&total_prohibited_sequences); set<string> keywords; for(int sequence_idx=0; sequence_idx < total_prohibited_sequences; sequence_idx++){ string str; cin >> str; keywords.insert(str); } AhoCorasick::SearchMachine* sm = new AhoCorasick::SearchMachine(keywords); priority_queue<State,vector<State>,greater<State> > que; que.push(State(sx,sy,0,"")); int res = INF; while(!que.empty()){ State s = que.top(); string route = s.route; int cost = s.cost; int sx = s.x; int sy = s.y; que.pop(); for(int i=0;i<4;i++){ int dx = sx + tx[i]; int dy = sy + ty[i]; if(dx < 0 || dx >= W || dy < 0 || dy >= H) continue; if(stage[dy][dx] == '#') continue; string next = route + dir_str[i]; if(next.size() > 10) next = next.substr(next.size()-10); AhoCorasick::MatchingResult mr = sm->feed(next); if((!mr.rv.empty())){ // cout << mr.rv.begin()->first << endl; // cout << next << endl; continue; } if(dp[dy][dx].count(mr.id)) continue; dp[dy][dx].insert(mr.id); if(stage[dy][dx] == 'G'){ res = cost + 1; goto found; } que.push(State(dx,dy,cost+1,next)); } } found:; printf("%d\n",res == INF ? -1 : res); } }
#include <bits/stdc++.h> using namespace std; #define rep(i,x,y) for(int i=(x);i<(y);++i) #define debug(x) #x << "=" << (x) #ifdef DEBUG #define _GLIBCXX_DEBUG #define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl #else #define print(x) #endif const int inf=1e9; const int64_t inf64=1e18; const double eps=1e-9; template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){ os << "["; for (const auto &v : vec) { os << v << ","; } os << "]"; return os; } using i64=int64_t; const int alphabet_size=256; class pma{ public: pma* next[alphabet_size],*failure; vector<int> matches; string s; pma(){ fill(next,next+alphabet_size,(pma*)0); failure=NULL; } void insert(const string &str,const int id){ insert(str,0,id); } void insert(const string &str,const int idx,const int id){ s=str.substr(0,idx); if(idx==str.size()){ matches.push_back(id); return; } if(next[str[idx]]==NULL) this->next[str[idx]]=new pma(); next[str[idx]]->insert(str,idx+1,id); } }; class aho_corasick{ public: vector<string> dic; pma* root; aho_corasick(const vector<string>& dic_):dic(dic_),root(new pma()){ for(int i=0; i<dic.size(); ++i) root->insert(dic[i],i); root->failure=root; queue<pma*> que; que.push(root); while(!que.empty()){ pma* curr=que.front(); que.pop(); curr->matches.insert(curr->matches.end(),curr->failure->matches.begin(),curr->failure->matches.end()); for(int i=0; i<alphabet_size; ++i){ pma*& next=curr->next[i]; if(next==NULL){ next=curr==root?root:curr->failure->next[i]; continue; } next->failure=curr==root?root:curr->failure->next[i]; next->matches.insert(next->matches.end(),curr->matches.begin(),curr->matches.end()); que.push(next); } } } vector<bool> match(const string& s)const{ vector<bool> res(dic.size()); const pma* state=root; for(char c:s){ state=state->next[c]; for(int i:state->matches) res[i]=true; } return res; } }; void solve(int N,int M){ vector<string> vs(N); int sy,sx,gy,gx; rep(i,0,N){ cin >> vs[i]; rep(j,0,M){ if(vs[i][j]=='S'){ sy=i; sx=j; } if(vs[i][j]=='G'){ gy=i; gx=j; } } } int P; cin >> P; vector<string> ban(P); rep(i,0,P){ cin >> ban[i]; for(char& c:ban[i]){ if(c=='R') c=0; if(c=='U') c=1; if(c=='L') c=2; if(c=='D') c=3; } } aho_corasick ac(ban); vector<int> dx={1,0,-1,0},dy={0,-1,0,1}; queue<tuple<int,int,pma*,int>> que; set<tuple<int,int,pma*>> visited; que.push(make_tuple(sy,sx,ac.root,0)); visited.insert(make_tuple(sy,sx,ac.root)); while(!que.empty()){ int y,x,d; pma* curr; tie(y,x,curr,d)=que.front(); que.pop(); if(y==gy and x==gx){ cout << d << endl; return; } rep(i,0,4){ int ny=y+dy[i],nx=x+dx[i]; if(ny<0 or N<=ny or nx<0 or M<=nx or vs[ny][nx]=='#') continue; pma* next=curr->next[i]; if(!next->matches.empty()) continue; if(visited.find(make_tuple(ny,nx,next))!=visited.end()) continue; que.push(make_tuple(ny,nx,next,d+1)); visited.insert(make_tuple(ny,nx,next)); } } cout << -1 << endl; } int main(){ std::cin.tie(0); std::ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(10); for(;;){ int N,M; cin >> N >> M; if(!N and !M) break; solve(N,M); } return 0; }
#include<iostream> #include<vector> #include<queue> #include<string> #include<cstring> using namespace std; class PMA{//Aho-Corasick int id; bool match; PMA *failure; PMA *next[256]; public: PMA(int id=0):id(id),match(false),failure(0){ memset(next,0,sizeof(next)); } ~PMA(){ for(int i=0;i<256;i++){ if(next[i]&&next[i]!=this)delete next[i]; } } int getID()const{return id;} bool matched()const{return match;} void build(const vector<string> &p){ int num=0; for(int i=0;i<(int)p.size();i++){ const string &s=p[i]; PMA *t=this; for(int j=0;j<(int)s.size();j++){ if(!t->next[s[j]])t->next[s[j]]=new PMA(++num); t=t->next[s[j]]; } t->match=true; } queue<PMA*> q; for(int i=0;i<256;i++){ if(next[i]){ q.push(next[i]); next[i]->failure=this; }else next[i]=this; } while(!q.empty()){ PMA *t=q.front();q.pop(); for(int i=0;i<256;i++){ if(t->next[i]){ q.push(t->next[i]); PMA *r=t->failure->step(i); t->next[i]->failure=r; t->next[i]->match |= r->match; } } } } PMA *step(char c)const{ const PMA *t=this; while(!t->next[c])t=t->failure; return t->next[c]; } }; string ch("DRUL"); int dy[]={1,0,-1,0}; int dx[]={0,1,0,-1}; int h,w; char m[52][52]; int dp[51][51][102]; struct Node{ int y,x; PMA *p; }; int bfs(PMA &pma){ memset(dp,-1,sizeof(dp)); Node a,b; for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)if(m[i][j]=='S'){ a.y=i; a.x=j; a.p=&pma; } queue<Node> q; dp[a.y][a.x][a.p->getID()]=0; q.push(a); while(!q.empty()){ a=q.front();q.pop(); int d=dp[a.y][a.x][a.p->getID()]; for(int i=0;i<4;i++){ b.y=a.y+dy[i]; b.x=a.x+dx[i]; if(m[b.y][b.x]=='#')continue; b.p=a.p->step(ch[i]); if(b.p->matched())continue; if(m[b.y][b.x]=='G')return d+1; if(dp[b.y][b.x][b.p->getID()]==-1){ dp[b.y][b.x][b.p->getID()] = d+1; q.push(b); } } } return -1; } int main(){ while(cin>>h>>w&&(h||w)){ memset(m,'#',sizeof(m)); for(int i=1;i<=h;i++) for(int j=1;j<=w;j++) cin>>m[i][j]; int n; cin>>n; vector<string> p(n); for(int i=0;i<n;i++){ cin>>p[i]; } PMA pma; pma.build(p); cout<<bfs(pma)<<endl; } return 0; }
#include <iostream> #include <string> #include <vector> #include <queue> #include <algorithm> #include <numeric> #include <cstring> using namespace std; struct Entry { int x, y, state, step; }; int dx[] = { -1, 1, 0, 0 }; int dy[] = { 0, 0, -1, 1 }; const char *LABELS[] = { "L", "R", "U", "D" }; class Matcher { struct PMA { int next[256]; vector<int> accept; PMA(){ fill(next, next + 256, -1); } }; vector<PMA> states; public: Matcher(const vector<string> &patterns){ states.push_back(PMA()); for(int i = 0; i < patterns.size(); ++i){ int cur = 0; for(size_t j = 0; j < patterns[i].size(); ++j){ char c = patterns[i][j]; if(states[cur].next[c] < 0){ states[cur].next[c] = static_cast<int>(states.size()); states.push_back(PMA()); } cur = states[cur].next[c]; } states[cur].accept.push_back(i); } queue<int> q; for(int c = 1; c < 256; ++c){ if(states[0].next[c] >= 0){ states[states[0].next[c]].next[0] = 0; q.push(states[0].next[c]); }else{ states[0].next[c] = 0; } } while(!q.empty()){ int t = q.front(); q.pop(); for(int c = 1; c < 256; ++c){ if(states[t].next[c] >= 0){ q.push(states[t].next[c]); int r = states[t].next[0]; while(states[r].next[c] < 0){ r = states[r].next[0]; } states[states[t].next[c]].next[0] = states[r].next[c]; } } } for(int i = 0; i < patterns.size(); ++i){ const string &pat = patterns[i]; for(int j = 1; j < states.size(); ++j){ int current = j, k = 0; for(; k < pat.size(); ++k){ if(states[current].next[pat[k]] < 0){ break; } current = states[current].next[pat[k]]; } if(k == pat.size()){ states[current].accept.push_back(i); } } } } int match(const string &str, vector<int> &result, int state = 0){ for(size_t i = 0; i < str.size(); ++i){ char c = str[i]; while(states[state].next[c] < 0){ state = states[state].next[0]; } state = states[state].next[c]; for(size_t j = 0; j < states[state].accept.size(); ++j){ ++(result[states[state].accept[j]]); } } return state; } int stateNum() const { return static_cast<int>(states.size()); } }; bool passed[52][52][101]; int main(){ while(true){ int N, M; cin >> N >> M; if(N == 0 && M == 0){ break; } memset(passed, 0, sizeof(passed)); vector<string> field(N + 2); field[0] = field[N + 1] = string(M + 2, '#'); Entry start; int goalX = 0, goalY = 0; for(int i = 1; i <= N; ++i){ string line; cin >> line; field[i] = "#" + line + "#"; for(int j = 1; j <= M; ++j){ if(field[i][j] == 'S'){ start.x = j; start.y = i; start.state = 0; start.step = 0; }else if(field[i][j] == 'G'){ goalX = j; goalY = i; } } } int P; cin >> P; vector<string> patterns(P); for(int i = 0; i < P; ++i){ cin >> patterns[i]; } Matcher matcher(patterns); queue<Entry> q; q.push(start); passed[start.y][start.x][start.state] = true; int answer = -1; vector<int> result(P); while(!q.empty()){ Entry e = q.front(); //cerr << "> " << e.x << " " << e.y << " " << e.state << endl; if(e.x == goalX && e.y == goalY){ answer = e.step; break; } q.pop(); for(int i = 0; i < 4; ++i){ Entry next; next.x = e.x + dx[i]; next.y = e.y + dy[i]; if(field[next.y][next.x] == '#'){ continue; } next.step = e.step + 1; fill(result.begin(), result.end(), 0); next.state = matcher.match(LABELS[i], result, e.state); if( accumulate(result.begin(), result.end(), 0) != 0 || passed[next.y][next.x][next.state] ){ continue; } passed[next.y][next.x][next.state] = true; q.push(next); } } cout << answer << endl; } return 0; }
#include <iostream> #include <algorithm> #include <vector> #include <queue> #include <map> #include <cstdio> #include <cstring> using namespace std; #define REP(i,a,n) for(int i=(a); i<(int)(n); i++) #define rep(i,n) REP(i,0,n) #define DEB 0 #define all(x) x.begin(), x.end() #define mp make_pair #define pb push_back class state{ public: int x,y; vector<int> ma; // 1base state(int _x, int _y, vector<int> m){ x=_x; y=_y; ma.swap(m); } bool operator<(const state& a)const{ if( x!=a.x ) return x<a.x; if( y!=a.y ) return y<a.y; return ma < a.ma; } bool operator==(const state& a)const{ return x==a.x && y==a.y && ma==a.ma; } }; const int dx[] = {0,1,0,-1}; //up, right, down, left const int dy[] = {-1,0,1,0}; int n,m,p; int sx,sy; map<state,long long> msi; char field[52][52]; vector<string> ope; bool inside(int x, int y){ return !(x<0 || x>=m || y>=n || y<0 || field[y][x]=='#'); } int DIR(char c){ if( c=='U' ) return 0; if( c=='R' ) return 1; if( c=='D' ) return 2; if( c=='L' ) return 3; } int main(){ while(cin>>n>>m,n|m){ ope.clear(); msi.clear(); rep(i,n){ cin>>field[i]; rep(j,m)if( field[i][j]=='S' ){ sx = j; sy = i; } } cin>>p; rep(i,p){ string tmp; cin>>tmp; ope.pb(tmp); } // •”•ª•¶Žš—ñ‚ŏo‚Ä‚­‚é‚à‚͍̂폜‚·‚é bool gao[16]; memset(gao,true,sizeof(gao)); rep(i,ope.size())if( gao[i] ){ int j; for(j=0; j<ope.size(); j++)if( i!=j && gao[j] ){ if( ope[i].find(ope[j]) != string::npos ){ gao[i] = false; break; } } } vector<string> tmp; rep(i,ope.size())if( gao[i] )tmp.pb(ope[i]); ope.swap(tmp); queue<state> q; bool goal = false; long long ans = -1; q.push(state(sx,sy,vector<int>(ope.size(),0))); msi[state(sx,sy,vector<int>(ope.size(),0))] = 0; while( !q.empty() ){ int x = q.front().x; int y = q.front().y; vector<int> ma = q.front().ma; long long cost = msi[q.front()]; q.pop(); rep(k,4){ vector<int> hoge(ope.size(),0); int tx = x + dx[k]; int ty = y + dy[k]; if( !inside(tx,ty) )continue; bool ok = true; rep(j,ma.size()){ if( DIR(ope[j][ma[j]+1-1]) == k ){ hoge[j] = ma[j]+1; if( hoge[j]==ope[j].length() ){ ok = false; break; } }else{ string aaa = ope[j].substr(0,ma[j]) + string(1,k==0?'U':k==1?'R':k==2?'D':'L'); int l; for(l=0; l<aaa.size(); l++){ int u; for(u=0; u+l<aaa.size(); u++){ if( aaa[l+u]!=ope[j][u] )break; } if( u+l==aaa.size() ){ break; } } hoge[j] = aaa.size() - l; } } if( !ok ) continue; if( field[ty][tx]=='G' ){ ans = cost + 1; goal = true; } state ts(tx,ty,hoge); map<state,long long>::iterator it = msi.lower_bound(ts); if( it!=msi.end() && it->first==ts ){ if( it->second > cost+1 ){ it->second = cost+1; q.push(ts); } }else{ msi.insert(it,make_pair(ts,cost+1)); q.push(ts); } } if( goal ) break; } printf("%lld\n",ans); } return 0; }
#include<stdio.h> #include<string> #include<algorithm> #include<queue> #include<map> using namespace std; char str[60][60]; char in[60]; int dx[]={1,0,-1,0}; int dy[]={0,1,0,-1}; char dc[7]="DRUL"; int bfs[60][60][110]; string val[110]; int ng[110]; int main(){ int a,b; while(scanf("%d%d",&a,&b),a){ for(int i=0;i<a;i++)scanf("%s",str[i]); int c;scanf("%d",&c); map<string,int>m; int sz=0; for(int i=0;i<110;i++)ng[i]=0; val[0]=""; m[string("")]=sz++; for(int i=0;i<c;i++){ scanf("%s",in); string tmp=in; for(int j=0;j<=tmp.size();j++){ if(!m.count(tmp.substr(0,j))){ val[sz]=tmp.substr(0,j); m[tmp.substr(0,j)]=sz++; } } ng[m[tmp]]=1; } for(int i=0;i<sz;i++){ string tmp=val[i]; while(tmp.size()){ tmp=tmp.substr(1,tmp.size()-1); if(m.count(tmp)&&ng[m[tmp]]){ng[i]=1;break;} } } int sr,sc,gr,gc; for(int i=0;i<a;i++)for(int j=0;j<b;j++){ if(str[i][j]=='S'){sr=i;sc=j;} if(str[i][j]=='G'){gr=i;gc=j;} } queue<pair<pair<int,int>,int> >Q; for(int i=0;i<a;i++)for(int j=0;j<b;j++)for(int k=0;k<sz;k++){ bfs[i][j][k]=99999999; } bfs[sr][sc][0]=0; Q.push(make_pair(make_pair(sr,sc),0)); while(Q.size()){ int row=Q.front().first.first; int col=Q.front().first.second; int at=Q.front().second; string now=val[at]; Q.pop(); for(int i=0;i<4;i++){ if(0<=row+dx[i]&&row+dx[i]<a&&0<=col+dy[i]&&col+dy[i]<b&&str[row+dx[i]][col+dy[i]]!='#'){ string to=now+dc[i]; while(!m.count(to)){ to=to.substr(1,to.size()-1); } int tt=m[to]; if(!ng[tt]&&bfs[row+dx[i]][col+dy[i]][tt]>999999){ bfs[row+dx[i]][col+dy[i]][tt]=bfs[row][col][at]+1; Q.push(make_pair(make_pair(row+dx[i],col+dy[i]),tt)); } } } } int ret=999999999; for(int i=0;i<sz;i++)ret=min(ret,bfs[gr][gc][i]); if(ret>9999999)printf("-1\n"); else printf("%d\n",ret); } }
#include <bits/stdc++.h> using namespace std; const int vy[] = {0, 1, 0, -1}, vx[] = {1, 0, -1, 0}; const string temp = "RDLU"; const int mask = (1 << 18) - 1; int H, W, P, sx, sy; string S[50], V[10]; int solve() { queue< tuple< int, int, int, int > > que; int min_cost[50][50][10][10]; memset(min_cost, -1, sizeof(min_cost)); que.emplace(sx, sy, 0, 0); min_cost[sx][sy][0][0] = 0; while(!que.empty()) { int x, y, a, b; tie(x, y, a, b) = que.front(); que.pop(); string pat = V[a].substr(0, b); bool f = true; for(int i = 0; i < P; i++) f &= pat.find(V[i]) == string::npos; if(!f) continue; if(S[y][x] == 'G') return (min_cost[x][y][a][b]); for(int i = 0; i < 4; i++) { int nx = x + vx[i], ny = y + vy[i]; if(nx < 0 || ny < 0 || nx >= W || ny >= H) continue; if(S[ny][nx] == '#') continue; string nextpat = pat + string(1, temp[i]); bool match = false; for(int j = 0; j < nextpat.size(); j++) { string st = nextpat.substr(j); for(int k = 0; k < P; k++) { if(V[k].find(st) == 0) { if(min_cost[nx][ny][k][st.size()] == -1) { que.emplace(nx, ny, k, st.size()); min_cost[nx][ny][k][st.size()] = min_cost[x][y][a][b] + 1; } match = true; break; } } if(match) break; } if(!match && min_cost[nx][ny][0][0] == -1) { que.emplace(nx, ny, 0, 0); min_cost[nx][ny][0][0] = min_cost[x][y][a][b] + 1; } } } return (-1); } int main() { while(cin >> H >> W, H) { for(int i = 0; i < H; i++) { cin >> S[i]; for(int j = 0; j < W; j++) { if(S[i][j] == 'S') sx = j, sy = i; } } cin >> P; for(int i = 0; i < P; i++) { cin >> V[i]; } cout << solve() << endl; } }
#include <bits/stdc++.h> #define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME #define pr(...) cerr<< GET_MACRO(__VA_ARGS__,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__) <<endl #define pr1(a) (#a)<<"="<<(a)<<" " #define pr2(a,b) pr1(a)<<pr1(b) #define pr3(a,b,c) pr1(a)<<pr2(b,c) #define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d) #define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e) #define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f) #define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g) #define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h) #define prArr(a) {cerr<<(#a)<<"={";int i=0;for(auto t:(a))cerr<<(i++?", ":"")<<t;cerr<<"}"<<endl;} using namespace std; using Int = long long; using _int = int; using ll = long long; using Double = long double; const Int INF = (1LL<<60)+1e9; // ~ 1.15 * 1e18 const Int mod = (1e9)+7; const Double EPS = 1e-8; const Double PI = 6.0 * asin((Double)0.5); using P = pair<Int,Int>; template<class T> T Max(T &a,T b){return a=max(a,b);} template<class T> T Min(T &a,T b){return a=min(a,b);} template<class T1, class T2> ostream& operator<<(ostream& o,pair<T1,T2> p){return o<<"("<<p.first<<","<<p.second<<")";} template<class T1, class T2, class T3> ostream& operator<<(ostream& o,tuple<T1,T2,T3> t){ return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";} template<class T1, class T2> istream& operator>>(istream& i,pair<T1,T2> &p){return i>>p.first>>p.second;} template<class T> ostream& operator<<(ostream& o,vector<T> a){Int i=0;for(T t:a)o<<(i++?" ":"")<<t;return o;} template<class T> istream& operator>>(istream& i,vector<T> &a){for(T &t:a)i>>t;return i;} /* Aho Corasick */ template <int X /*文字の種類*/ > class AhoCorasick{ public: struct Node{ char c; //頂点の文字 int pre; //親の頂点番号 int val; //重み int exist; //単語が存在するか int dep; //ノードの深さ int failEdge; //パターンマッチに失敗した時に戻るノード vector<int> bto; //to[i] != -1? (to[i]):(posからtoへのパターンマッチに失敗した時に戻るノード) vector<int> to; //次の頂点番号 Node(){}; Node(char c,int pre,int val = 0,int exist = 0): c(c),pre(pre),val(val),exist(exist), to(X,-1){}; }; vector<Node> v; //ノード function<int(char)> toI; //文字から数字に変換する関数 int ok; AhoCorasick(function<int(char)> toI=[](char ch){return ch-'A';} ,char c = '$'/*根に用いる文字*/) :toI(toI),ok(false){v.push_back(Node(c, -1, 0/*!!!!!*/));} int size(){return v.size();} Node operator [](int i)const {return v[i];} inline void check(int pos){assert(0 <= pos && pos<size());} inline int go(int pos,char c, int flag = 0){check(pos);return flag == 0? v[pos].to[toI(c)]:v[pos].bto[toI(c)];} inline int go(const string &s,int pos = 0){ for(char c:s){ pos = go(pos,c); if(pos == -1) return -1; } return pos; } inline int back(int pos){check(pos);return v[pos].pre;} inline int getVal(int pos){check(pos);return v[pos].val;} inline int exist(int pos){check(pos);return v[pos].exist;} inline int failEdge(int pos){check(pos);assert(ok);return v[pos].failEdge;} inline int failEdge(int pos,char to){check(pos);assert(ok);return v[pos].bto[toI(to)];} inline int depth(int pos){check(pos);assert(ok);return v[pos].dep;} inline void addWord(const string &s,int val = 1){ ok = false; int pos = 0, dep = 0; for(char c:s){ v[pos].dep = dep++; if(go(pos,c) != -1){pos = go(pos,c);continue;} v.push_back(Node(c,pos)); pos = v[pos].to[toI(c)] = v.size()-1; } v[pos].dep = dep; v[pos].exist = 1; v[pos].val = max(v[pos].val, val); //min,max,+ 臨機応変に変えて } void build(){ ok = 1; buildBackEdge(); nextMatch.resize(size()); for(int i=1;i<size();i++) nextMatch[i] = failEdge(i); nextMatch[0] = -1; } vector<int> nextMatch; //to[i] := ノードiを含めないノードiからみて最も単語長が長くなるノード //posから見て単語長が最も長くなるようなノードを返す。(pos自体が単語の場合はposを返す) int suffixMatch(int pos){ if(pos == -1) return -1; if(exist(pos)) return pos; return nextMatch[pos] = suffixMatch(nextMatch[pos]); } //res[i]にはs[i]からmatchする単語の長さが入っている。 vector<vector<int> > matchedIdx(const string &s){ assert(exist(0) == 0); //空文字列が単語として存在する場合、たぶん壊れるので直す必要がある。 assert(ok); int n = s.size(); vector<vector<int> > res(n); for(int i=0, pos=0;i<n;i++){ char ch = s[i]; pos = go(pos, ch, true); int p = suffixMatch(pos); while(p != -1 && exist(p)){ res[ i - depth(p) + 1].push_back(depth(p)); p = suffixMatch(nextMatch[p]); } } return res; } private: void buildBackEdge(){ const int root = 0; queue<int> Q; Q.push(root); v[root].failEdge = root; for(int i=0;i<size();i++) v[i].bto = v[i].to; for(int i=0;i<X;i++) if(v[root].bto[i] == -1) v[root].bto[i] = root; while(!Q.empty()){ int pos = Q.front(); Q.pop(); for(int i=0;i<X;i++){ int to = v[pos].to[i]; if(to == -1) continue; Q.push(to); v[to].failEdge = (pos == root)? root:v[ v[pos].failEdge ].bto[i]; for(int i=0;i<X;i++) if(v[to].bto[i] == -1) v[to].bto[i] = v[ v[to].failEdge ].bto[i]; } } } }; void check(){ AhoCorasick <26> aho([](char ch){return ch - 'a';}); aho.addWord("abcde"); aho.addWord("bc"); aho.addWord("bab"); aho.addWord("d"); aho.addWord("ab"); aho.build(); pr(aho.ok); for(int i=0;i<aho.size();i++){ pr(i, aho[i].c, aho[i].failEdge); } string s = "abcdefgabab"; auto Idx = aho.matchedIdx(s); for(int i=0;i<(int)s.size();i++) pr(i, s[i], Idx[i]); } void AOJ_2863(){ int n; cin>>n; AhoCorasick <26> aho([](char ch){return ch - 'a';}); for(int i=0;i<n;i++){ string s; cin>>s; aho.addWord(s); } aho.build(); string t; cin>>t; auto Idx = aho.matchedIdx(t); int len = t.size(); vector<int> dp(len+1, 0); dp[0] = 1; const int mod = 1e9 + 7; for(int i=0;i<len;i++){ for(int l:Idx[i]){ dp[i+l] = (dp[i+l] + dp[i])%mod; } } int ans = dp[len]; cout<<ans<<endl; } void AOJ_2212(){ while(1){ int h,w; cin>>h>>w; if(h == 0 && w == 0) return; vector<string> mp(h); for(int i=0;i<h;i++) cin>>mp[i]; auto func = [](char ch){ if(ch == 'U') return 0; if(ch == 'R') return 1; if(ch == 'D') return 2; if(ch == 'L') return 3; return -1; }; AhoCorasick <4> aho(func); int m; cin>>m; for(int i=0;i<m;i++){ string s; cin>>s; aho.addWord(s); } aho.build(); int sy, sx; for(int i=0;i<h;i++) for(int j=0;j<w;j++) if(mp[i][j] == 'S') sy = i, sx = j; auto bfs = [&]()->int{ typedef tuple<int,int,int,string> T; queue<T> Q; Q.push(T(sy, sx, 0, "")); vector<vector<vector<int> > > D(h, vector<vector<int> > (w, vector<int>(aho.size(),-1))); D[sy][sx][0] = 0; string str = "URDL"; int dy[] = {-1, 0, 1, 0}; int dx[] = {0, 1, 0, -1}; while(!Q.empty()){ int y, x, pos; string his; tie(y, x, pos, his) = Q.front(); Q.pop(); int cost = D[y][x][pos]; if(aho.suffixMatch(pos) != -1) continue; if(mp[y][x] == 'G') return cost; for(int i=0;i<4;i++){ int ny = y + dy[i]; int nx = x + dx[i]; char dir = str[i]; if(ny < 0 || nx < 0 || ny >= h || nx >= w || mp[ny][nx] == '#') continue; int to = aho.go(pos, dir); if(to == -1) to = aho.failEdge(pos, dir); if(D[ny][nx][to] != -1) continue; D[ny][nx][to] = cost+1; Q.push(T(ny, nx, to, his + dir)); } } return -1; }; int ans = bfs(); cout<<ans<<endl; } } signed main(){ //check(); AOJ_2212(); //AOJ_2863(); return 0; }
#include <cstdio> #include <iostream> #include <algorithm> #include <string> #include <vector> #include <queue> #include <set> #include <map> #include <cmath> using namespace std; typedef pair<int, int> P; typedef pair<P, int> P2; #define rep(i, n) for (int i=0; i<(n); i++) #define all(c) (c).begin(), (c).end() #define uniq(c) c.erase(unique(all(c)), (c).end()) #define _1 first #define _2 second #define pb push_back #define INF 1145141919 #define MOD 1000000007 int DX[4] = {-1, 0, 1, 0}; int DY[4] = {0, -1, 0, 1}; string DS = "lurd"; class Trie { public: vector<vector<int> > V; vector<vector<int> > par; Trie() { V.pb(vector<int>(26+1)); par.pb(vector<int>(26+1, 0)); } int find(string s) { int cur = 0; for (char ch : s) { int c = ch - 'a'; cur = V[cur][c+1]; if (cur == 0) return -1; } return cur; } void insert(string s) { int cur = 0; for (char ch : s) { int c = ch - 'a'; if (V[cur][c+1] == 0) { V[cur][c+1] = V.size(); V.pb(vector<int>(26+1)); par.pb(vector<int>(26+1, -1)); } cur = V[cur][c+1]; } } int back(int s, int c) { if (par[s][c] != -1) return par[s][c]; if (V[s][c+1] != 0) return s; return par[s][c] = back(V[s][0], c); } }; class ACMatch { public: Trie t; vector<int> acc; vector<P> flow[26]; vector<string> S; void add_str(string s) { t.insert(s); S.pb(s); } void build() { acc.resize(t.V.size(), 0); for (string s : S) acc[t.find(s)]++; queue<int> q; rep(i, 26) { if (!t.V[0][i+1]) continue; t.V[t.V[0][i+1]][0] = 0; q.push(t.V[0][i+1]); } while (!q.empty()) { int k = q.front(); q.pop(); rep(i, 26) { if (!t.V[k][i+1]) continue; q.push(t.V[k][i+1]); int pre = t.V[k][0]; while (pre && t.V[pre][i+1]==0) pre = t.V[pre][0]; t.V[t.V[k][i+1]][0] = t.V[pre][i+1]; acc[t.V[k][i+1]] += acc[t.V[pre][i+1]]; } } rep(c, 26) { rep(s, acc.size()) { int ns = t.back(s, c); ns = t.V[ns][c+1]; flow[c].pb(P(ns, acc[ns])); } } } P move(int s, int c) { return flow[c][s]; } int match(string S) { int sum = 0, cur = 0; for (char ch : S) { int c = ch - 'a'; while (cur && t.V[cur][c+1]==0) cur = t.V[cur][0]; cur = t.V[cur][c+1]; sum += acc[cur]; } return sum; } }; int W, H, N; int SX, SY, GX, GY; char A[50][50]; int dp[50][50][100]; signed main() { ios::sync_with_stdio(false); cin.tie(0); while (cin >> H >> W) { if (H == 0 && W == 0) break; rep(y, H) { rep(x, W) { char c; cin >> c; if (c == 'S') SX = x, SY = y; if (c == 'G') GX = x, GY = y; A[x][y] = c == '#'; } } ACMatch acm; cin >> N; rep(i, N) { string s; cin >> s; for (char &c : s) { if (c == 'L') c = 'l'; else if (c == 'U') c = 'u'; else if (c == 'R') c = 'r'; else if (c == 'D') c = 'd'; } acm.add_str(s); } acm.build(); int L = acm.acc.size(); rep(x, W) { rep(y, H) { rep(s, L) { dp[x][y][s] = INF; } } } queue<P2> q; q.push(P2(P(SX, SY), 0)); dp[SX][SY][0] = 0; while (!q.empty()) { int x = q.front()._1._1, y = q.front()._1._2, s = q.front()._2; q.pop(); rep(k, 4) { int nx = x+DX[k], ny = y+DY[k]; if (nx<0||nx>=W||ny<0||ny>=H) continue; if (A[nx][ny]) continue; P p = acm.move(s, DS[k]-'a'); if (p._2 > 0) continue; int ns = p._1; if (dp[nx][ny][ns] > dp[x][y][s]+1) { dp[nx][ny][ns] = dp[x][y][s]+1; q.push(P2(P(nx, ny), ns)); } } } int m = *min_element(dp[GX][GY], dp[GX][GY]+L); if (m == INF) m = -1; cout << m << "\n"; } return 0; }
#include <bits/stdc++.h> using namespace std; #define rep(i,x,y) for(int i=(x);i<(y);++i) #define debug(x) #x << "=" << (x) #ifdef DEBUG #define _GLIBCXX_DEBUG #define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl #else #define print(x) #endif const int inf=1e9; const int64_t inf64=1e18; const double eps=1e-9; template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){ os << "["; for (const auto &v : vec) { os << v << ","; } os << "]"; return os; } using i64=int64_t; const int alphabet_size=4; char table[4]={'R','U','L','D'}; class pma{ public: pma* next[alphabet_size],*failure; vector<int> matches; string s; pma(){ fill(next,next+alphabet_size,(pma*)0); failure=NULL; } void insert(const string &str,const int id){ insert(str,0,id); } void insert(const string &str,const int idx,const int id){ s=str.substr(0,idx); if(idx==str.size()){ matches.push_back(id); return; } if(next[str[idx]]==NULL) this->next[str[idx]]=new pma(); next[str[idx]]->insert(str,idx+1,id); } }; //ofstream ofs("graph.dot"); string convert(string s){ string res; //for(char c:s) res+=table[c]; return res; } void add_edge(pma* from,pma*to,string label){ /* ofs << " \""; ofs << convert(from->s); ofs << "\" -> \""; ofs << convert(to->s); ofs << "\" [label = \"" << label << "\"];" << endl; */ } class aho_corasick{ public: vector<string> dic; pma* root; aho_corasick(const vector<string>& dic_):dic(dic_),root(new pma()){ for(int i=0; i<dic.size(); ++i) root->insert(dic[i],i); root->failure=root; queue<pma*> que; que.push(root); add_edge(root,root,"failure"); while(!que.empty()){ pma* curr=que.front(); que.pop(); vector<bool> original_link(alphabet_size,true); curr->matches.insert(curr->matches.end(),curr->failure->matches.begin(),curr->failure->matches.end()); for(int i=0; i<alphabet_size; ++i){ pma*& next=curr->next[i]; if(next==NULL){ if(curr==root) next=root; else next=curr->failure->next[i]; //curr->matches.insert(curr->matches.end(),next->matches.begin(),next->matches.end()); original_link[i]=false; add_edge(curr,curr->next[i],string(1,table[i])); continue; } } for(int i=0; i<alphabet_size; ++i){ if(!original_link[i]) continue; pma*& next=curr->next[i]; if(curr==root) next->failure=root; else next->failure=curr->failure->next[i]; next->matches.insert(next->matches.end(),curr->matches.begin(),curr->matches.end()); que.push(next); add_edge(curr,next,string(1,table[i])); add_edge(next,next->failure,"failure"); } } } vector<bool> match(const string& s)const{ vector<bool> res(dic.size()); const pma* state=root; for(char c:s){ state=state->next[c]; for(int i:state->matches) res[i]=true; } return res; } }; void solve(int N,int M){ vector<string> vs(N); int sy,sx,gy,gx; rep(i,0,N){ cin >> vs[i]; rep(j,0,M){ if(vs[i][j]=='S'){ sy=i; sx=j; } if(vs[i][j]=='G'){ gy=i; gx=j; } } } int P; cin >> P; vector<string> ban(P); rep(i,0,P){ cin >> ban[i]; for(char& c:ban[i]){ if(c=='R') c=0; if(c=='U') c=1; if(c=='L') c=2; if(c=='D') c=3; } } aho_corasick ac(ban); vector<int> dx={1,0,-1,0},dy={0,-1,0,1}; queue<tuple<int,int,pma*,int>> que; set<tuple<int,int,pma*>> visited; que.push(make_tuple(sy,sx,ac.root,0)); visited.insert(make_tuple(sy,sx,ac.root)); while(!que.empty()){ int y,x,d; pma* curr; tie(y,x,curr,d)=que.front(); que.pop(); if(y==gy and x==gx){ cout << d << endl; return; } rep(i,0,4){ int ny=y+dy[i],nx=x+dx[i]; if(ny<0 or N<=ny or nx<0 or M<=nx or vs[ny][nx]=='#') continue; pma* next=curr->next[i]; if(!next->matches.empty()){ //print(convert(curr->s)); //print(convert(next->s)); continue; } if(visited.find(make_tuple(ny,nx,next))!=visited.end()) continue; que.push(make_tuple(ny,nx,next,d+1)); visited.insert(make_tuple(ny,nx,next)); } } cout << -1 << endl; /* function<int(int,int,pma*)> rec=[&](int y,int x,pma* state){ if(memo[y][x].find(state)!=memo[y][x].end()) return memo[y][x][state]; if(y==gy and x==gx) return memo[y][x][state]=0; memo[y][x][state]=inf; for(char c:state->s) cerr << int(c); cerr << endl; rep(i,0,4){ int ny=y+dy[i],nx=x+dx[i]; if(ny<0 or N<=ny or nx<0 or M<=nx or vs[ny][nx]=='#') continue; pma* next_state=state->next[i]; if(!next_state->ids.empty()){ cerr << "BAN" << endl; for(char c:next_state->s) cerr << int(c); cerr << endl; continue; } memo[y][x][state]=min(memo[y][x][state],rec(ny,nx,next_state)+1); } return memo[y][x][state]; }; int ans=rec(sy,sx,ac.root); if(ans==inf) ans=-1; cout << ans << endl; */ } int main(){ std::cin.tie(0); std::ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(10); //ofs << "digraph G {" << endl << " graph [layout = dot];" << endl << " node [shape = \"ellipse\"];" << endl; for(;;){ int N,M; cin >> N >> M; if(!N and !M) break; solve(N,M); } //ofs << "}" << endl; return 0; }
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() typedef long long ll; typedef pair<int,int> pii; const int INF = 1<<29; const double PI = acos(-1); const double EPS = 1e-8; #include <iostream> #include <vector> #include <string> #include <queue> using namespace std; // Aho-Corasick // UVa 10679 // ‚Ƃ肠‚¦‚¸ MM > 128‚É‚µ‚Ä‚¨‚¯‚ÎASCII‚Í“ü‚é // Trie‚ÅŽÀ‘•‚µ‚Ä‚¢‚é‚̂ŁAƒƒ‚ƒŠŒø—¦‚͈«‚¢ const int MM = 150; struct Node { int id; int next[MM]; int fail; vector<int> value; Node() { for(int i=0; i<MM; ++i) next[i] = 0; value.clear(); } }; class Trie { public: Trie(const vector<string> &vs) { nodes.push_back(new Node()); // dummy nodes.push_back(new Node()); for(int i=0; i<vs.size(); ++i) insert(vs[i],i); } Trie() { nodes.clear(); } void insert(const string &s,int k) { Node *cur = nodes[1]; for(int i=0; i<s.length(); ++i) { if(cur->next[s[i]] == 0) { cur->next[s[i]] = nodes.size(); nodes.push_back(new Node()); } cur = nodes[cur->next[s[i]]]; } cur->value.push_back(k); } vector<Node*> nodes; }; class Aho_Corasick { public: Aho_Corasick(const vector<string> &vs) { nodes = Trie(vs).nodes; make_failure_link(); } void make_failure_link() { //const vector<Node*> &nodes = _trie.nodes; queue<int> q; Node *root = nodes[1]; for(int i=0; i<MM; ++i) { if(root->next[i]) { nodes[root->next[i]]->fail = 1; q.push(root->next[i]); }else root->next[i] = 1; } while(!q.empty()) { Node *t = nodes[q.front()]; q.pop(); for(int i=0; i<MM; ++i) { int u = t->next[i]; if(u) { q.push(u); int r = t->fail; while(!nodes[r]->next[i]) r = nodes[r]->fail; nodes[u]->fail = nodes[r]->next[i]; FOR(it, nodes[nodes[u]->fail]->value) { nodes[u]->value.push_back(*it); } } } } } int match(const string &s) { int ret = 0; int v = 1; for(int i=0; i<s.length(); ++i) { while(!nodes[v]->next[s[i]]) { v = nodes[v]->fail; } v = nodes[v]->next[s[i]]; if(!(nodes[v]->value.empty())) { // found the word ret += nodes[v]->value.size(); } } return ret; } int next(int v, char c) { while(!nodes[v]->next[c]) { v = nodes[v]->fail; } v = nodes[v]->next[c]; if(!(nodes[v]->value.empty())) { // found the word return -1; } return v; } void free() { for(int i=0; i<nodes.size(); ++i) delete nodes[i]; } vector<Node*> nodes; }; char ba[50][50]; int dx[4] = {0,1,0,-1}; int dy[4] = {-1,0,1,0}; char dir[4] = {'U','R','D','L'}; struct P { int y, x, v; P(int y, int x, int v) : y(y),x(x),v(v) {} }; int dis[50][50][102]; int main() { int h, w; while(cin >> h >> w, h||w) { int sy,sx; REP(i, h) { REP(j, w) { cin >> ba[i][j]; if (ba[i][j] == 'S') sy=i,sx=j; } } int m; cin >> m; vector<string> vs(m); REP(i, m) cin >> vs[i]; Aho_Corasick pma(vs); queue<P> Q; Q.push(P(sy,sx,1)); memset(dis,-1,sizeof(dis)); dis[sy][sx][1] = 0; int ans = -1; while(!Q.empty()) { P p = Q.front(); Q.pop(); // cout << string(dis[p.y][p.x][p.v], ' '); // cout << p.x << " " << p.y << " " << p.v << endl; if (ba[p.y][p.x] == 'G') { ans = dis[p.y][p.x][p.v]; break; } REP(k, 4) { int yy = p.y+dy[k]; int xx = p.x+dx[k]; if (yy<0||yy>=h||xx<0||xx>=w) continue; if (ba[yy][xx] == '#') continue; int vv = pma.next(p.v, dir[k]); //cout << xx << ":" << yy << ":" << vv << endl; //cout << dis[yy][xx][vv] << endl; if (vv != -1 && dis[yy][xx][vv] == -1) { dis[yy][xx][vv] = dis[p.y][p.x][p.v]+1; Q.push(P(yy,xx,vv)); } } } cout << ans << endl; } }
#include<cstdio> #include<cstring> #include<algorithm> #include<string> #include<vector> #include<queue> using namespace std; typedef pair<int, int> P; int n, m, p, K, ans; const char UDLR[4] = {'U', 'D', 'L', 'R'}; const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1}; char map[52][52], tmp[15]; string patterns[15]; vector<string> pfx; int next_state[150][4], map_state[52][52][150]; bool ng[150]; queue< P > que; bool check(int x, int y){ return x>=0&&x<n&&y>=0&&y<m&&map[x][y]!='#'; } void bfs(){ memset(map_state, 255, sizeof(map_state)); int sx, sy, ex, ey; for(int i=0; i<n; i++) for(int j=0; j<m; j++) switch (map[i][j]){ case 'S': sx = i; sy = j; break; case 'G': ex = i; ey = j; break; default: break; } while(!que.empty()) que.pop(); map_state[sx][sy][0] = 0; que.push(P(sx*m+sy, 0)); bool reach=false; int tx, ty, tk, xx, yy, kk; ans = -1; while(!que.empty()){ tx = que.front().first / m; ty = que.front().first % m; tk = que.front().second; que.pop(); for(int i=0; i<4; i++){ kk = next_state[tk][i]; if(!ng[kk] && check(tx+dx[i], ty+dy[i])){ // state kk is not forbidden xx = tx + dx[i]; yy = ty + dy[i]; if(map_state[xx][yy][kk] == -1){ map_state[xx][yy][kk] = map_state[tx][ty][tk] + 1; que.push(P(xx*m+yy, kk)); if(xx==ex && yy==ey){ reach = true; ans = map_state[xx][yy][kk]; break; } } } } if(reach) break; } printf("%d\n", ans); } int main(){ //freopen("in.txt", "r", stdin); int k; while(scanf("%d %d", &n, &m), n!=0 && m!=0){ for(int i=0; i<n; i++) scanf("%s", map[i]); scanf("%d", &p); pfx.clear(); for(int i=0; i<p; i++){ scanf("%s", tmp); patterns[i].assign(tmp); for(int j=0; j<=patterns[i].length(); j++) pfx.push_back(patterns[i].substr(0, j)); } pfx.push_back(string("")); sort(pfx.begin(), pfx.end()); pfx.erase(unique(pfx.begin(), pfx.end()), pfx.end()); K = pfx.size(); for(int i=0; i<K; i++){ ng[i] = false; for(int j=0; j<p; j++){ ng[i] |= patterns[j].length()<=pfx[i].length() && pfx[i].substr(pfx[i].length()-patterns[j].length(), patterns[j].length()) == patterns[j]; } for(int j=0; j<4; j++){ string s = pfx[i] + UDLR[j]; for(;;){ k = lower_bound(pfx.begin(), pfx.end(), s) - pfx.begin(); if(k<K && pfx[k]==s) break; s = s.substr(1); } next_state[i][j] = k; } } bfs(); } return 0; }
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <cfloat> #include <ctime> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> #include <numeric> #include <list> using namespace std; #ifdef _MSC_VER #define __typeof__ decltype template <class T> int __builtin_popcount(T n) { return n ? 1 + __builtin_popcount(n & (n - 1)) : 0; } #endif #define foreach(it, c) for (__typeof__((c).begin()) it=(c).begin(); it != (c).end(); ++it) #define all(c) (c).begin(), (c).end() #define rall(c) (c).rbegin(), (c).rend() #define popcount __builtin_popcount #define rep(i, n) for (int i = 0; i < n; ++i) template <class T> void max_swap(T& a, const T& b) { a = max(a, b); } template <class T> void min_swap(T& a, const T& b) { a = min(a, b); } typedef long long ll; typedef pair<int, int> pint; const double PI = acos(-1.0); const int dx[] = { 0, 1, 0, -1 }; const int dy[] = { 1, 0, -1, 0 }; vector<int> build_pma(const vector<int>& pat) { vector<int> res(pat.size() + 1); res[0] = -1; for (int i = 0, j = -1; i < pat.size(); ++i) { while (j >= 0 && pat[i] != pat[j]) j = res[j]; res[i + 1] = ++j; } return res; } ll encode(const vector<int>& states) { ll res = 0; for (int i = states.size() - 1; i >= 0; --i) res = res << 4 | states[i]; return res; } void decode(ll e, vector<int>& res) { for (int i = 0; i < res.size(); ++i, e >>= 4) res[i] = e & 0xf; } ll next_states(const vector<vector<int> >& pat, const vector<vector<int> >& pma, ll states, int dir) { ll res = 0; vector<int> cur(pat.size()), next; decode(states, cur); for (int i = 0; i < cur.size(); ++i) { while (cur[i] >= 0 && pat[i][cur[i]] != dir) cur[i] = pma[i][cur[i]]; if (++cur[i] == pat[i].size()) return -1; next.push_back(cur[i]); } return encode(next); } struct Node { int x, y; ll states; Node(int x, int y, ll s) : x(x), y(y), states(s) {} }; int main() { int n, m, p; while (cin >> n >> m, n | m) { string maze[64], pp[16]; rep (i, n) cin >> maze[i]; cin >> p; rep (i, p) cin >> pp[i]; int sx, sy, gx, gy; rep (y, n) { rep (x, m) { if (maze[y][x] == 'S') sx = x, sy = y; else if (maze[y][x] == 'G') gx = x, gy = y; } } vector<vector<int> > pat(p); rep (i, p) rep (j, pp[i].size()) pat[i].push_back(string("DRUL").find(pp[i][j])); vector<vector<int> > pma(p); rep (i, p) pma[i] = build_pma(pat[i]); int res = -1; map<ll, int> visit[64][64]; queue<Node> q; q.push(Node(sx, sy, 0)); visit[sy][sx][0] = 0; while (!q.empty()) { Node cur = q.front(); q.pop(); int cost = visit[cur.y][cur.x][cur.states] + 1; for (int i = 0; i < 4; ++i) { int nx = cur.x + dx[i], ny = cur.y + dy[i]; if (0 <= nx && nx < m && 0 <= ny && ny < n && maze[ny][nx] != '#') { ll ns = next_states(pat, pma, cur.states, i); if (ns != -1 && !visit[ny][nx].count(ns)) { vector<int> s(p); decode(ns, s); if (nx == gx && ny == gy) { res = cost; goto End; } else { q.push(Node(nx, ny, ns)); visit[ny][nx][ns] = cost; } } } } } End: cout << res << endl; } }
#include <iostream> #include <string> #include <vector> #include <queue> #include <algorithm> #define V(x, y, z) ((x) * 1000000 + (y) * 1000 + (z)) #define inf 1000000000 using namespace std; int W, H; char map[55][55]; int P; string S[15]; int sx, sy, gx, gy; vector<string> vec; int Next[105][4]; bool ng[105][4]; const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1}; const char c[] = {'R', 'U', 'L', 'D'}; int dist[55][55][105]; int bfs() { for(int x = 1; x <= W; x++){ for(int y = 1; y <= H; y++){ for(int k = 0; k < vec.size(); k++){ dist[x][y][k] = inf; } } } dist[sx][sy][0] = 0; queue<int> Q; Q.push(V(sx, sy, 0)); int x, y, state; while(Q.size()){ state = Q.front() % 1000, Q.front() /= 1000; y = Q.front() % 1000, Q.front() /= 1000; x = Q.front(); Q.pop(); for(int i = 0; i < 4; i++){ int nx = x + dx[i], ny = y + dy[i], nstate = Next[state][i]; if(ng[state][i]) continue; if(nx <= 0 || nx > W || ny <= 0 || ny > H) continue; if(map[nx][ny] == '#') continue; if(dist[nx][ny][nstate] < inf) continue; dist[nx][ny][nstate] = dist[x][y][state] + 1; Q.push(V(nx, ny, nstate)); } } int ret = inf; for(int i = 0; i < vec.size(); i++) ret = min(ret, dist[gx][gy][i]); if(ret == inf) return -1; return ret; } int main(void) { while(1){ cin >> H >> W; if(H == 0 && W == 0) break; for(int y = 1; y <= H; y++){ for(int x = 1; x <= W; x++){ cin >> map[x][y]; if(map[x][y] == 'S') sx = x, sy = y; if(map[x][y] == 'G') gx = x, gy = y; } } cin >> P; for(int i = 0; i < P; i++) cin >> S[i]; vec.clear(); vec.push_back(""); for(int i = 0; i < P; i++){ for(int j = 0; j < S[i].size(); j++){ vec.push_back(S[i].substr(0, j)); } } sort(vec.begin(), vec.end()); vec.erase(unique(vec.begin(), vec.end()), vec.end()); for(int i = 0; i < vec.size(); i++){ for(int j = 0; j < 4; j++){ ng[i][j] = false; } } for(int i = 0; i < vec.size(); i++){ for(int j = 0; j < 4; j++){ string s = vec[i] + c[j]; for(int k = 0; k < P; k++){ string t = s; while(t.size()){ if(t == S[k]){ ng[i][j] = true; goto end; } t = t.substr(1); } } end:; while(1){ auto p = lower_bound(vec.begin(), vec.end(), s); if(p != vec.end() && *p == s){ Next[i][j] = p - vec.begin(); break; } s = s.substr(1); } } } cout << bfs() << endl; } return 0; }
#include<iostream> #include<vector> #include<queue> #include<string> #include<cstring> using namespace std; class PMA{//Aho-Corasick int id; bool match; PMA *failure; PMA *next[256]; public: PMA(int id=0):id(id),match(false),failure(0){ memset(next,0,sizeof(next)); } ~PMA(){ for(int i=0;i<256;i++){ if(next[i]&&next[i]!=this)delete next[i]; } } int getID()const{return id;} bool matched()const{return match;} void build(const vector<string> &p){ int num=1; for(int i=0;i<(int)p.size();i++){ const string &s=p[i]; PMA *t=this; for(int j=0;j<(int)s.size();j++){ if(!t->next[s[j]])t->next[s[j]]=new PMA(num++); t=t->next[s[j]]; } t->match=true; } queue<PMA*> q; for(int i=0;i<256;i++){ if(next[i]){ q.push(next[i]); next[i]->failure=this; }else next[i]=this; } while(!q.empty()){ PMA *t=q.front();q.pop(); for(int i=0;i<256;i++){ if(t->next[i]){ q.push(t->next[i]); PMA *r=t->failure; while(!r->next[i])r=r->failure; t->next[i]->failure=r=r->next[i]; t->next[i]->match |= r->match; } } } } PMA *step(char c)const{ const PMA *t=this; while(!t->next[c])t=t->failure; return t->next[c]; } }; string ch("DRUL"); int dy[]={1,0,-1,0}; int dx[]={0,1,0,-1}; int h,w; char m[52][52]; int dp[51][51][102]; struct Node{ int y,x; PMA *p; }; int bfs(PMA &pma){ memset(dp,-1,sizeof(dp)); Node a,b; for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)if(m[i][j]=='S'){ a.y=i; a.x=j; a.p=&pma; } queue<Node> q; dp[a.y][a.x][a.p->getID()]=0; q.push(a); while(!q.empty()){ a=q.front();q.pop(); int d=dp[a.y][a.x][a.p->getID()]; for(int i=0;i<4;i++){ b.y=a.y+dy[i]; b.x=a.x+dx[i]; if(m[b.y][b.x]=='#')continue; b.p=a.p->step(ch[i]); if(b.p->matched())continue; if(m[b.y][b.x]=='G')return d+1; if(dp[b.y][b.x][b.p->getID()]==-1){ dp[b.y][b.x][b.p->getID()] = d+1; q.push(b); } } } return -1; } int main(){ while(cin>>h>>w&&(h||w)){ memset(m,'#',sizeof(m)); for(int i=1;i<=h;i++) for(int j=1;j<=w;j++) cin>>m[i][j]; int n; cin>>n; vector<string> p(n); for(int i=0;i<n;i++){ cin>>p[i]; } PMA pma; pma.build(p); cout<<bfs(pma)<<endl; } return 0; }
#include<iostream> #include<string> #include<queue> #include<vector> #include<tuple> using namespace std; int H, W, K, x[60][60], dist[60][60][200], sx, sy, gx, gy, dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 }; string S[10], dir = "DRUL"; vector<tuple<string, int, int>>vec; vector<tuple<int, int, int>> X[60][60][200]; vector<pair<int, int>>banned[200]; void build_banned() { int cnt1 = 1; vec.push_back(make_tuple("", 0, 0)); for (int i = 0; i < K; i++) { for (int j = 0; j <= S[i].size(); j++) { string F = S[i].substr(0, j); bool OK = true; for (int k = 0; k < vec.size(); k++) { if (get<0>(vec[k]) == F) { OK = false; if (j == S[i].size()) { get<2>(vec[k]) = 1; } } } if (OK == true && j != S[i].size()) { vec.push_back(make_tuple(F, cnt1, 0)); cnt1++; } if (OK == true && j == S[i].size()) { vec.push_back(make_tuple(F, cnt1, 1)); cnt1++; } } } for (int i = 0; i < vec.size(); i++) { for (int j = 0; j < 4; j++) { string W2 = get<0>(vec[i]); W2 += dir[j]; bool OK = true; int to = 0; while (W2.size() >= 1) { for (int k = 0; k < vec.size(); k++) { string W3 = get<0>(vec[k]); if (W3 == W2 && get<2>(vec[k]) == 1) { OK = false; } if (W3 == W2 && get<2>(vec[k]) == 0) { if (get<0>(vec[to]).size() < W2.size())to = k; } } W2 = W2.substr(1, W2.size() - 1); } if (OK == true)banned[i].push_back(make_pair(to, j)); } } } void add_edges() { for (int i = 1; i <= H; i++) { for (int j = 1; j <= W; j++) { for (int k = 0; k < vec.size(); k++) { if (get<2>(vec[k]) == 1)continue; for (int l = 0; l < 4; l++) { int cx = i + dx[l], cy = j + dy[l]; if (cx <= 0 || cy <= 0 || cx > H || cy > W || x[cx][cy] == 2)continue; for (int m = 0; m < banned[k].size(); m++) { if (banned[k][m].second == l)X[i][j][k].push_back(make_tuple(cx, cy, banned[k][m].first)); } } } } } } int bfs() { queue<tuple<int, int, int>>Q; for (int i = 0; i < 60; i++) { for (int j = 0; j < 60; j++) { for (int k = 0; k < 200; k++)dist[i][j][k] = 999999999; } } Q.push(make_tuple(sx, sy, 0)); dist[sx][sy][0] = 0; while (!Q.empty()) { int a1 = get<0>(Q.front()), a2 = get<1>(Q.front()), a3 = get<2>(Q.front()); Q.pop(); for (int i = 0; i < X[a1][a2][a3].size(); i++) { int tox = get<0>(X[a1][a2][a3][i]), toy = get<1>(X[a1][a2][a3][i]), toz = get<2>(X[a1][a2][a3][i]); if (dist[tox][toy][toz] == 999999999) { dist[tox][toy][toz] = dist[a1][a2][a3] + 1; Q.push(make_tuple(tox, toy, toz)); } } } int maxn = 999999999; for (int i = 0; i < vec.size(); i++)maxn = min(maxn, dist[gx][gy][i]); return maxn; } int main() { while (true) { vec.clear(); for (int i = 0; i < 3600; i++)x[i / 60][i % 60] = 0; for (int i = 0; i < 60; i++) { for (int j = 0; j < 60; j++) { for (int k = 0; k < 200; k++)X[i][j][k].clear(); } } for (int i = 0; i < 200; i++)banned[i].clear(); cin >> H >> W; if (H == 0 && W == 0)break; for (int i = 1; i <= H; i++) { for (int j = 1; j <= W; j++) { char c; cin >> c; if (c == '.') { x[i][j] = 1; } if (c == '#') { x[i][j] = 2; } if (c == 'S') { x[i][j] = 1; sx = i; sy = j; } if (c == 'G') { x[i][j] = 1; gx = i; gy = j; } } } cin >> K; for (int i = 0; i < K; i++) { cin >> S[i]; } build_banned(); add_edges(); int ans = bfs(); if (ans == 999999999)ans = -1; cout << ans << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; const int INF = 1e8; const int dx[] = { 1, 0, -1, 0 }; const int dy[] = { 0, 1, 0, -1 }; string D = "DRUL"; // Aho-Corasick const int var = 4; int trans(char c) { switch (c) { case 'R': return 0; case 'D': return 1; case 'L': return 2; case 'U': return 3; default: break; } exit(EXIT_FAILURE); } struct node { node *fail; vector<node*> next; vector<int> ok; node() : fail(nullptr), next(var, nullptr) {} }; node* getnext(node* p, char c) { while (p->next[trans(c)] == nullptr) p = p->fail; return p->next[trans(c)]; } class Aho_Corasick { vector<int> unite(const vector<int>& a, const vector<int>& b) { vector<int> res; set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(res)); return res; } int K; node *root; public: Aho_Corasick(const vector<string>& Ts) : K(Ts.size()), root(new node) { node *now; root->fail = root; for (int i = 0; i < K; i++) { auto &T = Ts[i]; now = root; for (auto c : T) { if (now->next[trans(c)] == nullptr) { now->next[trans(c)] = new node; } now = now->next[trans(c)]; } now->ok.push_back(i); } queue<node*> q; for (int i = 0; i < var; i++) { if (root->next[i] == nullptr) { root->next[i] = root; } else { root->next[i]->fail = root; q.push(root->next[i]); } } while (!q.empty()) { now = q.front(); q.pop(); for (int i = 0; i < var; i++) { if (now->next[i] != nullptr) { node *nx = now->fail; while (nx->next[i] == nullptr) { nx = nx->fail; } now->next[i]->fail = nx->next[i]; now->next[i]->ok = unite(now->next[i]->ok, nx->next[i]->ok); q.push(now->next[i]); } } } } node* getroot() const { return root; } vector<int> count(const string& S) const { vector<int> res(K); node *now = root; for (auto c : S) { while (now->next[trans(c)] == nullptr) { now = now->fail; } now = now->next[trans(c)]; for (auto k : now->ok) { res[k]++; } } return res; } }; using T = tuple<int, int, node*>; int main() { ios::sync_with_stdio(false), cin.tie(0); int n, m, p; while (cin >> n >> m, n | m) { vector<string> S(n); int sx = 0, sy = 0, gx = 0, gy = 0; for (int i = 0; i < n; i++) { cin >> S[i]; for (int j = 0; j < (int)S[i].size(); j++) { if (S[i][j] == 'S') { sx = i; sy = j; } else if (S[i][j] == 'G') { gx = i; gy = j; } } } cin >> p; vector<string> pts(p); for (int i = 0; i < p; i++) { cin >> pts[i]; } Aho_Corasick aho(pts); vector<vector<map<node*, int>>> f(n, vector<map<node*, int>>(m)); queue<T> q; q.push(make_tuple(sx, sy, aho.getroot())); f[sx][sy][aho.getroot()] = 0; while (!q.empty()) { auto p = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int tx = get<0>(p) + dx[i], ty = get<1>(p) + dy[i]; node *t = getnext(get<2>(p), D[i]); if (0 <= tx && tx < n && 0 <= ty && ty < m && S[tx][ty] != '#' && t->ok.empty() && f[tx][ty].count(t) == 0) { q.push(make_tuple(tx, ty, t)); f[tx][ty][t] = f[get<0>(p)][get<1>(p)][get<2>(p)] + 1; } } } int res = INF; for (auto p : f[gx][gy]) { res = min(res, p.second); } cout << (res != INF ? res : -1) << endl; } return 0; }
#include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace std; class PMA { int n; vector<vector<int> > next; vector<bitset<32> > match; vector<int> failure; public: PMA(const vector<string>& pattern){ next.assign(1, vector<int>(128, -1)); match.assign(1, 0); for(unsigned i=0; i<pattern.size(); ++i){ int curr = 0; for(unsigned j=0; j<pattern[i].size(); ++j){ if(next[curr][pattern[i][j]] == -1){ next[curr][pattern[i][j]] = next.size(); next.push_back(vector<int>(128, -1)); match.push_back(0); } curr = next[curr][pattern[i][j]]; } match[curr][i] = true; } n = next.size(); failure.resize(n, 0); vector<int> node1(1, 0); while(!node1.empty()){ vector<int> node2; for(unsigned i=0; i<node1.size(); ++i){ for(int j=0; j<128; ++j){ int s = node1[i]; if(next[s][j] == -1) continue; node2.push_back(next[s][j]); int t = s; while(t != 0){ if(next[failure[t]][j] != -1){ failure[next[s][j]] = next[failure[t]][j]; match[next[s][j]] |= match[next[failure[t]][j]]; break; } t = failure[t]; } } } node1.swap(node2); } } int size(){ return n; } int transition(int curr, char c){ if(next[curr][c] != -1) return next[curr][c]; if(curr == 0) return 0; return transition(failure[curr], c); } bitset<32> checkMatch(int curr){ return match[curr]; } }; char dc[] = "URDL"; int dy[] = {-1, 0, 1, 0}; int dx[] = {0, 1, 0, -1}; int main() { for(;;){ int h, w; cin >> h >> w; if(h == 0) return 0; vector<string> grid(h+2, string(w+2, '#')); int sy, sx, gy, gx; for(int i=1; i<=h; ++i){ for(int j=1; j<=w; ++j){ cin >> grid[i][j]; if(grid[i][j] == 'S'){ sy = i; sx = j; grid[i][j] = '.'; } if(grid[i][j] == 'G'){ gy = i; gx = j; grid[i][j] = '.'; } } } int p; cin >> p; vector<string> pattern(p); for(int i=0; i<p; ++i) cin >> pattern[i]; PMA pma(pattern); int n = pma.size(); vector<vector<vector<int> > > minCost(h+2, vector<vector<int> >(w+2, vector<int>(n, INT_MAX))); minCost[sy][sx][0] = 0; queue<pair<pair<int, int>, int> > q; q.push(make_pair(make_pair(sy, sx), 0)); bool ng = true; while(!q.empty()){ int y0 = q.front().first.first; int x0 = q.front().first.second; int s = q.front().second; int cost = minCost[y0][x0][s]; q.pop(); if(y0 == gy && x0 == gx){ cout << cost << endl; ng = false; break; } for(int i=0; i<4; ++i){ int y = y0 + dy[i]; int x = x0 + dx[i]; int t = pma.transition(s, dc[i]); if(grid[y][x] == '#' || minCost[y][x][t] < INT_MAX || pma.checkMatch(t).any()) continue; minCost[y][x][t] = cost + 1; q.push(make_pair(make_pair(y, x), t)); } } if(ng) cout << -1 << endl; } }
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)(n); ++i) #define REP(i,n) FOR(i,0,n) #define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cerr<<*i<<" "; cerr<<endl; } inline bool valid(int x, int y, int W, int H){ return (x >= 0 && y >= 0 && x < W && y < H); } typedef long long ll; const int INF = 100000000; const double EPS = 1e-8; const int MOD = 1000000007; int dx[8] = {0, 1, 0, -1, 1, -1, -1, 1}; int dy[8] = {-1, 0, 1, 0, 1, 1, -1, -1}; struct PMA{ int next[0x100]; bool match; PMA() { memset(next, -1, sizeof(next)); match = false;} }; int SIZE = 0; PMA P[200]; string URDL = "URDL"; int make_PMA(){ P[SIZE] = PMA(); return SIZE++; } void build_PMA(vector<string> vs){ SIZE = 0; int root = make_PMA(); for(int i = 0; i < vs.size(); i++){ int t = root; for(int j = 0; j < vs[i].size(); j++){ if(P[t].next[vs[i][j]] == -1){ P[t].next[vs[i][j]] = make_PMA(); } t = P[t].next[vs[i][j]]; } P[t].match = true; } queue<int> que; for(int i = 0; i < 4; i++){ char c = URDL[i]; int next = P[root].next[c]; if(next != -1){ P[next].next[0] = root; que.push(next); }else { P[root].next[c] = root; } } while(!que.empty()){ int t = que.front(); que.pop(); for(int i = 0; i < 4; i++){ char c = URDL[i]; int next = P[t].next[c]; if(next != -1){ que.push(next); int r = P[t].next[0]; while(P[r].next[c] == -1) r = P[r].next[0]; P[next].next[0] = P[r].next[c]; //need?? if(P[P[r].next[c]].match) P[next].match = true; } } } } int move(int t, char c){ while(P[t].next[c] == -1) t = P[t].next[0]; return P[t].next[c]; } int main(){ int H, W; while(cin>>H>>W && H){ vector<string> grid(H); REP(y, H) cin>>grid[y]; int PL; cin>>PL; vector<string> ban(PL); REP(i, PL) cin>>ban[i]; build_PMA(ban); int dist[50][50][110] = {}; memset(dist, -1, sizeof(dist)); queue<int> qx, qy, qt; REP(y, H)REP(x, W)if(grid[y][x] == 'S'){ qx.push(x); qy.push(y); qt.push(0); dist[y][x][0] = 0; } int ans = -1; while(!qx.empty()){ int x = qx.front(); qx.pop(); int y = qy.front(); qy.pop(); int t = qt.front(); qt.pop(); int d = dist[y][x][t]; if(grid[y][x] == 'G'){ ans = d; break; } REP(r, 4){ int nx = x + dx[r]; int ny = y + dy[r]; int nt = move(t, URDL[r]); if(valid(nx, ny, W, H) && grid[ny][nx] != '#' && dist[ny][nx][nt] == -1 && !(P[nt].match)){ qy.push(ny); qx.push(nx); qt.push(nt); dist[ny][nx][nt] = d + 1; } } } cout<<ans<<endl; } return 0; }
#include <bits/stdc++.h> using namespace std; #define rep(i,x,y) for(int i=(x);i<(y);++i) #define debug(x) #x << "=" << (x) #ifdef DEBUG #define _GLIBCXX_DEBUG #define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl #else #define print(x) #endif const int inf=1e9; const int64_t inf64=1e18; const double eps=1e-9; template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){ os << "["; for (const auto &v : vec) { os << v << ","; } os << "]"; return os; } using i64=int64_t; const int alphabet_size=4; class pma{ public: pma* next[alphabet_size],*failure; vector<int> matches; string s; pma(){ fill(next,next+alphabet_size,(pma*)0); failure=NULL; } void insert(const string &str,const int id){ insert(str,0,id); } void insert(const string &str,const int idx,const int id){ s=str.substr(0,idx); if(idx==str.size()){ matches.push_back(id); return; } if(next[str[idx]]==NULL) this->next[str[idx]]=new pma(); next[str[idx]]->insert(str,idx+1,id); } }; class aho_corasick{ public: vector<string> dic; pma* root; aho_corasick(const vector<string>& dic_):dic(dic_),root(new pma()){ for(int i=0; i<dic.size(); ++i) root->insert(dic[i],i); root->failure=root; queue<pma*> que; que.push(root); while(!que.empty()){ pma* curr=que.front(); que.pop(); curr->matches.insert(curr->matches.end(),curr->failure->matches.begin(),curr->failure->matches.end()); for(int i=0; i<alphabet_size; ++i){ pma*& next=curr->next[i]; if(next==NULL){ next=curr==root?root:curr->failure->next[i]; continue; } next->failure=curr==root?root:curr->failure->next[i]; next->matches.insert(next->matches.end(),curr->matches.begin(),curr->matches.end()); que.push(next); } } } vector<bool> match(const string& s)const{ vector<bool> res(dic.size()); const pma* state=root; for(char c:s){ state=state->next[c]; for(int i:state->matches) res[i]=true; } return res; } }; void solve(int N,int M){ vector<string> vs(N); int sy,sx,gy,gx; rep(i,0,N){ cin >> vs[i]; rep(j,0,M){ if(vs[i][j]=='S'){ sy=i; sx=j; } if(vs[i][j]=='G'){ gy=i; gx=j; } } } int P; cin >> P; vector<string> ban(P); rep(i,0,P){ cin >> ban[i]; for(char& c:ban[i]){ if(c=='R') c=0; if(c=='U') c=1; if(c=='L') c=2; if(c=='D') c=3; } } aho_corasick ac(ban); vector<int> dx={1,0,-1,0},dy={0,-1,0,1}; queue<tuple<int,int,pma*,int>> que; set<tuple<int,int,pma*>> visited; que.push(make_tuple(sy,sx,ac.root,0)); visited.insert(make_tuple(sy,sx,ac.root)); while(!que.empty()){ int y,x,d; pma* curr; tie(y,x,curr,d)=que.front(); que.pop(); if(y==gy and x==gx){ cout << d << endl; return; } rep(i,0,4){ int ny=y+dy[i],nx=x+dx[i]; if(ny<0 or N<=ny or nx<0 or M<=nx or vs[ny][nx]=='#') continue; pma* next=curr->next[i]; if(!next->matches.empty()) continue; if(visited.find(make_tuple(ny,nx,next))!=visited.end()) continue; que.push(make_tuple(ny,nx,next,d+1)); visited.insert(make_tuple(ny,nx,next)); } } cout << -1 << endl; } int main(){ std::cin.tie(0); std::ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(10); for(;;){ int N,M; cin >> N >> M; if(!N and !M) break; solve(N,M); } return 0; }
#include <array> #include <cstdlib> #include <iostream> #include <queue> #include <tuple> #include <unordered_map> #include <vector> using namespace std; constexpr int ALPHA = 4; constexpr int MAX_V = 10000; const int BASE = 'a'; struct trie { int v; int failure; bool accept; array<int, ALPHA> next; explicit trie(int v_):v(v_), failure(0), accept(false) { next.fill(-1); } }; vector<trie> nodes; char convert[128]; void add(const string &s) { int v = 0; for(const char &c : s) { const int id = convert[c] - BASE; if(nodes[v].next[id] == -1) { nodes[v].next[id] = nodes.size(); nodes.emplace_back(nodes.size()); } v = nodes[v].next[id]; } nodes[v].accept = true; } void construct(const vector<string> &dict) { nodes.clear(); nodes.reserve(MAX_V); nodes.emplace_back(0); for(const auto &s : dict) { add(s); } queue<int> que; que.push(0); while(!que.empty()) { const trie &current = nodes[que.front()]; que.pop(); for(int i = 0; i < ALPHA; ++i) { const int next_id = current.next[i]; if(next_id == -1) continue; que.push(next_id); trie &u = nodes[next_id]; if(current.v) { int f = current.failure; while(f && nodes[f].next[i] == -1) { f = nodes[f].failure; } const int nf = nodes[f].next[i]; if(nf != -1) { u.failure = nf; u.accept |= nodes[nf].accept; } } } } } int move_to(int v, char c) { const int id = c - BASE; while(v && nodes[v].next[id] == -1) { v = nodes[v].failure; } if(nodes[v].next[id] != -1) { v = nodes[v].next[id]; } return v; } constexpr int dx[] = {-1, 0, 1, 0}; constexpr int dy[] = {0, 1, 0, -1}; inline bool out(int x, int y, int w, int h) { return x < 0 || y < 0 || x >= w || y >= h; } inline int bfs(const vector<string> &field) { const int h = field.size(); const int w = field[0].size(); vector<vector<unordered_map<int, int>>> dist(h, vector<unordered_map<int ,int>>(w)); queue<tuple<int, int, int>> que; for(int y = 0; y < h; ++y) { for(int x = 0; x < w; ++x) { if(field[y][x] == 'S') { dist[y][x][0] = 0; que.push(make_tuple(x, y, 0)); goto end_init; } } } end_init:; while(!que.empty()) { int x, y, v; tie(x, y, v) = que.front(); que.pop(); const int next_dist = dist[y][x][v] + 1; for(int d = 0; d < 4; ++d) { const int nx = x + dx[d]; const int ny = y + dy[d]; if(out(nx, ny, w, h) || field[ny][nx] == '#') continue; const int nv = move_to(v, d + BASE); if(nodes[nv].accept) continue; if(field[ny][nx] == 'G') return next_dist; if(!dist[ny][nx].count(nv)) { dist[ny][nx][nv] = next_dist; que.push(make_tuple(nx, ny, nv)); } } } return -1; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); const string dir = "LDRU"; for(unsigned i = 0; i < dir.size(); ++i) { convert[dir[i]] = 'a' + i; } for(int h, w; cin >> h >> w && h;) { vector<string> field(h); for(auto &e : field) cin >> e; int n; cin >> n; vector<string> ng(n); for(auto &e : ng) cin >> e; construct(ng); cout << bfs(field) << endl; } return EXIT_SUCCESS; }
#include<bits/stdc++.h> using namespace std; #define rep(i,a,b) for(int i=a;i<b;i++) #define CMAX 4 #define OFFSET 0 struct Node { int nxt[CMAX + 1]; int exist; vector<int> accept; Node() : exist(0){ memset(nxt, -1, sizeof(nxt)); }}; struct Trie { vector<Node> nodes; int root; Trie() : root(0){ nodes.push_back(Node()); } void update_direct(int node, int id) { nodes[node].accept.push_back(id); } void update_child(int node, int child, int id) { ++nodes[node].exist; } void add(const string &str, int str_index, int node_index, int id) { if (str_index == str.size()) update_direct(node_index, id); else { const int c = str[str_index] - OFFSET; if (nodes[node_index].nxt[c] == -1) { nodes[node_index].nxt[c] = (int)nodes.size(); nodes.push_back(Node()); } add(str, str_index + 1, nodes[node_index].nxt[c], id); update_child(node_index, nodes[node_index].nxt[c], id); } } void add(const string &str, int id) { add(str, 0, 0, id); } void add(const string &str) { add(str, nodes[0].exist); } int size() { return (nodes[0].exist); } int nodesize() { return ((int)nodes.size()); } }; struct AhoCorasick : Trie { static const int FAIL = CMAX; vector<int> correct; AhoCorasick() : Trie() {} void build() { correct.resize(nodes.size()); rep(i, 0, nodes.size()) correct[i] = (int)nodes[i].accept.size(); queue<int> que; rep(i, 0, CMAX + 1) { if (~nodes[0].nxt[i]) { nodes[nodes[0].nxt[i]].nxt[FAIL] = 0; que.emplace(nodes[0].nxt[i]); } else nodes[0].nxt[i] = 0; } while (!que.empty()) { Node &now = nodes[que.front()]; correct[que.front()] += correct[now.nxt[FAIL]]; que.pop(); for (int i = 0; i < CMAX; i++) { if (now.nxt[i] == -1) continue; int fail = now.nxt[FAIL]; while (nodes[fail].nxt[i] == -1) { fail = nodes[fail].nxt[FAIL]; } nodes[now.nxt[i]].nxt[FAIL] = nodes[fail].nxt[i]; auto &u = nodes[now.nxt[i]].accept; auto &v = nodes[nodes[fail].nxt[i]].accept; vector<int> accept; set_union(begin(u), end(u), begin(v), end(v), back_inserter(accept)); u = accept; que.emplace(now.nxt[i]); } } } int match(const string &str, vector< int > &result, int now = 0) { result.assign(size(), 0); int count = 0; for (auto &c : str) { while (nodes[now].nxt[c - OFFSET] == -1) now = nodes[now].nxt[FAIL]; now = nodes[now].nxt[c - OFFSET]; count += correct[now]; for (auto &v : nodes[now].accept) ++result[v]; } return count; } int next(int now, char c) { while(nodes[now].nxt[c - OFFSET] == -1) now = nodes[now].nxt[FAIL]; return nodes[now].nxt[c - OFFSET]; } }; //----------------------------------------------------------------- int H, W, P; string MAP[50], BAN[10]; int dx[4] = { 0, 1, 0, -1 }; int dy[4] = { -1, 0, 1, 0 }; string dir = "URDL"; #define INF INT_MAX/2 void change(string &s) { rep(i, 0, s.length()) rep(j, 0, 4) if (s[i] == dir[j]) s[i] = j; } bool done[50][50][100]; int dist[50][50][100]; int sol() { AhoCorasick ac; rep(i, 0, P) { change(BAN[i]); ac.add(BAN[i]); } ac.build(); // LD -> 32 // DD -> 22 // LLL -> 333 for (int i : ac.nodes[0].accept) { cout << i << endl; } rep(i, 0, 50) rep(j, 0, 50) rep(k, 0, 100) done[i][j][k] = false; rep(i, 0, 50) rep(j, 0, 50) rep(k, 0, 100) dist[i][j][k] = INF; queue<int> q; int N = ac.nodesize(); rep(y, 0, H) rep(x, 0, W) if (MAP[y][x] == 'S') { q.push(y * 100 * 100 + x * 100 + 0); dist[y][x][0] = 0; done[y][x][0] = true; } while (!q.empty()) { int y = q.front() / 10000; int x = (q.front() % 10000) / 100; int s = q.front() % 100; q.pop(); if (MAP[y][x] == 'G') return dist[y][x][s]; rep(i, 0, 4) { int xx = x + dx[i]; int yy = y + dy[i]; if (xx < 0 || W <= xx) continue; if (yy < 0 || H <= yy) continue; if (MAP[yy][xx] == '#') continue; int ss = ac.next(s, i); // ??°????????¢??¶??????????????\ if (ac.correct[ss]) continue; if (done[yy][xx][ss]) continue; q.push(yy * 10000 + xx * 100 + ss); dist[yy][xx][ss] = dist[y][x][s] + 1; done[yy][xx][ss] = true; } } return -1; } //----------------------------------------------------------------- int main() { while (cin >> H >> W) { if (H == 0) return 0; rep(y, 0, H) cin >> MAP[y]; cin >> P; rep(i, 0, P) cin >> BAN[i]; cout << sol() << endl; } }
#include <bits/stdc++.h> using namespace std; const int var = 4; const int pmax = 1e4; int trans(char c) { switch (c) { case 'R': return 0; case 'D': return 1; case 'L': return 2; case 'U': return 3; default: assert(false); } } struct ac_node { ac_node *fail; ac_node *next[var]; int ok; ac_node() : fail(nullptr), next{}, ok(0) {} }; ac_node* get_next(ac_node* p, char c) { while (!p->next[trans(c)]) p = p->fail; return p->next[trans(c)]; } class aho_corasick { ac_node* new_ac_node() { static ac_node pool[pmax]; static int it = 0; assert(it < pmax); return &pool[it++]; } int K; ac_node *root; public: aho_corasick(const vector<string>& Ts) : K(Ts.size()), root(new_ac_node()) { ac_node *now; root->fail = root; for (int i = 0; i < K; i++) { auto &T = Ts[i]; now = root; for (auto c : T) { if (!now->next[trans(c)]) { now->next[trans(c)] = new_ac_node(); } now = now->next[trans(c)]; } now->ok = 1; } queue<ac_node*> q; for (int i = 0; i < var; i++) { if (!root->next[i]) { root->next[i] = root; } else { root->next[i]->fail = root; q.push(root->next[i]); } } while (!q.empty()) { now = q.front(); q.pop(); for (int i = 0; i < var; i++) { if (now->next[i]) { ac_node *nx = now->fail; while (!nx->next[i]) { nx = nx->fail; } now->next[i]->fail = nx->next[i]; now->next[i]->ok = max(now->next[i]->ok, nx->next[i]->ok); q.push(now->next[i]); } } } } ac_node* get_root() const { return root; } int get_node_id(ac_node* nd) const { return (int)(nd - root); } }; const int INF = 1e8; const int dx[] = { 1, 0, -1, 0 }; const int dy[] = { 0, 1, 0, -1 }; string D = "DRUL"; using T = tuple<int, int, ac_node*>; int main() { ios::sync_with_stdio(false), cin.tie(0); int n, m, p; while (cin >> n >> m, n | m) { vector<string> S(n); int sx = 0, sy = 0, gx = 0, gy = 0; for (int i = 0; i < n; i++) { cin >> S[i]; for (int j = 0; j < (int)S[i].size(); j++) { if (S[i][j] == 'S') { sx = i; sy = j; } else if (S[i][j] == 'G') { gx = i; gy = j; } } } cin >> p; vector<string> pts(p); for (int i = 0; i < p; i++) { cin >> pts[i]; } aho_corasick aho(pts); vector<vector<vector<int>>> f(n, vector<vector<int>>(m, vector<int>(110, INF))); queue<T> q; q.push(make_tuple(sx, sy, aho.get_root())); f[sx][sy][aho.get_node_id(aho.get_root())] = 0; while (!q.empty()) { auto tup = q.front(); q.pop(); int x = get<0>(tup), y = get<1>(tup); ac_node *nd = get<2>(tup); int id = aho.get_node_id(nd); for (int i = 0; i < 4; i++) { int tx = x + dx[i], ty = y + dy[i]; ac_node *tnd = get_next(nd, D[i]); if (0 <= tx && tx < n && 0 <= ty && ty < m && S[tx][ty] != '#' && !tnd->ok && f[tx][ty][aho.get_node_id(tnd)] == INF) { q.push(make_tuple(tx, ty, tnd)); f[tx][ty][aho.get_node_id(tnd)] = f[x][y][id] + 1; } } } int res = INF; for (auto val : f[gx][gy]) { res = min(res, val); } cout << (res != INF ? res : -1) << endl; } return 0; }
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <string> #include <set> #include <map> using namespace std; struct State { int x, y, e; }; const int INF = (1<<28); const int MAXH = 51; const int MAXW = 51; const int MAXP = 11; const string dc[] = {"R","D","L","U"}; const int dx[] = {1,0,-1,0}; const int dy[] = {0,1,0,-1}; int H, W; char G[MAXH][MAXW]; int P; vector<string> S; int E[105][4]; int cost[MAXH][MAXW][105]; int bfs(int sx, int sy, int gx, int gy, int e) { queue<State> que; State s = {sx, sy, e}; fill(cost[0][0], cost[MAXH][0], INF); cost[s.y][s.x][s.e] = 0; que.push(s); while(!que.empty()) { s = que.front(); que.pop(); for(int i = 0; i < 4; ++i) { int nx = s.x + dx[i]; int ny = s.y + dy[i]; int ne = E[s.e][i]; if(ne == -1) continue; if(nx < 0 || nx >= W) continue; if(ny < 0 || ny >= H) continue; if(G[ny][nx] == '#') continue; if(cost[ny][nx][ne] != INF) continue; cost[ny][nx][ne] = cost[s.y][s.x][s.e] + 1; que.push((State){nx, ny, ne}); if(nx == gx && ny == gy) { return cost[ny][nx][ne]; } } } return INF; } int main() { while(cin >> H >> W && (H|W)) { int sx, sy, gx, gy; for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { cin >> G[i][j]; if(G[i][j] == 'S') { sx = j; sy = i; } if(G[i][j] == 'G') { gx = j; gy = i; } } } cin >> P; S.resize(P); for(int i = 0; i < P; ++i) { cin >> S[i]; } vector<string> v; v.push_back(""); for(int i = 0; i < P; ++i) { for(int j = 1; j < S[i].size(); ++j) { string s = S[i].substr(0, j); bool flag = true; for(int k = 0; k < S.size(); ++k) { if(s.find(S[k]) != string::npos) { flag = false; break; } } if(flag){ v.push_back(s); } } } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); fill(E[0], E[105], -1); for(int i = 0; i < v.size(); ++i) { for(int j = 0; j < 4; ++j) { string s = v[i] + dc[j]; bool flag = true; for(int k = 0; k < S.size(); ++k) { if(s.find(S[k]) != string::npos) { flag = false; break; } } if(!flag) continue; s = v[i] + dc[j]; while(1) { int p = lower_bound(v.begin(), v.end(), s) - v.begin(); if(p < v.size() && v[p] == s) { E[i][j] = p; break; } s = s.substr(1); } } } int ans = bfs(sx, sy, gx, gy, 0); if(ans == INF) ans = -1; cout << ans << endl; } return 0; }
#include <bits/stdc++.h> #define REP(i,n) for(int i=0; i<(int)(n); ++i) using namespace std; int NODE_NUM; struct Node{ map<char, Node*> next; Node* fail; vector<int> match; int node_id; Node() : fail(NULL) { node_id = NODE_NUM++; } ~Node(){ for(auto p : next) if(p.second) delete p.second; } }; Node *build(vector<string> pattens){ // 1. trie木 をつくる Node* root = new Node(); root->fail = root; for(int i = 0; i < pattens.size(); i++){ Node* p = root; for(auto c : pattens[i]){ if(p->next[c] == 0) p->next[c] = new Node(); p = p->next[c]; } p->match.push_back(i); } // 2. failure link を作る queue<Node*> que; for(int i = 0; i < 128; i++){ if(!root->next[i]){ root->next[i] = root; }else{ root->next[i]->fail = root; que.push(root->next[i]); } } while(!que.empty()){ Node* p = que.front(); que.pop(); for(int i = 0; i < 128; i++) if(p->next[i]) { Node* np = p->next[i]; // add que que.push(np); // search failure link Node* f = p->fail; while(!f->next[i]) f = f->fail; np->fail = f->next[i]; // update matching list np->match.insert(np->match.end(), np->fail->match.begin(), np->fail->match.end()); } } return root; } Node* next_node(Node* p, char c) { while(!p->next[c]) p = p->fail; return p->next[c]; } // クエリにマッチしたパターンについて // (last index, pattern id)のリストを返す typedef pair<int, int> P; vector<P> match(Node* root, string query){ int n = query.size(); vector<P> res; Node* p = root; REP(i, n) { int c = query[i]; p = next_node(p, c); for(int k : p->match){ res.push_back(P(i, k)); } } return res; } struct State{ int x, y; Node* p; }; int main(){ const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; const char dc[4]= {'R', 'D', 'L', 'U'}; int H, W; while(cin >> H >> W && H > 0) { vector<string> grid(H); REP(y, H) cin >> grid[y]; int sx, sy, gx, gy; REP(y, H) REP(x, W) if(grid[y][x] == 'S') sx = x, sy = y, grid[y][x] = '.'; REP(y, H) REP(x, W) if(grid[y][x] == 'G') gx = x, gy = y, grid[y][x] = '.'; int PN; cin >> PN; vector<string> pat(PN); REP(i, PN) cin >> pat[i]; NODE_NUM = 0; Node* root = build(pat); assert(NODE_NUM <= 110); int dist[50][50][110] = {}; REP(y, H) REP(x, W) REP(i, NODE_NUM) dist[y][x][i] = INT_MAX; queue<State> que; que.push({sx, sy, root}); dist[sy][sx][root->node_id] = 0; while(!que.empty()) { State s = que.front(); que.pop(); int d = dist[s.y][s.x][s.p->node_id]; REP(r, 4) { int nx = s.x + dx[r]; int ny = s.y + dy[r]; if(0 <= nx && 0 <= ny && nx < W && ny < H) { if(grid[ny][nx] == '#') continue; Node* np = next_node(s.p, dc[r]); if(np->match.size() > 0) continue; if(dist[ny][nx][np->node_id] > d + 1) { dist[ny][nx][np->node_id] = d + 1; que.push({nx, ny, np}); } } } } int ans = INT_MAX; REP(i, NODE_NUM) ans = min(ans, dist[gy][gx][i]); if(ans == INT_MAX) ans = -1; cout << ans << endl; } return 0; }
#include <string> #include <vector> #include <queue> #include <cassert> #include <numeric> #include <iostream> #include <algorithm> using namespace std; class AhoCorasick{ static const int ASIZE = 256; struct node_t { int ID; node_t *failure; node_t *output; node_t *next[ASIZE]; std::vector<int> match; node_t(int id) : ID(id), failure(NULL), output(NULL){ std::fill(next, next + ASIZE, (node_t*)NULL); } }; size_t n_size; size_t length; node_t *root; node_t **nodes; inline node_t *new_node(){ nodes[n_size] = new node_t(n_size); return nodes[n_size++]; } public: AhoCorasick(const std::vector<std::string> &pats) : n_size(0){ length = accumulate(pats.begin(), pats.end(), std::string("")).size(); nodes = new node_t* [length + 1]; root = new_node(); // construct key word tree for(size_t i = 0; i < pats.size(); i++){ node_t *v = root; for(size_t j = 0; j < pats[i].size(); j++){ int c = pats[i][j]; if(!v->next[c]) v->next[c] = new_node(); v = v->next[c]; } v->match.push_back(i); } // construct failure link and output link std::queue<node_t*> que; root->failure = root; root->output = root; que.push(root); while(!que.empty()){ node_t *p = que.front(); que.pop(); for(int x = 0; x < ASIZE; x++){ if(!p->next[x]) continue; node_t *v = p->next[x]; node_t *w = p->failure; if(p == root){ v->failure = root; v->output = root; }else{ while(w != root && !w->next[x]) w = w->failure; v->failure = w->next[x] ? w->next[x] : root; if(v->failure->match.empty()){ v->output = v->failure->output; }else{ v->output = v->failure; } } que.push(v); } } } ~AhoCorasick(){ for(size_t i = 0; i < n_size; i++) delete nodes[i]; delete [] nodes; } // initial state is always zero. size_t state_size() const{ return n_size; } int init_state() const{ return 0; } int next_state(size_t state, int c) const{ assert(state < n_size); node_t *v = nodes[state]; while(v != root && !v->next[c]) v = v->failure; v = v->next[c] ? v->next[c] : root; return v->ID; } std::vector<int> match(size_t state) const{ assert(state < n_size); std::vector<int> res; for(node_t *v = nodes[state]; v != root; v = v->output){ for(size_t i = 0; i < v->match.size(); i++){ res.push_back(v->match[i]); } } return res; } }; #include <cstring> #include <tuple> #include <queue> using namespace std; int dist[60][60][110]; int main(){ int N, M, P, sr, sc, gr, gc; char field[60][60]; int dr[] = {1, 0, -1, 0}; int dc[] = {0, -1, 0, 1}; char dir[] = {'D', 'L', 'U', 'R'}; while(cin >> N >> M && N + M){ for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ cin >> field[i][j]; if(field[i][j] == 'S'){ sr = i; sc = j; } if(field[i][j] == 'G'){ gr = i; gc = j; } } } cin >> P; vector<string> ps(P); for(int i = 0; i < P; i++) cin >> ps[i]; AhoCorasick aho(ps); memset(dist, -1, sizeof(dist)); queue<tuple<int, int, int>> que; que.push(make_tuple(sr, sc, aho.init_state())); dist[sr][sc][aho.init_state()] = 0; bool ok = false; while(!que.empty()){ int r, c, s; std::tie(r, c, s) = que.front(); que.pop(); if(r == gr && c == gc){ cout << dist[r][c][s] << endl; ok = true; break; } for(int i = 0; i < 4; i++){ int nr = r + dr[i]; int nc = c + dc[i]; int ns = aho.next_state(s, dir[i]); if(!aho.match(ns).empty()) continue; if(0 <= nr && nr < N && 0 <= nc && nc < M && field[nr][nc] != '#' && dist[nr][nc][ns] == -1) { dist[nr][nc][ns] = dist[r][c][s] + 1; que.push(make_tuple(nr, nc, ns)); } } } if(!ok) cout << -1 << endl; } }
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <set> #include <queue> #include <map> #include <fstream> using namespace std; class Sit{ public: int x,y; int cur; }; /* * ƒRƒ“ƒXƒgƒ‰ƒNƒ^‚ÉŽ«‘•¶Žš—ñ‚ð“n‚µ‚Ätry tree‚ðì¬ * ‚»‚ÌŒã‚ÍŠeŽí’TõŠÖ”‚ðŒÄ‚яo‚µ‚āA–؂ɑ΂µ‚Ä’Tõ‚ð‚©‚¯‚邱‚Æ‚ª‚Å‚«‚é */ class AhoCorasick{ private: static const int MAX_V=10001; private: map<string,int> _dict; string idToStr[MAX_V]; int _vertex; // Œ»Ý‚Ì•¶Žš—ñ‚©‚玟‚͂ǂ̕¶Žš—ñ‚Ö‘JˆÚ‚Å‚«‚é‚© map<int,set<int> > _stepPrv; // ’Tõޏ”s‚µ‚½ê‡‚É–ß‚éƒm[ƒh map<int,int> _stepBack; // Ž«‘•¶Žš—ñ‚̏W‡ set<int> _dictStr; // “_‚ɏî•ñ‚ð•t‰Á‚µ‚½‚¢Žž‚̂ݎg—p //T _vertexInfos[MAX_V]; public: //AhoCorasick(); AhoCorasick(const vector<string> inStrings):_vertex(1){ for(int i=0;i<inStrings.size();i++){ if(_dict.find(inStrings[i])==_dict.end()){ idToStr[_vertex]=inStrings[i]; _dict[inStrings[i]]=_vertex++; _dictStr.insert(_vertex-1); } } makeTree(inStrings); } int getStrId(string s){ if(_dict.find(s)==_dict.end())return -1; return _dict[s]; } int getVetex(){ return _vertex; } // Œ»Ý‚Ì•¶Žš—ñ‚ðŠO‚©‚ç—^‚¦A‚P•¶Žš‚¸‚Â’Tõ bool isMatchOneByOne(char ch,int &cur){ // •K—v‚Å‚ ‚ê‚΁A‚±‚±‚Åcur‚ªdict“à‚É‘¶Ý‚µ‚È‚¢‚©ƒ`ƒFƒbƒN /* */ while(1){ int nxt=cur; string nstr=idToStr[nxt]; nstr+=ch; nxt=_dict[nstr]; // ‚à‚µ¡‚̏ꏊ‚©‚玟‚̏ꏊ‚Ö‘JˆÚ‰Â”\‚È‚ç‚Î if(_stepPrv.find(cur)!=_stepPrv.end()&&_stepPrv[cur].find(nxt)!=_stepPrv[cur].end()){ // ¡‰ñ‚̏ꏊ‚©‚ç–ß‚ê‚éêŠ‚ŁAƒ}ƒbƒ`‚·‚é‚à‚Ì‚ª‚ ‚é‚©‚ðƒ`ƒFƒbƒN int tmpStr=nxt; while(tmpStr!=0){ if(_dictStr.find(tmpStr)!=_dictStr.end())return true; tmpStr=_stepBack[tmpStr]; } cur=nxt; break; } // ‚»‚¤‚łȂ¯‚ê‚΁A–ß‚Á‚ÄŽŸ‚̃‹[ƒv‚ōĂђTõ‚ðs‚¤ else{ // root‚ÅŒ©‚‚©‚ç‚È‚¯‚ê‚΁AI—¹ if(cur==0)return false; // Œ»Ý’Tõ’†‚Ì•¶Žš—ñ‚̓m[ƒh‚É‘¶Ý‚µ‚È‚¢ else if(_stepBack.find(cur)==_stepBack.end())cur=0; else{ // root‚łȂ¢ê‡‚́A–ß‚Á‚衉ñ‚Ì•¶Žš‚ð‚à‚¤ˆê“xŒ©‚é cur=_stepBack[cur]; } } } // ‚à‚µŽ«‘“à‚Ì•¶Žš—ñ‚ªŒ©‚‚©‚ê‚Îtrue if(_dictStr.find(cur)!=_dictStr.end())return true; return false; } // ­‚È‚­‚Æ‚àˆê‰ÓŠƒ}ƒbƒ`‚µ‚½‚çtrue bool isMatchLeastOne(const string &s){ int cur=0; for(int i=0;i<(int)s.size();i++){ string cstr=idToStr[cur]; string nstr=cstr+s[i]; // int nxt=_dict[nstr]; // ‚à‚µ¡‚̏ꏊ‚©‚玟‚̏ꏊ‚Ö‘JˆÚ‰Â”\‚È‚ç‚Î if(_stepPrv.find(cur)!=_stepPrv.end()&&_stepPrv[cur].find(nxt)!=_stepPrv[cur].end()){ cur=nxt; int tmpStr=nxt; // –ß‚Á‚Ä’Tõ while(tmpStr!=0){ if(_dictStr.find(tmpStr)!=_dictStr.end())return true; tmpStr=_stepBack[tmpStr]; } } // ‚»‚¤‚łȂ¯‚ê‚΁A–ß‚Á‚ÄŽŸ‚̃‹[ƒv‚ōĂђTõ‚ðs‚¤ else{ // root‚ÅŒ©‚‚©‚ç‚È‚¯‚ê‚΁A¡‰ñ‚Ì•¶Žš‚Í”ò‚΂· if(cur==0)continue; else if(_stepBack.find(cur)==_stepBack.end())cur=0; else{ // root‚łȂ¢ê‡‚́A–ß‚Á‚衉ñ‚Ì•¶Žš‚ð‚à‚¤ˆê“xŒ©‚é i--; cur=_stepBack[cur]; } } // ‚à‚µŽ«‘“à‚Ì•¶Žš—ñ‚ªŒ©‚‚©‚ê‚Îtrue if(_dictStr.find(cur)!=_dictStr.end())return true; } return false; } private: // ƒRƒs[ƒRƒ“ƒXƒgƒ‰ƒNƒ^‚ƁA‘ã“ü‰‰ŽZŽq‚ÍŽg—p‹ÖŽ~‚É‚·‚é AhoCorasick(const AhoCorasick&ah); AhoCorasick &operator=(const AhoCorasick&ah); private: // O(size(_dict)^2+size(_dict)*avg(strSize)) void makeTree(const vector<string> &inStrings){ // 0‚Ü‚½‚͋󕶎š—ñ‚ªƒ‹[ƒgƒm[ƒh _dict[""]=0; idToStr[0]=""; for(int i=0;i<(int)inStrings.size();i++){ for(int j=0;j<(int)inStrings[i].size();j++){ string s=inStrings[i].substr(0,j+1); // ‚Ü‚¾’ljÁ‚³‚ê‚Ä‚¢‚È‚¢‚̂ł ‚ê‚΁A’ljÁ‚·‚é if(_dict.find(s)==_dict.end()){ idToStr[_vertex]=s; _dict[s]=_vertex++; } } } // ’Tõ‚ð‘O‚ɐi‚ß‚é•ûŒü‚ÖƒGƒbƒW‚ðŒ‹‚Ô for(map<string,int>::iterator it=_dict.begin();it!=_dict.end();it++){ for(map<string,int>::iterator iit=_dict.begin();iit!=_dict.end();iit++){ if(it==iit)continue; // ‚à‚µiit->first‚ªsize(it->first)+1•¶Žš‚ō\¬‚³‚ê‚é‚È‚ç‚΁AƒGƒbƒW‚ðˆø‚­ if(it->first.size()==iit->first.size()-1 &&it->first==iit->first.substr(0,it->first.size())){ _stepPrv[it->second].insert(iit->second); } } } // ’Tõ‚ðŒã‚ë‚֐i‚ß‚é•ûŒü‚ÖƒGƒbƒW‚ðŒ‹‚Ô for(map<string,int>::iterator it=_dict.begin();it!=_dict.end();it++){ if(it->first=="")continue; // Œ»Ý‚Ì•¶Žš—ñ‚©‚çæ“ªi•¶Žš‚ðŽæ‚èœ‚¢‚½‚à‚֖̂߂ê‚é‚©‡”ԂɃ`ƒFƒbƒN // –ß‚ê‚È‚¯‚ê‚΃‹[ƒg‚Ö–ß‚é bool ok=false; for(int i=0;i<(int)it->first.size()-1;i++){ string s=it->first.substr(i+1); if(_dict.find(s)!=_dict.end()){ _stepBack[it->second]=_dict[s]; ok=true; break; } } // ƒ‹[ƒg‚Ö–ß‚é if(!ok)_stepBack[it->second]=0; } } }; int h,w; int n; char field[51][51]; string prohibits[20]; int sy,sx,gx,gy; set<int> used[51][51]; const int dy[]={-1,0,1,0}; const int dx[]={0,1,0,-1}; int bfs(){ vector<string> vs; for(int i=0;i<n;i++)vs.push_back(prohibits[i]); AhoCorasick ac(vs); Sit init; init.x=sx; init.y=sy; init.cur=0; queue<Sit> q[2]; int cur=0; int nxt=1; q[cur].push(init); used[init.y][init.x].insert(0); int cnt=0; while(q[cur].size()){ while(q[cur].size()){ Sit s=q[cur].front(); q[cur].pop(); if(s.y==gy&&s.x==gx)return cnt; for(int i=0;i<4;i++){ int ny=s.y+dy[i]; int nx=s.x+dx[i]; if(ny>=0&&nx>=0&&ny<h&&nx<w&&field[ny][nx]=='.'){ char ch=i+'0'; Sit nsit; nsit.y=ny;nsit.x=nx; nsit.cur=s.cur; bool b=ac.isMatchOneByOne(ch,nsit.cur); // match‚µ‚½‚çA‘JˆÚ‚µ‚È‚¢ if(b)continue; // nsit.cur‚̃m[ƒh‚Ö‚·‚łɒB‚µ‚½‚©‚Ç‚¤‚© if(used[ny][nx].find(nsit.cur)==used[ny][nx].end()){ q[nxt].push(nsit); used[ny][nx].insert(nsit.cur); } } } } cnt++; swap(cur,nxt); } return -1; } int main(){ while(cin>>h>>w&&(h|w)){ for(int i=0;i<h;i++)for(int j=0;j<w;j++)used[i][j].clear(); for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin>>field[i][j]; if(field[i][j]=='S'){ sy=i; sx=j; field[i][j]='.'; } else if(field[i][j]=='G'){ gy=i; gx=j; field[i][j]='.'; } } } cin>>n; for(int i=0;i<n;i++){ cin>>prohibits[i]; for(int j=0;j<(int)prohibits[i].size();j++){ if(prohibits[i][j]=='U')prohibits[i][j]='0'; else if(prohibits[i][j]=='R')prohibits[i][j]='1'; else if(prohibits[i][j]=='D')prohibits[i][j]='2'; else if(prohibits[i][j]=='L')prohibits[i][j]='3'; } } int res=bfs(); cout<<res<<endl; } return 0; }
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <complex> #include <string> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <functional> #include <cassert> typedef long long ll; using namespace std; #define debug(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl; #define mod 1000000007 //1e9+7(prime number) #define INF 1000000000 //1e9 #define LLINF 2000000000000000000LL //2e18 #define SIZE 100010 /* Aho Corasick */ int ACNodeId = 0; struct ACNode{ int val, id; ACNode *next[26], *failure; ACNode():val(0) { memset(next,0,sizeof(next)); id = ACNodeId++; } void insert(char *s){ if(!*s){ val++; return; } int al = *s-'A'; if(next[al]==NULL) next[al] = new ACNode; next[al]->insert(s+1); } ACNode *nextNode(char c){ int al = c - 'A'; if (next[al]) return next[al]; return failure == this ? this : failure->nextNode(c); } }; struct AhoCorasick{ ACNode *node; AhoCorasick(){node = new ACNode;} void insert(char *s) { node->insert(s); } void build() { queue<ACNode*> que; que.push(node); node->failure = node; while(que.size()){ ACNode *p = que.front(); que.pop(); for(int i=0;i<26;i++){ if(p->next[i]){ ACNode *failure = p->failure; while(!failure->next[i] && failure != node){ failure = failure->failure; } if (failure->next[i] && failure != p){ p->next[i]->failure = failure->next[i]; p->next[i]->val += failure->next[i]->val; }else{ p->next[i]->failure = node; } que.push(p->next[i]); } } } } }; int dx[8] = {0,0,1,-1,1,1,-1,-1}; int dy[8] = {1,-1,0,0,1,-1,1,-1}; char ds[] = "DURL"; bool solve(){ int h, w; char s[51][51]; int sx, sy, gx, gy; scanf("%d%d", &h, &w); if(h == 0) return false; for(int i=0;i<h;i++){ scanf("%s", s[i]); for(int j=0;j<w;j++){ if(s[i][j] == 'S'){ sx = j; sy = i; } if(s[i][j] == 'G'){ gx = j; gy = i; } } } int q; AhoCorasick ac; scanf("%d", &q); for(int i=0;i<q;i++){ char pattern[11]; scanf("%s", pattern); ac.insert(pattern); } ac.build(); bool visited[51][51][200] = {}; queue<pair<pair<int,int>,ACNode*> > que; que.push({{sy, sx}, ac.node}); for(int i=0;que.size();i++){ queue<pair<pair<int,int>,ACNode*> > que2; while(que.size()){ auto p = que.front(); que.pop(); int y = p.first.first; int x = p.first.second; ACNode* cur = p.second; if(cur->val) continue; if(y < 0 || h <= y || x < 0 || w <= x) continue; if(s[y][x] == '#') continue; if(visited[y][x][cur->id]) continue; visited[y][x][cur->id] = true; if(gy == y && gx == x){ printf("%d\n", i); return true; } for(int j=0;j<4;j++){ auto next = cur->nextNode(ds[j]); que2.push({{dy[j] + y, dx[j] + x}, next}); } } que = que2; } puts("-1"); return true; } int main(){ while(solve()); }
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <complex> #include <string> #include <sstream> #include <algorithm> #include <numeric> #include <vector> #include <queue> #include <stack> #include <functional> #include <iostream> #include <map> #include <set> #include <cassert> using namespace std; typedef pair<int,int> P; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vll; #define pu push #define pb push_back #define mp make_pair #define eps 1e-9 #define INF 2000000000 #define sz(x) ((int)(x).size()) #define fi first #define sec second #define SORT(x) sort((x).begin(),(x).end()) #define all(x) (x).begin(),(x).end() #define rep(i,n) for(int (i)=0;(i)<(int)(n);(i)++) #define repn(i,a,n) for(int (i)=(a);(i)<(int)(n);(i)++) #define EQ(a,b) (abs((a)-(b))<eps) // Aho-Corasick #define SIZE 256 struct Trie{ Trie* child[SIZE]; Trie* fail; vector<int> matched; Trie(){ for(int i=0;i<SIZE;i++)child[i]=NULL; fail = NULL; } ~Trie(){} }; Trie pool[5000]; int pool_pos; inline Trie* alloc(){return &(pool[pool_pos++]=Trie());} inline void destruct(){pool_pos=0;} vector<int> unite(const vector<int> &a,const vector<int> &b){ vector<int> ret; set_union(all(a),all(b),back_inserter(ret)); return ret; } Trie* build(vector<string> pattern){ Trie *root = alloc(); Trie *now; root->fail = root; for(int i=0;i<pattern.size();i++){ now = root; for(int j=0;j<pattern[i].size();j++){ int idx = (int)pattern[i][j]; if(now->child[idx]==NULL){ now->child[idx]=alloc(); } now = now->child[idx]; } now->matched.pb(i); } queue<Trie*> q; for(int i=0;i<SIZE;i++){ if((root->child[i])==NULL)root->child[i]=root; else{ root->child[i]->fail=root; q.push(root->child[i]); } } while(!q.empty()){ now = q.front();q.pop(); for(int i=0;i<SIZE;i++){ if(now->child[i]){ Trie *next = now->fail; while((next->child[i])==NULL)next=next->fail; now->child[i]->fail = next->child[i]; now->child[i]->matched = unite(now->child[i]->matched,next->child[i]->matched); q.push(now->child[i]); } } } return root; } // now???????????????????????????????????¨??§?¶?????????????????´¢?????? // ret???pattern???????´???°??§????????????????????¨??? // now????????§??????????????§????????????????????????????????¨??? void match(Trie* &now,const string s,vector<int> &ret){ for(int i=0;i<s.size();i++){ int idx = s[i]; while((now->child[idx])==NULL)now=now->fail; now=now->child[idx]; for(int j=0;j<(now->matched.size());j++){ ret[now->matched[j]]=1; } } } struct state{ P pos; Trie* trie; int turn; state(P pos,Trie* trie,int turn):pos(pos),trie(trie),turn(turn){} }; int dx[4]={0,-1,0,1}; int dy[4]={1,0,-1,0}; string dv[4]={"D","L","U","R"}; string f[55]; int main(){ while(1){ int n,m,p; P S,G; set<Trie*> s[55][55]; scanf("%d %d",&n,&m); if(n==0&&m==0)break; for(int i=0;i<n;i++)cin >> f[i]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(f[i][j]=='S'){S=P(j,i);} if(f[i][j]=='G'){G=P(j,i);} } } scanf("%d",&p); vector<string> pat(p); for(int i=0;i<p;i++)cin >> pat[i]; destruct(); Trie* root = build(pat); /*while(1){ string s; cin >> s; vector<int> v(p,0); Trie* r = root; match(r,s,v); int flag = 0; for(int i=0;i<p;i++)flag|=v[i]; if(flag)printf("exist\n"); else printf("not exist\n"); }*/ queue<state> q; q.push(state(S,root,0)); int ans = -1; while(!q.empty()){ state now = q.front(); q.pop(); if(now.pos == G){ans = now.turn;break;} int x = now.pos.fi , y = now.pos.sec; for(int i=0;i<4;i++){ int nx = x + dx[i]; int ny = y + dy[i]; if(nx<0||nx>=m||ny<0||ny>=n)continue; if(f[ny][nx]=='#')continue; vector<int> v(p,0); Trie* t = now.trie; match(t,dv[i],v); int flag = 0; for(int j=0;j<p;j++)flag|=v[j]; if(flag)continue; if(s[nx][ny].find(t)==s[nx][ny].end()){ s[nx][ny].insert(t); q.push(state(P(nx,ny),t,now.turn+1)); } } } printf("%d\n",ans); } return 0; }
// 12:17 - 13:14 #include<iostream> #include<cmath> #include<vector> #include<algorithm> #include<cstdio> #include<cassert> #include<climits> #include<map> #include<queue> #include<set> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define IINF (INT_MAX) #define MAX_SP 15 #define MAX_LEN 60 using namespace std; typedef pair<int,int> ii; struct Data{ int cur,cost; ii info; string debug; Data(int cur=IINF,int cost=IINF,ii info=ii(IINF,IINF),string debug="$$$"):cur(cur),cost(cost),info(info),debug(debug){} bool operator < (const Data& a)const{ return cost > a.cost; } }; int h,w,sp,gp,P; char G[MAX_LEN][MAX_LEN]; /* next_state[index][the number of match] 0 -> empty 1 -> spell[0] 2 -> spell[1] ... */ ii next_state[MAX_SP][MAX_SP][4]; int mincost[MAX_LEN*MAX_LEN][MAX_SP][MAX_SP]; string spell[MAX_SP]; int dx[] = {+0,+1,+0,-1}; int dy[] = {-1,+0,+1,+0}; char dc[] = {'U','R','D','L'}; ii getValue(string s){ rep(i,P+1){ int cur = 0; rep(j,spell[i].size()){ if(s[cur] != spell[i][j]){ break; } cur++; if(cur >= s.size()){ return ii(i,j+1); } } } return ii(0,0); } void INIT(){ rep(i,MAX_SP)rep(j,MAX_SP)rep(k,4)next_state[i][j][k] = ii(0,0); rep(i,P+1){ rep(j,spell[i].size()+1){ rep(dir,4){ rep(k,j+1){ ii value = getValue(spell[i].substr(0,j).substr(k)+dc[dir]); if(value != ii(0,0) && next_state[i][j][dir].second < value.second){ next_state[i][j][dir] = value; } } } } } } inline bool isValid(int x,int y){ return ( 0 <= x && x < w && 0 <= y && y < h ); } void compute(){ priority_queue<Data> Q; Q.push(Data(sp,0,ii(0,0))); rep(i,h*w)rep(j,MAX_SP)rep(k,MAX_SP)mincost[i][j][k] = IINF; mincost[sp][0][0] = 0; while(!Q.empty()){ Data data = Q.top(); Q.pop(); //cout << "(" << data.cur % w << "," << (int)(data.cur / w) << ") " << data.cost << " info(" << data.info.first << "," << data.info.second << ")" << endl; if(data.cur == gp){ //cout << "path : " << data.debug << endl; cout << data.cost << endl; return; } rep(dir,4){ int nx = data.cur % w + dx[dir]; int ny = data.cur / w + dy[dir]; if(!isValid(nx,ny))continue; if(G[ny][nx] == '#')continue; ii next = next_state[data.info.first][data.info.second][dir]; if(next.first != 0 && spell[next.first].size() == next.second)continue; if(mincost[nx+ny*w][next.first][next.second] > data.cost + 1){ mincost[nx+ny*w][next.first][next.second] = data.cost + 1; Q.push(Data(nx+ny*w,data.cost+1,next,data.debug+dc[dir])); } } } cout << -1 << endl; } bool cmp(const string& a,const string& b){ return a.size() < b.size(); } int main(){ while(cin >> h >> w,h|w){ rep(i,h){ rep(j,w){ cin >> G[i][j]; if(G[i][j] == 'S'){ sp = j + i * w; } else if(G[i][j] == 'G'){ gp = j + i * w; } } } cin >> P; spell[0].clear(); vector<string> tmp; rep(i,P){ cin >> spell[i+1]; tmp.push_back(spell[i+1]); } sort(tmp.begin(),tmp.end(),cmp); bool out[tmp.size()]; rep(i,tmp.size())out[i] = false; rep(i,tmp.size()){ REP(j,i+1,tmp.size()){ bool check = true; if(tmp[j].find(tmp[i]) == string::npos){ check = false; } if(check){ out[j] = true; } } } vector<string> tmp2; rep(i,tmp.size())if(!out[i]){ tmp2.push_back(tmp[i]); } P = tmp2.size(); rep(i,P){ spell[i+1] = tmp2[i]; } INIT(); /* rep(i,P+1){ cout << "spell[" << i<< "] = " << spell[i] << endl; rep(j,spell[i].size()+1){ rep(dir,4){ cout << "next_state[" << i << "][" << j << "][" << dir << "] => " << " | " << spell[i].substr(0,j) << " + " << dc[dir]<< " | " <<" next = (" << next_state[i][j][dir].first << "," << next_state[i][j][dir].second << ")" << endl; } } } */ compute(); } return 0; }
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} struct FastIO{ FastIO(){ cin.tie(0); ios::sync_with_stdio(0); } }fastio_beet; template<size_t X> struct Trie{ struct Node{ char c; array<int, X> nxt; vector<int> idxs; int idx; Node(char c):c(c),idx(-1){fill(nxt.begin(),nxt.end(),-1);} }; using F = function<int(char)>; vector<Node> vs; F conv; Trie(F conv,char c='$'):conv(conv){vs.emplace_back(c);} void add(const string &s,int x){ int pos=0; for(int i=0;i<(int)s.size();i++){ int k=conv(s[i]); if(~vs[pos].nxt[k]){ pos=vs[pos].nxt[k]; continue; } int npos=vs.size(); vs[pos].nxt[k]=npos; vs.emplace_back(s[i]); pos=npos; } vs[pos].idx=x; vs[pos].idxs.emplace_back(x); } int find(const string &s){ int pos=0; for(int i=0;i<(int)s.size();i++){ int k=conv(s[i]); if(vs[pos].nxt[k]<0) return -1; pos=vs[pos].nxt[k]; } return pos; } int find(int pos,char c){ return vs[pos].nxt[conv(c)]; } int idx(int pos){ return pos<0?-1:vs[pos].idx; } vector<int> idxs(int pos){ return pos<0?vector<int>():vs[pos].idxs; } }; template<size_t X> struct AhoCorasick : Trie<X+1>{ using TRIE = Trie<X+1>; using TRIE::TRIE; vector<int> cnt; void build(bool heavy=true){ auto &vs=TRIE::vs; int n=vs.size(); cnt.resize(n); for(int i=0;i<n;i++){ if(heavy) sort(vs[i].idxs.begin(),vs[i].idxs.end()); cnt[i]=vs[i].idxs.size(); } queue<int> que; for(int i=0;i<(int)X;i++){ if(~vs[0].nxt[i]){ vs[vs[0].nxt[i]].nxt[X]=0; que.emplace(vs[0].nxt[i]); }else{ vs[0].nxt[i]=0; } } while(!que.empty()){ auto &x=vs[que.front()]; cnt[que.front()]+=cnt[x.nxt[X]]; que.pop(); for(int i=0;i<(int)X;i++){ if(x.nxt[i]<0){ x.nxt[i]=vs[x.nxt[X]].nxt[i]; continue; } int fail=x.nxt[X]; vs[x.nxt[i]].nxt[X]=vs[fail].nxt[i]; if(heavy){ auto &idx=vs[x.nxt[i]].idxs; auto &idy=vs[vs[fail].nxt[i]].idxs; vector<int> idz; set_union(idx.begin(),idx.end(), idy.begin(),idy.end(), back_inserter(idz)); idx=idz; } que.emplace(x.nxt[i]); } } } vector<int> match(string s,int heavy=true){ auto &vs=TRIE::vs; vector<int> res(heavy?TRIE::size():1); int pos=0; for(auto &c:s){ pos=vs[pos].nxt[TRIE::conv(c)]; if(heavy) for(auto &x:vs[pos].idxs) res[x]++; else res[0]+=cnt[pos]; } return res; } int move(int pos,char c){ auto &vs=TRIE::vs; assert(pos<(int)vs.size()); return vs[pos].nxt[TRIE::conv(c)]; } int count(int pos){ return cnt[pos]; } int size(){return TRIE::vs.size();} }; //INSERT ABOVE HERE int dp[111][55][55]; signed main(){ int h,w; while(cin>>h>>w,h){ vector<string> ss(h); for(int i=0;i<h;i++) cin>>ss[i]; int p; cin>>p; vector<string> ps(p); for(int i=0;i<p;i++) cin>>ps[i]; auto conv= [&](char c){ if(c=='U') return 0; if(c=='R') return 1; if(c=='D') return 2; if(c=='L') return 3; return -1; }; AhoCorasick<4> aho(conv); for(int i=0;i<p;i++) aho.add(ps[i],i); aho.build(false); memset(dp,-1,sizeof(dp)); using T = tuple<int, int, int>; queue<T> que; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(ss[i][j]=='S'){ dp[0][i][j]=0; que.emplace(0,i,j); } } } string base="URDL"; int dy[]={-1,0,1,0}; int dx[]={0,1,0,-1}; auto in=[&](int y,int x){return 0<=y&&y<h&&0<=x&&x<w;}; int ans=-1; while(!que.empty()){ int p,y,x; tie(p,y,x)=que.front();que.pop(); if(ss[y][x]=='G'){ ans=dp[p][y][x]; break; } for(int k=0;k<4;k++){ int ny=y+dy[k],nx=x+dx[k]; if(!in(ny,nx)||ss[ny][nx]=='#') continue; char c=base[k]; int q=aho.move(p,c); if(aho.count(q)) continue; if(~dp[q][ny][nx]) continue; dp[q][ny][nx]=dp[p][y][x]+1; que.emplace(q,ny,nx); } } cout<<ans<<endl; } return 0; }
#include <bits/stdc++.h> #define rep(i,n) for(int i=0;i<n;++i) using namespace std; int n,m; string maze[55]; int fg[110][5],ac[110]; char dir[5]={' ','U','R','D','L'}; int di[5]={0,-1,0,1,0}; int dj[5]={0,0,1,0,-1}; int build(vector<string> pattern){ memset(fg,-1,sizeof(fg)); memset(ac,0,sizeof(ac)); int root=0,size=1; fg[root][0]=root; rep(i,pattern.size()){ int cur=root; rep(j,pattern[i].size()){ int tar=1; rep(k,5) if(dir[k]==pattern[i][j]) tar=k; if(fg[cur][tar]==-1) fg[cur][tar]=size++; cur=fg[cur][tar]; } ac[cur]++; } queue<int> q; for(int i=1;i<=4;++i){ if(fg[root][i]>=0){ fg[fg[root][i]][0]=root; q.push(fg[root][i]); }else fg[root][i]=root; } while(!q.empty()){ int now=q.front();q.pop(); for(int i=1;i<=4;++i){ if(fg[now][i]>=0){ int tar=fg[now][0]; while(fg[tar][i]==-1) tar=fg[tar][0]; fg[fg[now][i]][0]=fg[tar][i]; ac[fg[now][i]]+=ac[fg[tar][i]]; q.push(fg[now][i]); } } } return size; } typedef tuple<int,int,int> state; int dist[55][55][110]; int bfs(int limit){ memset(dist,-1,sizeof(dist)); int si,sj,gi,gj; rep(i,n)rep(j,m){ if(maze[i][j]=='S') si=i,sj=j; if(maze[i][j]=='G') gi=i,gj=j; } const int root=0; dist[si][sj][root]=0; queue<state> q; q.push(state(si,sj,root)); while(!q.empty()){ int ci,cj,cs; tie(ci,cj,cs)=q.front();q.pop(); for(int i=1;i<=4;++i){ int ni=ci,nj=cj,ns=cs; ni+=di[i],nj+=dj[i]; while(fg[ns][i]==-1) ns=fg[ns][0]; ns=fg[ns][i]; if(ni<0||n<=ni||nj<0||m<=nj) continue; if(maze[ni][nj]=='#') continue; if(ac[ns]>=1) continue; if(dist[ni][nj][ns]==-1){ dist[ni][nj][ns]=dist[ci][cj][cs]+1; q.push(make_tuple(ni,nj,ns)); } } } int ans=-1; rep(gs,limit){ if(dist[gi][gj][gs]>=0){ if(ans==-1) ans=dist[gi][gj][gs]; ans=min(ans,dist[gi][gj][gs]); } } return ans; } int main(void){ while(cin >> n >> m){ if(n==0) break; rep(i,n) cin >> maze[i]; int p; cin >> p; vector<string> pattern; rep(i,p){ string in; cin >> in; pattern.push_back(in); } cout << bfs(build(pattern)) << endl; } return 0; }
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() #define chmax(a,b) (a<b?(a=b,1):0) #define chmin(a,b) (a>b?(a=b,1):0) #define valid(y,x,h,w) (0<=y&&y<h&&0<=x&&x<w) typedef long long ll; typedef pair<int,int> pii; const int INF = 1<<29; const double PI = acos(-1); const double EPS = 1e-8; const int dy[4] = {-1,0,1,0}; const int dx[4] = {0,1,0,-1}; template <class T> struct dice { T t,b,n,s,e,w; // top bottom north south east west int x, y; dice() {t=' ';} dice(int y, int x) : y(y),x(x) { t=0,b=1,n=2,s=3,e=4,w=5; } dice(T t, T b, T n, T s, T e, T w) : t(t),b(b),n(n),s(s),e(e),w(w) {} void roll(T &a, T &b, T &c, T &d) { swap(a,b); swap(b,c); swap(c,d); } void roll_x() { roll(t, n, b, s); } void roll_y() { roll(t, w, b, e); } void roll_z() { roll(s, e, n, w); } vector<dice> all_rolls() { vector<dice> ret; for (int k=0; k<6; (k&1?roll_y():roll_x()),++k) for (int i=0; i<4; roll_z(), ++i) ret.push_back(*this); return ret; } void roll(int d) { if (d == 0) roll(t, s, b, n); else if (d == 1) roll(t, w, b, e); else if (d == 2) roll(t, n, b, s); else roll(t, e, b, w); x+=dx[d]; y+=dy[d]; } void toTable(T *res) { res[0]=t;res[1]=b;res[2]=n; res[3]=s;res[4]=e;res[5]=w; } }; typedef dice<char> Dice; Dice di[8][24]; Dice cube[2][2][2]; int posx[8] = {0,1,0,1,0,1,0,1}; int posy[8] = {0,0,1,1,0,0,1,1}; int posz[8] = {0,0,0,0,1,1,1,1}; const int dx3[6] = {0,0,-1,1,0,0}; const int dy3[6] = {0,0,0,0,1,-1}; const int dz3[6] = {1,-1,0,0,0,0}; bool check(int x, int y, int z, vector<char> &v) { char table[6]; cube[x][y][z].toTable(table); // if (x==1) { // cout << " "; // REP(i,6) cout << table[i] << ","; cout << endl; // } REP(i,6) { int xx=x+dx3[i]; int yy=y+dy3[i]; int zz=z+dz3[i]; int p = -1; if (xx<0) p=0; else if (xx>=2) p=1; else if (yy<0) p=2; else if (yy>=2) p=3; else if (zz<0) p=4; else if (zz>=2) p=5; // if (x==1) { // if (p>=0) cout << v[p] << " "; // cout << p << " " << table[i] << endl; // } if (p==-1 ^ table[i]=='#') return 0; // 内側は必ず黒.外側は黒以外 if (p!=-1 && v[p]!='.'&& v[p]!=table[i]) return 0; // 外側の色 if (p>=0) v[p] = table[i]; } return 1; } bool solve(int cnt, int S, vector<char> v) { // cout << cnt << endl; // FOR(it, v) cout << *it; cout << endl; if (cnt == 8) { set<char> st; FOR(it, v) st.insert(*it); return st.size() == 6; } REP(i,8) { if (S>>i&1) continue; REP(j,24) { int x = posx[cnt]; int y = posy[cnt]; int z = posz[cnt]; cube[x][y][z] = di[i][j]; vector<char> nxt(v); if (!check(x,y,z,nxt)) continue; // cout << i << " " << j << endl; if (solve(cnt+1, S|1<<i, nxt)) return 1; } } return 0; } bool visited[50][50]; char c[50][50]; int main() { int h,w; cin >> h >> w; REP(i,h)REP(j,w)cin>>c[i][j]; char array[8][6]; int num = 0; REP(i,h)REP(j,w)if(c[i][j]!='.'&&!visited[i][j]) { queue<Dice> Q; Q.push(Dice(i,j)); visited[i][j] = 1; while(!Q.empty()) { Dice now = Q.front(); Q.pop(); array[num][now.b] = c[now.y][now.x]; REP(k,4) { int y=now.y+dy[k]; int x=now.x+dx[k]; if (!valid(y,x,h,w)) continue; if (c[y][x] == '.') continue; if (!visited[y][x]) { visited[y][x] = 1; Dice nxt = now; nxt.roll(k); Q.push(nxt); } } } num++; } assert(num == 8); REP(i,num) { // REP(j,6) cout << array[i][j] << " "; cout << endl; char *a = array[i]; Dice tmp(a[0],a[1],a[2],a[3],a[4],a[5]); vector<Dice> V = tmp.all_rolls(); REP(j,V.size()) { di[i][j] = V[j]; } } vector<char> v(6,'.'); cout << (solve(0,0,v)?"Yes":"No") << endl; }
#include <bits/stdc++.h> #define rep(i,n) for(int i=0;i<(int)(n);i++) #define rep1(i,n) for(int i=1;i<=(int)(n);i++) #define all(c) c.begin(),c.end() #define pb push_back #define fs first #define sc second #define show(x) cout << #x << " = " << x << endl #define chmin(x,y) x=min(x,y) #define chmax(x,y) x=max(x,y) using namespace std; typedef array<int,6> Dice; int H,W; int I; string s[50]; int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1}; Dice ds[8]; Dice rot(Dice d,int x){ if(x==0) return Dice{d[4],d[0],d[2],d[3],d[5],d[1]}; if(x==1) return Dice{d[3],d[1],d[0],d[5],d[4],d[2]}; if(x==2) return Dice{d[1],d[5],d[2],d[3],d[0],d[4]}; if(x==3) return Dice{d[2],d[1],d[5],d[0],d[4],d[3]}; if(x==4) return Dice{d[0],d[3],d[1],d[4],d[2],d[5]}; if(x==5) return Dice{d[1],d[2],d[0],d[5],d[3],d[4]}; } void dfs(Dice d,int x,int y){ ds[I][d[5]]=s[x][y]; s[x][y]='.'; rep(i,4){ int nx=x+dx[i],ny=y+dy[i]; if(0<=nx&&nx<H&&0<=ny&&ny<W&&s[nx][ny]!='.') dfs(rot(d,i),nx,ny); } } int main(){ cin>>H>>W; rep(i,H) cin>>s[i]; rep(i,H) rep(j,W) if(s[i][j]!='.'){ Dice d={0,1,2,3,4,5}; dfs(d,i,j); I++; } map<char,int> mp; rep(i,8){ int b=0; set<char> ss; rep(j,6){ if(ds[i][j]=='#') b++; else ss.insert(ds[i][j]),mp[ds[i][j]]++; } if(b!=3||ss.size()!=3){ puts("No"); return 0; } } for(auto p:mp){ if(p.sc!=4){ puts("No"); return 0; } } rep(i,8){ rep(j,3) if(ds[i][j]=='#'&&ds[i][5-j]=='#'){ puts("No"); return 0; } while(ds[i][0]=='#') ds[i]=rot(ds[i],0); int cnt=0; while( (ds[i][1]=='#'||ds[i][2]=='#') && cnt<5) ds[i]=rot(ds[i],4),cnt++; } char c=(*mp.begin()).fs; vector<int> as; rep(i,8){ int cnt=0; while( ds[i][0]!=c && cnt<5) ds[i]=rot(ds[i],5),cnt++; if(cnt<5) as.pb(i); } assert(as.size()==4); char x=ds[as[0]][1]; vector<char> rs; { char xc=x; int cnt=0,pp=0; while(true){ rep(i,4){ if(ds[as[i]][1]==x){ x=ds[as[i]][2]; rs.pb(x); cnt++; break; } } if(x==xc) break; pp++; if(pp==6) break; } if(cnt!=4||pp==6){ puts("No"); return 0; } } for(auto p:mp){ char cc=p.fs; bool ok=1; rep(i,4) if(cc==rs[i]) ok=0; if(cc==c) ok=0; if(ok){ c=cc; break; } } vector<int> bs; rep(i,8){ int cnt=0; while( ds[i][0]!=c && cnt<5) ds[i]=rot(ds[i],5),cnt++; if(cnt<5) bs.pb(i); } assert(bs.size()==4); x=ds[bs[0]][2]; vector<char> ss; { char xc=x; int cnt=0; int pp=0; while(true){ rep(i,4){ if(ds[bs[i]][2]==x){ x=ds[bs[i]][1]; ss.pb(x); cnt++; break; } } if(x==xc) break; pp++; if(pp==6) break; } if(cnt!=4||pp==6){ puts("No"); return 0; } } rep(i,4){ if(ss==rs){ puts("Yes"); return 0; } ss={ss[3],ss[0],ss[1],ss[2]}; } puts("No"); return 0; }
#include<stdio.h> #include<vector> #include<algorithm> using namespace std; char str[60][60]; int h[]={2,3,3,3,3,3,3,3,3,3,3}; int w[]={5,4,4,4,4,4,4,4,4,4,4}; char tkz[11][6][6]={ { "DLU..", "..FRB" }, { "U...", "FRBL", "D..." }, { "U...", "FRBL", ".D.." }, { "U...", "FRBL", "..D." }, { "U...", "FRBL", "...D" }, { ".U..", "FRBL", ".D.." }, { ".U..", "FRBL", "..D." }, { "LU..", ".FR.", "..DB" }, { ".U..", "FRB.", "..DL" }, { "..U.", "FRB.", "..DL" }, { "U...", "FRB.", "..DL" } }; struct cube{ char p[6]; //FRBLUD cube(){} }; char ch[20]="FRBLUD"; cube t[8]; char tmp[6][6]; int black[8][3]={ {1,2,5}, {2,3,5}, {0,1,5}, {0,3,5}, {1,2,4}, {2,3,4}, {0,1,4}, {0,3,4} }; int pat[24][6]={ {0,1,2,3,4,5}, {1,2,3,0,4,5}, {2,3,0,1,4,5}, {3,0,1,2,4,5}, {3,2,1,0,5,4}, {2,1,0,3,5,4}, {1,0,3,2,5,4}, {0,3,2,1,5,4}, {5,1,4,3,0,2}, {1,4,3,5,0,2}, {4,3,5,1,0,2}, {3,5,1,4,0,2}, {3,4,1,5,2,0}, {4,1,5,3,2,0}, {1,5,3,4,2,0}, {5,3,4,1,2,0}, {0,5,2,4,1,3}, {5,2,4,0,1,3}, {2,4,0,5,1,3}, {4,0,5,2,1,3}, {4,2,5,0,3,1}, {2,5,0,4,3,1}, {5,0,4,2,3,1}, {0,4,2,5,3,1} }; int used[8]; char now[8][6]; int solve(int a){ if(a==8){ return 1; } for(int i=0;i<8;i++){ if(!used[i]){ for(int j=0;j<24;j++){ bool ok=true; for(int k=0;k<6;k++)now[a][k]=t[i].p[pat[j][k]]; for(int k=0;k<3;k++){ if(now[a][black[a][k]]!='#'){ ok=false; } } for(int k=0;k<a;k++){ for(int l=0;l<6;l++){ if(now[k][l]!='#'&&now[a][l]!='#'&&now[k][l]!=now[a][l])ok=false; for(int m=0;m<6;m++){ if(l!=m&&now[k][l]!='#'&&now[k][l]==now[a][m])ok=false; } } } if(!ok)continue; // if(ok)printf("OK %d %d %d\n",a,i,j); used[i]=1; if(solve(a+1))return 1; used[i]=0; } } } return 0; } int main(){ int a,b; scanf("%d%d",&a,&b); for(int i=0;i<a;i++)scanf("%s",str[i]); int sz=0; for(int u=0;u<2;u++){ for(int r=0;r<4;r++){ for(int i=0;i<a;i++){ for(int j=0;j<b;j++){ for(int k=0;k<11;k++){ if(i+h[k]>a||j+w[k]>b)continue; bool ok=true; for(int l=0;l<h[k];l++)for(int m=0;m<w[k];m++){ if(str[i+l][j+m]=='.'&&tkz[k][l][m]!='.')ok=false; } if(ok){ for(int l=0;l<h[k];l++)for(int m=0;m<w[k];m++){ if(tkz[k][l][m]!='.'){ for(int n=0;n<6;n++)if(tkz[k][l][m]==ch[n]){ t[sz].p[n]=str[i+l][j+m]; } str[i+l][j+m]='.'; } } sz++; } } } } for(int i=0;i<11;i++){ for(int j=0;j<h[i];j++){ for(int k=0;k<w[i];k++){ tmp[w[i]-1-k][j]=tkz[i][j][k]; } } swap(h[i],w[i]); for(int j=0;j<h[i];j++)for(int k=0;k<w[i];k++)tkz[i][j][k]=tmp[j][k]; } } for(int i=0;i<11;i++){ for(int j=0;j<h[i];j++){ for(int k=0;k<w[i];k++){ if(tkz[i][j][k]=='R')tkz[i][j][k]='L'; else if(tkz[i][j][k]=='L')tkz[i][j][k]='R'; tmp[j][w[i]-1-k]=tkz[i][j][k]; } } for(int j=0;j<h[i];j++)for(int k=0;k<w[i];k++)tkz[i][j][k]=tmp[j][k]; } } /* for(int i=0;i<sz;i++){ for(int j=0;j<6;j++)printf("%c",t[i].p[j]); printf("\n"); }*/ for(int i=0;i<8;i++){ int cnt=0; for(int j=0;j<6;j++){ if(t[i].p[j]!='#')cnt++; } if(cnt!=3){ printf("No\n");return 0; } } int ret=solve(0); if(ret)printf("Yes\n"); else printf("No\n"); }
#include <bits/stdc++.h> using namespace std; // 0: top, 1: front, 2:right, 3:back, 4:left, 5:bottom const vector<vector<string>> dice_map = { {"0...", "1234", "5..."}, {"0...", "1234", ".5.."}, {"0...", "1234", "..5."}, {"0...", "1234", "...5"}, {".0..", "4123", ".5.."}, {".0..", "4123", "..5."}, {"...0", "2341", "..5."}, {"...0", "2341", ".5.."}, {"...0", "2341", "5..."}, {"..0.", "3412", ".5.."}, {"..0.", "3412", "5..."}, {".0..", "4123", "5..."}, {"..025", "341.."}, {"025..", "..143"}, {"..02", "341.", "5..."}, {"40..", ".123", "...5"}, {"..02", "341.", ".5.."}, {"40..", ".123", "..5."}, {"..02", "341.", "..5."}, {"40..", ".123", ".5.."}, {"..02", ".41.", "35.."}, {"40..", ".12.", "..53"}, }; vector<string> rot_map(vector<string> const& v) { const int n = v.size(), m = v[0].size(); vector<string> res(m); for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { res[j] += v[n - i - 1][j]; } } return res; }; using dice = string; constexpr int rot_d[2][6] = { {3, 0, 2, 5, 4, 1}, // Front {0, 4, 1, 2, 3, 5}, // Side }; dice rot_dice(dice const& v, int dir) { dice res(6, ' '); for(int j = 0; j < 6; ++j) { res[j] = v[rot_d[dir][j]]; } return res; } bool is_valid_dice(dice const& d) { bool res = true; for(int i = 0; i < 3; ++i) { res &= isalpha(d[i]) || isdigit(d[i]); res &= d[i + 3] == '#'; } return res; } bool check(vector<dice>& ds, int i) { bool res = false; if(i == 8) { res = true; for(int j = 0; j < 4; ++j) { res &= ds[j][0] == ds[0][0]; // top res &= ds[j + 4][0] == ds[4][0]; // bottom // side res &= ds[j][2] == ds[(j + 1) % 4][1]; //res &= ds[j + 4][1] == ds[(j + 1) % 4 + 4][2]; res &= ds[j][1] == ds[j + 4][2] && ds[j][2] == ds[j + 4][1]; } return res; } else { for(int j = 0; j < 3; ++j) { res |= check(ds, i + 1); rotate(begin(ds[i]), begin(ds[i]) + 1, end(ds[i])); } } return res; } int main() { int h, w; cin >> h >> w; vector<string> v(h); for(auto& s : v) cin >> s; { // check1 map<char, int> cols; for(auto const& s : v) { for(auto const c : s) { if(c == '.' || c == '#') continue; cols[c] += 1; } } bool chk = cols.size() == 6u; for(auto const& p : cols) { chk &= p.second == 4; } if(!chk) { cout << "No" << endl; return 0; } } vector<dice> dices; auto in_range = [&] (int y, int x) { return 0 <= y && y < h && 0 <= x && x < w; }; for(int i = 0; i < h; ++i) { for(int j = 0; j < w; ++j) { for(auto dm : dice_map) { string td; for(int k = 0; k < 4; ++k, dm = rot_map(dm)) { const int n = dm.size(), m = dm[0].size(); if(!in_range(i + n - 1, j + m - 1)) continue; string d(6, '.'); for(int y = i; y < i + n; ++y) { for(int x = j; x < j + m; ++x) { if(dm[y - i][x - j] == '.') continue; d[dm[y - i][x - j] - '0'] = v[y][x]; } } if(d[0] == '.' || d[0] == '#') { d = rot_dice(rot_dice(d, 0), 0); } for(int l = 0; l < 4; ++l, d = rot_dice(d, 1)) { if(!is_valid_dice(d)) continue; td = d.substr(0, 3); } } if(!td.empty()) { dices.push_back(td); } } } } // check sort(begin(dices), end(dices)); bool ans = false; do { ans |= check(dices, 1); } while(!ans && next_permutation(begin(dices) + 1, end(dices))); cout << (ans ? "Yes" : "No") << endl; }
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <set> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(-1.0); #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++) #define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++) #define MEMSET(v, h) memset((v), h, sizeof(v)) struct Dice { int face[6]; // +Z int Top() const { return face[0]; } int &Top() { return face[0]; } // -Z int Bottom() const { return face[1]; } int &Bottom() { return face[1]; } // +X int Right() const { return face[2]; } int &Right() { return face[2]; } // -X int Left() const { return face[3]; } int &Left() { return face[3]; } // +Y int Front() const { return face[4]; } int &Front() { return face[4]; } // -Y int Back() const { return face[5]; } int &Back() { return face[5]; } Dice Rotate(int cnt, int dir) const { if (cnt == 0) { return *this; } if (cnt < 0) { cnt = cnt % 4 + 4; } else { cnt %= 4; } Dice ret; if (dir == 0) { // +X rotate(Y axis rotate) ret.face[0] = face[3]; ret.face[1] = face[2]; ret.face[2] = face[0]; ret.face[3] = face[1]; ret.face[4] = face[4]; ret.face[5] = face[5]; } else if (dir == 1) { // +Y rotate(X axis rotate) ret.face[0] = face[4]; ret.face[1] = face[5]; ret.face[2] = face[2]; ret.face[3] = face[3]; ret.face[4] = face[1]; ret.face[5] = face[0]; } else if (dir == 2) { // Z rotate(Z axis rotate) ret.face[0] = face[0]; ret.face[1] = face[1]; ret.face[2] = face[4]; ret.face[3] = face[5]; ret.face[4] = face[3]; ret.face[5] = face[2]; } else { assert(false); } return ret.Rotate(cnt - 1, dir); } vector<Dice> AllRotate() const { vector<Dice> ret; Dice temp = *this; REP(i, 6) { REP(j, 4) { ret.push_back(temp); temp = temp.Rotate(1, 2); } temp = temp.Rotate(1, i & 1); } return ret; } bool operator<(const Dice &rhs) const { REP(i, 6) { if (face[i] != rhs.face[i]) { return face[i] < rhs.face[i]; } } return false; } }; int h, w; char field[100][100]; bool visit[100][100]; const int dx[4] = { 0, 1, 0, -1 }; const int dy[4] = { 1, 0, -1, 0 }; int dfs(int x, int y, Dice &die) { if (visit[y][x]) { return 0; } visit[y][x] = true; int ret = 1; die.Bottom() = (int)field[y][x]; REP(i, 4) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx < 0 || nx >= w || ny < 0 || ny >= h || field[ny][nx] == '.') { continue; } die = die.Rotate(dx[i], 0); die = die.Rotate(dy[i], 1); ret += dfs(nx, ny, die); die = die.Rotate(-dx[i], 0); die = die.Rotate(-dy[i], 1); } return ret; } int main() { while (scanf("%d %d", &h, &w) > 0) { set<Dice> dice; MEMSET(field, 0); MEMSET(visit, false); REP(y, h) { scanf("%s", field[y]); } REP(sy, h) { REP(sx, w) { if (field[sy][sx] == '.' || visit[sy][sx]) { continue; } Dice die; REP(i, 6) { die.face[i] = -1; } int nret = dfs(sx, sy, die); assert(nret == 6); REP(i, 6) { assert(die.face[i] != -1); } vector<Dice> rolls = die.AllRotate(); FORIT(it, rolls) { dice.insert(*it); } } } FORIT(it1, dice) { FORIT(it2, dice) { if (it1 == it2) { break; } Dice big; big.Top() = it1->Top(); big.Right() = it1->Right(); big.Front() = it1->Front(); big.Bottom() = it2->Bottom(); big.Left() = it2->Left(); big.Back() = it2->Back(); REP(i, 6) { if (big.face[i] == '#') { goto next; } } REP(i, 6) { REP(j, i) { if (big.face[i] == big.face[j]) { goto next; } } } REP(i, 8) { Dice search; search.face[0] = ((i & 1) == 1) ? big.face[0] : (int)'#'; search.face[1] = ((i & 1) == 0) ? big.face[1] : (int)'#'; search.face[2] = ((i & 2) == 2) ? big.face[2] : (int)'#'; search.face[3] = ((i & 2) == 0) ? big.face[3] : (int)'#'; search.face[4] = ((i & 4) == 4) ? big.face[4] : (int)'#'; search.face[5] = ((i & 4) == 0) ? big.face[5] : (int)'#'; if (!dice.count(search)) { goto next; } } puts("Yes"); goto end; next:; } } puts("No"); end:; } }
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} struct Dice{ char f[7]; Dice(){ rep(i,6) f[i] = '?'; } void R(){ char tmp = f[0]; f[0] = f[4]; f[4] = f[5]; f[5] = f[2]; f[2] = tmp; } void L(){ char tmp = f[0]; f[0] = f[2]; f[2] = f[5]; f[5] = f[4]; f[4] = tmp; } void B(){ char tmp = f[0]; f[0] = f[1]; f[1] = f[5]; f[5] = f[3]; f[3] = tmp; } void F(){ char tmp = f[0]; f[0] = f[3]; f[3] = f[5]; f[5] = f[1]; f[1] = tmp; } void CCW(){ char tmp = f[1]; f[1] = f[4]; f[4] = f[3]; f[3] = f[2]; f[2] = tmp; } }; const int dy[4]={1,-1,0,0}; const int dx[4]={0,0,1,-1}; int h,w; string s[55]; bool vis[55][55]; bool IN(int y, int x){ return (0<=y && y<h && 0<=x && x<w && s[y][x]!='.'); } Dice t; void dfs(int y, int x){ vis[y][x] = true; t.f[0] = s[y][x]; rep(i,4){ int ny = y+dy[i], nx = x+dx[i]; if(IN(ny,nx) && !vis[ny][nx]){ if(i==0) t.B(); else if(i==1) t.F(); else if(i==2) t.L(); else if(i==3) t.R(); dfs(ny,nx); if(i==0) t.F(); else if(i==1) t.B(); else if(i==2) t.R(); else if(i==3) t.L(); } } } int black[8][3]={ {2,3,5}, {3,4,5}, {1,4,5}, {1,2,5}, {0,2,3}, {0,3,4}, {0,1,4}, {0,1,2} }; bool solve(){ cin >>h >>w; rep(i,h) cin >>s[i]; vector<Dice> d; rep(i,h)rep(j,w)if(s[i][j]!='.' && !vis[i][j]){ t = Dice(); dfs(i,j); d.pb(t); } assert(d.size() == 8); // rep(i,8){ // rep(j,6) printf(" %c",d[i].f[j]); // printf("\n"); // } rep(i,8){ int b_ct = 0; rep(j,6) b_ct += (d[i].f[j]=='#'); if(b_ct != 3) return false; } vector<int> p(8); rep(i,8) p[i] = i; do{ bool ok = true; vector<vector<char>> aa,bb; for(int i:{0,6}){ t = d[p[i]]; int CT = 0; rep(z1,4){ t.R(); rep(z2,4){ t.F(); rep(z3,4){ t.CCW(); int b_ct = 0; rep(j,3) b_ct += (t.f[black[i][j]]=='#'); if(b_ct == 3){ ++CT; if(i==0){ aa.pb({t.f[0],t.f[1],t.f[4]}); } else{ bb.pb({t.f[2],t.f[3],t.f[5]}); } } } } } if(CT == 0){ ok = false; break; } } if(!ok) continue; // dbg(p); sort(all(aa)); aa.erase(unique(all(aa)), aa.end()); sort(all(bb)); bb.erase(unique(all(bb)), bb.end()); int AA = aa.size(), BB = bb.size(); rep(ai,AA)rep(bi,BB){ char ch[7]; ch[0] = aa[ai][0]; ch[1] = aa[ai][1]; ch[2] = bb[bi][0]; ch[3] = bb[bi][1]; ch[4] = aa[ai][2]; ch[5] = bb[bi][2]; set<char> cols; rep(i,6) cols.insert(ch[i]); if(cols.size() != 6) continue; ok = true; rep(i,8){ bool found = false; t = d[p[i]]; rep(z1,4){ t.R(); rep(z2,4){ t.F(); rep(z3,4){ t.CCW(); int b_ct = 0; rep(j,3) b_ct += (t.f[black[i][j]]=='#'); if(b_ct == 3){ int ok_ct = 0; rep(j,6){ if(t.f[j]!='#'){ ok_ct += (t.f[j] == ch[j]); } } if(ok_ct == 3) found = true; } } } } if(!found){ ok = false; break; } } if(ok) return true; } }while(next_permutation(all(p))); return false; } int main(){ cout << (solve()?"Yes":"No") << endl; return 0; }
#include<bits/stdc++.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define HUGE_NUM 99999999999999999 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct LOC{ LOC(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; //0:上 1:北 2:東 3:西 4:南 5:裏側 struct Dice{ void roll(char dst){ for(int i = 0; i < 6; i++) work[i] = words[i]; switch(dst){ case 'E': setWords(work[3],work[1],work[0],work[5],work[4],work[2]); break; case 'S': setWords(work[1],work[5],work[2],work[3],work[0],work[4]); break; case 'N': setWords(work[4],work[0],work[2],work[3],work[5],work[1]); break; case 'W': setWords(work[2],work[1],work[5],work[0],work[4],work[3]); break; } }; void paint(char ch){ words[5] = ch; } void setWords(char n0,char n1,char n2,char n3,char n4,char n5){ words[0] = n0; words[1] = n1; words[2] = n2; words[3] = n3; words[4] = n4; words[5] = n5; } void init(){ for(int i = 0; i < 6; i++){ words[i] = '@'; } } int count_blank(){ int ret = 0; for(int i = 0; i < 6; i++){ if(words[i] == '@')ret++; } return ret; } void set(Dice arg){ for(int i = 0; i < 6; i++){ words[i] = arg.words[i]; } } char words[6],work[6]; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; char work[55][55],table[55][55]; char order[25] = "NNNNWNNNWNNNENNNENNNWNNN",dir[5] = "NWES"; bool visited[55][55],FLG; Dice dice[8],DICE,BICUBE[2][2][2]; bool rangeCheck(int row,int col){ return row >= 0 && row <= H-1 && col >= 0 && col <= W-1; } void recursive(int depth,Dice dice,int row,int col){ if(depth == 8 || FLG == true)return; dice.paint(table[row][col]); if(dice.count_blank() == 0){ DICE.set(dice); FLG = true; return; } for(int i = 0; i < 4; i++){ int adj_row = row+diff_row[i]; int adj_col = col+diff_col[i]; if(rangeCheck(adj_row,adj_col) == false || table[adj_row][adj_col] == '.')continue; Dice next_dice; next_dice.set(dice); next_dice.roll(dir[i]); recursive(depth+1,next_dice,adj_row,adj_col); } } int main(){ scanf("%d %d",&H,&W); for(int row = 0; row < H; row++){ scanf("%s",work[row]); } //シートを裏返す for(int col = 0; col < W; col++){ for(int row = 0; row < H; row++){ table[row][col] = work[row][W-1-col]; } } for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ visited[row][col] = false; } } //サイコロの表面に色を塗る int index = 0; for(int col = 0; col < W; col++){ for(int row = 0; row < H; row++){ if(table[row][col] != '.' && visited[row][col] == false){ Dice tmp_dice; tmp_dice.init(); FLG = false; recursive(0,tmp_dice,row,col); dice[index++].set(DICE); queue<LOC> Q; visited[row][col] = true; Q.push(LOC(row,col)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ int adj_row = Q.front().row+diff_row[i]; int adj_col = Q.front().col+diff_col[i]; if(rangeCheck(adj_row,adj_col) == false || table[adj_row][adj_col] == '.' || visited[adj_row][adj_col] == true)continue; visited[adj_row][adj_col] = true; Q.push(LOC(adj_row,adj_col)); } Q.pop(); } } } } int black_pos[6][3] = {{0,1,3},{0,2,4},{0,3,4},{1,2,5},{1,3,5},{2,4,5}}; int color_pos[6][3] = {{2,4,5},{1,3,5},{1,2,5},{0,3,4},{0,2,4},{0,1,3}}; int X[6] = {1,0,1,0,1,0}; int Y[6] = {0,1,1,0,0,1}; int Z[6] = {0,0,0,1,1,1}; //dice[0]を(0,0,0)にセットする for(int loop = 0; loop < 24; loop++){ dice[0].roll(order[loop]); if(dice[0].words[0] == '#' && dice[0].words[1] == '#' && dice[0].words[2] == '#'){ BICUBE[0][0][0].set(dice[0]); char color[6]; color[3] = BICUBE[0][0][0].words[3]; color[4] = BICUBE[0][0][0].words[4]; color[5] = BICUBE[0][0][0].words[5]; for(int i = 1; i <= 7; i++){ //(1,1,1)のダイスを設定 bool check[8]; check[0] = true; for(int k = 1; k < 8; k++){ check[k] = false; } check[i] = true; BICUBE[1][1][1].set(dice[i]); for(int k = 0; k < 24; k++){ BICUBE[1][1][1].roll(order[k]); if(BICUBE[1][1][1].words[3] == '#' && BICUBE[1][1][1].words[4] == '#' && BICUBE[1][1][1].words[5] == '#'){ color[0] = BICUBE[1][1][1].words[0]; color[1] = BICUBE[1][1][1].words[1]; color[2] = BICUBE[1][1][1].words[2]; bool color_FLG =true; for(int a = 0; a < 5; a++){ for(int b = a+1; b < 6; b++){ if(color[a] == color[b]){ color_FLG = false; break; } } if(!color_FLG)break; //面の色は全て異なっていないと不可 } if(!color_FLG)continue; for(int loc = 0; loc < 6; loc++){ if(color[loc] == '#'){ color_FLG = false; break; } } if(!color_FLG)continue; int index = 0; int sequence[6]; for(int g = 1; g <= 7; g++){ if(check[g])continue; sequence[index++] = g; } do{ for(int loc = 0; loc < 6; loc++){ //残り6箇所 int x = X[loc]; int y = Y[loc]; int z = Z[loc]; BICUBE[x][y][z].set(dice[sequence[loc]]); bool tmp_FLG = false; for(int b = 0; b < 24; b++){ //位置のループ BICUBE[x][y][z].roll(order[b]); tmp_FLG = true; for(int c = 0; c < 3; c++){ //黒の位置 if(BICUBE[x][y][z].words[black_pos[loc][c]] != '#'){ tmp_FLG = false; break; } } if(!tmp_FLG)continue; for(int c = 0; c < 3; c++){ if(BICUBE[x][y][z].words[color_pos[loc][c]] != color[color_pos[loc][c]]){ tmp_FLG = false; break; } } if(!tmp_FLG)continue; break; } if(!tmp_FLG)break; if(loc == 5){ printf("Yes\n"); return 0; } } }while(next_permutation(sequence,sequence+6)); } } } } } printf("No\n"); return 0; }
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} struct Dice{ int s[6]; void roll(char c){ //the view from above // N //W E // S //s[0]:top //s[1]:south //s[2]:east //s[3]:west //s[4]:north //s[5]:bottom int b; if(c=='E'){ b=s[0]; s[0]=s[3]; s[3]=s[5]; s[5]=s[2]; s[2]=b; } if(c=='W'){ b=s[0]; s[0]=s[2]; s[2]=s[5]; s[5]=s[3]; s[3]=b; } if(c=='N'){ b=s[0]; s[0]=s[1]; s[1]=s[5]; s[5]=s[4]; s[4]=b; } if(c=='S'){ b=s[0]; s[0]=s[4]; s[4]=s[5]; s[5]=s[1]; s[1]=b; } // migi neji if(c=='R'){ b=s[1]; s[1]=s[2]; s[2]=s[4]; s[4]=s[3]; s[3]=b; } if(c=='L'){ b=s[1]; s[1]=s[3]; s[3]=s[4]; s[4]=s[2]; s[2]=b; } } int top() { return s[0]; } int hash(){ int res=0; for(int i=0;i<6;i++) res=res*256+s[i]; return res; } }; vector<Dice> makeDices(Dice d){ vector<Dice> res; for(int i=0;i<6;i++){ Dice t(d); if(i==1) t.roll('N'); if(i==2) t.roll('S'); if(i==3) t.roll('S'),t.roll('S'); if(i==4) t.roll('L'); if(i==5) t.roll('R'); for(int k=0;k<4;k++){ res.push_back(t); t.roll('E'); } } return res; } template<typename T> vector<T> compress(vector<T> v){ sort(v.begin(),v.end()); v.erase(unique(v.begin(),v.end()),v.end()); return v; } template<typename T> map<T, int> dict(const vector<T> &v){ map<T, int> res; for(int i=0;i<(int)v.size();i++) res[v[i]]=i; return res; } //INSERT ABOVE HERE signed main(){ int h,w; cin>>h>>w; vector<string> s(h); for(int i=0;i<h;i++) cin>>s[i]; int dy[]={-1,0,1,0,0}; int dx[]={0,1,0,-1,0}; int dd[6][4]={{4,2,1,3}, {0,2,5,3}, {4,5,1,0}, {4,0,1,5}, {5,2,0,3}, {1,2,4,3}}; struct T{ int y,x,v,p; T(){} T(int y,int x,int v,int p):y(y),x(x),v(v),p(p){} }; auto in=[&](int y,int x){return 0<=y&&y<h&&0<=x&&x<w;}; vector<vector<int> > used(h,vector<int>(w,-1)); vector<vector<int> > dc; auto bfs= [&](int sy,int sx)->void{ queue<T> q; used[sy][sx]=0; q.emplace(sy,sx,0,4); vector<int> vs(6,'#'); while(!q.empty()){ T t=q.front();q.pop(); vs[t.v]=int(s[t.y][t.x]); int pd=0,pv=used[t.y-dy[t.p]][t.x-dx[t.p]]; for(int k=0;k<4;k++) if(dd[t.v][k]==pv) pd=(6-t.p)+(k); pd%=4; //cout<<t.v<<":"<<t.p<<":"<<char(vs[t.v])<<":"<<pv<<" "<<pd<<endl; for(int k=0;k<4;k++){ int ny=t.y+dy[k],nx=t.x+dx[k]; if(!in(ny,nx)||s[ny][nx]=='.'||~used[ny][nx]) continue; used[ny][nx]=dd[t.v][(pd+k)%4]; q.emplace(ny,nx,used[ny][nx],k); } } Dice di; for(int i=0;i<6;i++) di.s[i]=vs[i]; auto ds=makeDices(di); for(Dice d:ds){ if(d.s[0]=='#'||d.s[1]=='#'||d.s[2]=='#') continue; dc.push_back(vector<int>({d.s[0],d.s[1],d.s[2]})); // cout<<char(d.s[0])<<" "<<char(d.s[1])<<" "<<char(d.s[2])<<endl; } }; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(~used[i][j]||s[i][j]=='.') continue; bfs(i,j); } } dc=compress(dc); int m=dc.size(); using D = tuple<int, int, int>; set<D> ss; for(int i=0;i<m;i++) ss.emplace(dc[i][0],dc[i][1],dc[i][2]); auto YES=[&](){cout<<"Yes"<<endl;exit(0);}; for(int i=0;i<m;i++){ for(int j=0;j<i;j++){ int a=dc[i][0],b=dc[i][1],c=dc[i][2]; int d=dc[j][0],e=dc[j][1],f=dc[j][2]; set<int> sc({a,b,c,d,e,f}); if(sc.size()!=6u) continue; //cout<<char(a)<<" "<<char(b)<<" "<<char(c); //cout<<" "<<char(d)<<" "<<char(e)<<" "<<char(f)<<endl; if(!ss.count(D(d,b,e))) continue; if(!ss.count(D(e,b,a))) continue; if(!ss.count(D(a,b,c))) continue; if(!ss.count(D(c,b,d))) continue; if(!ss.count(D(d,e,f))) continue; if(!ss.count(D(e,a,f))) continue; if(!ss.count(D(a,c,f))) continue; if(!ss.count(D(c,d,f))) continue; YES(); } } cout<<"No"<<endl; return 0; }
#include<stdio.h> #include<algorithm> using namespace std; int p[500]; int q[250][500]; int r[250][500]; int ret[500]; int s[500]; int t[250][500]; int u[500]; int v[250][500]; int w[250][500]; int ABS(int a){return max(a,-a);} int LIM=240; int main(){ int a; scanf("%d",&a); for(int i=0;i<a;i++)p[i]=i; for(int i=0;i<LIM;i++){ random_shuffle(p,p+a); printf("?"); for(int j=0;j<a;j++)printf(" %d",p[j]+1); for(int j=0;j<a;j++)q[i][j]=p[j]; printf("\n");fflush(stdout); for(int j=0;j<a;j++)scanf("%d",&r[i][j]); } for(int i=0;i<a;i++)ret[i]=i; random_shuffle(ret,ret+a); int score=0; for(int i=0;i<a;i++)s[ret[i]]=i; for(int i=0;i<LIM;i++){ for(int j=0;j<a;j++){ t[i][q[i][j]]=j; } for(int j=0;j<a;j++)u[j]=ABS(s[j]-t[i][j]); for(int j=0;j<a;j++){ v[i][r[i][j]]++; w[i][u[j]]++; } for(int j=0;j<a;j++)score+=min(v[i][j],w[i][j]); } while(score<LIM*a){ int cl=rand()%a; int cr=rand()%a; if(cl==cr)continue; int nl=ret[cl]; int nr=ret[cr]; // swap(s[ret[cl]],s[ret[cr]]); // swap(ret[cl],ret[cr]); int tmp=score; for(int i=0;i<LIM;i++){ int at[4]; at[0]=ABS(s[nl]-t[i][nl]); at[1]=ABS(s[nl]-t[i][nr]); at[2]=ABS(s[nr]-t[i][nl]); at[3]=ABS(s[nr]-t[i][nr]); if(w[i][at[0]]<=v[i][at[0]])tmp--; w[i][at[0]]--; if(w[i][at[3]]<=v[i][at[3]])tmp--; w[i][at[3]]--; if(w[i][at[1]]<v[i][at[1]])tmp++; w[i][at[1]]++; if(w[i][at[2]]<v[i][at[2]])tmp++; w[i][at[2]]++; w[i][at[0]]++;w[i][at[1]]--;w[i][at[2]]--;w[i][at[3]]++; if(tmp<score-10)break; } if(tmp>=score){ score=tmp; for(int i=0;i<LIM;i++){ int at[4]; at[0]=ABS(s[nl]-t[i][nl]); at[1]=ABS(s[nl]-t[i][nr]); at[2]=ABS(s[nr]-t[i][nl]); at[3]=ABS(s[nr]-t[i][nr]); w[i][at[0]]--;w[i][at[1]]++;w[i][at[2]]++;w[i][at[3]]--; } swap(ret[cl],ret[cr]); swap(s[nl],s[nr]); } } printf("!"); for(int i=0;i<a;i++)printf(" %d",ret[i]+1); printf("\n"); fflush(stdout); }
#include <bits/stdc++.h> using namespace std; using VI = vector<int>; using VVI = vector<VI>; using PII = pair<int, int>; using LL = long long; using VL = vector<LL>; using VVL = vector<VL>; using PLL = pair<LL, LL>; using VS = vector<string>; #define ALL(a) begin((a)),end((a)) #define RALL(a) (a).rbegin(), (a).rend() #define PB push_back #define EB emplace_back #define MP make_pair #define SZ(a) int((a).size()) #define SORT(c) sort(ALL((c))) #define RSORT(c) sort(RALL((c))) #define UNIQ(c) (c).erase(unique(ALL((c))), end((c))) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define FF first #define SS second template<class S, class T> istream& operator>>(istream& is, pair<S,T>& p){ return is >> p.FF >> p.SS; } template<class S, class T> ostream& operator<<(ostream& os, const pair<S,T>& p){ return os << p.FF << " " << p.SS; } template<class T> void maxi(T& x, T y){ if(x < y) x = y; } template<class T> void mini(T& x, T y){ if(x > y) x = y; } const double EPS = 1e-10; const double PI = acos(-1.0); const LL MOD = 1e9+7; LL gcd(LL x, LL y){ if(y == 0) return x; return gcd(y, x%y); } int main(){ cin.tie(0); ios_base::sync_with_stdio(false); LL p, q; cin >> p >> q; LL g = gcd(p,q); LL n = q / g; LL ans = 1; LL ub = n; for(LL i=2;i*i<=ub;++i){ if(n % i == 0) ans *= i; while(n % i == 0) n /= i; } if(n > 1) ans *= n; cout << ans << endl; return 0; }
//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1180 #include <iostream> #include <string> #include <vector> #include <set> #include <map> #include <cmath> #include <algorithm> #include <iomanip> #include <queue> using ll = long long; using namespace std; int const MOD = 1e9 + 7; int GCD(int x, int y) { if (y == 0) return x; return GCD(y, x % y); } int main(void) { ll p, q; cin >> p >> q; int d = GCD(p, q); p /= d; q /= d; int ans = 1; for (int i = 2; i <= sqrt(q); ++i) { if (q % i == 0) { ans *= i; while (1) { if (q % i != 0) break; q /= i; } } } ans *= q; cout << ans << endl; return 0; }
#include<bits/stdc++.h> #define range(i,a,b) for(int i = (a); i < (b); i++) #define rep(i,b) for(int i = 0; i < (b); i++) #define all(a) (a).begin(), (a).end() #define debug(x) cout << "debug " << x << endl; const int INF = 100000000; using namespace std; //?????§??¬?´???° int gcd(int x, int y) { int r; if(x < y) swap(x, y); while(y > 0){ r = x % y; x = y; y = r; } return x; } int main(){ int p, q; cin >> p >> q; q/= gcd(p, q); int ans = 1; for(int i = 2; q >= i * i; i++){ if(q % i == 0){ ans*=i; while(q % i == 0){ q/=i; } } } cout << ans * q << endl; }
#include <iostream> #include <fstream> #include <cstdio> #include <cmath> #include <vector> #include <cstring> #include <string> #include <set> #include <map> #include <stack> #include <queue> #include <algorithm> using namespace std; #define REP(i,n) for(int i=0; i<n; ++i) #define FOR(i,a,b) for(int i=a; i<=b; ++i) #define FORR(i,a,b) for (int i=a; i>=b; --i) #define pi M_PI typedef long long ll; typedef vector<int> VI; typedef vector<ll> VL; typedef vector<VI> VVI; typedef pair<int,int> P; typedef pair<ll,ll> PL; int gcd(int x, int y){ if (y == 0) return x; return gcd(y, x % y); } int main() { int p, q; cin >> p >> q; int d = gcd(p, q); q /= d; ll ans = 1; for (ll i = 2; i * i <= q; i++){ if (q % i == 0){ ans *= i; while (q % i == 0) q /= i; } } cout << ans*q << endl; return 0; }
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; long long int gcd(long long int l, long long int r) { if (l > r)return gcd(r, l); else { if (r%l) { return gcd(l, r%l); } else { return l; } } } map<long long int, int>soinnsuu(long long int a) { map<long long int, int>ans; for (long long i = 2; i*i <= a; ++i) { while (a%i == 0) { ans[i]++; a /= i; } } if (a != 1)ans[a]++; return ans; } int main(){ long long int p,q;cin>>p>>q; long long int num=q/(gcd(p,q)); auto mp=soinnsuu(num); long long int ans=1; for (auto m: mp) { int k=1; for(int j=0;j<k;++j)ans*=m.first; } cout<<ans<<endl; return 0; }
#include <iostream> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int p, q; cin >> p >> q; int g = gcd(p, q); p /= g; q /= g; int ans = 1; for (int i = 2; i * i <= q; i++) { if (q % i != 0) continue; while (q % i == 0) { q /= i; } ans *= i; } ans *= q; cout << ans << endl; return 0; }
#include <iostream> using namespace std; int gcd(int x, int y) { return y == 0 ? x : gcd(y, x%y); } int P, Q; int main() { cin >> P >> Q; int v = Q / gcd(P, Q); for (int d = 2; d*d <= v; ++d) { if (v % d == 0) { while ((v/d)%d == 0) { v /= d; } } } cout << max(2, v) << endl; }
#include <bits/stdc++.h> using namespace std; #define MAX_N 1000000000 int gcd(int a, int b) { if (a < b) return gcd(b, a); else if (a % b) return gcd(b, a % b); else return b; } int main() { int p, q; cin >> p >> q; q /= gcd(p, q); map<int, int> res; for (int i = 2; i * i <= MAX_N; i++) { while (q % i == 0) { q /= i; res[i]++; } } if (q != 1) res[q]++; int ans = 1; for (auto p : res) { ans *= p.first; } cout << ans << endl; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> P; typedef pair<int ,P> P3; typedef pair<P ,P> PP; const ll MOD = ll(1e9+7); const int IINF = INT_MAX; const ll LLINF = LLONG_MAX; const int MAX_N = int(1e5 + 5); const double EPS = 1e-6; const int di[] = {0, 1, 0, -1}, dj[] = {1, 0, -1, 0}; #define REP(i, n) for (int i = 0; i < n; i++) #define REPR(i, n) for (int i = n; i >= 0; i--) #define SORT(v) sort((v).begin(), (v).end()) #define ALL(v) (v).begin(), (v).end() ll gcd(ll p, ll q){ if(p%q==0) return q; else return gcd(q, p%q); } int main() { ll p, q, m, ans=1; cin >> p >> q; m = q/gcd(p,q); for(ll i=2;i*i<=m;i++){ if(m%i==0){ ans *= i; while(m%i==0) m/=i; } } if(m!=1) ans *= m; cout << ans << endl; return 0; }
#include <iostream> #include <vector> using namespace std; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a%b); } int main() { vector<int> prime; vector<bool> is_prime(1e5, true); is_prime[0] = is_prime[1] = false; for(int i=2; i<1e5; ++i) { if(is_prime[i]) { prime.push_back(i); for(int j=i+i; j<100000; j+=i) { is_prime[j] = false; } } } int p, q; cin >> p >> q; int g = gcd(p, q); p /= g, q /= g; int ans = 1; for(int i=0; i<prime.size(); ++i) { if(q % prime[i] == 0) { ans *= prime[i]; while(q % prime[i] == 0) { q /= prime[i]; } } } if(q / ans > 1) { cout << q * ans << endl; } else { cout << ans << endl; } }
#include <iostream> using namespace std; int gcd(int u, int v){ while(v!=0){ int r = u%v; u = v; v = r; } return u; } int main(){ int p,q; cin >> p >> q; q /= gcd(p,q); int ans=1; int rq=q; for(int i=2; i*i<=q; i++){ if(rq%i==0){ ans*=i; } while(rq%i==0){ rq/=i; } } ans *= rq; cout << ans << endl; return 0; }
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> #include <cstdio> #include <functional> #include <numeric> #include <stack> #include <queue> #include <map> #include <set> #include <utility> #include <sstream> #include <complex> #include <fstream> #include <bitset> #include <time.h> using namespace std; typedef long long ll; typedef pair<ll, ll> P; typedef vector<ll> V; typedef complex<double> Point; #define PI acos(-1.0) #define EPS 1e-10 const ll INF = (1LL << 31) - 1; const ll MOD = 1e9 + 7; #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define rep(i,N) for(int i=0;i<(N);i++) #define ALL(s) (s).begin(),(s).end() #define EQ(a,b) (abs((a)-(b))<EPS) #define EQV(a,b) ( EQ((a).real(), (b).real()) && EQ((a).imag(), (b).imag()) ) #define fi first #define se second #define N_SIZE (1LL << 20) #define NIL -1 #define MAX_N 100100 * 3 map<int, int> prime_facter(ll n) { map<int, int> res; for (ll i = 2; i*i <= n; i++) { while (n%i == 0) { ++res[i]; n /= i; } } if (n != 1)res[n] = 1; return res; } ll gcd(ll a, ll b) { if (b == 0)return a; return gcd(b, a%b); } ll p, q; int main() { cin >> p >> q; map<int, int> mii = prime_facter(q / gcd(p, q)); int ans = 1; for (auto it : mii) { ans *= it.first; } cout << ans << endl; }
#include<bits/stdc++.h> using namespace std; #define int long long typedef pair<int,int>pint; typedef vector<int>vint; typedef vector<pint>vpint; #define pb push_back #define mp make_pair #define fi first #define se second #define all(v) (v).begin(),(v).end() #define rep(i,n) for(int i=0;i<(n);i++) #define reps(i,f,n) for(int i=(f);i<(n);i++) #define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++) template<class T,class U>inline void chmin(T &t,U f){if(t>f)t=f;} template<class T,class U>inline void chmax(T &t,U f){if(t<f)t=f;} int gcd(int a,int b){ return b?gcd(b,a%b):a; } signed main(){ int p,q; cin>>p>>q; int g=gcd(p,q); q/=g; for(int i=2;i*i<=q;i++){ if(q%i)continue; while(q%i==0)q/=i; q*=i; } cout<<q<<endl; return 0; }
#include<iostream> #include<algorithm> #include<string> #include<cstdlib> #include<map> #include<iomanip> #include<sstream> #include<vector> #include<stack> #include<math.h> #include<queue> #include<complex> #include<random> #include<ctime> #include<set> using namespace std; const long long int mod=1000000007; const long long int INF=99999999999999999; //ユークリッドの互除法 a,bは最大公約数を求めたい2つの数 class Euclid_Gojyohou{ public: long long int gcd(long long int a, long long int b) { long long int tmp; long long int r = 1; if (b > a) { tmp = a; a = b; b = tmp; } r = a % b; while (r != 0) { a = b; b = r; r = a % b; } return b; } }; int main() { cout << fixed << setprecision(18); long long int b,x=1,y,p,q,tmp; cin>>p>>q; Euclid_Gojyohou euc; q=q/euc.gcd(p,q); tmp=q; for(int i=2;i*i<=q;i++){ if(tmp%i==0){x*=i;} while(tmp%i==0){ tmp/=i; } } cout<<x*tmp<<endl; }
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<map> #include<set> #include<utility> #include<cmath> #include<cstring> #include<queue> #include<stack> #include<cstdio> #include<sstream> #include<iomanip> #include<assert.h> #define loop(i,a,b) for(int i=a;i<b;i++) #define rep(i,a) loop(i,0,a) #define pb push_back #define all(in) in.begin(),in.end() #define shosu(x) fixed<<setprecision(x) using namespace std; //kaewasuretyuui typedef long long ll; typedef int Def; typedef pair<Def,Def> pii; typedef vector<Def> vi; typedef vector<vi> vvi; typedef vector<pii> vp; typedef vector<vp> vvp; typedef vector<string> vs; typedef vector<double> vd; typedef vector<vd> vvd; typedef pair<Def,pii> pip; typedef vector<pip>vip; //#define mt make_tuple //typedef tuple<int,string> tp; //typedef vector<tp> vt; const double PI=acos(-1); const double EPS=1e-7; const int inf=1e9; const ll INF=2e18; int dx[]={0,1,0,-1}; int dy[]={1,0,-1,0}; ll gcd(ll a,ll b){ return (b==0?a:gcd(b,a%b)); } int main(){ ll a,b; cin>>a>>b; ll t=b/gcd(a,b); ll out=1; for(ll i=2;i*i<=t;i++){ if(t%i==0){ out*=i; while(t%i==0)t/=i; } } cout<<out*t<<endl; }
#include <bits/stdc++.h> using namespace std; #define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++) #define REP(i,n) FOR(i,0,n) #define ALL(a) a.begin(), a.end() #define MS(m,v) memset(m,v,sizeof(m)) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<string> vs; typedef pair<int, int> pii; const int MOD = 1e9 + 7; template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); } template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); } template<class T> istream& operator >> (istream& is, vector<T>& v) { for (auto &i : v) is >> i; return is; } template<class T> ostream& operator<<(ostream& os, vector<T>& v) { const string delimiter = "\n"; REP(i, v.size()) { os << v[i]; if (i != v.size() - 1) os << delimiter; } return os; } /*--------------------template--------------------*/ ll gcd(ll a, ll b) { if (a < b) swap(a, b); return (a%b ? gcd(a%b, b) : b); } const int N = 1111111; bool prime[N + 1]; vector<int> primes; void hurui() { memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int i = 2; i*i < N; i++) { if (!prime[i]) continue; for (int j = i; i*j < N; j++) { prime[i*j] = false; } } REP(i, N + 1) { if (prime[i]) primes.push_back(i); } } int main() { cin.sync_with_stdio(false); cout << fixed << setprecision(10); hurui(); ll a, b; cin >> a >> b; ll g = b / gcd(a, b); ll t = g; set<int> st; for (auto p : primes) { if (p > sqrt(g)) break; if (t % p == 0) st.insert(p); while (t % p == 0) t /= p; } st.insert(t); ll ans = 1; for (auto i : st) ans *= i; cout << ans << endl; return 0; }
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstring> #include <vector> #include <set> #include <map> #include <unordered_map> #include <queue> #include <deque> #include <stack> #include <algorithm> #include <bitset> #include <cmath> #include <cstdlib> #include <ctime> #include <numeric> #include <functional> #include <cctype> #include <list> #include <limits> #include <cassert> //#include <boost/multiprecision/cpp_int.hpp> const double EPS = (1e-10); using namespace std; using Int = long long; //using namespace boost::multiprecision; const Int MOD = 1000000007; void fast_input() { cin.tie(0); ios::sync_with_stdio(false); } template<typename T> T gcd(T a, T b) { return b != 0 ? gcd(b, a % b) : a; } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } vector<pair<int, int>> prime_factorization(int n) { int k = n; vector<pair<int, int>> ret; for (int i = 2; i <= sqrt(n); i++) { int cnt = 0; while(k % i == 0) { k /= i; // 重複を許さないならここを while に cnt++; } if (cnt) ret.push_back({i, cnt}); } if(k > 1) ret.push_back({k, 1}); return ret; } int main(void) { int p, q; cin >> p >> q; while (gcd(p, q) != 1) { int tmp = gcd(p, q); p /= tmp; q /= tmp; } vector<pair<int, int>> qfac = prime_factorization(q); int ans = 1; for (int i = 0; i < qfac.size(); i++) { ans *= qfac[i].first; } cout << ans << endl; }
#include <iostream> #include <vector> #include <math.h> using namespace std; int gcd(int a, int b){ int temp1 = a, temp2 = b; if (temp1 < temp2){ int temp; temp = temp1; temp1 = temp2; temp2 = temp; } if(temp2 == 0) return temp1; return gcd(temp2, temp1%temp2); } int main(){ int p, q, m; cin >> p >> q; m = q/gcd(p,q); if(m == 1){ cout << 1 << endl; return 0; } int temp = m, ans = 1; if(temp%2 == 0){ ans *= 2; while(temp % 2 == 0){ temp = temp/2; if(temp == 1) break; } } for(int i = 3;i<=m; i+=2){ if(temp%i == 0){ ans *= i; while(temp % i == 0){ temp = temp/i; if(temp == 1) break; } } } cout << ans << endl; return 0; }
/* main code starts from line 155. */ /* ---------- STL Libraries ---------- */ // IO library #include <cstdio> #include <iomanip> #include <ios> #include <iostream> // algorithm library #include <algorithm> #include <cmath> #include <numeric> // container library #include <array> #include <bitset> #include <map> #include <queue> #include <set> #include <string> #include <vector> /* ---------- Namespace ---------- */ using namespace std; /* ---------- Type Abbreviation ---------- */ template <typename T> using V = vector<T>; template <typename T, typename U> using P = pair<T, U>; template <typename T> using PQ = priority_queue<T>; template <typename T> using GPQ = priority_queue<T, vector<T>, greater<T>>; using ll = long long; #define fst first #define snd second #define pb push_back #define mp make_pair #define mt make_tuple /* ---------- conversion ---------- */ #define INT(c) static_cast<int>(c) #define CHAR(n) static_cast<char>(n) #define LL(n) static_cast<ll>(n) #define DOUBLE(n) static_cast<double>(n) /* ---------- container ---------- */ #define ALL(v) (v).begin(), (v).end() #define SIZE(v) (LL((v).size())) #define FIND(v, k) (v).find(k) != (v).end() #define VFIND(v, k) find(ALL(v), k) != (v).end() #define SORT(v) sort(ALL(v)) #define GSORT(v) sort(ALL(v), greater<decltype((v).front())>()) /* ---------- repetition ---------- */ #define FOR(i, a, b) for (ll i = (a); i <= (b); i++) #define RFOR(i, a, b) for (ll i = (a); i >= (b); i--) /* ---------- Short Functions ---------- */ template <typename T> T sq(T a) { return a * a; } template <typename T> T gcd(T a, T b) { if (a > b) return gcd(b, a); return a == 0 ? b : gcd(b % a, a); } template <typename T> T mypow(T b, T n) { if (n == 0) return 1; if (n == 1) return n; if (n % 2 == 0) { return mypow(sq(b), n / 2); } else { return mypow(b, n - 1) * b; } } /* -------------------- template <typename T> T mypow(T b, T n) { if (n == 0) return 1; if (n == 1) return n % MOD; if (n % 2 == 0) { return mypow(sq(b) % MOD, n / 2); } else { return mypow(b, n - 1) * b % MOD; } } -------------------- */ #define fcout cout << fixed << setprecision(10) /* ----------- debug ---------- */ template <typename T, typename U> void testP2(T a, U b) { cout << "(" << a << ", " << b << ")" << endl; return; } template <typename T> void testV(T v) { cout << "["; for (auto i : v) { cout << i << ", "; } cout << "\b\b]" << endl; return; } template <typename T> void testV2(T v) { for (auto sv : v) { testV(sv); } cout << endl; return; } #define GET_VAR_NAME(variable) #variable #define test(x) cout << GET_VAR_NAME(x) << " = " << x << endl; #define testP(p) \ cout << GET_VAR_NAME(p) << " = "; \ testP2(p.fst, p.snd); /* ---------- Constants ---------- */ // const ll MOD = 1e9 + 7; // const int INF = 1 << 25; // const ll INF = 1LL << 50; // const double PI = acos(-1); // const double EPS = 1e-10; // const ll dx[4] = {0, -1, 1, 0}; // const ll dy[4] = {-1, 0, 0, 1}; // const ll dx[8] = {-1, 0, 1, -1, 1, -1, 0, 1}; // const ll dy[8] = {-1, -1, -1, 0, 0, 1, 1, 1}; /* v-v-v-v-v-v-v-v-v Main Part v-v-v-v-v-v-v-v-v */ /* ---------- Type Definition ----------- */ /* ---------- Global Variance ----------- */ /* ------------- Functions -------------- */ /* ----------- Main Function ------------ */ int main() { cin.tie(0); ios::sync_with_stdio(false); ll p, q; cin >> p >> q; ll mot = q / gcd(p, q); ll ans = 1; while (mot > 1) { bool div = false; for (ll i = 2; sq(i) <= mot; i++) { if (mot % i == 0) { ans *= i; while (mot % i == 0) { mot /= i; } div = true; } } if (!div) { ans *= mot; mot = 1; } } cout << ans << endl; return 0; }
#include<iostream> using namespace std; int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } int main(){ int p, q; cin >> p >> q; int g = gcd(p, q); p /= g, q /= g; int ans = 1; for(int i = 2; i*i <= q; i++){ if(q % i == 0){ ans *= i; while(q % i == 0) q /= i; } } ans *= q; cout << ans << endl; return 0; }
#include<stdio.h> #include<math.h> int gcd(int a,int b){ if(a < b){ int c = a; a = b; b = c; } if(a % b == 0) return b; return gcd(b,a % b); } bool judgeprime(int n){ if(n == 1 || n % 2 == 0) return false; int i,j; j = (int)sqrt(n) + 1; bool k = true; for(i = 3;i < j;i += 2) if(n % i == 0){ k = false; break; } return k; } int nextprime(int prime){ prime++; while(judgeprime(prime++) == false); return prime - 1; } int main(void){ int p,q; scanf("%d%d",&p,&q); q /= gcd(p,q); int prime = 2,ans = 1; while(q > 1){ if(q % prime == 0){ ans *= prime; while(q % prime == 0) q /= prime; } if(judgeprime(q)){ ans *= q; break; } prime = nextprime(prime); } printf("%d\n",ans); return 0; }
#include<cstdio> #include<algorithm> #include<cmath> int era[100000]; using namespace std; int main(void) { int p,q,i,j,kou,x,a,b,suu,flg; scanf("%d %d",&p,&q); a=q; b=p; while(1) { x=a%b; if(x==0) break; a=b; b=x; } for(i=2;i<=100000;i++) era[i]=1; for(i=2;i*i<=100000;i++) { if(era[i]==1) { for(j=2;j*i<=100000;j++) { era[i*j]=0; } } } kou=b; x=q/kou; a=1; for(i=2;i<=100000;i++) { if(era[i]==1 && x%i==0) { a=a*i; while(x%i==0) x/=i; } if(x==1) break; } if(x!=1) a=a*x; printf("%d\n",a); return 0; }
#include <iostream> #define llint long long using namespace std; llint p, q; bool prime[100005]; llint gcd(llint a, llint b) { if(b == 0) return a; return gcd(b, a%b); } int main(void) { cin >> p >> q; llint g = gcd(p, q); p /= g, q /= g; for(int i = 2; i < 1005; i++){ if(prime[i]) continue; for(int j = 2*i; j < 100005; j+=i) prime[j] = true; } llint ans = 1; for(int i = 2; i < 100005; i++){ if(prime[i]) continue; bool flag = false; while(q % i == 0){ q /= i; flag = true; } if(flag) ans *= i; } if(q > 1) ans *= q; cout << ans << endl; return 0; }
#define _CRT_SECURE_NO_WARNINGS #pragma comment (linker, "/STACK:526000000") #include "bits/stdc++.h" using namespace std; typedef string::const_iterator State; #define eps 1e-11L #define MAX_MOD 1000000007LL #define GYAKU 500000004LL #define MOD 998244353LL #define seg_size 262144*2LL #define pb push_back #define mp make_pair typedef long long ll; #define REP(a,b) for(long long (a) = 0;(a) < (b);++(a)) #define ALL(x) (x).begin(),(x).end() unsigned long xor128() { static unsigned long x = 123456789, y = 362436069, z = 521288629, w = time(NULL); unsigned long t = (x ^ (x << 11)); x = y; y = z; z = w; return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))); } void init() { //iostream::sync_with_stdio(false); cout << fixed << setprecision(20); } #define int ll int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } void solve() { int p, q; cin >> p >> q; q /= gcd(p, q); int ans = 1; for (int i = 2; i * i <= q; ++i) { if (q % i == 0) { ans *= i; while (q % i == 0) { q /= i; } } } ans *= q; ans = max(ans, 2LL); cout << ans << endl; } #undef int int main() { init(); solve(); }
#include <iostream> #include <map> #include <cmath> using namespace std; int euclid(int x, int y){ int t; while (x % y){ x %= y; t = x; x = y; y = t; } return y; } int main(){ int p, q, n, m, t = 2, ans = 1; cin >> p >> q; n = q / euclid(p, q); m = n; map<int, int> f; while (n > 1 && t < sqrt(m) + 1){ if (! (n % t)){ n /= t; f[t] = 1; } while (! (n % t)){ ++f[t]; n /= t; } ++t; } if (n != 1) f[n] = 1; for (map<int,int>::iterator itr = f.begin(); itr != f.end(); ++itr){ ans *= itr->first; } cout << ans << endl; return 0; }
#include <iostream> #include <cstdio> #include <cmath> #include <cstdio> #include <cstring> #include <string> #include <vector> #include <set> #include <map> #include <algorithm> #define CH(N,A,B) (A<=N&&N<B) #define REP(i,a,b) for(int i=a;i<b;i++) #define RREP(i,a,b) for(int i=(b-1);a<=i;i--) using namespace std; int gcd(int a,int b) { if (a%b==0) { return(b); } else { return(gcd(b,a%b)); } } int main() { int p, q; cin>>p>>q; q = q/gcd(p,q); /*??????????´??????????????????????*/ //int qq = q/gcd(p,q); int qq = q; long long ans = 1; for(int j=2; j*j<=qq; j++){ if(qq % j == 0){ ans *= j; while(qq % j == 0){ qq /= j; } } } if(qq != 1) ans *= qq; cout<<ans<<endl; return 0; }
#include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <vector> #include <list> #include <map> #include <set> #include <queue> #include <stack> using std::cin; using std::cout; using std::endl; using std::setprecision; using std::fixed; using std::pair; using std::make_pair; using std::string; using std::vector; using std::list; using std::map; using std::set; using std::queue; using std::priority_queue; using std::stack; typedef vector<int> VI; typedef vector<vector<int> > VII; typedef vector<string> VS; typedef pair<int, int> PII; int gcd (int p, int q) { int temp; if (q == 0) { return p; } else { temp = p % q; p = q; q = temp; return gcd(p, q); } return 0; } int main(void) { int p; int q; cin >> p >> q; q /= gcd(p, q); int ans = 1; for (int i = 2; i * i <= q; i++) { if (q == 1) { break; } if (q % i != 0) { continue; } while (q % i == 0) { q /= i; } ans *= i; } cout << ans * q << endl; return 0; }
#include <iostream> using namespace std; long long GCD(long long a, long long b) { if (b == 0) return a; else return GCD(b, a % b); } int main() { long long p, q; cin >> p >> q; long long d = GCD(p, q); q /= d; for (long long v = 2; v*v <= q; ++v) { while (q % (v*v)== 0) q /= v; } cout << q << endl; }
#include <algorithm> #include <cmath> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <vector> #include <cassert> #include <functional> using namespace std; #define LOG(...) printf(__VA_ARGS__) //#define LOG(...) #define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);++i) #define REP(i,n) for(int i=0;i<(int)(n);++i) #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(),(a).rend() #define EXIST(s,e) ((s).find(e)!=(s).end()) #define SORT(c) sort((c).begin(),(c).end()) #define RSORT(c) sort((c).rbegin(),(c).rend()) #define CLR(a) memset((a), 0 ,sizeof(a)) typedef long long ll; typedef unsigned long long ull; typedef vector<bool> vb; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<vb> vvb; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int dx[] = { -1, 0, 1, 0 }; const int dy[] = { 0, 1, 0, -1 }; struct UnionFind { vector<int> v; UnionFind(int n) : v(n) { for (int i = 0; i < n; i++) v[i] = i; } int find(int x) { return v[x] == x ? x : v[x] = find(v[x]); } void unite(int x, int y) { v[find(x)] = find(y); } }; ll gcd(ll a, ll b) { if (a < b) swap(a, b); while (a%b != 0) { a %= b; swap(a, b); } return b; } int main() { map<int, int> mpii; FOR(i, 1, 40000) mpii[i*i] = i; int p, q; cin >> p >> q; q /= gcd(p, q); set<int> soinsu; int copy = q; FOR(i,2,sqrt(copy)+1) { while (q%i == 0) { q /= i; soinsu.insert(i); } } soinsu.insert(q); ll ans = 1; for (int a : soinsu) ans *= a; cout <<ans << endl; }
#include<iostream> using namespace std; int gcd(int x, int y) { return y == 0 ? x : gcd(y, x%y); } int main() { int p, q, r=1; cin >> p >> q; q = q / gcd(q, p); for (int i = 2; i*i <= q; ++i) { if (q%i == 0) { r *= i; while (q%i == 0) q /= i; } } cout << r * q << endl; }
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <cmath> #define REP(i,a,b) for(int i=int(a);i<int(b);i++) using namespace std; typedef long long int lli; lli gcd(lli a, lli b) { if (b == 0) return a; return gcd(b, a % b); } int main () { lli p, q; cin >> p >> q; lli t = gcd(p, q); q /= t; set<int> sl; lli num = q; for (int i = 2; i <= ceil(sqrt(q) + 1e-9); i++) { if (num % i == 0) { sl.insert(i); while (num % i == 0) num /= i; } } sl.insert(num); lli ans = 1; for (auto it : sl) ans *= it; cout << ans << endl; return 0; }
#include<iostream> #include<cstdio> #include<algorithm> #include<string> #include<vector> #include<queue> #include<set> #include<functional> #include<map> using namespace std; int gcd(int a, int b) { if (b == 0)return a; return gcd(b, a%b); } int main() { int a, b; cin >> a >> b; b = b / gcd(a, b); a = b; int c = 1; for (int i = 2; i*i <= a; i++) { if (b%i == 0)c *= i; while (b%i == 0)b /= i; } if (b != 1)c *= b; cout << c << endl; }
#include "bits/stdc++.h" #define REP(i, n, N) for(ll i=(n); i<(N); i++) #define RREP(i, n, N) for(ll i=(N-1); i>=(n); i--) #define LREP(lst,itr) for(auto itr = lst.begin(); itr != lst.end(); ++itr) #define CK(n, a, b) ((a)<=(n)&&(n)<(b)) #define ALL(v) (v).begin(),(v).end() #define MCP(a, b) memcpy(b,a,sizeof(b)) #define P(s) cout<<(s)<<endl #define P2(a, b) cout<<(a)<<" "<<(b)<<endl #define V2(T) vector<vector<T>> typedef long long ll; using namespace std; const ll MOD = 1e9 + 7; const ll INF = 1e18; ll gcd(ll A,ll B){ if(A<B) swap(A,B); return (B==0 ? A : gcd(B,A%B)); } int main(){ ll p,q,tar,ans=1; cin >> p >> q; tar = q/gcd(q,p); for(ll i=2;i*i<=tar;i++){ if(tar%i==0){ ans*=i; while(tar%i==0) tar/=i; } } cout << ans * tar << endl; }
#include <iostream> #include <vector> using namespace std; int main(){ int p,q,use; int so[40000]={0}; cin>>p>>q; use=q; int a; while(q%p!=0){ a=q%p; q=p; p=a; } use/=p; q=use; vector <int> sonaka; for(int i=2;i<40000;i++) if(so[i]==0){ sonaka.push_back(i); for(int j=i*2;j<40000;j+=i) so[j]=1; } int result=1; for(int i=0;sonaka[i]<=use&&i<sonaka.size();i++){ if(use%sonaka[i]==0){ result*=sonaka[i]; while(use%sonaka[i]==0) use/=sonaka[i]; } } cout<<result*use<<endl; return 0; }
#include <bits/stdc++.h> using namespace std; // calculate |gcd|. // if ether num is 0, return 0 long long GCD(long long left, long long right) { if(left == 0 || right == 0) return 0; if(left < 0) left *= -1; if(right < 0) right *= -1; if(left < right) swap(left, right); long long nextnum, ansgcd = -1; while(ansgcd == -1) { nextnum = left % right; if(nextnum == 0) ansgcd = right; left = right; right = nextnum; } return ansgcd; } long long LCM(long long left, long long right) { return left / GCD(left, right) * right; } long long p, q; long long solve(); int main() { cin >> p >> q; cout << solve() << endl; return 0; } long long solve() { long long now = q / GCD(p, q), ans = 1; for(long long i = 2; i * i <= now; ++i) if(now % i == 0) { ans *= i; while(now % i == 0) now /= i; } if(now > 1) ans *= now; return ans; }
#include <iostream> #include <vector> #define REP(i, a, n) for(int i = ((int) a); i < ((int) n); i++) using namespace std; typedef long long ll; int P, Q; bool p[100000]; vector<int> v; int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a % b); } bool prime(int n) { REP(i, 0, v.size()) if(n % v[i] == 0) return false; return true; } ll solve() { ll ans = 1; REP(i, 0, v.size()) if(Q % v[i] == 0) { ans *= v[i]; while(Q % v[i] == 0) Q /= v[i]; } if(prime(Q)) ans *= Q; return ans; } int main(void) { REP(i, 0, 100000) p[i] = true; p[0] = p[1] = false; REP(i, 0, 100000) if(p[i]) for(int j = i * 2; j < 100000; j += i) p[j] = false; REP(i, 0, 100000) if(p[i]) v.push_back(i); cin >> P >> Q; Q = Q / gcd(P, Q); cout << solve() << endl; return 0; }
#include <iostream> #include <map> #include <cmath> using namespace std; int euclid(int x, int y){ int t; while (x % y){ x %= y; t = x; x = y; y = t; } return y; } int main(){ int p, q, n, m, t = 2, ans = 1; cin >> p >> q; n = q / euclid(p, q); m = n; map<int, int> f; while (n > 1 && t < sqrt(m) + 1){ if (! (n % t)){ n /= t; f[t] = 1; } while (! (n % t)){ ++f[t]; n /= t; } ++t; } if (n != 1) f[n] = 1; for (auto itr = f.begin(); itr != f.end(); ++itr){ ans *= itr->first; } cout << ans << endl; return 0; }
#include <iostream> using namespace std; // a>b int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } int main() { int p, q; cin >> p >> q; q /= gcd(p, q); int ans = 1; for (int i = 2; i*i <= q; i++) { if (q%i == 0) { ans *= i; while (q%i == 0) q /= i; } } cout << ans*q << endl;; return 0; }
#include<bits/stdc++.h> #define rep(i,n)for(int i=0;i<n;i++) using namespace std; int gcd(int a, int b) { if (!b)return a; return gcd(b, a%b); } int main() { int p, q; cin >> p >> q; q /= gcd(p, q); map<int, int>m; for (int i = 2; i*i <= q; i++) { while (q%i == 0) { m[i]++; q /= i; } } if (q != 1)m[q] = 1; int c = 1; for (auto i : m) { c *= i.first; } cout << c << endl; }
#include<bits/stdc++.h> using namespace std; using ll = long long; using VI = vector<ll>; using VV = vector<VI>; using VS = vector<string>; using PII = pair<ll, ll>; // tourist set template <typename A, typename B> string to_string(pair<A, B> p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p); string to_string(const string& s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res; } template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; } void debug_out() { cerr << '\n'; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } #ifdef LOCAL #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) #else #define debug(...) 42 #endif // tourist set end template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; } #define FOR(i,a,b) for(ll i=(a);i<(b);++i) #define rep(i,b) FOR(i, 0, b) #define ALL(v) (v).begin(), (v).end() #define p(s) cout<<(s)<<'\n' #define p2(s, t) cout << (s) << " " << (t) << '\n' #define br() p("") #define pn(s) cout << (#s) << " " << (s) << '\n' #define p_yes() p("YES") #define p_no() p("NO") #define SZ(x) ((int)(x).size()) #define SORT(A) sort(ALL(A)) #define RSORT(A) sort(ALL(A), greater<ll>()) #define MP make_pair void no(){p_no(); exit(0);} void yes(){p_yes(); exit(0);} const ll mod = 1e9 + 7; const ll inf = 1e18; const double PI = acos(-1); // 素因数分解 // その素因数が何個あるかのmapを返す map<ll, ll> factorize(ll n){ map<ll, ll> mp; ll sq = sqrt(n); FOR(i, 2, sq+1){ while(n%i==0){ mp[i]++; n/=i; } } // 残り if(n!=1){ mp[n]++; } return mp; } ll gcd(ll a,ll b){ if(b == 0) return a; return gcd(b,a%b); } int main(){ cin.tie(0); ios::sync_with_stdio(false); // input ll p, q; cin >> p >> q; ll g = gcd(p, q); p /= g; q /= g; auto mp = factorize(q); ll ans = 1; for(auto pa : mp){ ans *= pa.first; } p(ans); return 0; }
#include <stdio.h> #include <math.h> int gcd(int a, int b) { int t; while(b) { t = a % b; a = b; b = t; } return a; } int main(void){ int p, q, i, j, ans = 1, bef = 0; scanf("%d%d", &p, &q); q /= gcd(p, q); for(i = 2; i <= sqrt(q) + 1;) { if(!(q % i)) { if(bef != i) ans *= i, bef = i; q /= i; } else ++i; } if(bef != q) ans *= q; printf("%d\n", ans); return 0; }
#include <iostream> #include <vector> using namespace std; int main(){ int p,q,use; int so[40000]={0}; cin>>p>>q; use=q; int a; while(q%p){ a=q%p; q=p; p=a; } use/=p; vector <int> sonaka; for(int i=2;i<40000;i++) if(!so[i]){ sonaka.push_back(i); for(int j=i*2;j<40000;j+=i) so[j]=1; } int result=1; for(int i=0;sonaka[i]<=use&&i<sonaka.size();i++) if(use%sonaka[i]==0){ result*=sonaka[i]; while(use%sonaka[i]==0) use/=sonaka[i]; } cout<<result*use<<endl; return 0; }
#include<bits/stdc++.h> using namespace std; #define N 1000000000 typedef long long int ll; ll gcd(ll a,ll b){ if(b==0)return a; else return gcd(b,a%b); } queue<ll> q; vector<bool> prime(N+1,true); void make(ll M){ prime[0]=prime[1]=false; ll i; for( i=2;i*i<=M+1;i++){ if(prime[i]){ ll j=2; q.push(i); while(i*j<M+1){ prime[i*j]=false; j++; } } } /* for(;i<=M;i++){ if(prime[i])q.push(i); }*/ return; } int main(){ ll a,b; //cout<<"ok"<<endl; cin>>a>>b; //make(max(a,b)); //cout<<"ok"<<endl; //cout<<b/gcd(a,b)<<endl; ll c=b/gcd(a,b); //cout<<c<<endl; ll ans = 1; ll ma = c; for(ll i=2;i*i<=ma;i++){ if(c%i==0){ ans*=i; while(c%i==0)c/=i; } } /*while(!q.empty()){ ll d = q.front(); // cout<<d<<endl; if(c%d==0){ while(c%d==0)c/=d; ans*=d; } q.pop(); }*/ //cout<<ans<<' '<<c<<endl; ans*=c; cout<<ans<<endl; return 0; }
#include <bits/stdc++.h> using namespace std; using vi=vector<int>; using vvi=vector<vi>; using vs=vector<string>; using msi=map<string,int>; using mii=map<int,int>; using pii=pair<int,int>; using vlai=valarray<int>; using ll=long long; #define rep(i,n) for(int i=0;i<n;i++) #define range(i,s,n) for(int i=s;i<n;i++) #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define fs first #define sc second #define pb push_back #define eb emplace_back constexpr int gcd(int a,int b){return b?gcd(b,a%b):a;} constexpr int lcm(int a,int b){return a*b/gcd(a,b);} class Eratosthenes{ public: int n, sqlim; vector<bool> prime; Eratosthenes(int N):n(N+1){ sqlim=(int)ceil(sqrt(n)); prime=vector<bool>(n,1); prime[0]=prime[1]=0; for(int i=2;i<=sqlim;i++) if(prime[i]) for(int j=i*i;j<=n;j+=i) prime[j]=0;} vector<int> primeArray(int s=0, int l=10000){vi ret; for(int i=s;ret.size()!=l;i++) if(prime[i]) ret.push_back(i); return ret;} }; int main(){ int p,q; cin>>p>>q; q/=gcd(p,q); vi v; for(int i=2;i*i<=q;i++){ if(q%i==0){ v.pb(i); while(q%i==0)q/=i; } } v.pb(q); cout<<accumulate(all(v),1,[](int a,int b){return a*b;})<<endl; return 0; }
#include<cstdio> #include<cstring> long long int gcd(long long int p, long long int q) { if(!q) return p; if(q>p) return gcd(q, p); return gcd(q, p%q); } int main(void) { long long int p,q; scanf("%lld%lld",&p,&q); long long int g = gcd(p,q); p/=g; q/=g; long long int b=1; for(long long int i=2; q-1 && i*i<=q; i++) { if(q%i) continue; b*=i; while(!(q%i)) q/=i; } b*=q; printf("%lld\n",b); }
#include <bits/stdc++.h> using namespace std; using ll = int64_t; ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } int main() { ll P, Q; cin >> P >> Q; ll G = gcd(P, Q); Q /= G; ll ans = 1; ll QQ = Q; for(ll i = 2; i * i <= Q; i++) { ll cnt = 0; while(QQ % i == 0) { QQ /= i; cnt++; } if(cnt) ans *= i; } if(QQ > 1) ans *= QQ; cout << max<ll>(2, ans) << endl; return 0; }
#include<iostream> #include <list> #include<stack> #include<queue> #include <vector> #include <set> #include<algorithm> #include<math.h> #include<stdlib.h> #include<string> #include <functional> #include<fstream> #define FOR(k,m,n) for(int (k)=(m);(k)<(n);(k)++) #define REP(i,n) FOR((i),0,(n)) #define LL long long #define CLR(a) memset((a),0,sizeof(a)) #define SZ(x) (int((x).size())) #define WAITING(str) int str;std::cin>>str; #define DEBUGING(str) cout<<str<<endl using namespace std; const LL MOD = 1000000007;// 10^9+7 const int INF = (1 << 30); //変数 LL p, q; //素因数分解 //in: number //out: prime numbers template<typename T> vector<T> prime_factorization(T n) { vector<T> res; T check = 2; while (check*check <= n) { if (n%check == 0) { n /= check; res.push_back(check); } else { check++; } } if (n != 1) res.push_back(n); sort(res.begin(), res.end()); return res; } //最大公約数 //(ユークリッドの互除法) //in: a,b //out: GCD(a,b) template<typename T> T GCD(T a, T b) { if (a < b)swap(a, b); int r = a % b; while (r != 0) { a = b; b = r; r = a % b; } return b; } //サブ関数 //入力 void input() { cin >> p >> q; } //計算 void calc() { LL gcd = GCD(p, q); q /= gcd; auto primes = prime_factorization(q); set<LL> primeKind; for (auto prime : primes)primeKind.insert(prime); LL res = 1; for (auto prime : primeKind)res *= prime; cout << res << endl; } //出力 void output() { } //デバッグ void debug() { int N; cin>>N; } //メイン関数 int main() { input(); calc(); output(); debug(); return 0; }
#include <bits/stdc++.h> #define rep(i,n) for(int i = 0; i < n; i++) using namespace std; typedef long long ll; typedef pair<ll,ll> P; typedef pair<ll,P> PP; const long long int MOD = 1000000007; const int INF = 1000000000; int p, q; int main(){ cin >> p >> q; int pp = p, qq = q; while(qq){ pp %= qq; swap(pp,qq); } q /= pp; int ans = 1; for(int i = 2;;i++){ if(i*i > q) break; if(q%i == 0){ ans *= i; } while(q%i == 0){ q /= i; } } ans *= q; cout << ans << endl; }
#include "bits/stdc++.h" using namespace std; //#define int long long #define DBG 1 #define dump(o) if(DBG){cerr<<#o<<" "<<o<<endl;} #define dumpc(o) if(DBG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;} #define rep(i,a,b) for(int i=(a);i<(b);i++) #define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--) #define each(it,c) for(auto it=(c).begin();it!=(c).end();it++) #define all(c) c.begin(),c.end() const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f; const int MOD = (int)(1e9 + 7); //?????§??¬?´???° int gcd(int x, int y) { return y ? gcd(y, x%y) : x; } //?????????: n??\???????´???° vector<int> getPrimes(int n) { vector<char> is_prime(n + 1, true); is_prime[0] = is_prime[1] = false; for (int i = 2; i*i <= n; i++) if (is_prime[i]) { int j = i + i; while (j <= n) { is_prime[j] = false; j += i; } } vector<int> primes; rep(i, 0, n + 1) if (is_prime[i]) primes.emplace_back(i); return primes; } //?´??????°????§£ vector<int> primeFactorization(int x) { vector<int> primes = getPrimes(sqrt(x)); //???x??\???????´???°???????????????????????°?????? vector<int> factors; for (auto &p : primes) { while (x%p == 0) { x /= p; factors.emplace_back(p); } } if (x != 1)factors.emplace_back(x); return factors; } //??§?¨???§??? vector?????????????´?????????? //v: ??§???????????§?¨??????? ???????????? template<typename T> void compress(vector<T> &v) { sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); } signed main() { int p, q; cin >> p >> q; int g = gcd(p, q); int a = q / g; int ans = 1; vector<int> factors = primeFactorization(a); compress(factors); rep(i, 0, factors.size()) { ans *= factors[i]; } cout << ans << endl; return 0; }
#include <iostream> #include <cmath> using std::cin; using std::cout; using std::endl; int gcd(int n, int m) { if ( n%m == 0 ) { return m; } else { return gcd(m,n%m); } } int main(void) { int p,q; cin >> p >> q; int n = q; int m = p; int l = gcd(n,m); while ( l != 1 ) { n = n/l; m = m/l; l = gcd(n,m); } while ( (int)sqrt(n) == sqrt(n) ) { n = sqrt(n); } for (int i = 2; i*i < n+1; i++) { if ( n%(i*i) == 0 ) { n = n/i; i--; } } cout << n << endl; return 0; }
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <vector> #include <queue> #include <sstream> using namespace std; long long int LCM(long long int a, long long int b){ long long int dummy1, dummy2, dummy; dummy1 = max(a, b); dummy2 = min(a, b); while(true){ dummy = dummy1 % dummy2; dummy1 = dummy2; dummy2 = dummy; if(dummy == 0){ break; } } return (a / dummy1) * (b / dummy1) * dummy1; } long long int GCD(long long int a, long long int b){ long long int dummy1, dummy2, dummy; dummy1 = max(a, b); dummy2 = min(a, b); while(true){ dummy = dummy1 % dummy2; dummy1 = dummy2; dummy2 = dummy; if(dummy == 0){ break; } } return dummy1; } int main(){ int N = 100000; bool a[100000]; for(int i = 0; i < N; i++){ a[i] = true; } a[0] = false; a[1] = false; for(int i = 2; i < N; i++){ if(a[i]){ for(int j = i * 2; j < N; j += i){ a[j] = false; } } } long long int p, q; cin >> p >> q; q = q / GCD(p, q); long long int ans = 1; long long int sq_q = sqrt(q); for(int i = 1; i <= sq_q; i++){ if(a[i] && q % i == 0){ ans *= i; while(q % i == 0){ q /= i; } } } ans *= q; cout << ans << endl; return 0; }
#include"bits/stdc++.h" using namespace std; using ll = int64_t; ll gcd(ll a, ll b) { return (b == 0 ? a : gcd(b, a % b)); } bool isPrime(ll n) { for (ll i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } int main() { ll p, q; cin >> p >> q; ll tar = q / gcd(p, q); if (isPrime(tar)) { cout << tar << endl; return 0; } ll ans = 1; for (ll i = 2; i * i <= tar; i++) { if (tar % i == 0) { ans *= i; while (tar % i == 0) { tar /= i; } if (isPrime(tar)) { ans *= tar; break; } } } cout << ans << endl; }
#include <bits/stdc++.h> #define ll long long #define INF 1000000005 #define MOD 1000000007 #define EPS 1e-10 #define rep(i,n) for(int i=0;i<(int)n;++i) #define each(a, b) for(auto (a): (b)) #define all(v) (v).begin(),(v).end() #define fi first #define se second #define pb push_back #define show(x) cout <<#x<<" = "<<(x)<<endl #define spair(p) cout <<#p<<": "<<p.fi<<" "<<p.se<<endl #define svec(v) cout<<#v<<":";rep(i,v.size())cout<<" "<<v[i];cout<<endl #define sset(s) cout<<#s<<":";each(i,s)cout <<" "<<i;cout<<endl using namespace std; typedef pair<int,int>P; const int MAX_N = 100005; int gcd(int a,int b) { if(a % b == 0){ return b; } return gcd(b,a%b); } int main() { int p,q; cin >> p >> q; q /= gcd(p,q); int mx = (int)(sqrt(q)); int ans = 1; for(int i=2;i<=mx;i++){ if(q % i == 0){ ans *= i; while(q % i == 0){ q /= i; } } } if(q != 1){ ans *= q; } cout << ans << "\n"; return 0; }
#include <bits/stdc++.h> using namespace std; int Prime[100000]={}; void pr(){ Prime[0]=2; int tmp=1,num=1; while(num<100000){ num+=2; int flag=0; for(int i=3;i<=sqrt(num);i+=2) if(num%i==0) flag++; if(flag==0) Prime[tmp++]=num; } } int gcd(int x,int y){ return y?gcd(y,x%y):x; } int main(){ pr(); int p,q; cin>>p>>q; int a=q/gcd(p,q); //while(sqrt(a)*sqrt(a)==a) a=sqrt(a); for(int i=0;a/Prime[i]>=Prime[i];++i){ int tmp=a; while(a%Prime[i]==0) a=a/Prime[i]; if(tmp!=a) a*=Prime[i]; } cout << a << endl; return 0; }