Search is not available for this dataset
name
stringlengths 2
88
| description
stringlengths 31
8.62k
| public_tests
dict | private_tests
dict | solution_type
stringclasses 2
values | programming_language
stringclasses 5
values | solution
stringlengths 1
983k
|
---|---|---|---|---|---|---|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | python3 | n, m = map(int, input().split())
a =list(map(int, input().split()))
t = max(a[0] - 1, n - a[-1])
for i in range(1, m):t = max(t, (a[i - 1] - a[i]) // 2)
print(t)
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
int main(void) {
int n, m;
cin >> n >> m;
vector<int> se;
se.resize(m);
for (int i = (0); i < (m); ++i) cin >> se[i];
int answer = 0;
answer = max(answer, se[0] - 1);
for (int i = (0); i < (m - 1); ++i)
answer = max(answer, (se[i + 1] - se[i] - 1) / 2);
answer = max(answer, n - se[m - 1]);
cout << answer << endl;
return 0;
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
long long esp_org, esp_new;
int N;
struct P {
int x, y, z;
int dist(P p) { return abs(x - p.x) + abs(y - p.y) + abs(z - p.z); }
P rotZ() { return {y, N - x - 1, z}; }
P rotY() { return {z, y, N - x - 1}; }
P rotX() { return {x, z, N - y - 1}; }
bool valid() {
if (x < 0 || x >= N) return false;
if (y < 0 || y >= N) return false;
if (z < 0 || z >= N) return false;
return true;
}
string toString() {
stringstream ss;
ss << "(" << x << " " << y << " " << z << ")";
return ss.str();
}
};
bool operator<(const P &a, const P &b) {
if (a.x != b.x) return a.x < b.x;
if (a.y != b.y) return a.y < b.y;
return a.z < b.z;
}
bool operator==(const P &a, const P &b) {
if (a.x != b.x) return false;
if (a.y != b.y) return false;
return a.z == b.z;
}
P operator+(P a, P b) {
a.x += b.x;
a.y += b.y;
a.z += b.z;
return a;
};
struct NODE {
vector<P> p;
int phase;
int cost;
};
bool operator<(const NODE &a, const NODE &b) {
if (a.phase != b.phase) return a.phase < b.phase;
return a.p < b.p;
}
int dx[] = {-1, 1, 0, 0, 0, 0, 0};
int dy[] = {0, 0, -1, 1, 0, 0, 0, 0};
int dz[] = {0, 0, 0, 0, -1, 1, 0, 0, 0, 0};
vector<P> rot(vector<P> p, int id) {
if (id == 0) {
p[0] = p[0].rotZ();
if (p[0].z == p[1].z) p[1] = p[1].rotZ();
}
if (id == 1) {
p[0] = p[0].rotY();
if (p[0].y == p[1].y) p[1] = p[1].rotY();
}
if (id == 2) {
p[0] = p[0].rotX();
if (p[0].x == p[1].x) p[1] = p[1].rotX();
}
if (id == 3) {
p[0] = p[0].rotZ().rotZ().rotZ();
if (p[0].z == p[1].z) p[1] = p[1].rotZ().rotZ().rotZ();
}
if (id == 4) {
p[0] = p[0].rotY().rotY().rotY();
if (p[0].y == p[1].y) p[1] = p[1].rotY().rotY().rotY();
}
if (id == 5) {
p[0] = p[0].rotX().rotX().rotX();
if (p[0].x == p[1].x) p[1] = p[1].rotX().rotX().rotX();
}
return p;
}
int main() {
cin >> N;
vector<P> c;
for (int i = 0; i < N; i++) {
int x, y, z;
cin >> x >> y >> z;
c.push_back({x, y, z});
}
c.resize(2);
N = 100000;
c[0] = {0, 0, 0};
c[1] = {N - 1, N - 1, N - 1};
map<NODE, int> done;
deque<NODE> Q;
int ans = 1e9;
Q.push_back({c, 0, 0});
while (Q.size()) {
NODE q = Q.front();
Q.pop_front();
if (done[q]++) continue;
ans = min(ans, q.cost + q.p[0].dist(q.p[1]));
if (q.phase == 2) continue;
if (q.phase == 0 || q.phase == 2) {
for (int i = 0; i < 6; i++) {
P ne = q.p[0] + P{dx[i], dy[i], dz[i]};
if (!ne.valid()) continue;
NODE nextq = q;
nextq.cost++;
nextq.p[0] = ne;
nextq.phase++;
if (!done[nextq]) Q.push_back(nextq);
}
} else if (q.phase == 1) {
for (int i = 0; i < 6; i++) {
NODE nextq = q;
nextq.cost++;
nextq.p = rot(nextq.p, i);
if (!done[nextq]) Q.push_back(nextq);
}
}
q.phase++;
Q.push_front(q);
}
cout << done.size() << endl;
cout << ans << endl;
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
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;
}
void mainmain() {
int ans = 0;
int n, m;
cin >> n >> m;
vector<int> v(m);
for (int(i) = (0); (i) < ((m)); ++(i)) {
cin >> v[i];
}
sort((v).begin(), (v).end());
for (int(i) = (0); (i) < ((v.size() - 1)); ++(i)) {
ans = max(ans, v[i + 1] - v[i]);
}
ans = (ans + 1) / 2;
ans = max(ans, v[0] - 1);
ans = max(ans, n - v.back());
cout << ans << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout << fixed << setprecision(20);
mainmain();
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
static const long long INF = 1LL << 61LL;
int N, M;
int A[100010];
int temp = 1;
int ans;
int main() {
cin >> N >> M;
for (int i = 0; i < M; ++i) {
int a;
cin >> a;
A[a] = 1;
}
for (int i = 1; i <= N; ++i) {
if (A[i] == 1) {
if (temp == 1) {
int t = (i - temp);
temp = i;
ans = max(ans, t);
continue;
}
int t = (i - temp - 1) / 2;
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;
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #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 >> now;
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;
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | /*
SA-IS
O(??????N+???????¨?K)??§??????????????§?????§????????????O(N)
s[]?????°?????§????????????char??§????????????????????°??????
sa_lcp.cpp??¨???????????????
sa[0]=N????????£?????????
char??????,
string s;
s.c_str()
lcp???O(N)
*/
#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 pb push_back
using namespace std;
namespace SuffixArray{
template<class T>
void induce(int N,const T s[],bool is[],int sa[],int lbase[],int K){
int it[K+1];
copy_n(lbase,K+1,it);
rep(i,N+1){
if(sa[i]>=1&&!is[sa[i]-1]){
int c=s[sa[i]-1];
sa[it[c]++]=sa[i]-1;
}
}
copy_n(lbase,K+1,it);
for(int i=N;i>0;i--){
if(sa[i]>=1&&is[sa[i]-1]){
int c=s[sa[i]-1];
sa[--it[c+1]]=sa[i]-1;
}
}
}
template<class T>
void SA(int N,const T s[],int sa[],int K){
bool is[N+1]; //stype?
int lcnt[K+1]={},scnt[K+1]={};
is[N]=1;
for(int i=N-1;i>=0;i--){
if(i==N-1||s[i]>s[i+1]) is[i]=0;
else if(s[i]<s[i+1]) is[i]=1;
else is[i]=is[i+1];
if(!is[i]) lcnt[(int)s[i]]++;
else scnt[(int)s[i]]++;
}
vector<int> v; //LMSs
int lms[N+1];
fill_n(lms,N+1,-1);
int c=0;
rep1(i,N-1){
if(!is[i-1]&&is[i]){
lms[i]=c++;
v.pb(i);
}
}
int lbase[K+1],sbase[K+1];
lbase[0]=1,sbase[0]=1+lcnt[0];
rep1(i,K){
lbase[i]=sbase[i-1]+scnt[i-1];
sbase[i]=lbase[i]+lcnt[i];
}
if(!v.empty()){
vector<int> v2=v;
int it[K+1]; //iterate
copy_n(sbase,K+1,it);
fill_n(sa,N+1,-1);
sa[0]=N;
rep(i,v.size()){
int c=s[v[i]];
sa[it[c]++]=v[i];
}
induce(N,s,is,sa,lbase,K);
int c=0;
rep1(i,N) if(lms[sa[i]]>=0) v[c++]=sa[i];
int s2[v.size()],sa2[v.size()+1];
c=0;
s2[lms[v[0]]]=0;
for(int i=1;i<(int)v.size();i++){
int l=v[i-1],r=v[i];
while(true){
if(s[l]!=s[r]){
c++;
break;
}
l++,r++;
if(lms[l]>=0||lms[r]>=0){
if(lms[l]<0||lms[r]<0) c++;
break;
}
}
s2[lms[v[i]]]=c;
}
SA(v.size(),s2,sa2,c);
rep1(i,v.size()) v[i-1]=v2[sa2[i]];
}
int it[K+1];
copy_n(sbase,K+1,it);
fill_n(sa,N+1,-1);
sa[0]=N;
rep(i,v.size()){
int c=s[v[i]];
sa[it[c]++]=v[i];
}
induce(N,s,is,sa,lbase,K);
}
template<class T>
void LCP(int N,const T s[],const int sa[],int lcp[]){
int isa[N+1];
rep(i,N+1) isa[sa[i]]=i;
int h=0;
rep(i,N){
int j=sa[isa[i]-1];
if(h>0) h--;
for(;j+h<N&&i+h<N;h++){
if(s[j+h]!=s[i+h]) break;
}
lcp[isa[i]-1]=h;
// printf("lcp[%d]=%d\n",isa[i]-1,h);
}
}
}
int main(){
string s;
int sa[100],lcp[100];
cin>>s;
int N=s.size();
SuffixArray::SA(N,s.c_str(),sa,256);
SuffixArray::LCP(N,s.c_str(),sa,lcp);
rep(i,N+1) cout<<sa[i]<<" ";
} |
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, A[100000], ans;
int i;
cin >> n >> m;
for (i = 0; i < m; i++) {
cin >> A[i];
}
if (m == 1) {
cout << max(n - A[0], A[0] - 1) << endl;
return -1;
} else if (m == 2) {
ans = max(A[0] - 1, n - A[1]);
ans = (ans, (A[1] - A[0]) / 2);
cout << ans << endl;
return -1;
} else {
for (i = 0; i < m; i++) {
if (i == 0) {
ans = A[0] - 1;
continue;
} else if (i = m - 1) {
ans = max(ans, n - A[m - 1]);
cout << ans << endl;
return 0;
} else {
if ((A[i] - A[i - 1]) % 2 == 0) {
ans = max(ans, (A[i] - A[i - 1]) / 2);
} else {
ans = max(ans, (A[i] - A[i - 1] / 2 + 1));
}
}
}
}
return 0;
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
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.first << "," << p.second << ")";
return o;
}
template <class T>
ostream &operator<<(ostream &o, const vector<T> &v) {
o << "[";
for (T t : v) {
o << t << ",";
}
o << "]";
return o;
}
class UnionFind {
public:
vector<int> par, rank;
UnionFind(int sz) : par(sz, -1), rank(sz, 0) {}
int find(int x) {
if (par[x] < 0)
return x;
else
return par[x] = find(par[x]);
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return;
if (rank[x] < rank[y]) swap(x, y);
par[x] += par[y];
par[y] = x;
if (rank[x] == rank[y]) rank[x]++;
}
inline bool same(int x, int y) { return find(x) == find(y); }
inline int size(int x) { return -par[find(x)]; }
};
int main() {
int n, m;
cin >> n >> m;
UnionFind uf(n);
for (int i = (int)(0); i < (int)(m); i++) {
int s, t;
cin >> s >> t;
s--;
t--;
uf.unite(s, t);
}
int ans = 0;
for (int i = (int)(0); i < (int)(n); i++) {
if (uf.size(i) == 1)
ans++;
else if (uf.par[i] < 0)
ans--;
}
cout << abs(ans) << endl;
return 0;
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
bool ok(long long t, int n, int m, vector<long long> x) {
long long p = 0;
for (int i = 0; i < m; i++) {
if (p < x[i]) {
if (x[i] - p > t) {
return false;
}
p = max(x[i] + (t - 2 * (x[i] - p)) + 1, x[i] + (t - (x[i] - p)) / 2 + 1);
} else {
p = max(p, x[i] + t + 1);
}
if (p >= n) {
return true;
}
}
return false;
}
int main(void) {
int n, m;
cin >> n >> m;
vector<long long> x(m);
for (int i = 0; i < m; i++) {
cin >> x[i];
x[i]--;
}
if (n == m) {
cout << 0 << endl;
return 0;
}
long long l = 0;
long long r = 3e9;
while (r - l > 1) {
long long mid = (r + l) / 2;
if (ok(mid, n, m, x)) {
r = mid;
} else {
l = mid;
}
}
cout << r << endl;
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
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) {
auto it = a.lower_bound(i);
int mi = N;
mi = min(mi, *it - i);
if (it != a.begin()) {
it--;
mi = min(mi, i - *it);
}
ma = max(ma, mi);
}
cout << ma << endl;
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
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;
if (!a) a++;
ans = max(ans, a);
}
}
cout << ans << endl;
}
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
template <class X>
void print(X Target) {
cout << Target << '\n';
}
bool check[100001];
bool tmp[100001];
signed main() {
ios::sync_with_stdio(false);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a;
cin >> a;
check[a] = true;
}
int cnt = 0;
while (true) {
memcpy(tmp, check, sizeof(tmp));
for (int i = 1; i <= n; i++) {
if (check[i]) {
if (0 < i - 1 && !tmp[i - 1]) {
tmp[i - 1] = true;
}
if (i + 1 <= n && !tmp[i + 1]) {
tmp[i + 1] = true;
}
}
}
cnt++;
bool finish = true;
for (int i = 1; i <= n; i++) {
if (!tmp[i]) {
finish = false;
break;
}
}
if (finish) break;
memcpy(check, tmp, sizeof(check));
}
print(cnt);
return (0);
}
|
p01059 Gossip | Problem
N idols, numbered from 1 to n in order, are lined up in a row.
Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1.
At time 0, m idols with numbers a1, a2, ..., am have secret information. Find the minimum amount of time all idols can get confidential information.
Constraints
* 2 ≤ n ≤ 105
* 1 ≤ m ≤ n
* 1 ≤ ai ≤ n
* All ai values are different
* ai are given in ascending order
Input
The input is given in the following format.
n m
a1 a2 ... am
Two integers n and m are given on the first line, separated by blanks.
On the second line, m integers a1, a2, ..., am are given, separated by blanks.
Output
Outputs the minimum time that information is transmitted to all idles on one line.
Examples
Input
3 2
1 3
Output
1
Input
10 3
2 5 7
Output
3
Input
10 5
2 5 6 8 10
Output
1
Input
100000 1
1
Output
99999 | {
"input": [
"10 3\n2 5 7",
"100000 1\n1",
"10 5\n2 5 6 8 10",
"3 2\n1 3"
],
"output": [
"3",
"99999",
"1",
"1"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
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;
}
void mainmain() {
int ans = 0;
int n, m;
cin >> n >> m;
vector<int> v(m);
for (int(i) = (0); (i) < ((m)); ++(i)) {
cin >> v[i];
}
v.push_back(0);
v.push_back(n + 1);
sort((v).begin(), (v).end());
for (int(i) = (0); (i) < ((v.size() - 1)); ++(i)) {
ans = max(ans, v[i + 1] - v[i]);
}
ans = (ans + 1) / 2;
cout << ans << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout << fixed << setprecision(20);
mainmain();
}
|
p01191 Grated Radish | Grated radish (daikon-oroshi) is one of the essential spices in Japanese cuisine. As the name shows, it’s made by grating white radish.
You are developing an automated robot for grating radish. You have finally finished developing mechan- ical modules that grates radish according to given instructions from the microcomputer. So you need to develop the software in the microcomputer that controls the mechanical modules. As the first step, you have decided to write a program that simulates the given instructions and predicts the resulting shape of the radish.
Input
The input consists of a number of test cases. The first line on each case contains two floating numbers R and L (in centimeters), representing the radius and the length of the cylinder-shaped radish, respectively. The white radish is placed in the xyz-coordinate system in such a way that cylinder’s axis of rotational symmetry lies on the z axis.
<image>
Figure 1: The placement of the white radish
The next line contains a single integer N, the number of instructions. The following N lines specify instructions given to the grating robot. Each instruction consists of two floating numbers θ and V, where θ is the angle of grating plane in degrees, and V (in cubic centimeters) is the volume of the grated part of the radish.
You may assume the following conditions:
* the direction is measured from positive x axis (0 degree) to positive y axis (90 degrees),
* 1 ≤ R ≤ 5 (in centimeters),
* 1 ≤ L ≤ 40 (in centimeters),
* 0 ≤ θ < 360, and
* the sum of V’s is the smaller than the volume of the given white radish.
<image>
Figure 2: An example of grating
Output
For each test case, print out in one line two numbers that indicate the shape of the base side (the side parallel to xy-plane) of the remaining radish after the entire grating procedure is finished, where the first number of the total length is the linear (straight) part and the second is the total length of the curved part.
You may output an arbitrary number of digits after the decimal points, provided that difference from the true answer is smaller than 10-6 centimeters.
Example
Input
2
1 2
1
42 3.141592653589793
5 20
3
0 307.09242465218927
180 307.09242465218927
90 728.30573874452591
Output
2.0 3.141592653589793
8.660254038 5.235987756 | {
"input": [
"2\n1 2\n1\n42 3.141592653589793\n5 20\n3\n0 307.09242465218927\n180 307.09242465218927\n90 728.30573874452591"
],
"output": [
"2.0 3.141592653589793\n8.660254038 5.235987756"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
} |
p01191 Grated Radish | Grated radish (daikon-oroshi) is one of the essential spices in Japanese cuisine. As the name shows, it’s made by grating white radish.
You are developing an automated robot for grating radish. You have finally finished developing mechan- ical modules that grates radish according to given instructions from the microcomputer. So you need to develop the software in the microcomputer that controls the mechanical modules. As the first step, you have decided to write a program that simulates the given instructions and predicts the resulting shape of the radish.
Input
The input consists of a number of test cases. The first line on each case contains two floating numbers R and L (in centimeters), representing the radius and the length of the cylinder-shaped radish, respectively. The white radish is placed in the xyz-coordinate system in such a way that cylinder’s axis of rotational symmetry lies on the z axis.
<image>
Figure 1: The placement of the white radish
The next line contains a single integer N, the number of instructions. The following N lines specify instructions given to the grating robot. Each instruction consists of two floating numbers θ and V, where θ is the angle of grating plane in degrees, and V (in cubic centimeters) is the volume of the grated part of the radish.
You may assume the following conditions:
* the direction is measured from positive x axis (0 degree) to positive y axis (90 degrees),
* 1 ≤ R ≤ 5 (in centimeters),
* 1 ≤ L ≤ 40 (in centimeters),
* 0 ≤ θ < 360, and
* the sum of V’s is the smaller than the volume of the given white radish.
<image>
Figure 2: An example of grating
Output
For each test case, print out in one line two numbers that indicate the shape of the base side (the side parallel to xy-plane) of the remaining radish after the entire grating procedure is finished, where the first number of the total length is the linear (straight) part and the second is the total length of the curved part.
You may output an arbitrary number of digits after the decimal points, provided that difference from the true answer is smaller than 10-6 centimeters.
Example
Input
2
1 2
1
42 3.141592653589793
5 20
3
0 307.09242465218927
180 307.09242465218927
90 728.30573874452591
Output
2.0 3.141592653589793
8.660254038 5.235987756 | {
"input": [
"2\n1 2\n1\n42 3.141592653589793\n5 20\n3\n0 307.09242465218927\n180 307.09242465218927\n90 728.30573874452591"
],
"output": [
"2.0 3.141592653589793\n8.660254038 5.235987756"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01191 Grated Radish | Grated radish (daikon-oroshi) is one of the essential spices in Japanese cuisine. As the name shows, it’s made by grating white radish.
You are developing an automated robot for grating radish. You have finally finished developing mechan- ical modules that grates radish according to given instructions from the microcomputer. So you need to develop the software in the microcomputer that controls the mechanical modules. As the first step, you have decided to write a program that simulates the given instructions and predicts the resulting shape of the radish.
Input
The input consists of a number of test cases. The first line on each case contains two floating numbers R and L (in centimeters), representing the radius and the length of the cylinder-shaped radish, respectively. The white radish is placed in the xyz-coordinate system in such a way that cylinder’s axis of rotational symmetry lies on the z axis.
<image>
Figure 1: The placement of the white radish
The next line contains a single integer N, the number of instructions. The following N lines specify instructions given to the grating robot. Each instruction consists of two floating numbers θ and V, where θ is the angle of grating plane in degrees, and V (in cubic centimeters) is the volume of the grated part of the radish.
You may assume the following conditions:
* the direction is measured from positive x axis (0 degree) to positive y axis (90 degrees),
* 1 ≤ R ≤ 5 (in centimeters),
* 1 ≤ L ≤ 40 (in centimeters),
* 0 ≤ θ < 360, and
* the sum of V’s is the smaller than the volume of the given white radish.
<image>
Figure 2: An example of grating
Output
For each test case, print out in one line two numbers that indicate the shape of the base side (the side parallel to xy-plane) of the remaining radish after the entire grating procedure is finished, where the first number of the total length is the linear (straight) part and the second is the total length of the curved part.
You may output an arbitrary number of digits after the decimal points, provided that difference from the true answer is smaller than 10-6 centimeters.
Example
Input
2
1 2
1
42 3.141592653589793
5 20
3
0 307.09242465218927
180 307.09242465218927
90 728.30573874452591
Output
2.0 3.141592653589793
8.660254038 5.235987756 | {
"input": [
"2\n1 2\n1\n42 3.141592653589793\n5 20\n3\n0 307.09242465218927\n180 307.09242465218927\n90 728.30573874452591"
],
"output": [
"2.0 3.141592653589793\n8.660254038 5.235987756"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-12;
const double pi = atan2(0.0, -1.0);
double cross(const complex<double>& a, const complex<double>& b) {
return imag(conj(a) * b);
}
double dot(const complex<double>& a, const complex<double>& b) {
return real(conj(a) * b);
}
complex<double> unit(const complex<double>& p) { return 1 / abs(p) * p; }
complex<double> unit(double a) { return complex<double>(cos(a), sin(a)); }
complex<double> rot90(const complex<double>& p) {
return p * complex<double>(0, 1);
}
int ccw(const complex<double>& a, complex<double> b, complex<double> 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 complex<double>& l0, const complex<double>& l1,
const complex<double>& m0, const complex<double>& m1) {
return abs(cross(l1 - l0, m1 - m0)) > EPS;
}
complex<double> crosspoint(const complex<double>& l0, const complex<double>& l1,
const complex<double>& m0,
const complex<double>& 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<complex<double>, complex<double> > > es;
C(double R) : R(R) {}
};
double size(const C& c) {
double t = 0;
for (int i = 0; i < (int)(c.as.size()); i++)
t += c.as[i].second - c.as[i].first;
double s = c.R * c.R * (2 * pi - t);
for (int i = 0; i < (int)(c.es.size()); i++)
s += cross(c.es[i].first, c.es[i].second);
return s / 2;
}
C cut(const C& c, double L, double t) {
const complex<double>& ori = L * unit(t);
const double sl = sqrt(c.R * c.R - L * L);
const complex<double> p0 = ori - sl * rot90(unit(t));
const complex<double> p1 = ori + sl * rot90(unit(t));
C nc(c);
const double a0 = arg(p0), a1 = arg(p1);
if (a0 <= a1)
nc.as.push_back(make_pair(a0, a1));
else {
nc.as.push_back(make_pair(-pi, a1));
nc.as.push_back(make_pair(a0, pi));
}
sort(nc.as.begin(), nc.as.end());
int m = 0;
for (int i = 0; i < (int)(nc.as.size()); i++) {
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);
bool f = true;
complex<double> s0 = p0, s1 = p1;
for (int i = 0; i < (int)(nc.es.size()); i++) {
if (!intersectLL(nc.es[i].first, nc.es[i].second, p0, p1)) continue;
const complex<double> 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;
}
for (int i = 0; i < (int)(nc.es.size()); i++) {
if (!intersectLL(nc.es[i].first, nc.es[i].second, p0, p1)) continue;
const complex<double> 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(make_pair(s0, s1));
m = 0;
for (int i = 0; i < (int)(nc.es.size()); i++) {
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);
for (int i = 0; i < (int)(n); i++) {
double t, V;
scanf("%lf%lf", &t, &V);
t = t / 180 * pi;
if (t >= pi) t -= 2 * pi;
const double s = size(c) - V / L;
double l = -R, r = R;
for (int _ = 0; _ < (int)(100); _++) {
const double mid = (l + r) / 2;
if (size(cut(c, mid, t)) < s)
l = mid;
else
r = mid;
}
c = cut(c, l, t);
}
double ansT = 0;
for (int i = 0; i < (int)(c.as.size()); i++)
ansT += c.as[i].second - c.as[i].first;
double ansE = 0;
for (int i = 0; i < (int)(c.es.size()); i++)
ansE += abs(c.es[i].second - c.es[i].first);
printf("%.9f %.9f\n", ansE, R * (2 * pi - ansT));
}
return 0;
}
|
p01191 Grated Radish | Grated radish (daikon-oroshi) is one of the essential spices in Japanese cuisine. As the name shows, it’s made by grating white radish.
You are developing an automated robot for grating radish. You have finally finished developing mechan- ical modules that grates radish according to given instructions from the microcomputer. So you need to develop the software in the microcomputer that controls the mechanical modules. As the first step, you have decided to write a program that simulates the given instructions and predicts the resulting shape of the radish.
Input
The input consists of a number of test cases. The first line on each case contains two floating numbers R and L (in centimeters), representing the radius and the length of the cylinder-shaped radish, respectively. The white radish is placed in the xyz-coordinate system in such a way that cylinder’s axis of rotational symmetry lies on the z axis.
<image>
Figure 1: The placement of the white radish
The next line contains a single integer N, the number of instructions. The following N lines specify instructions given to the grating robot. Each instruction consists of two floating numbers θ and V, where θ is the angle of grating plane in degrees, and V (in cubic centimeters) is the volume of the grated part of the radish.
You may assume the following conditions:
* the direction is measured from positive x axis (0 degree) to positive y axis (90 degrees),
* 1 ≤ R ≤ 5 (in centimeters),
* 1 ≤ L ≤ 40 (in centimeters),
* 0 ≤ θ < 360, and
* the sum of V’s is the smaller than the volume of the given white radish.
<image>
Figure 2: An example of grating
Output
For each test case, print out in one line two numbers that indicate the shape of the base side (the side parallel to xy-plane) of the remaining radish after the entire grating procedure is finished, where the first number of the total length is the linear (straight) part and the second is the total length of the curved part.
You may output an arbitrary number of digits after the decimal points, provided that difference from the true answer is smaller than 10-6 centimeters.
Example
Input
2
1 2
1
42 3.141592653589793
5 20
3
0 307.09242465218927
180 307.09242465218927
90 728.30573874452591
Output
2.0 3.141592653589793
8.660254038 5.235987756 | {
"input": [
"2\n1 2\n1\n42 3.141592653589793\n5 20\n3\n0 307.09242465218927\n180 307.09242465218927\n90 728.30573874452591"
],
"output": [
"2.0 3.141592653589793\n8.660254038 5.235987756"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-12;
const double pi = atan2(0.0, -1.0);
double cross(const complex<double>& a, const complex<double>& b) {
return imag(conj(a) * b);
}
double dot(const complex<double>& a, const complex<double>& b) {
return real(conj(a) * b);
}
complex<double> unit(const complex<double>& p) { return 1 / abs(p) * p; }
complex<double> unit(double a) { return complex<double>(cos(a), sin(a)); }
complex<double> rot90(const complex<double>& p) {
return p * complex<double>(0, 1);
}
int ccw(const complex<double>& a, complex<double> b, complex<double> 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 complex<double>& l0, const complex<double>& l1,
const complex<double>& m0, const complex<double>& m1) {
return abs(cross(l1 - l0, m1 - m0)) > EPS;
}
complex<double> crosspoint(const complex<double>& l0, const complex<double>& l1,
const complex<double>& m0,
const complex<double>& 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<complex<double>, complex<double> > > es;
C(double R) : R(R) {}
};
double size(const C& c) {
double t = 0;
for (int i = 0; i < (int)(c.as.size()); i++)
t += c.as[i].second - c.as[i].first;
double s = c.R * c.R * (2 * pi - t);
for (int i = 0; i < (int)(c.es.size()); i++)
s += cross(c.es[i].first, c.es[i].second);
return s / 2;
}
double norma(double t) {
if (t < -pi) t += 2 * pi;
if (t > pi) t -= 2 * pi;
return t;
}
C cut(const C& c, double dt, double t) {
C nc(c);
if (fabs(dt - pi) < EPS) {
nc.as.clear();
nc.as.push_back(make_pair(-pi, pi));
nc.es.clear();
return nc;
}
const complex<double> p0 = c.R * unit(t - dt);
const complex<double> p1 = c.R * unit(t + dt);
const double a0 = norma(t - dt), a1 = norma(t + dt);
if (a0 <= a1)
nc.as.push_back(make_pair(a0, a1));
else {
nc.as.push_back(make_pair(-pi, a1));
nc.as.push_back(make_pair(a0, pi));
}
sort(nc.as.begin(), nc.as.end());
int m = 0;
for (int i = 0; i < (int)(nc.as.size()); i++) {
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);
bool f = true;
complex<double> s0 = p0, s1 = p1;
for (int i = 0; i < (int)(nc.es.size()); i++) {
if (!intersectLL(nc.es[i].first, nc.es[i].second, p0, p1)) continue;
const complex<double> 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;
}
for (int i = 0; i < (int)(nc.es.size()); i++) {
if (!intersectLL(nc.es[i].first, nc.es[i].second, p0, p1)) continue;
const complex<double> 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(make_pair(s0, s1));
m = 0;
for (int i = 0; i < (int)(nc.es.size()); i++) {
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);
for (int i = 0; i < (int)(n); i++) {
double t, V;
scanf("%lf%lf", &t, &V);
t = t / 180 * pi;
if (t >= pi) t -= 2 * pi;
const double s = size(c) - V / L;
double l = 0, r = pi;
for (int _ = 0; _ < (int)(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;
for (int i = 0; i < (int)(c.as.size()); i++)
ansT += c.as[i].second - c.as[i].first;
double ansE = 0;
for (int i = 0; i < (int)(c.es.size()); i++)
ansE += abs(c.es[i].second - c.es[i].first);
printf("%.9f %.9f\n", ansE, R * (2 * pi - ansT));
}
return 0;
}
|
p01191 Grated Radish | Grated radish (daikon-oroshi) is one of the essential spices in Japanese cuisine. As the name shows, it’s made by grating white radish.
You are developing an automated robot for grating radish. You have finally finished developing mechan- ical modules that grates radish according to given instructions from the microcomputer. So you need to develop the software in the microcomputer that controls the mechanical modules. As the first step, you have decided to write a program that simulates the given instructions and predicts the resulting shape of the radish.
Input
The input consists of a number of test cases. The first line on each case contains two floating numbers R and L (in centimeters), representing the radius and the length of the cylinder-shaped radish, respectively. The white radish is placed in the xyz-coordinate system in such a way that cylinder’s axis of rotational symmetry lies on the z axis.
<image>
Figure 1: The placement of the white radish
The next line contains a single integer N, the number of instructions. The following N lines specify instructions given to the grating robot. Each instruction consists of two floating numbers θ and V, where θ is the angle of grating plane in degrees, and V (in cubic centimeters) is the volume of the grated part of the radish.
You may assume the following conditions:
* the direction is measured from positive x axis (0 degree) to positive y axis (90 degrees),
* 1 ≤ R ≤ 5 (in centimeters),
* 1 ≤ L ≤ 40 (in centimeters),
* 0 ≤ θ < 360, and
* the sum of V’s is the smaller than the volume of the given white radish.
<image>
Figure 2: An example of grating
Output
For each test case, print out in one line two numbers that indicate the shape of the base side (the side parallel to xy-plane) of the remaining radish after the entire grating procedure is finished, where the first number of the total length is the linear (straight) part and the second is the total length of the curved part.
You may output an arbitrary number of digits after the decimal points, provided that difference from the true answer is smaller than 10-6 centimeters.
Example
Input
2
1 2
1
42 3.141592653589793
5 20
3
0 307.09242465218927
180 307.09242465218927
90 728.30573874452591
Output
2.0 3.141592653589793
8.660254038 5.235987756 | {
"input": [
"2\n1 2\n1\n42 3.141592653589793\n5 20\n3\n0 307.09242465218927\n180 307.09242465218927\n90 728.30573874452591"
],
"output": [
"2.0 3.141592653589793\n8.660254038 5.235987756"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
int main() {}
|
p01191 Grated Radish | Grated radish (daikon-oroshi) is one of the essential spices in Japanese cuisine. As the name shows, it’s made by grating white radish.
You are developing an automated robot for grating radish. You have finally finished developing mechan- ical modules that grates radish according to given instructions from the microcomputer. So you need to develop the software in the microcomputer that controls the mechanical modules. As the first step, you have decided to write a program that simulates the given instructions and predicts the resulting shape of the radish.
Input
The input consists of a number of test cases. The first line on each case contains two floating numbers R and L (in centimeters), representing the radius and the length of the cylinder-shaped radish, respectively. The white radish is placed in the xyz-coordinate system in such a way that cylinder’s axis of rotational symmetry lies on the z axis.
<image>
Figure 1: The placement of the white radish
The next line contains a single integer N, the number of instructions. The following N lines specify instructions given to the grating robot. Each instruction consists of two floating numbers θ and V, where θ is the angle of grating plane in degrees, and V (in cubic centimeters) is the volume of the grated part of the radish.
You may assume the following conditions:
* the direction is measured from positive x axis (0 degree) to positive y axis (90 degrees),
* 1 ≤ R ≤ 5 (in centimeters),
* 1 ≤ L ≤ 40 (in centimeters),
* 0 ≤ θ < 360, and
* the sum of V’s is the smaller than the volume of the given white radish.
<image>
Figure 2: An example of grating
Output
For each test case, print out in one line two numbers that indicate the shape of the base side (the side parallel to xy-plane) of the remaining radish after the entire grating procedure is finished, where the first number of the total length is the linear (straight) part and the second is the total length of the curved part.
You may output an arbitrary number of digits after the decimal points, provided that difference from the true answer is smaller than 10-6 centimeters.
Example
Input
2
1 2
1
42 3.141592653589793
5 20
3
0 307.09242465218927
180 307.09242465218927
90 728.30573874452591
Output
2.0 3.141592653589793
8.660254038 5.235987756 | {
"input": [
"2\n1 2\n1\n42 3.141592653589793\n5 20\n3\n0 307.09242465218927\n180 307.09242465218927\n90 728.30573874452591"
],
"output": [
"2.0 3.141592653589793\n8.660254038 5.235987756"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
const double pi = atan2(0.0, -1.0);
double cross(const complex<double>& a, const complex<double>& b) {
return imag(conj(a) * b);
}
double dot(const complex<double>& a, const complex<double>& b) {
return real(conj(a) * b);
}
complex<double> unit(const complex<double>& p) { return 1 / abs(p) * p; }
complex<double> unit(double a) { return complex<double>(cos(a), sin(a)); }
complex<double> rot90(const complex<double>& p) {
return p * complex<double>(0, 1);
}
int ccw(const complex<double>& a, complex<double> b, complex<double> 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 complex<double>& l0, const complex<double>& l1,
const complex<double>& m0, const complex<double>& m1) {
return abs(cross(l1 - l0, m1 - m0)) > EPS;
}
complex<double> crosspoint(const complex<double>& l0, const complex<double>& l1,
const complex<double>& m0,
const complex<double>& 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<complex<double>, complex<double> > > es;
C(double R) : R(R) {}
};
double size(const C& c) {
double t = 0;
for (int i = 0; i < (int)(c.as.size()); i++)
t += c.as[i].second - c.as[i].first;
double s = c.R * c.R * (2 * pi - t);
for (int i = 0; i < (int)(c.es.size()); i++)
s += cross(c.es[i].first, c.es[i].second);
return s / 2;
}
C cut(const C& c, double L, double t) {
const complex<double>& ori = L * unit(t);
const double sl = sqrt(c.R * c.R - L * L);
const complex<double> p0 = ori - sl * rot90(unit(t));
const complex<double> p1 = ori + sl * rot90(unit(t));
C nc(c);
const double a0 = arg(p0), a1 = arg(p1);
if (a0 <= a1)
nc.as.push_back(make_pair(a0, a1));
else {
nc.as.push_back(make_pair(-pi, a1));
nc.as.push_back(make_pair(a0, pi));
}
sort(nc.as.begin(), nc.as.end());
int m = 0;
for (int i = 0; i < (int)(nc.as.size()); i++) {
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);
bool f = true;
complex<double> s0 = p0, s1 = p1;
for (int i = 0; i < (int)(nc.es.size()); i++) {
if (!intersectLL(nc.es[i].first, nc.es[i].second, p0, p1)) continue;
const complex<double> 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;
}
for (int i = 0; i < (int)(nc.es.size()); i++) {
if (!intersectLL(nc.es[i].first, nc.es[i].second, p0, p1)) continue;
const complex<double> 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(make_pair(s0, s1));
m = 0;
for (int i = 0; i < (int)(nc.es.size()); i++) {
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);
for (int i = 0; i < (int)(n); i++) {
double t, V;
scanf("%lf%lf", &t, &V);
t = t / 180 * pi;
const double s = size(c) - V / L;
double l = -R, r = R;
for (int _ = 0; _ < (int)(100); _++) {
const double mid = (l + r) / 2;
if (size(cut(c, mid, t)) < s)
l = mid;
else
r = mid;
}
c = cut(c, l, t);
}
double ansT = 0;
for (int i = 0; i < (int)(c.as.size()); i++)
ansT += c.as[i].second - c.as[i].first;
double ansE = 0;
for (int i = 0; i < (int)(c.es.size()); i++)
ansE += abs(c.es[i].second - c.es[i].first);
printf("%.9f %.9f\n", ansE, R * (2 * pi - ansT));
}
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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のときに進む頂点を返す
*/
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | /*
* 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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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:;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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:;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | /*
* 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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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());
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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:;
}
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | 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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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Áµ½¢ÌÝgp
//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©ç^¦AP¶¸ÂTõ
bool isMatchOneByOne(char ch,string &cur){
// KvÅ êÎA±±ÅcurªdictàɶݵȢ©`FbN
/*
*/
while(1){
string nxt=cur;
nxt+=ch;
// ൡÌê©çÌêÖJÚÂ\ÈçÎ
if(_stepPrv.find(cur)!=_stepPrv.end()&&_stepPrv[cur].find(nxt)!=_stepPrv[cur].end()){
// ¡ñÌê©çßêéêÅA}b`·éà̪ é©ð`FbN
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ũ©çȯêÎAI¹
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:
// Rs[RXgN^ÆAãüZqÍgpÖ~É·é
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ܽÍó¶ñª[gm[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);
// ܾÇÁ³êĢȢÌÅ êÎAÇÁ·é
if(_dict.find(s)==_dict.end())_dict[s]=_vertex++;
}
}
// TõðOÉißéûüÖGbWðÔ
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¶Å\¬³êéÈçÎAGbWðø
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ßéûüÖGbWðÔ
for(map<string,int>::iterator it=_dict.begin();it!=_dict.end();it++){
if(it->first=="")continue;
// »Ý̶ñ©çæªi¶ðæè¢½àÌÖßêé©ÔÉ`FbN
// ßêȯêÎ[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µ½çAJڵȢ
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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | //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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | java | import java.util.*;
class State{
char x, y;
short cost;
String path;
char[] match;
State(char x, char y, short cost, String path, char[] match){
this.x = x;
this.y = y;
this.cost = cost;
this.path = path;
this.match = match;
}
public boolean equals(Object o){
State st = (State)o;
if(x != st.x || y != st.y){
return false;
}
for(int i = 0; i < match.length; i++){
if(match[i] != st.match[i]){
return false;
}
}
return true;
}
public int hashCode(){
int res = x * 841841 + y * 841;
for(int i = 0, p = 1; i < match.length; i++, p *= 10){
res += (int)(match[i]) * p;
}
return res;
}
}
public class Main{
static int h, w, n;
static char sx, sy, gx, gy;
static char t[][];
static String[] p;
static char[] ds = {'U', 'R', 'D', 'L'};
static int dx[] = {0, 1, 0, -1};
static int dy[] = {-1, 0, 1, 0};
static int bfs(){
LinkedList<State> open = new LinkedList<State>();
HashSet<State> closed = new HashSet<State>();
State st = new State(sx, sy, (short)0, "", new char[n]);
open.add(st);
closed.add(st);
while(!open.isEmpty()){
st = open.poll();
//System.out.println(st.path);
if(st.x == gx && st.y == gy){
return st.cost;
}
for(int i = 0; i < 4; i++){
char nx = (char)(st.x + dx[i]);
char ny = (char)(st.y + dy[i]);
if(0 > nx || 0 > ny || nx >= w || ny >= h || t[ny][nx] == '#'){
continue;
}
String npath = st.path + ds[i];
if(npath.length() > 10){
npath = npath.substring(1);
}
boolean flg = true;
char[] nmatch = new char[n];
for(int j = 0; j < n; j++){
nmatch[j] = (char)0;
for(int len = Math.min(p[j].length(), npath.length()); len > 0; len--){
boolean matchFlg = true;
for(int k = 0; k < len; k++){
if(npath.charAt(npath.length() - len + k) != p[j].charAt(k)){
matchFlg = false;
break;
}
}
if(matchFlg){
nmatch[j] = (char)len;
break;
}
}
if(nmatch[j] == p[j].length()){
flg = false;
break;
}
}
if(!flg){
continue;
}
State nst = new State(nx, ny, (short)(st.cost + 1), npath, nmatch);
if(!closed.contains(nst)){
closed.add(nst);
open.add(nst);
}
}
}
return -1;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
h = sc.nextInt();
w = sc.nextInt();
if(h == 0 && w == 0) break;
t = new char[h][w];
for(int i = 0; i < h; i++){
t[i] = sc.next().toCharArray();
for(int j = 0; j < w; j++){
if(t[i][j] == 'S'){
sx = (char)j;
sy = (char)i;
}
else if(t[i][j] == 'G'){
gx = (char)j;
gy = (char)i;
}
}
}
n = sc.nextInt();
p = new String[n];
for(int i = 0; i < n; i++){
p[i] = sc.next();
}
System.out.println(bfs());
}
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #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;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | // 12:17 - 13:14
#include<iostream>
#include<cmath>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<cassert>
#include<climits>
#include<map>
#include<queue>
#include<set>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define IINF (INT_MAX)
#define MAX_SP 15
#define MAX_LEN 60
using namespace std;
typedef pair<int,int> ii;
struct Data{
int cur,cost;
ii info;
Data(int cur=IINF,int cost=IINF,ii info=ii(IINF,IINF)):cur(cur),cost(cost),info(info){}
bool operator < (const Data& a)const{
return cost > a.cost;
}
};
int h,w,sp,gp,P;
char G[MAX_LEN][MAX_LEN];
/*
next_state[index][the number of match]
0 -> empty
1 -> spell[0]
2 -> spell[1]
...
*/
ii next_state[MAX_SP][MAX_SP][4];
int mincost[MAX_LEN*MAX_LEN][MAX_SP][MAX_SP];
string spell[MAX_SP];
int dx[] = {+0,+1,+0,-1};
int dy[] = {-1,+0,+1,+0};
char dc[] = {'U','R','D','L'};
ii getValue(string s){
rep(i,P+1){
int cur = 0;
rep(j,spell[i].size()){
if(s[cur] != spell[i][j]){
break;
}
cur++;
if(cur >= s.size()){
return ii(i,j+1);
}
}
}
return ii(0,0);
}
void INIT(){
rep(i,MAX_SP)rep(j,MAX_SP)rep(k,4)next_state[i][j][k] = ii(0,0);
rep(i,P+1){
rep(j,spell[i].size()+1){
rep(dir,4){
rep(k,j+1){
ii value = getValue(spell[i].substr(0,j).substr(k)+dc[dir]);
if(value != ii(0,0) && next_state[i][j][dir].second < value.second){
next_state[i][j][dir] = value;
}
}
}
}
}
}
inline bool isValid(int x,int y){
return ( 0 <= x && x < w && 0 <= y && y < h );
}
void compute(){
priority_queue<Data> Q;
Q.push(Data(sp,0,ii(0,0)));
rep(i,h*w)rep(j,MAX_SP)rep(k,MAX_SP)mincost[i][j][k] = IINF;
mincost[sp][0][0] = 0;
while(!Q.empty()){
Data data = Q.top(); Q.pop();
if(data.cur == gp){
cout << data.cost << endl;
return;
}
rep(dir,4){
int nx = data.cur % w + dx[dir];
int ny = data.cur / w + dy[dir];
if(!isValid(nx,ny))continue;
if(G[ny][nx] == '#')continue;
ii next = next_state[data.info.first][data.info.second][dir];
if(next.first != 0 && spell[next.first].size() == next.second)continue;
if(mincost[nx+ny*w][next.first][next.second] > data.cost + 1){
mincost[nx+ny*w][next.first][next.second] = data.cost + 1;
Q.push(Data(nx+ny*w,data.cost+1,next));
}
}
}
cout << -1 << endl;
}
bool cmp(const string& a,const string& b){
return a.size() < b.size();
}
int main(){
while(cin >> h >> w,h|w){
rep(i,h){
rep(j,w){
cin >> G[i][j];
if(G[i][j] == 'S'){
sp = j + i * w;
}
else if(G[i][j] == 'G'){
gp = j + i * w;
}
}
}
cin >> P;
spell[0].clear();
vector<string> tmp;
rep(i,P){
cin >> spell[i+1];
tmp.push_back(spell[i+1]);
}
sort(tmp.begin(),tmp.end(),cmp);
bool out[tmp.size()];
rep(i,tmp.size())out[i] = false;
rep(i,tmp.size()){
REP(j,i+1,tmp.size()){
if(tmp[j].find(tmp[i]) != string::npos){
out[j] = true;
}
}
}
vector<string> tmp2;
rep(i,tmp.size())if(!out[i]){
tmp2.push_back(tmp[i]);
}
P = tmp2.size();
rep(i,P){
spell[i+1] = tmp2[i];
}
INIT();
compute();
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e8;
const int dx[] = { 1, 0, -1, 0 };
const int dy[] = { 0, 1, 0, -1 };
const int var = 4;
string D = "DRUL";
struct node {
node *fail;
vector<node*> next;
vector<int> ok;
node() : fail(nullptr), next(var, nullptr) {}
};
class Aho_Corasick {
static int trans(char c) {
switch (c)
{
case 'R': return 0;
case 'D': return 1;
case 'L': return 2;
case 'U': return 3;
default: break;
}
exit(EXIT_FAILURE);
}
vector<int> unite(const vector<int>& a, const vector<int>& b) {
vector<int> res;
set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(res));
return res;
}
int K;
public:
node *root;
Aho_Corasick(const vector<string>& Ts) : K(Ts.size()), root(new node) {
node *now;
root->fail = root;
for (int i = 0; i < K; i++) {
auto &T = Ts[i];
now = root;
for (auto c : T) {
if (now->next[trans(c)] == nullptr) {
now->next[trans(c)] = new node;
}
now = now->next[trans(c)];
}
now->ok.push_back(i);
}
queue<node*> q;
for (int i = 0; i < var; i++) {
if (root->next[i] == nullptr) {
root->next[i] = root;
}
else {
root->next[i]->fail = root;
q.push(root->next[i]);
}
}
while (!q.empty()) {
now = q.front(); q.pop();
for (int i = 0; i < var; i++) {
if (now->next[i] != nullptr) {
node *nx = now->fail;
while (nx->next[i] == nullptr) {
nx = nx->fail;
}
now->next[i]->fail = nx->next[i];
now->next[i]->ok = unite(now->next[i]->ok, nx->next[i]->ok);
q.push(now->next[i]);
}
}
}
}
node* getnext(node* p, char c) {
while (p->next[trans(c)] == nullptr) p = p->fail;
return p->next[trans(c)];
}
};
using T = tuple<int, int, node*>;
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int n, m, p;
while (cin >> n >> m, n | m) {
vector<string> S(n);
int sx = 0, sy = 0, gx = 0, gy = 0;
for (int i = 0; i < n; i++) {
cin >> S[i];
for (int j = 0; j < (int)S[i].size(); j++) {
if (S[i][j] == 'S') {
sx = i;
sy = j;
}
else if (S[i][j] == 'G') {
gx = i;
gy = j;
}
}
}
cin >> p;
vector<string> pts(p);
for (int i = 0; i < p; i++) {
cin >> pts[i];
}
Aho_Corasick aho(pts);
vector<vector<map<node*, int>>> f(n, vector<map<node*, int>>(m));
queue<T> q;
q.push(make_tuple(sx, sy, aho.root));
f[sx][sy][aho.root] = 0;
while (!q.empty()) {
auto p = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int tx = get<0>(p) + dx[i], ty = get<1>(p) + dy[i];
node *t = aho.getnext(get<2>(p), D[i]);
if (0 <= tx && tx < n && 0 <= ty && ty < m && S[tx][ty] != '#' && t->ok.empty() && f[tx][ty].count(t) == 0) {
q.push(make_tuple(tx, ty, t));
f[tx][ty][t] = f[get<0>(p)][get<1>(p)][get<2>(p)] + 1;
}
}
}
int res = INF;
for (auto p : f[gx][gy]) {
res = min(res, p.second);
}
cout << (res != INF ? res : -1) << endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <vector>
#include <string>
#include <memory>
#include <set>
#include <map>
#include <queue>
#include <iostream>
using namespace std;
#define rep(i,n) for(int i=0,i##_len=n;i<i##_len;i++)
#define all(x) begin(x),end(x)
#define lim(x,r,l) (r<=x&&x<l)
typedef long long ll;
typedef long double ld;
struct PMA {
bool isRoot = false;
set<int> matched;
map<char, PMA*> nexts;
PMA* faild;
PMA() : matched() , nexts() , faild() { }
~PMA() {
for(auto&& n : nexts){
delete n.second;
}
}
static PMA build(const vector<string>& patterns) {
PMA root;
root.isRoot = true;
root.faild = &root;
for(int i = 0; i < patterns.size(); i++){
PMA* now = &root;
for(int j = 0; j < patterns[i].size(); j++){
if(now->nexts.find(patterns[i][j]) == now->nexts.end()){
now->nexts[patterns[i][j]] = new PMA;
}
now = now->nexts[patterns[i][j]];
}
now->matched.insert(i);
}
queue<PMA*> que;
for(auto&& next : root.nexts){
next.second->faild = &root;
que.push(next.second);
}
while(!que.empty()){
PMA* now = que.front(); que.pop();
for(auto&& next : now->nexts){
char c = next.first;
PMA* nextfaild = now->faild;
while(!(nextfaild->isRoot || nextfaild->nexts.find(c) != nextfaild->nexts.end())){
nextfaild = nextfaild->faild;
}
if(nextfaild->nexts.find(c) != nextfaild->nexts.end()){
now->nexts[c]->faild = nextfaild->nexts[c];
now->nexts[c]->matched.insert(
begin(nextfaild->nexts[c]->matched), end(nextfaild->nexts[c]->matched));
}else{
now->nexts[c]->faild = &root;
}
que.push(now->nexts[c]);
}
}
return root;
}
tuple<set<int>, PMA*> match(const string& str, int i = 0, PMA* now_ = nullptr){
set<int> res;
PMA* now = now_ ? now_ : this;
for(; i < str.size(); i++){
int c = str[i];
while(!(now->isRoot || now->nexts.find(c) != now->nexts.end())){
now = now->faild;
}
if(now->nexts.find(c) != now->nexts.end()){
now = now->nexts[c];
}
res.insert(begin(now->matched), end(now->matched));
}
return make_tuple(res, now);
}
};
const vector<int> d4x({1, 0, -1, 0});
const vector<int> d4y({0, -1, 0, 1});
const vector<string> d4c({"D", "L", "U", "R"});
int main(){
int n, m;
while(cin >> n >> m, n != 0){
vector<vector<char>> bd(n, vector<char>(m));
int sx, sy, gx, gy;
rep(i, n) { rep(j, m) {
cin >> bd[i][j];
if(bd[i][j] == 'S'){ sx = i; sy = j;}
if(bd[i][j] == 'G'){ gx = i; gy = j;}
} }
int p; cin >> p;
vector<string> patterns(p);
rep(i, p){
cin >> patterns[i];
}
PMA pma = PMA::build(patterns);
set<tuple<int, int, PMA*>> visited;
queue<tuple<int, int, PMA*, int>> que;
que.emplace(sx, sy, &pma, 0);
int res = ([&]{
while(!que.empty()){
int nx, ny, c; PMA* now;
tie(nx, ny, now, c) = que.front(); que.pop();
rep(d, 4){
int tx = nx + d4x[d], ty = ny+d4y[d];
tuple<set<int>, PMA*> matched = pma.match(string(d4c[d]), 0, now);
if(!(tx >= 0 && tx < n && ty >= 0 && ty < m &&
bd[tx][ty] != '#')){
continue;
}
if(!get<0>(matched).empty()){
continue;
}
tuple<int, int, PMA*> next(tx, ty, get<1>(matched));
if(visited.find(next) != visited.end()){
continue;
}
visited.insert(next);
if(tx == gx && ty == gy){
return c + 1;
}
que.emplace(tx, ty, get<1>(matched), c + 1);
}
}
return -1;
})();
cout << res << endl;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include "bits/stdc++.h"
#define REP(i, n) for (int i = 0; i < n; ++i)
// https://onlinejudge.u-aizu.ac.jp/status/users/EtoNagisa/submissions/1/2212/judge/3966278/C++14
using namespace std;
#include "bits/stdc++.h"
struct lower_alphabet {
static constexpr std::size_t char_size = 26;
static constexpr char min_char = 'a';
};
struct upper_alphabet {
static constexpr std::size_t char_size = 26;
static constexpr char min_char = 'A';
};
struct general_char {
static constexpr std::size_t char_size = 256;
static constexpr char min_char = 0;
};
template <typename character>
class aho_corasick {
public:
static constexpr std::size_t invalid_index = -1;
struct PMA {
std::size_t fail; // index of state correspond to fail suffix
std::vector<std::size_t> next, accept;
std::set<std::size_t> r_fail;
PMA() : fail(0), next(character::char_size, invalid_index) {}
};
std::vector<PMA> nodes;
std::size_t cnt;
aho_corasick() : cnt(0) {}
void build(const std::vector<std::string> &dict) {
add_node();
for (std::size_t i = 0; i < dict.size(); ++i) {
std::size_t now = 0;
for (std::size_t j = 0; j < dict[i].size(); ++j) {
std::size_t t = static_cast<size_t>(dict[i][j] - character::min_char);
if (nodes[now].next[t] == invalid_index) {
std::size_t next = size();
add_node();
nodes[now].next[t] = next;
}
now = nodes[now].next[t];
}
nodes[now].accept.push_back(i);
}
std::queue<std::size_t> q;
for (std::size_t i = 0; i < character::char_size; ++i) {
if (nodes[0].next[i] == invalid_index) {
nodes[0].next[i] = 0;
} else {
set_fail(nodes[0].next[i], 0);
q.push(nodes[0].next[i]);
}
}
while (!q.empty()) {
std::size_t p = q.front();
q.pop();
for (std::size_t i = 0; i < character::char_size; ++i) {
if (nodes[p].next[i] != invalid_index) {
std::size_t tmp = next(nodes[p].fail, i + character::min_char);
set_fail(nodes[p].next[i], tmp);
for (std::size_t ac : nodes[tmp].accept) {
nodes[nodes[p].next[i]].accept.push_back(ac);
}
q.push(nodes[p].next[i]);
}
}
}
}
void add(const std::string &s) {
std::size_t start = -1, now = 0;
for (std::size_t i = 0; i < s.size(); ++i) {
std::size_t t = static_cast<size_t>(s[i] - character::min_char);
if (nodes[now].next[t] == invalid_index) {
start = i;
break;
}
now = nodes[now].next[t];
}
for (std::size_t i = start; i < s.size(); ++i) {
std::size_t t = static_cast<size_t>(s[i] - character::min_char);
std::size_t nxt = size();
add_node();
nodes[now].next[t] = nxt;
std::size_t tmp = next(nodes[now].fail, s[i]);
set_fail(nxt, tmp);
for (std::size_t ac : nodes[tmp]) {
nodes[nxt].accept.push_back(ac);
}
for (std::size_t p : nodes[now].r_fail) {
if (nodes[p].next[t] != invalid_index) {
set_fail(nodes[p].next[t], nxt);
}
}
now = nxt;
}
}
std::size_t size() const { return cnt; }
std::size_t next(std::size_t now, char c) const {
std::size_t t = static_cast<std::size_t>(c - character::min_char);
while (nodes[now].next[t] == invalid_index) now = nodes[now].fail;
return nodes[now].next[t];
}
std::vector<std::vector<std::size_t>> match(const std::string &s) const {
std::size_t now = 0;
std::vector<std::vector<std::size_t>> ret(s.size());
for (std::size_t i = 0; i < s.size(); ++i) {
now = next(now, s[i]);
for (auto ac : nodes[now].accept) {
ret[i].push_back(ac);
}
}
}
private:
void add_node() {
nodes.emplace_back();
cnt++;
}
void set_fail(std::size_t from, std::size_t to) {
nodes[nodes[from].fail].r_fail.erase(from);
nodes[from].fail = to;
nodes[to].r_fail.insert(from);
}
};
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
string mv = "DRUL";
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, m;
while (cin >> n >> m, n) {
vector<string> v(n);
REP(i, n) cin >> v[i];
int qu;
cin >> qu;
vector<string> p(qu);
REP(i, qu) cin >> p[i];
aho_corasick<upper_alphabet> ac;
ac.build(p);
int sx = -1, sy = -1, tx = -1, ty = -1;
REP(i, n) REP(j, m) {
if (v[i][j] == 'S') {
sx = i;
sy = j;
} else if (v[i][j] == 'G') {
tx = i;
ty = j;
}
}
int k = ac.nodes.size();
vector<vector<vector<int>>> dp(n,
vector<vector<int>>(m, vector<int>(k, 1e9)));
dp[sx][sy][0] = 0;
queue<pair<pair<int, int>, int>> q;
q.push({{sx, sy}, 0});
while (!q.empty()) {
auto c = q.front();
q.pop();
int x = c.first.first, y = c.first.second, s = c.second;
REP(d, 4) {
int nx = x + dx[d], ny = y + dy[d], ns = ac.next(s, mv[d]);
if (nx < 0 || nx >= n || ny < 0 || ny >= m || v[nx][ny] == '#' ||
ac.nodes[ns].accept.size() > 0)
continue;
if (dp[nx][ny][ns] > dp[x][y][s] + 1) {
dp[nx][ny][ns] = dp[x][y][s] + 1;
q.push({{nx, ny}, ns});
}
}
}
int ans = 1e9;
REP(i, k) ans = min(ans, dp[tx][ty][i]);
if (ans == 1e9)
cout << -1 << endl;
else
cout << ans << endl;
}
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <queue>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const string ds = "RDLU";
const vector<int> dx = { 0, 1, 0, -1 };
const vector<int> dy = { 1, 0, -1, 0 };
struct state {
int x, y, ban, len;
};
int dist[53][53][13][13];
int main() {
int H, W, P;
while (cin >> H >> W, H) {
vector<string> S(H);
int sx = -1, sy = -1, gx = -1, gy = -1;
for (int i = 0; i < H; ++i) {
cin >> S[i];
if (S[i].find('S') != string::npos) sx = i, sy = S[i].find('S');
if (S[i].find('G') != string::npos) gx = i, gy = S[i].find('G');
}
cin >> P;
vector<string> ban(P);
for (int i = 0; i < P; ++i) {
cin >> ban[i];
}
sort(ban.begin(), ban.end());
vector<string> rban;
for (int i = 0; i < P; ++i) {
bool flag = true;
for (int j = 0; j < P; ++j) {
if (ban[i] != ban[j] && ban[i].find(ban[j]) != string::npos) {
flag = false;
}
if (ban[i] == ban[j] && i > j) {
flag = false;
}
}
if (flag) rban.push_back(ban[i]);
}
ban = rban;
P = ban.size();
memset(dist, -1, sizeof(dist));
queue<state> que;
que.push(state{ sx, sy, P, 0 });
dist[sx][sy][P][0] = 0;
int ans = -1;
while (!que.empty()) {
state s = que.front(); que.pop();
int di = dist[s.x][s.y][s.ban][s.len];
if (s.x == gx && s.y == gy) {
if (ans == -1) ans = di;
else ans = min(ans, di);
}
for (int i = 0; i < 4; ++i) {
int tx = s.x + dx[i], ty = s.y + dy[i];
if (0 <= tx && tx < H && 0 <= ty && ty < W && S[tx][ty] != '#') {
bool incr = (s.ban != P && ban[s.ban][s.len] == ds[i]);
int nxt_ban = s.ban, nxt_len = s.len;
if (incr) {
++nxt_len;
}
else {
string recent = (s.ban == P ? "" : ban[s.ban].substr(0, s.len)) + ds[i];
nxt_ban = P; nxt_len = 0;
for (int j = s.len + 1; j > 0; --j) {
int ptr = -1;
for (int k = 0; k < P; ++k) {
if (recent.substr(s.len - j + 1) == ban[k].substr(0, j)) {
ptr = k;
}
}
if (ptr != -1) {
nxt_ban = ptr;
nxt_len = j;
break;
}
}
}
if (nxt_ban != P && nxt_len == ban[nxt_ban].length()) continue;
if (dist[tx][ty][nxt_ban][nxt_len] == -1) {
dist[tx][ty][nxt_ban][nxt_len] = di + 1;
que.push(state{ tx, ty, nxt_ban, nxt_len });
}
}
}
}
cout << ans << endl;
}
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #define _USE_MATH_DEFINES
#define INF 0x3f3f3f3f
#include <cstdio>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cctype>
#include <utility>
#include <iterator>
using namespace std;
typedef long long ll;
typedef pair <int,int> P;
typedef pair <int,P > PP;
int tx[] = {0,1,0,-1};//URDL
int ty[] = {-1,0,1,0};
static const double EPS = 1e-8;
//URDL
const static char dir[4] = {'U','R','D','L'};
const static string dir_str[4] = {"U","R","D","L"};
namespace AhoCorasick{
class Node;
class SearchMachine;
struct MatchingResult {
map<string,int> rv;
long long id;
};
};
class AhoCorasick::Node {
private:
set<string> results;
map<char,AhoCorasick::Node*> transitions;
vector<AhoCorasick::Node*> v_transitions;
char character;
AhoCorasick::Node* parent;
AhoCorasick::Node* failure;
public:
Node() : character('\0'),parent(NULL),failure(NULL){}
Node(AhoCorasick::Node* _p,char _c) : parent(_p),character(_c),failure(NULL){}
const char get_char() const {
return character;
}
AhoCorasick::Node* get_parent() const{
return parent;
}
AhoCorasick::Node* get_failure() const{
return failure;
}
void set_failure(AhoCorasick::Node* _n){
failure = _n;
}
AhoCorasick::Node* get_transition(const char c){
if(transitions.find(c) == transitions.end()) return NULL;
return transitions[c];
}
const set<string>& get_results() const{
return results;
}
void add_result(const string& str){
results.insert(str);
}
void add_transition(AhoCorasick::Node* node){
transitions[node->get_char()] = node;
v_transitions.push_back(node);
}
long long get_id() const{
return reinterpret_cast<long long>(this);
}
const vector<AhoCorasick::Node*>& get_transitions() const{
return v_transitions;
}
};
class AhoCorasick::SearchMachine{
private:
set<string> keywords;
AhoCorasick::Node* root;
AhoCorasick::Node* state;
public:
SearchMachine(set<string> _k) : keywords(_k){
_build_tree();
}
SearchMachine(){
_build_tree();
}
void _build_tree(){
root = new AhoCorasick::Node();
for(set<string>::iterator it = keywords.begin();
it != keywords.end();
it++){
AhoCorasick::Node* node = root;
const string& keyword = *it;
for(int i = 0; i < keyword.length(); i++){
AhoCorasick::Node* next_node = node->get_transition(keyword[i]);
if(next_node == NULL){
next_node = new AhoCorasick::Node(node,keyword[i]);
node->add_transition(next_node);
}
node = next_node;
}
node->add_result(keyword);
}
vector<AhoCorasick::Node*> nodes;
for(int i=0;i<root->get_transitions().size();i++){
root->get_transitions()[i]->set_failure(root);
vector<AhoCorasick::Node*> tmp_nodes;
tmp_nodes.reserve(nodes.size() + root->get_transitions()[i]->get_transitions().size() + 1);
merge(nodes.begin(), nodes.end(),
root->get_transitions()[i]->get_transitions().begin(), root->get_transitions()[i]->get_transitions().end(),
back_inserter<vector<AhoCorasick::Node*> >(tmp_nodes));
nodes.swap(tmp_nodes);
}
while(nodes.size() > 0){
vector<AhoCorasick::Node*> next_nodes;
for(int i=0;i<nodes.size();i++){
AhoCorasick::Node* r = nodes[i]->get_parent()->get_failure();
const char c = nodes[i]->get_char();
while((r != NULL) && (r->get_transition(c) == NULL)){
r = r->get_failure();
}
if(r == NULL){
nodes[i]->set_failure(root);
}
else{
AhoCorasick::Node* tc = r->get_transition(c);
nodes[i]->set_failure(tc);
set<string> results;
if(tc != NULL) results = tc->get_results();
for(set<string>::iterator it = results.begin();
it != results.end();
it++){
nodes[i]->add_result(*it);
}
}
vector<AhoCorasick::Node*> tmp_nodes;
tmp_nodes.reserve(next_nodes.size() + nodes[i]->get_transitions().size() + 1);
merge(next_nodes.begin(), next_nodes.end(),
nodes[i]->get_transitions().begin(), nodes[i]->get_transitions().end(),
back_inserter<vector<AhoCorasick::Node*> >(tmp_nodes));
next_nodes.swap(tmp_nodes);
}
nodes = next_nodes;
}
root->set_failure(root);
state = root;
}
MatchingResult feed(const string& text){
MatchingResult mr;
int index = 0;
while(index < text.length()){
AhoCorasick::Node* trans = NULL;
while(state != NULL){
trans = state->get_transition(text[index]);
if(state == root || trans != NULL) break;
state = state->get_failure();
}
if(trans != NULL){
state = trans;
}
set<string> results;
if(state != NULL) results = state->get_results();
for(set<string>::iterator it = results.begin();
it != results.end();
it++){
mr.rv[*it] = index - it->length() + 1;
}
index++;
}
mr.id = state->get_id();
state = root;
return mr;
}
};
class State{
public:
int cost;
string route;
int x;
int y;
State(int _x,int _y,int _c,string _r) : cost(_c), route(_r),x(_x),y(_y){}
bool operator<(const State& s) const{
return cost < s.cost;
}
bool operator>(const State& s) const{
return cost > s.cost;
}
};
int main(){
int H,W;
while(~scanf("%d %d",&H,&W)){
if(H==0 && W==0) break;
char stage[50][50];
set<ll> dp[50][50];
int sx = 0;
int sy = 0;
int gx = 0;
int gy = 0;
for(int y=0;y<H;y++){
char line[51];
scanf("%s",line);
for(int x=0;x<W;x++){
stage[y][x] = line[x];
if(line[x] == 'S'){
sx = x;
sy = y;
}
else if(line[x] == 'G'){
gx = x;
gy = y;
}
}
}
int total_prohibited_sequences;
scanf("%d",&total_prohibited_sequences);
set<string> keywords;
for(int sequence_idx=0;
sequence_idx < total_prohibited_sequences;
sequence_idx++){
string str;
cin >> str;
keywords.insert(str);
}
AhoCorasick::SearchMachine* sm = new AhoCorasick::SearchMachine(keywords);
priority_queue<State,vector<State>,greater<State> > que;
que.push(State(sx,sy,0,""));
int res = INF;
while(!que.empty()){
State s = que.top();
string route = s.route;
int cost = s.cost;
int sx = s.x;
int sy = s.y;
que.pop();
for(int i=0;i<4;i++){
int dx = sx + tx[i];
int dy = sy + ty[i];
if(dx < 0 || dx >= W
|| dy < 0 || dy >= H) continue;
if(stage[dy][dx] == '#') continue;
string next = route + dir_str[i];
if(next.size() > 10) next = next.substr(next.size()-10);
AhoCorasick::MatchingResult mr = sm->feed(next);
if((!mr.rv.empty())){
// cout << mr.rv.begin()->first << endl;
// cout << next << endl;
continue;
}
if(dp[dy][dx].count(mr.id)) continue;
dp[dy][dx].insert(mr.id);
if(stage[dy][dx] == 'G'){
res = cost + 1;
goto found;
}
que.push(State(dx,dy,cost+1,next));
}
}
found:;
printf("%d\n",res == INF ? -1 : res);
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i,x,y) for(int i=(x);i<(y);++i)
#define debug(x) #x << "=" << (x)
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl
#else
#define print(x)
#endif
const int inf=1e9;
const int64_t inf64=1e18;
const double eps=1e-9;
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){
os << "[";
for (const auto &v : vec) {
os << v << ",";
}
os << "]";
return os;
}
using i64=int64_t;
const int alphabet_size=256;
class pma{
public:
pma* next[alphabet_size],*failure;
vector<int> matches;
string s;
pma(){
fill(next,next+alphabet_size,(pma*)0);
failure=NULL;
}
void insert(const string &str,const int id){ insert(str,0,id); }
void insert(const string &str,const int idx,const int id){
s=str.substr(0,idx);
if(idx==str.size()){
matches.push_back(id);
return;
}
if(next[str[idx]]==NULL) this->next[str[idx]]=new pma();
next[str[idx]]->insert(str,idx+1,id);
}
};
class aho_corasick{
public:
vector<string> dic;
pma* root;
aho_corasick(const vector<string>& dic_):dic(dic_),root(new pma()){
for(int i=0; i<dic.size(); ++i) root->insert(dic[i],i);
root->failure=root;
queue<pma*> que;
que.push(root);
while(!que.empty()){
pma* curr=que.front();
que.pop();
curr->matches.insert(curr->matches.end(),curr->failure->matches.begin(),curr->failure->matches.end());
for(int i=0; i<alphabet_size; ++i){
pma*& next=curr->next[i];
if(next==NULL){
next=curr==root?root:curr->failure->next[i];
continue;
}
next->failure=curr==root?root:curr->failure->next[i];
next->matches.insert(next->matches.end(),curr->matches.begin(),curr->matches.end());
que.push(next);
}
}
}
vector<bool> match(const string& s)const{
vector<bool> res(dic.size());
const pma* state=root;
for(char c:s){
state=state->next[c];
for(int i:state->matches) res[i]=true;
}
return res;
}
};
void solve(int N,int M){
vector<string> vs(N);
int sy,sx,gy,gx;
rep(i,0,N){
cin >> vs[i];
rep(j,0,M){
if(vs[i][j]=='S'){
sy=i;
sx=j;
}
if(vs[i][j]=='G'){
gy=i;
gx=j;
}
}
}
int P;
cin >> P;
vector<string> ban(P);
rep(i,0,P){
cin >> ban[i];
for(char& c:ban[i]){
if(c=='R') c=0;
if(c=='U') c=1;
if(c=='L') c=2;
if(c=='D') c=3;
}
}
aho_corasick ac(ban);
vector<int> dx={1,0,-1,0},dy={0,-1,0,1};
queue<tuple<int,int,pma*,int>> que;
set<tuple<int,int,pma*>> visited;
que.push(make_tuple(sy,sx,ac.root,0));
visited.insert(make_tuple(sy,sx,ac.root));
while(!que.empty()){
int y,x,d;
pma* curr;
tie(y,x,curr,d)=que.front();
que.pop();
if(y==gy and x==gx){
cout << d << endl;
return;
}
rep(i,0,4){
int ny=y+dy[i],nx=x+dx[i];
if(ny<0 or N<=ny or nx<0 or M<=nx or vs[ny][nx]=='#') continue;
pma* next=curr->next[i];
if(!next->matches.empty()) continue;
if(visited.find(make_tuple(ny,nx,next))!=visited.end()) continue;
que.push(make_tuple(ny,nx,next,d+1));
visited.insert(make_tuple(ny,nx,next));
}
}
cout << -1 << endl;
}
int main(){
std::cin.tie(0);
std::ios::sync_with_stdio(false);
cout.setf(ios::fixed);
cout.precision(10);
for(;;){
int N,M;
cin >> N >> M;
if(!N and !M) break;
solve(N,M);
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include<iostream>
#include<vector>
#include<queue>
#include<string>
#include<cstring>
using namespace std;
class PMA{//Aho-Corasick
int id;
bool match;
PMA *failure;
PMA *next[256];
public:
PMA(int id=0):id(id),match(false),failure(0){
memset(next,0,sizeof(next));
}
~PMA(){
for(int i=0;i<256;i++){
if(next[i]&&next[i]!=this)delete next[i];
}
}
int getID()const{return id;}
bool matched()const{return match;}
void build(const vector<string> &p){
int num=0;
for(int i=0;i<(int)p.size();i++){
const string &s=p[i];
PMA *t=this;
for(int j=0;j<(int)s.size();j++){
if(!t->next[s[j]])t->next[s[j]]=new PMA(++num);
t=t->next[s[j]];
}
t->match=true;
}
queue<PMA*> q;
for(int i=0;i<256;i++){
if(next[i]){
q.push(next[i]);
next[i]->failure=this;
}else next[i]=this;
}
while(!q.empty()){
PMA *t=q.front();q.pop();
for(int i=0;i<256;i++){
if(t->next[i]){
q.push(t->next[i]);
PMA *r=t->failure->step(i);
t->next[i]->failure=r;
t->next[i]->match |= r->match;
}
}
}
}
PMA *step(char c)const{
const PMA *t=this;
while(!t->next[c])t=t->failure;
return t->next[c];
}
};
string ch("DRUL");
int dy[]={1,0,-1,0};
int dx[]={0,1,0,-1};
int h,w;
char m[52][52];
int dp[51][51][102];
struct Node{
int y,x;
PMA *p;
};
int bfs(PMA &pma){
memset(dp,-1,sizeof(dp));
Node a,b;
for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)if(m[i][j]=='S'){
a.y=i;
a.x=j;
a.p=&pma;
}
queue<Node> q;
dp[a.y][a.x][a.p->getID()]=0;
q.push(a);
while(!q.empty()){
a=q.front();q.pop();
int d=dp[a.y][a.x][a.p->getID()];
for(int i=0;i<4;i++){
b.y=a.y+dy[i];
b.x=a.x+dx[i];
if(m[b.y][b.x]=='#')continue;
b.p=a.p->step(ch[i]);
if(b.p->matched())continue;
if(m[b.y][b.x]=='G')return d+1;
if(dp[b.y][b.x][b.p->getID()]==-1){
dp[b.y][b.x][b.p->getID()] = d+1;
q.push(b);
}
}
}
return -1;
}
int main(){
while(cin>>h>>w&&(h||w)){
memset(m,'#',sizeof(m));
for(int i=1;i<=h;i++)
for(int j=1;j<=w;j++)
cin>>m[i][j];
int n;
cin>>n;
vector<string> p(n);
for(int i=0;i<n;i++){
cin>>p[i];
}
PMA pma;
pma.build(p);
cout<<bfs(pma)<<endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | java |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main{
String INPUT = "./data/judge/201709/A2212.txt";
public static void main(String[] args) throws IOException {
new Main().run();
}
static final char[] TAG = {'D','U','L','R'};
static final int[] R = {1, -1, 0, 0};
static final int[] C = {0, 0, -1, 1};
static final int INF = 0x3f3f3f3f;
static int idx = 0;
class State{
int i;
int j;
Node s;
State(int i, int j, Node s){
this.i = i;
this.j = j;
this.s = s;
}
@Override
public int hashCode() {
return i * 31 + j * 17 + s.id * 11;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null ||obj.getClass() != getClass()) return false;
State o = (State) obj;
return o.i == i && o.j == j && o.s == s;
}
@Override
public String toString() {
return i + " " + j + " " + s;
}
}
class Node{
Map<Character, Node> cs = new TreeMap<Character, Node>();
Node[] next = new Node[4];
Node fail;
boolean accept;
int id;
Node() {id = idx++;}
@Override
public String toString() {
return id + " " + accept;
}
}
Node root;
void AhoCorasick(char[][] p) {
int n = p.length;
root = new Node();
for (int i = 0; i < n; ++i) {
Node t = root;
for (char c : p[i]) {
if (!t.cs.containsKey(c)) t.cs.put(c, new Node());
t = t.cs.get(c);
}
t.accept = true;
}
// fail
Queue<Node> que = new LinkedList<Node>();
que.offer(root);
while (!que.isEmpty()) {
Node r = que.poll();
for (Map.Entry<Character, Node> entry : r.cs.entrySet()) {
char c = entry.getKey();
Node v = entry.getValue();
que.offer(v);
Node f = r.fail;
while (f != null && !f.cs.containsKey(c)) {
f = f.fail;
}
if (f == null) {
v.fail = root;
}
else {
v.fail = f.cs.get(c);
}
}
}
// next
que.offer(root);
while (!que.isEmpty()) {
Node t = que.poll();
outer : for (char[] cs : p) {
Node r = t;
for (char c : cs) {
if (r.cs.containsKey(c)) {
r = r.cs.get(c);
}
else continue outer;
}
r.accept = true;
}
for (int i = 0; i < 4; ++i) {
char c = TAG[i];
Node r = t;
while (r != null && !r.cs.containsKey(c)) {
r = r.fail;
}
if (r == null) {
t.next[i] = root;
}
else {
t.next[i] = r.cs.get(c);
}
}
for (Node r : t.cs.values()) {
que.offer(r);
}
}
}
int startR;
int startC;
int endR, endC;
int solve(char[][] f) {
int N = f.length;
int M = f[0].length;
int n = ni();
char[][] p = new char[n][];
for (int i = 0; i < n; ++i) {
p[i] = ns().toCharArray();
}
AhoCorasick(p);
State state = new State(startR, startC, root);
Queue<State> queue = new LinkedList<>();
Set<State> vis = new HashSet<>();
queue.offer(state);
vis.add(state);
int turn = 0;
int ans = INF;
boolean find = false;
outer: while (!queue.isEmpty() && !find) {
int size = queue.size();
for (int i = 0; i < size; ++i) {
State now = queue.poll();
if (now.i == endR && now.j == endC) {
ans = turn;
find = true;
break outer;
}
for (int j = 0; j < 4; ++j) {
int nx = now.i + R[j];
int ny = now.j + C[j];
if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue;
if (f[nx][ny] == '#') continue;
Node next = now.s.next[j];
if (next.accept) continue;
State ns = new State(nx, ny, next);
if (vis.contains(ns)) continue;
queue.offer(ns);
vis.add(ns);
}
}
turn++;
}
return ans == INF ? -1 : ans;
}
void read() {
while (true) {
int N = ni();
if (N == 0) break;
int M = ni();
char[][] f = new char[N][M];
for (int i = 0; i < N; ++i) {
char[] cs = ns().toCharArray();
for (int j = 0; j < M; ++j) {
f[i][j] = cs[j];
if (cs[j] == 'S') {
startR = i;
startC = j;
}
if (cs[j] == 'G') {
endR = i;
endC = j;
}
}
}
idx = 0;
out.println(solve(f));
}
}
FastScanner in;
PrintWriter out;
void run() throws IOException {
boolean oj;
try {
oj = ! System.getProperty("user.dir").equals("F:\\java_workspace\\leetcode");
} catch (Exception e) {
oj = System.getProperty("ONLINE_JUDGE") != null;
}
InputStream is = oj ? System.in : new FileInputStream(new File(INPUT));
in = new FastScanner(is);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
read();
out.flush();
if (!oj){
System.out.println("[" + (System.currentTimeMillis() - s) + "ms]");
}
}
public boolean more(){
return in.hasNext();
}
public int ni(){
return in.nextInt();
}
public long nl(){
return in.nextLong();
}
public double nd(){
return in.nextDouble();
}
public String ns(){
return in.nextString();
}
public char nc(){
return in.nextChar();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
boolean hasNext;
public FastScanner(InputStream is) throws IOException {
br = new BufferedReader(new InputStreamReader(is));
hasNext = true;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
hasNext = false;
return "##";
}
}
return st.nextToken();
}
String next = null;
public boolean hasNext(){
next = nextToken();
return hasNext;
}
public int nextInt() {
if (next == null){
hasNext();
}
String more = next;
next = null;
return Integer.parseInt(more);
}
public long nextLong() {
if (next == null){
hasNext();
}
String more = next;
next = null;
return Long.parseLong(more);
}
public double nextDouble() {
if (next == null){
hasNext();
}
String more = next;
next = null;
return Double.parseDouble(more);
}
public String nextString(){
if (next == null){
hasNext();
}
String more = next;
next = null;
return more;
}
public char nextChar(){
if (next == null){
hasNext();
}
String more = next;
next = null;
return more.charAt(0);
}
}
static class ArrayUtils {
public static void fill(int[][] f, int value) {
for (int i = 0; i < f.length; ++i) {
Arrays.fill(f[i], value);
}
}
public static void fill(int[][][] f, int value) {
for (int i = 0; i < f.length; ++i) {
fill(f[i], value);
}
}
public static void fill(int[][][][] f, int value) {
for (int i = 0; i < f.length; ++i) {
fill(f[i], value);
}
}
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <numeric>
#include <cstring>
using namespace std;
struct Entry {
int x, y, state, step;
};
int dx[] = { -1, 1, 0, 0 };
int dy[] = { 0, 0, -1, 1 };
const char *LABELS[] = { "L", "R", "U", "D" };
class Matcher {
struct PMA {
int next[256];
vector<int> accept;
PMA(){ fill(next, next + 256, -1); }
};
vector<PMA> states;
public:
Matcher(const vector<string> &patterns){
states.push_back(PMA());
for(int i = 0; i < patterns.size(); ++i){
int cur = 0;
for(size_t j = 0; j < patterns[i].size(); ++j){
char c = patterns[i][j];
if(states[cur].next[c] < 0){
states[cur].next[c] = static_cast<int>(states.size());
states.push_back(PMA());
}
cur = states[cur].next[c];
}
states[cur].accept.push_back(i);
}
queue<int> q;
for(int c = 1; c < 256; ++c){
if(states[0].next[c] >= 0){
states[states[0].next[c]].next[0] = 0;
q.push(states[0].next[c]);
}else{
states[0].next[c] = 0;
}
}
while(!q.empty()){
int t = q.front();
q.pop();
for(int c = 1; c < 256; ++c){
if(states[t].next[c] >= 0){
q.push(states[t].next[c]);
int r = states[t].next[0];
while(states[r].next[c] < 0){ r = states[r].next[0]; }
states[states[t].next[c]].next[0] = states[r].next[c];
}
}
}
for(int i = 0; i < patterns.size(); ++i){
const string &pat = patterns[i];
for(int j = 1; j < states.size(); ++j){
int current = j, k = 0;
for(; k < pat.size(); ++k){
if(states[current].next[pat[k]] < 0){ break; }
current = states[current].next[pat[k]];
}
if(k == pat.size()){ states[current].accept.push_back(i); }
}
}
}
int match(const string &str, vector<int> &result, int state = 0){
for(size_t i = 0; i < str.size(); ++i){
char c = str[i];
while(states[state].next[c] < 0){ state = states[state].next[0]; }
state = states[state].next[c];
for(size_t j = 0; j < states[state].accept.size(); ++j){
++(result[states[state].accept[j]]);
}
}
return state;
}
int stateNum() const { return static_cast<int>(states.size()); }
};
bool passed[52][52][101];
int main(){
while(true){
int N, M;
cin >> N >> M;
if(N == 0 && M == 0){ break; }
memset(passed, 0, sizeof(passed));
vector<string> field(N + 2);
field[0] = field[N + 1] = string(M + 2, '#');
Entry start;
int goalX = 0, goalY = 0;
for(int i = 1; i <= N; ++i){
string line;
cin >> line;
field[i] = "#" + line + "#";
for(int j = 1; j <= M; ++j){
if(field[i][j] == 'S'){
start.x = j;
start.y = i;
start.state = 0;
start.step = 0;
}else if(field[i][j] == 'G'){
goalX = j;
goalY = i;
}
}
}
int P;
cin >> P;
vector<string> patterns(P);
for(int i = 0; i < P; ++i){ cin >> patterns[i]; }
Matcher matcher(patterns);
queue<Entry> q;
q.push(start);
passed[start.y][start.x][start.state] = true;
int answer = -1;
vector<int> result(P);
while(!q.empty()){
Entry e = q.front();
//cerr << "> " << e.x << " " << e.y << " " << e.state << endl;
if(e.x == goalX && e.y == goalY){
answer = e.step;
break;
}
q.pop();
for(int i = 0; i < 4; ++i){
Entry next;
next.x = e.x + dx[i];
next.y = e.y + dy[i];
if(field[next.y][next.x] == '#'){ continue; }
next.step = e.step + 1;
fill(result.begin(), result.end(), 0);
next.state = matcher.match(LABELS[i], result, e.state);
if(
accumulate(result.begin(), result.end(), 0) != 0 ||
passed[next.y][next.x][next.state]
){
continue;
}
passed[next.y][next.x][next.state] = true;
q.push(next);
}
}
cout << answer << endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <cstdio>
#include <cstring>
using namespace std;
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define DEB 0
#define all(x) x.begin(), x.end()
#define mp make_pair
#define pb push_back
class state{
public:
int x,y;
vector<int> ma; // 1base
state(int _x, int _y, vector<int> m){
x=_x; y=_y;
ma.swap(m);
}
bool operator<(const state& a)const{
if( x!=a.x ) return x<a.x;
if( y!=a.y ) return y<a.y;
return ma < a.ma;
}
bool operator==(const state& a)const{
return x==a.x && y==a.y && ma==a.ma;
}
};
const int dx[] = {0,1,0,-1}; //up, right, down, left
const int dy[] = {-1,0,1,0};
int n,m,p;
int sx,sy;
map<state,long long> msi;
char field[52][52];
vector<string> ope;
bool inside(int x, int y){
return !(x<0 || x>=m || y>=n || y<0 || field[y][x]=='#');
}
int DIR(char c){
if( c=='U' ) return 0;
if( c=='R' ) return 1;
if( c=='D' ) return 2;
if( c=='L' ) return 3;
}
int main(){
while(cin>>n>>m,n|m){
ope.clear();
msi.clear();
rep(i,n){
cin>>field[i];
rep(j,m)if( field[i][j]=='S' ){
sx = j;
sy = i;
}
}
cin>>p;
rep(i,p){
string tmp; cin>>tmp;
ope.pb(tmp);
}
// ª¶ñÅoÄéàÌÍí·é
bool gao[16];
memset(gao,true,sizeof(gao));
rep(i,ope.size())if( gao[i] ){
int j;
for(j=0; j<ope.size(); j++)if( i!=j && gao[j] ){
if( ope[i].find(ope[j]) != string::npos ){
gao[i] = false;
break;
}
}
}
vector<string> tmp;
rep(i,ope.size())if( gao[i] )tmp.pb(ope[i]);
ope.swap(tmp);
queue<state> q;
bool goal = false;
long long ans = -1;
q.push(state(sx,sy,vector<int>(ope.size(),0)));
msi[state(sx,sy,vector<int>(ope.size(),0))] = 0;
while( !q.empty() ){
int x = q.front().x;
int y = q.front().y;
vector<int> ma = q.front().ma;
long long cost = msi[q.front()];
q.pop();
rep(k,4){
vector<int> hoge(ope.size(),0);
int tx = x + dx[k];
int ty = y + dy[k];
if( !inside(tx,ty) )continue;
bool ok = true;
rep(j,ma.size()){
if( DIR(ope[j][ma[j]+1-1]) == k ){
hoge[j] = ma[j]+1;
if( hoge[j]==ope[j].length() ){ ok = false; break; }
}else{
string aaa = ope[j].substr(0,ma[j]) + string(1,k==0?'U':k==1?'R':k==2?'D':'L');
int l;
for(l=0; l<aaa.size(); l++){
int u;
for(u=0; u+l<aaa.size(); u++){
if( aaa[l+u]!=ope[j][u] )break;
}
if( u+l==aaa.size() ){
break;
}
}
hoge[j] = aaa.size() - l;
}
}
if( !ok ) continue;
if( field[ty][tx]=='G' ){
ans = cost + 1;
goal = true;
}
state ts(tx,ty,hoge);
map<state,long long>::iterator it = msi.lower_bound(ts);
if( it!=msi.end() && it->first==ts ){
if( it->second > cost+1 ){
it->second = cost+1;
q.push(ts);
}
}else{
msi.insert(it,make_pair(ts,cost+1));
q.push(ts);
}
}
if( goal ) break;
}
printf("%lld\n",ans);
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
static int[] DR = { -1, 0, 1, 0 };
static int[] DC = { 0, 1, 0, -1 };
static int N, M;
static char[][] f;
public static void main(String[] args) {
while (true) {
N = sc.nextInt();
if (N == 0) break;
M = sc.nextInt();
f = new char[N + 2][M + 2];
int startR = 0;
int startC = 0;
Arrays.fill(f[0], '#');
Arrays.fill(f[N + 1], '#');
for (int i = 0; i < N; ++i) {
String row = sc.next();
f[i + 1][0] = f[i + 1][M + 1] = '#';
for (int j = 0; j < M; ++j) {
char c = row.charAt(j);
if (c == 'S') {
startR = i + 1;
startC = j + 1;
c = '.';
}
f[i + 1][j + 1] = c;
}
}
System.out.println(solve(startR, startC));
}
}
static int solve(int startR, int startC) {
int P = sc.nextInt();
String[] pat = new String[P];
for (int i = 0; i < P; ++i) {
pat[i] = sc.next();
}
Automaton automaton = new Automaton(pat);
boolean[][][] visited = new boolean[N + 2][M + 2][automaton.nodes.size()];
State initial = new State(startR, startC, 0);
ArrayList<State> cur = new ArrayList<State>();
cur.add(initial);
visited[startR][startC][0] = true;
int turn = 1;
while (!cur.isEmpty()) {
// System.err.println("turn:" + turn);
ArrayList<State> next = new ArrayList<State>();
for (State st : cur) {
for (int i = 0; i < 4; ++i) {
int nr = st.r + DR[i];
int nc = st.c + DC[i];
if (f[nr][nc] == '#') continue;
Node n = automaton.nodes.get(st.i).next[i];
if (n == Automaton.terminal) continue;
if (visited[nr][nc][n.idx]) continue;
if (f[nr][nc] == 'G') return turn;
visited[nr][nc][n.idx] = true;
next.add(new State(nr, nc, n.idx));
// System.err.println("nr:" + nr + " nc:" + nc + " idx:" + n.idx);
}
}
cur = next;
++turn;
}
return -1;
}
static class State {
int r, c, i;
public State(int r, int c, int i) {
this.r = r;
this.c = c;
this.i = i;
}
}
static class Automaton {
static final Node terminal = new Node(0L);
Node root = new Node(0L);
HashMap<Long, Node> map = new HashMap<Long, Node>();
ArrayList<Node> nodes = new ArrayList<Node>();
int[][] pattern;
Automaton(String[] patStr) {
pattern = new int[patStr.length][];
for (int i = 0; i < patStr.length; ++i) {
pattern[i] = new int[patStr[i].length()];
for (int j = 0; j < pattern[i].length; ++j) {
switch (patStr[i].charAt(j)) {
case 'U':
pattern[i][j] = 0;
break;
case 'R':
pattern[i][j] = 1;
break;
case 'D':
pattern[i][j] = 2;
break;
case 'L':
pattern[i][j] = 3;
break;
}
}
}
build(root);
}
void build(Node parent) {
parent.idx = nodes.size();
nodes.add(parent);
map.put(parent.pos, parent);
for (int i = 0; i < 4; ++i) {
long nextPos = 0;
for (int j = 0; j < pattern.length; ++j) {
int curElemPos = (int) ((parent.pos >> (j * 4)) & 0xF);
long nextElemPos;
if (pattern[j][curElemPos] == i) {
nextElemPos = curElemPos + 1;
} else {
nextElemPos = 0;
for (int k = curElemPos; k >= 0; --k) {
if (pattern[j][k] != i) continue;
boolean ok = true;
for (int l = 1; l <= k; ++l) {
if (pattern[j][curElemPos - l] != pattern[j][k - l]) {
ok = false;
break;
}
}
if (ok) {
nextElemPos = k + 1;
break;
}
}
}
if (nextElemPos == pattern[j].length) {
parent.next[i] = terminal;
break;
} else {
nextPos += nextElemPos << (j * 4);
}
}
if (parent.next[i] == null) {
Node child = map.get(nextPos);
if (child == null) {
child = new Node(nextPos);
build(child);
}
parent.next[i] = child;
}
}
}
}
static class Node {
Node[] next = new Node[4];
long pos;
int idx;
Node(long pos) {
this.pos = pos;
}
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include<stdio.h>
#include<string>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
char str[60][60];
char in[60];
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
char dc[7]="DRUL";
int bfs[60][60][110];
string val[110];
int ng[110];
int main(){
int a,b;
while(scanf("%d%d",&a,&b),a){
for(int i=0;i<a;i++)scanf("%s",str[i]);
int c;scanf("%d",&c);
map<string,int>m;
int sz=0;
for(int i=0;i<110;i++)ng[i]=0;
val[0]="";
m[string("")]=sz++;
for(int i=0;i<c;i++){
scanf("%s",in);
string tmp=in;
for(int j=0;j<=tmp.size();j++){
if(!m.count(tmp.substr(0,j))){
val[sz]=tmp.substr(0,j);
m[tmp.substr(0,j)]=sz++;
}
}
ng[m[tmp]]=1;
}
for(int i=0;i<sz;i++){
string tmp=val[i];
while(tmp.size()){
tmp=tmp.substr(1,tmp.size()-1);
if(m.count(tmp)&&ng[m[tmp]]){ng[i]=1;break;}
}
}
int sr,sc,gr,gc;
for(int i=0;i<a;i++)for(int j=0;j<b;j++){
if(str[i][j]=='S'){sr=i;sc=j;}
if(str[i][j]=='G'){gr=i;gc=j;}
}
queue<pair<pair<int,int>,int> >Q;
for(int i=0;i<a;i++)for(int j=0;j<b;j++)for(int k=0;k<sz;k++){
bfs[i][j][k]=99999999;
}
bfs[sr][sc][0]=0;
Q.push(make_pair(make_pair(sr,sc),0));
while(Q.size()){
int row=Q.front().first.first;
int col=Q.front().first.second;
int at=Q.front().second;
string now=val[at];
Q.pop();
for(int i=0;i<4;i++){
if(0<=row+dx[i]&&row+dx[i]<a&&0<=col+dy[i]&&col+dy[i]<b&&str[row+dx[i]][col+dy[i]]!='#'){
string to=now+dc[i];
while(!m.count(to)){
to=to.substr(1,to.size()-1);
}
int tt=m[to];
if(!ng[tt]&&bfs[row+dx[i]][col+dy[i]][tt]>999999){
bfs[row+dx[i]][col+dy[i]][tt]=bfs[row][col][at]+1;
Q.push(make_pair(make_pair(row+dx[i],col+dy[i]),tt));
}
}
}
}
int ret=999999999;
for(int i=0;i<sz;i++)ret=min(ret,bfs[gr][gc][i]);
if(ret>9999999)printf("-1\n");
else printf("%d\n",ret);
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int vy[] = {0, 1, 0, -1}, vx[] = {1, 0, -1, 0};
const string temp = "RDLU";
const int mask = (1 << 18) - 1;
int H, W, P, sx, sy;
string S[50], V[10];
int solve()
{
queue< tuple< int, int, int, int > > que;
int min_cost[50][50][10][10];
memset(min_cost, -1, sizeof(min_cost));
que.emplace(sx, sy, 0, 0);
min_cost[sx][sy][0][0] = 0;
while(!que.empty()) {
int x, y, a, b;
tie(x, y, a, b) = que.front();
que.pop();
string pat = V[a].substr(0, b);
bool f = true;
for(int i = 0; i < P; i++) f &= pat.find(V[i]) == string::npos;
if(!f) continue;
if(S[y][x] == 'G') return (min_cost[x][y][a][b]);
for(int i = 0; i < 4; i++) {
int nx = x + vx[i], ny = y + vy[i];
if(nx < 0 || ny < 0 || nx >= W || ny >= H) continue;
if(S[ny][nx] == '#') continue;
string nextpat = pat + string(1, temp[i]);
bool match = false;
for(int j = 0; j < nextpat.size(); j++) {
string st = nextpat.substr(j);
for(int k = 0; k < P; k++) {
if(V[k].find(st) == 0) {
if(min_cost[nx][ny][k][st.size()] == -1) {
que.emplace(nx, ny, k, st.size());
min_cost[nx][ny][k][st.size()] = min_cost[x][y][a][b] + 1;
}
match = true;
break;
}
}
if(match) break;
}
if(!match && min_cost[nx][ny][0][0] == -1) {
que.emplace(nx, ny, 0, 0);
min_cost[nx][ny][0][0] = min_cost[x][y][a][b] + 1;
}
}
}
return (-1);
}
int main()
{
while(cin >> H >> W, H) {
for(int i = 0; i < H; i++) {
cin >> S[i];
for(int j = 0; j < W; j++) {
if(S[i][j] == 'S') sx = j, sy = i;
}
}
cin >> P;
for(int i = 0; i < P; i++) {
cin >> V[i];
}
cout << solve() << endl;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME
#define pr(...) cerr<< GET_MACRO(__VA_ARGS__,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__) <<endl
#define pr1(a) (#a)<<"="<<(a)<<" "
#define pr2(a,b) pr1(a)<<pr1(b)
#define pr3(a,b,c) pr1(a)<<pr2(b,c)
#define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d)
#define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e)
#define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f)
#define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g)
#define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h)
#define prArr(a) {cerr<<(#a)<<"={";int i=0;for(auto t:(a))cerr<<(i++?", ":"")<<t;cerr<<"}"<<endl;}
using namespace std;
using Int = long long;
using _int = int;
using ll = long long;
using Double = long double;
const Int INF = (1LL<<60)+1e9; // ~ 1.15 * 1e18
const Int mod = (1e9)+7;
const Double EPS = 1e-8;
const Double PI = 6.0 * asin((Double)0.5);
using P = pair<Int,Int>;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
template<class T1, class T2> ostream& operator<<(ostream& o,pair<T1,T2> p){return o<<"("<<p.first<<","<<p.second<<")";}
template<class T1, class T2, class T3> ostream& operator<<(ostream& o,tuple<T1,T2,T3> t){
return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";}
template<class T1, class T2> istream& operator>>(istream& i,pair<T1,T2> &p){return i>>p.first>>p.second;}
template<class T> ostream& operator<<(ostream& o,vector<T> a){Int i=0;for(T t:a)o<<(i++?" ":"")<<t;return o;}
template<class T> istream& operator>>(istream& i,vector<T> &a){for(T &t:a)i>>t;return i;}
/* Aho Corasick */
template <int X /*文字の種類*/ >
class AhoCorasick{
public:
struct Node{
char c; //頂点の文字
int pre; //親の頂点番号
int val; //重み
int exist; //単語が存在するか
int dep; //ノードの深さ
int failEdge; //パターンマッチに失敗した時に戻るノード
vector<int> bto; //to[i] != -1? (to[i]):(posからtoへのパターンマッチに失敗した時に戻るノード)
vector<int> to; //次の頂点番号
Node(){};
Node(char c,int pre,int val = 0,int exist = 0):
c(c),pre(pre),val(val),exist(exist), to(X,-1){};
};
vector<Node> v; //ノード
function<int(char)> toI; //文字から数字に変換する関数
int ok;
AhoCorasick(function<int(char)> toI=[](char ch){return ch-'A';} ,char c = '$'/*根に用いる文字*/)
:toI(toI),ok(false){v.push_back(Node(c, -1, 0/*!!!!!*/));}
int size(){return v.size();}
Node operator [](int i)const {return v[i];}
inline void check(int pos){assert(0 <= pos && pos<size());}
inline int go(int pos,char c, int flag = 0){check(pos);return flag == 0? v[pos].to[toI(c)]:v[pos].bto[toI(c)];}
inline int go(const string &s,int pos = 0){
for(char c:s){
pos = go(pos,c);
if(pos == -1) return -1;
}
return pos;
}
inline int back(int pos){check(pos);return v[pos].pre;}
inline int getVal(int pos){check(pos);return v[pos].val;}
inline int exist(int pos){check(pos);return v[pos].exist;}
inline int failEdge(int pos){check(pos);assert(ok);return v[pos].failEdge;}
inline int failEdge(int pos,char to){check(pos);assert(ok);return v[pos].bto[toI(to)];}
inline int depth(int pos){check(pos);assert(ok);return v[pos].dep;}
inline void addWord(const string &s,int val = 1){
ok = false;
int pos = 0, dep = 0;
for(char c:s){
v[pos].dep = dep++;
if(go(pos,c) != -1){pos = go(pos,c);continue;}
v.push_back(Node(c,pos));
pos = v[pos].to[toI(c)] = v.size()-1;
}
v[pos].dep = dep;
v[pos].exist = 1;
v[pos].val = max(v[pos].val, val); //min,max,+ 臨機応変に変えて
}
void build(){
ok = 1;
buildBackEdge();
nextMatch.resize(size());
for(int i=1;i<size();i++) nextMatch[i] = failEdge(i);
nextMatch[0] = -1;
}
vector<int> nextMatch; //to[i] := ノードiを含めないノードiからみて最も単語長が長くなるノード
//posから見て単語長が最も長くなるようなノードを返す。(pos自体が単語の場合はposを返す)
int suffixMatch(int pos){
if(pos == -1) return -1;
if(exist(pos)) return pos;
return nextMatch[pos] = suffixMatch(nextMatch[pos]);
}
//res[i]にはs[i]からmatchする単語の長さが入っている。
vector<vector<int> > matchedIdx(const string &s){
assert(exist(0) == 0); //空文字列が単語として存在する場合、たぶん壊れるので直す必要がある。
assert(ok);
int n = s.size();
vector<vector<int> > res(n);
for(int i=0, pos=0;i<n;i++){
char ch = s[i];
pos = go(pos, ch, true);
int p = suffixMatch(pos);
while(p != -1 && exist(p)){
res[ i - depth(p) + 1].push_back(depth(p));
p = suffixMatch(nextMatch[p]);
}
}
return res;
}
private:
void buildBackEdge(){
const int root = 0;
queue<int> Q;
Q.push(root);
v[root].failEdge = root;
for(int i=0;i<size();i++) v[i].bto = v[i].to;
for(int i=0;i<X;i++) if(v[root].bto[i] == -1) v[root].bto[i] = root;
while(!Q.empty()){
int pos = Q.front(); Q.pop();
for(int i=0;i<X;i++){
int to = v[pos].to[i];
if(to == -1) continue;
Q.push(to);
v[to].failEdge = (pos == root)? root:v[ v[pos].failEdge ].bto[i];
for(int i=0;i<X;i++) if(v[to].bto[i] == -1) v[to].bto[i] = v[ v[to].failEdge ].bto[i];
}
}
}
};
void check(){
AhoCorasick <26> aho([](char ch){return ch - 'a';});
aho.addWord("abcde");
aho.addWord("bc");
aho.addWord("bab");
aho.addWord("d");
aho.addWord("ab");
aho.build();
pr(aho.ok);
for(int i=0;i<aho.size();i++){
pr(i, aho[i].c, aho[i].failEdge);
}
string s = "abcdefgabab";
auto Idx = aho.matchedIdx(s);
for(int i=0;i<(int)s.size();i++) pr(i, s[i], Idx[i]);
}
void AOJ_2863(){
int n;
cin>>n;
AhoCorasick <26> aho([](char ch){return ch - 'a';});
for(int i=0;i<n;i++){
string s;
cin>>s;
aho.addWord(s);
}
aho.build();
string t;
cin>>t;
auto Idx = aho.matchedIdx(t);
int len = t.size();
vector<int> dp(len+1, 0);
dp[0] = 1;
const int mod = 1e9 + 7;
for(int i=0;i<len;i++){
for(int l:Idx[i]){
dp[i+l] = (dp[i+l] + dp[i])%mod;
}
}
int ans = dp[len];
cout<<ans<<endl;
}
void AOJ_2212(){
while(1){
int h,w;
cin>>h>>w;
if(h == 0 && w == 0) return;
vector<string> mp(h);
for(int i=0;i<h;i++) cin>>mp[i];
auto func = [](char ch){
if(ch == 'U') return 0;
if(ch == 'R') return 1;
if(ch == 'D') return 2;
if(ch == 'L') return 3;
return -1;
};
AhoCorasick <4> aho(func);
int m;
cin>>m;
for(int i=0;i<m;i++){
string s;
cin>>s;
aho.addWord(s);
}
aho.build();
int sy, sx;
for(int i=0;i<h;i++)
for(int j=0;j<w;j++) if(mp[i][j] == 'S') sy = i, sx = j;
auto bfs = [&]()->int{
typedef tuple<int,int,int,string> T;
queue<T> Q;
Q.push(T(sy, sx, 0, ""));
vector<vector<vector<int> > > D(h, vector<vector<int> > (w, vector<int>(aho.size(),-1)));
D[sy][sx][0] = 0;
string str = "URDL";
int dy[] = {-1, 0, 1, 0};
int dx[] = {0, 1, 0, -1};
while(!Q.empty()){
int y, x, pos;
string his;
tie(y, x, pos, his) = Q.front(); Q.pop();
int cost = D[y][x][pos];
if(aho.suffixMatch(pos) != -1) continue;
if(mp[y][x] == 'G') return cost;
for(int i=0;i<4;i++){
int ny = y + dy[i];
int nx = x + dx[i];
char dir = str[i];
if(ny < 0 || nx < 0 || ny >= h || nx >= w || mp[ny][nx] == '#') continue;
int to = aho.go(pos, dir);
if(to == -1) to = aho.failEdge(pos, dir);
if(D[ny][nx][to] != -1) continue;
D[ny][nx][to] = cost+1;
Q.push(T(ny, nx, to, his + dir));
}
}
return -1;
};
int ans = bfs();
cout<<ans<<endl;
}
}
signed main(){
//check();
AOJ_2212();
//AOJ_2863();
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cmath>
using namespace std;
typedef pair<int, int> P;
typedef pair<P, int> P2;
#define rep(i, n) for (int i=0; i<(n); i++)
#define all(c) (c).begin(), (c).end()
#define uniq(c) c.erase(unique(all(c)), (c).end())
#define _1 first
#define _2 second
#define pb push_back
#define INF 1145141919
#define MOD 1000000007
int DX[4] = {-1, 0, 1, 0};
int DY[4] = {0, -1, 0, 1};
string DS = "lurd";
class Trie {
public:
vector<vector<int> > V;
vector<vector<int> > par;
Trie() {
V.pb(vector<int>(26+1));
par.pb(vector<int>(26+1, 0));
}
int find(string s) {
int cur = 0;
for (char ch : s) {
int c = ch - 'a';
cur = V[cur][c+1];
if (cur == 0) return -1;
}
return cur;
}
void insert(string s) {
int cur = 0;
for (char ch : s) {
int c = ch - 'a';
if (V[cur][c+1] == 0) {
V[cur][c+1] = V.size();
V.pb(vector<int>(26+1));
par.pb(vector<int>(26+1, -1));
}
cur = V[cur][c+1];
}
}
int back(int s, int c) {
if (par[s][c] != -1) return par[s][c];
if (V[s][c+1] != 0) return s;
return par[s][c] = back(V[s][0], c);
}
};
class ACMatch {
public:
Trie t;
vector<int> acc;
vector<P> flow[26];
vector<string> S;
void add_str(string s) {
t.insert(s);
S.pb(s);
}
void build() {
acc.resize(t.V.size(), 0);
for (string s : S) acc[t.find(s)]++;
queue<int> q;
rep(i, 26) {
if (!t.V[0][i+1]) continue;
t.V[t.V[0][i+1]][0] = 0;
q.push(t.V[0][i+1]);
}
while (!q.empty()) {
int k = q.front(); q.pop();
rep(i, 26) {
if (!t.V[k][i+1]) continue;
q.push(t.V[k][i+1]);
int pre = t.V[k][0];
while (pre && t.V[pre][i+1]==0) pre = t.V[pre][0];
t.V[t.V[k][i+1]][0] = t.V[pre][i+1];
acc[t.V[k][i+1]] += acc[t.V[pre][i+1]];
}
}
rep(c, 26) {
rep(s, acc.size()) {
int ns = t.back(s, c);
ns = t.V[ns][c+1];
flow[c].pb(P(ns, acc[ns]));
}
}
}
P move(int s, int c) {
return flow[c][s];
}
int match(string S) {
int sum = 0, cur = 0;
for (char ch : S) {
int c = ch - 'a';
while (cur && t.V[cur][c+1]==0) cur = t.V[cur][0];
cur = t.V[cur][c+1];
sum += acc[cur];
}
return sum;
}
};
int W, H, N;
int SX, SY, GX, GY;
char A[50][50];
int dp[50][50][100];
signed main() {
ios::sync_with_stdio(false); cin.tie(0);
while (cin >> H >> W) {
if (H == 0 && W == 0) break;
rep(y, H) {
rep(x, W) {
char c;
cin >> c;
if (c == 'S') SX = x, SY = y;
if (c == 'G') GX = x, GY = y;
A[x][y] = c == '#';
}
}
ACMatch acm;
cin >> N;
rep(i, N) {
string s;
cin >> s;
for (char &c : s) {
if (c == 'L') c = 'l';
else if (c == 'U') c = 'u';
else if (c == 'R') c = 'r';
else if (c == 'D') c = 'd';
}
acm.add_str(s);
}
acm.build();
int L = acm.acc.size();
rep(x, W) {
rep(y, H) {
rep(s, L) {
dp[x][y][s] = INF;
}
}
}
queue<P2> q;
q.push(P2(P(SX, SY), 0));
dp[SX][SY][0] = 0;
while (!q.empty()) {
int x = q.front()._1._1,
y = q.front()._1._2,
s = q.front()._2;
q.pop();
rep(k, 4) {
int nx = x+DX[k], ny = y+DY[k];
if (nx<0||nx>=W||ny<0||ny>=H) continue;
if (A[nx][ny]) continue;
P p = acm.move(s, DS[k]-'a');
if (p._2 > 0) continue;
int ns = p._1;
if (dp[nx][ny][ns] > dp[x][y][s]+1) {
dp[nx][ny][ns] = dp[x][y][s]+1;
q.push(P2(P(nx, ny), ns));
}
}
}
int m = *min_element(dp[GX][GY], dp[GX][GY]+L);
if (m == INF) m = -1;
cout << m << "\n";
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i,x,y) for(int i=(x);i<(y);++i)
#define debug(x) #x << "=" << (x)
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl
#else
#define print(x)
#endif
const int inf=1e9;
const int64_t inf64=1e18;
const double eps=1e-9;
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){
os << "[";
for (const auto &v : vec) {
os << v << ",";
}
os << "]";
return os;
}
using i64=int64_t;
const int alphabet_size=4;
char table[4]={'R','U','L','D'};
class pma{
public:
pma* next[alphabet_size],*failure;
vector<int> matches;
string s;
pma(){
fill(next,next+alphabet_size,(pma*)0);
failure=NULL;
}
void insert(const string &str,const int id){ insert(str,0,id); }
void insert(const string &str,const int idx,const int id){
s=str.substr(0,idx);
if(idx==str.size()){
matches.push_back(id);
return;
}
if(next[str[idx]]==NULL) this->next[str[idx]]=new pma();
next[str[idx]]->insert(str,idx+1,id);
}
};
//ofstream ofs("graph.dot");
string convert(string s){
string res;
//for(char c:s) res+=table[c];
return res;
}
void add_edge(pma* from,pma*to,string label){
/*
ofs << " \"";
ofs << convert(from->s);
ofs << "\" -> \"";
ofs << convert(to->s);
ofs << "\" [label = \"" << label << "\"];" << endl;
*/
}
class aho_corasick{
public:
vector<string> dic;
pma* root;
aho_corasick(const vector<string>& dic_):dic(dic_),root(new pma()){
for(int i=0; i<dic.size(); ++i) root->insert(dic[i],i);
root->failure=root;
queue<pma*> que;
que.push(root);
add_edge(root,root,"failure");
while(!que.empty()){
pma* curr=que.front();
que.pop();
vector<bool> original_link(alphabet_size,true);
curr->matches.insert(curr->matches.end(),curr->failure->matches.begin(),curr->failure->matches.end());
for(int i=0; i<alphabet_size; ++i){
pma*& next=curr->next[i];
if(next==NULL){
if(curr==root) next=root;
else next=curr->failure->next[i];
//curr->matches.insert(curr->matches.end(),next->matches.begin(),next->matches.end());
original_link[i]=false;
add_edge(curr,curr->next[i],string(1,table[i]));
continue;
}
}
for(int i=0; i<alphabet_size; ++i){
if(!original_link[i]) continue;
pma*& next=curr->next[i];
if(curr==root) next->failure=root;
else next->failure=curr->failure->next[i];
next->matches.insert(next->matches.end(),curr->matches.begin(),curr->matches.end());
que.push(next);
add_edge(curr,next,string(1,table[i]));
add_edge(next,next->failure,"failure");
}
}
}
vector<bool> match(const string& s)const{
vector<bool> res(dic.size());
const pma* state=root;
for(char c:s){
state=state->next[c];
for(int i:state->matches) res[i]=true;
}
return res;
}
};
void solve(int N,int M){
vector<string> vs(N);
int sy,sx,gy,gx;
rep(i,0,N){
cin >> vs[i];
rep(j,0,M){
if(vs[i][j]=='S'){
sy=i;
sx=j;
}
if(vs[i][j]=='G'){
gy=i;
gx=j;
}
}
}
int P;
cin >> P;
vector<string> ban(P);
rep(i,0,P){
cin >> ban[i];
for(char& c:ban[i]){
if(c=='R') c=0;
if(c=='U') c=1;
if(c=='L') c=2;
if(c=='D') c=3;
}
}
aho_corasick ac(ban);
vector<int> dx={1,0,-1,0},dy={0,-1,0,1};
queue<tuple<int,int,pma*,int>> que;
set<tuple<int,int,pma*>> visited;
que.push(make_tuple(sy,sx,ac.root,0));
visited.insert(make_tuple(sy,sx,ac.root));
while(!que.empty()){
int y,x,d;
pma* curr;
tie(y,x,curr,d)=que.front();
que.pop();
if(y==gy and x==gx){
cout << d << endl;
return;
}
rep(i,0,4){
int ny=y+dy[i],nx=x+dx[i];
if(ny<0 or N<=ny or nx<0 or M<=nx or vs[ny][nx]=='#') continue;
pma* next=curr->next[i];
if(!next->matches.empty()){
//print(convert(curr->s));
//print(convert(next->s));
continue;
}
if(visited.find(make_tuple(ny,nx,next))!=visited.end()) continue;
que.push(make_tuple(ny,nx,next,d+1));
visited.insert(make_tuple(ny,nx,next));
}
}
cout << -1 << endl;
/*
function<int(int,int,pma*)> rec=[&](int y,int x,pma* state){
if(memo[y][x].find(state)!=memo[y][x].end()) return memo[y][x][state];
if(y==gy and x==gx) return memo[y][x][state]=0;
memo[y][x][state]=inf;
for(char c:state->s) cerr << int(c);
cerr << endl;
rep(i,0,4){
int ny=y+dy[i],nx=x+dx[i];
if(ny<0 or N<=ny or nx<0 or M<=nx or vs[ny][nx]=='#') continue;
pma* next_state=state->next[i];
if(!next_state->ids.empty()){
cerr << "BAN" << endl;
for(char c:next_state->s) cerr << int(c);
cerr << endl;
continue;
}
memo[y][x][state]=min(memo[y][x][state],rec(ny,nx,next_state)+1);
}
return memo[y][x][state];
};
int ans=rec(sy,sx,ac.root);
if(ans==inf) ans=-1;
cout << ans << endl;
*/
}
int main(){
std::cin.tie(0);
std::ios::sync_with_stdio(false);
cout.setf(ios::fixed);
cout.precision(10);
//ofs << "digraph G {" << endl << " graph [layout = dot];" << endl << " node [shape = \"ellipse\"];" << endl;
for(;;){
int N,M;
cin >> N >> M;
if(!N and !M) break;
solve(N,M);
}
//ofs << "}" << endl;
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
using namespace std;
#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef pair<int,int> pii;
const int INF = 1<<29;
const double PI = acos(-1);
const double EPS = 1e-8;
#include <iostream>
#include <vector>
#include <string>
#include <queue>
using namespace std;
// Aho-Corasick
// UVa 10679
// Æè ¦¸ MM > 128ɵĨ¯ÎASCIIÍüé
// TrieÅÀµÄ¢éÌÅAø¦Í«¢
const int MM = 150;
struct Node {
int id;
int next[MM];
int fail;
vector<int> value;
Node() {
for(int i=0; i<MM; ++i) next[i] = 0;
value.clear();
}
};
class Trie {
public:
Trie(const vector<string> &vs) {
nodes.push_back(new Node()); // dummy
nodes.push_back(new Node());
for(int i=0; i<vs.size(); ++i)
insert(vs[i],i);
}
Trie() {
nodes.clear();
}
void insert(const string &s,int k) {
Node *cur = nodes[1];
for(int i=0; i<s.length(); ++i) {
if(cur->next[s[i]] == 0) {
cur->next[s[i]] = nodes.size();
nodes.push_back(new Node());
}
cur = nodes[cur->next[s[i]]];
}
cur->value.push_back(k);
}
vector<Node*> nodes;
};
class Aho_Corasick {
public:
Aho_Corasick(const vector<string> &vs) {
nodes = Trie(vs).nodes;
make_failure_link();
}
void make_failure_link() {
//const vector<Node*> &nodes = _trie.nodes;
queue<int> q;
Node *root = nodes[1];
for(int i=0; i<MM; ++i) {
if(root->next[i]) {
nodes[root->next[i]]->fail = 1;
q.push(root->next[i]);
}else root->next[i] = 1;
}
while(!q.empty()) {
Node *t = nodes[q.front()]; q.pop();
for(int i=0; i<MM; ++i) {
int u = t->next[i];
if(u) {
q.push(u);
int r = t->fail;
while(!nodes[r]->next[i]) r = nodes[r]->fail;
nodes[u]->fail = nodes[r]->next[i];
FOR(it, nodes[nodes[u]->fail]->value) {
nodes[u]->value.push_back(*it);
}
}
}
}
}
int match(const string &s) {
int ret = 0;
int v = 1;
for(int i=0; i<s.length(); ++i) {
while(!nodes[v]->next[s[i]]) {
v = nodes[v]->fail;
}
v = nodes[v]->next[s[i]];
if(!(nodes[v]->value.empty())) { // found the word
ret += nodes[v]->value.size();
}
}
return ret;
}
int next(int v, char c) {
while(!nodes[v]->next[c]) {
v = nodes[v]->fail;
}
v = nodes[v]->next[c];
if(!(nodes[v]->value.empty())) { // found the word
return -1;
}
return v;
}
void free() {
for(int i=0; i<nodes.size(); ++i)
delete nodes[i];
}
vector<Node*> nodes;
};
char ba[50][50];
int dx[4] = {0,1,0,-1};
int dy[4] = {-1,0,1,0};
char dir[4] = {'U','R','D','L'};
struct P {
int y, x, v;
P(int y, int x, int v) : y(y),x(x),v(v) {}
};
int dis[50][50][102];
int main() {
int h, w;
while(cin >> h >> w, h||w) {
int sy,sx;
REP(i, h) {
REP(j, w) {
cin >> ba[i][j];
if (ba[i][j] == 'S') sy=i,sx=j;
}
}
int m;
cin >> m;
vector<string> vs(m);
REP(i, m) cin >> vs[i];
Aho_Corasick pma(vs);
queue<P> Q;
Q.push(P(sy,sx,1));
memset(dis,-1,sizeof(dis));
dis[sy][sx][1] = 0;
int ans = -1;
while(!Q.empty()) {
P p = Q.front(); Q.pop();
// cout << string(dis[p.y][p.x][p.v], ' ');
// cout << p.x << " " << p.y << " " << p.v << endl;
if (ba[p.y][p.x] == 'G') {
ans = dis[p.y][p.x][p.v];
break;
}
REP(k, 4) {
int yy = p.y+dy[k];
int xx = p.x+dx[k];
if (yy<0||yy>=h||xx<0||xx>=w) continue;
if (ba[yy][xx] == '#') continue;
int vv = pma.next(p.v, dir[k]);
//cout << xx << ":" << yy << ":" << vv << endl;
//cout << dis[yy][xx][vv] << endl;
if (vv != -1 && dis[yy][xx][vv] == -1) {
dis[yy][xx][vv] = dis[p.y][p.x][p.v]+1;
Q.push(P(yy,xx,vv));
}
}
}
cout << ans << endl;
}
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
using namespace std;
typedef pair<int, int> P;
int n, m, p, K, ans;
const char UDLR[4] = {'U', 'D', 'L', 'R'};
const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
char map[52][52], tmp[15];
string patterns[15];
vector<string> pfx;
int next_state[150][4], map_state[52][52][150];
bool ng[150];
queue< P > que;
bool check(int x, int y){
return x>=0&&x<n&&y>=0&&y<m&&map[x][y]!='#';
}
void bfs(){
memset(map_state, 255, sizeof(map_state));
int sx, sy, ex, ey;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
switch (map[i][j]){
case 'S':
sx = i;
sy = j;
break;
case 'G':
ex = i;
ey = j;
break;
default:
break;
}
while(!que.empty()) que.pop();
map_state[sx][sy][0] = 0;
que.push(P(sx*m+sy, 0));
bool reach=false;
int tx, ty, tk, xx, yy, kk;
ans = -1;
while(!que.empty()){
tx = que.front().first / m; ty = que.front().first % m; tk = que.front().second;
que.pop();
for(int i=0; i<4; i++){
kk = next_state[tk][i];
if(!ng[kk] && check(tx+dx[i], ty+dy[i])){
// state kk is not forbidden
xx = tx + dx[i];
yy = ty + dy[i];
if(map_state[xx][yy][kk] == -1){
map_state[xx][yy][kk] = map_state[tx][ty][tk] + 1;
que.push(P(xx*m+yy, kk));
if(xx==ex && yy==ey){
reach = true;
ans = map_state[xx][yy][kk];
break;
}
}
}
}
if(reach) break;
}
printf("%d\n", ans);
}
int main(){
//freopen("in.txt", "r", stdin);
int k;
while(scanf("%d %d", &n, &m), n!=0 && m!=0){
for(int i=0; i<n; i++)
scanf("%s", map[i]);
scanf("%d", &p);
pfx.clear();
for(int i=0; i<p; i++){
scanf("%s", tmp);
patterns[i].assign(tmp);
for(int j=0; j<=patterns[i].length(); j++)
pfx.push_back(patterns[i].substr(0, j));
}
pfx.push_back(string(""));
sort(pfx.begin(), pfx.end());
pfx.erase(unique(pfx.begin(), pfx.end()), pfx.end());
K = pfx.size();
for(int i=0; i<K; i++){
ng[i] = false;
for(int j=0; j<p; j++){
ng[i] |= patterns[j].length()<=pfx[i].length()
&& pfx[i].substr(pfx[i].length()-patterns[j].length(), patterns[j].length()) == patterns[j];
}
for(int j=0; j<4; j++){
string s = pfx[i] + UDLR[j];
for(;;){
k = lower_bound(pfx.begin(), pfx.end(), s) - pfx.begin();
if(k<K && pfx[k]==s) break;
s = s.substr(1);
}
next_state[i][j] = k;
}
}
bfs();
}
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <cfloat>
#include <ctime>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <numeric>
#include <list>
using namespace std;
#ifdef _MSC_VER
#define __typeof__ decltype
template <class T> int __builtin_popcount(T n) { return n ? 1 + __builtin_popcount(n & (n - 1)) : 0; }
#endif
#define foreach(it, c) for (__typeof__((c).begin()) it=(c).begin(); it != (c).end(); ++it)
#define all(c) (c).begin(), (c).end()
#define rall(c) (c).rbegin(), (c).rend()
#define popcount __builtin_popcount
#define rep(i, n) for (int i = 0; i < n; ++i)
template <class T> void max_swap(T& a, const T& b) { a = max(a, b); }
template <class T> void min_swap(T& a, const T& b) { a = min(a, b); }
typedef long long ll;
typedef pair<int, int> pint;
const double PI = acos(-1.0);
const int dx[] = { 0, 1, 0, -1 };
const int dy[] = { 1, 0, -1, 0 };
vector<int> build_pma(const vector<int>& pat)
{
vector<int> res(pat.size() + 1);
res[0] = -1;
for (int i = 0, j = -1; i < pat.size(); ++i)
{
while (j >= 0 && pat[i] != pat[j])
j = res[j];
res[i + 1] = ++j;
}
return res;
}
ll encode(const vector<int>& states)
{
ll res = 0;
for (int i = states.size() - 1; i >= 0; --i)
res = res << 4 | states[i];
return res;
}
void decode(ll e, vector<int>& res)
{
for (int i = 0; i < res.size(); ++i, e >>= 4)
res[i] = e & 0xf;
}
ll next_states(const vector<vector<int> >& pat, const vector<vector<int> >& pma, ll states, int dir)
{
ll res = 0;
vector<int> cur(pat.size()), next;
decode(states, cur);
for (int i = 0; i < cur.size(); ++i)
{
while (cur[i] >= 0 && pat[i][cur[i]] != dir)
cur[i] = pma[i][cur[i]];
if (++cur[i] == pat[i].size())
return -1;
next.push_back(cur[i]);
}
return encode(next);
}
struct Node
{
int x, y;
ll states;
Node(int x, int y, ll s)
: x(x), y(y), states(s) {}
};
int main()
{
int n, m, p;
while (cin >> n >> m, n | m)
{
string maze[64], pp[16];
rep (i, n)
cin >> maze[i];
cin >> p;
rep (i, p)
cin >> pp[i];
int sx, sy, gx, gy;
rep (y, n)
{
rep (x, m)
{
if (maze[y][x] == 'S')
sx = x, sy = y;
else if (maze[y][x] == 'G')
gx = x, gy = y;
}
}
vector<vector<int> > pat(p);
rep (i, p)
rep (j, pp[i].size())
pat[i].push_back(string("DRUL").find(pp[i][j]));
vector<vector<int> > pma(p);
rep (i, p)
pma[i] = build_pma(pat[i]);
int res = -1;
map<ll, int> visit[64][64];
queue<Node> q;
q.push(Node(sx, sy, 0));
visit[sy][sx][0] = 0;
while (!q.empty())
{
Node cur = q.front(); q.pop();
int cost = visit[cur.y][cur.x][cur.states] + 1;
for (int i = 0; i < 4; ++i)
{
int nx = cur.x + dx[i], ny = cur.y + dy[i];
if (0 <= nx && nx < m && 0 <= ny && ny < n
&& maze[ny][nx] != '#')
{
ll ns = next_states(pat, pma, cur.states, i);
if (ns != -1 && !visit[ny][nx].count(ns))
{
vector<int> s(p);
decode(ns, s);
if (nx == gx && ny == gy)
{
res = cost;
goto End;
}
else
{
q.push(Node(nx, ny, ns));
visit[ny][nx][ns] = cost;
}
}
}
}
}
End:
cout << res << endl;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#define V(x, y, z) ((x) * 1000000 + (y) * 1000 + (z))
#define inf 1000000000
using namespace std;
int W, H;
char map[55][55];
int P;
string S[15];
int sx, sy, gx, gy;
vector<string> vec;
int Next[105][4];
bool ng[105][4];
const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const char c[] = {'R', 'U', 'L', 'D'};
int dist[55][55][105];
int bfs()
{
for(int x = 1; x <= W; x++){
for(int y = 1; y <= H; y++){
for(int k = 0; k < vec.size(); k++){
dist[x][y][k] = inf;
}
}
}
dist[sx][sy][0] = 0;
queue<int> Q;
Q.push(V(sx, sy, 0));
int x, y, state;
while(Q.size()){
state = Q.front() % 1000, Q.front() /= 1000;
y = Q.front() % 1000, Q.front() /= 1000;
x = Q.front();
Q.pop();
for(int i = 0; i < 4; i++){
int nx = x + dx[i], ny = y + dy[i], nstate = Next[state][i];
if(ng[state][i]) continue;
if(nx <= 0 || nx > W || ny <= 0 || ny > H) continue;
if(map[nx][ny] == '#') continue;
if(dist[nx][ny][nstate] < inf) continue;
dist[nx][ny][nstate] = dist[x][y][state] + 1;
Q.push(V(nx, ny, nstate));
}
}
int ret = inf;
for(int i = 0; i < vec.size(); i++) ret = min(ret, dist[gx][gy][i]);
if(ret == inf) return -1;
return ret;
}
int main(void)
{
while(1){
cin >> H >> W;
if(H == 0 && W == 0) break;
for(int y = 1; y <= H; y++){
for(int x = 1; x <= W; x++){
cin >> map[x][y];
if(map[x][y] == 'S') sx = x, sy = y;
if(map[x][y] == 'G') gx = x, gy = y;
}
}
cin >> P;
for(int i = 0; i < P; i++) cin >> S[i];
vec.clear();
vec.push_back("");
for(int i = 0; i < P; i++){
for(int j = 0; j < S[i].size(); j++){
vec.push_back(S[i].substr(0, j));
}
}
sort(vec.begin(), vec.end());
vec.erase(unique(vec.begin(), vec.end()), vec.end());
for(int i = 0; i < vec.size(); i++){
for(int j = 0; j < 4; j++){
ng[i][j] = false;
}
}
for(int i = 0; i < vec.size(); i++){
for(int j = 0; j < 4; j++){
string s = vec[i] + c[j];
for(int k = 0; k < P; k++){
string t = s;
while(t.size()){
if(t == S[k]){
ng[i][j] = true;
goto end;
}
t = t.substr(1);
}
}
end:;
while(1){
auto p = lower_bound(vec.begin(), vec.end(), s);
if(p != vec.end() && *p == s){
Next[i][j] = p - vec.begin();
break;
}
s = s.substr(1);
}
}
}
cout << bfs() << endl;
}
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include<iostream>
#include<vector>
#include<queue>
#include<string>
#include<cstring>
using namespace std;
class PMA{//Aho-Corasick
int id;
bool match;
PMA *failure;
PMA *next[256];
public:
PMA(int id=0):id(id),match(false),failure(0){
memset(next,0,sizeof(next));
}
~PMA(){
for(int i=0;i<256;i++){
if(next[i]&&next[i]!=this)delete next[i];
}
}
int getID()const{return id;}
bool matched()const{return match;}
void build(const vector<string> &p){
int num=1;
for(int i=0;i<(int)p.size();i++){
const string &s=p[i];
PMA *t=this;
for(int j=0;j<(int)s.size();j++){
if(!t->next[s[j]])t->next[s[j]]=new PMA(num++);
t=t->next[s[j]];
}
t->match=true;
}
queue<PMA*> q;
for(int i=0;i<256;i++){
if(next[i]){
q.push(next[i]);
next[i]->failure=this;
}else next[i]=this;
}
while(!q.empty()){
PMA *t=q.front();q.pop();
for(int i=0;i<256;i++){
if(t->next[i]){
q.push(t->next[i]);
PMA *r=t->failure;
while(!r->next[i])r=r->failure;
t->next[i]->failure=r=r->next[i];
t->next[i]->match |= r->match;
}
}
}
}
PMA *step(char c)const{
const PMA *t=this;
while(!t->next[c])t=t->failure;
return t->next[c];
}
};
string ch("DRUL");
int dy[]={1,0,-1,0};
int dx[]={0,1,0,-1};
int h,w;
char m[52][52];
int dp[51][51][102];
struct Node{
int y,x;
PMA *p;
};
int bfs(PMA &pma){
memset(dp,-1,sizeof(dp));
Node a,b;
for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)if(m[i][j]=='S'){
a.y=i;
a.x=j;
a.p=&pma;
}
queue<Node> q;
dp[a.y][a.x][a.p->getID()]=0;
q.push(a);
while(!q.empty()){
a=q.front();q.pop();
int d=dp[a.y][a.x][a.p->getID()];
for(int i=0;i<4;i++){
b.y=a.y+dy[i];
b.x=a.x+dx[i];
if(m[b.y][b.x]=='#')continue;
b.p=a.p->step(ch[i]);
if(b.p->matched())continue;
if(m[b.y][b.x]=='G')return d+1;
if(dp[b.y][b.x][b.p->getID()]==-1){
dp[b.y][b.x][b.p->getID()] = d+1;
q.push(b);
}
}
}
return -1;
}
int main(){
while(cin>>h>>w&&(h||w)){
memset(m,'#',sizeof(m));
for(int i=1;i<=h;i++)
for(int j=1;j<=w;j++)
cin>>m[i][j];
int n;
cin>>n;
vector<string> p(n);
for(int i=0;i<n;i++){
cin>>p[i];
}
PMA pma;
pma.build(p);
cout<<bfs(pma)<<endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include<iostream>
#include<string>
#include<queue>
#include<vector>
#include<tuple>
using namespace std;
int H, W, K, x[60][60], dist[60][60][200], sx, sy, gx, gy, dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
string S[10], dir = "DRUL";
vector<tuple<string, int, int>>vec;
vector<tuple<int, int, int>> X[60][60][200];
vector<pair<int, int>>banned[200];
void build_banned() {
int cnt1 = 1;
vec.push_back(make_tuple("", 0, 0));
for (int i = 0; i < K; i++) {
for (int j = 0; j <= S[i].size(); j++) {
string F = S[i].substr(0, j);
bool OK = true;
for (int k = 0; k < vec.size(); k++) {
if (get<0>(vec[k]) == F) {
OK = false;
if (j == S[i].size()) { get<2>(vec[k]) = 1; }
}
}
if (OK == true && j != S[i].size()) { vec.push_back(make_tuple(F, cnt1, 0)); cnt1++; }
if (OK == true && j == S[i].size()) { vec.push_back(make_tuple(F, cnt1, 1)); cnt1++; }
}
}
for (int i = 0; i < vec.size(); i++) {
for (int j = 0; j < 4; j++) {
string W2 = get<0>(vec[i]); W2 += dir[j];
bool OK = true; int to = 0;
while (W2.size() >= 1) {
for (int k = 0; k < vec.size(); k++) {
string W3 = get<0>(vec[k]);
if (W3 == W2 && get<2>(vec[k]) == 1) { OK = false; }
if (W3 == W2 && get<2>(vec[k]) == 0) {
if (get<0>(vec[to]).size() < W2.size())to = k;
}
}
W2 = W2.substr(1, W2.size() - 1);
}
if (OK == true)banned[i].push_back(make_pair(to, j));
}
}
}
void add_edges() {
for (int i = 1; i <= H; i++) {
for (int j = 1; j <= W; j++) {
for (int k = 0; k < vec.size(); k++) {
if (get<2>(vec[k]) == 1)continue;
for (int l = 0; l < 4; l++) {
int cx = i + dx[l], cy = j + dy[l];
if (cx <= 0 || cy <= 0 || cx > H || cy > W || x[cx][cy] == 2)continue;
for (int m = 0; m < banned[k].size(); m++) {
if (banned[k][m].second == l)X[i][j][k].push_back(make_tuple(cx, cy, banned[k][m].first));
}
}
}
}
}
}
int bfs() {
queue<tuple<int, int, int>>Q;
for (int i = 0; i < 60; i++) { for (int j = 0; j < 60; j++) { for (int k = 0; k < 200; k++)dist[i][j][k] = 999999999; } }
Q.push(make_tuple(sx, sy, 0)); dist[sx][sy][0] = 0;
while (!Q.empty()) {
int a1 = get<0>(Q.front()), a2 = get<1>(Q.front()), a3 = get<2>(Q.front()); Q.pop();
for (int i = 0; i < X[a1][a2][a3].size(); i++) {
int tox = get<0>(X[a1][a2][a3][i]), toy = get<1>(X[a1][a2][a3][i]), toz = get<2>(X[a1][a2][a3][i]);
if (dist[tox][toy][toz] == 999999999) {
dist[tox][toy][toz] = dist[a1][a2][a3] + 1;
Q.push(make_tuple(tox, toy, toz));
}
}
}
int maxn = 999999999;
for (int i = 0; i < vec.size(); i++)maxn = min(maxn, dist[gx][gy][i]);
return maxn;
}
int main() {
while (true) {
vec.clear(); for (int i = 0; i < 3600; i++)x[i / 60][i % 60] = 0;
for (int i = 0; i < 60; i++) { for (int j = 0; j < 60; j++) { for (int k = 0; k < 200; k++)X[i][j][k].clear(); } }
for (int i = 0; i < 200; i++)banned[i].clear();
cin >> H >> W; if (H == 0 && W == 0)break;
for (int i = 1; i <= H; i++) {
for (int j = 1; j <= W; j++) {
char c; cin >> c;
if (c == '.') { x[i][j] = 1; }
if (c == '#') { x[i][j] = 2; }
if (c == 'S') { x[i][j] = 1; sx = i; sy = j; }
if (c == 'G') { x[i][j] = 1; gx = i; gy = j; }
}
}
cin >> K; for (int i = 0; i < K; i++) { cin >> S[i]; }
build_banned();
add_edges();
int ans = bfs(); if (ans == 999999999)ans = -1;
cout << ans << endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e8;
const int dx[] = { 1, 0, -1, 0 };
const int dy[] = { 0, 1, 0, -1 };
string D = "DRUL";
// Aho-Corasick
const int var = 4;
int trans(char c) {
switch (c)
{
case 'R': return 0;
case 'D': return 1;
case 'L': return 2;
case 'U': return 3;
default: break;
}
exit(EXIT_FAILURE);
}
struct node {
node *fail;
vector<node*> next;
vector<int> ok;
node() : fail(nullptr), next(var, nullptr) {}
};
node* getnext(node* p, char c) {
while (p->next[trans(c)] == nullptr) p = p->fail;
return p->next[trans(c)];
}
class Aho_Corasick {
vector<int> unite(const vector<int>& a, const vector<int>& b) {
vector<int> res;
set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(res));
return res;
}
int K;
node *root;
public:
Aho_Corasick(const vector<string>& Ts) : K(Ts.size()), root(new node) {
node *now;
root->fail = root;
for (int i = 0; i < K; i++) {
auto &T = Ts[i];
now = root;
for (auto c : T) {
if (now->next[trans(c)] == nullptr) {
now->next[trans(c)] = new node;
}
now = now->next[trans(c)];
}
now->ok.push_back(i);
}
queue<node*> q;
for (int i = 0; i < var; i++) {
if (root->next[i] == nullptr) {
root->next[i] = root;
}
else {
root->next[i]->fail = root;
q.push(root->next[i]);
}
}
while (!q.empty()) {
now = q.front(); q.pop();
for (int i = 0; i < var; i++) {
if (now->next[i] != nullptr) {
node *nx = now->fail;
while (nx->next[i] == nullptr) {
nx = nx->fail;
}
now->next[i]->fail = nx->next[i];
now->next[i]->ok = unite(now->next[i]->ok, nx->next[i]->ok);
q.push(now->next[i]);
}
}
}
}
node* getroot() const {
return root;
}
vector<int> count(const string& S) const {
vector<int> res(K);
node *now = root;
for (auto c : S) {
while (now->next[trans(c)] == nullptr) {
now = now->fail;
}
now = now->next[trans(c)];
for (auto k : now->ok) {
res[k]++;
}
}
return res;
}
};
using T = tuple<int, int, node*>;
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int n, m, p;
while (cin >> n >> m, n | m) {
vector<string> S(n);
int sx = 0, sy = 0, gx = 0, gy = 0;
for (int i = 0; i < n; i++) {
cin >> S[i];
for (int j = 0; j < (int)S[i].size(); j++) {
if (S[i][j] == 'S') {
sx = i;
sy = j;
}
else if (S[i][j] == 'G') {
gx = i;
gy = j;
}
}
}
cin >> p;
vector<string> pts(p);
for (int i = 0; i < p; i++) {
cin >> pts[i];
}
Aho_Corasick aho(pts);
vector<vector<map<node*, int>>> f(n, vector<map<node*, int>>(m));
queue<T> q;
q.push(make_tuple(sx, sy, aho.getroot()));
f[sx][sy][aho.getroot()] = 0;
while (!q.empty()) {
auto p = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int tx = get<0>(p) + dx[i], ty = get<1>(p) + dy[i];
node *t = getnext(get<2>(p), D[i]);
if (0 <= tx && tx < n && 0 <= ty && ty < m && S[tx][ty] != '#' && t->ok.empty() && f[tx][ty].count(t) == 0) {
q.push(make_tuple(tx, ty, t));
f[tx][ty][t] = f[get<0>(p)][get<1>(p)][get<2>(p)] + 1;
}
}
}
int res = INF;
for (auto p : f[gx][gy]) {
res = min(res, p.second);
}
cout << (res != INF ? res : -1) << endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;
class PMA
{
int n;
vector<vector<int> > next;
vector<bitset<32> > match;
vector<int> failure;
public:
PMA(const vector<string>& pattern){
next.assign(1, vector<int>(128, -1));
match.assign(1, 0);
for(unsigned i=0; i<pattern.size(); ++i){
int curr = 0;
for(unsigned j=0; j<pattern[i].size(); ++j){
if(next[curr][pattern[i][j]] == -1){
next[curr][pattern[i][j]] = next.size();
next.push_back(vector<int>(128, -1));
match.push_back(0);
}
curr = next[curr][pattern[i][j]];
}
match[curr][i] = true;
}
n = next.size();
failure.resize(n, 0);
vector<int> node1(1, 0);
while(!node1.empty()){
vector<int> node2;
for(unsigned i=0; i<node1.size(); ++i){
for(int j=0; j<128; ++j){
int s = node1[i];
if(next[s][j] == -1)
continue;
node2.push_back(next[s][j]);
int t = s;
while(t != 0){
if(next[failure[t]][j] != -1){
failure[next[s][j]] = next[failure[t]][j];
match[next[s][j]] |= match[next[failure[t]][j]];
break;
}
t = failure[t];
}
}
}
node1.swap(node2);
}
}
int size(){
return n;
}
int transition(int curr, char c){
if(next[curr][c] != -1)
return next[curr][c];
if(curr == 0)
return 0;
return transition(failure[curr], c);
}
bitset<32> checkMatch(int curr){
return match[curr];
}
};
char dc[] = "URDL";
int dy[] = {-1, 0, 1, 0};
int dx[] = {0, 1, 0, -1};
int main()
{
for(;;){
int h, w;
cin >> h >> w;
if(h == 0)
return 0;
vector<string> grid(h+2, string(w+2, '#'));
int sy, sx, gy, gx;
for(int i=1; i<=h; ++i){
for(int j=1; j<=w; ++j){
cin >> grid[i][j];
if(grid[i][j] == 'S'){
sy = i;
sx = j;
grid[i][j] = '.';
}
if(grid[i][j] == 'G'){
gy = i;
gx = j;
grid[i][j] = '.';
}
}
}
int p;
cin >> p;
vector<string> pattern(p);
for(int i=0; i<p; ++i)
cin >> pattern[i];
PMA pma(pattern);
int n = pma.size();
vector<vector<vector<int> > > minCost(h+2, vector<vector<int> >(w+2, vector<int>(n, INT_MAX)));
minCost[sy][sx][0] = 0;
queue<pair<pair<int, int>, int> > q;
q.push(make_pair(make_pair(sy, sx), 0));
bool ng = true;
while(!q.empty()){
int y0 = q.front().first.first;
int x0 = q.front().first.second;
int s = q.front().second;
int cost = minCost[y0][x0][s];
q.pop();
if(y0 == gy && x0 == gx){
cout << cost << endl;
ng = false;
break;
}
for(int i=0; i<4; ++i){
int y = y0 + dy[i];
int x = x0 + dx[i];
int t = pma.transition(s, dc[i]);
if(grid[y][x] == '#' || minCost[y][x][t] < INT_MAX || pma.checkMatch(t).any())
continue;
minCost[y][x][t] = cost + 1;
q.push(make_pair(make_pair(y, x), t));
}
}
if(ng)
cout << -1 << endl;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
using namespace std;
#define FOR(i,k,n) for(int i=(k); i<(int)(n); ++i)
#define REP(i,n) FOR(i,0,n)
#define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cerr<<*i<<" "; cerr<<endl; }
inline bool valid(int x, int y, int W, int H){ return (x >= 0 && y >= 0 && x < W && y < H); }
typedef long long ll;
const int INF = 100000000;
const double EPS = 1e-8;
const int MOD = 1000000007;
int dx[8] = {0, 1, 0, -1, 1, -1, -1, 1};
int dy[8] = {-1, 0, 1, 0, 1, 1, -1, -1};
struct PMA{
int next[0x100];
bool match;
PMA() { memset(next, -1, sizeof(next)); match = false;}
};
int SIZE = 0;
PMA P[200];
string URDL = "URDL";
int make_PMA(){
P[SIZE] = PMA();
return SIZE++;
}
void build_PMA(vector<string> vs){
SIZE = 0;
int root = make_PMA();
for(int i = 0; i < vs.size(); i++){
int t = root;
for(int j = 0; j < vs[i].size(); j++){
if(P[t].next[vs[i][j]] == -1){ P[t].next[vs[i][j]] = make_PMA(); }
t = P[t].next[vs[i][j]];
}
P[t].match = true;
}
queue<int> que;
for(int i = 0; i < 4; i++){
char c = URDL[i];
int next = P[root].next[c];
if(next != -1){
P[next].next[0] = root;
que.push(next);
}else {
P[root].next[c] = root;
}
}
while(!que.empty()){
int t = que.front(); que.pop();
for(int i = 0; i < 4; i++){
char c = URDL[i];
int next = P[t].next[c];
if(next != -1){
que.push(next);
int r = P[t].next[0];
while(P[r].next[c] == -1) r = P[r].next[0];
P[next].next[0] = P[r].next[c];
//need??
if(P[P[r].next[c]].match) P[next].match = true;
}
}
}
}
int move(int t, char c){
while(P[t].next[c] == -1) t = P[t].next[0];
return P[t].next[c];
}
int main(){
int H, W;
while(cin>>H>>W && H){
vector<string> grid(H);
REP(y, H) cin>>grid[y];
int PL;
cin>>PL;
vector<string> ban(PL);
REP(i, PL) cin>>ban[i];
build_PMA(ban);
int dist[50][50][110] = {};
memset(dist, -1, sizeof(dist));
queue<int> qx, qy, qt;
REP(y, H)REP(x, W)if(grid[y][x] == 'S'){
qx.push(x);
qy.push(y);
qt.push(0);
dist[y][x][0] = 0;
}
int ans = -1;
while(!qx.empty()){
int x = qx.front(); qx.pop();
int y = qy.front(); qy.pop();
int t = qt.front(); qt.pop();
int d = dist[y][x][t];
if(grid[y][x] == 'G'){
ans = d;
break;
}
REP(r, 4){
int nx = x + dx[r];
int ny = y + dy[r];
int nt = move(t, URDL[r]);
if(valid(nx, ny, W, H) && grid[ny][nx] != '#' && dist[ny][nx][nt] == -1 && !(P[nt].match)){
qy.push(ny); qx.push(nx); qt.push(nt);
dist[ny][nx][nt] = d + 1;
}
}
}
cout<<ans<<endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i,x,y) for(int i=(x);i<(y);++i)
#define debug(x) #x << "=" << (x)
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl
#else
#define print(x)
#endif
const int inf=1e9;
const int64_t inf64=1e18;
const double eps=1e-9;
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){
os << "[";
for (const auto &v : vec) {
os << v << ",";
}
os << "]";
return os;
}
using i64=int64_t;
const int alphabet_size=4;
class pma{
public:
pma* next[alphabet_size],*failure;
vector<int> matches;
string s;
pma(){
fill(next,next+alphabet_size,(pma*)0);
failure=NULL;
}
void insert(const string &str,const int id){ insert(str,0,id); }
void insert(const string &str,const int idx,const int id){
s=str.substr(0,idx);
if(idx==str.size()){
matches.push_back(id);
return;
}
if(next[str[idx]]==NULL) this->next[str[idx]]=new pma();
next[str[idx]]->insert(str,idx+1,id);
}
};
class aho_corasick{
public:
vector<string> dic;
pma* root;
aho_corasick(const vector<string>& dic_):dic(dic_),root(new pma()){
for(int i=0; i<dic.size(); ++i) root->insert(dic[i],i);
root->failure=root;
queue<pma*> que;
que.push(root);
while(!que.empty()){
pma* curr=que.front();
que.pop();
curr->matches.insert(curr->matches.end(),curr->failure->matches.begin(),curr->failure->matches.end());
for(int i=0; i<alphabet_size; ++i){
pma*& next=curr->next[i];
if(next==NULL){
next=curr==root?root:curr->failure->next[i];
continue;
}
next->failure=curr==root?root:curr->failure->next[i];
next->matches.insert(next->matches.end(),curr->matches.begin(),curr->matches.end());
que.push(next);
}
}
}
vector<bool> match(const string& s)const{
vector<bool> res(dic.size());
const pma* state=root;
for(char c:s){
state=state->next[c];
for(int i:state->matches) res[i]=true;
}
return res;
}
};
void solve(int N,int M){
vector<string> vs(N);
int sy,sx,gy,gx;
rep(i,0,N){
cin >> vs[i];
rep(j,0,M){
if(vs[i][j]=='S'){
sy=i;
sx=j;
}
if(vs[i][j]=='G'){
gy=i;
gx=j;
}
}
}
int P;
cin >> P;
vector<string> ban(P);
rep(i,0,P){
cin >> ban[i];
for(char& c:ban[i]){
if(c=='R') c=0;
if(c=='U') c=1;
if(c=='L') c=2;
if(c=='D') c=3;
}
}
aho_corasick ac(ban);
vector<int> dx={1,0,-1,0},dy={0,-1,0,1};
queue<tuple<int,int,pma*,int>> que;
set<tuple<int,int,pma*>> visited;
que.push(make_tuple(sy,sx,ac.root,0));
visited.insert(make_tuple(sy,sx,ac.root));
while(!que.empty()){
int y,x,d;
pma* curr;
tie(y,x,curr,d)=que.front();
que.pop();
if(y==gy and x==gx){
cout << d << endl;
return;
}
rep(i,0,4){
int ny=y+dy[i],nx=x+dx[i];
if(ny<0 or N<=ny or nx<0 or M<=nx or vs[ny][nx]=='#') continue;
pma* next=curr->next[i];
if(!next->matches.empty()) continue;
if(visited.find(make_tuple(ny,nx,next))!=visited.end()) continue;
que.push(make_tuple(ny,nx,next,d+1));
visited.insert(make_tuple(ny,nx,next));
}
}
cout << -1 << endl;
}
int main(){
std::cin.tie(0);
std::ios::sync_with_stdio(false);
cout.setf(ios::fixed);
cout.precision(10);
for(;;){
int N,M;
cin >> N >> M;
if(!N and !M) break;
solve(N,M);
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <array>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <tuple>
#include <unordered_map>
#include <vector>
using namespace std;
constexpr int ALPHA = 4;
constexpr int MAX_V = 10000;
const int BASE = 'a';
struct trie {
int v;
int failure;
bool accept;
array<int, ALPHA> next;
explicit trie(int v_):v(v_), failure(0), accept(false) { next.fill(-1); }
};
vector<trie> nodes;
char convert[128];
void add(const string &s) {
int v = 0;
for(const char &c : s) {
const int id = convert[c] - BASE;
if(nodes[v].next[id] == -1) {
nodes[v].next[id] = nodes.size();
nodes.emplace_back(nodes.size());
}
v = nodes[v].next[id];
}
nodes[v].accept = true;
}
void construct(const vector<string> &dict) {
nodes.clear();
nodes.reserve(MAX_V);
nodes.emplace_back(0);
for(const auto &s : dict) {
add(s);
}
queue<int> que;
que.push(0);
while(!que.empty()) {
const trie ¤t = nodes[que.front()];
que.pop();
for(int i = 0; i < ALPHA; ++i) {
const int next_id = current.next[i];
if(next_id == -1) continue;
que.push(next_id);
trie &u = nodes[next_id];
if(current.v) {
int f = current.failure;
while(f && nodes[f].next[i] == -1) {
f = nodes[f].failure;
}
const int nf = nodes[f].next[i];
if(nf != -1) {
u.failure = nf;
u.accept |= nodes[nf].accept;
}
}
}
}
}
int move_to(int v, char c) {
const int id = c - BASE;
while(v && nodes[v].next[id] == -1) {
v = nodes[v].failure;
}
if(nodes[v].next[id] != -1) {
v = nodes[v].next[id];
}
return v;
}
constexpr int dx[] = {-1, 0, 1, 0};
constexpr int dy[] = {0, 1, 0, -1};
inline bool out(int x, int y, int w, int h) {
return x < 0 || y < 0 || x >= w || y >= h;
}
inline int bfs(const vector<string> &field) {
const int h = field.size();
const int w = field[0].size();
vector<vector<unordered_map<int, int>>> dist(h, vector<unordered_map<int ,int>>(w));
queue<tuple<int, int, int>> que;
for(int y = 0; y < h; ++y) {
for(int x = 0; x < w; ++x) {
if(field[y][x] == 'S') {
dist[y][x][0] = 0;
que.push(make_tuple(x, y, 0));
goto end_init;
}
}
}
end_init:;
while(!que.empty()) {
int x, y, v;
tie(x, y, v) = que.front();
que.pop();
const int next_dist = dist[y][x][v] + 1;
for(int d = 0; d < 4; ++d) {
const int nx = x + dx[d];
const int ny = y + dy[d];
if(out(nx, ny, w, h) || field[ny][nx] == '#') continue;
const int nv = move_to(v, d + BASE);
if(nodes[nv].accept) continue;
if(field[ny][nx] == 'G') return next_dist;
if(!dist[ny][nx].count(nv)) {
dist[ny][nx][nv] = next_dist;
que.push(make_tuple(nx, ny, nv));
}
}
}
return -1;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
const string dir = "LDRU";
for(unsigned i = 0; i < dir.size(); ++i) {
convert[dir[i]] = 'a' + i;
}
for(int h, w; cin >> h >> w && h;) {
vector<string> field(h);
for(auto &e : field) cin >> e;
int n;
cin >> n;
vector<string> ng(n);
for(auto &e : ng) cin >> e;
construct(ng);
cout << bfs(field) << endl;
}
return EXIT_SUCCESS;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<b;i++)
#define CMAX 4
#define OFFSET 0
struct Node { int nxt[CMAX + 1]; int exist; vector<int> accept;
Node() : exist(0){ memset(nxt, -1, sizeof(nxt)); }};
struct Trie {
vector<Node> nodes; int root;
Trie() : root(0){ nodes.push_back(Node()); }
void update_direct(int node, int id) { nodes[node].accept.push_back(id); }
void update_child(int node, int child, int id) { ++nodes[node].exist; }
void add(const string &str, int str_index, int node_index, int id)
{
if (str_index == str.size()) update_direct(node_index, id);
else {
const int c = str[str_index] - OFFSET;
if (nodes[node_index].nxt[c] == -1) {
nodes[node_index].nxt[c] = (int)nodes.size();
nodes.push_back(Node());
}
add(str, str_index + 1, nodes[node_index].nxt[c], id);
update_child(node_index, nodes[node_index].nxt[c], id);
}
}
void add(const string &str, int id) { add(str, 0, 0, id); }
void add(const string &str) { add(str, nodes[0].exist); }
int size() { return (nodes[0].exist); }
int nodesize() { return ((int)nodes.size()); }
};
struct AhoCorasick : Trie {
static const int FAIL = CMAX; vector<int> correct;
AhoCorasick() : Trie() {}
void build() {
correct.resize(nodes.size());
rep(i, 0, nodes.size()) correct[i] = (int)nodes[i].accept.size();
queue<int> que;
rep(i, 0, CMAX + 1) {
if (~nodes[0].nxt[i]) {
nodes[nodes[0].nxt[i]].nxt[FAIL] = 0;
que.emplace(nodes[0].nxt[i]);
} else nodes[0].nxt[i] = 0;
}
while (!que.empty()) {
Node &now = nodes[que.front()];
correct[que.front()] += correct[now.nxt[FAIL]];
que.pop();
for (int i = 0; i < CMAX; i++) {
if (now.nxt[i] == -1) continue;
int fail = now.nxt[FAIL];
while (nodes[fail].nxt[i] == -1) {
fail = nodes[fail].nxt[FAIL];
}
nodes[now.nxt[i]].nxt[FAIL] = nodes[fail].nxt[i];
auto &u = nodes[now.nxt[i]].accept;
auto &v = nodes[nodes[fail].nxt[i]].accept;
vector<int> accept;
set_union(begin(u), end(u), begin(v), end(v), back_inserter(accept));
u = accept;
que.emplace(now.nxt[i]);
}
}
}
int match(const string &str, vector< int > &result, int now = 0) {
result.assign(size(), 0);
int count = 0;
for (auto &c : str) {
while (nodes[now].nxt[c - OFFSET] == -1) now = nodes[now].nxt[FAIL];
now = nodes[now].nxt[c - OFFSET];
count += correct[now];
for (auto &v : nodes[now].accept) ++result[v];
}
return count;
}
int next(int now, char c) {
while(nodes[now].nxt[c - OFFSET] == -1) now = nodes[now].nxt[FAIL];
return nodes[now].nxt[c - OFFSET];
}
};
//-----------------------------------------------------------------
int H, W, P;
string MAP[50], BAN[10];
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { -1, 0, 1, 0 };
string dir = "URDL";
#define INF INT_MAX/2
void change(string &s) {
rep(i, 0, s.length()) rep(j, 0, 4) if (s[i] == dir[j]) s[i] = j;
}
bool done[50][50][100];
int dist[50][50][100];
int sol() {
AhoCorasick ac;
rep(i, 0, P) {
change(BAN[i]);
ac.add(BAN[i]);
}
ac.build();
// LD -> 32
// DD -> 22
// LLL -> 333
for (int i : ac.nodes[0].accept) {
cout << i << endl;
}
rep(i, 0, 50) rep(j, 0, 50) rep(k, 0, 100) done[i][j][k] = false;
rep(i, 0, 50) rep(j, 0, 50) rep(k, 0, 100) dist[i][j][k] = INF;
queue<int> q;
int N = ac.nodesize();
rep(y, 0, H) rep(x, 0, W) if (MAP[y][x] == 'S') {
q.push(y * 100 * 100 + x * 100 + 0);
dist[y][x][0] = 0;
done[y][x][0] = true;
}
while (!q.empty()) {
int y = q.front() / 10000;
int x = (q.front() % 10000) / 100;
int s = q.front() % 100;
q.pop();
if (MAP[y][x] == 'G') return dist[y][x][s];
rep(i, 0, 4) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 0 || W <= xx) continue;
if (yy < 0 || H <= yy) continue;
if (MAP[yy][xx] == '#') continue;
int ss = ac.next(s, i);
// ??°????????¢??¶??????????????\
if (ac.correct[ss]) continue;
if (done[yy][xx][ss]) continue;
q.push(yy * 10000 + xx * 100 + ss);
dist[yy][xx][ss] = dist[y][x][s] + 1;
done[yy][xx][ss] = true;
}
}
return -1;
}
//-----------------------------------------------------------------
int main() {
while (cin >> H >> W) {
if (H == 0) return 0;
rep(y, 0, H) cin >> MAP[y];
cin >> P;
rep(i, 0, P) cin >> BAN[i];
cout << sol() << endl;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int var = 4;
const int pmax = 1e4;
int trans(char c) {
switch (c)
{
case 'R': return 0;
case 'D': return 1;
case 'L': return 2;
case 'U': return 3;
default: assert(false);
}
}
struct ac_node {
ac_node *fail;
ac_node *next[var];
int ok;
ac_node() : fail(nullptr), next{}, ok(0) {}
};
ac_node* get_next(ac_node* p, char c) {
while (!p->next[trans(c)]) p = p->fail;
return p->next[trans(c)];
}
class aho_corasick {
ac_node* new_ac_node() {
static ac_node pool[pmax];
static int it = 0;
assert(it < pmax);
return &pool[it++];
}
int K;
ac_node *root;
public:
aho_corasick(const vector<string>& Ts) : K(Ts.size()), root(new_ac_node()) {
ac_node *now;
root->fail = root;
for (int i = 0; i < K; i++) {
auto &T = Ts[i];
now = root;
for (auto c : T) {
if (!now->next[trans(c)]) {
now->next[trans(c)] = new_ac_node();
}
now = now->next[trans(c)];
}
now->ok = 1;
}
queue<ac_node*> q;
for (int i = 0; i < var; i++) {
if (!root->next[i]) {
root->next[i] = root;
}
else {
root->next[i]->fail = root;
q.push(root->next[i]);
}
}
while (!q.empty()) {
now = q.front(); q.pop();
for (int i = 0; i < var; i++) {
if (now->next[i]) {
ac_node *nx = now->fail;
while (!nx->next[i]) {
nx = nx->fail;
}
now->next[i]->fail = nx->next[i];
now->next[i]->ok = max(now->next[i]->ok, nx->next[i]->ok);
q.push(now->next[i]);
}
}
}
}
ac_node* get_root() const {
return root;
}
int get_node_id(ac_node* nd) const {
return (int)(nd - root);
}
};
const int INF = 1e8;
const int dx[] = { 1, 0, -1, 0 };
const int dy[] = { 0, 1, 0, -1 };
string D = "DRUL";
using T = tuple<int, int, ac_node*>;
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int n, m, p;
while (cin >> n >> m, n | m) {
vector<string> S(n);
int sx = 0, sy = 0, gx = 0, gy = 0;
for (int i = 0; i < n; i++) {
cin >> S[i];
for (int j = 0; j < (int)S[i].size(); j++) {
if (S[i][j] == 'S') {
sx = i;
sy = j;
}
else if (S[i][j] == 'G') {
gx = i;
gy = j;
}
}
}
cin >> p;
vector<string> pts(p);
for (int i = 0; i < p; i++) {
cin >> pts[i];
}
aho_corasick aho(pts);
vector<vector<vector<int>>> f(n, vector<vector<int>>(m, vector<int>(110, INF)));
queue<T> q;
q.push(make_tuple(sx, sy, aho.get_root()));
f[sx][sy][aho.get_node_id(aho.get_root())] = 0;
while (!q.empty()) {
auto tup = q.front(); q.pop();
int x = get<0>(tup), y = get<1>(tup);
ac_node *nd = get<2>(tup);
int id = aho.get_node_id(nd);
for (int i = 0; i < 4; i++) {
int tx = x + dx[i], ty = y + dy[i];
ac_node *tnd = get_next(nd, D[i]);
if (0 <= tx && tx < n && 0 <= ty && ty < m && S[tx][ty] != '#' && !tnd->ok && f[tx][ty][aho.get_node_id(tnd)] == INF) {
q.push(make_tuple(tx, ty, tnd));
f[tx][ty][aho.get_node_id(tnd)] = f[x][y][id] + 1;
}
}
}
int res = INF;
for (auto val : f[gx][gy]) {
res = min(res, val);
}
cout << (res != INF ? res : -1) << endl;
}
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <string>
#include <set>
#include <map>
using namespace std;
struct State {
int x, y, e;
};
const int INF = (1<<28);
const int MAXH = 51;
const int MAXW = 51;
const int MAXP = 11;
const string dc[] = {"R","D","L","U"};
const int dx[] = {1,0,-1,0};
const int dy[] = {0,1,0,-1};
int H, W;
char G[MAXH][MAXW];
int P;
vector<string> S;
int E[105][4];
int cost[MAXH][MAXW][105];
int bfs(int sx, int sy, int gx, int gy, int e) {
queue<State> que;
State s = {sx, sy, e};
fill(cost[0][0], cost[MAXH][0], INF);
cost[s.y][s.x][s.e] = 0;
que.push(s);
while(!que.empty()) {
s = que.front();
que.pop();
for(int i = 0; i < 4; ++i) {
int nx = s.x + dx[i];
int ny = s.y + dy[i];
int ne = E[s.e][i];
if(ne == -1) continue;
if(nx < 0 || nx >= W) continue;
if(ny < 0 || ny >= H) continue;
if(G[ny][nx] == '#') continue;
if(cost[ny][nx][ne] != INF) continue;
cost[ny][nx][ne] = cost[s.y][s.x][s.e] + 1;
que.push((State){nx, ny, ne});
if(nx == gx && ny == gy) {
return cost[ny][nx][ne];
}
}
}
return INF;
}
int main() {
while(cin >> H >> W && (H|W)) {
int sx, sy, gx, gy;
for(int i = 0; i < H; ++i) {
for(int j = 0; j < W; ++j) {
cin >> G[i][j];
if(G[i][j] == 'S') {
sx = j;
sy = i;
}
if(G[i][j] == 'G') {
gx = j;
gy = i;
}
}
}
cin >> P;
S.resize(P);
for(int i = 0; i < P; ++i) {
cin >> S[i];
}
vector<string> v;
v.push_back("");
for(int i = 0; i < P; ++i) {
for(int j = 1; j < S[i].size(); ++j) {
string s = S[i].substr(0, j);
bool flag = true;
for(int k = 0; k < S.size(); ++k) {
if(s.find(S[k]) != string::npos) {
flag = false;
break;
}
}
if(flag){
v.push_back(s);
}
}
}
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
fill(E[0], E[105], -1);
for(int i = 0; i < v.size(); ++i) {
for(int j = 0; j < 4; ++j) {
string s = v[i] + dc[j];
bool flag = true;
for(int k = 0; k < S.size(); ++k) {
if(s.find(S[k]) != string::npos) {
flag = false;
break;
}
}
if(!flag) continue;
s = v[i] + dc[j];
while(1) {
int p = lower_bound(v.begin(), v.end(), s) - v.begin();
if(p < v.size() && v[p] == s) {
E[i][j] = p;
break;
}
s = s.substr(1);
}
}
}
int ans = bfs(sx, sy, gx, gy, 0);
if(ans == INF) ans = -1;
cout << ans << endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | java |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class Main{
String INPUT = "./data/judge/201709/A2212.txt";
public static void main(String[] args) throws IOException {
new Main().run();
}
static class Node{
Node[] next = new Node[4];
long pos;
int idx;
Node (long pos) {
this.pos = pos;
}
}
static class Automaton{
static final Node terminal = new Node(0L);
Node root = new Node(0L);
HashMap<Long, Node> map = new HashMap<Long, Node>();
ArrayList<Node> nodes = new ArrayList<Node>();
int[][] pattern;
Automaton(String[] patStr) {
pattern = new int[patStr.length][];
for (int i = 0; i < patStr.length; ++i) {
pattern[i] = new int[patStr[i].length()];
for (int j = 0; j < pattern[i].length; ++j) {
switch (patStr[i].charAt(j)) {
case 'U':
pattern[i][j] = 0;
break;
case 'R':
pattern[i][j] = 1;
break;
case 'D':
pattern[i][j] = 2;
break;
case 'L':
pattern[i][j] = 3;
break;
}
}
}
build(root);
}
void build(Node parent) {
parent.idx = nodes.size();
nodes.add(parent);
map.put(parent.pos, parent);
for (int i = 0; i < 4; ++i) {
long nextPos = 0;
for (int j = 0; j < pattern.length; ++j) {
int curElemPos = (int) ((parent.pos >> (j * 4)) & 0xF);
long nextElemPos;
if (pattern[j][curElemPos] == i) {
nextElemPos = curElemPos + 1;
}
else {
nextElemPos = 0;
for (int k = curElemPos; k >= 0; --k) {
if (pattern[j][k] != i) continue;
boolean ok = true;
for (int l = 1; l <= k; ++l) {
if (pattern[j][curElemPos - l] != pattern[j][k - l]) {
ok = false;
break;
}
}
if (ok) {
nextElemPos = k + 1;
break;
}
}
}
if (nextElemPos == pattern[j].length) {
parent.next[i] = terminal;
break;
}
else {
nextPos += nextElemPos << (j * 4);
}
}
if (parent.next[i] == null) {
Node child = map.get(nextPos);
if (child == null) {
child = new Node(nextPos);
build(child);
}
parent.next[i] = child;
}
}
}
}
class State{
int r, c, i;
State(int r, int c, int i){
this.r = r;
this.c = c;
this.i = i;
}
}
static int[] DR = {-1, 0, 1, 0};
static int[] DC = {0, 1, 0, -1};
int N, M;
char[][] f;
void read() {
while (true) {
N = ni();
if (N == 0) break;
M = ni();
f = new char[N + 2][M + 2];
int startR = 0;
int startC = 0;
Arrays.fill(f[0], '#');
Arrays.fill(f[N + 1], '#');
for (int i = 0; i < N; ++i) {
String row = ns();
f[i + 1][0] = f[i + 1][M + 1] = '#';
for (int j = 0; j < M; ++j) {
char c = row.charAt(j);
if (c == 'S') {
startR = i + 1;
startC = j + 1;
c = '.';
}
f[i + 1][j + 1] = c;
}
}
out.println(solve(startR, startC));
}
}
int solve(int startR, int startC) {
int P = ni();
String[] pat = new String[P];
for (int i = 0; i < P; ++i) {
pat[i] = ns();
}
Automaton automaton = new Automaton(pat);
boolean[][][] visited = new boolean[N + 2][M + 2][automaton.nodes.size()];
State initial = new State(startR, startC, 0);
ArrayList<State> cur = new ArrayList<State>();
cur.add(initial);
visited[startR][startC][0] = true;
int turn = 1;
while (!cur.isEmpty()) {
// System.err.println("turn:" + turn);
ArrayList<State> next = new ArrayList<State>();
for (State st : cur) {
for (int i = 0; i < 4; ++i) {
int nr = st.r + DR[i];
int nc = st.c + DC[i];
if (f[nr][nc] == '#') continue;
Node n = automaton.nodes.get(st.i).next[i];
if (n == Automaton.terminal) continue;
if (visited[nr][nc][n.idx]) continue;
if (f[nr][nc] == 'G') return turn;
visited[nr][nc][n.idx] = true;
next.add(new State(nr, nc, n.idx));
// System.err.println("nr:" + nr + " nc:" + nc + " idx:" + n.idx);
}
}
cur = next;
++turn;
}
return -1;
}
FastScanner in;
PrintWriter out;
void run() throws IOException {
boolean oj;
try {
oj = ! System.getProperty("user.dir").equals("F:\\java_workspace\\leetcode");
} catch (Exception e) {
oj = System.getProperty("ONLINE_JUDGE") != null;
}
InputStream is = oj ? System.in : new FileInputStream(new File(INPUT));
in = new FastScanner(is);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
read();
out.flush();
if (!oj){
System.out.println("[" + (System.currentTimeMillis() - s) + "ms]");
}
}
public boolean more(){
return in.hasNext();
}
public int ni(){
return in.nextInt();
}
public long nl(){
return in.nextLong();
}
public double nd(){
return in.nextDouble();
}
public String ns(){
return in.nextString();
}
public char nc(){
return in.nextChar();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
boolean hasNext;
public FastScanner(InputStream is) throws IOException {
br = new BufferedReader(new InputStreamReader(is));
hasNext = true;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
hasNext = false;
return "##";
}
}
return st.nextToken();
}
String next = null;
public boolean hasNext(){
next = nextToken();
return hasNext;
}
public int nextInt() {
if (next == null){
hasNext();
}
String more = next;
next = null;
return Integer.parseInt(more);
}
public long nextLong() {
if (next == null){
hasNext();
}
String more = next;
next = null;
return Long.parseLong(more);
}
public double nextDouble() {
if (next == null){
hasNext();
}
String more = next;
next = null;
return Double.parseDouble(more);
}
public String nextString(){
if (next == null){
hasNext();
}
String more = next;
next = null;
return more;
}
public char nextChar(){
if (next == null){
hasNext();
}
String more = next;
next = null;
return more.charAt(0);
}
}
static class ArrayUtils {
public static void fill(int[][] f, int value) {
for (int i = 0; i < f.length; ++i) {
Arrays.fill(f[i], value);
}
}
public static void fill(int[][][] f, int value) {
for (int i = 0; i < f.length; ++i) {
fill(f[i], value);
}
}
public static void fill(int[][][][] f, int value) {
for (int i = 0; i < f.length; ++i) {
fill(f[i], value);
}
}
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
int NODE_NUM;
struct Node{
map<char, Node*> next;
Node* fail;
vector<int> match;
int node_id;
Node() : fail(NULL) {
node_id = NODE_NUM++;
}
~Node(){ for(auto p : next) if(p.second) delete p.second; }
};
Node *build(vector<string> pattens){
// 1. trie木 をつくる
Node* root = new Node();
root->fail = root;
for(int i = 0; i < pattens.size(); i++){
Node* p = root;
for(auto c : pattens[i]){
if(p->next[c] == 0) p->next[c] = new Node();
p = p->next[c];
}
p->match.push_back(i);
}
// 2. failure link を作る
queue<Node*> que;
for(int i = 0; i < 128; i++){
if(!root->next[i]){
root->next[i] = root;
}else{
root->next[i]->fail = root;
que.push(root->next[i]);
}
}
while(!que.empty()){
Node* p = que.front(); que.pop();
for(int i = 0; i < 128; i++) if(p->next[i]) {
Node* np = p->next[i];
// add que
que.push(np);
// search failure link
Node* f = p->fail;
while(!f->next[i]) f = f->fail;
np->fail = f->next[i];
// update matching list
np->match.insert(np->match.end(), np->fail->match.begin(), np->fail->match.end());
}
}
return root;
}
Node* next_node(Node* p, char c) {
while(!p->next[c]) p = p->fail;
return p->next[c];
}
// クエリにマッチしたパターンについて
// (last index, pattern id)のリストを返す
typedef pair<int, int> P;
vector<P> match(Node* root, string query){
int n = query.size();
vector<P> res;
Node* p = root;
REP(i, n) {
int c = query[i];
p = next_node(p, c);
for(int k : p->match){
res.push_back(P(i, k));
}
}
return res;
}
struct State{
int x, y;
Node* p;
};
int main(){
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const char dc[4]= {'R', 'D', 'L', 'U'};
int H, W;
while(cin >> H >> W && H > 0) {
vector<string> grid(H);
REP(y, H) cin >> grid[y];
int sx, sy, gx, gy;
REP(y, H) REP(x, W) if(grid[y][x] == 'S') sx = x, sy = y, grid[y][x] = '.';
REP(y, H) REP(x, W) if(grid[y][x] == 'G') gx = x, gy = y, grid[y][x] = '.';
int PN;
cin >> PN;
vector<string> pat(PN);
REP(i, PN) cin >> pat[i];
NODE_NUM = 0;
Node* root = build(pat);
assert(NODE_NUM <= 110);
int dist[50][50][110] = {};
REP(y, H) REP(x, W) REP(i, NODE_NUM) dist[y][x][i] = INT_MAX;
queue<State> que;
que.push({sx, sy, root});
dist[sy][sx][root->node_id] = 0;
while(!que.empty()) {
State s = que.front(); que.pop();
int d = dist[s.y][s.x][s.p->node_id];
REP(r, 4) {
int nx = s.x + dx[r];
int ny = s.y + dy[r];
if(0 <= nx && 0 <= ny && nx < W && ny < H) {
if(grid[ny][nx] == '#') continue;
Node* np = next_node(s.p, dc[r]);
if(np->match.size() > 0) continue;
if(dist[ny][nx][np->node_id] > d + 1) {
dist[ny][nx][np->node_id] = d + 1;
que.push({nx, ny, np});
}
}
}
}
int ans = INT_MAX;
REP(i, NODE_NUM) ans = min(ans, dist[gy][gx][i]);
if(ans == INT_MAX) ans = -1;
cout << ans << endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <string>
#include <vector>
#include <queue>
#include <cassert>
#include <numeric>
#include <iostream>
#include <algorithm>
using namespace std;
class AhoCorasick{
static const int ASIZE = 256;
struct node_t {
int ID;
node_t *failure;
node_t *output;
node_t *next[ASIZE];
std::vector<int> match;
node_t(int id) : ID(id), failure(NULL), output(NULL){
std::fill(next, next + ASIZE, (node_t*)NULL);
}
};
size_t n_size;
size_t length;
node_t *root;
node_t **nodes;
inline node_t *new_node(){
nodes[n_size] = new node_t(n_size);
return nodes[n_size++];
}
public:
AhoCorasick(const std::vector<std::string> &pats) : n_size(0){
length = accumulate(pats.begin(), pats.end(), std::string("")).size();
nodes = new node_t* [length + 1];
root = new_node();
// construct key word tree
for(size_t i = 0; i < pats.size(); i++){
node_t *v = root;
for(size_t j = 0; j < pats[i].size(); j++){
int c = pats[i][j];
if(!v->next[c]) v->next[c] = new_node();
v = v->next[c];
}
v->match.push_back(i);
}
// construct failure link and output link
std::queue<node_t*> que;
root->failure = root;
root->output = root;
que.push(root);
while(!que.empty()){
node_t *p = que.front(); que.pop();
for(int x = 0; x < ASIZE; x++){
if(!p->next[x]) continue;
node_t *v = p->next[x];
node_t *w = p->failure;
if(p == root){
v->failure = root;
v->output = root;
}else{
while(w != root && !w->next[x]) w = w->failure;
v->failure = w->next[x] ? w->next[x] : root;
if(v->failure->match.empty()){
v->output = v->failure->output;
}else{
v->output = v->failure;
}
}
que.push(v);
}
}
}
~AhoCorasick(){
for(size_t i = 0; i < n_size; i++) delete nodes[i];
delete [] nodes;
}
// initial state is always zero.
size_t state_size() const{ return n_size; }
int init_state() const{ return 0; }
int next_state(size_t state, int c) const{
assert(state < n_size);
node_t *v = nodes[state];
while(v != root && !v->next[c]) v = v->failure;
v = v->next[c] ? v->next[c] : root;
return v->ID;
}
std::vector<int> match(size_t state) const{
assert(state < n_size);
std::vector<int> res;
for(node_t *v = nodes[state]; v != root; v = v->output){
for(size_t i = 0; i < v->match.size(); i++){
res.push_back(v->match[i]);
}
}
return res;
}
};
#include <cstring>
#include <tuple>
#include <queue>
using namespace std;
int dist[60][60][110];
int main(){
int N, M, P, sr, sc, gr, gc;
char field[60][60];
int dr[] = {1, 0, -1, 0};
int dc[] = {0, -1, 0, 1};
char dir[] = {'D', 'L', 'U', 'R'};
while(cin >> N >> M && N + M){
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cin >> field[i][j];
if(field[i][j] == 'S'){
sr = i;
sc = j;
}
if(field[i][j] == 'G'){
gr = i;
gc = j;
}
}
}
cin >> P;
vector<string> ps(P);
for(int i = 0; i < P; i++) cin >> ps[i];
AhoCorasick aho(ps);
memset(dist, -1, sizeof(dist));
queue<tuple<int, int, int>> que;
que.push(make_tuple(sr, sc, aho.init_state()));
dist[sr][sc][aho.init_state()] = 0;
bool ok = false;
while(!que.empty()){
int r, c, s;
std::tie(r, c, s) = que.front(); que.pop();
if(r == gr && c == gc){
cout << dist[r][c][s] << endl;
ok = true;
break;
}
for(int i = 0; i < 4; i++){
int nr = r + dr[i];
int nc = c + dc[i];
int ns = aho.next_state(s, dir[i]);
if(!aho.match(ns).empty()) continue;
if(0 <= nr && nr < N && 0 <= nc && nc < M &&
field[nr][nc] != '#' && dist[nr][nc][ns] == -1)
{
dist[nr][nc][ns] = dist[r][c][s] + 1;
que.push(make_tuple(nr, nc, ns));
}
}
}
if(!ok) cout << -1 << endl;
}
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <queue>
#include <map>
#include <fstream>
using namespace std;
class Sit{
public:
int x,y;
int cur;
};
/*
* RXgN^É«¶ñðnµÄtry treeðì¬
* »ÌãÍeíTõÖðÄÑoµÄAØÉεÄTõð©¯é±ÆªÅ«é
*/
class AhoCorasick{
private:
static const int MAX_V=10001;
private:
map<string,int> _dict;
string idToStr[MAX_V];
int _vertex;
// »Ý̶ñ©çÍÇ̶ñÖJÚÅ«é©
map<int,set<int> > _stepPrv;
// Tõ¸sµ½êÉßém[h
map<int,int> _stepBack;
// «¶ñÌW
set<int> _dictStr;
// _ÉîñðtÁµ½¢ÌÝgp
//T _vertexInfos[MAX_V];
public:
//AhoCorasick();
AhoCorasick(const vector<string> inStrings):_vertex(1){
for(int i=0;i<inStrings.size();i++){
if(_dict.find(inStrings[i])==_dict.end()){
idToStr[_vertex]=inStrings[i];
_dict[inStrings[i]]=_vertex++;
_dictStr.insert(_vertex-1);
}
}
makeTree(inStrings);
}
int getStrId(string s){
if(_dict.find(s)==_dict.end())return -1;
return _dict[s];
}
int getVetex(){
return _vertex;
}
// »Ý̶ñðO©ç^¦AP¶¸ÂTõ
bool isMatchOneByOne(char ch,int &cur){
// KvÅ êÎA±±ÅcurªdictàɶݵȢ©`FbN
/*
*/
while(1){
int nxt=cur;
string nstr=idToStr[nxt];
nstr+=ch;
nxt=_dict[nstr];
// ൡÌê©çÌêÖJÚÂ\ÈçÎ
if(_stepPrv.find(cur)!=_stepPrv.end()&&_stepPrv[cur].find(nxt)!=_stepPrv[cur].end()){
// ¡ñÌê©çßêéêÅA}b`·éà̪ é©ð`FbN
int tmpStr=nxt;
while(tmpStr!=0){
if(_dictStr.find(tmpStr)!=_dictStr.end())return true;
tmpStr=_stepBack[tmpStr];
}
cur=nxt;
break;
}
// »¤ÅȯêÎAßÁÄÌ[vÅÄÑTõðs¤
else{
// rootũ©çȯêÎAI¹
if(cur==0)return false;
// »ÝTõ̶ñÍm[hɶݵȢ
else if(_stepBack.find(cur)==_stepBack.end())cur=0;
else{
// rootÅÈ¢êÍAßÁÄ¡ñ̶ðà¤êx©é
cur=_stepBack[cur];
}
}
}
// ൫à̶ñª©Â©êÎtrue
if(_dictStr.find(cur)!=_dictStr.end())return true;
return false;
}
// ÈÆàêÓ}b`µ½çtrue
bool isMatchLeastOne(const string &s){
int cur=0;
for(int i=0;i<(int)s.size();i++){
string cstr=idToStr[cur];
string nstr=cstr+s[i];
//
int nxt=_dict[nstr];
// ൡÌê©çÌêÖJÚÂ\ÈçÎ
if(_stepPrv.find(cur)!=_stepPrv.end()&&_stepPrv[cur].find(nxt)!=_stepPrv[cur].end()){
cur=nxt;
int tmpStr=nxt;
// ßÁÄTõ
while(tmpStr!=0){
if(_dictStr.find(tmpStr)!=_dictStr.end())return true;
tmpStr=_stepBack[tmpStr];
}
}
// »¤ÅȯêÎAßÁÄÌ[vÅÄÑTõðs¤
else{
// rootũ©çȯêÎA¡ñ̶Íòη
if(cur==0)continue;
else if(_stepBack.find(cur)==_stepBack.end())cur=0;
else{
// rootÅÈ¢êÍAßÁÄ¡ñ̶ðà¤êx©é
i--;
cur=_stepBack[cur];
}
}
// ൫à̶ñª©Â©êÎtrue
if(_dictStr.find(cur)!=_dictStr.end())return true;
}
return false;
}
private:
// Rs[RXgN^ÆAãüZqÍgpÖ~É·é
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ܽÍó¶ñª[gm[h
_dict[""]=0;
idToStr[0]="";
for(int i=0;i<(int)inStrings.size();i++){
for(int j=0;j<(int)inStrings[i].size();j++){
string s=inStrings[i].substr(0,j+1);
// ܾÇÁ³êĢȢÌÅ êÎAÇÁ·é
if(_dict.find(s)==_dict.end()){
idToStr[_vertex]=s;
_dict[s]=_vertex++;
}
}
}
// TõðOÉißéûüÖGbWðÔ
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¶Å\¬³êéÈçÎAGbWðø
if(it->first.size()==iit->first.size()-1
&&it->first==iit->first.substr(0,it->first.size())){
_stepPrv[it->second].insert(iit->second);
}
}
}
// TõðãëÖißéûüÖGbWðÔ
for(map<string,int>::iterator it=_dict.begin();it!=_dict.end();it++){
if(it->first=="")continue;
// »Ý̶ñ©çæªi¶ðæè¢½àÌÖßêé©ÔÉ`FbN
// ßêȯêÎ[gÖßé
bool ok=false;
for(int i=0;i<(int)it->first.size()-1;i++){
string s=it->first.substr(i+1);
if(_dict.find(s)!=_dict.end()){
_stepBack[it->second]=_dict[s];
ok=true;
break;
}
}
// [gÖßé
if(!ok)_stepBack[it->second]=0;
}
}
};
int h,w;
int n;
char field[51][51];
string prohibits[20];
int sy,sx,gx,gy;
set<int> used[51][51];
const int dy[]={-1,0,1,0};
const int dx[]={0,1,0,-1};
int bfs(){
vector<string> vs;
for(int i=0;i<n;i++)vs.push_back(prohibits[i]);
AhoCorasick ac(vs);
Sit init;
init.x=sx;
init.y=sy;
init.cur=0;
queue<Sit> q[2];
int cur=0;
int nxt=1;
q[cur].push(init);
used[init.y][init.x].insert(0);
int cnt=0;
while(q[cur].size()){
while(q[cur].size()){
Sit s=q[cur].front();
q[cur].pop();
if(s.y==gy&&s.x==gx)return cnt;
for(int i=0;i<4;i++){
int ny=s.y+dy[i];
int nx=s.x+dx[i];
if(ny>=0&&nx>=0&&ny<h&&nx<w&&field[ny][nx]=='.'){
char ch=i+'0';
Sit nsit;
nsit.y=ny;nsit.x=nx;
nsit.cur=s.cur;
bool b=ac.isMatchOneByOne(ch,nsit.cur);
// matchµ½çAJڵȢ
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;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <complex>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <cassert>
typedef long long ll;
using namespace std;
#define debug(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl;
#define mod 1000000007 //1e9+7(prime number)
#define INF 1000000000 //1e9
#define LLINF 2000000000000000000LL //2e18
#define SIZE 100010
/* Aho Corasick */
int ACNodeId = 0;
struct ACNode{
int val, id;
ACNode *next[26], *failure;
ACNode():val(0) {
memset(next,0,sizeof(next));
id = ACNodeId++;
}
void insert(char *s){
if(!*s){ val++; return; }
int al = *s-'A';
if(next[al]==NULL) next[al] = new ACNode;
next[al]->insert(s+1);
}
ACNode *nextNode(char c){
int al = c - 'A';
if (next[al]) return next[al];
return failure == this ? this : failure->nextNode(c);
}
};
struct AhoCorasick{
ACNode *node;
AhoCorasick(){node = new ACNode;}
void insert(char *s) {
node->insert(s);
}
void build() {
queue<ACNode*> que;
que.push(node);
node->failure = node;
while(que.size()){
ACNode *p = que.front();
que.pop();
for(int i=0;i<26;i++){
if(p->next[i]){
ACNode *failure = p->failure;
while(!failure->next[i] && failure != node){
failure = failure->failure;
}
if (failure->next[i] && failure != p){
p->next[i]->failure = failure->next[i];
p->next[i]->val += failure->next[i]->val;
}else{
p->next[i]->failure = node;
}
que.push(p->next[i]);
}
}
}
}
};
int dx[8] = {0,0,1,-1,1,1,-1,-1};
int dy[8] = {1,-1,0,0,1,-1,1,-1};
char ds[] = "DURL";
bool solve(){
int h, w;
char s[51][51];
int sx, sy, gx, gy;
scanf("%d%d", &h, &w);
if(h == 0) return false;
for(int i=0;i<h;i++){
scanf("%s", s[i]);
for(int j=0;j<w;j++){
if(s[i][j] == 'S'){
sx = j; sy = i;
}
if(s[i][j] == 'G'){
gx = j; gy = i;
}
}
}
int q;
AhoCorasick ac;
scanf("%d", &q);
for(int i=0;i<q;i++){
char pattern[11];
scanf("%s", pattern);
ac.insert(pattern);
}
ac.build();
bool visited[51][51][200] = {};
queue<pair<pair<int,int>,ACNode*> > que;
que.push({{sy, sx}, ac.node});
for(int i=0;que.size();i++){
queue<pair<pair<int,int>,ACNode*> > que2;
while(que.size()){
auto p = que.front(); que.pop();
int y = p.first.first;
int x = p.first.second;
ACNode* cur = p.second;
if(cur->val) continue;
if(y < 0 || h <= y || x < 0 || w <= x) continue;
if(s[y][x] == '#') continue;
if(visited[y][x][cur->id]) continue;
visited[y][x][cur->id] = true;
if(gy == y && gx == x){
printf("%d\n", i);
return true;
}
for(int j=0;j<4;j++){
auto next = cur->nextNode(ds[j]);
que2.push({{dy[j] + y, dx[j] + x}, next});
}
}
que = que2;
}
puts("-1");
return true;
}
int main(){
while(solve());
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <complex>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <functional>
#include <iostream>
#include <map>
#include <set>
#include <cassert>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-9
#define INF 2000000000
#define sz(x) ((int)(x).size())
#define fi first
#define sec second
#define SORT(x) sort((x).begin(),(x).end())
#define all(x) (x).begin(),(x).end()
#define rep(i,n) for(int (i)=0;(i)<(int)(n);(i)++)
#define repn(i,a,n) for(int (i)=(a);(i)<(int)(n);(i)++)
#define EQ(a,b) (abs((a)-(b))<eps)
// Aho-Corasick
#define SIZE 256
struct Trie{
Trie* child[SIZE];
Trie* fail;
vector<int> matched;
Trie(){
for(int i=0;i<SIZE;i++)child[i]=NULL;
fail = NULL;
}
~Trie(){}
};
Trie pool[5000];
int pool_pos;
inline Trie* alloc(){return &(pool[pool_pos++]=Trie());}
inline void destruct(){pool_pos=0;}
vector<int> unite(const vector<int> &a,const vector<int> &b){
vector<int> ret;
set_union(all(a),all(b),back_inserter(ret));
return ret;
}
Trie* build(vector<string> pattern){
Trie *root = alloc();
Trie *now;
root->fail = root;
for(int i=0;i<pattern.size();i++){
now = root;
for(int j=0;j<pattern[i].size();j++){
int idx = (int)pattern[i][j];
if(now->child[idx]==NULL){
now->child[idx]=alloc();
}
now = now->child[idx];
}
now->matched.pb(i);
}
queue<Trie*> q;
for(int i=0;i<SIZE;i++){
if((root->child[i])==NULL)root->child[i]=root;
else{
root->child[i]->fail=root;
q.push(root->child[i]);
}
}
while(!q.empty()){
now = q.front();q.pop();
for(int i=0;i<SIZE;i++){
if(now->child[i]){
Trie *next = now->fail;
while((next->child[i])==NULL)next=next->fail;
now->child[i]->fail = next->child[i];
now->child[i]->matched = unite(now->child[i]->matched,next->child[i]->matched);
q.push(now->child[i]);
}
}
}
return root;
}
// now???????????????????????????????????¨??§?¶?????????????????´¢??????
// ret???pattern???????´???°??§????????????????????¨???
// now????????§??????????????§????????????????????????????????¨???
void match(Trie* &now,const string s,vector<int> &ret){
for(int i=0;i<s.size();i++){
int idx = s[i];
while((now->child[idx])==NULL)now=now->fail;
now=now->child[idx];
for(int j=0;j<(now->matched.size());j++){
ret[now->matched[j]]=1;
}
}
}
struct state{
P pos;
Trie* trie;
int turn;
state(P pos,Trie* trie,int turn):pos(pos),trie(trie),turn(turn){}
};
int dx[4]={0,-1,0,1};
int dy[4]={1,0,-1,0};
string dv[4]={"D","L","U","R"};
string f[55];
int main(){
while(1){
int n,m,p;
P S,G;
set<Trie*> s[55][55];
scanf("%d %d",&n,&m);
if(n==0&&m==0)break;
for(int i=0;i<n;i++)cin >> f[i];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(f[i][j]=='S'){S=P(j,i);}
if(f[i][j]=='G'){G=P(j,i);}
}
}
scanf("%d",&p);
vector<string> pat(p);
for(int i=0;i<p;i++)cin >> pat[i];
destruct();
Trie* root = build(pat);
/*while(1){
string s;
cin >> s;
vector<int> v(p,0);
Trie* r = root;
match(r,s,v);
int flag = 0;
for(int i=0;i<p;i++)flag|=v[i];
if(flag)printf("exist\n");
else printf("not exist\n");
}*/
queue<state> q;
q.push(state(S,root,0));
int ans = -1;
while(!q.empty()){
state now = q.front(); q.pop();
if(now.pos == G){ans = now.turn;break;}
int x = now.pos.fi , y = now.pos.sec;
for(int i=0;i<4;i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx<0||nx>=m||ny<0||ny>=n)continue;
if(f[ny][nx]=='#')continue;
vector<int> v(p,0);
Trie* t = now.trie;
match(t,dv[i],v);
int flag = 0;
for(int j=0;j<p;j++)flag|=v[j];
if(flag)continue;
if(s[nx][ny].find(t)==s[nx][ny].end()){
s[nx][ny].insert(t);
q.push(state(P(nx,ny),t,now.turn+1));
}
}
}
printf("%d\n",ans);
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | // 12:17 - 13:14
#include<iostream>
#include<cmath>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<cassert>
#include<climits>
#include<map>
#include<queue>
#include<set>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define IINF (INT_MAX)
#define MAX_SP 15
#define MAX_LEN 60
using namespace std;
typedef pair<int,int> ii;
struct Data{
int cur,cost;
ii info;
string debug;
Data(int cur=IINF,int cost=IINF,ii info=ii(IINF,IINF),string debug="$$$"):cur(cur),cost(cost),info(info),debug(debug){}
bool operator < (const Data& a)const{
return cost > a.cost;
}
};
int h,w,sp,gp,P;
char G[MAX_LEN][MAX_LEN];
/*
next_state[index][the number of match]
0 -> empty
1 -> spell[0]
2 -> spell[1]
...
*/
ii next_state[MAX_SP][MAX_SP][4];
int mincost[MAX_LEN*MAX_LEN][MAX_SP][MAX_SP];
string spell[MAX_SP];
int dx[] = {+0,+1,+0,-1};
int dy[] = {-1,+0,+1,+0};
char dc[] = {'U','R','D','L'};
ii getValue(string s){
rep(i,P+1){
int cur = 0;
rep(j,spell[i].size()){
if(s[cur] != spell[i][j]){
break;
}
cur++;
if(cur >= s.size()){
return ii(i,j+1);
}
}
}
return ii(0,0);
}
void INIT(){
rep(i,MAX_SP)rep(j,MAX_SP)rep(k,4)next_state[i][j][k] = ii(0,0);
rep(i,P+1){
rep(j,spell[i].size()+1){
rep(dir,4){
rep(k,j+1){
ii value = getValue(spell[i].substr(0,j).substr(k)+dc[dir]);
if(value != ii(0,0) && next_state[i][j][dir].second < value.second){
next_state[i][j][dir] = value;
}
}
}
}
}
}
inline bool isValid(int x,int y){
return ( 0 <= x && x < w && 0 <= y && y < h );
}
void compute(){
priority_queue<Data> Q;
Q.push(Data(sp,0,ii(0,0)));
rep(i,h*w)rep(j,MAX_SP)rep(k,MAX_SP)mincost[i][j][k] = IINF;
mincost[sp][0][0] = 0;
while(!Q.empty()){
Data data = Q.top(); Q.pop();
//cout << "(" << data.cur % w << "," << (int)(data.cur / w) << ") " << data.cost << " info(" << data.info.first << "," << data.info.second << ")" << endl;
if(data.cur == gp){
//cout << "path : " << data.debug << endl;
cout << data.cost << endl;
return;
}
rep(dir,4){
int nx = data.cur % w + dx[dir];
int ny = data.cur / w + dy[dir];
if(!isValid(nx,ny))continue;
if(G[ny][nx] == '#')continue;
ii next = next_state[data.info.first][data.info.second][dir];
if(next.first != 0 && spell[next.first].size() == next.second)continue;
if(mincost[nx+ny*w][next.first][next.second] > data.cost + 1){
mincost[nx+ny*w][next.first][next.second] = data.cost + 1;
Q.push(Data(nx+ny*w,data.cost+1,next,data.debug+dc[dir]));
}
}
}
cout << -1 << endl;
}
bool cmp(const string& a,const string& b){
return a.size() < b.size();
}
int main(){
while(cin >> h >> w,h|w){
rep(i,h){
rep(j,w){
cin >> G[i][j];
if(G[i][j] == 'S'){
sp = j + i * w;
}
else if(G[i][j] == 'G'){
gp = j + i * w;
}
}
}
cin >> P;
spell[0].clear();
vector<string> tmp;
rep(i,P){
cin >> spell[i+1];
tmp.push_back(spell[i+1]);
}
sort(tmp.begin(),tmp.end(),cmp);
bool out[tmp.size()];
rep(i,tmp.size())out[i] = false;
rep(i,tmp.size()){
REP(j,i+1,tmp.size()){
bool check = true;
if(tmp[j].find(tmp[i]) == string::npos){
check = false;
}
if(check){
out[j] = true;
}
}
}
vector<string> tmp2;
rep(i,tmp.size())if(!out[i]){
tmp2.push_back(tmp[i]);
}
P = tmp2.size();
rep(i,P){
spell[i+1] = tmp2[i];
}
INIT();
/*
rep(i,P+1){
cout << "spell[" << i<< "] = " << spell[i] << endl;
rep(j,spell[i].size()+1){
rep(dir,4){
cout << "next_state[" << i << "][" << j << "][" << dir << "] => " << " | " << spell[i].substr(0,j) << " + " << dc[dir]<< " | " <<" next = (" << next_state[i][j][dir].first << "," << next_state[i][j][dir].second << ")" << endl;
}
}
}
*/
compute();
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
struct FastIO{
FastIO(){
cin.tie(0);
ios::sync_with_stdio(0);
}
}fastio_beet;
template<size_t X>
struct Trie{
struct Node{
char c;
array<int, X> nxt;
vector<int> idxs;
int idx;
Node(char c):c(c),idx(-1){fill(nxt.begin(),nxt.end(),-1);}
};
using F = function<int(char)>;
vector<Node> vs;
F conv;
Trie(F conv,char c='$'):conv(conv){vs.emplace_back(c);}
void add(const string &s,int x){
int pos=0;
for(int i=0;i<(int)s.size();i++){
int k=conv(s[i]);
if(~vs[pos].nxt[k]){
pos=vs[pos].nxt[k];
continue;
}
int npos=vs.size();
vs[pos].nxt[k]=npos;
vs.emplace_back(s[i]);
pos=npos;
}
vs[pos].idx=x;
vs[pos].idxs.emplace_back(x);
}
int find(const string &s){
int pos=0;
for(int i=0;i<(int)s.size();i++){
int k=conv(s[i]);
if(vs[pos].nxt[k]<0) return -1;
pos=vs[pos].nxt[k];
}
return pos;
}
int find(int pos,char c){
return vs[pos].nxt[conv(c)];
}
int idx(int pos){
return pos<0?-1:vs[pos].idx;
}
vector<int> idxs(int pos){
return pos<0?vector<int>():vs[pos].idxs;
}
};
template<size_t X>
struct AhoCorasick : Trie<X+1>{
using TRIE = Trie<X+1>;
using TRIE::TRIE;
vector<int> cnt;
void build(bool heavy=true){
auto &vs=TRIE::vs;
int n=vs.size();
cnt.resize(n);
for(int i=0;i<n;i++){
if(heavy) sort(vs[i].idxs.begin(),vs[i].idxs.end());
cnt[i]=vs[i].idxs.size();
}
queue<int> que;
for(int i=0;i<(int)X;i++){
if(~vs[0].nxt[i]){
vs[vs[0].nxt[i]].nxt[X]=0;
que.emplace(vs[0].nxt[i]);
}else{
vs[0].nxt[i]=0;
}
}
while(!que.empty()){
auto &x=vs[que.front()];
cnt[que.front()]+=cnt[x.nxt[X]];
que.pop();
for(int i=0;i<(int)X;i++){
if(x.nxt[i]<0){
x.nxt[i]=vs[x.nxt[X]].nxt[i];
continue;
}
int fail=x.nxt[X];
vs[x.nxt[i]].nxt[X]=vs[fail].nxt[i];
if(heavy){
auto &idx=vs[x.nxt[i]].idxs;
auto &idy=vs[vs[fail].nxt[i]].idxs;
vector<int> idz;
set_union(idx.begin(),idx.end(),
idy.begin(),idy.end(),
back_inserter(idz));
idx=idz;
}
que.emplace(x.nxt[i]);
}
}
}
vector<int> match(string s,int heavy=true){
auto &vs=TRIE::vs;
vector<int> res(heavy?TRIE::size():1);
int pos=0;
for(auto &c:s){
pos=vs[pos].nxt[TRIE::conv(c)];
if(heavy) for(auto &x:vs[pos].idxs) res[x]++;
else res[0]+=cnt[pos];
}
return res;
}
int move(int pos,char c){
auto &vs=TRIE::vs;
assert(pos<(int)vs.size());
return vs[pos].nxt[TRIE::conv(c)];
}
int count(int pos){
return cnt[pos];
}
int size(){return TRIE::vs.size();}
};
//INSERT ABOVE HERE
int dp[111][55][55];
signed main(){
int h,w;
while(cin>>h>>w,h){
vector<string> ss(h);
for(int i=0;i<h;i++) cin>>ss[i];
int p;
cin>>p;
vector<string> ps(p);
for(int i=0;i<p;i++) cin>>ps[i];
auto conv=
[&](char c){
if(c=='U') return 0;
if(c=='R') return 1;
if(c=='D') return 2;
if(c=='L') return 3;
return -1;
};
AhoCorasick<4> aho(conv);
for(int i=0;i<p;i++) aho.add(ps[i],i);
aho.build(false);
memset(dp,-1,sizeof(dp));
using T = tuple<int, int, int>;
queue<T> que;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
if(ss[i][j]=='S'){
dp[0][i][j]=0;
que.emplace(0,i,j);
}
}
}
string base="URDL";
int dy[]={-1,0,1,0};
int dx[]={0,1,0,-1};
auto in=[&](int y,int x){return 0<=y&&y<h&&0<=x&&x<w;};
int ans=-1;
while(!que.empty()){
int p,y,x;
tie(p,y,x)=que.front();que.pop();
if(ss[y][x]=='G'){
ans=dp[p][y][x];
break;
}
for(int k=0;k<4;k++){
int ny=y+dy[k],nx=x+dx[k];
if(!in(ny,nx)||ss[ny][nx]=='#') continue;
char c=base[k];
int q=aho.move(p,c);
if(aho.count(q)) continue;
if(~dp[q][ny][nx]) continue;
dp[q][ny][nx]=dp[p][y][x]+1;
que.emplace(q,ny,nx);
}
}
cout<<ans<<endl;
}
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | CORRECT | cpp | #include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;++i)
using namespace std;
int n,m;
string maze[55];
int fg[110][5],ac[110];
char dir[5]={' ','U','R','D','L'};
int di[5]={0,-1,0,1,0};
int dj[5]={0,0,1,0,-1};
int build(vector<string> pattern){
memset(fg,-1,sizeof(fg));
memset(ac,0,sizeof(ac));
int root=0,size=1;
fg[root][0]=root;
rep(i,pattern.size()){
int cur=root;
rep(j,pattern[i].size()){
int tar=1;
rep(k,5) if(dir[k]==pattern[i][j]) tar=k;
if(fg[cur][tar]==-1) fg[cur][tar]=size++;
cur=fg[cur][tar];
}
ac[cur]++;
}
queue<int> q;
for(int i=1;i<=4;++i){
if(fg[root][i]>=0){
fg[fg[root][i]][0]=root;
q.push(fg[root][i]);
}else
fg[root][i]=root;
}
while(!q.empty()){
int now=q.front();q.pop();
for(int i=1;i<=4;++i){
if(fg[now][i]>=0){
int tar=fg[now][0];
while(fg[tar][i]==-1) tar=fg[tar][0];
fg[fg[now][i]][0]=fg[tar][i];
ac[fg[now][i]]+=ac[fg[tar][i]];
q.push(fg[now][i]);
}
}
}
return size;
}
typedef tuple<int,int,int> state;
int dist[55][55][110];
int bfs(int limit){
memset(dist,-1,sizeof(dist));
int si,sj,gi,gj;
rep(i,n)rep(j,m){
if(maze[i][j]=='S') si=i,sj=j;
if(maze[i][j]=='G') gi=i,gj=j;
}
const int root=0;
dist[si][sj][root]=0;
queue<state> q;
q.push(state(si,sj,root));
while(!q.empty()){
int ci,cj,cs;
tie(ci,cj,cs)=q.front();q.pop();
for(int i=1;i<=4;++i){
int ni=ci,nj=cj,ns=cs;
ni+=di[i],nj+=dj[i];
while(fg[ns][i]==-1) ns=fg[ns][0];
ns=fg[ns][i];
if(ni<0||n<=ni||nj<0||m<=nj) continue;
if(maze[ni][nj]=='#') continue;
if(ac[ns]>=1) continue;
if(dist[ni][nj][ns]==-1){
dist[ni][nj][ns]=dist[ci][cj][cs]+1;
q.push(make_tuple(ni,nj,ns));
}
}
}
int ans=-1;
rep(gs,limit){
if(dist[gi][gj][gs]>=0){
if(ans==-1) ans=dist[gi][gj][gs];
ans=min(ans,dist[gi][gj][gs]);
}
}
return ans;
}
int main(void){
while(cin >> n >> m){
if(n==0) break;
rep(i,n) cin >> maze[i];
int p;
cin >> p;
vector<string> pattern;
rep(i,p){
string in;
cin >> in;
pattern.push_back(in);
}
cout << bfs(build(pattern)) << endl;
}
return 0;
} |
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
class state {
public:
int x, y;
vector<int> ma;
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};
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();
for (int i = (0); i < (int)(n); i++) {
cin >> field[i];
for (int j = (0); j < (int)(m); j++)
if (field[i][j] == 'S') {
sx = j;
sy = i;
}
}
cin >> p;
for (int i = (0); i < (int)(p); i++) {
string tmp;
cin >> tmp;
ope.push_back(tmp);
}
vector<string> tmp;
for (int i = (0); i < (int)(ope.size()); i++) {
int j;
for (j = 0; j < ope.size(); j++)
if (i != j) {
if (ope[i].find(ope[j]) != string::npos) break;
}
if (j == ope.size()) tmp.push_back(ope[i]);
}
ope.swap(tmp);
queue<state> q;
bool goal = false;
long long ans = -1;
q.push(state(sx, sy, vector<int>(ope.size(), 0)));
msi[state(sx, sy, vector<int>(ope.size(), 0))] = 0;
while (!q.empty()) {
int x = q.front().x;
int y = q.front().y;
vector<int> ma = q.front().ma;
long long cost = msi[q.front()];
q.pop();
for (int k = (0); k < (int)(4); k++) {
vector<int> hoge(ope.size(), 0);
int tx = x + dx[k];
int ty = y + dy[k];
if (!inside(tx, ty)) continue;
bool ok = true;
for (int j = (0); j < (int)(ma.size()); j++) {
if (DIR(ope[j][ma[j] + 1 - 1]) == k) {
hoge[j] = ma[j] + 1;
if (hoge[j] == ope[j].length()) {
ok = false;
break;
}
} else {
string aaa = ope[j].substr(0, ma[j]) + string(1, k == 0 ? 'U'
: k == 1 ? 'R'
: k == 2 ? 'D'
: 'L');
int l;
for (l = 0; l < aaa.size(); l++) {
int u;
for (u = 0; u + l < aaa.size(); u++) {
if (aaa[l + u] != ope[j][u]) break;
}
if (u + l == aaa.size()) {
break;
}
}
hoge[j] = aaa.size() - l;
}
}
if (!ok) continue;
if (field[ty][tx] == 'G') {
ans = cost + 1;
goal = true;
}
state ts(tx, ty, hoge);
map<state, long long>::iterator it = msi.lower_bound(ts);
if (it != msi.end() && it->first == ts) {
if (it->second > cost + 1) {
it->second = cost + 1;
q.push(ts);
}
} else {
msi.insert(it, make_pair(ts, cost + 1));
q.push(ts);
}
}
if (goal) break;
}
printf("%lld\n", ans);
}
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
int tx[] = {0, 1, 0, -1};
int ty[] = {-1, 0, 1, 0};
static const double EPS = 1e-8;
class Nodes {
public:
class Nodes* children[256];
bool has_word;
Nodes() : has_word(false) {
for (int i = 0; i < 256; i++) {
children[i] = NULL;
}
}
};
class Trie {
private:
Nodes* root;
public:
Trie() { root = new Nodes(); }
void insert(const string& str) {
Nodes* current = root;
for (int i = 0; i < str.size(); i++) {
char c = str[i];
if (current->children[c] == NULL) {
current->children[c] = new Nodes();
}
current = current->children[c];
}
current->has_word = true;
}
bool common_prefix_search(const string& str) {
Nodes* current = root;
for (int i = 0; i < str.size(); i++) {
char c = str[i];
if (current->children[c] != NULL) {
current = current->children[c];
} else {
return false;
}
if (current->has_word) return true;
}
return false;
}
};
const static char dir[4] = {'U', 'R', 'D', 'L'};
const static string dir_str[4] = {"U", "R", "D", "L"};
class State {
public:
int cost;
int h;
string route;
int x;
int y;
State(int _x, int _y, int _c, string _r, int _h)
: cost(_c), route(_r), x(_x), y(_y), h(_h) {}
bool operator<(const State& s) const { return cost + h < s.cost + s.h; }
bool operator>(const State& s) const { return cost + h > s.cost + s.h; }
};
int main() {
int H, W;
while (~scanf("%d %d", &H, &W)) {
if (H == 0 && W == 0) break;
char stage[50][50];
map<pair<string, int>, int> dp;
int sx = 0;
int sy = 0;
int gx = 0;
int gy = 0;
for (int y = 0; y < H; y++) {
char line[51];
scanf("%s", line);
for (int x = 0; x < W; x++) {
stage[y][x] = line[x];
if (line[x] == 'S') {
sx = x;
sy = y;
} else if (line[x] == 'G') {
gx = x;
gy = y;
}
}
}
int total_prohibited_sequences;
scanf("%d", &total_prohibited_sequences);
Trie trie;
for (int sequence_idx = 0; sequence_idx < total_prohibited_sequences;
sequence_idx++) {
string str;
cin >> str;
reverse(str.begin(), str.end());
trie.insert(str);
}
priority_queue<State, vector<State>, greater<State> > que;
que.push(State(sx, sy, 0, "", 0));
int res = 0x3f3f3f3f;
while (!que.empty()) {
State s = que.top();
string route = s.route;
int cost = s.cost;
int sx = s.x;
int sy = s.y;
que.pop();
for (int i = 0; i < 4; i++) {
int dx = sx + tx[i];
int dy = sy + ty[i];
if (dx < 0 || dx >= W || dy < 0 || dy >= H) continue;
if (stage[dy][dx] == '#') continue;
string next = dir_str[i] + route;
if (trie.common_prefix_search(next)) {
continue;
}
if (stage[dy][dx] == 'G') {
res = cost + 1;
goto found;
}
string key = next.substr(0, next.size() >= 5 ? 5 : next.size());
if (dp.find(pair<string, int>(key, dy * 50 + dx)) != dp.end()) continue;
dp[pair<string, int>(key, dy * 50 + dx)] = cost + 1;
State s_next(dx, dy, cost + 1, next, abs(gy - dy) + abs(gx - dx));
que.push(s_next);
}
}
found:;
printf("%d\n", res == 0x3f3f3f3f ? -1 : res);
}
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
int tx[] = {0, 1, 0, -1};
int ty[] = {-1, 0, 1, 0};
static const double EPS = 1e-8;
const static char dir[4] = {'U', 'R', 'D', 'L'};
const static string dir_str[4] = {"U", "R", "D", "L"};
namespace AhoCorasick {
class Node;
class SearchMachine;
}; // namespace AhoCorasick
class AhoCorasick::Node {
private:
set<string> results;
map<char, AhoCorasick::Node*> transitions;
vector<AhoCorasick::Node*> v_transitions;
char character;
AhoCorasick::Node* parent;
AhoCorasick::Node* failure;
public:
Node() : character('\0'), parent(NULL), failure(NULL) {}
Node(AhoCorasick::Node* _p, char _c)
: parent(_p), character(_c), failure(NULL) {}
const char get_char() const { return character; }
AhoCorasick::Node* get_parent() const { return parent; }
AhoCorasick::Node* get_failure() const { return failure; }
void set_failure(AhoCorasick::Node* _n) { failure = _n; }
AhoCorasick::Node* get_transition(char c) {
if (transitions.find(c) == transitions.end()) return NULL;
return transitions[c];
}
const set<string>& get_results() const { return results; }
void add_result(const string& str) { results.insert(str); }
void add_transition(AhoCorasick::Node* node) {
transitions[node->get_char()] = node;
v_transitions.push_back(node);
}
const vector<AhoCorasick::Node*>& get_transitions() const {
return v_transitions;
}
};
class AhoCorasick::SearchMachine {
private:
set<string> keywords;
AhoCorasick::Node* root;
AhoCorasick::Node* state;
public:
SearchMachine(set<string> _k) : keywords(_k) { _build_tree(); }
SearchMachine() { _build_tree(); }
void _build_tree() {
root = new AhoCorasick::Node();
for (set<string>::iterator it = keywords.begin(); it != keywords.end();
it++) {
AhoCorasick::Node* node = root;
const string& keyword = *it;
for (int i = 0; i < keyword.length(); i++) {
AhoCorasick::Node* next_node = node->get_transition(keyword[i]);
if (next_node == NULL) {
next_node = new AhoCorasick::Node(node, keyword[i]);
node->add_transition(next_node);
}
node = next_node;
}
node->add_result(keyword);
}
vector<AhoCorasick::Node*> nodes;
for (int i = 0; i < root->get_transitions().size(); i++) {
root->get_transitions()[i]->set_failure(root);
nodes.push_back(root->get_transitions()[i]);
}
while (nodes.size() > 0) {
vector<AhoCorasick::Node*> next_nodes;
for (int i = 0; i < nodes.size(); i++) {
AhoCorasick::Node* r = nodes[i]->get_parent()->get_failure();
char c = nodes[i]->get_char();
while ((r != NULL) && (r->get_transition(c) != NULL)) {
r = r->get_failure();
}
if (r == NULL) {
nodes[i]->set_failure(root);
} else {
AhoCorasick::Node* tc = r->get_transition(c);
nodes[i]->set_failure(tc);
set<string> results;
if (tc != NULL) results = tc->get_results();
for (set<string>::iterator it = results.begin(); it != results.end();
it++) {
nodes[i]->add_result(*it);
}
}
vector<AhoCorasick::Node*> tmp_nodes;
tmp_nodes.reserve(next_nodes.size() +
nodes[i]->get_transitions().size() + 1);
merge(next_nodes.begin(), next_nodes.end(),
nodes[i]->get_transitions().begin(),
nodes[i]->get_transitions().end(),
back_inserter<vector<AhoCorasick::Node*> >(tmp_nodes));
next_nodes.swap(tmp_nodes);
}
nodes = next_nodes;
}
root->set_failure(root);
state = root;
}
map<string, int> feed(const string& text,
map<string, int> (*callback)(int pos,
const string& text)) {
int index = 0;
map<string, int> rv;
while (index < text.length()) {
AhoCorasick::Node* trans = NULL;
while (1) {
trans = state->get_transition(text[index]);
if (state == root || trans != NULL) break;
state = state->get_failure();
}
if (trans != NULL) {
state = trans;
}
set<string> results = state->get_results();
for (set<string>::iterator it = results.begin(); it != results.end();
it++) {
rv = (*callback)(index - it->length() + 1, *it);
if (!rv.empty()) {
return rv;
}
}
index++;
}
return rv;
}
};
class State {
public:
int cost;
string route;
int x;
int y;
State(int _x, int _y, int _c, string _r)
: cost(_c), route(_r), x(_x), y(_y) {}
bool operator<(const State& s) const { return cost < s.cost; }
bool operator>(const State& s) const { return cost > s.cost; }
};
map<string, int> handle_first_func(int pos, const string& keyword) {
map<string, int> total;
total[keyword] = pos;
return total;
}
map<string, int> find_first(const string& text, AhoCorasick::SearchMachine* m) {
map<string, int> (*handle_first)(int pos, const string& keyword) =
handle_first_func;
map<string, int> rv = m->feed(text, handle_first);
return rv;
}
int main() {
int H, W;
while (~scanf("%d %d", &H, &W)) {
if (H == 0 && W == 0) break;
set<string> dp[50][50];
char stage[50][50];
int sx = 0;
int sy = 0;
int gx = 0;
int gy = 0;
for (int y = 0; y < H; y++) {
char line[51];
scanf("%s", line);
for (int x = 0; x < W; x++) {
stage[y][x] = line[x];
if (line[x] == 'S') {
sx = x;
sy = y;
} else if (line[x] == 'G') {
gx = x;
gy = y;
}
}
}
int total_prohibited_sequences;
scanf("%d", &total_prohibited_sequences);
set<string> keywords;
for (int sequence_idx = 0; sequence_idx < total_prohibited_sequences;
sequence_idx++) {
string str;
cin >> str;
reverse(str.begin(), str.end());
keywords.insert(str);
}
AhoCorasick::SearchMachine* sm = new AhoCorasick::SearchMachine(keywords);
priority_queue<State, vector<State>, greater<State> > que;
que.push(State(sx, sy, 0, ""));
int res = 0x3f3f3f3f;
while (!que.empty()) {
State s = que.top();
string route = s.route;
int cost = s.cost;
int sx = s.x;
int sy = s.y;
que.pop();
for (int i = 0; i < 4; i++) {
int dx = sx + tx[i];
int dy = sy + ty[i];
if (dx < 0 || dx >= W || dy < 0 || dy >= H) continue;
if (stage[dy][dx] == '#') continue;
string next = dir_str[i] + route;
next = next.substr(0, 10);
if (!(find_first(next, sm)).empty()) {
continue;
}
if (dp[dy][dx].count(next)) continue;
dp[dy][dx].insert(next);
if (stage[dy][dx] == 'G') {
res = cost + 1;
goto found;
}
que.push(State(dx, dy, cost + 1, next));
}
}
found:;
printf("%d\n", res == 0x3f3f3f3f ? -1 : res);
}
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
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) {
char field[52][52];
for (int i = 0; i < 52; i++)
for (int j = 0; j < 52; j++) field[i][j] = '#';
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++) cin >> field[i + 1][j + 1];
int sx, sy;
for (int i = 0; i < W + 1; i++)
for (int j = 0; j < W + 1; j++)
if (field[i][j] == 'S') sx = j, sy = i;
int p;
cin >> p;
vector<string> P(10);
for (int i = 0; i < p; i++) cin >> P[i];
for (int i = 0; i < p; i++)
for (int j = 0; j < p - 1; j++)
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));
while (Q.size()) {
NODE q = Q.front();
Q.pop();
string pt = P[q.a].substr(0, q.b);
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;
for (int d = 0; d < 4; d++) {
string st, t = pt + dc[d];
if (count(P.begin(), P.end(), t)) continue;
for (int i = 0; i < t.size(); i++) {
st = t.substr(i);
for (int j = 0; j < p; j++) {
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:;
}
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const string ds = "URDL";
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {-1, 0, 1, 0};
int n, m;
vector<string> g;
struct AhoCorasick {
static const int alph_size = 26;
struct node_t {
int parent, suffLink;
char charFromParent;
int children[alph_size];
int transitions[alph_size];
bool isLeaf;
node_t() {
fill(children, children + alph_size, -1);
fill(transitions, transitions + alph_size, -1);
suffLink = -1;
isLeaf = false;
}
};
vector<node_t> nodes;
int nodeCount;
AhoCorasick(int maxNodes) {
nodes.resize(maxNodes);
nodes[0] = node_t();
nodes[0].suffLink = 0;
nodes[0].parent = -1;
nodeCount = 1;
}
void add(string s) {
int cur = 0;
for (int i = 0; i < s.size(); i++) {
int c = s[i] - 'A';
if (nodes[cur].children[c] == -1) {
nodes[nodeCount] = node_t();
nodes[nodeCount].parent = cur;
nodes[nodeCount].charFromParent = s[i];
nodes[cur].children[c] = nodeCount++;
}
cur = nodes[cur].children[c];
}
nodes[cur].isLeaf = true;
}
int suffLink(int nodeIndex) {
node_t node = nodes[nodeIndex];
if (node.suffLink == -1) {
node.suffLink = (node.parent == 0) ? 0
: transition(suffLink(node.parent),
node.charFromParent);
}
return node.suffLink;
}
int transition(int nodeIndex, char ch) {
int c = ch - 'A';
node_t node = nodes[nodeIndex];
if (node.transitions[c] == -1) {
node.transitions[c] =
(node.children[c] != -1)
? node.children[c]
: (nodeIndex == 0 ? 0 : transition(suffLink(nodeIndex), ch));
}
return node.transitions[c];
}
int contain(string s) {
int node = 0, cnt = 0;
for (int i = 0; i < s.size(); i++) {
node = transition(node, s[i]);
cnt += nodes[node].isLeaf;
}
return cnt;
}
};
struct state {
int step, x, y, nodeIndex;
};
int dist[51][51][1001];
int bfs() {
int p;
cin >> p;
AhoCorasick aho(1001);
for (int i = 0; i < p; i++) {
string s;
cin >> s;
aho.add(s);
}
fill(*dist[0], *dist[51], (1 << 29));
queue<state> que;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == 'S') {
dist[i][j][0] = 0;
que.push((state){0, j, i, 0});
break;
}
}
}
while (!que.empty()) {
state now = que.front();
que.pop();
if (g[now.y][now.x] == 'G') return now.step;
if (dist[now.y][now.x][now.nodeIndex] < now.step) continue;
dist[now.y][now.x][now.nodeIndex] = now.step;
for (int i = 0; i < 4; i++) {
int nx = now.x + dx[i], ny = now.y + dy[i];
if (nx < 0 || ny < 0 || m <= nx || n <= ny) continue;
if (g[ny][nx] == '#') continue;
int nextNode = aho.transition(now.nodeIndex, ds[i]);
if (aho.nodes[nextNode].isLeaf) continue;
que.push((state){now.step + 1, nx, ny, nextNode});
}
}
return -1;
}
int main(void) {
while (cin >> n >> m, n | m) {
g.resize(n);
for (int i = 0; i < n; i++) cin >> g[i];
cout << bfs() << endl;
}
return 0;
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
struct P {
int x, y, n;
uint64_t pat;
int cost;
bool operator>(const P& p) const {
if (n != p.n) {
return n > p.n;
}
return cost > p.cost;
}
};
const int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
const char dirchar[] = {'L', 'D', 'R', 'U'};
int shortest[50][50];
int main() {
int H, W;
while (cin >> H >> W, H | W) {
vector<vector<bool>> field(H, vector<bool>(W));
int ix, iy, ox, oy;
for (int y = 0; y < (int)(H); ++y)
for (int x = 0; x < (int)(W); ++x) {
char c;
cin >> c;
if (c == '#') {
field[y][x] = true;
} else if (c == 'S') {
ix = x;
iy = y;
} else if (c == 'G') {
ox = x;
oy = y;
}
}
fill_n((int*)shortest, 50 * 50, 0);
for (int y = 0; y < (int)(H); ++y) {
for (int x = 0; x < (int)(W); ++x) {
queue<pair<int, int>> que;
que.push({ix, iy});
pair<int, int> sentry = {-1, -1};
que.push(sentry);
int cnt = 0;
vector<vector<bool>> G(H, vector<bool>(W));
G[y][x] = true;
while (!que.empty()) {
pair<int, int> p = que.front();
que.pop();
if (p.first == ox && p.second == oy) {
shortest[y][x] = cnt;
break;
}
if (p == sentry) {
if (que.empty()) break;
que.push(sentry);
cnt++;
continue;
}
for (int i = 0; i < (int)(4); ++i) {
int sx = p.first + dx[i], sy = p.second + dy[i];
if (0 <= sx && sx < W && 0 <= sy && sy < H) {
if (!G[sy][sx]) {
G[sy][sx] = true;
que.push({sx, sy});
}
}
}
}
}
}
set<uint64_t> forbidden;
int n;
cin >> n;
for (int i = 0; i < (int)(n); ++i) {
string s;
cin >> s;
uint64_t pat = 0;
for (int i = 0; i < (int)(((int)(s).size())); ++i) {
pat <<= 3;
pat |= find(dirchar, dirchar + 4, s[i]) - dirchar + 1;
}
forbidden.insert(pat);
}
vector<vector<set<uint64_t>>> G(H, vector<set<uint64_t>>(W));
priority_queue<P, vector<P>, greater<P>> que;
que.push({ix, iy, 0, 0, 0});
while (!que.empty()) {
P p = que.top();
que.pop();
if (p.x == ox && p.y == oy) {
cout << p.n << endl;
goto END;
}
for (int i = 0; i < (int)(4); ++i) {
int sx = p.x + dx[i], sy = p.y + dy[i];
if (0 <= sx && sx < W && 0 <= sy && sy < H && !field[sy][sx]) {
uint64_t pat = ((p.pat << 3) | (i + 1)) & 0x3fffffff;
if (!((G[sy][sx]).find(pat) != (G[sy][sx]).end())) {
G[sy][sx].insert(pat);
bool ok = true;
for (int j = (int)(1); j < (int)(11); ++j) {
uint64_t p = pat & ((1LL << j * 3) - 1);
if (((forbidden).find(p) != (forbidden).end())) {
ok = false;
break;
}
}
if (ok) que.push({sx, sy, p.n + 1, pat, shortest[sy][sx]});
}
}
}
}
cout << -1 << endl;
END : {}
}
}
|
p01329 Stolen Jewel | The jewel, a national treasure of the Kingdom of Pal, was stolen by bandits. As an adventurer, you heard the rumor and headed for the thief's hideout and managed to get the jewels back.
However, when I went to return the jewel to the castle of the Kingdom of Pal, the guard of the castle said, "My king has not completely trusted you yet. I doubt that the jewel is genuine, and I got it back in the first place. It is a lie, and I suspect that he is a member of the thief who is aiming for the king's life. "
You have been challenged by the guards to see if you really can be trusted. The content of the trial is, "Go to the castle's underground warehouse and place the jewel in the designated place. There is a magic circle that reacts when the jewel is genuine. However, do not cause suspicious behavior. Therefore, do not follow the movement pattern that the guards said from the entrance of the underground warehouse to the designated place. "
For example, for the shape and prohibition pattern of the underground warehouse shown in the figure below, the movement pattern as shown in the figure must not be adopted. This is because part of the movement pattern (highlighted in red) is included in the prohibited pattern. (In addition, the second and third movements "↓↓" in this movement pattern are also included in the prohibited pattern)
<image>
On the other hand, a movement pattern as shown in the figure below is allowed because no part of the movement pattern is included in the prohibited pattern.
<image>
As input, the shape of the underground warehouse and the prohibition pattern are given. Find the minimum number of moves required to move from the entrance to the magic circle without taking the ban pattern.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When n, m is 0, it indicates the end of input.
<!-
Input
The inputs include the shape of the underground warehouse and the prohibition pattern.
The shape of the underground warehouse is represented as follows. First, two integers N and M are given. It means the number of rows and columns of the underground warehouse, respectively. (1 ≤ N, M ≤ 50)
Subsequently, N lines of character strings consisting of M characters are given. The characters included and their meanings are as follows.
Character | Meaning
--- | ---
S | The entrance to the underground warehouse. Only one is always included per underground warehouse.
G | Magic circle. Only one is always included per underground warehouse.
. | Aisle. You can pass (if you don't take the prohibition pattern).
| Wall. You can't go through the wall.
Next, a prohibition pattern is given. The prohibition pattern is expressed as follows. First, one integer P is given. Means the number of prohibited patterns. (0 ≤ P ≤ 10)
Subsequently, a character string meaning a prohibition pattern is given over P lines. The characters included in the prohibited pattern and their meanings are as follows.
Character | Meaning
--- | ---
U | ↑ move.
Move R |->.
D | ↓ movement.
L | <-Move.
The length of the prohibited pattern is 1 or more and 10 or less. One prohibition pattern may be a substring of another prohibition pattern. It may also include the same prohibition pattern.
Output
Output an integer that means the minimum number of moves required. If you can't reach the magic circle, output -1.
Examples
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
########
S......G
########
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
Output
13
Input
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
Output
60
Input
3 8
S......G
2
U
D
Output
7
Input
6 10
..........
.S........
..........
..........
........G.
..........
0
Output
10
Input
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
Output
-1
Input
7 6
......
.####.
.####.
...S#.
...##.
...##.
.....G
3
LD
DD
LLL
7 8
S#......
.#.####.
.#.#G.#.
.#.##.#.
.#....#.
.######.
........
8
DDDD
DDDU
UUUU
UUUD
RRRR
RRRL
LLLL
LLLR
3 8
S......G
2
U
D
6 10
..........
.S........
..........
..........
........G.
..........
0
6 7
.......
...#...
...#.S.
...###.
.G.....
.......
2
LL
DD
0 0
Output
13
60
7
10
-1 | {
"input": [
"6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n\nS......G\n\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"3 8\n\nS......G\n\n2\nU\nD",
"6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL\n7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR\n3 8\n########\nS......G\n########\n2\nU\nD\n6 10\n..........\n.S........\n..........\n..........\n........G.\n..........\n0\n6 7\n.......\n...#...\n...#.S.\n...###.\n.G.....\n.......\n2\nLL\nDD\n0 0",
"7 6\n......\n.####.\n.####.\n...S#.\n...##.\n...##.\n.....G\n3\nLD\nDD\nLLL",
"7 8\nS#......\n.#.####.\n.#.#G.#.\n.#.##.#.\n.#....#.\n.######.\n........\n8\nDDDD\nDDDU\nUUUU\nUUUD\nRRRR\nRRRL\nLLLL\nLLLR"
],
"output": [
"-1",
"13\n60\n7\n10\n-1",
"7",
"10",
"13\n60\n7\n10\n-1",
"13",
"60"
]
} | {
"input": [],
"output": []
} | IN-CORRECT | cpp | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const unsigned long long B = 100000007;
const int MAX_H = 55;
const int MAX_W = 55;
const int MAX_L = 12;
const int MAX_P = 5;
namespace std {
bool operator<(const pair<string, pair<int, int> > &a,
const pair<string, pair<int, int> > &b) {
return a.first.length() < b.first.length();
}
} // namespace std
int H, W, P, L;
pair<int, int> S, G;
string SYM = "URDL";
pair<int, int> mv[] = {pair<int, int>(-1, 0), pair<int, int>(0, 1),
pair<int, int>(1, 0), pair<int, int>(0, -1)};
int overlap(string a, string b) {
int al = a.length(), bl = b.length();
int ans = 0;
unsigned long long ah = 0, bh = 0, t = 1;
for (int i = 1; i <= min(al, bl); ++i) {
ah = ah + a[al - i] * t;
bh = bh * B + b[i - 1];
if (ah == bh) ans = i;
t *= B;
}
if (ans == b.length()) return -1;
return ans;
}
int check(pair<int, int> &now, int t, string s,
int closed[MAX_H][MAX_W][MAX_L][MAX_P], vector<string> &ps,
vector<vector<char> > &v) {
int ny = now.first + mv[t].first, nx = now.second + mv[t].second;
if (ny < 0 || nx < 0 || ny >= H || nx >= W || v[ny][nx] == '#') return -1;
int r = 0;
s += SYM[t];
int sl = s.length();
for (int i = 0; i < (int)(ps.size()); ++i) {
int tmpr = overlap(s, ps[i]);
if (tmpr == -1) return -1;
r = max(r, tmpr);
}
if (closed[ny][nx][r][t] <= sl + 1) return -1;
return r;
}
int solve(vector<vector<char> > &v, vector<string> &ps) {
queue<pair<string, pair<int, int> > > open;
open.push(pair<string, pair<int, int> >("", S));
int closed[MAX_H][MAX_W][MAX_L][MAX_P];
for (int i = 0; i < (int)(MAX_H); ++i)
for (int j = 0; j < (int)(MAX_W); ++j)
for (int k = 0; k < (int)(MAX_L); ++k)
for (int l = 0; l < (int)(MAX_P); ++l) closed[i][j][k][l] = INF;
closed[S.first][S.second][0][0] = 0;
while (!open.empty()) {
string s = open.front().first;
pair<int, int> now = open.front().second;
open.pop();
if (now == G) return s.length();
for (int i = 0; i < (int)(4); ++i) {
int r = check(now, i, s, closed, ps, v);
if (r != -1) {
closed[now.first + mv[i].first][now.second + mv[i].second][r][i] =
(int)s.length() + 1;
open.push(pair<string, pair<int, int> >(
(s + SYM[i]), pair<int, int>(now.first + mv[i].first,
now.second + mv[i].second)));
}
}
}
return -1;
}
int main() {
while (cin >> H >> W && H && W) {
vector<vector<char> > v(H, vector<char>(W));
for (int i = 0; i < (int)(H); ++i) {
for (int j = 0; j < (int)(W); ++j) {
cin >> v[i][j];
if (v[i][j] == 'S') S = pair<int, int>(i, j);
if (v[i][j] == 'G') G = pair<int, int>(i, j);
}
}
cin >> P;
vector<string> ps(P);
L = 0;
for (int i = 0; i < (int)(P); ++i) {
cin >> ps[i];
L = max(L, (int)(ps[i].length()));
}
cout << solve(v, ps) << endl;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.