text
stringlengths
49
983k
#include<iostream> #include<list> #include<string> #include<algorithm> #include <utility> #include<stdio.h> #include<climits> using namespace std; int main(void){ int n,m; int c,d; int f[1000] = {}; cin >> n >> m; int i,j; for(i = 0;i < m;i++){ cin >> c >> d; for(j = c;j < d;j++){ f[j] = 1; } } for(i = 0,j = 0;i < n;i++){ if(f[i]) j++; } cout << n+1+2*j << endl; }
#include<iostream> using namespace std; int main(){ int n,m; cin >> n >> m; int p[1050]={}; int i,j,k; for(i=0;i<m;i++){ cin >> j >> k; p[j]=max(p[j],k); } int inf = 1<<15; int dp[1050][1050]; fill(dp[0],dp[1049],inf); dp[0][0]=0; i=0; for(j=max(i+1,p[i+1]);j<=n+1;j++){ dp[j][i+1]=min(dp[j][i+1],dp[i][i]+2*(j-i)-1); } for(i=1;i<=n+1;i++){ if(i>=p[i]) dp[i][i]=min(dp[i][i],dp[i-1][i-1]+1); for(j=p[i];j<=n+1;j++){ dp[j][i]=min(dp[j][i],dp[j][i-1]+1); } for(j=max(i+1,p[i+1]);j<=n+1;j++){ dp[j][i+1]=min(dp[j][i+1],dp[i][i]+2*(j-i)-1); } } //cout << dp[1000][2] << endl; /* for(i=0;i<=10;i++){ for(j=0;j<=10;j++){ //cout << dp[j][i] << " "; printf("%3d ", dp[j][i]); } cout << endl; } */ /* for(i=990;i<=1001;i++){ for(j=990;j<=1001;j++){ //cout << dp[j][i] << " "; printf("%3d ", dp[j][i]); } cout << endl; } */ int o=inf; o=min(o,dp[n+1][n+1]); cout << o << endl; return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr) #define all(x) (x).begin(),(x).end() #define mp make_pair #define pb push_back #define fi first #define se second typedef pair<int,int> pi; int main() { int n,m; cin >>n >>m; vector<pi> s; //c?????????d?????????????????¨?????? rep(i,m) { int c,d; scanf(" %d %d",&c,&d); if(c<d) s.pb(pi(c,d)); } sort(all(s)); int ans=n+1; int back=s[0].fi; int now=s[0].se; if(m>0) { rep(i,m-1) { if(now<s[i+1].fi) { ans+=2*(now-back); back=s[i+1].fi; now=s[i+1].se; } else { now=max(now,s[i+1].se); } } ans+=2*(now-back); } printf("%d\n", ans); return 0; }
#include"bits/stdc++.h" using namespace std; using ll = int64_t; int main() { ll N, m; cin >> N >> m; vector<ll> restricts(N, -1); for (int i = 0; i < m; i++) { ll c, d; cin >> c >> d; c--; d--; restricts[c] = max(restricts[c], d); } ll ans = 0; ll left = INT_MAX; ll right = -1; for (ll curr_pos = 0; curr_pos < N; curr_pos++) { if (restricts[curr_pos] != -1) { right = max(right, restricts[curr_pos]); left = min(left, curr_pos); } else { if (curr_pos == right) { ans += 2 * (right - left); left = INT_MAX; } } ans++; } cout << ans + 1 << endl; }
#include<bits/stdc++.h> using namespace std; int n,m; bool b[3000]={}; int main(){ cin>>n>>m; while(m--){ int l,r; cin>>l>>r; for(int i=l;i<r;i++){ b[i]=true; } } int ans=0; for(int i=0;i<n+1;i++){ if(b[i]) ans+=3; else ans++; } cout<<ans<<endl; }
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; template<class T> using Table = vector<vector<T>>; int main() { int N,m; cin >> N >> m; vector<int>backs(N, false); for (int i = 0; i < m; ++i) { int t, f; cin >> t >> f; t--; f--; for (int j = t; j < f; ++j) { backs[j] = true; } } int ans = 1+N + 2*accumulate(backs.begin(), backs.end(), 0); cout << ans << endl; return 0; }
#include <bits/stdc++.h> using namespace std; int main(){ int N,M; cin >> N >> M; vector< pair<int,int> > e; int ans = N + 1 ; for(int i = 0 ; i < M ; i++){ int a,b; cin >> a >> b; e.push_back(make_pair(a,b)); } if( M == 0 ){ cout << ans << endl; return 0; } sort(e.begin(),e.end()); int le = e[0].first; int ri = e[0].second; for(int i = 1 ; i < M ; i++){ if( ri < e[i].first ){ ans += 2 * (ri - le); le = e[i].first; ri = e[i].second; }else ri = max(ri,e[i].second); } ans += 2 * (ri-le); cout << ans << endl; }
#include <bits/stdc++.h> using namespace std; #define int long long // <-----!!!!!!!!!!!!!!!!!!! #define rep(i,n) for (int i=0;i<(n);i++) #define rep2(i,a,b) for (int i=(a);i<(b);i++) #define rrep(i,n) for (int i=(n)-1;i>=0;i--) #define rrep2(i,a,b) for (int i=(b)-1;i>=(a);i--) #define all(a) (a).begin(),(a).end() typedef long long ll; typedef pair<int, int> Pii; typedef tuple<int, int, int> TUPLE; typedef vector<int> V; typedef vector<V> VV; typedef vector<VV> VVV; typedef vector<vector<int>> Graph; const int inf = 1e9; const int mod = 1e9 + 7; signed main() { std::ios::sync_with_stdio(false); std::cin.tie(0); int N, m; cin >> N >> m; vector<Pii> v(m); rep(i, m) cin >> v[i].first >> v[i].second; sort(all(v)); vector<Pii> u; rep(i, m) { if (!u.empty() && v[i].first <= u.back().second) { u.back().second = max(u.back().second, v[i].second); } else u.emplace_back(v[i]); } int ans = N + 1; for (auto p : u) { ans += 2 * (p.second - p.first); } cout << ans << endl; }
#include <bits/stdc++.h> #define For(i, a, b) for(int (i)=(int)(a); (i)<(int)(b); ++(i)) #define rFor(i, a, b) for(int (i)=(int)(a)-1; (i)>=(int)(b); --(i)) #define rep(i, n) For((i), 0, (n)) #define rrep(i, n) rFor((i), (n), 0) #define fi first #define se second using namespace std; typedef long long lint; typedef unsigned long long ulint; typedef pair<int, int> pii; template<class T> bool chmax(T &a, const T &b){if(a<b){a=b; return true;} return false;} template<class T> bool chmin(T &a, const T &b){if(a>b){a=b; return true;} return false;} template<class T> T div_floor(T a, T b){ if(b < 0) a *= -1, b *= -1; return a>=0 ? a/b : (a+1)/b-1; } template<class T> T div_ceil(T a, T b){ if(b < 0) a *= -1, b *= -1; return a>0 ? (a-1)/b+1 : a/b; } constexpr lint mod = 1e9+7; constexpr lint INF = mod * mod; constexpr int MAX = 200010; int main(){ int n, m; scanf("%d%d", &n, &m); int a[n+2]; memset(a, 0, sizeof(a)); rep(i, m){ int c, d; scanf("%d%d", &c, &d); ++a[c]; --a[d]; } partial_sum(a, a+n+2, a); int ans = n+1; int l = 0; while(l < n+1){ if(a[l] == 0){ ++l; continue; } int r = l; while(r < n+1 && a[r] > 0) ++r; ans += (r-l) * 2; l = r; } printf("%d\n", ans); }
#include <iostream> #include <vector> #include <string> #include <cstring> #include <algorithm> #include <sstream> #include <map> #include <set> #define REP(i,k,n) for(int i=k;i<n;i++) #define rep(i,n) for(int i=0;i<n;i++) #define INF 1<<30 #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair<int,int> P; int main() { int n, m; cin >> n >> m; vector<int> c(m), d(m); rep(i, m) cin >> c[i] >> d[i]; int cnt[1005]; memset(cnt, 0, sizeof(cnt)); rep(i, m) { REP(j, c[i], d[i]) { cnt[j]++; } } int ans = 3 * (n + 1); rep(i, n + 1) { if(cnt[i] == 0) { ans -= 2; } } cout << ans << endl; return 0; }
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define MAX 600 struct rest{ int start, end; inline void set(int a, int b){ start = a; end = b; } bool operator < (const rest &a) const { return end < a.end; } } rests[MAX]; int n, m, restlen; bool exist[MAX]; int main(){ int a, b; while(scanf("%d%d", &n, &m) == 2){ restlen = 0; memset(exist, true, sizeof(exist)); for(int i = 0; i < m; i++){ scanf("%d%d", &a, &b); if(a < b){ rests[restlen].start = a; rests[restlen].end = b; restlen++; } } sort(rests, rests + restlen); for(int i = 0; i < m; i++){ for(int j = i - 1; j >= 0; j--) if(exist[j] && rests[j].end >= rests[i].start){ rests[i].start = min(rests[i].start, rests[j].start); exist[j] = false; } } int ans = n + 1; for(int i = 0; i < m; i++) if(exist[i]) ans += (rests[i].end - rests[i].start) << 1; printf("%d\n", ans); } return 0; }
#include<bits/stdc++.h> using namespace std; #define int long long #define MOD ((int)1e9+7) #define MAX 2000 int N, m, ans; int c[MAX], d[MAX]; int temp[MAX]; signed main(){ cin>>N>>m; for(int i = 0; i < m; i++){ cin>>c[i]>>d[i]; temp[c[i]]++; temp[d[i]]--; } for(int i = 0; i <= N; i++){ temp[i+1] += temp[i]; } for(int i = 1; i < N; i++){ if(temp[i]) ans += 2; } cout<<ans+N+1<<endl; return 0; }
#include <cstdio> int n,m; int c[501],d[501]; int cnt[1001]; int main(void){ scanf("%d %d",&n,&m); for(int i=0;i<m;i++){ scanf("%d %d",&c[i],&d[i]); for(int j=c[i];j<d[i];j++){ cnt[j]=1; } } int res=n+1; for(int i=0;i<=n;i++){ res+=cnt[i]*2; } printf("%d\n",res); return 0; }
/* * c.cc: */ #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<string> #include<vector> #include<map> #include<set> #include<stack> #include<list> #include<queue> #include<deque> #include<algorithm> #include<numeric> #include<utility> #include<complex> #include<functional> using namespace std; /* constant */ const int MAX_N = 1000; const int MAX_M = 500; /* typedef */ typedef pair<int,int> pii; /* global variables */ pii rvs[MAX_M]; /* subroutines */ /* main */ int main() { int n, m; cin >> n >> m; for (int i = 0; i < m; i++) cin >> rvs[i].first >> rvs[i].second; sort(rvs, rvs + m); int sum = 0, pci = -1, pdi = -1; for (int i = 0; i < m; i++) { int &ci = rvs[i].first, &di = rvs[i].second; if (pdi >= ci) { if (pdi < di) pdi = di; } else { sum += pdi - pci; pci = ci, pdi = di; } } sum += pdi - pci; printf("%d\n", n + 1 + sum * 2); return 0; }
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<map> #include<set> #include<utility> #include<cmath> #include<cstring> #include<queue> #include<cstdio> #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 mp make_pair #define all(in) in.begin(),in.end() const double PI=acos(-1); const double EPS=1e-10; const int inf=1e8; using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pii; int main(){ int n,m; cin>>n>>m; vi in(m); rep(i,m)cin>>in[i]; int ma=in[0]-1; rep(i,m-1){ int q=in[i+1]-in[i]; q/=2; ma=max(ma,q); } ma=max(ma,n-in[m-1]); cout<<ma<<endl; }
#include <bits/stdc++.h> using namespace std; int main() { int N, M; cin >> N >> M; long long int ans = LLONG_MIN / 6; long long int now; cin >> ans; now = ans; ans--; for( size_t i = 1; i < M; i++ ) { long long int a; cin >> a; ans = max( (a - now) / 2, ans ); now = a; } ans = max( N - now, ans ); cout << ans << endl; }
#include<bits/stdc++.h> using namespace std; const int INF = 1 << 28; int N, M, B[100000]; int dp[100000][4]; int rec(int idx, int dir) { if(idx < 0 || idx >= N) return(INF); if(~dp[idx][dir + 1]) return(dp[idx][dir + 1]); if(B[idx]) return(0); return(dp[idx][dir + 1] = rec(idx + dir, dir) + 1); } int main() { fill_n(*dp, 4 * 100000, -1); cin >> N >> M; for(int i = 0; i < M; i++) { int A; cin >> A; B[--A] = true; } int ret = 0; for(int i = 0; i < N; i++) { ret = max(ret, min(rec(i, -1), rec(i, +1))); } cout << ret << endl; }
#include <bits/stdc++.h> using namespace std; #define _MACRO(_1, _2, _3, NAME, ...) NAME #define _repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define _rep(i,n) _repl(i,0,n) #define rep(...) _MACRO(__VA_ARGS__, _repl, _rep)(__VA_ARGS__) #define mp make_pair #define pb push_back #define all(x) begin(x),end(x) #define uniq(x) sort(all(x)),(x).erase(unique(all(x)),end(x)) #define fi first #define se second #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__) void _dbg(string){cerr<<endl;} template<class H,class... T> void _dbg(string s,H h,T... t){int l=s.find(',');cerr<<s.substr(0,l)<<" = "<<h<<", ";_dbg(s.substr(l+1),t...);} 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;} int main(){ int n,m; cin>>n>>m; vector<int> a(m); rep(i,m) cin>>a[i]; int ans = max(a[0]-1, n - a.back()); rep(i,m-1){ ans = max(ans, (a[i+1] - a[i])/2); } cout << ans << endl; return 0; }
#include <iostream> using namespace std; int main() { int n, m; int a, last_a; int max_diff = 0; int diff; cin >> n >> m; cin >> a; last_a = a; max_diff = a -1; for (int i = 1; i < m; i++) { cin >> a; diff = a - last_a - 1; !(diff % 2) ? diff /= 2 : diff = diff / 2 + 1; if (diff > max_diff) max_diff = diff; last_a = a; } if (n - a > max_diff) max_diff = n - a; cout << max_diff << endl; }
#include<bits/stdc++.h> #define rep(i,n) for(int i=0;i<(int)n;i++) #define all(c) (c).begin(),(c).end() #define mp make_pair #define pb push_back #define each(i,c) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();i++) #define dbg(x) cerr<<__LINE__<<": "<<#x<<" = "<<(x)<<endl using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> pi; const int inf = (int)1e9; const double INF = 1e12, EPS = 1e-9; int a[100000]; int main(){ int n, m; cin >> n >> m; int ans = 0; rep(i, m) cin >> a[i]; rep(i, m - 1) ans = max(ans, (a[i + 1] - a[i]) / 2); ans = max(ans, a[0] - 1); ans = max(ans, n - a[m - 1]); cout << ans << endl; return 0; }
#include <iostream> #include <vector> using namespace std; int main(){ int n,m; cin >> n >> m; if(m == 1){ int a; cin >> a; cout << max(a-1,n-a) << endl; return 0; } vector<int> a(m); for(int i = 0; i < m; i++){ cin >> a[i]; } int ans = 0; for(int i = 0; i < m-1; i++){ ans = max(ans,(a[i+1]-a[i])/2); } ans = max(ans,max(a[0]-1,n-a[m-1])); cout << ans << '\n'; return 0; }
#include<iostream> #include<algorithm> using namespace std; int main(){ int n, m, a[100000], ans=0; cin>>n>>m; for(int i=0;i<m;i++) cin>>a[i]; for(int i=1;i<m;i++) ans=max(ans, (a[i]-a[i-1])/2); ans=max(ans, a[0]-1); ans=max(ans, n-a[m-1]); cout<<ans<<endl; return 0; }
#define _USE_MATH_DEFINES #include <iostream> #include <fstream> #include<vector> #include<algorithm> using namespace std; struct init{ init(){ cin.tie(0); ios::sync_with_stdio(false); } }________init; int main() { #ifdef INPUT_FROM_FILE ifstream cin("sample.in"); ofstream cout("sample.out"); #endif int n, m; cin >> n >> m; vector<int> a(m); for (auto& it : a){ cin >> it; } int res = 0; res = max(res, n - a[m - 1]); res = max(res, a[0] - 1); for (int i = 1; i < m; i++){ res = max(res, (a[i] - a[i - 1]) / 2); } cout << res << endl; return 0; }
#include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <complex> #include <queue> #include <deque> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <iomanip> #include <assert.h> #include <array> #include <cstdio> #include <cstring> #include <random> #include <functional> #include <numeric> #include <bitset> using namespace std; #define REP(i,a,b) for(int i=a;i<(int)b;i++) #define rep(i,n) REP(i,0,n) #define all(c) (c).begin(), (c).end() #define zero(a) memset(a, 0, sizeof a) #define minus(a) memset(a, -1, sizeof a) template<class T1, class T2> inline bool minimize(T1 &a, T2 b) { return b < a && (a = b, 1); } template<class T1, class T2> inline bool maximize(T1 &a, T2 b) { return a < b && (a = b, 1); } typedef long long ll; int const inf = 1<<29; int main() { int N, M; cin >> N >> M; vector<int> v(N, inf); rep(i, M) { int x; cin >> x; x--; v[x] = 0; } REP(i, 1, N) { v[i] = min(v[i], v[i-1] + 1); } for(int i=N-2; i>=0; i--) { v[i] = min(v[i], v[i+1] + 1); } cout << *max_element(all(v)) << endl; return 0; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int n,m; cin >> n >> m; vector<int> a(m); cin >> a[0]; int ma=0; for(int i=1;i<m;i++){ cin >> a[i]; int tmp = (a[i]-a[i-1])/2; ma = max(ma,tmp); } //cout << ma << endl; // cout << a[0]-1 << endl; ma = max(ma,n-a[m-1]); if(ma <= a[0]-1){ cout << a[0]-1 << endl; }else{ cout << ma << endl; } }
#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin >> n >> m; int d[n],d2[n],ans=0; fill(d,d+n,1<<29); fill(d2,d2+n,1<<29); for(int i=0,x; i<m; i++) { cin >> x; d[x-1]=d2[x-1]=0; } for(int i=1; i<n; i++) d[i]=min(d[i],d[i-1]+1); for(int i=n-2; i>=0; i--) d2[i]=min(d2[i],d2[i+1]+1); for(int i=0; i<n; i++) ans=max(ans,min(d[i],d2[i])); cout << ans << endl; return 0; }
/* * a.cc: */ #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<string> #include<vector> #include<map> #include<set> #include<stack> #include<list> #include<queue> #include<deque> #include<algorithm> #include<numeric> #include<utility> #include<complex> #include<functional> using namespace std; /* constant */ const int MAX_N = 100000; /* typedef */ /* global variables */ int as[MAX_N]; /* subroutines */ /* main */ int main() { int n, m; cin >> n >> m; for (int i = 0; i < m; i++) (cin >> as[i]), as[i]--; int ans = max(as[0], n - 1 - as[m - 1]); for (int i = 0; i < m - 1; i++) { int c = (as[i + 1] - as[i]) / 2; if (ans < c) ans = c; } printf("%d\n", ans); return 0; }
#include <bits/stdc++.h> using namespace std; int t[100000]; int main(){ int n,m; cin>>n>>m; vector<int> a(m); for(int i=0;i<n;i++) t[i]=1e9; queue<int> q; for(int i=0;i<m;i++){ cin>>a[i]; a[i]--; t[a[i]]=0; q.push(a[i]); } while(!q.empty()){ int cur=q.front(); q.pop(); if(cur+1<n){ if(t[cur+1]>t[cur]+1){ t[cur+1]=t[cur]+1; q.push(cur+1); } } if(cur-1>=0){ if(t[cur-1]>t[cur]+1){ t[cur-1]=t[cur]+1; q.push(cur-1); } } } int ans=0; for(int i=0;i<n;i++) ans=max(ans,t[i]); cout<<ans<<endl; return 0; }
#include <iostream> #include <vector> #include <string> #include <sstream> #include <algorithm> #include <map> #include <set> #include <cstdio> #include <cmath> #include <cstring> #include <stack> #include <queue> #include <utility> #define rep(i,l,n) for(lint i=l;i<n;i++) #define rer(i,l,n) for(lint i=l;i<=n;i++) #define all(a) a.begin(),a.end() #define o(a) cout<<a<<endl #define fi first #define se second using namespace std; typedef long long lint; typedef vector<int> vi; typedef vector<lint> vli; typedef vector<vi> vvi; typedef pair<int,int> pii; int main(){ int n,m; cin>>n>>m; vi know(m+1); rep(i,0,m) cin>>know[i]; know[m]=1e8; int MAX=0,l=0,r=1; rep(i,1,n+1){ if(i==know[r]){ l=r; r++; } int tmp=min(know[r]-i,abs(i-know[l])); MAX=max(tmp,MAX); } o(MAX); }
#define _USE_MATH_DEFINES #include<stdio.h> #include<stdlib.h> #include<algorithm> #include<vector> #include<string> #include<queue> #include<iostream> #include<fstream> #include<iomanip> using namespace std; int n, m; int data[100000]; int main(){ scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i){ scanf("%d", &data[i]); } int Max = data[0] - 1; for (int i = 1; i < m; ++i) { if ((data[i] - data[i - 1])/2>Max){ Max = (data[i] - data[i - 1])/2; } } if (n - data[m - 1] > Max) { Max = n - data[m - 1]; } printf("%d\n", Max); return 0; }
#include <bits/stdc++.h> using namespace std; #define int long long #define pb push_back #define mp make_pair #define fr first #define sc second #define Rep(i, n) for( int i = 0; i < (n); i++ ) #define Rrep(i, a, n) for( int i = (a); i < (n); i++ ) #define All(v) v.begin(), v.end() typedef pair<int, int> Pii; typedef pair<int, Pii> Pip; const int INF = 1107110711071107; signed main() { int n, m; cin >> n >> m; int a[100010]; Rep(i, m) cin >> a[i]; int mx = 0; for ( int i = 0; i < m-1; i++ ) { mx = max(mx, (a[i+1]-a[i]) / 2); } cout << max(mx, max(a[0]-1, n - a[m-1])) << endl; }
#include <iostream> #include <queue> #define REP(i,a,b) for(int i=a;i<(int)b;i++) #define rep(i,n) REP(i,0,n) using namespace std; int main() { int n; cin >> n; int m; cin >> m; vector<int> a; rep(i, m) { int x; cin >> x; x--; a.push_back(x); } int ans = 0; REP(i, 0, (int)a.size()-1) { ans = max(ans, (a[i+1]-a[i]) / 2); } if(a[0] != 0) { ans = max(ans, a[0]); } if(a[m-1] != n-1) { ans = max(ans, n - a[m-1] - 1); } cout << ans << endl; return 0; }
#include<bits/stdc++.h> #define rep(i,n) for(int i=0;i<n;++i) #define FOR(i,a,b) for(int i=a;i<=b;++i) #define LL long long #define Fi first #define Se second using namespace std; static const LL INF = 1LL<<61LL; typedef pair<int,int> PII; int N,M; int A[100010]; int temp=1; int ans; int main(){ cin>>N>>M; rep(i,M){ int a; cin>>a; A[a]=1; } FOR(i,1,N){ //cout<<temp<<endl; if(A[i]==1){ if(temp==1&&A[1]!=1){ int t=(i-temp); temp=i; ans=max(ans,t); continue; } int t=(i-temp-1)/2; if(i-temp-1<=0)t=0; else if((i-temp-1)%2!=0)t++; temp=i; ans=max(ans,t); } else if(i==N){ ans=max(ans,N-temp); } } cout<<ans<<endl; }
#include <iostream> using namespace std; int main(){ int n,m,a[100000],r=0;; cin>>n>>m; for(int i=0;i<m;i++) cin>>a[i]; r=max(a[0]-1,n-a[m-1]); for(int i=1;i<m;i++) r=max(r,(a[i]-a[i-1])/2); cout<<r<<endl; return 0; }
#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; int N,M,a[100000]; int main(){ cin>>N>>M; rep(i,M) cin>>a[i]; int ans=0; rep(i,M-1) chmax(ans,(a[i+1]-a[i])/2); chmax(ans,a[0]-1); chmax(ans,N-a[M-1]); cout<<ans<<endl; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef complex<double> P; typedef pair<int,int> pii; #define REP(i,n) for(ll i=0;i<n;++i) #define REPR(i,n) for(ll i=1;i<n;++i) #define FOR(i,a,b) for(ll i=a;i<b;++i) #define DEBUG(x) cout<<#x<<": "<<x<<endl #define DEBUG_VEC(v) cout<<#v<<":";REP(i,v.size())cout<<" "<<v[i];cout<<endl #define ALL(a) (a).begin(),(a).end() #define MOD (ll)(1e9+7) #define ADD(a,b) a=((a)+(b))%MOD #define FIX(a) ((a)%MOD+MOD)%MOD int main(){ int n,m; cin>>n>>m; vi a(m); REP(i,m)cin>>a[i]; REP(i,m)--a[i]; vi d(n,1145141919); queue<int> Q; REP(i,m){ d[a[i]]=0; Q.push(a[i]); } while(!Q.empty()){ int p = Q.front(); Q.pop(); if(p>0){ if(d[p-1]>d[p]+1){ d[p-1] = d[p]+1; Q.push(p-1); } } if(p<n-1){ if(d[p+1]>d[p]+1){ d[p+1] = d[p]+1; Q.push(p+1); } } } int res = 0; REP(i,n)res=max(res,d[i]); cout<<res<<endl; return 0; }
#include <iostream> #include <algorithm> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; int n,m; int a[200005]; int b[200005]; int main() { cin>>n>>m; rep(i,m) cin>>a[i]; rep(i,m) a[i]--; rep(i,200005) b[i]=1e8; rep(i,m) b[a[i]]=0; rep(i,n) if(i) { b[i]=min(b[i],b[i-1]+1); } for(int i=n-1;i>=0;i--) if(i+1!=n) b[i]=min(b[i],b[i+1]+1); int ans=0; rep(i,n) ans=max(ans,b[i]); cout<<ans<<endl; return 0; }
#include<iostream> #include<vector> #include<cassert> #include<string> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cmath> #include<stack> #include<queue> #include<set> #include<map> #include<tuple> #include<numeric> using namespace std; typedef pair<int,int> pii; typedef long long ll; typedef ll int__; #define rep(i,j) for(int__ i=0;i<(int__)(j);i++) #define repeat(i,j,k) for(int__ i=(j);i<(int__)(k);i++) #define all(v) v.begin(),v.end() template<typename T> ostream& operator << (ostream &os , const vector<T> &v){ rep(i,v.size()) os << v[i] << (i!=v.size()-1 ? " " : "\n"); return os; } template<typename T> istream& operator >> (istream &is , vector<T> &v){ rep(i,v.size()) is >> v[i]; return is; } bool solve(){ int n, m; cin >> n >> m; vector<int> a(m); cin >> a; int ans = max(a[0] - 1, n - a.back()); rep(i, m-1){ ans = max(ans, (a[i+1] - a[i]) / 2); } cout << ans << endl; return false; } int main(){ ios::sync_with_stdio(false); while(solve()); return 0; }
#include <cstdio> #include <iostream> #include <algorithm> #include <vector> #include <string> #define pb push_back #define rep(i,n) for (int i = 0; i < n; ++i) #define rrep(i,n) for (int i = 1; i <= n; ++i) #define drep(i,n) for (int i = (n)-1; i >= 0; --i) #define mins(x,y) x = min(x,y) #define maxs(x,y) x = max(x,y) using namespace std; typedef vector<int> vi; const int MX = 100005; const int INF = 1001001001; int n, m; int a[MX]; int main() { scanf("%d%d",&n,&m); rrep(i,n) a[i] = INF; rep(i,m) { int x; scanf("%d",&x); a[x] = 0; } rrep(i,n) mins(a[i+1],a[i]+1); drep(i,n) mins(a[i],a[i+1]+1); int ans = 0; rrep(i,n) maxs(ans, a[i]); cout<<ans<<endl; return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int n,m;cin>>n>>m; int ans=0; int b; for(int i=0;i<m;i++){ int a;cin>>a; if(i==0)ans=max(ans,a-1); else ans=max(ans,(a-b)/2); b=a; } ans=max(ans,n-b); cout<<ans<<endl; return 0; }
#include <iostream> #include <algorithm> #define rep(i, n) for(int i = 0; i < (n); ++i) using namespace std; int n, m; int a[100000]; int main(){ cin >> n >> m; rep(i, m){ cin >> a[i]; } int ans = max(a[0] - 1, n - a[m - 1]); rep(i, m - 1){ ans = max((a[i + 1] - a[i]) / 2, ans); } cout << ans << endl; return 0; }
#include <cstdio> #include <algorithm> using namespace std; int main() { int n, m, t, prev = 1, curr, ans = 0; scanf("%d %d", &n, &m); scanf("%d", &curr); if (curr > 1) { ans = curr - 1; prev = curr; } for (int i = 1; i < m; i++) { scanf("%d", &curr); t = (curr - prev) / 2; ans = max(ans, t); prev = curr; } if (prev < n) { t = n - prev; ans = max(ans, t); } printf("%d\n", ans); return 0; }
/* _/ _/ _/_/_/ _/ _/_/_/_/ _/_/ _/_/_/_/ _/_/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/_/ _/_/ _/_/ _/_/ _/ */ #include<iostream> #include<algorithm> #include<cmath> #include<iomanip> #include<set> #include<map> #include<queue> #include<vector> using namespace std; using ll=long long; const int MOD=1e9+7; const double pi=3.14159265358979323846; const int inf=2e9; const ll INF=1e18; using P=pair<int,int>; int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1}; int main() { cin.tie(0),cout.tie(0); ios::sync_with_stdio(false); int n,m,a,x[100005]={},ans=0; cin >> n >> m; for(int i=1; i<=n; i++) { x[i]=inf; } for(int i=0; i<m; i++) { cin >> a; x[a]=0; } for(int i=2; i<=n; i++) { if(x[i-1]!=inf) { x[i]=min(x[i-1]+1,x[i]); } } for(int i=n-1; i>=1; i--) { if(x[i+1]!=inf) { x[i]=min(x[i+1]+1,x[i]); } } for(int i=1; i<=n; i++) { ans=max(ans,x[i]); } cout << ans << endl; }
#include <iostream> using namespace std; int N,M; const int MAX_N = 100010; const int INF = 1 << 20; int A[MAX_N]; int Left[MAX_N]; int Right[MAX_N]; int main(){ cin >> N >> M; int result = 0; for (int i = 0; i < M; i++){ int x; cin >> x; x--; A[x]++; } int tmp = INF; for (int i = 0; i < N; i++){ if (A[i]){ tmp = 0; } Left[i] = tmp; tmp++; } tmp = INF; for (int i = N - 1; i >= 0; i--){ if (A[i]){ tmp = 0; } Right[i] = tmp; tmp++; } int res = 0; for (int i = 0; i < N; i++){ res = max(res, min(Left[i], Right[i])); } cout << res << endl; return 0; }
#include<iostream> #include<algorithm> using namespace std; int main() { int n, m, i, in, def = 0, ans = 0, before = 0; cin >> n >> m; for(i = 0; i < m; i++) { cin >> in; if(i == 0 && in != 1) { def = in - 1; } else def = (in-before)/2 +0.5; ans = max(ans, def); before = in; } ans = max(ans, n - in); cout << ans << endl; return 0; }
#include<iostream> using namespace std; int main() { int n, m, d; cin >> n >> m; bool a[n+2]; for( int i = 0; i < n + 2; i++ ) a[i] = 0; a[0] = a[n+1] = 1; int ma = 0; for( int i = 0; i < m; i++ ) { cin >> d; if( i == 0 ) ma = d - 1; if( i == m - 1 ) ma = max( ma, n - d ); a[d] = 1; } int sum = 0; for( int i = 0; i < n + 2; i++ ) { if( a[i] ) sum = 0; if( !a[i] ) sum++; if( ma < ( sum + 1 ) / 2 ) ma = ( sum + 1 ) / 2; } cout << ma << endl; return 0; }
#include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <set> #include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <complex> #include <stack> #include <queue> #include <cstdio> #include <cstring> #include <iterator> #include <bitset> #include <unordered_set> #include <unordered_map> #include <fstream> #include <iomanip> #include <cassert> //#include <utility> //#include <memory> //#include <functional> //#include <deque> //#include <cctype> //#include <ctime> //#include <numeric> //#include <list> //#include <iomanip> //#if __cplusplus >= 201103L //#include <array> //#include <tuple> //#include <initializer_list> //#include <forward_list> // //#define cauto const auto& //#else //#endif using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef vector<int> vint; typedef vector<vector<int> > vvint; typedef vector<long long> vll, vLL; typedef vector<vector<long long> > vvll, vvLL; #define VV(T) vector<vector< T > > template <class T> void initvv(vector<vector<T> > &v, int a, int b, const T &t = T()){ v.assign(a, vector<T>(b, t)); } template <class F, class T> void convert(const F &f, T &t){ stringstream ss; ss << f; ss >> t; } #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define reep(i,a,b) for(int i=(a);i<(b);++i) #define rep(i,n) reep((i),0,(n)) #define ALL(v) (v).begin(),(v).end() #define PB push_back #define F first #define S second #define mkp make_pair #define RALL(v) (v).rbegin(),(v).rend() #define DEBUG #ifdef DEBUG #define dump(x) cout << #x << " = " << (x) << endl; #define debug(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl; #else #define dump(x) #define debug(x) #endif #define MOD 1000000007LL #define EPS 1e-8 #define INF 0x3f3f3f3f #define INFL 0x3f3f3f3f3f3f3f3fLL #define maxs(x,y) x=max(x,y) #define mins(x,y) x=min(x,y) void mainmain(){ int ans=0; int n,m; cin>>n>>m; vint v(m); rep(i,m){ cin>>v[i]; } sort(ALL(v)); rep(i,v.size()-1){ maxs(ans,v[i+1]-v[i]-1); } ans=(ans+1)/2; // cout<<ans<<endl; maxs(ans,v[0]-1); maxs(ans,n-v.back()); cout<<ans<<endl; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout<<fixed<<setprecision(20); mainmain(); }
#include "bits/stdc++.h" using namespace std; int main() { int N, M; cin >> N >> M; vector<int>v; for (int i = 0; i < M; ++i) { int a; cin >> a; v.emplace_back(a); } int ans = 0; ans = max(ans, v[0] - 1); ans = max(ans, N - v.back()); for (int i = 0; i < M-1; ++i) { ans = max(ans, (v[i + 1] - v[i]) / 2); } cout << ans << endl; return 0; }
#include <fstream> #include <iostream> #include <vector> #include <iomanip> #include <algorithm> using namespace std; #define ALL(c) (c).begin(), (c).end() #define REP(i,n) for(ll i=0; i < (n); ++i) using ll = long long; using vl = vector<ll>; int main(){ #ifdef _WIN32 ifstream cin("sample.in"); ofstream cout("sample.out"); #endif cout << fixed << setprecision(8); ll n, m; cin >> n >> m; vl a(m); REP(i, m) cin >> a[i]; REP(i, m) a[i]--; sort(ALL(a)); ll mi = 0; REP(i, n){ auto it = lower_bound(ALL(a), i); ll mii = 100000; if(it != a.end()) mii = min<ll>(mii, abs(*it - i)); if (it != a.begin()) mii = min<ll>(mii, abs(*--it - i)); mi = max(mi, mii); } cout << mi << endl; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> P; int n,m; int a[100001]; int main(void){ scanf("%d%d",&n,&m); for(int i=0;i<m;i++){ scanf("%d",&a[i]); } int ans=max(a[0]-1,n-a[m-1]); for(int i=0;i<m-1;i++){ ans=max(ans,(a[i+1]-a[i])/2); } printf("%d\n",ans); return 0; }
#include <stdio.h> int main(void) { int m, n, i, j, be = 1, ans = 0, t; scanf("%d%d", &n, &m); for(i = 0; i < m; ++i) { scanf("%d", &t); if(!i) ans = t - 1; else if((t - be) / 2 > ans) ans = (t - be) / 2; be = t; } if(n - be > ans) ans = n - be; printf("%d\n", ans); return 0; }
#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;} int main(){ int n,m; cin >>n >>m; const int INF = 10000000; vector<int> a; a.pb(-INF); rep(i,m){ int v; cin >>v; a.pb(v); } a.pb(INF); int idx = 0; int ans = 0; for(int i=1; i<=n; ++i){ ans = max(ans, min(i-a[idx], a[idx+1]-i)); if(a[idx+1] == i) ++idx; } cout << ans << endl; return 0; }
#include<iostream> using namespace std; int main(){ int sum; while(cin >> sum){ int number, info[100005], ans; cin >> number; for(int i = 0; i < number; i++){ cin >> info[i]; } for(int i = 0; i < number + 1; i++){ if(!i){ ans = info[i] - 1; }else if(i == number){ ans = max(ans, sum - info[i - 1]); }else{ int a = (info[i] - info[i - 1]) / 2; ans = max(ans, a); } } cout << ans << endl; } }
/* _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pass System Test! */ #include <bits/stdc++.h> using namespace std; typedef long long ll; template <typename T> std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) { if (!v.empty()) { out << '['; std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, ", ")); out << "\b\b]"; } return out; } int main() { cin.tie(0); ios::sync_with_stdio(false); int N, M; cin >> N >> M; set<int> a; for (int i = 0; i < M; ++i) { int b; cin >> b; b--; a.insert(b); } int ma = 0; for (int i = 0; i < N; ++i) { if (i >= *(a.rbegin())) { ma = max(ma, i - *(a.rbegin())); continue; } auto it = a.lower_bound(i); int mi = N; mi = min(mi, *it - i); if (it != a.begin()) { it--; mi = min(mi, i - *it); } // cerr << mi << endl; ma = max(ma, mi); } cout << ma << endl; }
#include<iostream> #include<algorithm> #include<cstdio> #include<cmath> #include<cctype> #include<math.h> #include<string> #include<string.h> #include<stack> #include<queue> #include<vector> #include<utility> #include<set> #include<map> #include<stdlib.h> #include<iomanip> using namespace std; #define ll long long #define ld long double #define EPS 0.0000000001 #define INF 1e9 #define LINF (ll)INF*INF #define MOD 1000000007 #define rep(i,n) for(int i=0;i<(n);i++) #define loop(i,a,n) for(int i=a;i<(n);i++) #define all(in) in.begin(),in.end() #define shosu(x) fixed<<setprecision(x) #define int ll //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! typedef vector<int> vi; typedef vector<string> vs; typedef pair<int,int> pii; typedef vector<pii> vp; int gcd(int a, int b){ if(b==0) return a; return gcd(b,a%b); } int lcm(int a, int b){ return a/gcd(a,b)*b; } signed main(void) { int n,m; cin >> n >> m; vi a(m); rep(i,m)cin >> a[i]; int ans = max(a[0]-1, n-a[m-1]); rep(i,m-1){ ans = max(ans, (a[i+1]-a[i])/2); } cout << ans << endl; }
#include <iostream> #include <vector> int main() { int n, m; std::cin >> n >> m; std::vector<int> min_t(n, (1 << 29)); for (int i = 0; i < m; i++) { int a; std::cin >> a; min_t[a - 1] = 0; } for (int i = 1; i < n; i++) { min_t[i] = std::min(min_t[i], min_t[i - 1] + 1); } for (int i = n - 2; i >= 0; i--) { min_t[i] = std::min(min_t[i], min_t[i + 1] + 1); } int ret = 0; for (int t : min_t) { ret = std::max(ret, t); } std::cout << ret << std::endl; return 0; }
#include <iostream> #include <algorithm> #include <string> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cmath> #define rep(i,a,b) for(int (i)=(a);i<(b);i++) #define INF 100000000 #define MAX_N 1000000 using namespace std; int main(){ int n,m,a=0,b=0; cin>>n>>m; int ans=0; cin>>a; int z=a; b=a; rep(i,1,m){ cin>>a; ans=max(a-b,ans); //cout<<ans<<endl; b=a; } //cout<<ans<<endl; if(ans/2<n-a&&z-1<n-a){ cout<<n-a<<endl; }else{ cout<<max(ans/2,z-1)<<endl; } return 0; }
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; int main(){ int N,M; scanf("%d %d",&N,&M); int left_len,maximum = 0,right_len,tmp,pre; scanf("%d",&tmp); left_len = tmp-1; pre = tmp; if(M == 1){ right_len = N-tmp; printf("%d\n",max(left_len,right_len)); }else{ for(int i = 0; i < M-1; i++){ scanf("%d",&tmp); maximum = max(maximum,tmp-pre); pre = tmp; } right_len = N-tmp; printf("%d\n",max(max(left_len,right_len),maximum/2)); } return 0; }
#include<bits/stdc++.h> using namespace std; #define int long long typedef long long ll; 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>void chmin(T &t,U f){if(t>f)t=f;} template<class T,class U>void chmax(T &t,U f){if(t<f)t=f;} int N,M; int dp[111111]; signed main(){ cin>>N>>M; fill_n(dp,N,1<<25); rep(i,M){ int a; cin>>a; dp[--a]=0; } reps(i,1,N)chmin(dp[i],dp[i-1]+1); for(int i=N-2;i>=0;i--)chmin(dp[i],dp[i+1]+1); cout<<*max_element(dp,dp+N)<<endl; return 0; }
#include<iostream> #include<iomanip> #include<string> #include<cstdlib> #include<cmath> #include<algorithm> #include<vector> #include<iomanip> using namespace std; int main() { int n,m; cin >> n >> m; int count = 0; int input; int ex; for(int i=0; i<m; i++) { cin >> input; if(i == 0 && input-1 > count) count = input-1; if(i == m-1 && n-input > count) count = n-input; if(i != 0 && (input-ex)/2 > count) count = (input-ex)/2; ex=input; } cout << count << endl; return 0; }
#include <iostream> #include <algorithm> using namespace std; int main() { int n ; int m; int a[100000]; int b; int ans = 0; cin >> n >> m; for (int i = 0; i < m; i++){ cin >> a[i]; } for (int i = 0; i < m + 1; i++){ if (i == 0){ b = a[i] - 1; } else if (i == m){ b = n - a[i - 1]; } else{ b = a[i] - a[i-1] - 1; if (b % 2 == 0){ b /= 2; } else{ b++; b /= 2; } } ans = max(b, ans); } cout << ans << endl; return 0; }
#include <bits/stdc++.h> typedef long long LL; #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) using namespace std; int main(void) { int n,m; cin >> n >> m; vector<int> se; se.resize(m); REP(i,m) cin >> se[i]; int answer=0; answer=max(answer,se[0]-1); REP(i,m-1) answer=max(answer,(se[i+1]-se[i])/2); answer=max(answer,n-se[m-1]); cout << answer << endl; return 0; }
#include <string> #include <vector> #include <algorithm> #include <numeric> #include <set> #include <map> #include <queue> #include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <cctype> #include <cassert> #include <limits> #include <functional> #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i)) #define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i)) #if defined(_MSC_VER) || __cplusplus > 199711L #define aut(r,v) auto r = (v) #else #define aut(r,v) __typeof(v) r = (v) #endif #define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it) #define all(o) (o).begin(), (o).end() #define pb(x) push_back(x) #define mp(x,y) make_pair((x),(y)) #define mset(m,v) memset(m,v,sizeof(m)) #define INF 0x3f3f3f3f #define INFL 0x3f3f3f3f3f3f3f3fLL using namespace std; typedef vector<int> vi; typedef pair<int, int> pii; typedef vector<pair<int, int> > vpii; typedef long long ll; template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; } template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; } int main() { int n; int m; while(~scanf("%d%d", &n, &m)) { vector<int> a(m); for(int i = 0; i < m; ++ i) scanf("%d", &a[i]), -- a[i]; int ans = max(a[0], n - 1 - a[m-1]); rep(i, m - 1) amax(ans, (a[i + 1] - a[i]) / 2); printf("%d\n", ans); } return 0; }
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <iostream> #include <vector> #include <string> #include <sstream> #include <algorithm> #include <utility> #include <set> #include <map> #include <stack> #include <queue> #include <deque> #include <functional> using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; #define fst first #define scd second #define PB push_back #define MP make_pair #define rep(i,x) for(int i=0;i<(x);++i) #define rep1(i,x) for(int i=1;i<=(x);++i) #define rrep(i,x) for(int i=(x)-1;i>=0;--i) #define rrep1(i,x) for(int i=(x);i>=1;--i) #define FOR(i,a,x) for(int i=(a);i<(x);++i) #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define omajinai ios::sync_with_stdio(false);cin.tie(0) template<typename T>bool chmax(T&a,T b){if(a<b){a=b;return true;}return false;} template<typename T>bool chmin(T&a,T b){if(a>b){a=b;return true;}return false;} template<typename T>T get(){T a;cin>>a;return a;} template<typename T>T rev(T a){reverse(all(a));return a;} template<typename T>istream&operator>>(istream&is,vector<T>&vec){rep(i,vec.size())is>>vec[i];return is;} template<typename T>vector<T>&sort(vector<T>&a){sort(all(a));return a;} const int inf = 1e9; const ll linf = 3e18; const double eps = 1e-9; int dx[2] = {-1, 1}; int a[100000]; signed main() { omajinai; int N, M; cin >> N >> M; memset(a, -1, sizeof(a)); queue<int> q; rep(i, M) { int b; cin >> b; b--; a[b] = 0; q.push(b); } int ma = 0; while (q.size()) { int x = q.front(); q.pop(); rep(i, 2) { int nx = x + dx[i]; if (0 <= nx && nx < N) { if (~a[nx]) continue; a[nx] = a[x] + 1; q.push(nx); ma = max(ma, a[nx]); } } } cout << ma << endl; }
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; set<int> ok; for(int i = 0; i < m; ++i) { int a; cin >> a; ok.emplace(a); } int ans = 0; for(int i = 1; i <= n; ++i) { auto it = ok.lower_bound(i); int mn = INT_MAX; if(it != ok.end()) { mn = min(mn, *it - i); } if(it != ok.begin()) { --it; mn = min(mn, i - *it); } ans = max(ans, mn); } cout << ans << endl; return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> A; A.push_back(1); int a; for(int i = 1; i <= m; i++) { cin >> a; A.push_back(a); } A.push_back(n); int ans = 0; for(int i = 1; i < A.size(); i++) { int tmp; if(i == 1 || i == A.size() - 1) tmp = A[i] - A[i - 1]; else tmp = (A[i] - A[i - 1]) / 2; ans = max(tmp, ans); } cout << ans << endl; return 0; }
#include <stdio.h> #include <math.h> #include <iostream> #include <complex> #include <vector> #include <utility> #include <algorithm> using namespace std; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define mp make_pair const double EPS = 1e-12; const double pi = atan2(0.0, -1.0); typedef complex<double> P; double norma(double t) { while (t < -pi) t += 2*pi; while (t > pi) t -= 2*pi; return t; } double cross(const P& a, const P& b) { return imag(conj(a)*b); } double dot(const P& a, const P& b) { return real(conj(a)*b); } P unit(const P& p) { return 1/abs(p)*p; } P unit(double a) { return P(cos(a), sin(a)); } P rot90(const P& p) { return p * P(0, 1); } int ccw(const P& a, P b, P c) { b -= a, c -= a; if (cross(b, c) > 0) return 1; if (cross(b, c) < 0) return -1; if (dot(b, c) < 0) return 2; if (norm(b) < norm(c)) return -2; return 0; } bool intersectLL(const P& l0, const P& l1, const P& m0, const P& m1) { return abs(cross(l1-l0, m1-m0)) > EPS; } P crosspoint(const P& l0, const P& l1, const P& m0, const P& m1) { const double a = cross(l1-l0, m1-m0); const double b = cross(l1-l0, l1-m0); if (abs(a) < EPS && abs(b) < EPS) return m0; if (abs(a) < EPS) throw 0; return m0 + b/a * (m1-m0); } struct C { double R; vector<pair<double, double> > as; vector<pair<P, P> > es; C(double R) : R(R) {} }; C empty(double R) { C c(R); c.as.push_back(mp(-pi, pi)); return c; } double size(const C& c) { double t = 0; rep (i, c.as.size()) t += c.as[i].second - c.as[i].first; double s = c.R*c.R*(2*pi-t); rep (i, c.es.size()) s += cross(c.es[i].first, c.es[i].second); return s / 2; } C cut(const C& c, double dt, double t) { if (fabs(dt-pi) < EPS) return empty(c.R); C nc(c); const P p0 = c.R*unit(t-dt); const P p1 = c.R*unit(t+dt); const double a0 = norma(t-dt), a1 = norma(t+dt); if (a0 <= a1) nc.as.push_back(mp(a0, a1)); else { nc.as.push_back(mp(-pi, a1)); nc.as.push_back(mp(a0, pi)); } sort(nc.as.begin(), nc.as.end()); int m = 0; rep (i, nc.as.size()) { if (!m || nc.as[m-1].second < nc.as[i].first) nc.as[m++] = nc.as[i]; else nc.as[m-1].second = max(nc.as[m-1].second, nc.as[i].second); } nc.as.resize(m); P s0 = p0, s1 = p1; rep (i, nc.es.size()) { if (!intersectLL(nc.es[i].first, nc.es[i].second, p0, p1)) { const int cc = ccw(nc.es[i].first, nc.es[i].second, p0); if (cc == -1) s0 = s1 = P(0, 0); else if (abs(cc) != 1) { if (dot(p1-p0, nc.es[i].second-nc.es[i].first) < -EPS) { return empty(c.R); } } continue; } const P cp = crosspoint(nc.es[i].first, nc.es[i].second, p0, p1); if (ccw(nc.es[i].first, nc.es[i].second, s0) == -1) s0 = cp; if (ccw(nc.es[i].first, nc.es[i].second, s1) == -1) s1 = cp; } rep (i, nc.es.size()) { if (!intersectLL(nc.es[i].first, nc.es[i].second, p0, p1)) { const int cc = ccw(p0, p1, nc.es[i].first); if (cc == -1) nc.es[i].first = nc.es[i].second = P(0, 0); else if (abs(cc) != 1) { if (dot(p1-p0, nc.es[i].second-nc.es[i].first) < -EPS) { return empty(c.R); } } continue; } const P cp = crosspoint(nc.es[i].first, nc.es[i].second, p0, p1); if (ccw(p0, p1, nc.es[i].first) == -1) nc.es[i].first = cp; if (ccw(p0, p1, nc.es[i].second) == -1) nc.es[i].second = cp; } nc.es.push_back(mp(s0, s1)); m = 0; rep (i, nc.es.size()) { if (abs(nc.es[i].first - nc.es[i].second) > EPS) nc.es[m++] = nc.es[i]; } nc.es.resize(m); return nc; } int main() { int T; scanf("%d", &T); while (T--) { double R, L; scanf("%lf%lf", &R, &L); int n; scanf("%d", &n); C c(R); rep (i, n) { double t, V; scanf("%lf%lf", &t, &V); t = norma(t/180*pi); const double s = size(c) - V/L; double l = 0, r = pi; rep (_, 100) { const double mid = (l+r) / 2; if (size(cut(c, mid, t)) < s) r = mid; else l = mid; } c = cut(c, l, t); } double ansT = 0; rep (i, c.as.size()) ansT += c.as[i].second - c.as[i].first; double ansE = 0; rep (i, c.es.size()) ansE += abs(c.es[i].second - c.es[i].first); printf("%.9f %.9f\n", ansE, R*(2*pi-ansT)); } return 0; }
#include <iostream> #include <iomanip> #include <complex> #include <vector> #include <algorithm> #include <cmath> #include <array> using namespace std; const double EPS = 1e-8; const double INF = 1e12; const double PI = acos(-1); #define EQ(n,m) (abs((n)-(m)) < EPS) #define X real() #define Y imag() typedef complex<double> P; typedef vector<P> VP; struct L : array<P, 2>{ L(const P& a, const P& b){ at(0)=a; at(1)=b; } L(){} }; struct C{ P p; double r; C(const P& p, const double& r) : p(p), r(r) {} C(){} }; namespace std{ bool operator < (const P& a, const P& b){ return !EQ(a.X,b.X) ? a.X<b.X : a.Y+EPS<b.Y; } bool operator == (const P& a, const P& b){ return abs(a-b) < EPS; } } double dot(P a, P b){ return (conj(a)*b).X; } double cross(P a, P b){ return (conj(a)*b).Y; } int ccw(P a, P b, P c){ b -= a; c -= a; if(cross(b,c) > EPS) return +1; //ccw if(cross(b,c) < -EPS) return -1; //cw if(dot(b,c) < -EPS) return +2; //c-a-b if(abs(c)-abs(b) > EPS) return -2; //a-b-c return 0; //a-c-b } P unit(const P &p){ return p/abs(p); } P rotate(const P &p, double rad){ return p *P(cos(rad), sin(rad)); } bool intersectSP(const L& s, const P &p){ return abs(cross(s[0]-p, s[1]-p))<EPS && dot(s[0]-p, s[1]-p)<EPS; } P projection(const L& l, const P& p) { double t = dot(p-l[0], l[0]-l[1]) / norm(l[0]-l[1]); return l[0] + t*(l[0]-l[1]); } double distanceLP(const L &l, const P &p) { return abs(cross(l[1]-l[0], p-l[0])) /abs(l[1]-l[0]); } double distanceSP(const L &s, const P &p) { if(dot(s[1]-s[0], p-s[0]) < EPS) return abs(p-s[0]); if(dot(s[0]-s[1], p-s[1]) < EPS) return abs(p-s[1]); return distanceLP(s, p); } P crosspointLL(const L &l, const L &m) { double A = cross(l[1]-l[0], m[1]-m[0]); double B = cross(l[1]-l[0], l[1]-m[0]); return m[0] + B/A *(m[1]-m[0]); } VP crosspointCL(const C &c, const L &l){ VP ret; P mid = projection(l, c.p); double d = distanceLP(l, c.p); if(EQ(d, c.r)){ ret.push_back(mid); }else if(d < c.r){ double len = sqrt(c.r*c.r -d*d); ret.push_back(mid +len*unit(l[1]-l[0])); ret.push_back(mid -len*unit(l[1]-l[0])); } return ret; } VP crosspointCS(const C &c, const L &s){ VP ret; VP cp = crosspointCL(c,s); for(int i=0; i<(int)cp.size(); i++){ if(intersectSP(s, cp[i])){ ret.push_back(cp[i]); } } return ret; } int in_poly(const P &p, const VP &poly){ int n = poly.size(); int ret = -1; for(int i=0; i<n; i++){ P a = poly[i]-p; P b = poly[(i+1)%n]-p; if(a.Y > b.Y) swap(a,b); if(intersectSP(L(a,b), P(0,0))) return 0; if(a.Y<=0 && b.Y>0 && cross(a,b)<0) ret = -ret; } return ret; } VP convex_cut(const VP& p, const L& l){ VP ret; int n = p.size(); for(int i=0; i<n; i++){ P curr = p[i]; P next = p[(i+1)%n]; if(ccw(l[0], l[1], curr) != -1) ret.push_back(curr); if(ccw(l[0], l[1], curr) *ccw(l[0], l[1], next) == -1){ ret.push_back(crosspointLL(L(curr, next), l)); } } return ret; } VP convex(VP v){ VP ret; int n = v.size(); sort(v.begin(), v.end()); for(int i=0; i<n; i++){ while((int)ret.size()>1 && cross(ret.back()-ret[ret.size()-2], v[i]-ret.back()) < EPS){ ret.pop_back(); } ret.push_back(v[i]); } int t = ret.size(); for(int i=n-2; i>=0; i--){ while((int)ret.size()>t && cross(ret.back()-ret[ret.size()-2], v[i]-ret.back()) < EPS){ ret.pop_back(); } ret.push_back(v[i]); } if((int)ret.size() > 1) ret.pop_back(); return ret; } double commonarea_circle_convex(C c, VP poly){ int n = poly.size(); for(int i=0; i<n; i++) poly[i] -= c.p; c.p = P(0, 0); double mindist = INF; VP cp; for(int i=0; i<n; i++){ L edge(poly[i], poly[(i+1)%n]); VP ret = crosspointCS(c, edge); cp.insert(cp.begin(), ret.begin(), ret.end()); if(abs(poly[i]) < c.r) cp.push_back(poly[i]); mindist = min(mindist, distanceSP(edge, c.p)); } sort(cp.begin(), cp.end()); cp.erase(unique(cp.begin(), cp.end()), cp.end()); if(mindist +EPS > c.r && in_poly(c.p, poly) > 0){ return PI *c.r *c.r; } double res = 0; VP v = convex(cp); int m = v.size(); for(int i=0; i<m; i++){ P curr = v[i]; P next = v[(i+1)%m]; if(EQ(abs(curr), c.r) && EQ(abs(next), c.r) && in_poly(c.r *unit(next -curr)*P(0,-1), poly) > 0){ double theta = arg(next /curr); if(theta < 0) theta += 2*PI; res += c.r*c.r *theta /2; }else{ res += cross(curr, next) /2; } } return res; } int main(){ int dn; cin >> dn; for(int rep=0; rep<dn; rep++){ double r,l; int n; cin >> r >> l >> n; VP poly{P(-r-1, -r-1), P(r+1, -r-1), P(r+1, r+1), P(-r-1, r+1)}; C circle(P(0, 0), r); double rem = r*r*PI; for(int i=0; i<n; i++){ double theta, v; cin >> theta >> v; theta *= PI/180; v /= l; P base = rotate(P(1, 0), theta); P dir = base *P(0, 1); double lb=-r, ub=r; for(int j=0; j<50; j++){ double mid = (lb +ub)/2; L cut(mid*base, mid*base +dir); VP tmp = convex_cut(poly, cut); if(rem -commonarea_circle_convex(circle, tmp) > v){ lb = mid; }else{ ub = mid; } } L cut(lb*base, lb*base +dir); poly = convex_cut(poly, cut); rem = commonarea_circle_convex(circle, poly); } vector<double> angle; vector<VP> cp(poly.size()); for(int i=0; i<(int)poly.size(); i++){ L edge(poly[i], poly[(i+1)%poly.size()]); VP ret = crosspointCS(circle, edge); for(P p: ret){ angle.push_back(arg(p)); cp[i].push_back(p); } cp[i].push_back(poly[i]); cp[i].push_back(poly[(i+1)%poly.size()]); sort(cp[i].begin(), cp[i].end()); } if(!angle.empty()){ sort(angle.begin(), angle.end()); angle.push_back(angle[0] +2*PI); } double lenstraight=0, lencurve=0; for(int i=0; i<(int)cp.size(); i++){ for(int j=0; j<(int)cp[i].size()-1; j++){ P mp = (cp[i][j] +cp[i][j+1])/2.0; if(abs(mp) < r){ lenstraight += abs(cp[i][j+1] -cp[i][j]); } } } for(int i=0; i<(int)angle.size()-1; i++){ double mid = (angle[i] +angle[i+1])/2; P mp = rotate(P(r, 0), mid); if(in_poly(mp, poly) == 1){ lencurve += (angle[i+1] -angle[i]) *r; } } cout << fixed << setprecision(10); cout << lenstraight << " " << lencurve << endl; } return 0; }
#include<iostream> #include<string> #include<queue> #include<algorithm> #include<set> using namespace std; #define rep(i,n) for ( int i = 0; i < n; i++) static const int MAX = 50; static const int PMAX = 11; static const string DT = "URDL"; static const int di[4] = {-1, 0, 1, 0}; static const int dj[4] = {0, 1, 0, -1}; int H, W, np; char G[MAX][MAX]; string P[PMAX]; class State{ public: unsigned short pos; short M[PMAX], cost; string path; State(){ rep(i, np) M[i] = -1; path = ""; cost = 0; } bool shift(char ch){ path += ch; rep(i, np){ int p = -1; string s = P[i]; for ( int k = 0; k < s.size(); k++ ){ int st = path.size() -1 -k; if ( st < 0 ) continue; bool match = true; for ( int j = 0; j <= k; j++ ){ if ( path[st+j] != s[j] ) { match = false; break; } } if ( match ) p = k; } M[i] = p; if ( M[i] == P[i].size() -1 ) return false; } return true; } bool operator < ( const State &s ) const{ if ( pos != s.pos ) return pos < s.pos; rep(i, np){ if ( M[i] == s.M[i] ) continue; return M[i] < s.M[i]; } return false; } }; int bfs(int si, int sj, int gi, int gj){ queue<State> Q; set<State> V; State s; s.pos = si*W + sj; V.insert(s); Q.push(s); State u, v; int ni, nj; while(!Q.empty()){ u = Q.front(); Q.pop(); if ( u.pos/W == gi && u.pos%W == gj ) return u.cost; rep(r, 4){ ni = u.pos/W + di[r]; nj = u.pos%W + dj[r]; if ( ni < 0 || nj < 0 || ni >= H || nj >= W ) continue; if ( G[ni][nj] == '#' ) continue; v = u; v.pos = ni*W + nj; if (!v.shift(DT[r])) continue; v.cost++; if ( V.find(v) == V.end() ){ V.insert(v); Q.push(v); } } } return -1; } int main(){ int si, sj, gi, gj; while( cin >> H >> W && H){ rep(i,H) rep(j, W){ cin >> G[i][j]; if ( G[i][j] == 'S' ){ si = i; sj = j; G[i][j] = '.'; } if ( G[i][j] == 'G' ){ gi = i; gj = j; G[i][j] = '.'; } } cin >> np; rep(i, np) cin >> P[i]; cout << bfs(si, sj, gi, gj) << endl; } }
#include <bits/stdc++.h> template<class Converter, class SuffixInfo, int NODE_NUM = 1000000> class AhoCorasick { public: using value_structure = typename Converter::value_structure; using size_type = std::uint64_t; static constexpr size_type num_of_kinds = Converter::num_of_kinds; using value_type = typename SuffixInfo::value_type; using merged_value_type = typename SuffixInfo::merged_value_type; struct Node { size_type size, end, len, faillink; value_type val; merged_value_type suf_info; std::array<int, num_of_kinds> ch; Node () : size(0), end(0), len(0), val(SuffixInfo::identity()), suf_info(SuffixInfo::midentity()), faillink(0) { ch.fill(-1); } }; private: std::vector<Node> node; public: AhoCorasick() { node.reserve(NODE_NUM); node.push_back(Node()); } void insert(const value_structure& v, size_type num = 1, value_type val = value_type(), size_type k = 0, size_type idx = 0) { node[idx].size += num; if (k == v.size()) { node[idx].end += num; node[idx].val = SuffixInfo::operation(node[idx].val, val); return; } size_type nxt = Converter::convert(v[k]); if (node[idx].ch[nxt] == -1) { node.push_back(Node()); node[idx].ch[nxt] = node.size()-1; node.back().len = k+1; } insert(v, num, val, k+1, node[idx].ch[nxt]); } size_type count_prefix(const value_structure& v, size_type k = 0, size_type idx = 0) { if (v.size() == k) return node[idx].size; size_type nxt = Converter::convert(v[k]); if (node[idx].ch[nxt] == -1) return 0; return count_prefix(v, k+1, node[idx].ch[nxt]); } size_type count(const value_structure& v, size_type k = 0, size_type idx = 0) { if (v.size() == k) return node[idx].end; size_type nxt = Converter::convert(v[k]); if (node[idx].ch[nxt] == -1) return 0; return count(v, k+1, node[idx].ch[nxt]); } template<typename F> void query(const value_structure& v, const F& f, size_type k = 0, size_type idx = 0) { if (node[idx].size > 0) f(node[idx]); if (v.size() == k) return; size_type nxt = Converter::convert(v[k]); if (node[idx].ch[nxt] == -1) return; query(v, f, k+1, node[idx].ch[nxt]); } size_type proceed(size_type k, size_type c, bool need_convert = 1) { if (need_convert) c = Converter::convert(c); while (node[k].ch[c] == -1) k = node[k].faillink; return node[k].ch[c]; } void build() { std::queue<size_type> que; for (int i = 0; i < num_of_kinds; i++) { if (node[0].ch[i] == -1) node[0].ch[i] = 0; else { que.push(node[0].ch[i]); SuffixInfo::merge(node[node[0].ch[i]].suf_info, node[node[0].ch[i]].val); } } while (que.size()) { int k = que.front(); que.pop(); for (int i = 0; i < num_of_kinds; i++) { if (node[k].ch[i] == -1) continue; size_type nx = node[k].ch[i]; node[nx].faillink = proceed(node[k].faillink, i, false); SuffixInfo::merge(node[nx].suf_info, node[nx].val); SuffixInfo::merge(node[nx].suf_info, node[node[nx].faillink].suf_info); que.push(nx); } } } const Node& operator[](size_type k) { return node[k]; } }; int dy[4] = {-1, 1, 0, 0}; int dx[4] = {0, 0, -1, 1}; class Converter { public: using value_structure = std::string; using value_type = typename value_structure::value_type; static constexpr std::size_t num_of_kinds = 4; static std::size_t convert(const value_type& v) { switch (v) { case 'U': return 0; case 'D': return 1; case 'L': return 2; case 'R': return 3; } } }; class SuffixInfo { public: using value_type = int; using merged_value_type = int; static value_type identity() { return 0; } static merged_value_type midentity() { return 0; } static value_type operation(const value_type& a, const value_type& b) { return a | b; } static void merge(merged_value_type& a, const merged_value_type& b) { a |= b; } // static void merge(merged_value_type& a, const value_type& b) { // a |= b; // } }; void solve() { using namespace std; AhoCorasick<Converter, SuffixInfo> ah; int n, m; cin >> n >> m; if (n + m == 0) exit(0); vector<string> f(n); string dir="UDLR"; pair<int, int> st, goal; for (int i = 0; i < n; i++) { cin >> f[i]; for (int j = 0; j < m; j++) { if (f[i][j] == 'S') st = {i, j}; if (f[i][j] == 'G') goal = {i, j}; } } auto in = [&](int y, int x) { return 0<=y&&y<n&&0<=x&&x<m&&f[y][x]!='#'; }; int P; cin >> P; for (int i = 0; i < P; i++) { string s; cin >> s; ah.insert(s, 1, 1); } ah.build(); using T = tuple<int, int, int, int>; // d, y, x, v vector<vector<vector<int>>> d(n, vector<vector<int>>(m, vector<int>(110, (int)1e9))); queue<T> que; que.emplace(0, st.first, st.second, 0); d[st.first][st.second][0] = 0; while (que.size()) { int dd, ny, nx, v; tie(dd, ny, nx, v) = que.front(); que.pop(); for (int i = 0; i < 4; i++) { int yy = ny+dy[i], xx = nx+dx[i], vv = ah.proceed(v, dir[i]); if (!in(yy, xx)) continue; if (ah[vv].suf_info) { continue; } else { if (d[yy][xx][vv] > dd + 1) { d[yy][xx][vv] = dd + 1; que.emplace(dd+1, yy, xx, vv); } } } } int res = 1e9; for (int i = 0; i < 110; i++) { res = min(res, d[goal.first][goal.second][i]); } if (res == 1e9) { cout << -1 << endl; } else { cout << res << endl; } } int main(void) { while(1) { solve(); } } /* verify: https://tenka1-2016-final-open.contest.atcoder.jp/submissions/8400970 template<class Converter, class SuffixInfo> class AhoCorasick Converter: - 要求 - value_structure: std::string, std::vectorなどの列構造 - size, operator[] が必要 - static constexpr std::size_t num_of_kinds - 現れる値の種類数 - static convert(value_type) -> size_t - 値を[0, num_of_kinds)に変換する SuffixInfo: - 要求 - value_type: それぞれの文字列が持つ値の型 - merged_value_type: suffixが一致する要素の情報をまとめたもの - identity -> value_type - value_typeの単位元(初期値) - midentity -> merged_value_type - merged_value_typeの初期値(単位元とは???) - operation(const value_type&, const value_type&) - merge(merged_value_type&, const value_type&) - merge(merged_value_type&, const merged_value_type&) AhoCorasick - 提供 - Node - size - 部分木に単語がいくつあるか - end - その頂点で終わる単語がいくつあるか - len - その頂点までで何文字あるか - ch[num_of_kinds] - それぞれの子のpoolでのindex(存在しなければ-1) - insert(value_structure v, num, k) - O(|v|) - num個のv[k..)を挿入する - count_prefix(value_structure v, k) - O(|v|) - v[k..)をprefixとして含むものがいくつあるか返す - count(value_structure v, k) - O(|v|) - v[k..)がいくつあるか返す - query(value_structure v, F f, k) - O(|v|) - v[k..)のprefixそれぞれについてf(node)を呼び出す - build - proceed(k, c) - 今いる頂点がkのとき、次の文字がcのときに進む頂点を返す */
#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"; 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: assert(false); } } struct ac_node { ac_node *fail; ac_node *next[var]; vector<int> ok; ac_node() : fail(nullptr), next{} {} }; ac_node* new_ac_node() { static const int pmax = 1e5; static ac_node pool[pmax]; static int it = 0; assert(it < pmax); return &pool[it++]; } ac_node* getnext(ac_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; 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)] == nullptr) { now->next[trans(c)] = new_ac_node(); } now = now->next[trans(c)]; } now->ok.push_back(i); } queue<ac_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) { ac_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]); } } } } ac_node* getroot() const { return root; } int get_node_id(ac_node* nd) const { return (int)(nd - root); } vector<int> count(const string& S) const { vector<int> res(K); ac_node *now = root; for (auto c : S) { now = getnext(now, c); for (auto k : now->ok) res[k]++; } return res; } }; 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>(200, INF))); queue<T> q; q.push(make_tuple(sx, sy, aho.getroot())); f[sx][sy][aho.get_node_id(aho.getroot())] = 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 = getnext(nd, D[i]); if (0 <= tx && tx < n && 0 <= ty && ty < m && S[tx][ty] != '#' && tnd->ok.empty() && 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; }
/* * AOJ 2212: Stolen Jewel * ?¢?????????°?????????????????°??°???????????¨?????¨???????????????????????¨???????????¶?????????????????¢?????????????????¨???????????????????????¢????¬????????????¶????±???°????????????????°???\??°??? * ?±???????DP+????????? * ??????????????¢?§???????????????????????????¶???????¢??????????????????¨??¶???i????????????????????????????¬???¬?§???°?????????????????¶???j???d[x][y][i]??¨??????(x,y)??¨?????????i???????°???\??°?????¨Dijkstra?????°??°???????????????????????? */ #include <cstdio> #include <queue> #include <cstring> #include <algorithm> #include <iostream> #include <string> using namespace std; int m, n, nr, ns; string mat[53]; string rule[13]; int d[53][53][113]; int t[113][4]; string suf[113]; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; char dc[] = {'U', 'R', 'D', 'L'}; struct Status { int x, y, s, d; Status() {} Status(int dd, int xx, int yy, int ss) : d(dd), x(xx), y(yy), s(ss) {} void Get(int &dd, int &xx, int &yy, int &ss) const { dd = d; xx = x; yy = y; ss = s; } bool operator<(const Status &ts) const { return d > ts.d; } }; priority_queue<Status> pq; int Dijkstra() { while (!pq.empty()) pq.pop(); memset(d, 0x3f, sizeof(d)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (mat[i][j] == 'S') { d[i][j][0] = 0; pq.emplace(0, i, j, 0); goto L; } } } L: int ans = -1; while (!pq.empty()) { int pre, x, y, s; pq.top().Get(pre, x, y, s); pq.pop(); if (pre > d[x][y][s]) continue; for (int k = 0; k < 4; ++k) { int xx, yy, ss; ss = t[s][k]; if (ss == -1) continue; xx = x + dx[k]; yy = y + dy[k]; if (xx >= 0 && xx < m && yy >= 0 && yy < n && mat[xx][yy] != '#' && pre + 1 < d[xx][yy][ss]) { if (mat[xx][yy] == 'G') { ans = pre + 1; return ans; } d[xx][yy][ss] = pre + 1; pq.emplace(pre + 1, xx, yy, ss); } } } return ans; } bool IsSuf(string a, string b) { if (a.length() < b.length()) return false; return a.substr(a.length() - b.length()) == b; } void GaoEdge() { sort(suf, suf + ns); ns = unique(suf, suf + ns) - suf; memset(t, 0, sizeof(t)); for (int i = 0; i < ns; ++i) { for (int k = 0; k < 4; ++k) { string ts = suf[i] + dc[k]; for (int j = 0; j < nr; ++j) { if (IsSuf(ts, rule[j])) { t[i][k] = -1; break; } } if (t[i][k] != -1) { for (int j = 0; j < ns; ++j) { if (IsSuf(ts, suf[j]) && suf[j].length() > suf[t[i][k]].length()) { t[i][k] = j; } } } } } } int main() { //freopen("/Users/yogy/acm-challenge-workbook/db.in", "r", stdin); while (cin >> m >> n && m > 0 && n > 0) { for (int i = 0; i < m; ++i) { cin >> mat[i]; } cin >> nr; ns = 0; suf[ns++] = ""; for (int i = 0; i < nr; ++i) { cin >> rule[i]; for (int j = 1; j < rule[i].length(); ++j) { suf[ns++] = rule[i].substr(0, j); } } GaoEdge(); int ans = Dijkstra(); cout << ans << 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); #if DEB puts("aaa"); rep(i,ope.size()){ cout << ope[i] << endl; } #endif 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(); #if DEB puts("init"); printf("(%d,%lld),cost:%d\n",x,y,cost); rep(l,ma.size()){ printf("%d,",ma[l]); } puts(""); #endif 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); #if DEB puts(" update"); printf(" (%d,%d), dir:%d, cost:%lld\n",tx,ty,k,cost+1); rep(l,hoge.size()){ printf(" %d",hoge[l]); } puts(""); #endif } }else{ msi.insert(it,make_pair(ts,cost+1)); q.push(ts); #if DEB puts(" new"); printf(" (%d,%d), dir:%d, cost:%lld\n",tx,ty,k,cost+1); rep(l,hoge.size()){ printf(" %d",hoge[l]); } puts(""); #endif } } if( goal ) break; } printf("%lld\n",ans); } return 0; }
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <set> #include <string> #include <queue> using namespace std; typedef long long ll; 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 Point { int x; int y; int cost; int str; Point(int x, int y, int cost, int str) : x(x), y(y), cost(cost), str(str) {;} }; int w, h; char field[60][60]; char str[100]; const int dx[4] = { 1, 0, -1, 0 }; const int dy[4] = { 0, 1, 0, -1 }; const char move[4] = { 'R', 'D', 'L', 'U' }; char temp[100]; int main() { while (scanf("%d %d", &h, &w), h|w) { int p = 0; char revmove[300]; revmove[(int)'R'] = 1; revmove[(int)'D'] = 2; revmove[(int)'L'] = 3; revmove[(int)'U'] = 4; set<int> prefix; set<int> ban; set<string> pattern; set<int> visit[60][60]; int sx, sy; REP(y, h) { REP(x, w) { scanf(" %c ", &field[y][x]); if (field[y][x] == 'S') { sx = x; sy = y; } } } scanf("%d", &p); REP(i, p) { scanf("%s", str); pattern.insert((string)str); } for (set<string>::iterator it1 = pattern.begin(); it1 != pattern.end();) { FORIT(it2, pattern) { if (it1 == it2) { continue; } if (it1->find(*it2) != string::npos) { pattern.erase(it1++); goto next; } } it1++; next:; } FORIT(it, pattern) { int num = 0; REP(i, it->size()) { num = num * 5 + revmove[(int)(*it)[i]]; prefix.insert(num); } ban.insert(num); } prefix.insert(2000000000); queue<Point> que; que.push(Point(sx, sy, 0, 0)); visit[sy][sx].insert(0); while (!que.empty()) { Point p = que.front(); que.pop(); //cout << p.x << " " << p.y << " " << p.cost << " " << p.str << endl; if (field[p.y][p.x] == 'G') { printf("%d\n", p.cost); goto next2; } REP(i, 4) { int nx = p.x + dx[i]; int ny = p.y + dy[i]; if (nx < 0 || nx >= w || ny < 0 || ny >= h || field[ny][nx] == '#') { continue; } int nstr = p.str * 5 + i + 1; int start = pow(5, 11); while (nstr != 0 && !prefix.count(nstr)) { nstr %= start; start /= 5; } if (ban.count(nstr)) { continue; } if (visit[ny][nx].count(nstr)) { continue; } visit[ny][nx].insert(nstr); que.push(Point(nx, ny, p.cost + 1, nstr)); } } puts("-1"); next2:; } }
#include<bits/stdc++.h> using namespace std; int to[256]; struct TrieNode { int nxt[5]; int exist; // ???????????\???????????¨????????????????????°???????¨? vector< int > accept; // ???????????????id TrieNode() : exist(0) { memset(nxt, -1, sizeof(nxt)); } }; struct Trie { vector< TrieNode > nodes; int root; Trie() : root(0) { nodes.push_back(TrieNode()); } virtual void direct_action(int node, int id) {} virtual void child_action(int node, int child, int id) {} void update_direct(int node, int id) { nodes[node].accept.push_back(id); direct_action(node, id); } void update_child(int node, int child, int id) { ++nodes[node].exist; child_action(node, child, id); } 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 = to[str[str_index]]; if(nodes[node_index].nxt[c] == -1) { nodes[node_index].nxt[c] = (int) nodes.size(); nodes.push_back(TrieNode()); } 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 Aho_Corasick : Trie { static const int FAIL = 4; vector< int > correct; Aho_Corasick() : Trie() {} void build() { correct.resize(nodes.size()); for(int i = 0; i < nodes.size(); i++) { correct[i] = (int) nodes[i].accept.size(); } queue< int > que; for(int i = 0; i < 5; i++) { 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()) { TrieNode &now = nodes[que.front()]; correct[que.front()] += correct[now.nxt[FAIL]]; que.pop(); for(int i = 0; i < 4; 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]; que.emplace(now.nxt[i]); } } } int move(const string &str, int now = 0) { for(auto &c : str) { while(nodes[now].nxt[to[c]] == -1) now = nodes[now].nxt[FAIL]; now = nodes[now].nxt[to[c]]; if(correct[now]) return (-1); } return (now); } }; const int vy[] = {-1, 0, 1, 0}, vx[] = {0, 1, 0, -1}; const string tt = "URDL"; int H, W, P; string S[50], pat[10]; int bfs() { Aho_Corasick aho; queue< tuple< int, int, int > > que; vector< int > v[50][50]; for(int i = 0; i < P; i++) aho.add(pat[i]); aho.build(); for(int i = 0; i < H; i++) { for(int j = 0; j < W; j++) { v[i][j].resize(aho.nodesize(), -1); if(S[i][j] == 'S') { que.emplace(i, j, 0); v[i][j][0] = 0; } } } while(!que.empty()) { int y, x, now; tie(y, x, now) = que.front(); que.pop(); if(S[y][x] == 'G') return (v[y][x][now]); for(int i = 0; i < 4; i++) { int ny = y + vy[i], nx = x + vx[i]; if(ny < 0 || nx < 0 || nx >= W || ny >= H || S[ny][nx] == '#') continue; int nt = aho.move(string(1, tt[i]), now); if(nt == -1 || ~v[ny][nx][nt]) continue; v[ny][nx][nt] = v[y][x][now] + 1; que.emplace(ny, nx, nt); } } return (-1); } int main() { to['U'] = 0, to['R'] = 1, to['D'] = 2, to['L'] = 3; while(cin >> H >> W, H) { for(int i = 0; i < H; i++) cin >> S[i]; cin >> P; for(int i = 0; i < P; i++) cin >> pat[i]; cout << bfs() << endl; } }
#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"; 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; 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]); } } } } }; 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<unordered_map<node*, int>>> f(n, vector<unordered_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 = 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 <cstdio> #include <iostream> #include <algorithm> #include <vector> #include <string> #include <set> #include <queue> #include <map> #include <fstream> #include <cstring> #include <sstream> using namespace std; typedef long long ll; class Sit{ public: int x,y; int cur; }; class AhoCorasick{ private: // ノード数の最大サイズ static const int MAX_V=10001; private: map<string,int> _dict; string idToStr[MAX_V]; int _vertex; // 現在の文字列から次はどの文字列へ遷移できるか map<int,set<int> > _stepPrv; // // 探索失敗した場合に戻るノード // map<int,int> _stepBack; int _stepBack[MAX_V]; // // 辞書文字列の集合 // set<int> _dictStr; bool _dictStr[MAX_V]; // 点に情報を付加したい時のみ使用 //T _vertexInfos[MAX_V]; public: //AhoCorasick(); AhoCorasick(const vector<string> inStrings):_vertex(1){ memset(_dictStr,0,sizeof(_dictStr)); memset(_stepBack,0,sizeof(_stepBack)); for(int i=0;i<(int)inStrings.size();i++){ if(_dict.find(inStrings[i])==_dict.end()){ idToStr[_vertex]=inStrings[i]; _dict[inStrings[i]]=_vertex++; _dictStr[_vertex-1]=true; //_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; } // 現在の文字列を外から与え、1文字ずつ探索(valid) bool isMatchOneByOne(char ch,int &cur){ // 必要であれば、ここでcurがdict内に存在しないかチェック /* */ while(1){ int nxt=cur; string nstr=idToStr[nxt]; nstr+=ch; bool isFound=false; if(_dict.count(nstr)>0){ isFound=true; nxt=_dict[nstr]; } // もし今の場所から次の場所へ遷移可能ならば if(isFound&& _stepPrv.find(cur)!=_stepPrv.end() &&_stepPrv[cur].find(nxt)!=_stepPrv[cur].end()){ // 今回の場所から戻れる場所で、マッチするものがあるかをチェック int tmpStr=nxt; while(tmpStr!=0){ if(_dictStr[tmpStr]){ //if(_dictStr.find(tmpStr)!=_dictStr.end()){ cur=tmpStr; return true; } tmpStr=_stepBack[tmpStr]; } cur=nxt;/*これをいれる必要あり?*/ break; } // そうでなければ、戻って次のループで再び探索を行う else{ // rootで見つからなければ、終了 if(cur==0)return false; // 現在探索中の文字列はノードに存在しない //else if(_stepBack[cur]==-1)cur=0; //else if(_stepBack.find(cur)==_stepBack.end())cur=0; else{ // rootでない場合は、戻って今回の文字をもう一度見る cur=_stepBack[cur]; } } } // もし辞書内の文字列が見つかればtrue return (_dictStr[cur]); // if(_dictStr.find(cur)!=_dictStr.end())return true; // return false; } private: // コピーコンストラクタと、代入演算子は使用禁止にする 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または空文字列がルートノード _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); // まだ追加されていないのであれば、追加する if(_dict.find(s)==_dict.end()){ idToStr[_vertex]=s; _dict[s]=_vertex++; } } } // 探索を前に進める方向へエッジを結ぶ 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文字で構成されるならば、エッジを引く if(it->first.size()==iit->first.size()-1 &&it->first==iit->first.substr(0,it->first.size())){ _stepPrv[it->second].insert(iit->second); } } } // 探索を後ろへ進める方向へエッジを結ぶ for(map<string,int>::iterator it=_dict.begin();it!=_dict.end();it++){ if(it->first=="")continue; // 現在の文字列から先頭i文字を取り除いたものへ戻れるか順番にチェック // 戻れなければルートへ戻る 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; } } // ルートへ戻る 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したら、遷移しない if(b)continue; // nsit.curのノードへすでに達したかどうか 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<iostream> #include<vector> #include<tuple> #include<queue> #include<set> using namespace std; struct S{ int y,x,t; vector<int> v; }; int main(){ for(int N,M;cin>>N>>M,N;){ char g[50][51]; int y,x; for(int i=0;i<N;i++){ cin>>g[i]; for(int j=0;j<M;j++){ if(g[i][j]=='S'){ y=i; x=j; } } } int P; cin>>P; string p[10]; for(int i=0;i<P;i++){ cin>>p[i]; } set<vector<int> > s[50][50]; queue<S> que; que.push({y,x,0,vector<int>(P)}); while(!que.empty()){ auto cs=que.front(); if(g[cs.y][cs.x]=='G')break; que.pop(); if(!s[cs.y][cs.x].insert(cs.v).second)continue; for(int i=0;i<4;i++){ static const int dy[]={-1,0,1,0}; static const int dx[]={0,1,0,-1}; int ny=cs.y+dy[i]; int nx=cs.x+dx[i]; if(0<=ny&&ny<N&&0<=nx&&nx<M&&g[ny][nx]!='#'){ S ns{ny,nx,cs.t+1,cs.v}; for(int j=0;j<P;j++){ string c=p[j].substr(0,cs.v[j])+"URDL"[i]; while(p[j].compare(0,c.size(),c)){ c.erase(c.begin()); } if(c==p[j])goto fail; ns.v[j]=c.size(); } que.push(ns); fail: ; } } } cout<<(que.empty()?-1:que.front().t)<<endl; } }
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> #include <utility> #include <tuple> #define maxn 55 #define maxV 105 #define mt make_tuple using namespace std; typedef long long ll; typedef tuple<int, int, int> T; struct node{ int chi[4], fail; bool forbid; node(){ memset(chi, 0, sizeof(chi)); fail = forbid = 0; } }a[maxV]; int V; // root: node 1. namespace acAuto{ void init(){ for(int i = 1;i <= V;i++) a[i] = node(); V = 1; } void ins(int* s, int n){ // |S| = n. int u = 1; for(int i = 1;i <= n;i++){ if(!a[u].chi[s[i]]) a[u].chi[s[i]] = ++V; u = a[u].chi[s[i]]; } a[u].forbid = true; } void build(){ queue<int> que; que.push(1); while(!que.empty()){ int u = que.front(); que.pop(); for(int i = 0;i < 4;i++){ int v = a[u].chi[i], f = a[u].fail; if(v){ if(f) a[v].fail = a[f].chi[i]; else a[v].fail = 1; if(a[a[v].fail].forbid) a[v].forbid = true; que.push(v); }else{ if(f) a[u].chi[i] = a[f].chi[i]; else a[u].chi[i] = 1; } } } } } const int dx[] = {-1, 0, 1, 0}; const int dy[] = {0, 1, 0, -1}; int idx[135], n, m, p, sidx[15], rs, cs, rg, cg; char grid[maxn][maxn], s[15]; int f[maxn][maxn][maxV]; void solve(){ acAuto::init(); for(int i = 1;i <= n;i++) scanf("%s", grid[i] + 1); scanf("%d", &p); for(int i = 1;i <= p;i++){ scanf("%s", s + 1); int l = strlen(s + 1); for(int j = 1;j <= l;j++) sidx[j] = idx[(int)s[j]]; acAuto::ins(sidx, l); } acAuto::build(); for(int i = 0;i <= n + 1;i++) grid[i][0] = grid[i][m + 1] = '#'; for(int i = 1;i <= m;i++) grid[0][i] = grid[n + 1][i] = '#'; for(int i = 1;i <= n;i++){ for(int j = 1;j <= m;j++){ if(grid[i][j] == 'S') rs = i, cs = j; else if(grid[i][j] == 'G') rg = i, cg = j; } } memset(f, 0x3f, sizeof(f)); f[rs][cs][1] = 0; queue<T> que; que.push(mt(rs, cs, 1)); while(!que.empty()){ int x = get<0>(que.front()), y = get<1>(que.front()), u = get<2>(que.front()); que.pop(); if(x == rg && y == cg){ printf("%d\n", f[x][y][u]); return; } for(int d = 0;d < 4;d++){ int cx = x + dx[d], cy = y + dy[d], cu = a[u].chi[d]; if(grid[cx][cy] != '#' && !a[cu].forbid && f[x][y][u] + 1 < f[cx][cy][cu]){ f[cx][cy][cu] = f[x][y][u] + 1; que.push(mt(cx, cy, cu)); } } } puts("-1"); } int main(){ idx['U'] = 0, idx['R'] = 1, idx['D'] = 2, idx['L'] = 3; while(~scanf("%d%d", &n, &m) && n) solve(); return 0; }
#include <iostream> #include <cstdlib> #include <map> #include <vector> #include <queue> #include <algorithm> #define rep(i,n) for(int i = 0 ; i < n ; i++) using namespace std; struct NODE{ int x,y,a,b,cost; NODE(int A,int B,int C,int D,int E){ x = A , y = B , a = C , b = D , cost = E ; } }; int dx[] = {-1,0,1,0}; int dy[] = {0,-1,0,1}; char dc[]= {'L','U','R','D'}; int main(){ int W,H; while(cin >> H >> W , H ){ char field[52][52]; rep(i,52)rep(j,52)field[i][j] = '#'; rep(i,H)rep(j,W)cin >> field[i+1][j+1]; int sx , sy; rep(i,H+1)rep(j,W+1) if(field[i][j] == 'S') sx = j , sy = i; int p; cin >> p; vector<string> P(10); rep(i,p) cin >> P[i]; //rep(i,p)rep(j,p-1)if(P[j].length() < P[j+1].length() ) swap(P[j],P[j+1]); bool done[52][52][11][11]={0}; queue<NODE> Q; Q.push(NODE(sx,sy,0,0,0)); //rep(i,p)cout << P[i] << endl; while(Q.size()){ NODE q = Q.front(); Q.pop(); string pt = P[q.a].substr(0,q.b); bool f = true; rep(i,p) if(~pt.find(P[i]))f=0; if(!f)continue; if(field[q.y][q.x] == 'G'){ cout << q.cost << endl; goto end; } if(done[q.y][q.x][q.a][q.b]) continue; else done[q.y][q.x][q.a][q.b] = true; if(field[q.y][q.x] == '#') continue; rep(d,4){ string st , t = pt + dc[d]; int tx = q.x + dx[d] , ty = q.y + dy[d]; rep(i,t.size()){ st = t.substr(i); rep(j,p){ if( P[j].find(st) == 0){ Q.push(NODE(q.x+dx[d],q.y+dy[d],j,st.size(),q.cost+1)); goto ooo; } } } Q.push(NODE(q.x+dx[d],q.y+dy[d],0,0,q.cost+1)); ooo:; } } cout << -1 << endl; end:; } }
/* * AOJ 2212: Stolen Jewel * ???????????°?????????????????°??°???????????¨?????¨???????????????????????¨???????????¶?????????????????¢?????????????????¨???????????????????????¢????¬????????????¶????±???°????????????????°???\??°??? * ?±???????DP+????????? * ??????????????¢?§???????????????????????????¶???????¢??????????????????¨??¶???i????????????????????????????¬???¬?§???°?????????????????¶???j???d[x][y][i]??¨??????(x,y)??¨?????????i???????°???\??°?????¨Dijkstra?????°??°???????????????????????? */ #include <cstdio> #include <queue> #include <cstring> #include <algorithm> #include <iostream> #include <string> using namespace std; int m, n, nr, ns; string mat[53]; string rule[13]; int d[53][53][113]; int t[113][4]; string suf[113]; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; char dc[] = {'U', 'R', 'D', 'L'}; struct Status { int x, y, s, d; Status() {} Status(int dd, int xx, int yy, int ss) : d(dd), x(xx), y(yy), s(ss) {} void Get(int &dd, int &xx, int &yy, int &ss) const { dd = d; xx = x; yy = y; ss = s; } bool operator<(const Status &ts) const { return d > ts.d; } }; priority_queue<Status> pq; int Dijkstra() { while (!pq.empty()) pq.pop(); memset(d, 0x3f, sizeof(d)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (mat[i][j] == 'S') { d[i][j][0] = 0; pq.emplace(0, i, j, 0); goto L; } } } L: int ans = -1; while (!pq.empty()) { int pre, x, y, s; pq.top().Get(pre, x, y, s); pq.pop(); if (pre > d[x][y][s]) continue; for (int k = 0; k < 4; ++k) { int xx, yy, ss; ss = t[s][k]; if (ss == -1) continue; xx = x + dx[k]; yy = y + dy[k]; if (xx >= 0 && xx < m && yy >= 0 && yy < n && mat[xx][yy] != '#' && pre + 1 < d[xx][yy][ss]) { if (mat[xx][yy] == 'G') { ans = pre + 1; return ans; } d[xx][yy][ss] = pre + 1; pq.emplace(pre + 1, xx, yy, ss); } } } return ans; } bool IsSuf(string a, string b) { if (a.length() < b.length()) return false; return a.substr(a.length() - b.length()) == b; } void GaoEdge() { sort(suf, suf + ns); memset(t, 0, sizeof(t)); for (int i = 0; i < ns; ++i) { for (int k = 0; k < 4; ++k) { string ts = suf[i] + dc[k]; for (int j = 0; j < nr; ++j) { if (IsSuf(ts, rule[j])) { t[i][k] = -1; break; } } if (t[i][k] != -1) { for (int j = 0; j < ns; ++j) { if (IsSuf(ts, suf[j]) && suf[j].length() > suf[t[i][k]].length()) { t[i][k] = j; } } } } } } int main() { //freopen("/Users/yogy/acm-challenge-workbook/db.in", "r", stdin); while (cin >> m >> n && m > 0 && n > 0) { for (int i = 0; i < m; ++i) { cin >> mat[i]; } cin >> nr; ns = 0; suf[ns++] = ""; for (int i = 0; i < nr; ++i) { cin >> rule[i]; for (int j = 1; j < rule[i].length(); ++j) { suf[ns++] = rule[i].substr(0, j); } } GaoEdge(); int ans = Dijkstra(); cout << ans << endl; } 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 { char x, y; ll states; Node(char x, char 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 <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <queue> using namespace std; struct node{ int proh; int to[4]; int fail; node(){ proh = 0; memset(to, -1, sizeof to); fail = 0; } }; int w, h; char field[52][52]; vector<node> ac; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, -1, 0, 1}; void addptn(const char *ptn){ int x = 1, f = 0; for(; *ptn; ++ptn){ int d = 0; switch(*ptn){ case 'L': d = 0; break; case 'U': d = 1; break; case 'R': d = 2; break; case 'D': d = 3; break; } int y = ac[x].to[d]; if(y == -1){ y = ac.size(); ac[x].to[d] = y; ac.push_back(node()); } x = y; } ac[x].proh = 1; } int getproh(int p){ if(!ac[p].proh){ ac[p].proh = getproh(ac[p].fail); } return ac[p].proh; } int solve(){ memset(field, '#', sizeof field); ac.assign(2, node()); fill(ac[0].to, ac[0].to + 4, 1); ac[0].proh = -1; for(int i = 1; i <= h; ++i){ scanf("%s", field[i] + 1); field[i][w + 1] = '#'; } int n; char ptn[16]; scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%s", ptn); addptn(ptn); } queue<int> q; q.push(1); while(!q.empty()){ int p = q.front(); q.pop(); for(int i = 0; i < 4; ++i){ int t = ac[p].to[i]; if(t != -1){ q.push(t); int f = ac[p].fail; while(ac[f].to[i] == -1){ f = ac[f].fail; } ac[t].fail = ac[f].to[i]; } } } const int yofs = 52; const int pofs = yofs * yofs; int sy, sx; for(int y = 1; y <= h; ++y) for(int x = 1; x <= w; ++x){ if(field[y][x] == 'S'){ sy = y; sx = x; } } vector<char> vis(pofs * ac.size()); q.push(sy * yofs + sx + pofs); vis[q.front()] = 1; q.push(-1); int ret = 1; while(q.size() > 1){ int st = q.front(); q.pop(); if(st == -1){ q.push(-1); ++ret; continue; } int y = st % pofs / yofs; int x = st % yofs; int p = st / pofs; for(int i = 0; i < 4; ++i){ int ny = y + dy[i], nx = x + dx[i]; if(field[ny][nx] == '#'){ continue; } int np = p; while(ac[np].to[i] == -1){ np = ac[np].fail; } np = ac[np].to[i]; if(getproh(np) == 1){ continue; } int nst = np * pofs + ny * yofs + nx; if(vis[nst]){ continue; } vis[nst] = 1; if(field[ny][nx] == 'G'){ return ret; } q.push(nst); } } return -1; } int main(){ while(scanf("%d%d", &h, &w), h){ printf("%d\n", solve()); } }
#include <bits/stdc++.h> using namespace std; struct Ahocora{ int idx; struct PMA { int state; PMA* next[256]; vector<int> matched; PMA(int idx) { memset(next, 0, sizeof(next)); state = idx ; } ~PMA() { for(int i = 0; i < 256; i++) if(next[i]) delete next[i]; } }; vector<int> set_uni(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; }; PMA *root; map<int,PMA*>M; Ahocora(vector<string> &pattern) { idx=0; root = new PMA(idx++); M[idx-1]=root; PMA *now; root->next[0] = root; for(int i = 0; i < pattern.size(); i++) { now = root; for(int j = 0; j < pattern[i].size(); j++) { if(now->next[(int)pattern[i][j]] == 0){ now->next[(int)pattern[i][j]] = new PMA(idx++); M[idx-1] = now->next[(int)pattern[i][j]]; } now = now->next[(int)pattern[i][j]]; } now->matched.push_back(i); } queue<PMA*> que; for(int i=1;i<256;i++){ if(!root->next[i]) root->next[i] = root; else{ root->next[i]->next[0] = root; que.push(root->next[i]); } } while(!que.empty()) { now = que.front(); que.pop();//cout<<1; for(int i = 1; i < 256; i++) { if(now->next[i]){ PMA *nxt = now->next[0]; while(!nxt->next[i]) nxt = nxt->next[0]; now->next[i]->next[0] = nxt->next[i]; now->next[i]->matched = set_uni(now->next[i]->matched, nxt->next[i]->matched); que.push(now->next[i]); } } } } void match( const string s, vector<int> &res) { PMA *pma=root; for(int i = 0; i < s.size(); i++){ int c = s[i]; while(!pma->next[c]) pma = pma->next[0]; pma = pma->next[c]; for(int j = 0; j < pma->matched.size(); j++) res[pma->matched[j]] = true; } } int NG( const string s,int S) { PMA *pm = M[S]; //cout<<pm->state<<endl; for(int i = 0; i < s.size(); i++){ int c = s[i]; while(!pm->next[c]) pm = pm->next[0]; pm = pm->next[c]; for(int j = 0; j < pm->matched.size(); j++) return -1; } //cout<<pm->state<<endl; return pm->state; } }; #define r(i,n) for(int i=0;i<n;i++) int h,w,m,x,y; int dp[55][55][222]; string s[100]; string a; vector<string>v; int dx[]={0,1,0,-1}; int dy[]={-1,0,1,0}; string dc[]={"U","R","D","L"}; struct A{ int x,y,s; A(int a,int b,int c){x=a,y=b,s=c;} }; int main(){ while(1){ v.clear(); memset(dp,-1,sizeof(dp)); cin>>h>>w; if(!h)break; r(i,h)cin>>s[i]; r(i,h)r(j,w)if(s[i][j]=='S')x=j,y=i; cin>>m; r(i,m){ cin>>a; v.push_back(a); } Ahocora AHO(v); queue<A>q; q.push(A(x,y,0)); dp[y][x][0]=0; while(!q.empty()){ A p=q.front();q.pop(); x=p.x; y=p.y; int S=p.s; r(i,4){ int nx=x+dx[i]; int ny=y+dy[i]; int ns=AHO.NG(dc[i],S); if(ns==-1)continue; if(ny<0||nx<0||ny>=h||nx>=w)continue; if(s[ny][nx]=='#')continue; if(dp[ny][nx][ns]!=-1)continue; if(s[ny][nx]=='G'){ cout<<dp[y][x][S]+1<<endl; goto L; } dp[ny][nx][ns]=dp[y][x][S]+1; q.push(A(nx,ny,ns)); } } cout<<-1<<endl; L:; } }
class _in{struct my_iterator{int it;const bool rev;explicit constexpr my_iterator(int it_, bool rev=false):it(it_),rev(rev){}constexpr int operator*(){return it;}constexpr bool operator!=(my_iterator& r){return it!=r.it;}void operator++(){rev?--it:++it;}};const my_iterator i,n;public:explicit constexpr _in(int n):i(0),n(n){}explicit constexpr _in(int i,int n):i(i,n<i),n(n){}constexpr const my_iterator& begin(){return i;}constexpr const my_iterator& end(){return n;}}; #include <bits/stdc++.h> using namespace std; template<int Code> struct Node_ { Node_* next[Code]; Node_* fail; bool is_taboo; Node_() : fail(nullptr), is_taboo(false) { fill_n(next, Code, nullptr);} }; typedef Node_<4> node_t; const int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0}; const string urdl = "URDL"; map<char, int> encoder; void setEncoder() { for(int i : _in(4)) encoder[urdl[i]] = i;} void constructAC(vector<node_t>& nodes, const vector<string>& patterns) { node_t* root = &nodes[0]; //Phase 1 (trie) int count = 0; for(const auto& s : patterns) { node_t* cur = root; for(const char& c : s) { int k = encoder[c]; if(cur->next[k] == nullptr) cur->next[k] = &nodes[++count]; cur = cur->next[k]; } cur->is_taboo = true; } //Phase 2 (failue link) queue<node_t*> que; for(int i : _in(4)) { if(root->next[i] != nullptr) { root->next[i]->fail = root; que.emplace(root->next[i]); } else root->next[i] = root; } while(!que.empty()) { node_t* cur = que.front(); que.pop(); for(int i : _in(4)) { if(cur->next[i] == nullptr) continue; que.emplace(cur->next[i]); node_t* f = cur->fail; while(f->next[i] == nullptr) f = f->fail; cur->next[i]->fail = f->next[i]; } } } bool getTaboo(node_t* cur, node_t* root) { if(cur == root) return false; if(cur->is_taboo == false) return getTaboo(cur->fail, root); else return true; } using bs = bitset<2500>; int main() { cin.tie(0); ios::sync_with_stdio(false); setEncoder(); int N, M; while(cin >> N >> M && N) { vector<string> fld(N); for(auto& s : fld) cin >> s; int P; cin >> P; vector<string> patterns(P); for(auto& s : patterns) cin >> s; vector<node_t> nodes(P * 10 + 1); constructAC(nodes, patterns); node_t* root = &nodes[0]; int sx = -1, sy = -1; for(int i : _in(N)) for(int j : _in(M)) if(fld[i][j] == 'S'){ sx = j, sy = i; break; } vector<bs> used(nodes.size()); queue<tuple<int, int, int, int>> que; que.emplace(0, sx, sy, 0); used[0][sy * 50 + sx] = true; bool ok = false; while(!que.empty()) { int cid, cx, cy, dist; tie(cid, cx, cy, dist) = que.front(); que.pop(); if(fld[cy][cx] == 'G') { cout << dist << endl; ok = true; break; } for(int i : _in(4)) { int nx = cx + dx[i], ny = cy + dy[i]; if(nx < 0 || ny < 0 || M <= nx || N <= ny) continue; if(fld[ny][nx] == '#') continue; node_t* cur = &nodes[cid]; while(cur->next[i] == nullptr) cur = cur->fail; cur = cur->next[i]; if(getTaboo(cur, root)) continue; int id = cur - root; if(used[id][ny * 50 + nx] == true) continue; que.emplace(id, nx, ny, dist + 1); used[id][ny * 50 + nx] = true; } } if(!ok) cout << -1 << endl; } }
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; enum DIR{ North, East, South, West, }; enum Type{ TRUE, FALSE, UNKNOWN, }; struct Node{ int parent_id,children[4],suffix_link,depth; bool finish_FLG; }; struct SL{ SL(int arg_node_id,DIR arg_tmp_dir){ node_id = arg_node_id; tmp_dir = arg_tmp_dir; } int node_id; DIR tmp_dir; }; struct Data{ void set(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; struct Info{ Info(int arg_row,int arg_col,int arg_sum_cost,int arg_node_loc){ row = arg_row; col = arg_col; sum_cost = arg_sum_cost; node_loc = arg_node_loc; } bool operator<(const struct Info &arg) const{ return sum_cost > arg.sum_cost; } int row,col,sum_cost,node_loc; }; int H,W,POW[11]; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; int table[128],min_cost[50][50][200]; DIR dir_table[4] = {North,East,South,West}; char base_map[50][51]; Node nodes[200]; Type type[200]; Data start,goal; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void debug(DIR dir){ switch(dir){ case North: printf("U"); break; case East: printf("R"); break; case South: printf("D"); break; case West: printf("L"); break; } } void func(){ for(int i = 0; i < 200; i++){ nodes[i].finish_FLG = false; nodes[i].suffix_link = 0; for(int k = 0; k < 4; k++)nodes[i].children[k] = -1; } for(int row = 0; row < H; row++){ scanf("%s",base_map[row]); for(int col = 0; col < W; col++){ if(base_map[row][col] == 'S'){ start.set(row,col); }else if(base_map[row][col] == 'G'){ goal.set(row,col); } } } int P; scanf("%d",&P); int root = 0; nodes[root].parent_id = -1; nodes[root].depth = 0; int node_index = 1,tmp_ch,tmp_loc,parent_id,tmp_index; char buf[11]; for(int loop = 0; loop < P; loop++){ scanf("%s",buf); tmp_index = 0; tmp_ch = table[buf[tmp_index]]; tmp_loc = root; tmp_index = 0; while(true){ parent_id = tmp_loc; if(nodes[tmp_loc].children[tmp_ch] == -1){ nodes[tmp_loc].children[tmp_ch] = node_index++; } tmp_loc = nodes[tmp_loc].children[tmp_ch]; nodes[tmp_loc].parent_id = parent_id; nodes[tmp_loc].depth = nodes[parent_id].depth+1; tmp_index++; if(buf[tmp_index] == '\0'){ nodes[tmp_loc].finish_FLG = true; break; } tmp_ch = table[buf[tmp_index]]; } } int tmp,start_pos; bool Found; queue<SL> MAKE_SL; for(int i = 0; i < 4; i++){ if(nodes[root].children[i] != -1){ MAKE_SL.push(SL(nodes[root].children[i],dir_table[i])); } } int node_id; DIR tmp_dir; while(!MAKE_SL.empty()){ node_id = MAKE_SL.front().node_id; tmp_dir = MAKE_SL.front().tmp_dir; MAKE_SL.pop(); for(int i = 0; i < 4; i++){ if(nodes[node_id].children[i] != -1){ MAKE_SL.push(SL(nodes[node_id].children[i],dir_table[i])); } } for(tmp_loc = nodes[nodes[node_id].parent_id].suffix_link; tmp_loc != root; tmp_loc = nodes[tmp_loc].suffix_link){ if(nodes[tmp_loc].children[tmp_dir] != -1){ break; } } if(tmp_loc == root){ if(nodes[root].children[tmp_dir] != -1){ if(node_id == nodes[root].children[tmp_dir]){ nodes[node_id].suffix_link = root; }else{ nodes[node_id].suffix_link = nodes[root].children[tmp_dir]; } }else{ nodes[node_id].suffix_link = root; } }else{ nodes[node_id].suffix_link = nodes[tmp_loc].children[tmp_dir]; } } for(int i = 0; i < node_index; i++){ type[i] = UNKNOWN; } type[root] = FALSE; queue<int> CHECK; for(int i = 0; i < 4; i++){ if(nodes[root].children[i] != -1){ if(nodes[nodes[root].children[i]].finish_FLG){ type[nodes[root].children[i]] = TRUE; }else{ type[nodes[root].children[i]] = FALSE; } CHECK.push(nodes[root].children[i]); } } while(!CHECK.empty()){ node_id = CHECK.front(); CHECK.pop(); for(int i = 0; i < 4; i++){ if(nodes[node_id].children[i] != -1){ CHECK.push(nodes[node_id].children[i]); } } if(nodes[node_id].finish_FLG){ type[node_id] = TRUE; }else{ for(tmp_loc = nodes[node_id].suffix_link; tmp_loc != root; tmp_loc = nodes[tmp_loc].suffix_link){ if(type[tmp_loc] != UNKNOWN)break; } type[node_id] = type[tmp_loc]; } } for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ for(int node_loc = 0; node_loc < node_index; node_loc++)min_cost[row][col][node_loc] = BIG_NUM; } } min_cost[start.row][start.col][0] = 0; priority_queue<Info> Q; Q.push(Info(start.row,start.col,0,0)); int next_node_pos,adj_row,adj_col; DIR next_dir; bool FLG; int calc; while(!Q.empty()){ if(Q.top().row == goal.row && Q.top().col == goal.col){ printf("%d\n",Q.top().sum_cost); return; }else if(Q.top().sum_cost > min_cost[Q.top().row][Q.top().col][Q.top().node_loc]){ Q.pop(); }else{ for(int i = 0; i < 4; i++){ adj_row = Q.top().row+diff_row[i]; adj_col = Q.top().col+diff_col[i]; if(rangeCheck(adj_row,adj_col) == false || base_map[adj_row][adj_col] == '#')continue; switch(i){ case 0: next_dir = North; break; case 1: next_dir = West; break; case 2: next_dir = East; break; case 3: next_dir = South; break; } if(nodes[Q.top().node_loc].children[next_dir] != -1){ next_node_pos = nodes[Q.top().node_loc].children[next_dir]; }else{ if(Q.top().node_loc == 0){ next_node_pos = 0; if(min_cost[adj_row][adj_col][next_node_pos] > Q.top().sum_cost+1){ min_cost[adj_row][adj_col][next_node_pos] = Q.top().sum_cost+1; Q.push(Info(adj_row,adj_col,Q.top().sum_cost+1,next_node_pos)); } continue; } tmp = nodes[Q.top().node_loc].suffix_link; while(tmp != 0 && nodes[tmp].children[next_dir] == -1){ tmp = nodes[tmp].suffix_link; } if(tmp == 0){ if(nodes[tmp].children[next_dir] == -1){ next_node_pos = 0; }else{ next_node_pos = nodes[tmp].children[next_dir]; } }else{ next_node_pos = nodes[tmp].children[next_dir]; } } FLG = true; tmp = next_node_pos; if(type[next_node_pos] == TRUE)continue; if(min_cost[adj_row][adj_col][next_node_pos] > Q.top().sum_cost+1){ min_cost[adj_row][adj_col][next_node_pos] = Q.top().sum_cost+1; Q.push(Info(adj_row,adj_col,Q.top().sum_cost+1,next_node_pos)); } } Q.pop(); } } printf("-1\n"); } int main(){ for(int i = 0; i < 11; i++)POW[i] = pow(4,i); table['U'] = North; table['R'] = East; table['D'] = South; table['L'] = West; while(true){ scanf("%d %d",&H,&W); if(H == 0 && W == 0)break; func(); } return 0; }
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; enum DIR{ North, East, South, West, }; struct Node{ int num,parent_id,children[4],suffix_link,depth; bool finish_FLG; DIR pattern[10]; }; struct Data{ void set(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; struct Info{ Info(int arg_row,int arg_col,int arg_sum_cost,int arg_node_loc){ row = arg_row; col = arg_col; sum_cost = arg_sum_cost; node_loc = arg_node_loc; } bool operator<(const struct Info &arg) const{ return sum_cost > arg.sum_cost; } int row,col,sum_cost,node_loc; }; int H,W,POW[11]; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; int table[128],min_cost[50][50][200]; DIR dir_table[4] = {North,East,South,West}; char base_map[50][51]; Node nodes[200]; Data start,goal; map<int,int> MAP; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void debug(DIR dir){ switch(dir){ case North: printf("U"); break; case East: printf("R"); break; case South: printf("D"); break; case West: printf("L"); break; } } void func(){ for(int i = 0; i < 200; i++){ nodes[i].finish_FLG = false; for(int k = 0; k < 4; k++)nodes[i].children[k] = -1; } for(int row = 0; row < H; row++){ scanf("%s",base_map[row]); for(int col = 0; col < W; col++){ if(base_map[row][col] == 'S'){ start.set(row,col); }else if(base_map[row][col] == 'G'){ goal.set(row,col); } } } int P; scanf("%d",&P); nodes[0].parent_id = -1; nodes[0].num = 0; nodes[0].depth = 0; int node_index = 1,tmp_ch,tmp_loc,parent_id,tmp_index; char buf[11]; MAP.clear(); for(int loop = 0; loop < P; loop++){ scanf("%s",buf); tmp_index = 0; tmp_ch = table[buf[tmp_index]]; tmp_loc = 0; tmp_index = 0; while(true){ parent_id = tmp_loc; if(nodes[tmp_loc].children[tmp_ch] == -1){ nodes[tmp_loc].children[tmp_ch] = node_index++; } tmp_loc = nodes[tmp_loc].children[tmp_ch]; nodes[tmp_loc].parent_id = parent_id; for(int i = 0; i < nodes[parent_id].depth; i++){ nodes[tmp_loc].pattern[i] = nodes[parent_id].pattern[i]; } nodes[tmp_loc].pattern[nodes[parent_id].depth] = dir_table[tmp_ch]; nodes[tmp_loc].depth = nodes[parent_id].depth+1; tmp_index++; nodes[tmp_loc].num = -1; for(int i = 0; i < nodes[tmp_loc].depth; i++){ nodes[tmp_loc].num += (nodes[tmp_loc].pattern[i]+1)*POW[i]; } MAP[nodes[tmp_loc].num] = tmp_loc; if(buf[tmp_index] == '\0'){ nodes[tmp_loc].finish_FLG = true; break; } tmp_ch = table[buf[tmp_index]]; } } int tmp,start_pos; bool Found; for(int i = 1; i < node_index; i++){ Found = false; start_pos = 1; while(start_pos < nodes[i].depth){ tmp = -1; for(int k = start_pos; k < nodes[i].depth; k++){ tmp += (nodes[i].pattern[k]+1)*POW[k-start_pos]; } auto at = MAP.find(tmp); if(at != MAP.end()){ Found = true; break; } start_pos++; } if(!Found){ nodes[i].suffix_link = 0; }else{ nodes[i].suffix_link = MAP[tmp]; } } for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ for(int node_loc = 0; node_loc < node_index; node_loc++)min_cost[row][col][node_loc] = BIG_NUM; } } min_cost[start.row][start.col][0] = 0; priority_queue<Info> Q; Q.push(Info(start.row,start.col,0,0)); int next_node_pos,adj_row,adj_col; DIR next_dir; bool FLG; int calc; while(!Q.empty()){ if(Q.top().row == goal.row && Q.top().col == goal.col){ printf("%d\n",Q.top().sum_cost); return; }else if(Q.top().sum_cost > min_cost[Q.top().row][Q.top().col][Q.top().node_loc]){ Q.pop(); }else{ for(int i = 0; i < 4; i++){ adj_row = Q.top().row+diff_row[i]; adj_col = Q.top().col+diff_col[i]; if(rangeCheck(adj_row,adj_col) == false || base_map[adj_row][adj_col] == '#')continue; switch(i){ case 0: next_dir = North; break; case 1: next_dir = West; break; case 2: next_dir = East; break; case 3: next_dir = South; break; } if(nodes[Q.top().node_loc].children[next_dir] != -1){ next_node_pos = nodes[Q.top().node_loc].children[next_dir]; }else{ if(Q.top().node_loc == 0){ next_node_pos = 0; if(min_cost[adj_row][adj_col][next_node_pos] > Q.top().sum_cost+1){ min_cost[adj_row][adj_col][next_node_pos] = Q.top().sum_cost+1; Q.push(Info(adj_row,adj_col,Q.top().sum_cost+1,next_node_pos)); } continue; } tmp = nodes[Q.top().node_loc].suffix_link; while(tmp != 0 && nodes[tmp].children[next_dir] == -1){ tmp = nodes[tmp].suffix_link; } if(tmp == 0){ if(nodes[tmp].children[next_dir] == -1){ next_node_pos = 0; }else{ next_node_pos = nodes[tmp].children[next_dir]; } }else{ next_node_pos = nodes[tmp].children[next_dir]; } } FLG = true; tmp = next_node_pos; while(tmp != 0){ if(nodes[tmp].finish_FLG){ FLG = false; break; } tmp = nodes[tmp].suffix_link; } if(!FLG)continue; if(min_cost[adj_row][adj_col][next_node_pos] > Q.top().sum_cost+1){ min_cost[adj_row][adj_col][next_node_pos] = Q.top().sum_cost+1; Q.push(Info(adj_row,adj_col,Q.top().sum_cost+1,next_node_pos)); } } Q.pop(); } } printf("-1\n"); } int main(){ for(int i = 0; i < 11; i++)POW[i] = pow(4,i); table['U'] = North; table['R'] = East; table['D'] = South; table['L'] = West; while(true){ scanf("%d %d",&H,&W); if(H == 0 && W == 0)break; func(); } 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){ if(curr==root) next=root; else next=curr->failure->next[i]; continue; } 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); } } } 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 <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"; 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; 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]); } } } } }; 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 = 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<map> #include<cassert> #include<cstdlib> #include<algorithm> #include<numeric> #include<vector> #include<queue> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) const int N = 5; const int NODE=120; struct PMA{ PMA *next[N]; int ac; PMA(){fill(next,next+N,(PMA*)0);ac=0;} }; map<PMA*,int> M; PMA *buildPMA(string *in,int size){ PMA *root=new PMA; M[root]=0; rep(i,size){ PMA *t = root; rep(j,in[i].size()){ char c=in[i][j]; if (t->next[c] == NULL){ int ind=M.size(); t->next[c]=new PMA; M[t->next[c]]=ind; } t=t->next[c]; } t->ac++; } queue<PMA*> Q; REP(i,1,N){ char c=i; if (root->next[c]){ root->next[c]->next[0]=root; Q.push(root->next[c]); }else root->next[c]=root; } while(!Q.empty()){ PMA *t=Q.front();Q.pop(); REP(c,1,N){ if (t->next[c]){ Q.push(t->next[c]); PMA *r=t->next[0]; while(!r->next[c])r=r->next[0]; t->next[c]->next[0]=r->next[c]; t->next[c]->ac+=r->next[c]->ac; } } } return root; } PMA* match(PMA *r,char in){ while(!r->next[in])r=r->next[0]; r=r->next[in]; return r; } struct Edge{int dir,node;}; const string dir="DURL"; const int dx[]={0,0,1,-1}; const int dy[]={1,-1,0,0}; vector<Edge> edge[NODE]; void makegraph(PMA *now,PMA* root){ //rep(i,4){ REP(i,1,N){ PMA* next=now; next=match(next,i); if (next->ac != 0)continue; edge[M[now]].push_back((Edge){i-1,M[next]}); } } void travarse(PMA *t,PMA *root){ makegraph(t,root); REP(i,1,N){ if (t->next[i] != NULL && t->next[i] != root)travarse(t->next[i],root); } } char m[50][50]; struct st{ int y,x,node,cost; }; int cost[50][50][NODE]; int solve(int r,int c,int sy,int sx){ rep(i,r)rep(j,c)rep(k,M.size())cost[i][j][k]=-1; queue<st> Q; Q.push((st){sy,sx,0,0}); cost[sy][sx][0]=0; while(!Q.empty()){ st now=Q.front();Q.pop(); //cout << now.y <<" " << now.x <<" " << now.node <<" " << now.cost << endl; rep(i,edge[now.node].size()){ int dir=edge[now.node][i].dir; int next=edge[now.node][i].node; int ney=now.y+dy[dir],nex=now.x+dx[dir]; if (ney == -1 || nex == -1 || ney == r || nex == c|| m[ney][nex] == '#' || cost[ney][nex][next] != -1)continue; cost[ney][nex][next]=now.cost+1; if (m[ney][nex] == 'G')return now.cost+1; Q.push((st){ney,nex,next,now.cost+1}); } } return -1; } int main(){ int r,c; int n; string in[10]; while(cin>>r>>c && r){ M.clear(); rep(i,NODE)edge[i].clear(); rep(i,r)cin>>m[i]; cin>>n; rep(i,n){ cin>>in[i]; rep(j,in[i].size()){ rep(k,dir.size())if (in[i][j] == dir[k])in[i][j]=k+1; } } PMA* root=buildPMA(in,n); travarse(root,root); int sy,sx; rep(i,r)rep(j,c)if (m[i][j] == 'S')sy=i,sx=j; cout << solve(r,c,sy,sx) << endl; } return false; }
#include <cstdio> #include <vector> #include <stack> #include <iostream> #include <string> #include <tuple> #include <random> #include <map> #include <queue> #include <set> #include <complex> #include <algorithm> #include <cassert> #include <iterator> #include <numeric> using namespace std; typedef long double ld; typedef long long ll; typedef pair<ll, ll> P; const ll INF = 1e15; const double eps = 1e-6; // Aho-Corasick 法 /* * 複数パターン検索を行う. * パターン文字列の長さの和&L&,検索文字列の長さ$M$のとき * PMA構築に$\mathcal{O}(L)$,検索に$\mathcal{O}(L+N)$かかる. * - verified by : UVa 10679 */ struct PMAnode { PMAnode * next[256]; PMAnode * fail; vector<int> accept; int id; PMAnode(int id_) { fill(next, next + 256, nullptr); id = id_; } PMAnode() { fill(next, next + 256, nullptr); id = 0; } }; // Aho Corasick struct PMA { PMAnode root; int n_pat; // number of patterns vector<PMAnode*> idto; PMA(vector<string> &ps) { // パターン文字列を与える int id = 1; n_pat = ps.size(); idto.push_back(&root); // construct Trie tree for (int k = 0; k < ps.size(); k++) { string p = ps[k]; PMAnode * t = &root; for (int i = 0; i < p.size(); i++) { if (t->next[p[i]] == nullptr) { t->next[p[i]] = new PMAnode(id); id++; idto.push_back(t->next[p[i]]); } t = t->next[p[i]]; } t->accept.push_back(k); } // construct failure link queue< PMAnode * > Q; for (char c = ' '; c <= '~'; c++) { if (root.next[c] != nullptr) { root.next[c]->fail = &root; Q.push(root.next[c]); // add node which is adjacent to root } else { root.next[c] = &root; } } while (!Q.empty()) { PMAnode *t = Q.front(); Q.pop(); for (char c = ' '; c <= '~'; c++) { if (t->next[c] != nullptr) { Q.push(t->next[c]); PMAnode * r = t->fail; while (r->next[c] == nullptr) r = r->fail; t->next[c]->fail = r->next[c]; vector<int> &tac = t->next[c]->accept; vector<int> &rac = r->next[c]->accept; tac.insert(tac.end(), rac.begin(), rac.end()); sort(tac.begin(), tac.end()); unique(tac.begin(), tac.end()); } } } } // strを最後まで見たときの最終的なPMAnodeを返す PMAnode * match(string str) { PMAnode * t = &root; for (char c : str) { while (t->next[c] == nullptr) t = t->fail; t = t->next[c]; } return t; } // strでマッチしたパターンの種類と回数を返す // res[i] := パターン文字列ps[i]のstrにおける出現回数 vector< int > match_n(string str) { vector<int> res(n_pat, 0); PMAnode * t = &root; for (char c : str) { while (t->next[c] == nullptr) t = t->fail; t = t->next[c]; for (int i = 0; i < t->accept.size(); i++) { res[t->accept[i]]++; } } return res; } }; typedef ll Weight; struct Edge { int src, dst; Weight weight; Edge(int src, int dst, Weight weight) : src(src), dst(dst), weight(weight) { } }; bool operator < (const Edge &e, const Edge &f) { return e.weight != f.weight ? e.weight > f.weight : // !!INVERSE!! e.src != f.src ? e.src < f.src : e.dst < f.dst; } typedef vector<Edge> Edges; typedef vector<Edges> Graph; void shortestPath(const Graph &g, int s, vector<Weight> &dist, vector<int> &prev) { int n = g.size(); dist.assign(n, INF); dist[s] = 0; prev.assign(n, -1); priority_queue<Edge> Q; // "e < f" <=> "e.weight > f.weight" for (Q.push(Edge(-2, s, 0)); !Q.empty(); ) { Edge e = Q.top(); Q.pop(); if (prev[e.dst] != -1) continue; prev[e.dst] = e.src; for (auto f = g[e.dst].begin();f != g[e.dst].end();f++) { if (dist[f->dst] > e.weight + f->weight) { dist[f->dst] = e.weight + f->weight; Q.push(Edge(f->src, f->dst, e.weight + f->weight)); } } } } vector<ll> dx{ -1, 0, 1, 0 }; vector<ll> dy{ 0, 1, 0, -1 }; vector<char> dc{ 'L', 'D', 'R', 'U' }; ll H, W; ll f(ll id, ll y, ll x) { return (H + 2)*(W + 2)*id + (W + 2)*y + x; } int main() { while (cin >> H >> W, H != 0) { vector<string> area(H + 2, string(W + 2, '#')); for (int i = 1;i <= H;i++) { cin >> area[i]; area[i] = "#" + area[i] + "#"; } ll sy, sx, gy, gx; for (int y = 1;y <= H;y++) for (int x = 1;x <= W;x++) if (area[y][x] == 'S') { sx = x; sy = y; } else if (area[y][x] == 'G') { gy = y; gx = x; } ll P; cin >> P; vector<string> patt(P); for (int i = 0;i < P;i++) cin >> patt[i]; PMA aho(patt); Graph g((H+2)*(W+2) * 100); for (int y = 1;y <= H;y++) { for (int x = 1;x <= W;x++) { if (area[y][x] == '#') continue; for (int node = 0;node < min(100, (int)aho.idto.size()); node++) { for (int k = 0;k < 4;k++) { ll nx = x + dx[k]; ll ny = y + dy[k]; if (area[ny][nx] == '#') continue; PMAnode* now = aho.idto[node]; while (now->next[dc[k]] == nullptr) now = now->fail; now = now->next[dc[k]]; if(now->accept.empty()) g[f(node, y, x)].push_back(Edge(f(node, y, x), f(now->id, ny, nx), 1)); } } } } vector<ll> dist; vector<int> prev; shortestPath(g, f(0, sy, sx), dist, prev); ll ans = INF; for (int i = 0;i < min(100, (int)aho.idto.size());i++) ans = min(ans, dist[f(i, gy, gx)]); if (ans == INF) cout << -1 << endl; else cout << ans << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; #define int ll using PII = pair<int, int>; template <typename T> using V = vector<T>; template <typename T> using VV = vector<V<T>>; template <typename T> using VVV = vector<VV<T>>; #define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i) #define REP(i, n) FOR(i, 0, n) #define ALL(x) x.begin(), x.end() #define PB push_back const ll INF = (1LL<<60); const int MOD = 1000000007; template <typename T> T &chmin(T &a, const T &b) { return a = min(a, b); } template <typename T> T &chmax(T &a, const T &b) { return a = max(a, b); } template <typename T> bool IN(T a, T b, T x) { return a<=x&&x<b; } template<typename T> T ceil(T a, T b) { return a/b + !!(a%b); } template<class S,class T> ostream &operator <<(ostream& out,const pair<S,T>& a){ out<<'('<<a.first<<','<<a.second<<')'; return out; } template<class T> ostream &operator <<(ostream& out,const vector<T>& a){ out<<'['; REP(i, a.size()) {out<<a[i];if(i!=a.size()-1)out<<',';} out<<']'; return out; } // D, R, U, L int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}; // 文字の種類数をtemplate引数で渡す template <int types = 26> struct AhoCorasick { // trie木のnode struct node { node *fail; V<node*> next; V<int> matched; int idx; node() : fail(nullptr), next(types, nullptr) {} node(int idx) : fail(nullptr), next(types, nullptr), idx(idx) {} }; // 辞書のサイズ, 頂点数 int sz, nodesize; // trie木の根 node *root; // vectorを結合 V<int> unite(const V<int> &a, const V<int> &b) { V<int> ret; set_union(ALL(a), ALL(b), back_inserter(ret)); return ret; } // 文字と数字の対応付けをする関数 function<int(char)> trans; // 初期化 AhoCorasick() {} AhoCorasick(V<string> pattern, function<int(char)> f = [](char c){return c-'a';}) { nodesize = 0; trans = f; build(pattern); } // 文字列集合patternからtrie木っぽいオートマトンを作成 void build(V<string> pattern) { sz = pattern.size(), root = new node(nodesize++); node *now; root->fail = root; REP(i, sz) { now = root; for(const auto &c: pattern[i]) { if(now->next[trans(c)] == nullptr) { now->next[trans(c)] = new node(nodesize++); } now = now->next[trans(c)]; } now->matched.PB(i); } queue<node*> que; REP(i, types) { if(root->next[i] == nullptr) { root->next[i] = root; } else { root->next[i]->fail = root; que.push(root->next[i]); } } while(que.size()) { now = que.front(); que.pop(); REP(i, types) { if(now->next[i] != nullptr) { node *nxt = now->fail; while(!nxt->next[i]) nxt = nxt->fail; now->next[i]->fail = nxt->next[i]; now->next[i]->matched = unite(now->next[i]->matched, nxt->next[i]->matched); que.push(now->next[i]); } } } } // 一文字ずつ照合していく node* next(node* p, const char c) { while(p->next[trans(c)] == nullptr) p = p->fail; return p->next[trans(c)]; } // 文字列s中に辞書と一致する部分列がどれだけあるか V<int> match(const string s) { V<int> res(sz); node *now = root; for(auto c : s) { now = next(now, c); for(auto i : now->matched) res[i]++; } return res; } }; signed main(){ cin.tie(0); ios::sync_with_stdio(false); while(1) { int h, w; cin >> h >> w; if(!h) break; V<string> board(h); REP(i, h) cin >> board[i]; int n; cin >> n; V<string> v(n); REP(i, n) cin >> v[i]; int sx = -1, sy = -1, gx = -1, gy = -1; REP(i, h) REP(j, w) { if(board[i][j] == 'S') { sx = j, sy = i; } else if(board[i][j] == 'G') { gx = j, gy = i; } } char dir[4] = {'D', 'R', 'U', 'L'}; auto trans = [&](char c) { if(c == 'D') return 0; else if(c == 'R') return 1; else if(c == 'U') return 2; else if(c == 'L') return 3; }; AhoCorasick<4> aho(v, trans); // cout << "nodesize=" << aho.nodesize << endl; AhoCorasick<4>::node *now = aho.root; struct nt { int y, x; AhoCorasick<4>::node *node; nt(int x, int y, AhoCorasick<4>::node *n) : y(y), x(x) { node = n; } }; // d[y][x][あほこらのnode] = 最小距離 VVV<int> d(h, VV<int>(w, V<int>(aho.nodesize, INF))); queue<nt> que; d[sy][sx][0] = 0; que.push(nt(sx, sy, now)); while(que.size()) { nt vec = que.front(); que.pop(); // cout << vec.x << " " << vec.y << " " << vec.node->idx << endl; REP(i, 4) { int nx = vec.x + dx[i], ny = vec.y + dy[i]; // cout << "nx=" << nx << " ny=" << ny << endl; if(!IN(0LL,w,nx) || !IN(0LL,h,ny) || board[ny][nx]=='#') continue; AhoCorasick<4>::node *next = aho.next(vec.node, dir[i]); if(next == nullptr) { continue; } // cout << next->matched << endl; if(next->matched.size()) continue; if(d[ny][nx][next->idx] > d[vec.y][vec.x][vec.node->idx] + 1) { d[ny][nx][next->idx] = d[vec.y][vec.x][vec.node->idx] + 1; que.push(nt(nx, ny, next)); } } } int ret = INF; REP(i, aho.nodesize) chmin(ret, d[gy][gx][i]); if(ret == INF) cout << -1 << endl; else cout << ret << endl; } return 0; }
#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; string cur; }; class AhoCorasick{ private: static const int MAX_V=1000001; private: map<string,int> _dict; int _vertex; // Œ»Ý‚Ì•¶Žš—ñ‚©‚玟‚͂ǂ̕¶Žš—ñ‚Ö‘JˆÚ‚Å‚«‚é‚© map<string,set<string> > _stepPrv; // ’Tõޏ”s‚µ‚½ê‡‚É–ß‚éƒm[ƒh map<string,string> _stepBack; // Ž«‘•¶Žš—ñ‚̏W‡ set<string> _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++)_dictStr.insert(inStrings[i]); makeTree(inStrings); } int getVetex(){ return _vertex; } // Œ»Ý‚Ì•¶Žš—ñ‚ðŠO‚©‚ç—^‚¦A‚P•¶Žš‚¸‚Â’Tõ bool isMatchOneByOne(char ch,string &cur){ // •K—v‚Å‚ ‚ê‚΁A‚±‚±‚Åcur‚ªdict“à‚É‘¶Ý‚µ‚È‚¢‚©ƒ`ƒFƒbƒN /* */ while(1){ string nxt=cur; nxt+=ch; // ‚à‚µ¡‚̏ꏊ‚©‚玟‚̏ꏊ‚Ö‘JˆÚ‰Â”\‚È‚ç‚Î if(_stepPrv.find(cur)!=_stepPrv.end()&&_stepPrv[cur].find(nxt)!=_stepPrv[cur].end()){ // ¡‰ñ‚̏ꏊ‚©‚ç–ß‚ê‚éêŠ‚ŁAƒ}ƒbƒ`‚·‚é‚à‚Ì‚ª‚ ‚é‚©‚ðƒ`ƒFƒbƒN string tmpStr=nxt; while(tmpStr!=""){ if(_dictStr.find(tmpStr)!=_dictStr.end())return true; tmpStr=_stepBack[tmpStr]; } cur=nxt; break; } // ‚»‚¤‚łȂ¯‚ê‚΁A–ß‚Á‚ÄŽŸ‚̃‹[ƒv‚ōĂђTõ‚ðs‚¤ else{ // root‚ÅŒ©‚‚©‚ç‚È‚¯‚ê‚΁AI—¹ if(cur=="")return false; // Œ»Ý’Tõ’†‚Ì•¶Žš—ñ‚̓m[ƒh‚É‘¶Ý‚µ‚È‚¢ else if(_stepBack.find(cur)==_stepBack.end())cur=""; 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){ string cur=""; for(int i=0;i<s.size();i++){ string nxt=cur+s[i]; // ‚à‚µ¡‚̏ꏊ‚©‚玟‚̏ꏊ‚Ö‘JˆÚ‰Â”\‚È‚ç‚Î if(_stepPrv.find(cur)!=_stepPrv.end()&&_stepPrv[cur].find(nxt)!=_stepPrv[cur].end()){ cur=nxt; string tmpStr=nxt; // –ß‚Á‚Ä’Tõ while(tmpStr!=""){ if(_dictStr.find(tmpStr)!=_dictStr.end())return true; tmpStr=_stepBack[tmpStr]; } } // ‚»‚¤‚łȂ¯‚ê‚΁A–ß‚Á‚ÄŽŸ‚̃‹[ƒv‚ōĂђTõ‚ðs‚¤ else{ // root‚ÅŒ©‚‚©‚ç‚È‚¯‚ê‚΁A¡‰ñ‚Ì•¶Žš‚Í”ò‚΂· if(cur=="")continue; else if(_stepBack.find(cur)==_stepBack.end())cur=""; 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; 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())_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->first].insert(iit->first); } } } // ’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<it->first.size()-1;i++){ string s=it->first.substr(i+1); if(_dict.find(s)!=_dict.end()){ _stepBack[it->first]=s; ok=true; break; } } // ƒ‹[ƒg‚Ö–ß‚é if(!ok)_stepBack[it->first]=""; } } }; int h,w; int n; char field[51][51]; string prohibits[20]; int sy,sx,gx,gy; set<string> 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=""; queue<Sit> q[2]; int cur=0; int nxt=1; q[cur].push(init); used[init.y][init.x].insert(""); 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; }
//Name: Stolen Jewel //Level: 3 //Category: グラフ,Graph,Aho-Corasick //Note: /** * Aho-Corasick法のオートマトンを作成し、(現在位置,Aho-Corasickのノード位置)で幅優先探索すればよい。 * * オーダーはO(NMP|S|)。 */ #include <iostream> #include <string> #include <vector> #include <queue> #include <array> #include <tuple> using namespace std; template <typename T> struct Maybe {/*{{{*/ T val; bool valid; Maybe() : valid(false) {} Maybe(T &t) : val(t), valid(true) {} T& operator =(const T &rv) { val = rv; valid = true; return val; } operator T() { return valid ? val : T(); } const T& fetch(const T &fallback) const { return valid ? val : fallback; } template<typename Cond> bool update(const T &v, Cond cond) { if(!valid || cond(v, val)) { val = v; valid = true; return true; } return false; } bool update(const T &v) { return update(v, less<T>()); } };/*}}}*/ template<int CharNum> struct AhoCorasick { struct Node { bool terminal; int failure; array<Maybe<int>,CharNum> edge; Node() : terminal(false), failure(0) { fill(begin(edge), end(edge), Maybe<int>()); } }; vector<Node> g_; int pos_; AhoCorasick(const vector<string> &dict) { g_.resize(1); // Build trie for(const auto &s : dict) { int cur = 0; for(const int c : s) { if(!g_[cur].edge[c].valid) { g_.push_back(Node()); g_[cur].edge[c] = (int)g_.size() - 1; } cur = g_[cur].edge[c]; } g_[cur].terminal = true; } // Build failure link queue<int> q; q.push(0); while(!q.empty()) { const int cur = q.front(); q.pop(); for(int ch = 0; ch < CharNum; ++ch) { if(g_[cur].edge[ch].valid) { const int n = g_[cur].edge[ch].val; q.push(n); int f = g_[cur].failure; while(f != 0 && !g_[f].edge[ch].valid) { f = g_[f].failure; } g_[n].failure = g_[f].edge[ch].fetch(0); if(g_[n].failure == n) g_[n].failure = 0; } } } // Update terminal state for(auto &n : g_) { int f = n.failure; while(f != 0) { if(g_[f].terminal) { n.terminal = true; break; } f = g_[f].failure; } } } void reset(int pos = 0) { pos_ = pos; } int advance(int ch) { while(pos_ != 0 && !g_[pos_].edge[ch].valid) { pos_ = g_[pos_].failure; } pos_ = g_[pos_].edge[ch].fetch(0); return pos_; } int size() const { return g_.size(); } bool accepted() const { return g_[pos_].terminal; } }; const int DR[] = {0, -1, 0, 1}; const int DC[] = {1, 0, -1, 0}; bool solve(bool first) { int R, C; if(!(cin >> R >> C)) return false; if(!R && !C) return false; vector<string> field(R+2); pair<int,int> start, goal; field[0] = field[R+1] = string(C+2, '#'); for(int r = 1; r < R+1; ++r) { cin >> field[r]; field[r] = string("#") + field[r] + "#"; for(int c = 1; c < C+2; ++c) { if(field[r][c] == 'S') { start = make_pair(r, c); } else if(field[r][c] == 'G') { goal = make_pair(r, c); } } } int P; cin >> P; vector<string> prohibited(P); for(int i = 0; i < P; ++i) { cin >> prohibited[i]; for(char &c : prohibited[i]) { switch(c) { case 'R': c = 0; break; case 'U': c = 1; break; case 'L': c = 2; break; case 'D': c = 3; break; } } } AhoCorasick<4> am(prohibited); // Automaton vector<vector<vector<Maybe<int>>>> memo(R+2, vector<vector<Maybe<int>>>(C+2, vector<Maybe<int>>(am.size()))); memo[start.first][start.second][0] = 0; queue<tuple<int,int,int>> q; q.push(make_tuple(start.first, start.second, 0)); int ans = -1; while(!q.empty()) { int r, c, s; tie(r, c, s) = q.front(); //cout << r << ' ' << c << ' ' << s << endl; q.pop(); if(r == goal.first && c == goal.second) { ans = memo[r][c][s]; break; } for(int i = 0; i < 4; ++i) { am.reset(s); const int nr = r + DR[i]; const int nc = c + DC[i]; const int ns = am.advance(i); if(field[nr][nc] == '#') continue; if(am.accepted()) continue; if(memo[nr][nc][ns].valid) continue; memo[nr][nc][ns] = memo[r][c][s] + 1; q.push(make_tuple(nr, nc, ns)); } } cout << ans << endl; return true; } int main() { cin.tie(0); ios::sync_with_stdio(0); cout.setf(ios::fixed); cout.precision(10); bool first = true; while(solve(first)) { first = false; } return 0; }
#include<bits/stdc++.h> using namespace std; struct TrieNode { int nxt[27]; int exist; // ???????????\???????????¨????????????????????°???????¨? vector< int > accept; // ???????????????id TrieNode() : exist(0) { memset(nxt, -1, sizeof(nxt)); } }; struct Trie { vector< TrieNode > nodes; int root; Trie() : root(0) { nodes.push_back(TrieNode()); } virtual void direct_action(int node, int id) {} virtual void child_action(int node, int child, int id) {} void update_direct(int node, int id) { nodes[node].accept.push_back(id); direct_action(node, id); } void update_child(int node, int child, int id) { ++nodes[node].exist; child_action(node, child, id); } 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] - 'A'; if(nodes[node_index].nxt[c] == -1) { nodes[node_index].nxt[c] = (int) nodes.size(); nodes.push_back(TrieNode()); } 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 Aho_Corasick : Trie { static const int FAIL = 26; vector< int > correct; Aho_Corasick() : Trie() {} void build() { correct.resize(nodes.size()); for(int i = 0; i < nodes.size(); i++) { correct[i] = (int) nodes[i].accept.size(); } queue< int > que; for(int i = 0; i < 27; i++) { 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()) { TrieNode &now = nodes[que.front()]; correct[que.front()] += correct[now.nxt[FAIL]]; que.pop(); for(int i = 0; i < 26; 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]; que.emplace(now.nxt[i]); } } } int move(const string &str, int now = 0) { for(auto &c : str) { while(nodes[now].nxt[c - 'A'] == -1) now = nodes[now].nxt[FAIL]; now = nodes[now].nxt[c - 'A']; if(correct[now]) return (-1); } return (now); } }; const int vy[] = {-1, 0, 1, 0}, vx[] = {0, 1, 0, -1}; const string tt = "URDL"; int H, W, P; string S[50], pat[10]; int bfs() { Aho_Corasick aho; queue< tuple< int, int, int > > que; vector< int > v[50][50]; for(int i = 0; i < P; i++) aho.add(pat[i]); aho.build(); for(int i = 0; i < H; i++) { for(int j = 0; j < W; j++) { v[i][j].resize(aho.nodesize(), -1); if(S[i][j] == 'S') { que.emplace(i, j, 0); v[i][j][0] = 0; } } } while(!que.empty()) { int y, x, now; tie(y, x, now) = que.front(); que.pop(); if(S[y][x] == 'G') return (v[y][x][now]); for(int i = 0; i < 4; i++) { int ny = y + vy[i], nx = x + vx[i]; if(ny < 0 || nx < 0 || nx >= W || ny >= H || S[ny][nx] == '#') continue; int nt = aho.move(string(1, tt[i]), now); if(nt == -1 || ~v[ny][nx][nt]) continue; v[ny][nx][nt] = v[y][x][now] + 1; que.emplace(ny, nx, nt); } } return (-1); } int main() { while(cin >> H >> W, H) { for(int i = 0; i < H; i++) cin >> S[i]; cin >> P; for(int i = 0; i < P; i++) cin >> pat[i]; cout << bfs() << 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]; vector<int> ok; ac_node() : fail(nullptr), next{} {} }; 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++]; } 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; 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.push_back(i); } 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 = unite(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.empty() && 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<bits/stdc++.h> using namespace std; using ll=long long; #include<vector> #include<string> #include<queue> namespace ProconLib{ template<class Language> class AhoCorasick{ public: using char_t=typename Language::char_t; using string_t=typename Language::string_t; private: using Edges=std::vector<int>; using Graph=std::vector<Edges>; private: Language lang; int N,C; Graph g; std::vector<int> _failure; std::vector<int> _accept; void add(int id,const string_t& pat); public: AhoCorasick(std::vector<string_t> patterns,Language lang=Language()); int getRoot(){return 0;} int rejectToken(){return -1;} int size(){return N;} int next(int v,char_t x){return g[v][lang.id_of(x)]; } int failure(int v){return _failure[v];} int accept(int v){return _accept[v];} }; template<class Language> void AhoCorasick<Language>::add(int id,const string_t& pat){ int v=0; for(auto& c:pat){ int to=g[v][lang.id_of(c)]; if(to==0){ to=N++; g.push_back(Edges(C,0)); _accept.push_back(rejectToken()); g[v][lang.id_of(c)]=to; } v=to; } _accept[v]=id; } template<class Language> AhoCorasick<Language>::AhoCorasick(std::vector<string_t> patterns,Language lang) :lang(lang),C(lang.size()),N(1),g(1,Edges(C)),_accept(1,rejectToken()),_failure(1,0) { int id=0; for(auto &pat:patterns){ add(id++,pat); } _failure.assign(N,0); struct T3{int pre,label,v;}; std::queue<T3> que; que.push(T3{0,-1,0}); while(!que.empty()){ T3 st=que.front(); que.pop(); if(st.pre!=0){ _failure[st.v]=g[_failure[st.pre]][st.label]; _accept[st.v]=max(_accept[st.v],_accept[_failure[st.v]]); } for(int i=0;i<C;i++) if(g[st.v][i]!=0) que.push(T3{st.v,i,g[st.v][i]}); for(int i=0;i<C;i++) if(g[st.v][i]==0) g[st.v][i]=g[_failure[st.v]][i]; } } // example struct LowerCase{ using char_t=char; using string_t=std::string; constexpr int size(){return 26;} int id_of(char x){return x-'a';} }; } using namespace ProconLib; using Field=vector<string>; using vi=vector<int>; using vvi=vector<vi>; using vvvi=vector<vvi>; int dx[]={1,0,-1,0}; int dy[]={0,1,0,-1}; char dc[]={'d','r','u','l'}; int solve(int h,int w){ Field f(h); for(int i=0;i<h;i++) cin>>f[i]; auto isRange=[&](int i,int j){ return 0<=i && i<h && 0<=j && j<w; }; int k; cin>>k; vector<string> pat(k); for(int i=0;i<k;i++) cin>>pat[i]; for(int i=0;i<k;i++) for(char& x:pat[i]) x=tolower(x); AhoCorasick<LowerCase> ac(pat); int n=ac.size(); auto isValid=[&](int x,int y,int st){ int v=ac.accept(st); return isRange(x,y) && f[x][y]!='#' && v==ac.rejectToken(); }; const int INF=1e9; vvvi dp(h,vvi(w,vi(n,INF))); struct X{ int x,y; int st; }; queue<X> que; pair<int,int> gpos; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(f[i][j]=='S'){ dp[i][j][0]=0; que.push(X{i,j,0}); } if(f[i][j]=='G'){ gpos.first=i; gpos.second=j; } } } while(!que.empty()){ X tmp=que.front(); que.pop(); for(int i=0;i<4;i++){ X tox={tmp.x+dx[i],tmp.y+dy[i],ac.next(tmp.st,dc[i])}; if(isValid(tox.x,tox.y,tox.st) && dp[tox.x][tox.y][tox.st]==INF){ dp[tox.x][tox.y][tox.st]=dp[tmp.x][tmp.y][tmp.st]+1; que.push(tox); } } } int res=INF; for(int i=0;i<n;i++){ res=min(res,dp[gpos.first][gpos.second][i]); } cout<<(res<INF ? res: -1)<<endl; return 0; } int main(){ int h,w; while(cin>>h>>w,h){ solve(h,w); } return 0; }
#include <iostream> #include <vector> #include <string> #include <cstring> #include <queue> #include <algorithm> using namespace std; int Psz; struct PMA{ int n; PMA *next[0x200]; vector<int> accept; PMA() { fill(next, next+0x200, (PMA*)0); } PMA(int a) { n=a; fill(next, next+0x200, (PMA*)0); } }; PMA *buildPMA(vector<string>& p, vector<PMA*>& vpma, int size) { Psz=0; PMA *root = new PMA(Psz++); vpma.push_back(root); for(int i=0; i<size; i++) { PMA* t=root; for(int j=0; j<p[i].size(); j++) { char c=p[i][j]; if(t->next[c] == NULL) { t->next[c] = new PMA(Psz++); vpma.push_back(t->next[c]); } t = t->next[c]; } } queue<PMA*> Q; for(int c = 'A'; c<='Z'; c++) { if(root->next[c]) { root->next[c]->next[0]=root; Q.push(root->next[c]); } else { root->next[c] = root; } } while(!Q.empty()) { PMA *t = Q.front(); Q.pop(); for(int c = 'A'; c<='Z'; c++) { if(t->next[c]) { Q.push(t->next[c]); PMA *r = t->next[0]; while(!r->next[c]) r = r->next[0]; t->next[c]->next[0] = r->next[c]; } } } return root; } int match(char t, PMA* v, int &ret) { int r=v->n; char c=t; while(!v->next[c]) v = v->next[0]; v = v->next[c]; r = v->n; ret += v->accept.size(); return r; } void makeacpt(PMA* p, int n, string w) { PMA *t = p; for(int j=0; j<w.size(); j++) { char c=w[j]; if(t->next[c]==NULL) return; t = t->next[c]; } for(int i=0; i<t->accept.size(); i++) if(t->accept[i]==n) return; t->accept.push_back(n); } class State { public: int x,y,pma,c; State(int x, int y, int pma, int c) :x(x),y(y),pma(pma),c(c) {} }; int dx[]={-1,0,1,0}; int dy[]={0,-1,0,1}; bool v[60][60][60]; char dir[4]={'L', 'U', 'R', 'D'}; int main() { int M,N; while(cin >> N >> M, (M||N)) { memset(v,0,sizeof(v)); int sx,sy; char f[90][90]; for(int i=0; i<N; i++) for(int j=0; j<M; j++) { cin >> f[j][i]; if(f[j][i]=='S') { sx=j; sy=i; } } int P; cin >> P; vector<string> str; for(int i=0; i<P; i++) { string s; cin >> s; str.push_back(s); } vector<PMA*> vpma; PMA* root = buildPMA(str,vpma,str.size()); for(int j=0; j<str.size(); j++) for(int i=0; i<Psz; i++) { PMA* p=vpma[i]; makeacpt(p,j,str[j]); } bool g=false; queue<State> q; q.push(State(sx,sy,0,0)); while(!q.empty()) { State s=q.front(); q.pop(); if(v[s.x][s.y][s.pma]) continue; v[s.x][s.y][s.pma]=1; if(f[s.x][s.y]=='G') { g=true; cout << s.c << endl; break; } for(int i=0; i<4; i++) { int tx=s.x+dx[i], ty=s.y+dy[i]; if(tx<0||ty<0||tx>=M||ty>=N) continue; if(f[tx][ty]=='#') continue; int ret=0; int tpma = match(dir[i],vpma[s.pma],ret); if(ret!=0) continue; if(v[tx][ty][tpma]) continue; q.push(State(tx,ty,tpma,s.c+1)); } } if(!g) cout << -1 << endl; } }
#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; vector<int> s(p); 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)) { 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 <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> P; #define each(i,a) for (auto&& i : a) #define FOR(i,a,b) for (ll i=(a),__last_##i=(b);i<__last_##i;i++) #define RFOR(i,a,b) for (ll i=(b)-1,__last_##i=(a);i>=__last_##i;i--) #define REP(i,n) FOR(i,0,n) #define RREP(i,n) RFOR(i,0,n) #define __GET_MACRO3(_1, _2, _3, NAME, ...) NAME #define rep(...) __GET_MACRO3(__VA_ARGS__, FOR, REP)(__VA_ARGS__) #define rrep(...) __GET_MACRO3(__VA_ARGS__, RFOR, RREP)(__VA_ARGS__) #define pb push_back #define all(a) (a).begin(),(a).end() #define chmin(x,v) x = min(x, v) #define chmax(x,v) x = max(x, v) const ll linf = 1e18; const double eps = 1e-12; const double pi = acos(-1); template<typename T> istream& operator>>(istream& is, vector<T>& vec) { each(x,vec) is >> x; return is; } template<typename T> ostream& operator<<(ostream& os, const vector<T>& vec) { rep(i,vec.size()) { if (i) os << " "; os << vec[i]; } return os; } template<typename T> ostream& operator<<(ostream& os, const vector< vector<T> >& vec) { rep(i,vec.size()) { if (i) os << endl; os << vec[i]; } return os; } class AhoCorasick { void clear_graph() { root.child.clear(); root.pattern.clear(); } void generate_trie(const vector<string>& patterns) { ll n = patterns.size(); rep(i, n) { Node* t = &root; each(c, patterns[i]) { if (t->child.count(c) == 0) { t->child[c] = Node(nodes.size()); nodes.pb(&t->child[c]); } t = &(t->child[c]); } t->pattern.push_back(i); } } void add_failure_edge() { queue<Node*> Q; Q.push(&root); //幅優先探索で帰納的に失敗時の遷移辺を追加していく while (!Q.empty()) { Node* t = Q.front(); Q.pop(); each(p, t->child) { Q.push(&(p.second)); char c = p.first; Node* node = &(p.second); // 文字cで遷移する頂点 Node* anode = t->failure; // 失敗したときの遷移先 while ( anode != NULL && anode->child.count(c) == 0 ) { anode = anode->failure; } //遷移失敗時に続けられる別の頂点へ遷移 if (anode == NULL) { node->failure = &root; } else { node->failure = &(anode->child[c]); } //マッチするパターンを追加 each(to, node->failure->pattern) { node->pattern.pb(to); } //メモリ食いすぎ回避のため切り詰めておく vector<size_t>(node->pattern).swap(node->pattern); } } } //Pattern Match Automatonを構築 void make_PMA(const vector<string>& patterns) { clear_graph(); generate_trie(patterns); add_failure_edge(); } public: struct Node { ll id; map<char,Node> child; //遷移辺(!) vector<size_t> pattern; //マッチするパターン(のindex) Node* failure; //遷移失敗時の遷移先ノード Node():failure(NULL) { } Node(ll id):failure(NULL), id(id) {} }; vector<Node*> nodes; Node root; AhoCorasick(const vector<string>& patterns) : nodes(0), root(0) { nodes.assign(1, &root); make_PMA(patterns); } pair<Node*, vector<ll>> find(Node* node, char c) { vector<ll> res; while (node != NULL && node->child.count(c) == 0) { node = node->failure; } if (node == NULL) node = &root; else node = &(node->child[c]); each(ptn, node->pattern) { res.pb(ptn); } return pair<Node*, vector<ll>>(node, res); } }; const string dname = "URDL"; const ll dx[] = {0, 1, 0, -1}; const ll dy[] = {-1, 0, 1, 0}; struct Node2 { ll x, y, nid; }; int main() { ios::sync_with_stdio(false); cin.tie(0); ll h, w; while (cin >> h >> w, h || w) { vector<string> m(h); cin >> m; ll patterns; cin >> patterns; vector<string> ptn(patterns); cin >> ptn; AhoCorasick ac(ptn); auto inRange = [&](ll x, ll y) { return 0 <= x && x < w && 0 <= y && y < h; }; ll sx, sy, gx, gy; rep(y, h) rep(x, w) { if (m[y][x] == 'S') sx = x, sy = y; if (m[y][x] == 'G') gx = x, gy = y; } ll n = ac.nodes.size(); vector<vector<vector<ll>>> dist(h, vector<vector<ll>>(w, vector<ll>(n, linf))); queue<Node2> Q; dist[sy][sx][0] = 0; Q.push({sx, sy, 0}); while ( !Q.empty() ) { Node2 node = Q.front(); Q.pop(); ll x = node.x, y = node.y, nid = node.nid; AhoCorasick::Node* ac_node = ac.nodes[nid]; rep(d, 4) { ll nx = x + dx[d]; ll ny = y + dy[d]; if ( !inRange(nx, ny) ) continue; if ( m[ny][nx] == '#' ) continue; auto result = ac.find(ac_node, dname[d]); if ( result.second.size() > 0 ) continue; ll nnid = result.first->id; assert(nnid < n); if (dist[y][x][nid]+1 < dist[ny][nx][nnid]) { dist[ny][nx][nnid] = dist[y][x][nid]+1; Q.push({nx, ny, nnid}); } } } ll ans = linf; rep(i, n) chmin(ans, dist[gy][gx][i]); if (ans == linf) cout << -1 << endl; else cout << ans << endl; } }