output
stringlengths
52
181k
instruction
stringlengths
296
182k
#include <iostream> #include <iomanip> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex> #include <cmath> #include <limits> #include <cfloat> #include <climits> #include <ctime> #include <cassert> #include <numeric> #include <functional> using namespace std; #define rep(i,a,n) for(int (i)=(a); (i)<(n); (i)++) #define repq(i,a,n) for(int (i)=(a); (i)<=(n); (i)++) #define repr(i,a,n) for(int (i)=(a); (i)>=(n); (i)--) #define int long long int template<typename T> void chmax(T &a, T b) {a = max(a, b);} template<typename T> void chmin(T &a, T b) {a = min(a, b);} template<typename T> void chadd(T &a, T b) {a = a + b;} typedef pair<int, int> pii; typedef long long ll; int dx[] = {0, 0, 1, -1, 1, 1, -1, -1}; int dy[] = {1, -1, 0, 0, 1, -1, 1, -1}; constexpr ll INF = 1001001001001001LL; constexpr ll MOD = 1000000007LL; int H, W; char board[15][25]; bool used[15][25]; map<string, int> memo; void solve(int x, int y, int dir) { string ret = ""; int s = x, t = y; while(1) { if(used[s][t]) break; used[s][t] = true; ret += board[s][t]; memo[ret]++; s = (s + dx[dir] + H) % H; t = (t + dy[dir] + W) % W; } } bool isbetter(string a, string b) { if(a.length() != b.length()) return a.length() > b.length(); else return a < b; } signed main() { while(cin >> H >> W, H || W) { memo.clear(); rep(i,0,H) rep(j,0,W) cin >> board[i][j]; rep(i,0,H) rep(j,0,W) rep(k,0,8) { memset(used, false, sizeof(used)); solve(i, j, k); } string ans = ""; for(auto elem : memo) { if(elem.second < 2) continue; if(elem.first.length() < 2) continue; if(isbetter(elem.first, ans)) ans = elem.first; } if(ans == "") cout << 0 << endl; else cout << ans << endl; } return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <iomanip> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex> #include <cmath> #include <limits> #include <cfloat> #include <climits> #include <ctime> #include <cassert> #include <numeric> #include <functional> using namespace std; #define rep(i,a,n) for(int (i)=(a); (i)<(n); (i)++) #define repq(i,a,n) for(int (i)=(a); (i)<=(n); (i)++) #define repr(i,a,n) for(int (i)=(a); (i)>=(n); (i)--) #define int long long int template<typename T> void chmax(T &a, T b) {a = max(a, b);} template<typename T> void chmin(T &a, T b) {a = min(a, b);} template<typename T> void chadd(T &a, T b) {a = a + b;} typedef pair<int, int> pii; typedef long long ll; int dx[] = {0, 0, 1, -1, 1, 1, -1, -1}; int dy[] = {1, -1, 0, 0, 1, -1, 1, -1}; constexpr ll INF = 1001001001001001LL; constexpr ll MOD = 1000000007LL; int H, W; char board[15][25]; bool used[15][25]; map<string, int> memo; void solve(int x, int y, int dir) { string ret = ""; int s = x, t = y; while(1) { if(used[s][t]) break; used[s][t] = true; ret += board[s][t]; memo[ret]++; s = (s + dx[dir] + H) % H; t = (t + dy[dir] + W) % W; } } bool isbetter(string a, string b) { if(a.length() != b.length()) return a.length() > b.length(); else return a < b; } signed main() { while(cin >> H >> W, H || W) { memo.clear(); rep(i,0,H) rep(j,0,W) cin >> board[i][j]; rep(i,0,H) rep(j,0,W) rep(k,0,8) { memset(used, false, sizeof(used)); solve(i, j, k); } string ans = ""; for(auto elem : memo) { if(elem.second < 2) continue; if(elem.first.length() < 2) continue; if(isbetter(elem.first, ans)) ans = elem.first; } if(ans == "") cout << 0 << endl; else cout << ans << endl; } return 0; } ```
#include<iostream> #include<string> #include<cstring> #include<vector> #include<set> using namespace std; typedef vector<int> vi; set<string> cands; int dy[]={-1,-1,-1,0,0,1,1,1}; int dx[]={-1,0,1,-1,1,-1,0,1}; int maxlength=0,h,w; string ans=""; void check(int y,int x,string *board) { for(int k=0;k<8;k++) { bool visited[h][w]; memset(visited,false,sizeof(visited)); int yy=y,xx=x; string str=""; while(!visited[yy][xx]) { str+=board[yy][xx]; if(cands.find(str)!=cands.end()) { int str_len=str.length(); if(maxlength<str_len) { ans=str; maxlength=str_len; } else if(maxlength==str_len && str<ans) { ans=str; maxlength=str_len; } } else { cands.insert(str); } visited[yy][xx]=true; yy=(yy+dy[k]+h)%h; xx=(xx+dx[k]+w)%w; } } } int main() { while(1) { cin >> h >> w; if(h==0) break; string board[h]; cands.clear(); for(int i=0;i<h;i++) { cin >> board[i]; } maxlength=0; ans="0"; for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { check(i,j,board); } } if(maxlength>=2) { cout << ans << endl; } else { cout << "0" << endl; } } }
### Prompt Create a solution in Cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<string> #include<cstring> #include<vector> #include<set> using namespace std; typedef vector<int> vi; set<string> cands; int dy[]={-1,-1,-1,0,0,1,1,1}; int dx[]={-1,0,1,-1,1,-1,0,1}; int maxlength=0,h,w; string ans=""; void check(int y,int x,string *board) { for(int k=0;k<8;k++) { bool visited[h][w]; memset(visited,false,sizeof(visited)); int yy=y,xx=x; string str=""; while(!visited[yy][xx]) { str+=board[yy][xx]; if(cands.find(str)!=cands.end()) { int str_len=str.length(); if(maxlength<str_len) { ans=str; maxlength=str_len; } else if(maxlength==str_len && str<ans) { ans=str; maxlength=str_len; } } else { cands.insert(str); } visited[yy][xx]=true; yy=(yy+dy[k]+h)%h; xx=(xx+dx[k]+w)%w; } } } int main() { while(1) { cin >> h >> w; if(h==0) break; string board[h]; cands.clear(); for(int i=0;i<h;i++) { cin >> board[i]; } maxlength=0; ans="0"; for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { check(i,j,board); } } if(maxlength>=2) { cout << ans << endl; } else { cout << "0" << endl; } } } ```
#include <iostream> #include <string> using namespace std; int dx[] = {-1,-1,-1,0,1,1,1,0}; int dy[] = {-1,0,1,1,1,0,-1,-1}; int main(){ int h, w; string mp[10]; while(cin >> h >> w, h){ for(int i=0;i<h;i++) cin >> mp[i]; string res = ""; for(int i=0;i<w*h;i++){ if(res.size() == w*h) break; int x1 = i/w, y1 = i%w; for(int j=i+1;j<w*h;j++){ if(res.size() == w*h) break; int x2 = j/w, y2 = j%w; if(mp[x1][y1]!=mp[x2][y2]) continue; for(int di=0;di<8;di++){ for(int dj=0;dj<8;dj++){ string cur; int nx1 = (x1+dx[di]+h)%h, ny1 = (y1+dy[di]+w)%w; int nx2 = (x2+dx[dj]+h)%h, ny2 = (y2+dy[dj]+w)%w; if(mp[nx1][ny1]!=mp[nx2][ny2]) continue; cur += mp[x1][y1]; while((x1 != nx1 || y1 != ny1) && (x2 != nx2 || y2 != ny2) && mp[nx1][ny1] == mp[nx2][ny2]){ cur += mp[nx1][ny1]; nx1 = (nx1+dx[di]+h)%h, ny1 = (ny1+dy[di]+w)%w; nx2 = (nx2+dx[dj]+h)%h, ny2 = (ny2+dy[dj]+w)%w; } if(cur.size() > res.size()) res = cur; else if(cur.size() == res.size()) res = min(res, cur); } } } } cout << (res=="" ? "0" : res) << endl; } }
### Prompt In CPP, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> using namespace std; int dx[] = {-1,-1,-1,0,1,1,1,0}; int dy[] = {-1,0,1,1,1,0,-1,-1}; int main(){ int h, w; string mp[10]; while(cin >> h >> w, h){ for(int i=0;i<h;i++) cin >> mp[i]; string res = ""; for(int i=0;i<w*h;i++){ if(res.size() == w*h) break; int x1 = i/w, y1 = i%w; for(int j=i+1;j<w*h;j++){ if(res.size() == w*h) break; int x2 = j/w, y2 = j%w; if(mp[x1][y1]!=mp[x2][y2]) continue; for(int di=0;di<8;di++){ for(int dj=0;dj<8;dj++){ string cur; int nx1 = (x1+dx[di]+h)%h, ny1 = (y1+dy[di]+w)%w; int nx2 = (x2+dx[dj]+h)%h, ny2 = (y2+dy[dj]+w)%w; if(mp[nx1][ny1]!=mp[nx2][ny2]) continue; cur += mp[x1][y1]; while((x1 != nx1 || y1 != ny1) && (x2 != nx2 || y2 != ny2) && mp[nx1][ny1] == mp[nx2][ny2]){ cur += mp[nx1][ny1]; nx1 = (nx1+dx[di]+h)%h, ny1 = (ny1+dy[di]+w)%w; nx2 = (nx2+dx[dj]+h)%h, ny2 = (ny2+dy[dj]+w)%w; } if(cur.size() > res.size()) res = cur; else if(cur.size() == res.size()) res = min(res, cur); } } } } cout << (res=="" ? "0" : res) << endl; } } ```
#include<iostream> #include<string> #include<map> #include<algorithm> using namespace std; const int dx[] = {-1,-1,-1, 0, 0, 1, 1, 1}; const int dy[] = {-1, 0, 1,-1, 1,-1, 0, 1}; typedef map<string,int>M; M spell; string mat[10]; void Search(int sx,int sy, int a, int h, int w) { bool f[10][20]={}; string str; int x,y; for(x=sx, y=sy; ; x=(x+dx[a]+w)%w, y=(y+dy[a]+h)%h) { if(f[y][x]) break; f[y][x]=true; str+=mat[y][x]; ++spell[str]; } } int main() { int h,w; while(cin>>h>>w,h) { for(int i=0; i<h; ++i) cin >> mat[i]; spell.clear(); for(int x=0; x<w; ++x) for(int y=0; y<h; ++y) for(int a=0; a<8; ++a) Search(x,y,a,h,w); string res(""); for(M::iterator ite=spell.begin(); ite!=spell.end(); ++ite) { if(ite->second<=1) continue; if(res.size()<ite->first.size() || res>ite->first) res=ite->first; } if(res.size()<=1) res="0"; cout << res << endl; } }
### Prompt Generate a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<string> #include<map> #include<algorithm> using namespace std; const int dx[] = {-1,-1,-1, 0, 0, 1, 1, 1}; const int dy[] = {-1, 0, 1,-1, 1,-1, 0, 1}; typedef map<string,int>M; M spell; string mat[10]; void Search(int sx,int sy, int a, int h, int w) { bool f[10][20]={}; string str; int x,y; for(x=sx, y=sy; ; x=(x+dx[a]+w)%w, y=(y+dy[a]+h)%h) { if(f[y][x]) break; f[y][x]=true; str+=mat[y][x]; ++spell[str]; } } int main() { int h,w; while(cin>>h>>w,h) { for(int i=0; i<h; ++i) cin >> mat[i]; spell.clear(); for(int x=0; x<w; ++x) for(int y=0; y<h; ++y) for(int a=0; a<8; ++a) Search(x,y,a,h,w); string res(""); for(M::iterator ite=spell.begin(); ite!=spell.end(); ++ite) { if(ite->second<=1) continue; if(res.size()<ite->first.size() || res>ite->first) res=ite->first; } if(res.size()<=1) res="0"; cout << res << endl; } } ```
#include <iostream> #include <string> #include <vector> #include <set> using namespace std; #define rep(i, n) for(int i=0; i<(n); ++i) #define mp(a, b) make_pair(a, b) template<typename T, typename Compare = greater<T> > inline void chmax(T& t, T f, Compare comp){if(!comp(t, f))t = f;} int h, w; inline int add(int a, int b, int mod){ int t = a + b; return t < mod? t < 0? mod + t: t: t - mod; } string solve(vector<string>& patterns){ string res = "0"; set<string> spells; rep(x, h)rep(y, w){ for(int dx=-1; dx<=1; ++dx){ for(int dy=-1; dy<=1; ++dy){ string spell = ""; spell += patterns[x][y]; for(int nx=add(x, dx, h), ny=add(y, dy, w); nx!=x || ny!=y; nx=add(nx, dx, h), ny=add(ny, dy, w)){ spell += patterns[nx][ny]; if(!spells.insert(spell).second){ chmax(res, spell, [](string& s, string& t){return mp(t.size(), s) < mp(s.size(), t);}); } } } } } return res; } int main(){ while(cin >> h >> w, h|w){ vector<string> patterns(h); rep(i, h)cin >> patterns[i]; cout << solve(patterns) << '\n'; } return 0; }
### Prompt Please formulate a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <vector> #include <set> using namespace std; #define rep(i, n) for(int i=0; i<(n); ++i) #define mp(a, b) make_pair(a, b) template<typename T, typename Compare = greater<T> > inline void chmax(T& t, T f, Compare comp){if(!comp(t, f))t = f;} int h, w; inline int add(int a, int b, int mod){ int t = a + b; return t < mod? t < 0? mod + t: t: t - mod; } string solve(vector<string>& patterns){ string res = "0"; set<string> spells; rep(x, h)rep(y, w){ for(int dx=-1; dx<=1; ++dx){ for(int dy=-1; dy<=1; ++dy){ string spell = ""; spell += patterns[x][y]; for(int nx=add(x, dx, h), ny=add(y, dy, w); nx!=x || ny!=y; nx=add(nx, dx, h), ny=add(ny, dy, w)){ spell += patterns[nx][ny]; if(!spells.insert(spell).second){ chmax(res, spell, [](string& s, string& t){return mp(t.size(), s) < mp(s.size(), t);}); } } } } } return res; } int main(){ while(cin >> h >> w, h|w){ vector<string> patterns(h); rep(i, h)cin >> patterns[i]; cout << solve(patterns) << '\n'; } return 0; } ```
#include <bits/stdc++.h> #define var auto using ll = long long; const char newl = '\n'; 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;} using namespace std; signed main(){ while(true){ int h, w; cin >> h >> w; if (h == 0) return 0; vector<string> s(h); for (int i = 0; i < h; i++) cin >> s[i]; vector<pair<int, int>> dirs{ make_pair(1, 1), make_pair(0, 1), make_pair(-1, 1), make_pair(1, 0), make_pair(-1, 0), make_pair(1, -1), make_pair(0, -1), make_pair(-1, -1), }; string longest = ""; unordered_set<string> se{}; for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ for (auto&& dir : dirs){ int y = i, x = j; string cur = ""; cur += s[y][x]; do{ y += dir.first; x += dir.second; if (y < 0) y += h; if (x < 0) x += w; if (h <= y) y -= h; if (w <= x) x -= w; if (y == i && x == j) break; cur += s[y][x]; //cout << cur << endl; if (!se.insert(cur).second){ if (cur.size() > longest.size() || (cur.size() == longest.size() && cur < longest)) longest = cur; } } while (true); } } } cout << (longest.size() == 0 ? "0" : longest) << endl; } }
### Prompt Your task is to create a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> #define var auto using ll = long long; const char newl = '\n'; 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;} using namespace std; signed main(){ while(true){ int h, w; cin >> h >> w; if (h == 0) return 0; vector<string> s(h); for (int i = 0; i < h; i++) cin >> s[i]; vector<pair<int, int>> dirs{ make_pair(1, 1), make_pair(0, 1), make_pair(-1, 1), make_pair(1, 0), make_pair(-1, 0), make_pair(1, -1), make_pair(0, -1), make_pair(-1, -1), }; string longest = ""; unordered_set<string> se{}; for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ for (auto&& dir : dirs){ int y = i, x = j; string cur = ""; cur += s[y][x]; do{ y += dir.first; x += dir.second; if (y < 0) y += h; if (x < 0) x += w; if (h <= y) y -= h; if (w <= x) x -= w; if (y == i && x == j) break; cur += s[y][x]; //cout << cur << endl; if (!se.insert(cur).second){ if (cur.size() > longest.size() || (cur.size() == longest.size() && cur < longest)) longest = cur; } } while (true); } } } cout << (longest.size() == 0 ? "0" : longest) << endl; } } ```
#include <bits/stdc++.h> using namespace std; #define rep(i, n) REP(i, 0, n) #define REP(i, s, e) for(int i = (int)(s); i< (int)(e); ++i) int dx[] = {0, 0, -1,-1, -1, 1, 1, 1}; int dy[] = {-1, 1, 0, 1, -1, 0, 1,-1}; map<string, int> mp; vector<string> input; int H, W; typedef long long ll; typedef pair<int, int> pii; void f(int x, int y, set<pii>& st, string& s, const int dir) { // cout << x << " " << y << " " << dir <<" " << s << endl; // cout <<mp.size() << endl; // cout <<s.size() << " " << st.size() << " " << mp.size() << endl; s += input[y][x]; if(s.size() >= 2) mp[s]++; pii p; p = make_pair(y, x); st.insert(p); (x += dx[dir] + W) %= W; (y += dy[dir] + H) %= H; assert(x >= 0 && x < W); assert(y >= 0 && y < H); p = make_pair(y, x); if(st.count(p)) { // mp[s]++; return; } f(x, y, st, s, dir); } int main() { while(cin >> H >> W) { if(H == 0 && W == 0) break; mp.clear(); input.resize(H); rep(i, H) cin >> input[i]; rep(i, H) rep(j, W) { //mp[input[i].substr(j, 1)]++; rep(k, 8) { set<pii> st; string s; f(j, i, st, s, k); } } string s; for(map<string, int>::iterator it = mp.begin(); it != mp.end(); ++it) { if(it->second == 1) continue; if(s.size() < it->first.size()) s = it->first; else { if(s.size() == it->first.size() && s > it->first) s = it->first; } } if(s.size() == 0) cout << 0 << endl; else cout << s << endl; } return 0; }
### Prompt Create a solution in cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define rep(i, n) REP(i, 0, n) #define REP(i, s, e) for(int i = (int)(s); i< (int)(e); ++i) int dx[] = {0, 0, -1,-1, -1, 1, 1, 1}; int dy[] = {-1, 1, 0, 1, -1, 0, 1,-1}; map<string, int> mp; vector<string> input; int H, W; typedef long long ll; typedef pair<int, int> pii; void f(int x, int y, set<pii>& st, string& s, const int dir) { // cout << x << " " << y << " " << dir <<" " << s << endl; // cout <<mp.size() << endl; // cout <<s.size() << " " << st.size() << " " << mp.size() << endl; s += input[y][x]; if(s.size() >= 2) mp[s]++; pii p; p = make_pair(y, x); st.insert(p); (x += dx[dir] + W) %= W; (y += dy[dir] + H) %= H; assert(x >= 0 && x < W); assert(y >= 0 && y < H); p = make_pair(y, x); if(st.count(p)) { // mp[s]++; return; } f(x, y, st, s, dir); } int main() { while(cin >> H >> W) { if(H == 0 && W == 0) break; mp.clear(); input.resize(H); rep(i, H) cin >> input[i]; rep(i, H) rep(j, W) { //mp[input[i].substr(j, 1)]++; rep(k, 8) { set<pii> st; string s; f(j, i, st, s, k); } } string s; for(map<string, int>::iterator it = mp.begin(); it != mp.end(); ++it) { if(it->second == 1) continue; if(s.size() < it->first.size()) s = it->first; else { if(s.size() == it->first.size() && s > it->first) s = it->first; } } if(s.size() == 0) cout << 0 << endl; else cout << s << endl; } return 0; } ```
#include<iostream> #include<vector> #include<cstring> #include<algorithm> using namespace std; int gcd(int a, int b){ if(b == 0)return a; return gcd(b, a%b); } int lcm(int a, int b){ return a/gcd(a, b) * b; } int main(int argc, char *argv[]){ int w, h; while(cin >> h >> w, h){ string torus[30]; string s[2222]; for (int i = 0; i < h; i++) { cin >> torus[i]; } int l = lcm(w, h); int num = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int k = 0; k < h; k++) { s[num].push_back(torus[(h + i + k)%h][j]); s[num + 1].push_back(torus[(h + i - k)%h][j]); } for (int k = 0; k < w; k++) { s[num + 2].push_back(torus[i][(w + j + k)%w]); s[num + 3].push_back(torus[i][(w + j - k)%w]); } for (int k = 0; k < l; k++) { s[num + 4].push_back(torus[(l*h + i + k)%h][(l*w + j + k)%w]); s[num + 5].push_back(torus[(l*h + i - k)%h][(l*w + j + k)%w]); s[num + 6].push_back(torus[(l*h + i + k)%h][(l*w + j - k)%w]); s[num + 7].push_back(torus[(l*h + i - k)%h][(l*w + j - k)%w]); } num += 8; } } sort(s, s + 8*w*h); string ans = ""; for (int i = 0; i < 8*w*h - 1; i++) { int length = 0; for (int j = 0; j < min(s[i].length(), s[i + 1].length()); j++) { if(s[i][length] == s[i + 1][length])length++; else break; } if(length > ans.length())ans = s[i].substr(0,length); } if(ans.length() > 1)std::cout << ans << std::endl; else std::cout << 0 << std::endl; } return 0; }
### Prompt Please formulate a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<vector> #include<cstring> #include<algorithm> using namespace std; int gcd(int a, int b){ if(b == 0)return a; return gcd(b, a%b); } int lcm(int a, int b){ return a/gcd(a, b) * b; } int main(int argc, char *argv[]){ int w, h; while(cin >> h >> w, h){ string torus[30]; string s[2222]; for (int i = 0; i < h; i++) { cin >> torus[i]; } int l = lcm(w, h); int num = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int k = 0; k < h; k++) { s[num].push_back(torus[(h + i + k)%h][j]); s[num + 1].push_back(torus[(h + i - k)%h][j]); } for (int k = 0; k < w; k++) { s[num + 2].push_back(torus[i][(w + j + k)%w]); s[num + 3].push_back(torus[i][(w + j - k)%w]); } for (int k = 0; k < l; k++) { s[num + 4].push_back(torus[(l*h + i + k)%h][(l*w + j + k)%w]); s[num + 5].push_back(torus[(l*h + i - k)%h][(l*w + j + k)%w]); s[num + 6].push_back(torus[(l*h + i + k)%h][(l*w + j - k)%w]); s[num + 7].push_back(torus[(l*h + i - k)%h][(l*w + j - k)%w]); } num += 8; } } sort(s, s + 8*w*h); string ans = ""; for (int i = 0; i < 8*w*h - 1; i++) { int length = 0; for (int j = 0; j < min(s[i].length(), s[i + 1].length()); j++) { if(s[i][length] == s[i + 1][length])length++; else break; } if(length > ans.length())ans = s[i].substr(0,length); } if(ans.length() > 1)std::cout << ans << std::endl; else std::cout << 0 << std::endl; } return 0; } ```
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int h, w; void solve(int y, int x, vector<string> const& v, vector<string>& ret) { int dx[8] = {0, 1, 1, 1, 0, -1, -1, -1}, dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; for(int i=0; i<8; ++i) { string s; vector<vector<bool>> used(h, vector<bool>(w, false)); while(!used[y][x]) { s += v[y][x]; used[y][x] = true; x = (x + dx[i] + w)%w; y = (y + dy[i] + h)%h; if(s.size() >= 2) { ret.push_back(s); } } } } int main() { while(cin >> h >> w, h) { vector<string> v(h); vector<string> ret; for(int i=0; i<h; ++i) { cin >> v[i]; } for(int i=0; i<h; ++i) { for(int j=0; j<w; ++j) { solve(i, j, v, ret); } } sort(ret.begin(), ret.end()); string ret2; for(int i=0; i<ret.size()-1; ++i) { if(ret[i] == ret[i+1]) { if(ret2.size() < ret[i].size() || ret2.size() == ret[i].size() && ret2 > ret[i]) { ret2 = ret[i]; } } } if(ret2.size() == 0) { cout << 0 << endl; } else { cout << ret2 << endl; } } }
### Prompt In cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int h, w; void solve(int y, int x, vector<string> const& v, vector<string>& ret) { int dx[8] = {0, 1, 1, 1, 0, -1, -1, -1}, dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; for(int i=0; i<8; ++i) { string s; vector<vector<bool>> used(h, vector<bool>(w, false)); while(!used[y][x]) { s += v[y][x]; used[y][x] = true; x = (x + dx[i] + w)%w; y = (y + dy[i] + h)%h; if(s.size() >= 2) { ret.push_back(s); } } } } int main() { while(cin >> h >> w, h) { vector<string> v(h); vector<string> ret; for(int i=0; i<h; ++i) { cin >> v[i]; } for(int i=0; i<h; ++i) { for(int j=0; j<w; ++j) { solve(i, j, v, ret); } } sort(ret.begin(), ret.end()); string ret2; for(int i=0; i<ret.size()-1; ++i) { if(ret[i] == ret[i+1]) { if(ret2.size() < ret[i].size() || ret2.size() == ret[i].size() && ret2 > ret[i]) { ret2 = ret[i]; } } } if(ret2.size() == 0) { cout << 0 << endl; } else { cout << ret2 << endl; } } } ```
#include <bits/stdc++.h> using namespace std; const int MAX_H=11,MAX_W=21; const int dx[8]={1,0,-1,0,1,1,-1,-1}; const int dy[8]={0,1,0,-1,1,-1,1,-1}; int h,w,x,y; string now,ans; string S[MAX_H]; int visited[MAX_H][MAX_W]; set<string> cnt; void solve(){ ans=""; cnt.clear(); for (int i=0;i<h;++i){ for (int j=0;j<w;++j){ for (int k=0;k<8;++k){ for (int l=0;l<h;++l) for (int m=0;m<w;++m) visited[l][m]=0; x=i,y=j; now=""; while(!visited[x][y]){ now+=S[x][y]; visited[x][y]=1; (x+=dx[k]+h)%=h; (y+=dy[k]+w)%=w; if (!cnt.count(now)){cnt.emplace(now); continue;} if (ans.size()<now.size()) ans=now; else if (ans.size()==now.size()&&now<ans) ans=now; } } } } if (ans.size()<2) cout << 0 << '\n'; else cout << ans << '\n'; } int main(){ cin.tie(0); ios::sync_with_stdio(false); while(cin >> h >> w,h){ for (int i=0;i<h;++i) cin >> S[i]; solve(); } }
### Prompt Create a solution in Cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAX_H=11,MAX_W=21; const int dx[8]={1,0,-1,0,1,1,-1,-1}; const int dy[8]={0,1,0,-1,1,-1,1,-1}; int h,w,x,y; string now,ans; string S[MAX_H]; int visited[MAX_H][MAX_W]; set<string> cnt; void solve(){ ans=""; cnt.clear(); for (int i=0;i<h;++i){ for (int j=0;j<w;++j){ for (int k=0;k<8;++k){ for (int l=0;l<h;++l) for (int m=0;m<w;++m) visited[l][m]=0; x=i,y=j; now=""; while(!visited[x][y]){ now+=S[x][y]; visited[x][y]=1; (x+=dx[k]+h)%=h; (y+=dy[k]+w)%=w; if (!cnt.count(now)){cnt.emplace(now); continue;} if (ans.size()<now.size()) ans=now; else if (ans.size()==now.size()&&now<ans) ans=now; } } } } if (ans.size()<2) cout << 0 << '\n'; else cout << ans << '\n'; } int main(){ cin.tie(0); ios::sync_with_stdio(false); while(cin >> h >> w,h){ for (int i=0;i<h;++i) cin >> S[i]; solve(); } } ```
#include <iostream> #include <map> #include <string> using namespace std; int w,h; string ans; string ptn[30]; int di[] = {0,1,0,-1, 1,1,-1,-1}; int dj[] = {1,0,-1,0, 1,-1,-1,1}; int main(){ string s; while( cin >> h >> w && (h|w) ){ for( int i=0;i<h;i++ ){ cin >> ptn[i]; } ans=""; map<string,int> mp; for( int st=0;st<h;st++ ){ for( int en=0;en<w;en++ ){ for( int lp=0;lp<8;lp++ ){ int i=st, j=en; // cout << ptn[i][j] << endl; string s = ptn[i].substr(j,1); while( true ){ i+=di[lp]; j+=dj[lp]; if( i==h ) i=0; else if( i==-1) i=h-1; if( j==w ) j=0; else if( j==-1 ) j=w-1; if( i==st && j==en ) break; s += ptn[i][j]; if( s.length() < ans.length() ) continue; mp[s]++; if( mp[s]==2 ){ if( s.length() > ans.length() ) ans = s; else if( s.length()==ans.length() && s < ans ) ans = s; } } } } } if( ans.length()<2 ) cout << 0 << endl; else cout << ans << endl; } return 0; }
### Prompt Create a solution in CPP for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <map> #include <string> using namespace std; int w,h; string ans; string ptn[30]; int di[] = {0,1,0,-1, 1,1,-1,-1}; int dj[] = {1,0,-1,0, 1,-1,-1,1}; int main(){ string s; while( cin >> h >> w && (h|w) ){ for( int i=0;i<h;i++ ){ cin >> ptn[i]; } ans=""; map<string,int> mp; for( int st=0;st<h;st++ ){ for( int en=0;en<w;en++ ){ for( int lp=0;lp<8;lp++ ){ int i=st, j=en; // cout << ptn[i][j] << endl; string s = ptn[i].substr(j,1); while( true ){ i+=di[lp]; j+=dj[lp]; if( i==h ) i=0; else if( i==-1) i=h-1; if( j==w ) j=0; else if( j==-1 ) j=w-1; if( i==st && j==en ) break; s += ptn[i][j]; if( s.length() < ans.length() ) continue; mp[s]++; if( mp[s]==2 ){ if( s.length() > ans.length() ) ans = s; else if( s.length()==ans.length() && s < ans ) ans = s; } } } } } if( ans.length()<2 ) cout << 0 << endl; else cout << ans << endl; } return 0; } ```
#include <iostream> #include <vector> #include <algorithm> #include <map> #include <queue> #include <cstdio> #include <ctime> #include <assert.h> #include <chrono> #include <random> #include <numeric> #include <set> #include <deque> #include <stack> #include <bitset> using namespace std; typedef long long int ll; typedef unsigned long long ull; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); ll myRand(ll B) { return (ull)rng() % B; } map<string,int> mp; int h,w; char fi[22][22]; int dx[]={1,1,1,0,0,-1,-1,-1}; int dy[]={-1,0,1,-1,1,-1,0,1}; void dfs(int sx,int sy,int x,int y,int k,string s){ s+=fi[x][y]; mp[s]++; int nx=(x+dx[k]+h)%h; int ny=(y+dy[k]+w)%w; if(nx==sx&&ny==sy)return; dfs(sx,sy,nx,ny,k,s); } int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); while(cin >> h >> w,h){ mp.clear(); for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> fi[i][j]; } } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ dfs(i,j,i,j,k,""); } } } string res=""; for(auto p:mp){ if(p.second>=2){ if(p.first.size()>res.size())res=p.first; else if(p.first.size()==res.size())res=min(res,p.first); } } cout << ((res.size()>=2)?res:"0") << endl; } }
### Prompt Develop a solution in cpp to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <algorithm> #include <map> #include <queue> #include <cstdio> #include <ctime> #include <assert.h> #include <chrono> #include <random> #include <numeric> #include <set> #include <deque> #include <stack> #include <bitset> using namespace std; typedef long long int ll; typedef unsigned long long ull; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); ll myRand(ll B) { return (ull)rng() % B; } map<string,int> mp; int h,w; char fi[22][22]; int dx[]={1,1,1,0,0,-1,-1,-1}; int dy[]={-1,0,1,-1,1,-1,0,1}; void dfs(int sx,int sy,int x,int y,int k,string s){ s+=fi[x][y]; mp[s]++; int nx=(x+dx[k]+h)%h; int ny=(y+dy[k]+w)%w; if(nx==sx&&ny==sy)return; dfs(sx,sy,nx,ny,k,s); } int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); while(cin >> h >> w,h){ mp.clear(); for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> fi[i][j]; } } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ dfs(i,j,i,j,k,""); } } } string res=""; for(auto p:mp){ if(p.second>=2){ if(p.first.size()>res.size())res=p.first; else if(p.first.size()==res.size())res=min(res,p.first); } } cout << ((res.size()>=2)?res:"0") << endl; } } ```
#include <cstdio> #include <cstring> #include <cstdlib> #include <cassert> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <set> using namespace std; #define LET(name, value) __typeof(value) name = value #define REP(i, n) for (int i = 0; i < (int)(n); ++i) #define FOR(i, a, b) for (int i = (a); i < (int)(b); ++i) #define FOREQ(i, a, b) for (int i = (a); i <= (int)(b); ++i) #define ALL(c) (c).begin(), (c).end() #define FOREACH(i, c) for (LET(i, (c).begin()); i != (c).end(); ++i) char field[30][30]; int main() { int h, w; while (scanf("%d%d", &h, &w), h|w) { REP(y, h) REP(x, w) { scanf(" %c", &field[y][x]); } static const int dy[] = {-1, -1, -1, 0, 0, 1, 1, 1}; static const int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1}; set<string> dict; string ans, str; REP(sy, h) REP(sx, w) REP(dir, 8) { int y = sy, x = sx; str.clear(); do { str += field[y][x]; LET(it, dict.lower_bound(str)); if (it != dict.end() && *it == str) { if (str.size() > ans.size() || (str.size() == ans.size() && str < ans)) { ans = str; } } else { dict.insert(it, str); } y = (y + dy[dir] + h) % h; x = (x + dx[dir] + w) % w; } while (y != sy || x != sx); } printf("%s\n", ans.size() > 1 ? ans.c_str() : "0"); } }
### Prompt Develop a solution in Cpp to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstdio> #include <cstring> #include <cstdlib> #include <cassert> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <set> using namespace std; #define LET(name, value) __typeof(value) name = value #define REP(i, n) for (int i = 0; i < (int)(n); ++i) #define FOR(i, a, b) for (int i = (a); i < (int)(b); ++i) #define FOREQ(i, a, b) for (int i = (a); i <= (int)(b); ++i) #define ALL(c) (c).begin(), (c).end() #define FOREACH(i, c) for (LET(i, (c).begin()); i != (c).end(); ++i) char field[30][30]; int main() { int h, w; while (scanf("%d%d", &h, &w), h|w) { REP(y, h) REP(x, w) { scanf(" %c", &field[y][x]); } static const int dy[] = {-1, -1, -1, 0, 0, 1, 1, 1}; static const int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1}; set<string> dict; string ans, str; REP(sy, h) REP(sx, w) REP(dir, 8) { int y = sy, x = sx; str.clear(); do { str += field[y][x]; LET(it, dict.lower_bound(str)); if (it != dict.end() && *it == str) { if (str.size() > ans.size() || (str.size() == ans.size() && str < ans)) { ans = str; } } else { dict.insert(it, str); } y = (y + dy[dir] + h) % h; x = (x + dx[dir] + w) % w; } while (y != sy || x != sx); } printf("%s\n", ans.size() > 1 ? ans.c_str() : "0"); } } ```
#include <cstdio> #include <string> #include <set> #include <vector> using namespace std; int dr[]={-1, -1, -1, 0, 0, 1, 1, 1}; int dc[]={-1, 0, 1, -1, 1, -1, 0, 1}; bool cmp(const string& a, const string& b) { if (a.size()<b.size()) return 1; if (a.size()>b.size()) return 0; return a>b; } int main() { int n, m; while (scanf("%d%d", &n, &m), n) { char s[11][21]; for(int i=0;i<n;++i) scanf("%s", s[i]); int maxlen=0; vector<string> spells[200]; for(int i=0;i<n;++i) for(int j=0;j<m;++j) for(int k=0;k<8;++k) { int r=i, c=j, q=0; string t; do { t+=s[r][c]; spells[q++].push_back(t); r=(r+dr[k]+2*n)%n; c=(c+dc[k]+2*m)%m; } while (r!=i || c!=j); maxlen=max(maxlen, q); } string res; for(int k=1;k<maxlen;++k) { int N=spells[k].size(); set<string> v; for(int i=0;i<N;++i) { if (v.count(spells[k][i]) and cmp(res, spells[k][i])) res=spells[k][i]; v.insert(spells[k][i]); } } puts(res.size()?res.c_str():"0"); } return 0; }
### Prompt Create a solution in CPP for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstdio> #include <string> #include <set> #include <vector> using namespace std; int dr[]={-1, -1, -1, 0, 0, 1, 1, 1}; int dc[]={-1, 0, 1, -1, 1, -1, 0, 1}; bool cmp(const string& a, const string& b) { if (a.size()<b.size()) return 1; if (a.size()>b.size()) return 0; return a>b; } int main() { int n, m; while (scanf("%d%d", &n, &m), n) { char s[11][21]; for(int i=0;i<n;++i) scanf("%s", s[i]); int maxlen=0; vector<string> spells[200]; for(int i=0;i<n;++i) for(int j=0;j<m;++j) for(int k=0;k<8;++k) { int r=i, c=j, q=0; string t; do { t+=s[r][c]; spells[q++].push_back(t); r=(r+dr[k]+2*n)%n; c=(c+dc[k]+2*m)%m; } while (r!=i || c!=j); maxlen=max(maxlen, q); } string res; for(int k=1;k<maxlen;++k) { int N=spells[k].size(); set<string> v; for(int i=0;i<N;++i) { if (v.count(spells[k][i]) and cmp(res, spells[k][i])) res=spells[k][i]; v.insert(spells[k][i]); } } puts(res.size()?res.c_str():"0"); } return 0; } ```
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> using namespace std; #define rep(i, n) for(int i = 0 ; i < n ; i++) const int dx[] = {0, 0, 1, -1, 1, 1, -1, -1}; const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1}; int H, W; map<string, int> past; char field[12][22]; void solve(int x, int y){ rep(i, 8){ bool used[12][22]; string s = ""; memset(used, 0, sizeof(used)); used[y][x] = true; s += field[y][x]; int nx = x+dx[i], ny = y+dy[i]; if(nx < 0) nx = W-1; else if(nx >= W) nx = 0; if(ny < 0) ny = H-1; else if(ny >= H) ny = 0; while(true){ if(used[ny][nx]) break; used[ny][nx] = true; s += field[ny][nx]; nx += dx[i], ny += dy[i]; if(nx < 0) nx = W-1; else if(nx >= W) nx = 0; if(ny < 0) ny = H-1; else if(ny >= H) ny = 0; if(s.size() >= 2) past[s]++; //if(s == "MF") cout << "x = " << x << ", y = " << y << endl; } } } void init(){ past.clear(); } int main(){ while(cin >> H >> W, H|W){ init(); rep(i, H){ cin >> field[i]; } rep(i, H){ rep(j, W){ solve(j, i); } } int L = 0; string ans = ""; for(map<string, int>::iterator it = past.begin() ; it != past.end() ; it++){ if(it->second < 2 ) continue; string tmp = it->first; //cout << tmp << endl; if(tmp.size() > L){ L = tmp.size(); ans = tmp; } else if(tmp.size() == L){ if(ans > tmp){ ans = tmp; } } } if(ans.size() == 0) cout << "0" << endl; else cout << ans << endl; } return 0; }
### Prompt In Cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> using namespace std; #define rep(i, n) for(int i = 0 ; i < n ; i++) const int dx[] = {0, 0, 1, -1, 1, 1, -1, -1}; const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1}; int H, W; map<string, int> past; char field[12][22]; void solve(int x, int y){ rep(i, 8){ bool used[12][22]; string s = ""; memset(used, 0, sizeof(used)); used[y][x] = true; s += field[y][x]; int nx = x+dx[i], ny = y+dy[i]; if(nx < 0) nx = W-1; else if(nx >= W) nx = 0; if(ny < 0) ny = H-1; else if(ny >= H) ny = 0; while(true){ if(used[ny][nx]) break; used[ny][nx] = true; s += field[ny][nx]; nx += dx[i], ny += dy[i]; if(nx < 0) nx = W-1; else if(nx >= W) nx = 0; if(ny < 0) ny = H-1; else if(ny >= H) ny = 0; if(s.size() >= 2) past[s]++; //if(s == "MF") cout << "x = " << x << ", y = " << y << endl; } } } void init(){ past.clear(); } int main(){ while(cin >> H >> W, H|W){ init(); rep(i, H){ cin >> field[i]; } rep(i, H){ rep(j, W){ solve(j, i); } } int L = 0; string ans = ""; for(map<string, int>::iterator it = past.begin() ; it != past.end() ; it++){ if(it->second < 2 ) continue; string tmp = it->first; //cout << tmp << endl; if(tmp.size() > L){ L = tmp.size(); ans = tmp; } else if(tmp.size() == L){ if(ans > tmp){ ans = tmp; } } } if(ans.size() == 0) cout << "0" << endl; else cout << ans << endl; } return 0; } ```
#include <iostream> #include <string> #include <map> using namespace std; int main() { int w, h; char seat[10][20]; map<string, int> mp; int dx[] = { 0, 1, 1, 1, 0, -1, -1, -1 }; int dy[] = { 1, 1, 0, -1, -1, -1, 0, 1 }; while( cin >> h >> w, (h||w)) { mp.clear(); for( int j = 0; j < h; j++) for( int i = 0; i < w; i++) { cin >> seat[j][i]; } for( int j = 0; j < h; j++) for( int i = 0; i < w; i++) for( int d = 0; d < 8 ; d++ ) { string str = ""; int x = i, y = j; do { str += seat[y][x]; x = (x + w + dx[d]) % w; y = (y + h + dy[d]) % h; mp[str] += 1; } while( x != i || y != j ); } string out = ""; map<string, int>::iterator it; for( it = mp.begin() ; it != mp.end(); it++ ) { if( (*it).second >= 2 ) if( (*it).first.length() > out.length() ) { out = (*it).first; } else if( (*it).first.length() == out.length() ) { if( out > (*it).first ) out = (*it).first; } } if( out.length() >= 2 ) cout << out << endl; else cout << '0' << endl; } return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <map> using namespace std; int main() { int w, h; char seat[10][20]; map<string, int> mp; int dx[] = { 0, 1, 1, 1, 0, -1, -1, -1 }; int dy[] = { 1, 1, 0, -1, -1, -1, 0, 1 }; while( cin >> h >> w, (h||w)) { mp.clear(); for( int j = 0; j < h; j++) for( int i = 0; i < w; i++) { cin >> seat[j][i]; } for( int j = 0; j < h; j++) for( int i = 0; i < w; i++) for( int d = 0; d < 8 ; d++ ) { string str = ""; int x = i, y = j; do { str += seat[y][x]; x = (x + w + dx[d]) % w; y = (y + h + dy[d]) % h; mp[str] += 1; } while( x != i || y != j ); } string out = ""; map<string, int>::iterator it; for( it = mp.begin() ; it != mp.end(); it++ ) { if( (*it).second >= 2 ) if( (*it).first.length() > out.length() ) { out = (*it).first; } else if( (*it).first.length() == out.length() ) { if( out > (*it).first ) out = (*it).first; } } if( out.length() >= 2 ) cout << out << endl; else cout << '0' << endl; } return 0; } ```
#include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; const int dy[8] = {1,1,1,0,0,-1,-1,-1}; const int dx[8] = {-1,0,1,-1,1,-1,0,1}; int h,w; string str[10]; void solve(){ int y, x, ansn = 0; string ans = "0", st; set<string> s; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ st.clear(); st += str[i][j]; y = i; x = j; while(1){ y = (y + h + dy[k]) % h; x = (x + w + dx[k]) % w; if(y == i && j == x) break; else st += str[y][x]; if(!s.empty() && s.find(st) != s.end()){ if(ansn < st.size() || ansn == st.size() && ans > st){ ans = st; ansn = st.size(); } } else if(st.size() >= ansn) s.insert(st); } } } } cout << ans << endl; } int main(){ while(cin >> h >> w && (h|w)){ for(int i=0;i<h;i++){ cin >> str[i]; } solve(); } }
### Prompt Generate a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; const int dy[8] = {1,1,1,0,0,-1,-1,-1}; const int dx[8] = {-1,0,1,-1,1,-1,0,1}; int h,w; string str[10]; void solve(){ int y, x, ansn = 0; string ans = "0", st; set<string> s; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ st.clear(); st += str[i][j]; y = i; x = j; while(1){ y = (y + h + dy[k]) % h; x = (x + w + dx[k]) % w; if(y == i && j == x) break; else st += str[y][x]; if(!s.empty() && s.find(st) != s.end()){ if(ansn < st.size() || ansn == st.size() && ans > st){ ans = st; ansn = st.size(); } } else if(st.size() >= ansn) s.insert(st); } } } } cout << ans << endl; } int main(){ while(cin >> h >> w && (h|w)){ for(int i=0;i<h;i++){ cin >> str[i]; } solve(); } } ```
#include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(), (x).end() using namespace std; 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); } using ll = long long; using ld = long double; const int INF = 1e9; const ld eps = 1e-9, pi = acos(-1.0); int W, H; string mat[10][20]; int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1}; int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1}; vector<string> strs; int oi, oj; void dfs(int i, int j, int k, string str){ int ni = (i+dx[k]+H)%H; int nj = (j+dy[k]+W)%W; if(ni == oi && nj == oj) { strs.push_back(str); return; } str.append(mat[ni][nj]); dfs(ni, nj, k, str); return; } int main(){ while(cin >> H >> W and W + H){ strs.clear(); REP(i, H) { string str; cin >> str; REP(j, W) mat[i][j] = string(&str[j], 1); } REP(i, H) REP(j, W) REP(k, 8){ oi = i; oj = j; dfs(i, j, k, mat[i][j]); } sort(ALL(strs)); int rcnt = 0; string res; REP(i, strs.size()-1){ int cnt = 0; REP(j, min(strs[i].size(), strs[i+1].size())){ if(strs[i][j] != strs[i+1][j]) break; cnt++; } if(cnt > rcnt) { rcnt = cnt; res = strs[i].substr(0, rcnt); } } if(rcnt < 2) cout << "0" << endl; else cout << res << endl; } return 0; }
### Prompt Generate a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(), (x).end() using namespace std; 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); } using ll = long long; using ld = long double; const int INF = 1e9; const ld eps = 1e-9, pi = acos(-1.0); int W, H; string mat[10][20]; int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1}; int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1}; vector<string> strs; int oi, oj; void dfs(int i, int j, int k, string str){ int ni = (i+dx[k]+H)%H; int nj = (j+dy[k]+W)%W; if(ni == oi && nj == oj) { strs.push_back(str); return; } str.append(mat[ni][nj]); dfs(ni, nj, k, str); return; } int main(){ while(cin >> H >> W and W + H){ strs.clear(); REP(i, H) { string str; cin >> str; REP(j, W) mat[i][j] = string(&str[j], 1); } REP(i, H) REP(j, W) REP(k, 8){ oi = i; oj = j; dfs(i, j, k, mat[i][j]); } sort(ALL(strs)); int rcnt = 0; string res; REP(i, strs.size()-1){ int cnt = 0; REP(j, min(strs[i].size(), strs[i+1].size())){ if(strs[i][j] != strs[i+1][j]) break; cnt++; } if(cnt > rcnt) { rcnt = cnt; res = strs[i].substr(0, rcnt); } } if(rcnt < 2) cout << "0" << endl; else cout << res << endl; } return 0; } ```
#include <bits/stdc++.h> #define rep(i,n) for(int i=0;i<n;i++) using namespace std; const int INF=INT_MAX,MOD=1e9+7; int main(){ int dx[8]={0,1,1,1,0,-1,-1,-1}; int dy[8]={-1,-1,0,1,1,1,0,-1}; int h,w; while(cin>>h>>w&&h){ char c[h][w]; rep(i,h)rep(j,w) cin>>c[i][j]; vector<string> s; for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ for(int dir=0;dir<8;dir++){ int nowy=y,nowx=x; string tmp; while(1){ tmp+=c[nowy][nowx]; nowy=(h+nowy+dy[dir])%h; nowx=(w+nowx+dx[dir])%w; s.push_back(tmp); if(nowy==y&&nowx==x) break; } } } } sort(s.begin(),s.end()); string ans="0"; int size=1; for(int i=0;i<(int)s.size()-1;i++){ //cout<<s[i]<<endl; string tmp; if(s[i]==s[i+1]){ tmp=s[i]; } if(size<(int)tmp.size()){ ans=tmp; size=tmp.size(); } } cout<<ans<<endl; } return 0; }
### Prompt Create a solution in cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> #define rep(i,n) for(int i=0;i<n;i++) using namespace std; const int INF=INT_MAX,MOD=1e9+7; int main(){ int dx[8]={0,1,1,1,0,-1,-1,-1}; int dy[8]={-1,-1,0,1,1,1,0,-1}; int h,w; while(cin>>h>>w&&h){ char c[h][w]; rep(i,h)rep(j,w) cin>>c[i][j]; vector<string> s; for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ for(int dir=0;dir<8;dir++){ int nowy=y,nowx=x; string tmp; while(1){ tmp+=c[nowy][nowx]; nowy=(h+nowy+dy[dir])%h; nowx=(w+nowx+dx[dir])%w; s.push_back(tmp); if(nowy==y&&nowx==x) break; } } } } sort(s.begin(),s.end()); string ans="0"; int size=1; for(int i=0;i<(int)s.size()-1;i++){ //cout<<s[i]<<endl; string tmp; if(s[i]==s[i+1]){ tmp=s[i]; } if(size<(int)tmp.size()){ ans=tmp; size=tmp.size(); } } cout<<ans<<endl; } return 0; } ```
#include<iostream> #include<string> #include<algorithm> #include<vector> #include<cstdio> #include<cstring> #include<map> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) #define REP(n) rep(i,n) #define all(n) n.begin(),n.end() #define foreach(c,it) for(typeof(c.begin()) it=c.begin();it!=c.end();++it) int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1}; int dy[] = {1, 1, 1, 0, 0, -1, -1, -1}; const int MAXH = 10, MAXW = 20; char tile[MAXW][MAXH]; int checked[MAXW][MAXH]; typedef pair<int, string> p; int main() { int w, h; while(cin >> h >> w && h) { rep(j,h)rep(i,w){ cin >> tile[i][j];} vector<p> ans; rep(sx,w)rep(sy,h)rep(v,8) { memset(checked, 0, sizeof(checked)); int x = sx, y = sy; string s; while(!checked[x][y]) { //cout << x << " " << y << endl; s += tile[x][y]; ans.push_back(p( -s.size(), s)); checked[x][y] = 1; x += dx[v]; y += dy[v]; if(x == w) x = 0; if(x == -1) x = w - 1; if(y == h) y = 0; if(y == -1) y = h - 1; } } sort(all(ans)); int found = 0; for(int i = 0; i < ans.size() - 1; i++)if(ans[i] == ans[i + 1] && ans[i].first <= -2) { cout << ans[i].second << endl; found = 1; break; } if(!found) cout << 0 << endl; } return 0; }
### Prompt In CPP, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<string> #include<algorithm> #include<vector> #include<cstdio> #include<cstring> #include<map> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) #define REP(n) rep(i,n) #define all(n) n.begin(),n.end() #define foreach(c,it) for(typeof(c.begin()) it=c.begin();it!=c.end();++it) int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1}; int dy[] = {1, 1, 1, 0, 0, -1, -1, -1}; const int MAXH = 10, MAXW = 20; char tile[MAXW][MAXH]; int checked[MAXW][MAXH]; typedef pair<int, string> p; int main() { int w, h; while(cin >> h >> w && h) { rep(j,h)rep(i,w){ cin >> tile[i][j];} vector<p> ans; rep(sx,w)rep(sy,h)rep(v,8) { memset(checked, 0, sizeof(checked)); int x = sx, y = sy; string s; while(!checked[x][y]) { //cout << x << " " << y << endl; s += tile[x][y]; ans.push_back(p( -s.size(), s)); checked[x][y] = 1; x += dx[v]; y += dy[v]; if(x == w) x = 0; if(x == -1) x = w - 1; if(y == h) y = 0; if(y == -1) y = h - 1; } } sort(all(ans)); int found = 0; for(int i = 0; i < ans.size() - 1; i++)if(ans[i] == ans[i + 1] && ans[i].first <= -2) { cout << ans[i].second << endl; found = 1; break; } if(!found) cout << 0 << endl; } return 0; } ```
#include <bits/stdc++.h> #include <regex> using namespace std; #define FOR(i,k,n) for(int i = (k); i < (n); i++) #define REP(i,n) FOR(i,0,n) #define ALL(a) begin(a),end(a) #define MS(m,v) memset(m,v,sizeof(m)) #define D10 fixed<<setprecision(10) typedef vector<int> vi; typedef vector<string> vs; typedef pair<int, int> P; typedef complex<double> Point; typedef long long ll; const int INF = 1145141919; const int MOD = 100000007; const double EPS = 1e-10; const double PI = acos(-1.0); struct edge { int from, to, cost; bool operator < (const edge& e) const { return cost < e.cost; } bool operator >(const edge& e) const { return cost > e.cost; } }; ///*************************************************************************************/// ///*************************************************************************************/// ///*************************************************************************************/// int dx[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; int dy[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; int w, h; vector<string> s; int main() { while (cin >> h >> w, w) { s.resize(h); REP(i, h) cin >> s[i]; map<string,int> used; REP(i, h) { REP(j, w) { REP(k, 8) { string t; t+=s[i][j]; int nx = i; int ny = j; while (1) { nx += dx[k]; ny += dy[k]; if (nx == h) nx = 0; else if (nx < 0) nx = h - 1; if (ny == w) ny = 0; else if (ny < 0) ny = w - 1; if (nx == i&&ny == j) break; t += s[nx][ny]; used[t]++; } } } } string ans = "0"; for (auto ite = used.begin(); ite != used.end(); ite++) { if ((*ite).second >= 2) { auto tmp = (*ite).first; if (ans.size() < tmp.size()) ans = tmp; else if (ans.size() == tmp.size()) ans = min(ans, tmp); } } cout << ans << endl; } return 0; }
### Prompt Construct a CPP code solution to the problem outlined: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> #include <regex> using namespace std; #define FOR(i,k,n) for(int i = (k); i < (n); i++) #define REP(i,n) FOR(i,0,n) #define ALL(a) begin(a),end(a) #define MS(m,v) memset(m,v,sizeof(m)) #define D10 fixed<<setprecision(10) typedef vector<int> vi; typedef vector<string> vs; typedef pair<int, int> P; typedef complex<double> Point; typedef long long ll; const int INF = 1145141919; const int MOD = 100000007; const double EPS = 1e-10; const double PI = acos(-1.0); struct edge { int from, to, cost; bool operator < (const edge& e) const { return cost < e.cost; } bool operator >(const edge& e) const { return cost > e.cost; } }; ///*************************************************************************************/// ///*************************************************************************************/// ///*************************************************************************************/// int dx[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; int dy[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; int w, h; vector<string> s; int main() { while (cin >> h >> w, w) { s.resize(h); REP(i, h) cin >> s[i]; map<string,int> used; REP(i, h) { REP(j, w) { REP(k, 8) { string t; t+=s[i][j]; int nx = i; int ny = j; while (1) { nx += dx[k]; ny += dy[k]; if (nx == h) nx = 0; else if (nx < 0) nx = h - 1; if (ny == w) ny = 0; else if (ny < 0) ny = w - 1; if (nx == i&&ny == j) break; t += s[nx][ny]; used[t]++; } } } } string ans = "0"; for (auto ite = used.begin(); ite != used.end(); ite++) { if ((*ite).second >= 2) { auto tmp = (*ite).first; if (ans.size() < tmp.size()) ans = tmp; else if (ans.size() == tmp.size()) ans = min(ans, tmp); } } cout << ans << endl; } return 0; } ```
#include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <cstring> #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 <unordered_set> #include <unordered_map> using namespace std; int dx[] = { 1,1,1,0,-1,-1,-1,0 }; int dy[] = { 1,0,-1,-1,-1,0,1,1 }; int main(void) { for (;;) { int h, w; cin >> h >> w; if (!h)break; vector<string>donut; for (int i = 0; i < h; ++i) { string s; cin >> s; donut.push_back(s); } map<string, int>dic; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { for (int dir = 0; dir < 8; ++dir) { int ii = i, jj = j; set<pair<int, int>>st; string str; for (;;) { if (st.count({ ii,jj }))break; st.insert({ ii,jj }); str.push_back(donut[ii][jj]); dic[str]++; ii += dx[dir]; jj += dy[dir]; ii += h; jj += w; ii %= h; jj %= w; } } } } string ans = "0"; for (auto page : dic) { if (page.second > 1) { const string& s = page.first; if (s.size() > ans.size()) { ans = s; } else if (s.size() == ans.size()) { if (s < ans)ans = s; } } } cout << ans << endl; } return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <cstring> #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 <unordered_set> #include <unordered_map> using namespace std; int dx[] = { 1,1,1,0,-1,-1,-1,0 }; int dy[] = { 1,0,-1,-1,-1,0,1,1 }; int main(void) { for (;;) { int h, w; cin >> h >> w; if (!h)break; vector<string>donut; for (int i = 0; i < h; ++i) { string s; cin >> s; donut.push_back(s); } map<string, int>dic; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { for (int dir = 0; dir < 8; ++dir) { int ii = i, jj = j; set<pair<int, int>>st; string str; for (;;) { if (st.count({ ii,jj }))break; st.insert({ ii,jj }); str.push_back(donut[ii][jj]); dic[str]++; ii += dx[dir]; jj += dy[dir]; ii += h; jj += w; ii %= h; jj %= w; } } } } string ans = "0"; for (auto page : dic) { if (page.second > 1) { const string& s = page.first; if (s.size() > ans.size()) { ans = s; } else if (s.size() == ans.size()) { if (s < ans)ans = s; } } } cout << ans << endl; } return 0; } ```
#include <iostream> #include <algorithm> #include <set> using namespace std; #define REP(i,x)for(__typeof(x) i=0;i<x;i++) string res; set<string> m; int H,W,dx,dy,min_len; char s[200]; string MAP[11]; bool visit[20][20]; void dfs(int x,int y,int k){ if(k==min_len){ if(m.count(string(s)))res=min(res,string(s)); m.insert(string(s)); }else if(k>min_len){ if(m.count(string(s)))res=string(s),min_len=k; m.insert(string(s)); } m.insert(string(s)); if(visit[y][x]) return; s[k]=MAP[y][x]; visit[y][x]=1; dfs((x + dx + W) % W, (y + dy + H) % H, k + 1); s[k]=0; visit[y][x]=0; } int main() { while(cin>>H>>W,H){ REP(i,H)cin>>MAP[i]; m.clear(); min_len=1; res="0"; REP(y,H)REP(x,W){ for(dx=-1;dx<=1;dx++){ for(dy=-1;dy<=1;dy++){ if(dx|dy)dfs(x,y,0); } } } cout<<res<<endl; } }
### Prompt In cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <algorithm> #include <set> using namespace std; #define REP(i,x)for(__typeof(x) i=0;i<x;i++) string res; set<string> m; int H,W,dx,dy,min_len; char s[200]; string MAP[11]; bool visit[20][20]; void dfs(int x,int y,int k){ if(k==min_len){ if(m.count(string(s)))res=min(res,string(s)); m.insert(string(s)); }else if(k>min_len){ if(m.count(string(s)))res=string(s),min_len=k; m.insert(string(s)); } m.insert(string(s)); if(visit[y][x]) return; s[k]=MAP[y][x]; visit[y][x]=1; dfs((x + dx + W) % W, (y + dy + H) % H, k + 1); s[k]=0; visit[y][x]=0; } int main() { while(cin>>H>>W,H){ REP(i,H)cin>>MAP[i]; m.clear(); min_len=1; res="0"; REP(y,H)REP(x,W){ for(dx=-1;dx<=1;dx++){ for(dy=-1;dy<=1;dy++){ if(dx|dy)dfs(x,y,0); } } } cout<<res<<endl; } } ```
#include <bits/stdc++.h> using namespace std; int dy[8] = {-1, -1, -1, 0, 0, 1, 1, 1}; int dx[8] = {-1, 0, 1, -1, 1, -1, 0, 1}; int h, w; vector<string> lt; map<string, int> mp; void dfs(int sy, int sx, int y, int x, int dir, string s) { int ny = (y + dy[dir] + h) % h; int nx = (x + dx[dir] + w) % w; if (sy != ny || sx != nx) { string ns = s + lt[ny][nx]; mp[ns] ++; dfs(sy, sx, ny, nx, dir, ns); } } int main() { while (cin >> h >> w) { if (!h) break; lt.resize(h); for (int i=0; i<h; ++i) { cin >> lt[i]; } mp.clear(); for (int i=0; i<h; ++i) { for (int j=0; j<w; ++j) { for (int k=0; k<8; ++k) { string s(1, lt[i][j]); dfs(i, j, i, j, k, s); } } } string magic = ""; int len = -1; for (auto it=mp.begin(); it!=mp.end(); ++it) { if (it->second < 2) continue; if (len < (int)(it->first).size() || (len == (int)(it->first).size() && it->first < magic)) { len = (it->first).size(); magic = it->first; } } if (magic == "") { cout << 0 << endl; } else { cout << magic << endl; } } return 0; }
### Prompt Generate a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; int dy[8] = {-1, -1, -1, 0, 0, 1, 1, 1}; int dx[8] = {-1, 0, 1, -1, 1, -1, 0, 1}; int h, w; vector<string> lt; map<string, int> mp; void dfs(int sy, int sx, int y, int x, int dir, string s) { int ny = (y + dy[dir] + h) % h; int nx = (x + dx[dir] + w) % w; if (sy != ny || sx != nx) { string ns = s + lt[ny][nx]; mp[ns] ++; dfs(sy, sx, ny, nx, dir, ns); } } int main() { while (cin >> h >> w) { if (!h) break; lt.resize(h); for (int i=0; i<h; ++i) { cin >> lt[i]; } mp.clear(); for (int i=0; i<h; ++i) { for (int j=0; j<w; ++j) { for (int k=0; k<8; ++k) { string s(1, lt[i][j]); dfs(i, j, i, j, k, s); } } } string magic = ""; int len = -1; for (auto it=mp.begin(); it!=mp.end(); ++it) { if (it->second < 2) continue; if (len < (int)(it->first).size() || (len == (int)(it->first).size() && it->first < magic)) { len = (it->first).size(); magic = it->first; } } if (magic == "") { cout << 0 << endl; } else { cout << magic << endl; } } return 0; } ```
#include<bits/stdc++.h> using namespace std; #define int long long typedef pair<int,int>pint; typedef vector<int>vint; typedef vector<pint>vpint; #define pb push_back #define mp make_pair #define fi first #define se second #define all(v) (v).begin(),(v).end() #define rep(i,n) for(int i=0;i<(n);i++) #define reps(i,f,n) for(int i=(f);i<(n);i++) #define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++) template<class T,class U>inline void chmin(T &t,U f){if(t>f)t=f;} template<class T,class U>inline void chmax(T &t,U f){if(t<f)t=f;} const int dx[]={-1,0,1,-1,1,-1,0,1}; const int dy[]={-1,-1,-1,0,0,1,1,1}; int H,W; char fld[50][50]; void solve(){ rep(i,H)cin>>fld[i]; map<string,int>M; rep(i,H)rep(j,W)rep(d,8){ int y=i,x=j; string hoge; do{ hoge.pb(fld[y][x]); if(hoge.size()>1)M[hoge]++; y=(y+dy[d]+H)%H; x=(x+dx[d]+W)%W; }while(x!=j||y!=i); } string ans; each(it,M){ if(it->se<=1)continue; if(ans.size()<it->fi.size())ans=it->fi; else if(ans.size()==it->fi.size())chmin(ans,it->fi); } if(ans=="")cout<<0<<endl; else cout<<ans<<endl; } signed main(){ while(cin>>H>>W,H||W)solve(); return 0; }
### Prompt In cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<bits/stdc++.h> using namespace std; #define int long long typedef pair<int,int>pint; typedef vector<int>vint; typedef vector<pint>vpint; #define pb push_back #define mp make_pair #define fi first #define se second #define all(v) (v).begin(),(v).end() #define rep(i,n) for(int i=0;i<(n);i++) #define reps(i,f,n) for(int i=(f);i<(n);i++) #define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++) template<class T,class U>inline void chmin(T &t,U f){if(t>f)t=f;} template<class T,class U>inline void chmax(T &t,U f){if(t<f)t=f;} const int dx[]={-1,0,1,-1,1,-1,0,1}; const int dy[]={-1,-1,-1,0,0,1,1,1}; int H,W; char fld[50][50]; void solve(){ rep(i,H)cin>>fld[i]; map<string,int>M; rep(i,H)rep(j,W)rep(d,8){ int y=i,x=j; string hoge; do{ hoge.pb(fld[y][x]); if(hoge.size()>1)M[hoge]++; y=(y+dy[d]+H)%H; x=(x+dx[d]+W)%W; }while(x!=j||y!=i); } string ans; each(it,M){ if(it->se<=1)continue; if(ans.size()<it->fi.size())ans=it->fi; else if(ans.size()==it->fi.size())chmin(ans,it->fi); } if(ans=="")cout<<0<<endl; else cout<<ans<<endl; } signed main(){ while(cin>>H>>W,H||W)solve(); return 0; } ```
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int h, w; int dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; int dx[8] = {0, 1, 1, 1, 0, -1, -1, -1}; bool vis[10][20]; char dat[10][20]; vector<string> str; void calc(int y, int x, int d){ fill(vis[0], vis[10], false); string path; int ny = y; int nx = x; while(!vis[ny][nx]){ vis[ny][nx] = true; path.push_back(dat[ny][nx]); ny = (ny + dy[d] + h) % h; nx = (nx + dx[d] + w) % w; } if(path.size() > 1) str.push_back(path); } int comp(string& a, string& b){ int size = min(a.size(), b.size()); for(int i=0;i<size;i++) if(a[i] != b[i]) return i; return size; } int main(){ while(cin >> h >> w && (h|w)){ str.clear(); for(int i=0;i<h;i++) for(int j=0;j<w;j++) cin >> dat[i][j]; for(int i=0;i<h;i++) for(int j=0;j<w;j++) for(int k=0;k<8;k++) calc(i, j, k); sort(str.begin(), str.end()); int ans = 0, id; for(int i=1;i<str.size();i++){ int tmp = comp(str[i-1], str[i]); if(ans < tmp){ ans = tmp; id = i; } } if(ans > 1) cout << str[id].substr(0, ans) << endl; else cout << 0 << endl; } }
### Prompt Create a solution in CPP for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int h, w; int dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; int dx[8] = {0, 1, 1, 1, 0, -1, -1, -1}; bool vis[10][20]; char dat[10][20]; vector<string> str; void calc(int y, int x, int d){ fill(vis[0], vis[10], false); string path; int ny = y; int nx = x; while(!vis[ny][nx]){ vis[ny][nx] = true; path.push_back(dat[ny][nx]); ny = (ny + dy[d] + h) % h; nx = (nx + dx[d] + w) % w; } if(path.size() > 1) str.push_back(path); } int comp(string& a, string& b){ int size = min(a.size(), b.size()); for(int i=0;i<size;i++) if(a[i] != b[i]) return i; return size; } int main(){ while(cin >> h >> w && (h|w)){ str.clear(); for(int i=0;i<h;i++) for(int j=0;j<w;j++) cin >> dat[i][j]; for(int i=0;i<h;i++) for(int j=0;j<w;j++) for(int k=0;k<8;k++) calc(i, j, k); sort(str.begin(), str.end()); int ans = 0, id; for(int i=1;i<str.size();i++){ int tmp = comp(str[i-1], str[i]); if(ans < tmp){ ans = tmp; id = i; } } if(ans > 1) cout << str[id].substr(0, ans) << endl; else cout << 0 << endl; } } ```
#include <bits/stdc++.h> using namespace std; long long int dx[] = { 0,1,1,1,0,-1,-1,-1 }; long long int dy[] = { 1,1,0,-1,-1,-1,0,1 }; int main() { long long int M , N; while(cin >> M >> N , M || N) { vector<vector<char>>D(M , vector<char>(N)); set<string>SS; string ans; for(size_t i = 0; i < M; i++) { for(size_t j = 0; j < N; j++) { cin >> D[i][j]; } } for(long long int i = 0; i < M; i++) { for(long long int j = 0; j < N; j++) { long long int startx = j , starty = i; for(long long int k = 0; k < 8; k++) { long long int p = 1; string s; s.push_back(D[starty][startx]); while(!( ( startx + p*dx[k] + N * 2000 ) % N == startx && ( starty + p*dy[k] + M * 2000 ) % M == starty )) { s.push_back(D[( starty + p*dy[k] + M * 2000 ) % M][( startx + p*dx[k] + N * 2000 ) % N]); if(s.length() >= ans.length()) { auto s2 = s; reverse(s2.begin() , s2.end()); if(s2 <= s) { if(SS.find(s2) != SS.end() && ( ans.length() < s2.length() || ans > s2 )) { ans = s2; } else { SS.insert(s2); } } } p++; } } } } if(ans.length() <= 1) { cout << 0 << endl; } else { cout << ans << endl; } } }
### Prompt Please create a solution in CPP to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int dx[] = { 0,1,1,1,0,-1,-1,-1 }; long long int dy[] = { 1,1,0,-1,-1,-1,0,1 }; int main() { long long int M , N; while(cin >> M >> N , M || N) { vector<vector<char>>D(M , vector<char>(N)); set<string>SS; string ans; for(size_t i = 0; i < M; i++) { for(size_t j = 0; j < N; j++) { cin >> D[i][j]; } } for(long long int i = 0; i < M; i++) { for(long long int j = 0; j < N; j++) { long long int startx = j , starty = i; for(long long int k = 0; k < 8; k++) { long long int p = 1; string s; s.push_back(D[starty][startx]); while(!( ( startx + p*dx[k] + N * 2000 ) % N == startx && ( starty + p*dy[k] + M * 2000 ) % M == starty )) { s.push_back(D[( starty + p*dy[k] + M * 2000 ) % M][( startx + p*dx[k] + N * 2000 ) % N]); if(s.length() >= ans.length()) { auto s2 = s; reverse(s2.begin() , s2.end()); if(s2 <= s) { if(SS.find(s2) != SS.end() && ( ans.length() < s2.length() || ans > s2 )) { ans = s2; } else { SS.insert(s2); } } } p++; } } } } if(ans.length() <= 1) { cout << 0 << endl; } else { cout << ans << endl; } } } ```
#include <iostream> #include <fstream> #include <cstdio> #include <cmath> #include <vector> #include <cstring> #include <string> #include <set> #include <map> #include <stack> #include <queue> #include <algorithm> using namespace std; #define REP(i,n) for(int i=0; i<n; ++i) #define FOR(i,a,b) for(int i=a; i<=b; ++i) #define FORR(i,a,b) for (int i=a; i>=b; --i) #define pi M_PI typedef long long ll; typedef vector<int> VI; typedef vector<ll> VL; typedef vector<VI> VVI; typedef pair<int,int> P; typedef pair<ll,ll> PL; int mod(int x, int y){ return x % y + (x < 0 ? y : 0); } int main() { int w, h; int dx[] = {1,1,1,0,0,0,-1,-1,-1}, dy[] = {1,0,-1,1,0,-1,1,0,-1}; while (cin >> h >> w && w){ vector<string> s(h); REP(i,h) cin >> s[i]; map<string, int> mp; string ans; REP(si,h) REP(sj,w) REP(k,9){ string res; res += s[si][sj]; for (int i=mod(si+dx[k],h), j=mod(sj+dy[k],w); i!=si || j!=sj; i=mod(i+dx[k],h), j=mod(j+dy[k],w)){ res += s[i][j]; if (mp[res]){ if (res.length() > ans.length() || (res.length() == ans.length() && res < ans)) ans = res; } mp[res] = 1; } } if (ans.length() <= 1) cout << 0 << endl; else cout << ans << endl; } return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <fstream> #include <cstdio> #include <cmath> #include <vector> #include <cstring> #include <string> #include <set> #include <map> #include <stack> #include <queue> #include <algorithm> using namespace std; #define REP(i,n) for(int i=0; i<n; ++i) #define FOR(i,a,b) for(int i=a; i<=b; ++i) #define FORR(i,a,b) for (int i=a; i>=b; --i) #define pi M_PI typedef long long ll; typedef vector<int> VI; typedef vector<ll> VL; typedef vector<VI> VVI; typedef pair<int,int> P; typedef pair<ll,ll> PL; int mod(int x, int y){ return x % y + (x < 0 ? y : 0); } int main() { int w, h; int dx[] = {1,1,1,0,0,0,-1,-1,-1}, dy[] = {1,0,-1,1,0,-1,1,0,-1}; while (cin >> h >> w && w){ vector<string> s(h); REP(i,h) cin >> s[i]; map<string, int> mp; string ans; REP(si,h) REP(sj,w) REP(k,9){ string res; res += s[si][sj]; for (int i=mod(si+dx[k],h), j=mod(sj+dy[k],w); i!=si || j!=sj; i=mod(i+dx[k],h), j=mod(j+dy[k],w)){ res += s[i][j]; if (mp[res]){ if (res.length() > ans.length() || (res.length() == ans.length() && res < ans)) ans = res; } mp[res] = 1; } } if (ans.length() <= 1) cout << 0 << endl; else cout << ans << endl; } return 0; } ```
#include <stdio.h> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <vector> #include <set> #include <string> #include <iostream> typedef long long int ll; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000001 using namespace std; int div_row[8] = {-1,-1,-1,0,0,1,1,1},div_col[8] = {-1,0,1,-1,1,-1,0,1},H,W; int main(){ int work_row,work_col,max_length; char table[10][21]; string ans; set<string> SPELL; while(true){ cin >> H >> W; if(H == 0 && W == 0)break; SPELL.clear(); ans = "0"; for(int i = 0; i < H; i++){ for(int k = 0; k < W; k++)cin >>table[i][k]; } max_length = 2; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ for(int a = 0; a < 8; a++){ string work; work += table[row][col]; work_row = (row + div_row[a]+H)%H; work_col = (col + div_col[a]+W)%W; while(work_row != row || work_col != col){ work += table[work_row][work_col]; if(SPELL.find(work) != SPELL.end()){ if(work.length() > max_length){ max_length = work.length(); ans = work; }else if(work.length() == max_length){ if(work < ans){ ans = work; } } }else{ SPELL.insert(work); } work_row = (work_row + div_row[a]+H)%H; work_col = (work_col + div_col[a]+W)%W; } } } } cout << ans << endl; } return 0; }
### Prompt Create a solution in cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <stdio.h> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <vector> #include <set> #include <string> #include <iostream> typedef long long int ll; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000001 using namespace std; int div_row[8] = {-1,-1,-1,0,0,1,1,1},div_col[8] = {-1,0,1,-1,1,-1,0,1},H,W; int main(){ int work_row,work_col,max_length; char table[10][21]; string ans; set<string> SPELL; while(true){ cin >> H >> W; if(H == 0 && W == 0)break; SPELL.clear(); ans = "0"; for(int i = 0; i < H; i++){ for(int k = 0; k < W; k++)cin >>table[i][k]; } max_length = 2; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ for(int a = 0; a < 8; a++){ string work; work += table[row][col]; work_row = (row + div_row[a]+H)%H; work_col = (col + div_col[a]+W)%W; while(work_row != row || work_col != col){ work += table[work_row][work_col]; if(SPELL.find(work) != SPELL.end()){ if(work.length() > max_length){ max_length = work.length(); ans = work; }else if(work.length() == max_length){ if(work < ans){ ans = work; } } }else{ SPELL.insert(work); } work_row = (work_row + div_row[a]+H)%H; work_col = (work_col + div_col[a]+W)%W; } } } } cout << ans << endl; } return 0; } ```
#include <cstdio> #include <iostream> #include <cmath> #include <ctype.h> #include <string> #include <sstream> #include <iostream> #include <algorithm> #include <cstdlib> #include <map> #include <queue> #include <utility> #include <vector> #include <set> #include <list> #include <cstring> using namespace std; int w, h; string s[21]; string solve() { vector<string> result; int cnt = 0, wcnt = 0, hcnt = 0; int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ // ???????????????s[i][j] for(int k = 0; k < 8; k++){ string tmp = ""; int sx = i, sy = j; while(!(sx == i && sy == j) || tmp.length() == 0){ tmp += s[sx][sy]; // cout << tmp << endl; sx += dx[k]; sy += dy[k]; if(sx >= h) sx = 0; if(sy >= w) sy = 0; if(sx < 0) sx = h - 1; if(sy < 0) sy = w - 1; } result.push_back(tmp); } } } sort(result.begin(), result.end()); string ans = ""; for(int i = 0; i < result.size() - 1; i++){ // cout << result[i] << endl; if(result[i].length() < ans.length()) continue; int cnt = 0; string nowans = ""; while(cnt < min(result[i].length(), result[i + 1].length())){ if(result[i][cnt] == result[i + 1][cnt]){ nowans += result[i][cnt]; cnt++; } else { break; } } if(nowans.length() > ans.length()) ans = nowans; } if(ans.length() < 2) return "0"; else return ans; } int main() { while(1){ cin >> h >> w; if(h == 0 && w == 0) break; for(int i = 0; i < h; i++){ cin >> s[i]; } cout << solve() << endl; } return 0; }
### Prompt Create a solution in CPP for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstdio> #include <iostream> #include <cmath> #include <ctype.h> #include <string> #include <sstream> #include <iostream> #include <algorithm> #include <cstdlib> #include <map> #include <queue> #include <utility> #include <vector> #include <set> #include <list> #include <cstring> using namespace std; int w, h; string s[21]; string solve() { vector<string> result; int cnt = 0, wcnt = 0, hcnt = 0; int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ // ???????????????s[i][j] for(int k = 0; k < 8; k++){ string tmp = ""; int sx = i, sy = j; while(!(sx == i && sy == j) || tmp.length() == 0){ tmp += s[sx][sy]; // cout << tmp << endl; sx += dx[k]; sy += dy[k]; if(sx >= h) sx = 0; if(sy >= w) sy = 0; if(sx < 0) sx = h - 1; if(sy < 0) sy = w - 1; } result.push_back(tmp); } } } sort(result.begin(), result.end()); string ans = ""; for(int i = 0; i < result.size() - 1; i++){ // cout << result[i] << endl; if(result[i].length() < ans.length()) continue; int cnt = 0; string nowans = ""; while(cnt < min(result[i].length(), result[i + 1].length())){ if(result[i][cnt] == result[i + 1][cnt]){ nowans += result[i][cnt]; cnt++; } else { break; } } if(nowans.length() > ans.length()) ans = nowans; } if(ans.length() < 2) return "0"; else return ans; } int main() { while(1){ cin >> h >> w; if(h == 0 && w == 0) break; for(int i = 0; i < h; i++){ cin >> s[i]; } cout << solve() << endl; } return 0; } ```
#include <map> #include <vector> #include <iostream> #include <cstring> using namespace std; int m[29][29]; int main(){ string s,t; int h,w,i,j,x,y; for(;cin>>h>>w,h;cout<<s<<endl){ vector<string>v; for(i=0;i<h;i++)cin>>s,v.push_back(s); s="0"; map<string,int>M; for(i=0;i<h;i++)for(j=0;j<w;j++)for(x=-1;x<=1;x++)for(y=-1;y<=1;y++){ if(x==0&&y==0)continue; memset(m,0,sizeof(m)); int Y=i,X=j; t=v[Y][X],m[Y][X]=1;X=(X+x+w)%w,Y=(Y+y+h)%h; for(;!m[Y][X];X=(X+x+w)%w,Y=(Y+y+h)%h){ t+=v[Y][X],m[Y][X]=1; if(++M[t]>1 && (s.size()<t.size()||(s.size()==t.size()&&s>t)))s=t; } } } }
### Prompt Generate a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <map> #include <vector> #include <iostream> #include <cstring> using namespace std; int m[29][29]; int main(){ string s,t; int h,w,i,j,x,y; for(;cin>>h>>w,h;cout<<s<<endl){ vector<string>v; for(i=0;i<h;i++)cin>>s,v.push_back(s); s="0"; map<string,int>M; for(i=0;i<h;i++)for(j=0;j<w;j++)for(x=-1;x<=1;x++)for(y=-1;y<=1;y++){ if(x==0&&y==0)continue; memset(m,0,sizeof(m)); int Y=i,X=j; t=v[Y][X],m[Y][X]=1;X=(X+x+w)%w,Y=(Y+y+h)%h; for(;!m[Y][X];X=(X+x+w)%w,Y=(Y+y+h)%h){ t+=v[Y][X],m[Y][X]=1; if(++M[t]>1 && (s.size()<t.size()||(s.size()==t.size()&&s>t)))s=t; } } } } ```
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> using namespace std; #define rep(i, n) for(int i = 0 ; i < n ; i++) const int dx[] = {0, 1, 0, -1, 1, 1, -1, -1}; const int dy[] = {1, 0, -1, 0, 1, -1, 1, -1}; int H, W; char field[11][21]; map<string, int> v; void solve(int x, int y){ rep(i, 8){ string s = ""; s += field[y][x]; bool used[11][21]; memset(used, false, sizeof(used)); used[y][x] = true; int nx = x+dx[i], ny = y+dy[i]; while(true){ if(nx < 0) nx = W-1; else if(nx >= W) nx = 0; if(ny < 0) ny = H-1; else if(ny >= H) ny = 0; if(used[ny][nx]) break; used[ny][nx] = true; s += field[ny][nx]; nx += dx[i], ny += dy[i]; if(s.size() >= 2) v[s]++; } } } int main(){ while(cin >> H >> W, H|W){ v.clear(); rep(i, H) cin >> field[i]; rep(i, H) rep(j, W) solve(j, i); string ans = ""; int L = 0; for(map<string, int>::iterator it = v.begin() ; it != v.end() ; it++){ if(it->second < 2) continue; if(it->first.size() > L){ L = it->first.size(); ans = it->first; } else if(it->first.size() == L && ans > it->first) ans = it->first; } if(ans.size() == 0) cout << "0" << endl; else cout << ans << endl; } return 0; }
### Prompt Generate a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> using namespace std; #define rep(i, n) for(int i = 0 ; i < n ; i++) const int dx[] = {0, 1, 0, -1, 1, 1, -1, -1}; const int dy[] = {1, 0, -1, 0, 1, -1, 1, -1}; int H, W; char field[11][21]; map<string, int> v; void solve(int x, int y){ rep(i, 8){ string s = ""; s += field[y][x]; bool used[11][21]; memset(used, false, sizeof(used)); used[y][x] = true; int nx = x+dx[i], ny = y+dy[i]; while(true){ if(nx < 0) nx = W-1; else if(nx >= W) nx = 0; if(ny < 0) ny = H-1; else if(ny >= H) ny = 0; if(used[ny][nx]) break; used[ny][nx] = true; s += field[ny][nx]; nx += dx[i], ny += dy[i]; if(s.size() >= 2) v[s]++; } } } int main(){ while(cin >> H >> W, H|W){ v.clear(); rep(i, H) cin >> field[i]; rep(i, H) rep(j, W) solve(j, i); string ans = ""; int L = 0; for(map<string, int>::iterator it = v.begin() ; it != v.end() ; it++){ if(it->second < 2) continue; if(it->first.size() > L){ L = it->first.size(); ans = it->first; } else if(it->first.size() == L && ans > it->first) ans = it->first; } if(ans.size() == 0) cout << "0" << endl; else cout << ans << endl; } return 0; } ```
#include <iostream> #include <algorithm> #include <string> #include <map> #include <vector> using namespace std; const int MAX_H = 11; const int MAX_W = 21; map<string, int> M; vector<string> V; int H, W; char G[MAX_H][MAX_W]; bool compare(const string &a, const string &b) { if(a.size() != b.size()) return a.size() > b.size(); return a < b; } string solve() { V.clear(); M.clear(); for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { for(int dx = -1; dx <= 1; ++dx) { for(int dy = -1; dy <= 1; ++dy) { if(dx == 0 && dy == 0) continue; int x = j; int y = i; string s = ""; do { s += G[y][x]; if(s.size() >= 2 && ++M[s] == 2) { V.push_back(s); } x = (x+dx+W)%W; y = (y+dy+H)%H; } while(!(x == j && y == i)); } } } } if(V.size() == 0) return "0"; sort(V.begin(), V.end(), compare); return V[0]; } int main() { while(cin >> H >> W && (H | W)) { for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { cin >> G[i][j]; } } cout << solve() << endl; } return 0; }
### Prompt Develop a solution in cpp to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <algorithm> #include <string> #include <map> #include <vector> using namespace std; const int MAX_H = 11; const int MAX_W = 21; map<string, int> M; vector<string> V; int H, W; char G[MAX_H][MAX_W]; bool compare(const string &a, const string &b) { if(a.size() != b.size()) return a.size() > b.size(); return a < b; } string solve() { V.clear(); M.clear(); for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { for(int dx = -1; dx <= 1; ++dx) { for(int dy = -1; dy <= 1; ++dy) { if(dx == 0 && dy == 0) continue; int x = j; int y = i; string s = ""; do { s += G[y][x]; if(s.size() >= 2 && ++M[s] == 2) { V.push_back(s); } x = (x+dx+W)%W; y = (y+dy+H)%H; } while(!(x == j && y == i)); } } } } if(V.size() == 0) return "0"; sort(V.begin(), V.end(), compare); return V[0]; } int main() { while(cin >> H >> W && (H | W)) { for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { cin >> G[i][j]; } } cout << solve() << endl; } return 0; } ```
#include <iostream> #include <string> #include <map> using namespace std; int main(){ int h,w; string s[10],t; map<string,int> v; while(1){ cin>>h>>w; if(!h&&!w) break; for(int i=0;i<h;i++) cin>>s[i]; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=-1;k<=1;k++){ for(int l=-1;l<=1;l++){ if(!k&&!l) continue; int y=i,x=j; t=""; t+=s[y][x]; while(1){ y+=k; x+=l; if(y<0) y+=h; if(x<0) x+=w; if(h<=y) y-=h; if(w<=x) x-=w; if(y==i&&x==j) break; t+=s[y][x]; if(v.find(t)!=v.end()) v[t]++; else v.insert(make_pair(t,0)); } } } } } int ans=0; for(map<string,int>::iterator it=v.begin();it!=v.end();it++){ string z=it->first; if(it->second>0&&ans<z.size()) ans=z.size(); } if(ans>=2){ for(map<string,int>::iterator it=v.begin();it!=v.end();it++) if(it->second>0&&ans==it->first.size()){ cout<<it->first<<endl; break; } }else cout<<0<<endl; v.clear(); } return 0; }
### Prompt Your task is to create a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <map> using namespace std; int main(){ int h,w; string s[10],t; map<string,int> v; while(1){ cin>>h>>w; if(!h&&!w) break; for(int i=0;i<h;i++) cin>>s[i]; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=-1;k<=1;k++){ for(int l=-1;l<=1;l++){ if(!k&&!l) continue; int y=i,x=j; t=""; t+=s[y][x]; while(1){ y+=k; x+=l; if(y<0) y+=h; if(x<0) x+=w; if(h<=y) y-=h; if(w<=x) x-=w; if(y==i&&x==j) break; t+=s[y][x]; if(v.find(t)!=v.end()) v[t]++; else v.insert(make_pair(t,0)); } } } } } int ans=0; for(map<string,int>::iterator it=v.begin();it!=v.end();it++){ string z=it->first; if(it->second>0&&ans<z.size()) ans=z.size(); } if(ans>=2){ for(map<string,int>::iterator it=v.begin();it!=v.end();it++) if(it->second>0&&ans==it->first.size()){ cout<<it->first<<endl; break; } }else cout<<0<<endl; v.clear(); } return 0; } ```
#include<bits/stdc++.h> #define range(i,a,b) for(int i = (a); i < (b); i++) #define rep(i,b) for(int i = 0; i < (b); i++) #define all(a) (a).begin(), (a).end() #define debug(x) cout << "debug " << x << endl; const int INF = 100000000; using namespace std; string m[1000]; string ans; int h, w; map<string, int> msi; static const int dy[8] = {0,-1,-1,-1,0,1,1,1}; static const int dx[8] = {1,1,0,-1,-1,-1,0,1}; string big(string a, string b){ if(a.size() > b.size()) return a; else if(a.size() < b.size()) return b; else{ if(a < b) return a; else return b; } } void search(int y, int x){ rep(i,8){ string s; int j = 0; while(true){ s += m[y + dy[i] * j][x + dx[i] * j]; msi[s]++; if(msi[s] == 2){ ans = big(ans, s); } j++; if(dy[i] * j % h == 0 && dx[i] * j % w == 0) break; } } } int main(){ while(cin >> h >> w, h||w){ rep(i,1000) m[i] = ""; ans = ""; msi.clear(); rep(i,h){ string s; cin >> s; rep(j,50) rep(k,50) m[i + j * h]+=s; } for(int i = h * 25; i < h * 26; i++){ for(int j = w * 25; j < w * 26; j++){ search(i,j); } } if(ans.size() < 2 ) cout << 0 << endl; else cout << ans << endl; } }
### Prompt Generate a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<bits/stdc++.h> #define range(i,a,b) for(int i = (a); i < (b); i++) #define rep(i,b) for(int i = 0; i < (b); i++) #define all(a) (a).begin(), (a).end() #define debug(x) cout << "debug " << x << endl; const int INF = 100000000; using namespace std; string m[1000]; string ans; int h, w; map<string, int> msi; static const int dy[8] = {0,-1,-1,-1,0,1,1,1}; static const int dx[8] = {1,1,0,-1,-1,-1,0,1}; string big(string a, string b){ if(a.size() > b.size()) return a; else if(a.size() < b.size()) return b; else{ if(a < b) return a; else return b; } } void search(int y, int x){ rep(i,8){ string s; int j = 0; while(true){ s += m[y + dy[i] * j][x + dx[i] * j]; msi[s]++; if(msi[s] == 2){ ans = big(ans, s); } j++; if(dy[i] * j % h == 0 && dx[i] * j % w == 0) break; } } } int main(){ while(cin >> h >> w, h||w){ rep(i,1000) m[i] = ""; ans = ""; msi.clear(); rep(i,h){ string s; cin >> s; rep(j,50) rep(k,50) m[i + j * h]+=s; } for(int i = h * 25; i < h * 26; i++){ for(int j = w * 25; j < w * 26; j++){ search(i,j); } } if(ans.size() < 2 ) cout << 0 << endl; else cout << ans << endl; } } ```
#include<iostream> #include<map> using namespace std; int gcd(int a,int b){return b?gcd(b,a%b):a;} int lcm(int a,int b){return a/gcd(a,b)*b;} int main(){ int h,w; string g[10]; int dx[] = {0,1,1,1,0,-1,-1,-1},dy[] ={-1,-1,0,1,1,1,0,-1}; int lm; while(cin>> h >> w &&(h||w)){ for(int i=0;i<h;i++)cin >> g[i]; map<string,int> m; for(int i=0;i<h;i++) for(int j=0;j<w;j++) for(int k=0;k<8;k++){ string tmp; tmp += g[i][j]; int sx = j,sy = i; if(k&1)lm = lcm(h,w); else if(!(k%4))lm = h; else lm = w; for(int t=1;t<lm;t++){ sx = (sx+w+dx[k])%w; sy = (sy+h+dy[k])%h; tmp += g[sy][sx]; m[tmp]++; } } string ans = "A"; map<string,int>::iterator ite; for(ite=m.begin();ite!=m.end();ite++) if((*ite).second>1){ string tmp = (*ite).first; if(ans.size()<tmp.size() || (ans.size()==tmp.size()&&ans>tmp))ans = tmp; } if(ans.size()>1)cout << ans << endl; else cout << 0 << endl; } }
### Prompt Generate a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<map> using namespace std; int gcd(int a,int b){return b?gcd(b,a%b):a;} int lcm(int a,int b){return a/gcd(a,b)*b;} int main(){ int h,w; string g[10]; int dx[] = {0,1,1,1,0,-1,-1,-1},dy[] ={-1,-1,0,1,1,1,0,-1}; int lm; while(cin>> h >> w &&(h||w)){ for(int i=0;i<h;i++)cin >> g[i]; map<string,int> m; for(int i=0;i<h;i++) for(int j=0;j<w;j++) for(int k=0;k<8;k++){ string tmp; tmp += g[i][j]; int sx = j,sy = i; if(k&1)lm = lcm(h,w); else if(!(k%4))lm = h; else lm = w; for(int t=1;t<lm;t++){ sx = (sx+w+dx[k])%w; sy = (sy+h+dy[k])%h; tmp += g[sy][sx]; m[tmp]++; } } string ans = "A"; map<string,int>::iterator ite; for(ite=m.begin();ite!=m.end();ite++) if((*ite).second>1){ string tmp = (*ite).first; if(ans.size()<tmp.size() || (ans.size()==tmp.size()&&ans>tmp))ans = tmp; } if(ans.size()>1)cout << ans << endl; else cout << 0 << endl; } } ```
#include <cstdio> #include <string> #include <algorithm> #include <set> #include <vector> using namespace std; #define REP(i,x)for(int i=0;i<x;i++) string res; int H,W,dx,dy,min_len; char s[200]; char MAP[11][22]; bool visit[20][20]; vector<string> ss; void dfs(int x,int y,int k){ if(visit[y][x]){ ss.push_back(string(s)); return; } s[k]=MAP[y][x]; visit[y][x]=1; dfs((x + dx + W) % W, (y + dy + H) % H, k + 1); s[k]=0; visit[y][x]=0; } int main() { while(scanf("%d%d",&H,&W),H){ REP(i,H)scanf("%s",MAP[i]); ss.clear(); min_len=1; res="0"; REP(y,H)REP(x,W){ for(dx=-1;dx<=1;dx++){ for(dy=-1;dy<=1;dy++){ if(dx|dy)dfs(x,y,0); } } } string res = "0"; sort(ss.begin(),ss.end()); REP(i,ss.size()-1){ int len = 0; if(min(ss[i].size(),ss[i+1].size()) < len)continue; REP(k,min(ss[i].size(),ss[i+1].size())){ if(ss[i][k]==ss[i+1][k])len++; else break; } if(len < res.size())continue; if(res.size() == len){ res = min(res, ss[i].substr(0,len)); }else{ res = ss[i].substr(0, len); } } puts(res.c_str()); } }
### Prompt Your task is to create a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstdio> #include <string> #include <algorithm> #include <set> #include <vector> using namespace std; #define REP(i,x)for(int i=0;i<x;i++) string res; int H,W,dx,dy,min_len; char s[200]; char MAP[11][22]; bool visit[20][20]; vector<string> ss; void dfs(int x,int y,int k){ if(visit[y][x]){ ss.push_back(string(s)); return; } s[k]=MAP[y][x]; visit[y][x]=1; dfs((x + dx + W) % W, (y + dy + H) % H, k + 1); s[k]=0; visit[y][x]=0; } int main() { while(scanf("%d%d",&H,&W),H){ REP(i,H)scanf("%s",MAP[i]); ss.clear(); min_len=1; res="0"; REP(y,H)REP(x,W){ for(dx=-1;dx<=1;dx++){ for(dy=-1;dy<=1;dy++){ if(dx|dy)dfs(x,y,0); } } } string res = "0"; sort(ss.begin(),ss.end()); REP(i,ss.size()-1){ int len = 0; if(min(ss[i].size(),ss[i+1].size()) < len)continue; REP(k,min(ss[i].size(),ss[i+1].size())){ if(ss[i][k]==ss[i+1][k])len++; else break; } if(len < res.size())continue; if(res.size() == len){ res = min(res, ss[i].substr(0,len)); }else{ res = ss[i].substr(0, len); } } puts(res.c_str()); } } ```
#include <iostream> #include <vector> #include <algorithm> #include <cstring> //#include <unordered_set> #include <set> using namespace std; char field[1001][1001]; bool used[1001][1001]; int main(){ int H,W; while(cin>>H>>W&&(H|W)){ for(int i=0;i<H;i++) for(int j=0;j<W;j++) cin>>field[i][j]; vector<string> vs; for(int dy=-1;dy<=1;dy++){ for(int dx=-1;dx<=1;dx++){ if(dy==0&&dx==0)continue; memset(used,0,sizeof(used)); for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(!(i==0||j==0||i==H-1||j==W-1))continue; int cx=j; int cy=i; string s; if(used[cy][cx])continue; while(1){ used[cy][cx]=true; s+=field[cy][cx]; cy+=dy;cx+=dx; cy=(cy+H)%H; cx=(cx+W)%W; if(used[cy][cx])break; } vs.push_back(s); //cout<<s<<endl; } } } } //unordered_set<string> us; set<string> us; string cand; for(int i=0;i<(int)vs.size();i++){ for(int j=0;j<(int)vs[i].size();j++){ for(int k=1;k<=(int)vs[i].size();k++){ string s; for(int l=0;l<k;l++){ s+=vs[i][(j+l)%vs[i].size()]; } if(us.count(s)==1){ if(cand==""||cand.size()<s.size()) cand=s; else if(cand.size()==s.size()&&cand>s) cand=s; } else if(us.count(s)==0) us.insert(s); } } } if(cand.size()>1)cout<<cand<<endl; else cout<<0<<endl; } return 0; }
### Prompt In cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <algorithm> #include <cstring> //#include <unordered_set> #include <set> using namespace std; char field[1001][1001]; bool used[1001][1001]; int main(){ int H,W; while(cin>>H>>W&&(H|W)){ for(int i=0;i<H;i++) for(int j=0;j<W;j++) cin>>field[i][j]; vector<string> vs; for(int dy=-1;dy<=1;dy++){ for(int dx=-1;dx<=1;dx++){ if(dy==0&&dx==0)continue; memset(used,0,sizeof(used)); for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(!(i==0||j==0||i==H-1||j==W-1))continue; int cx=j; int cy=i; string s; if(used[cy][cx])continue; while(1){ used[cy][cx]=true; s+=field[cy][cx]; cy+=dy;cx+=dx; cy=(cy+H)%H; cx=(cx+W)%W; if(used[cy][cx])break; } vs.push_back(s); //cout<<s<<endl; } } } } //unordered_set<string> us; set<string> us; string cand; for(int i=0;i<(int)vs.size();i++){ for(int j=0;j<(int)vs[i].size();j++){ for(int k=1;k<=(int)vs[i].size();k++){ string s; for(int l=0;l<k;l++){ s+=vs[i][(j+l)%vs[i].size()]; } if(us.count(s)==1){ if(cand==""||cand.size()<s.size()) cand=s; else if(cand.size()==s.size()&&cand>s) cand=s; } else if(us.count(s)==0) us.insert(s); } } } if(cand.size()>1)cout<<cand<<endl; else cout<<0<<endl; } return 0; } ```
#include <iostream> #include <map> #include <string> #include <algorithm> #define MAX_H 10 using namespace std; map<string, int> mp; int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; string s[MAX_H]; int h, w; int mystrcmp(string a, string b) { if (a.size() > b.size()) return 1; if (a.size() < b.size()) return -1; for (int i = 0; i < a.size(); i++) { if (a[i] < b[i]) return 1; if (a[i] > b[i]) return -1; } return 0; } void dfs(int x, int y, int xnow, int ynow, int k, string str) { int xnext = (xnow + dx[k] + h) % h; int ynext = (ynow + dy[k] + w) % w; mp[str]++; if (x == xnext && y == ynext) return; string str2; str2.push_back(s[xnext][ynext]); dfs(x, y, xnext, ynext, k, str + str2); } int main() { while (true) { for (int i = 0; i < MAX_H; i++) { s[i].erase(); } mp.clear(); cin >> h >> w; if (h == 0 && w == 0) return 0; for (int i = 0; i < h; i++) { cin >> s[i]; } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int k = 0; k < 8; k++) { string str; str.push_back(s[i][j]); dfs(i, j, i, j, k, str); } } } string ans; for (map<string, int>::const_iterator itr = mp.begin(); itr != mp.end(); ++itr) { // cout << itr->first << " " << itr->second << endl; if (itr == mp.begin()) { ans += itr->first; continue; } if (itr->second > 1 && mystrcmp(itr->first, ans) > 0) { ans.erase(); ans += itr->first; } } if (ans.size() >= 2) cout << ans << endl; else cout << 0 << endl; } }
### Prompt Create a solution in CPP for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <map> #include <string> #include <algorithm> #define MAX_H 10 using namespace std; map<string, int> mp; int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; string s[MAX_H]; int h, w; int mystrcmp(string a, string b) { if (a.size() > b.size()) return 1; if (a.size() < b.size()) return -1; for (int i = 0; i < a.size(); i++) { if (a[i] < b[i]) return 1; if (a[i] > b[i]) return -1; } return 0; } void dfs(int x, int y, int xnow, int ynow, int k, string str) { int xnext = (xnow + dx[k] + h) % h; int ynext = (ynow + dy[k] + w) % w; mp[str]++; if (x == xnext && y == ynext) return; string str2; str2.push_back(s[xnext][ynext]); dfs(x, y, xnext, ynext, k, str + str2); } int main() { while (true) { for (int i = 0; i < MAX_H; i++) { s[i].erase(); } mp.clear(); cin >> h >> w; if (h == 0 && w == 0) return 0; for (int i = 0; i < h; i++) { cin >> s[i]; } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int k = 0; k < 8; k++) { string str; str.push_back(s[i][j]); dfs(i, j, i, j, k, str); } } } string ans; for (map<string, int>::const_iterator itr = mp.begin(); itr != mp.end(); ++itr) { // cout << itr->first << " " << itr->second << endl; if (itr == mp.begin()) { ans += itr->first; continue; } if (itr->second > 1 && mystrcmp(itr->first, ans) > 0) { ans.erase(); ans += itr->first; } } if (ans.size() >= 2) cout << ans << endl; else cout << 0 << endl; } } ```
#include<iostream> #include<map> #include<cstring> using namespace std; bool used[10][20]; int main(){ int h, w; while(cin >> h >> w, h+w){ char mat[h][w]; for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) cin >> mat[i][j]; map<string,int> cnt; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ for(int di = -1; di <= 1; di++){ for(int dj = -1; dj <= 1; dj++){ if(di == 0 && dj == 0) continue; memset(used, 0, sizeof(used)); string acc = ""; int si = i, sj = j; while(!used[si][sj]){ acc += mat[si][sj]; cnt[acc]++; used[si][sj] = true; si += di, sj += dj; si = (si + h) % h; sj = (sj + w) % w; } } } } } string ans = "0"; for(pair<string,int> p : cnt){ if(p.second > 1 && p.first.length() > ans.length()) ans = p.first; } cout << ans << endl; } return 0; }
### Prompt Construct a CPP code solution to the problem outlined: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<map> #include<cstring> using namespace std; bool used[10][20]; int main(){ int h, w; while(cin >> h >> w, h+w){ char mat[h][w]; for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) cin >> mat[i][j]; map<string,int> cnt; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ for(int di = -1; di <= 1; di++){ for(int dj = -1; dj <= 1; dj++){ if(di == 0 && dj == 0) continue; memset(used, 0, sizeof(used)); string acc = ""; int si = i, sj = j; while(!used[si][sj]){ acc += mat[si][sj]; cnt[acc]++; used[si][sj] = true; si += di, sj += dj; si = (si + h) % h; sj = (sj + w) % w; } } } } } string ans = "0"; for(pair<string,int> p : cnt){ if(p.second > 1 && p.first.length() > ans.length()) ans = p.first; } cout << ans << endl; } return 0; } ```
#include <iostream> #include <cstdio> #include <cstring> #include <sstream> #include <algorithm> #include <cmath> #include <map> #include <queue> #include <vector> #include <cstdlib> #include <string> #include <set> #include <ctime> using namespace std; int dx[8]={0,0,1,1,1,-1,-1,-1},dy[8]={1,-1,0,-1,1,0,-1,1}; string s[2000],temp; char str[30][30]; int main() { int n,m,i,j,x,y; while(scanf("%d%d",&n,&m)==2) { if(!n&&!m) break; for(i=0;i<n;i++) scanf("%s",str[i]); int num=0,l=0,ans=0,l1,l2,d; for(i=0;i<n;i++) { for(j=0;j<m;j++) { for(d=0;d<8;d++) { x=i; y=j; temp=""; temp+=str[x][y]; while(1) { x+=dx[d]; y+=dy[d]; // printf("%d %d %d %d %d\n",i,j,d,x,y); if(x>=n) x-=n; if(y>=m) y-=m; if(x<0) x+=n; if(y<0) y+=m; if(x==i&&y==j) break; temp+=str[x][y]; } s[num++]=temp; // cout<<temp<<endl; } } } sort(s,s+num); for(i=1;i<num;i++) { l1=s[i-1].size(); l2=s[i].size(); for(j=0;j<l1&&j<l2;j++) { if(s[i-1][j]!=s[i][j]) break; } if(j>l) { l=j; ans=i; } } if(l<2) printf("0\n"); else { for(i=0;i<l;i++) printf("%c",s[ans][i]); printf("\n"); } } return 0; }
### Prompt Develop a solution in cpp to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <cstdio> #include <cstring> #include <sstream> #include <algorithm> #include <cmath> #include <map> #include <queue> #include <vector> #include <cstdlib> #include <string> #include <set> #include <ctime> using namespace std; int dx[8]={0,0,1,1,1,-1,-1,-1},dy[8]={1,-1,0,-1,1,0,-1,1}; string s[2000],temp; char str[30][30]; int main() { int n,m,i,j,x,y; while(scanf("%d%d",&n,&m)==2) { if(!n&&!m) break; for(i=0;i<n;i++) scanf("%s",str[i]); int num=0,l=0,ans=0,l1,l2,d; for(i=0;i<n;i++) { for(j=0;j<m;j++) { for(d=0;d<8;d++) { x=i; y=j; temp=""; temp+=str[x][y]; while(1) { x+=dx[d]; y+=dy[d]; // printf("%d %d %d %d %d\n",i,j,d,x,y); if(x>=n) x-=n; if(y>=m) y-=m; if(x<0) x+=n; if(y<0) y+=m; if(x==i&&y==j) break; temp+=str[x][y]; } s[num++]=temp; // cout<<temp<<endl; } } } sort(s,s+num); for(i=1;i<num;i++) { l1=s[i-1].size(); l2=s[i].size(); for(j=0;j<l1&&j<l2;j++) { if(s[i-1][j]!=s[i][j]) break; } if(j>l) { l=j; ans=i; } } if(l<2) printf("0\n"); else { for(i=0;i<l;i++) printf("%c",s[ans][i]); printf("\n"); } } return 0; } ```
#include<iostream> #include<string> #include<algorithm> using namespace std; int lcm(int a,int b){ //a,b < 20だしいいよね if (a < b){ swap(a,b); } int times = a * b; int gcd,lcm; while(1){ int n; n = a % b; if(n == 0){ break;} a = b; b = n; } gcd = b; lcm = times / gcd; return lcm; } int main(){ int h,w; while(1){ cin >> h >> w ; if(h == 0 && w == 0){ break;} char donut[10][20]; for(int i=0;i<10;i++){ for(int j=0;j<20;j++){ donut[i][j] = 0; } } string code[1600]; bool much[1600]; for(int i = 0; i < 1600; i++){ code[i] = ""; much[i] = true; } //初期化… unsigned int l = lcm(w,h); //ななめの最大数 int a = 0; //strの数を数えます for(int i = 0; i < h; i++){ for(int j =0; j < w; j++){ cin >> donut[i][j]; } } //input for(int y = 0; y < h; y++){ for(int x = 0; x < w; x++){ for(int i = 0; i < h; i++){ //縦列 code[a].append(1,donut[(y + i)%h][x]); code[a+1].append(1,donut[h-(y + i)%h-1][x]); } a += 2; for(int j = 0; j < w; j++){ //横列 code[a].append(1,donut[y][(x + j)%w]); code[a+1].append(1,donut[y][w-(x+j)%w-1]);//absつけなくても0になりません! } a += 2; for(unsigned int k = 0; k < l; k++){ //ななめ code[a].append(1,donut[(y + k)%h][(x + k)%w]); code[a+1].append(1,donut[(y + k)%h][(l + x - k)%w]); code[a+2].append(1,donut[(l + y - k)%h][(x + k)%w]); code[a+3].append(1,donut[(l + y - k)%h][(l + x - k)%w]); } a += 4; } } string mag = ""; //a:strの数-1 sort(code,code+a);//nとn+1を比べます for(unsigned int i = 1; i < l; i++){ //2文字目から for(int j = a-1; j > 0; j--){ //逆順 if(much[j] == true && code[j].length() >= i+1 && code[j-1].length() >= i+1){//=を忘れていました //jのi+1文字目とj-1のi+1文字目を比べるよ if(code[j][i] != code[j-1][i]){ much[j] = false; }else{ mag = code[j]; mag.resize(i+1); } } } } if(mag == ""){ cout << "0" << endl; }else{ cout << mag << endl; } } return 0; }
### Prompt Construct a cpp code solution to the problem outlined: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<string> #include<algorithm> using namespace std; int lcm(int a,int b){ //a,b < 20だしいいよね if (a < b){ swap(a,b); } int times = a * b; int gcd,lcm; while(1){ int n; n = a % b; if(n == 0){ break;} a = b; b = n; } gcd = b; lcm = times / gcd; return lcm; } int main(){ int h,w; while(1){ cin >> h >> w ; if(h == 0 && w == 0){ break;} char donut[10][20]; for(int i=0;i<10;i++){ for(int j=0;j<20;j++){ donut[i][j] = 0; } } string code[1600]; bool much[1600]; for(int i = 0; i < 1600; i++){ code[i] = ""; much[i] = true; } //初期化… unsigned int l = lcm(w,h); //ななめの最大数 int a = 0; //strの数を数えます for(int i = 0; i < h; i++){ for(int j =0; j < w; j++){ cin >> donut[i][j]; } } //input for(int y = 0; y < h; y++){ for(int x = 0; x < w; x++){ for(int i = 0; i < h; i++){ //縦列 code[a].append(1,donut[(y + i)%h][x]); code[a+1].append(1,donut[h-(y + i)%h-1][x]); } a += 2; for(int j = 0; j < w; j++){ //横列 code[a].append(1,donut[y][(x + j)%w]); code[a+1].append(1,donut[y][w-(x+j)%w-1]);//absつけなくても0になりません! } a += 2; for(unsigned int k = 0; k < l; k++){ //ななめ code[a].append(1,donut[(y + k)%h][(x + k)%w]); code[a+1].append(1,donut[(y + k)%h][(l + x - k)%w]); code[a+2].append(1,donut[(l + y - k)%h][(x + k)%w]); code[a+3].append(1,donut[(l + y - k)%h][(l + x - k)%w]); } a += 4; } } string mag = ""; //a:strの数-1 sort(code,code+a);//nとn+1を比べます for(unsigned int i = 1; i < l; i++){ //2文字目から for(int j = a-1; j > 0; j--){ //逆順 if(much[j] == true && code[j].length() >= i+1 && code[j-1].length() >= i+1){//=を忘れていました //jのi+1文字目とj-1のi+1文字目を比べるよ if(code[j][i] != code[j-1][i]){ much[j] = false; }else{ mag = code[j]; mag.resize(i+1); } } } } if(mag == ""){ cout << "0" << endl; }else{ cout << mag << endl; } } return 0; } ```
#include <bits/stdc++.h> using namespace std; #define INF 1001000100010001000 #define MOD 1000000007 #define EPS 1e-10 #define int long long #define rep(i, N) for (int i = 0; i < N; i++) #define Rep(i, N) for (int i = 1; i < N; i++) #define For(i, a, b) for (int i = (a); i < (b); i++) #define pb push_back #define mp make_pair #define i_i pair<int, int> #define vi vector<int> #define vvi vector<vi > #define vb vector<bool> #define vvb vector<vb > #define vp vector< i_i > #define all(a) (a).begin(), (a).end() #define Int(x) int x; scanf("%lld", &x); //int dxy[5] = {0, 1, 0, -1, 0}; int dx[8] = {1, 1, 1, 0, 0, -1, -1, -1}; int dy[8] = {1, 0, -1, 1, -1, 1, 0, -1}; // assign string comp(string a, string b); signed main() { int n, m; while (cin >> n >> m, n) { vector<string> donut(n); rep(i, n) { cin >> donut[i]; } set<string> can; string ans = "z"; rep(i, n) { rep(j, m) { rep(k, 8) { vvb used(n, vb(m, false)); string spell; int x = i, y = j; while (!used[x][y]) { spell.pb(donut[x][y]); used[x][y] = true; if (can.find(spell) != can.end()) { ans = comp(ans, spell); } else { can.insert(spell); } x = (x + dx[k] + n) % n; y = (y + dy[k] + m) % m; } } } } cout << ((ans.length() > 1) ? ans : "0") << endl; } return 0; } string comp(string a, string b) { if (a.length() < b.length()) { return b; } else if (a.length() > b.length()) { return a; } else { rep(i, a.length()) { if (a[i] < b[i]) { return a; } else if (a[i] > b[i]) { return b; } } } return a; }
### Prompt Create a solution in cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define INF 1001000100010001000 #define MOD 1000000007 #define EPS 1e-10 #define int long long #define rep(i, N) for (int i = 0; i < N; i++) #define Rep(i, N) for (int i = 1; i < N; i++) #define For(i, a, b) for (int i = (a); i < (b); i++) #define pb push_back #define mp make_pair #define i_i pair<int, int> #define vi vector<int> #define vvi vector<vi > #define vb vector<bool> #define vvb vector<vb > #define vp vector< i_i > #define all(a) (a).begin(), (a).end() #define Int(x) int x; scanf("%lld", &x); //int dxy[5] = {0, 1, 0, -1, 0}; int dx[8] = {1, 1, 1, 0, 0, -1, -1, -1}; int dy[8] = {1, 0, -1, 1, -1, 1, 0, -1}; // assign string comp(string a, string b); signed main() { int n, m; while (cin >> n >> m, n) { vector<string> donut(n); rep(i, n) { cin >> donut[i]; } set<string> can; string ans = "z"; rep(i, n) { rep(j, m) { rep(k, 8) { vvb used(n, vb(m, false)); string spell; int x = i, y = j; while (!used[x][y]) { spell.pb(donut[x][y]); used[x][y] = true; if (can.find(spell) != can.end()) { ans = comp(ans, spell); } else { can.insert(spell); } x = (x + dx[k] + n) % n; y = (y + dy[k] + m) % m; } } } } cout << ((ans.length() > 1) ? ans : "0") << endl; } return 0; } string comp(string a, string b) { if (a.length() < b.length()) { return b; } else if (a.length() > b.length()) { return a; } else { rep(i, a.length()) { if (a[i] < b[i]) { return a; } else if (a[i] > b[i]) { return b; } } } return a; } ```
#include <vector> #include <iostream> #include <utility> #include <algorithm> #include <string> #include <deque> #include <tuple> #include <queue> #include <functional> #include <cmath> #include <iomanip> #include <map> //cin.sync_with_stdio(false); //streambuf using namespace std; typedef long long ll; typedef pair<int, int> pii; int main() { int h, w; while (cin >> h >> w, h) { vector<string> map(h); for (auto &a : map)cin >> a; int dx[] = { 0,0,1,1,1,-1,-1,-1 }; int dy[] = { 1,-1,0,-1,1,0,1,-1 }; vector<tuple<string, int, int, int>> buf; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int d = 0; d < 8; d++) { buf.push_back(make_tuple((string)"" + map[i][j], j, i, d)); } } } int l = 0; for (;; l++) { sort(buf.begin(), buf.end()); vector<tuple<string, int, int, int>> buf2; for (int i = 1; i < buf.size(); i++) { if (get<0>(buf[i - 1]).size() < l)continue; if (get<0>(buf[i - 1]) == get<0>(buf[i]))buf2.push_back(buf[i - 1]); for (; i<buf.size()&&get<0>(buf[i - 1]) == get<0>(buf[i]); i++)buf2.push_back(buf[i]); } if (buf2.empty())break; buf = move(buf2); for (auto &a : buf) { string str; int x, y, d; tie(str, x, y, d) = a; int x1 = ((x + dx[d]*l) % w + w) % w; int y1 = ((y + dy[d]*l) % h + h) % h; if (x1 == x && y1 == y)continue; str += map[y1][x1]; a = make_tuple(str, x, y, d); } } if (l < 3)cout << 0 << endl; else { string str = get<0>(buf[0]); cout << str.substr(0, l-1) << endl; } } return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <vector> #include <iostream> #include <utility> #include <algorithm> #include <string> #include <deque> #include <tuple> #include <queue> #include <functional> #include <cmath> #include <iomanip> #include <map> //cin.sync_with_stdio(false); //streambuf using namespace std; typedef long long ll; typedef pair<int, int> pii; int main() { int h, w; while (cin >> h >> w, h) { vector<string> map(h); for (auto &a : map)cin >> a; int dx[] = { 0,0,1,1,1,-1,-1,-1 }; int dy[] = { 1,-1,0,-1,1,0,1,-1 }; vector<tuple<string, int, int, int>> buf; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int d = 0; d < 8; d++) { buf.push_back(make_tuple((string)"" + map[i][j], j, i, d)); } } } int l = 0; for (;; l++) { sort(buf.begin(), buf.end()); vector<tuple<string, int, int, int>> buf2; for (int i = 1; i < buf.size(); i++) { if (get<0>(buf[i - 1]).size() < l)continue; if (get<0>(buf[i - 1]) == get<0>(buf[i]))buf2.push_back(buf[i - 1]); for (; i<buf.size()&&get<0>(buf[i - 1]) == get<0>(buf[i]); i++)buf2.push_back(buf[i]); } if (buf2.empty())break; buf = move(buf2); for (auto &a : buf) { string str; int x, y, d; tie(str, x, y, d) = a; int x1 = ((x + dx[d]*l) % w + w) % w; int y1 = ((y + dy[d]*l) % h + h) % h; if (x1 == x && y1 == y)continue; str += map[y1][x1]; a = make_tuple(str, x, y, d); } } if (l < 3)cout << 0 << endl; else { string str = get<0>(buf[0]); cout << str.substr(0, l-1) << endl; } } return 0; } ```
#include <iostream> #include <cstdio> #include <vector> #include <string> #include <cstring> #include <set> #include <map> #include <queue> #include <cmath> #include <algorithm> 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() int main() { int dx[8] = {-1,-1,-1,0,0,1,1,1}; int dy[8] = {-1,0,1,-1,1,-1,0,1}; int h,w; while(cin>>h>>w, h||w) { set<string> ap; char ba[h][w]; REP(i, h) { REP(j, w) { cin >> ba[i][j]; } } string ans = ""; REP(i, h) { REP(j, w) { REP(k, 8) { string str = ""; int y = i; int x = j; do { str += string(1,ba[y][x]); if(ap.find(str) != ap.end()) { // cout<<str<<endl; if(ans == "" || ans.length() < str.length() || (ans.length() == str.length() && str < ans)) ans = str; } if(str.length() > 1) ap.insert(str); y += dy[k]; x += dx[k]; if (x<0) x = w-1; if (x>=w) x = 0; if (y<0) y = h-1; if (y>=h) y = 0; //cout << k << " " << j <<" " << i << " " << x << " " << y << endl; if (i==y && j==x) break; } while(1); // cout << str << endl; } } } if(ans.length() == 0) ans = "0"; cout<<ans<<endl; } }
### Prompt Create a solution in cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <cstdio> #include <vector> #include <string> #include <cstring> #include <set> #include <map> #include <queue> #include <cmath> #include <algorithm> 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() int main() { int dx[8] = {-1,-1,-1,0,0,1,1,1}; int dy[8] = {-1,0,1,-1,1,-1,0,1}; int h,w; while(cin>>h>>w, h||w) { set<string> ap; char ba[h][w]; REP(i, h) { REP(j, w) { cin >> ba[i][j]; } } string ans = ""; REP(i, h) { REP(j, w) { REP(k, 8) { string str = ""; int y = i; int x = j; do { str += string(1,ba[y][x]); if(ap.find(str) != ap.end()) { // cout<<str<<endl; if(ans == "" || ans.length() < str.length() || (ans.length() == str.length() && str < ans)) ans = str; } if(str.length() > 1) ap.insert(str); y += dy[k]; x += dx[k]; if (x<0) x = w-1; if (x>=w) x = 0; if (y<0) y = h-1; if (y>=h) y = 0; //cout << k << " " << j <<" " << i << " " << x << " " << y << endl; if (i==y && j==x) break; } while(1); // cout << str << endl; } } } if(ans.length() == 0) ans = "0"; cout<<ans<<endl; } } ```
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <queue> #include <deque> #include <stack> #include <map> #include <set> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <cctype> using namespace std; typedef long long ll; #define REP(i,n,m) for(int i=n;i<m;i++) #define rep(i,n) REP(i,0,n) #define MAX_H (10+10) #define MAX_W (20+10) int h,w; char t[MAX_H][MAX_W]; set<string> tmp; int dx[8] = {0,1,1,1,0,-1,-1,-1}; int dy[8] = {-1,-1,0,1,1,1,0,-1}; void solve(){ tmp.clear(); string res = ""; /* rep(i,h) rep(j,w){ string s = ""; s += t[i][j]; cout << "res=" << res << endl; if(tmp.find(s) != tmp.end()){ if(s.size() > res.size()) res = s; else if(s.size() == res.size() && s < res) res = s; } else{ tmp.insert(s); } } */ rep(i,h) rep(j,w) rep(k,8){ int sx = j, sy = i; int x = j, y = i; string s = ""; s += t[y][x]; x += w+dx[k]; x %= w; y += h+dy[k]; y %= h; while(!(x == sx && y == sy)){ s += t[y][x]; x += w+dx[k]; x %= w; y += h+dy[k]; y %= h; // cout << "sx=" << sx << ",sy=" << sy << endl; // cout << "x=" << x << ",y=" << y << endl; // cout << "s=" << s << endl; if(tmp.find(s) != tmp.end()){ if(s.size() > res.size()) res = s; else if(s.size() == res.size() && s < res) res = s; } else{ tmp.insert(s); } } } if(res.size() == 0) cout << 0 << endl; else cout << res << endl; } void solve2(string s){ } int main(){ while(true){ cin >> h >> w; if(h == 0 && w == 0) break; rep(i,h) cin >> t[i]; /* if(h == 1){ s = t[0]; solve2(s); } else if(w == 1){ rep(i,h) s += t[0][i]; solve2(s); } */ solve(); } }
### Prompt Your task is to create a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <queue> #include <deque> #include <stack> #include <map> #include <set> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <cctype> using namespace std; typedef long long ll; #define REP(i,n,m) for(int i=n;i<m;i++) #define rep(i,n) REP(i,0,n) #define MAX_H (10+10) #define MAX_W (20+10) int h,w; char t[MAX_H][MAX_W]; set<string> tmp; int dx[8] = {0,1,1,1,0,-1,-1,-1}; int dy[8] = {-1,-1,0,1,1,1,0,-1}; void solve(){ tmp.clear(); string res = ""; /* rep(i,h) rep(j,w){ string s = ""; s += t[i][j]; cout << "res=" << res << endl; if(tmp.find(s) != tmp.end()){ if(s.size() > res.size()) res = s; else if(s.size() == res.size() && s < res) res = s; } else{ tmp.insert(s); } } */ rep(i,h) rep(j,w) rep(k,8){ int sx = j, sy = i; int x = j, y = i; string s = ""; s += t[y][x]; x += w+dx[k]; x %= w; y += h+dy[k]; y %= h; while(!(x == sx && y == sy)){ s += t[y][x]; x += w+dx[k]; x %= w; y += h+dy[k]; y %= h; // cout << "sx=" << sx << ",sy=" << sy << endl; // cout << "x=" << x << ",y=" << y << endl; // cout << "s=" << s << endl; if(tmp.find(s) != tmp.end()){ if(s.size() > res.size()) res = s; else if(s.size() == res.size() && s < res) res = s; } else{ tmp.insert(s); } } } if(res.size() == 0) cout << 0 << endl; else cout << res << endl; } void solve2(string s){ } int main(){ while(true){ cin >> h >> w; if(h == 0 && w == 0) break; rep(i,h) cin >> t[i]; /* if(h == 1){ s = t[0]; solve2(s); } else if(w == 1){ rep(i,h) s += t[0][i]; solve2(s); } */ solve(); } } ```
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <set> #define REP(i,a,b) for (int i = (a); i < (b); i++) #define rep(i,a) REP(i,0,a) using namespace std; int H, W; int dw[] = {1,1,0,-1,-1,-1,0,1}; int dh[] = {0,1,1,1,0,-1,-1,-1}; int main(void){ while (cin >> H >> W && H) { vector<string> S(H,""); rep(i, H) cin >> S[i]; string ans = ""; set<string> appear; rep(h, H) rep(w, W) rep(i, 8) { string s = ""; s += S[h][w]; int iw = w, ih = h; w = (w+dw[i]+W)%W; h = (h+dh[i]+H)%H; while (!(w == iw && h == ih)) { s.append(1, S[h][w]); if (s.length() >= ans.length() && appear.find(s) != appear.end()) { if (s.length() > ans.length()) ans = s; if (s.length() == ans.length()) ans = min(ans, s); } appear.insert(s); w = (w+dw[i]+W)%W; h = (h+dh[i]+H)%H; } } cout << (ans.length() > 1 ? ans:"0") << endl; } return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <vector> #include <algorithm> #include <set> #define REP(i,a,b) for (int i = (a); i < (b); i++) #define rep(i,a) REP(i,0,a) using namespace std; int H, W; int dw[] = {1,1,0,-1,-1,-1,0,1}; int dh[] = {0,1,1,1,0,-1,-1,-1}; int main(void){ while (cin >> H >> W && H) { vector<string> S(H,""); rep(i, H) cin >> S[i]; string ans = ""; set<string> appear; rep(h, H) rep(w, W) rep(i, 8) { string s = ""; s += S[h][w]; int iw = w, ih = h; w = (w+dw[i]+W)%W; h = (h+dh[i]+H)%H; while (!(w == iw && h == ih)) { s.append(1, S[h][w]); if (s.length() >= ans.length() && appear.find(s) != appear.end()) { if (s.length() > ans.length()) ans = s; if (s.length() == ans.length()) ans = min(ans, s); } appear.insert(s); w = (w+dw[i]+W)%W; h = (h+dh[i]+H)%H; } } cout << (ans.length() > 1 ? ans:"0") << endl; } return 0; } ```
#include <iostream> #include <string> #include <stdio.h> #include <set> using namespace std; #define dirmax 8 int l[2]; int dir[8][2] = { {0,1}, {1,0}, {-1,0}, {0,-1}, {1,1}, {-1,1}, {1,-1}, {-1,-1} }; string ans; void search( set<string> *v, int pos[2] , char ch[10][20]){ for(int i = 0; i < dirmax; i++) { string str; int cpos[] = { pos[0], pos[1] }; str += ch[pos[0]][pos[1]]; while( 1 ) { for(int j = 0; j < 2; j++) { cpos[j] += dir[i][j]; if( cpos[j] < 0 ) cpos[j] = l[j] - 1; if( cpos[j] >= l[j] ) cpos[j] = 0; } if( cpos[0] == pos[0] && cpos[1] == pos[1] ) break; str += ch[cpos[0]][cpos[1]]; if( v->find(str) != v->end() ) { if( ( str.length() > ans.length() ) || ( str.length() == ans.length() && str < ans ) ) { ans = str; } } else v->insert(str); } } } int main(void){ while(1){ cin >> l[0] >> l[1]; if( l[0] == 0 && l[1] == 0 ) break; char donut[10][20]; int pos[2]; ans = ""; set< string > strs; //入力を取得する for(int i = 0; i < l[0]; i++) cin >> donut[i]; for(pos[0] = 0; pos[0] < l[0]; pos[0]++) for(pos[1] = 0; pos[1] < l[1]; pos[1]++) search( &strs, pos, donut ); if(ans == "") cout << 0 << endl; else cout << ans << endl; } return 0; }
### Prompt Develop a solution in cpp to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <stdio.h> #include <set> using namespace std; #define dirmax 8 int l[2]; int dir[8][2] = { {0,1}, {1,0}, {-1,0}, {0,-1}, {1,1}, {-1,1}, {1,-1}, {-1,-1} }; string ans; void search( set<string> *v, int pos[2] , char ch[10][20]){ for(int i = 0; i < dirmax; i++) { string str; int cpos[] = { pos[0], pos[1] }; str += ch[pos[0]][pos[1]]; while( 1 ) { for(int j = 0; j < 2; j++) { cpos[j] += dir[i][j]; if( cpos[j] < 0 ) cpos[j] = l[j] - 1; if( cpos[j] >= l[j] ) cpos[j] = 0; } if( cpos[0] == pos[0] && cpos[1] == pos[1] ) break; str += ch[cpos[0]][cpos[1]]; if( v->find(str) != v->end() ) { if( ( str.length() > ans.length() ) || ( str.length() == ans.length() && str < ans ) ) { ans = str; } } else v->insert(str); } } } int main(void){ while(1){ cin >> l[0] >> l[1]; if( l[0] == 0 && l[1] == 0 ) break; char donut[10][20]; int pos[2]; ans = ""; set< string > strs; //入力を取得する for(int i = 0; i < l[0]; i++) cin >> donut[i]; for(pos[0] = 0; pos[0] < l[0]; pos[0]++) for(pos[1] = 0; pos[1] < l[1]; pos[1]++) search( &strs, pos, donut ); if(ans == "") cout << 0 << endl; else cout << ans << endl; } return 0; } ```
#include <iostream> #include <unordered_set> #include <algorithm> using namespace std; int dx[8]={1, 1, 1, 0, 0,-1,-1,-1}; int dy[8]={1, 0,-1, 1,-1, 1, 0,-1}; int main(){ while(1){ int h,w; cin >> h >> w; if(h==0) break; char c[10][20]; for(int i=0; i<h; i++){ for(int j=0; j<w; j++){ cin >> c[i][j]; } } unordered_set<string> spell; string ans = "0"; for(int i=0; i<h; i++){ for(int j=0; j<w; j++){ for(int d=0; d<8; d++){ string str(1,c[i][j]); int y=(i+dy[d]+h)%h; int x=(j+dx[d]+w)%w; while(y!=i || x!=j){ str += c[y][x]; auto itr = spell.find(str); if(itr != spell.end()){ if(str.length()>ans.length() || (str.length()==ans.length() && str<ans)){ ans = str; } }else{ spell.insert(str); } y = (y+dy[d]+h)%h; x = (x+dx[d]+w)%w; } } } } cout << ans << endl; } return 0; }
### Prompt Please formulate a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <unordered_set> #include <algorithm> using namespace std; int dx[8]={1, 1, 1, 0, 0,-1,-1,-1}; int dy[8]={1, 0,-1, 1,-1, 1, 0,-1}; int main(){ while(1){ int h,w; cin >> h >> w; if(h==0) break; char c[10][20]; for(int i=0; i<h; i++){ for(int j=0; j<w; j++){ cin >> c[i][j]; } } unordered_set<string> spell; string ans = "0"; for(int i=0; i<h; i++){ for(int j=0; j<w; j++){ for(int d=0; d<8; d++){ string str(1,c[i][j]); int y=(i+dy[d]+h)%h; int x=(j+dx[d]+w)%w; while(y!=i || x!=j){ str += c[y][x]; auto itr = spell.find(str); if(itr != spell.end()){ if(str.length()>ans.length() || (str.length()==ans.length() && str<ans)){ ans = str; } }else{ spell.insert(str); } y = (y+dy[d]+h)%h; x = (x+dx[d]+w)%w; } } } } cout << ans << endl; } return 0; } ```
#include <iostream> #include <stdio.h> #include <algorithm> #include <vector> #include <queue> #include <numeric> #include <string> #include <string.h> #include <map> #include <set> #include <functional> #include <complex> #include <stack> #include <tuple> #include <array> using namespace std; #define rep(i,n) for (int i=0; i < (n); i++) typedef long long int ll; typedef double D; // ??§?¨?????????????double???long double????????? typedef complex<D> P; // Point typedef pair<P, P> L; // Line typedef vector<P> VP; const int INF = (1<<30) - 1; const D EPS = 1e-9; #define X real() #define Y imag() #define LE(n,m) ((n) < (m) + EPS) #define GE(n,m) ((n) + EPS > (m)) #define EQ(n,m) (abs((n)-(m)) < EPS) int H, W; vector<string> field; int dh[] = {1, 1, 0, -1, -1, -1, 0, 1}; int dw[] = {0, 1, 1, 1, 0, -1, -1, -1}; void func(int h, int w, int d, map<string, int>& memo){ int sh = h, sw = w; string s = ""; do{ s += field[h][w]; if(s.length() >= 2) memo[s]++; h = (h+dh[d]+H)%H; w = (w+dw[d]+W)%W; }while(sh!=h || sw!=w); } void solve(){ map<string, int> memo; for(int h=0; h<H; h++){ for(int w=0; w<W; w++){ for(int i=0; i<8; i++){ func(h, w, i, memo); } } } string ans = ""; for(auto p: memo){ if(p.second < 2) continue; if(ans.length() < p.first.length() || (ans.length() == p.first.length() && p.first < ans)) ans = p.first; } if(ans.length() == 0) cout << 0 << endl; else cout << ans << endl; } //g++ -std=c++0x -msse4.2 -O3 //#include <bits/stdc++.h> int main(){ ios::sync_with_stdio(false); cin.tie(0); //cout.precision(16); //cout.setf(ios::fixed); while(cin>>H>>W, H|W){ field = vector<string>(H); for(int i=0; i<H; i++) cin >> field[i]; solve(); } return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <stdio.h> #include <algorithm> #include <vector> #include <queue> #include <numeric> #include <string> #include <string.h> #include <map> #include <set> #include <functional> #include <complex> #include <stack> #include <tuple> #include <array> using namespace std; #define rep(i,n) for (int i=0; i < (n); i++) typedef long long int ll; typedef double D; // ??§?¨?????????????double???long double????????? typedef complex<D> P; // Point typedef pair<P, P> L; // Line typedef vector<P> VP; const int INF = (1<<30) - 1; const D EPS = 1e-9; #define X real() #define Y imag() #define LE(n,m) ((n) < (m) + EPS) #define GE(n,m) ((n) + EPS > (m)) #define EQ(n,m) (abs((n)-(m)) < EPS) int H, W; vector<string> field; int dh[] = {1, 1, 0, -1, -1, -1, 0, 1}; int dw[] = {0, 1, 1, 1, 0, -1, -1, -1}; void func(int h, int w, int d, map<string, int>& memo){ int sh = h, sw = w; string s = ""; do{ s += field[h][w]; if(s.length() >= 2) memo[s]++; h = (h+dh[d]+H)%H; w = (w+dw[d]+W)%W; }while(sh!=h || sw!=w); } void solve(){ map<string, int> memo; for(int h=0; h<H; h++){ for(int w=0; w<W; w++){ for(int i=0; i<8; i++){ func(h, w, i, memo); } } } string ans = ""; for(auto p: memo){ if(p.second < 2) continue; if(ans.length() < p.first.length() || (ans.length() == p.first.length() && p.first < ans)) ans = p.first; } if(ans.length() == 0) cout << 0 << endl; else cout << ans << endl; } //g++ -std=c++0x -msse4.2 -O3 //#include <bits/stdc++.h> int main(){ ios::sync_with_stdio(false); cin.tie(0); //cout.precision(16); //cout.setf(ios::fixed); while(cin>>H>>W, H|W){ field = vector<string>(H); for(int i=0; i<H; i++) cin >> field[i]; solve(); } return 0; } ```
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <string> #include <map> #include <set> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(-1.0); #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++) #define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++) #define MEMSET(v, h) memset((v), h, sizeof(v)) const int dx[8] = { 1, 1, 1, 0, -1, -1, -1, 0 }; const int dy[8] = { -1, 0, 1, 1, 1, 0, -1, -1 }; char field[100][100]; bool visit[30][30]; int h, w; int main() { while (scanf("%d %d", &h, &w), h|w) { REP(y, h) { scanf("%s", field[y]); } string ans = "0"; map<string, int> open; REP(sy, h) { REP(sx, w) { REP(dir, 8) { MEMSET(visit, false); string s; int x = sx; int y = sy; while (!visit[y][x]) { visit[y][x] = true; s += field[y][x]; if (s.size() > 1) { open[s]++; if (open[s] >= 2) { if (ans.size() < s.size() || (ans.size() == s.size() && s < ans)) { ans = s; } } } x = (x + dx[dir] + w) % w; y = (y + dy[dir] + h) % h; } } } } cout << ans << endl; } }
### Prompt Your challenge is to write a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <string> #include <map> #include <set> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(-1.0); #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++) #define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++) #define MEMSET(v, h) memset((v), h, sizeof(v)) const int dx[8] = { 1, 1, 1, 0, -1, -1, -1, 0 }; const int dy[8] = { -1, 0, 1, 1, 1, 0, -1, -1 }; char field[100][100]; bool visit[30][30]; int h, w; int main() { while (scanf("%d %d", &h, &w), h|w) { REP(y, h) { scanf("%s", field[y]); } string ans = "0"; map<string, int> open; REP(sy, h) { REP(sx, w) { REP(dir, 8) { MEMSET(visit, false); string s; int x = sx; int y = sy; while (!visit[y][x]) { visit[y][x] = true; s += field[y][x]; if (s.size() > 1) { open[s]++; if (open[s] >= 2) { if (ans.size() < s.size() || (ans.size() == s.size() && s < ans)) { ans = s; } } } x = (x + dx[dir] + w) % w; y = (y + dy[dir] + h) % h; } } } } cout << ans << endl; } } ```
#include <cstdio> #include <iostream> #include <string> #include <sstream> #include <stack> #include <algorithm> #include <cmath> #include <queue> #include <map> #include <set> #include <cstdlib> #include <bitset> #include <tuple> #include <assert.h> #include <deque> #include <bitset> #include <iomanip> #include <limits> #include <chrono> #include <random> #include <array> #include <unordered_map> #include <functional> #include <complex> #include <numeric> template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } constexpr long long MAX = 5100000; constexpr long long INF = 1LL << 60; constexpr int inf = 1 << 28; constexpr long long mod = 1000000007LL; //constexpr long long mod = 998244353LL; using namespace std; typedef unsigned long long ull; typedef long long ll; int dh[8] = { 0,1,1,1,0,-1,-1,-1 }; int dw[8] = { 1,1,0,-1,-1,-1,0,1 }; vector<string> vs; map<string, ll> mp; void solve() { int H, W; cin >> H >> W; if (H == 0 and W == 0) exit(0); vs.resize(H); for (int i = 0; i < H; i++) cin >> vs[i]; mp.clear(); for (int h = 0; h < H; h++) { for (int w = 0; w < W; w++) { for (int i = 0; i < 8; i++) { int nh = h; int nw = w; string s; s += vs[nh][nw]; while (1) { nh += dh[i]; nw += dw[i]; if (nh >= H) nh = 0; if (nw >= W) nw = 0; if (nh < 0) nh = H - 1; if (nw < 0) nw = W - 1; if (nh == h and nw == w) break; s += vs[nh][nw]; mp[s]++; } } } } string res; for (auto& p : mp) { if (p.second >= 2) { if (res.size() < p.first.size()) res = p.first; else if (res.size() == p.first.size() and res > p.first) res = p.first; } } if (res == "") cout << "0" << "\n"; else cout << res << "\n"; } int main() { /* cin.tie(nullptr); ios::sync_with_stdio(false); */ int kkt = 89; while (kkt) { solve(); } return 0; }
### Prompt Create a solution in CPP for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstdio> #include <iostream> #include <string> #include <sstream> #include <stack> #include <algorithm> #include <cmath> #include <queue> #include <map> #include <set> #include <cstdlib> #include <bitset> #include <tuple> #include <assert.h> #include <deque> #include <bitset> #include <iomanip> #include <limits> #include <chrono> #include <random> #include <array> #include <unordered_map> #include <functional> #include <complex> #include <numeric> template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } constexpr long long MAX = 5100000; constexpr long long INF = 1LL << 60; constexpr int inf = 1 << 28; constexpr long long mod = 1000000007LL; //constexpr long long mod = 998244353LL; using namespace std; typedef unsigned long long ull; typedef long long ll; int dh[8] = { 0,1,1,1,0,-1,-1,-1 }; int dw[8] = { 1,1,0,-1,-1,-1,0,1 }; vector<string> vs; map<string, ll> mp; void solve() { int H, W; cin >> H >> W; if (H == 0 and W == 0) exit(0); vs.resize(H); for (int i = 0; i < H; i++) cin >> vs[i]; mp.clear(); for (int h = 0; h < H; h++) { for (int w = 0; w < W; w++) { for (int i = 0; i < 8; i++) { int nh = h; int nw = w; string s; s += vs[nh][nw]; while (1) { nh += dh[i]; nw += dw[i]; if (nh >= H) nh = 0; if (nw >= W) nw = 0; if (nh < 0) nh = H - 1; if (nw < 0) nw = W - 1; if (nh == h and nw == w) break; s += vs[nh][nw]; mp[s]++; } } } } string res; for (auto& p : mp) { if (p.second >= 2) { if (res.size() < p.first.size()) res = p.first; else if (res.size() == p.first.size() and res > p.first) res = p.first; } } if (res == "") cout << "0" << "\n"; else cout << res << "\n"; } int main() { /* cin.tie(nullptr); ios::sync_with_stdio(false); */ int kkt = 89; while (kkt) { solve(); } return 0; } ```
#include <iostream> #include <cstdio> #include <map> #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++) using namespace std; char d[20][30]; int dx[8] = {-1, 0, 1,-1, 1,-1, 0, 1}; int dy[8] = {-1,-1,-1, 0, 0, 1, 1, 1}; int main(){ int h, w; while(scanf("%d%d", &h, &w), h + w){ map<string, int> m; REP(i,h) scanf("%s", d[i]); REP(i,h) REP(j,w){ REP(k,8){ int x = j; int y = i; string tmp = ""; do{ tmp += d[y][x]; x = (x + w + dx[k]) % w; y = (y + h + dy[k]) % h; m[tmp]++; }while(i != y || j != x); } } string ans = ""; FOR(it, m) if(it->second > 1){ const string &s = it->first; if(s.size() > ans.size()) ans = s; else if(s.size() == ans.size() && s < ans) ans = s; } if(ans.size() > 1) puts(ans.c_str()); else puts("0"); } return 0; }
### Prompt Please create a solution in CPP to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <cstdio> #include <map> #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++) using namespace std; char d[20][30]; int dx[8] = {-1, 0, 1,-1, 1,-1, 0, 1}; int dy[8] = {-1,-1,-1, 0, 0, 1, 1, 1}; int main(){ int h, w; while(scanf("%d%d", &h, &w), h + w){ map<string, int> m; REP(i,h) scanf("%s", d[i]); REP(i,h) REP(j,w){ REP(k,8){ int x = j; int y = i; string tmp = ""; do{ tmp += d[y][x]; x = (x + w + dx[k]) % w; y = (y + h + dy[k]) % h; m[tmp]++; }while(i != y || j != x); } } string ans = ""; FOR(it, m) if(it->second > 1){ const string &s = it->first; if(s.size() > ans.size()) ans = s; else if(s.size() == ans.size() && s < ans) ans = s; } if(ans.size() > 1) puts(ans.c_str()); else puts("0"); } return 0; } ```
#include<bits/stdc++.h> using namespace std; int di[8] = {0, -1, -1, -1, 0, 1, 1, 1}; int dj[8] = {1, 1, 0, -1, -1, -1, 0, 1}; int main(){ while(1){ int h, w; cin >> h >> w; if(h == 0) break; vector<string> a(h); for(int i = 0; i < h; i++) cin >> a[i]; string ans = "["; set<string> s; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ for(int k = 0; k < 8; k++){ string tmp; tmp += a[i][j]; int ni = (h + i + di[k]) % h; int nj = (w + j + dj[k]) % w; while(!(ni == i && nj == j)){ tmp += a[ni][nj]; //cout << i << " " << j << " " << ni << " " << nj << " " << tmp << endl; ni = (h + ni + di[k]) % h; nj = (w + nj + dj[k]) % w; //cout << i << " " << j << " " << ni << " " << nj << " " << tmp << endl; if(s.find(tmp) != s.end()){ //cout << "find" << endl; if(ans.size() < tmp.size()){ ans = tmp; }else if(ans.size() == tmp.size() && ans > tmp){ ans = tmp; } }else{ //cout << "insert" << endl; s.insert(tmp); } } } } } //string hoge = "ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ"; //cout << hoge.size() << endl; if(ans == "[") cout << 0 << endl; else cout << ans << endl; } return 0; }
### Prompt Construct a CPP code solution to the problem outlined: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<bits/stdc++.h> using namespace std; int di[8] = {0, -1, -1, -1, 0, 1, 1, 1}; int dj[8] = {1, 1, 0, -1, -1, -1, 0, 1}; int main(){ while(1){ int h, w; cin >> h >> w; if(h == 0) break; vector<string> a(h); for(int i = 0; i < h; i++) cin >> a[i]; string ans = "["; set<string> s; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ for(int k = 0; k < 8; k++){ string tmp; tmp += a[i][j]; int ni = (h + i + di[k]) % h; int nj = (w + j + dj[k]) % w; while(!(ni == i && nj == j)){ tmp += a[ni][nj]; //cout << i << " " << j << " " << ni << " " << nj << " " << tmp << endl; ni = (h + ni + di[k]) % h; nj = (w + nj + dj[k]) % w; //cout << i << " " << j << " " << ni << " " << nj << " " << tmp << endl; if(s.find(tmp) != s.end()){ //cout << "find" << endl; if(ans.size() < tmp.size()){ ans = tmp; }else if(ans.size() == tmp.size() && ans > tmp){ ans = tmp; } }else{ //cout << "insert" << endl; s.insert(tmp); } } } } } //string hoge = "ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ"; //cout << hoge.size() << endl; if(ans == "[") cout << 0 << endl; else cout << ans << endl; } return 0; } ```
#include<cstdio> #include<iostream> #include<string> #include<map> using namespace std; static const int MAX_H = 10; int h, w; string s[MAX_H]; int dy[] = {0, -1, -1, -1, 0, 1, 1, 1}; int dx[] = {1, 1, 0, -1, -1, -1, 0, 1}; int main(){ for(;;){ scanf("%d %d", &h, &w); if(h == 0 && w == 0) break; for(int i = 0; i < h; i++) cin >> s[i]; map<string, int> mpa; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ int sy = i; int sx = j; for(int k = 0; k < 8; k++){ int cy = i; int cx = j; string str; str += s[sy][sx]; mpa[str]++; for(;;){ cy += dy[k]; cx += dx[k]; cy = (cy + h) % h; cx = (cx + w) % w; if(cy == sy && cx == sx) break; str += s[cy][cx]; mpa[str]++; } } } } string res = "0"; for(map<string, int>::iterator itr = mpa.begin(); itr != mpa.end(); itr++){ if(itr->second < 2 || itr->first.length() < 2) continue; if(itr->first.length() > res.length() || (itr->first.length() == res.length() && itr->first < res)) res = itr->first; } cout << res << endl; } }
### Prompt In Cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<cstdio> #include<iostream> #include<string> #include<map> using namespace std; static const int MAX_H = 10; int h, w; string s[MAX_H]; int dy[] = {0, -1, -1, -1, 0, 1, 1, 1}; int dx[] = {1, 1, 0, -1, -1, -1, 0, 1}; int main(){ for(;;){ scanf("%d %d", &h, &w); if(h == 0 && w == 0) break; for(int i = 0; i < h; i++) cin >> s[i]; map<string, int> mpa; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ int sy = i; int sx = j; for(int k = 0; k < 8; k++){ int cy = i; int cx = j; string str; str += s[sy][sx]; mpa[str]++; for(;;){ cy += dy[k]; cx += dx[k]; cy = (cy + h) % h; cx = (cx + w) % w; if(cy == sy && cx == sx) break; str += s[cy][cx]; mpa[str]++; } } } } string res = "0"; for(map<string, int>::iterator itr = mpa.begin(); itr != mpa.end(); itr++){ if(itr->second < 2 || itr->first.length() < 2) continue; if(itr->first.length() > res.length() || (itr->first.length() == res.length() && itr->first < res)) res = itr->first; } cout << res << endl; } } ```
#include <cstring> #include <algorithm> #include <string> #include <iostream> #include <map> using namespace std; #define loop(i,a,b) for(int i=(a);i<int(b);i++) #define rep(i,b) loop(i,0,b) int dx[]={1,1,1,0}; int dy[]={-1,0,1,1}; string g[100]; int h,w; int main(){ while(cin>>h>>w && h){ map<string,int> m; rep(i,h)cin>>g[i]; rep(i,h)rep(j,w){ rep(d,4){ string s; for(int ii=i, jj=j; s.size()==0 || ii!=i || jj!=j; ii=(ii+h+dy[d])%h, jj=(jj+w+dx[d])%w){ s += g[ii][jj]; m[s]++; reverse(s.begin(),s.end()); m[s]++; reverse(s.begin(),s.end()); } } } string ans; for(auto& p:m){ //cout << p.first << " " << p.second << endl; if(p.second < 2) continue; if(ans.size() > p.first.size()) continue; if(ans.size() == p.first.size()){ ans = min(ans,p.first); } if(ans.size() < p.first.size()) ans = p.first; } if(ans.size() <= 1) ans="0"; cout<<ans<<endl; getchar(); } }
### Prompt Please formulate a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstring> #include <algorithm> #include <string> #include <iostream> #include <map> using namespace std; #define loop(i,a,b) for(int i=(a);i<int(b);i++) #define rep(i,b) loop(i,0,b) int dx[]={1,1,1,0}; int dy[]={-1,0,1,1}; string g[100]; int h,w; int main(){ while(cin>>h>>w && h){ map<string,int> m; rep(i,h)cin>>g[i]; rep(i,h)rep(j,w){ rep(d,4){ string s; for(int ii=i, jj=j; s.size()==0 || ii!=i || jj!=j; ii=(ii+h+dy[d])%h, jj=(jj+w+dx[d])%w){ s += g[ii][jj]; m[s]++; reverse(s.begin(),s.end()); m[s]++; reverse(s.begin(),s.end()); } } } string ans; for(auto& p:m){ //cout << p.first << " " << p.second << endl; if(p.second < 2) continue; if(ans.size() > p.first.size()) continue; if(ans.size() == p.first.size()){ ans = min(ans,p.first); } if(ans.size() < p.first.size()) ans = p.first; } if(ans.size() <= 1) ans="0"; cout<<ans<<endl; getchar(); } } ```
/* * GCA : "Computer is artificial subject absolutely,Math is God" */ #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <climits> #include <vector> #include <set> #include <map> #include <queue> #include <cctype> #include <utility> #include <ctime> using namespace std; #ifdef DEBUG #define VAR(a,b) __typeof(b) a=(b) #define debug(...) printf("DEBUG: "),printf(__VA_ARGS__) #else #define VAR(a,b) __typeof(b) a=(b) #define debug(...) #endif typedef unsigned int uint; typedef long long int Int; typedef unsigned long long int UInt; #define Set(a,s) memset(a,s,sizeof(a)) #define Pln() printf("\n") #define For(i,x)for(int i=0;i<x;i++) #define CON(x,y) x##y #define M 25 #define PB push_back #define oo INT_MAX #define FOR(a,b) for(VAR(a,(b).begin());a!=(b).end();++a) #define eps 1e-9 #define X first #define Y second inline bool xdy(double x,double y){return x>y+eps;} inline bool xddy(double x,double y){return x>y-eps;} inline bool xcy(double x,double y){return x<y-eps;} inline bool xcdy(double x,double y){return x<y+eps;} const Int mod=1000000007; int nx,ny; char mz[M][M]; set<string> sid; int dx[8]={0,1,1,1,0,-1,-1,-1}; int dy[8]={1,1,0,-1,-1,-1,0,1}; char store[M*M]; int ox,oy; string ans; bool vis[M][M]; void dfs(int x,int y,int d,int dep){ store[dep]=mz[y][x]; int nex=(x+dx[d]+nx)%nx; int ney=(y+dy[d]+ny)%ny; store[dep+1]=0; string ss(store); if(sid.count(ss)&&ss.length()>=2){ if(ss.length()>ans.length())ans=ss; else if(ss.length()==ans.length()&&ss<ans){ ans=ss; } } sid.insert(ss); vis[x][y]=1; if(!vis[nex][ney])dfs(nex,ney,d,dep+1); vis[x][y]=0; } void solve(){ Set(vis,0); for(int i=0;i<ny;i++){ for(int j=0;j<nx;j++){ for(int k=0;k<8;k++){ vis[j][i]=1; dfs(j,i,k,0); vis[j][i]=0; } } } if(ans.size()) puts(ans.c_str()); else puts("0"); } int main() { ios_base::sync_with_stdio(0); while(~scanf("%d%d",&ny,&nx)&&ny&&nx){ sid.clear(); ans=""; for(int i=0;i<ny;i++)scanf("%s",mz[i]); solve(); } }
### Prompt In cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp /* * GCA : "Computer is artificial subject absolutely,Math is God" */ #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <climits> #include <vector> #include <set> #include <map> #include <queue> #include <cctype> #include <utility> #include <ctime> using namespace std; #ifdef DEBUG #define VAR(a,b) __typeof(b) a=(b) #define debug(...) printf("DEBUG: "),printf(__VA_ARGS__) #else #define VAR(a,b) __typeof(b) a=(b) #define debug(...) #endif typedef unsigned int uint; typedef long long int Int; typedef unsigned long long int UInt; #define Set(a,s) memset(a,s,sizeof(a)) #define Pln() printf("\n") #define For(i,x)for(int i=0;i<x;i++) #define CON(x,y) x##y #define M 25 #define PB push_back #define oo INT_MAX #define FOR(a,b) for(VAR(a,(b).begin());a!=(b).end();++a) #define eps 1e-9 #define X first #define Y second inline bool xdy(double x,double y){return x>y+eps;} inline bool xddy(double x,double y){return x>y-eps;} inline bool xcy(double x,double y){return x<y-eps;} inline bool xcdy(double x,double y){return x<y+eps;} const Int mod=1000000007; int nx,ny; char mz[M][M]; set<string> sid; int dx[8]={0,1,1,1,0,-1,-1,-1}; int dy[8]={1,1,0,-1,-1,-1,0,1}; char store[M*M]; int ox,oy; string ans; bool vis[M][M]; void dfs(int x,int y,int d,int dep){ store[dep]=mz[y][x]; int nex=(x+dx[d]+nx)%nx; int ney=(y+dy[d]+ny)%ny; store[dep+1]=0; string ss(store); if(sid.count(ss)&&ss.length()>=2){ if(ss.length()>ans.length())ans=ss; else if(ss.length()==ans.length()&&ss<ans){ ans=ss; } } sid.insert(ss); vis[x][y]=1; if(!vis[nex][ney])dfs(nex,ney,d,dep+1); vis[x][y]=0; } void solve(){ Set(vis,0); for(int i=0;i<ny;i++){ for(int j=0;j<nx;j++){ for(int k=0;k<8;k++){ vis[j][i]=1; dfs(j,i,k,0); vis[j][i]=0; } } } if(ans.size()) puts(ans.c_str()); else puts("0"); } int main() { ios_base::sync_with_stdio(0); while(~scanf("%d%d",&ny,&nx)&&ny&&nx){ sid.clear(); ans=""; for(int i=0;i<ny;i++)scanf("%s",mz[i]); solve(); } } ```
#include<iostream> #include<string> #include<vector> #include<cstdio> #include<sstream> #include<algorithm> #include<cmath> #include<map> #include<functional> #include<queue> #include<stack> #include<set> using namespace std; #define SZ(n) (int)n.size() #define dump(x) cerr<<#x<<" = "<<(x)<<endl; #define debug(x)cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl; #define MP make_pair #define PB push_back int dx[]={1,1,0,-1,-1,-1,0,1},dy[]={0,1,1,1,0,-1,-1,-1}; string _or(string a,string b){ if(SZ(a)>SZ(b))return a; if(SZ(a)<SZ(b))return b; return min(a,b); } char ta[50][50]; int main(){ int w,h; while(cin>>h>>w,(h||w)){ map<string,int>ans; for(int i=0;i<h;i++)for(int j=0;j<w;j++)cin>>ta[i][j]; string tmp; for(int ni=0;ni<h;ni++){ for(int nj=0;nj<w;nj++){ for(int p=0;p<8;p++){ tmp.clear(); int i=ni,j=nj; tmp.push_back(ta[ni][nj]); while(true){ i+=dy[p],j+=dx[p]; if(i<0)i=h-1; if(j<0)j=w-1; if(i>h-1)i=0; if(j>w-1)j=0; if(i==ni&&j==nj)break; tmp.push_back(ta[i][j]); if(SZ(tmp)>=2){ ans[tmp]++; } } } } } string tans=""; for(map<string,int>::iterator it=ans.begin();it!=ans.end();it++){ if((*it).second>=2){tans=_or(tans,(*it).first);} } if(SZ(tans)<2)cout<<"0"<<endl; else cout<<tans<<endl; for(int i=0;i<50;i++)for(int j=0;j<50;j++)ta[i][j]=' '; } return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<string> #include<vector> #include<cstdio> #include<sstream> #include<algorithm> #include<cmath> #include<map> #include<functional> #include<queue> #include<stack> #include<set> using namespace std; #define SZ(n) (int)n.size() #define dump(x) cerr<<#x<<" = "<<(x)<<endl; #define debug(x)cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl; #define MP make_pair #define PB push_back int dx[]={1,1,0,-1,-1,-1,0,1},dy[]={0,1,1,1,0,-1,-1,-1}; string _or(string a,string b){ if(SZ(a)>SZ(b))return a; if(SZ(a)<SZ(b))return b; return min(a,b); } char ta[50][50]; int main(){ int w,h; while(cin>>h>>w,(h||w)){ map<string,int>ans; for(int i=0;i<h;i++)for(int j=0;j<w;j++)cin>>ta[i][j]; string tmp; for(int ni=0;ni<h;ni++){ for(int nj=0;nj<w;nj++){ for(int p=0;p<8;p++){ tmp.clear(); int i=ni,j=nj; tmp.push_back(ta[ni][nj]); while(true){ i+=dy[p],j+=dx[p]; if(i<0)i=h-1; if(j<0)j=w-1; if(i>h-1)i=0; if(j>w-1)j=0; if(i==ni&&j==nj)break; tmp.push_back(ta[i][j]); if(SZ(tmp)>=2){ ans[tmp]++; } } } } } string tans=""; for(map<string,int>::iterator it=ans.begin();it!=ans.end();it++){ if((*it).second>=2){tans=_or(tans,(*it).first);} } if(SZ(tans)<2)cout<<"0"<<endl; else cout<<tans<<endl; for(int i=0;i<50;i++)for(int j=0;j<50;j++)ta[i][j]=' '; } return 0; } ```
#include <bits/stdc++.h> using namespace std; const int dx[] = {-1, 0, 1, 0, -1, -1, 1, 1}; const int dy[] = {0, -1, 0, 1, -1, 1, -1, 1}; int h, w; string s[10]; vector<string> generate(int sx, int sy, int dir) { int x = sx, y = sy; string str = ""; vector<string> res; while (true){ str += s[x][y]; res.push_back(str); x = (x + dx[dir] + h) % h; y = (y + dy[dir] + w) % w; if (sx == x && sy == y) break; } return res; } string solve() { map<string, int> mp; for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ for (int d = 0; d < 8; d++){ vector<string> vs = generate(i, j, d); for (auto &s : vs){ mp[s]++; } } } } string res = "0"; for (auto &p : mp){ if (p.second < 2) continue; if (res.size() > p.first.size()) continue; if (res.size() < p.first.size()){ res = p.first; } else res = min(res, p.first); } return res; } int main() { while (cin >> h >> w, h){ for (int i = 0; i < h; i++){ cin >> s[i]; } cout << solve() << endl; } }
### Prompt Create a solution in Cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int dx[] = {-1, 0, 1, 0, -1, -1, 1, 1}; const int dy[] = {0, -1, 0, 1, -1, 1, -1, 1}; int h, w; string s[10]; vector<string> generate(int sx, int sy, int dir) { int x = sx, y = sy; string str = ""; vector<string> res; while (true){ str += s[x][y]; res.push_back(str); x = (x + dx[dir] + h) % h; y = (y + dy[dir] + w) % w; if (sx == x && sy == y) break; } return res; } string solve() { map<string, int> mp; for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ for (int d = 0; d < 8; d++){ vector<string> vs = generate(i, j, d); for (auto &s : vs){ mp[s]++; } } } } string res = "0"; for (auto &p : mp){ if (p.second < 2) continue; if (res.size() > p.first.size()) continue; if (res.size() < p.first.size()){ res = p.first; } else res = min(res, p.first); } return res; } int main() { while (cin >> h >> w, h){ for (int i = 0; i < h; i++){ cin >> s[i]; } cout << solve() << endl; } } ```
#include<iostream> #include<vector> #include<string> #include<map> #define f first #define s second using namespace std; int h,w,ii,jj; int X[8]={-1,1,-1,1,0,-1,0,1}; int Y[8]={-1,1,1,-1,1,0,-1,0}; char Donut[10][20]; vector<string> V; string maxs; map<string,pair<int,int> > M; void Check(string s) { if(maxs.length()<s.length())maxs=s; else if(maxs.length()==s.length()){ if(maxs>s)maxs=s; } } void make(int x,int y) { for(int k=0;k<8;k++){ string S=""; int a=x,b=y; S+=Donut[a][b]; while(1){ a+=Y[k]; b+=X[k]; if(a==-1)a=h-1; if(b==-1)b=w-1; if(a==h)a=0; if(b==w)b=0; if(a==x && b==y)break; S+=Donut[a][b]; if(M[S].f==0 && M[S].s==0){ M[S].f=x+1; M[S].s=y+1; } else { Check(S); } } } } int main() { while(1){ cin>>h>>w; if(h+w==0)break; for(int i=0;i<h;i++){ for(int j=0;j<w;j++)cin>>Donut[i][j]; } M.clear(); maxs=""; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ make(i,j); } } if(maxs=="")cout<<0<<endl; else cout<<maxs<<endl; } return 0; }
### Prompt Please formulate a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<vector> #include<string> #include<map> #define f first #define s second using namespace std; int h,w,ii,jj; int X[8]={-1,1,-1,1,0,-1,0,1}; int Y[8]={-1,1,1,-1,1,0,-1,0}; char Donut[10][20]; vector<string> V; string maxs; map<string,pair<int,int> > M; void Check(string s) { if(maxs.length()<s.length())maxs=s; else if(maxs.length()==s.length()){ if(maxs>s)maxs=s; } } void make(int x,int y) { for(int k=0;k<8;k++){ string S=""; int a=x,b=y; S+=Donut[a][b]; while(1){ a+=Y[k]; b+=X[k]; if(a==-1)a=h-1; if(b==-1)b=w-1; if(a==h)a=0; if(b==w)b=0; if(a==x && b==y)break; S+=Donut[a][b]; if(M[S].f==0 && M[S].s==0){ M[S].f=x+1; M[S].s=y+1; } else { Check(S); } } } } int main() { while(1){ cin>>h>>w; if(h+w==0)break; for(int i=0;i<h;i++){ for(int j=0;j<w;j++)cin>>Donut[i][j]; } M.clear(); maxs=""; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ make(i,j); } } if(maxs=="")cout<<0<<endl; else cout<<maxs<<endl; } return 0; } ```
#include<iostream> #include<string> #include<iomanip> #include<cmath> #include<vector> #include<algorithm> #include<map> using namespace std; #define int long long #define endl "\n" const long long INF = (long long)1e18; const long long MOD = (long long)1e9 + 7; string yn(bool f){return f?"Yes":"No";} string YN(bool f){return f?"YES":"NO";} #define MAX vector<string> str; map<string, int> mp; int h, w, maximum, co; string ans; void check(int y, int x){ vector<vector<int>> used(h,vector<int>(w,0)); int count = 1; string res; // cout<<"y = "<<y<<" x = "<<x<<endl; for(int i = -1; i <= 1; i++){ for(int j = -1; j <= 1; j++){ string temp; // cout<<"i = "<<i<<" j = "<<j<<endl; for(int ny = y, nx = x; count != used[ny][nx]; nx = (j+w+nx)%w, ny = (i+h+ny)%h){ used[ny][nx] = count; temp.push_back(str[ny][nx]); // cout<<temp<<endl; if(temp.size() <= 1) continue; if(++mp[temp] != 2) continue; if(ans.size() < temp.size()){ ans = temp; } else if(ans.size() == temp.size() && ans > temp){ ans = temp; } } count++; } } // return res; } signed main(){ // cin.tie(0); // ios::sync_with_stdio(false); // cout<<fixed<<setprecision(10); while(true){ mp.clear(); ans.clear(); cin>>h>>w; if(!h && !w) break; str.clear(); str.resize(h); for(int i = 0; i < h; i++){ cin>>str[i]; } for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ check(i,j); } } cout<<(ans.size()?ans:"0")<<endl; } return 0; }
### Prompt Create a solution in cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<string> #include<iomanip> #include<cmath> #include<vector> #include<algorithm> #include<map> using namespace std; #define int long long #define endl "\n" const long long INF = (long long)1e18; const long long MOD = (long long)1e9 + 7; string yn(bool f){return f?"Yes":"No";} string YN(bool f){return f?"YES":"NO";} #define MAX vector<string> str; map<string, int> mp; int h, w, maximum, co; string ans; void check(int y, int x){ vector<vector<int>> used(h,vector<int>(w,0)); int count = 1; string res; // cout<<"y = "<<y<<" x = "<<x<<endl; for(int i = -1; i <= 1; i++){ for(int j = -1; j <= 1; j++){ string temp; // cout<<"i = "<<i<<" j = "<<j<<endl; for(int ny = y, nx = x; count != used[ny][nx]; nx = (j+w+nx)%w, ny = (i+h+ny)%h){ used[ny][nx] = count; temp.push_back(str[ny][nx]); // cout<<temp<<endl; if(temp.size() <= 1) continue; if(++mp[temp] != 2) continue; if(ans.size() < temp.size()){ ans = temp; } else if(ans.size() == temp.size() && ans > temp){ ans = temp; } } count++; } } // return res; } signed main(){ // cin.tie(0); // ios::sync_with_stdio(false); // cout<<fixed<<setprecision(10); while(true){ mp.clear(); ans.clear(); cin>>h>>w; if(!h && !w) break; str.clear(); str.resize(h); for(int i = 0; i < h; i++){ cin>>str[i]; } for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ check(i,j); } } cout<<(ans.size()?ans:"0")<<endl; } return 0; } ```
#include<bits/stdc++.h> #define r(i,n) for(int i=0;i<n;i++) using namespace std; string s[21]; int dx[]={1,1,1,0,0,-1,-1,-1}; int dy[]={1,0,-1,1,-1,1,0,-1}; int h,w; vector<string>v; set<string> se; void dfs(int d,int y,int x,int p,string t,int p1,int p2){ if(d&&y==p1&&x==p2)return; t+=s[y][x]; if(d){ if(!se.count(t))se.insert(t); else v.push_back(t); } x+=dx[p],y+=dy[p]; if(x<0)x=w-1; if(y<0)y=h-1; if(x>=w)x=0; if(y>=h)y=0; dfs(d+1,y,x,p,t,p1,p2); } int main(){ while(cin>>h>>w,h){ se.clear(); v.clear(); r(i,h)cin>>s[i]; r(i,h)r(j,w)r(k,8)dfs(0,i,j,k,"",i,j); sort(v.begin(),v.end()); int p=0; r(i,v.size())p=max(p,(int)v[i].size()); if(v.size())r(i,v.size()){ if(v[i].size()==p){ cout<<v[i]<<endl; break; } } else cout<<0<<endl; } }
### Prompt Create a solution in CPP for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<bits/stdc++.h> #define r(i,n) for(int i=0;i<n;i++) using namespace std; string s[21]; int dx[]={1,1,1,0,0,-1,-1,-1}; int dy[]={1,0,-1,1,-1,1,0,-1}; int h,w; vector<string>v; set<string> se; void dfs(int d,int y,int x,int p,string t,int p1,int p2){ if(d&&y==p1&&x==p2)return; t+=s[y][x]; if(d){ if(!se.count(t))se.insert(t); else v.push_back(t); } x+=dx[p],y+=dy[p]; if(x<0)x=w-1; if(y<0)y=h-1; if(x>=w)x=0; if(y>=h)y=0; dfs(d+1,y,x,p,t,p1,p2); } int main(){ while(cin>>h>>w,h){ se.clear(); v.clear(); r(i,h)cin>>s[i]; r(i,h)r(j,w)r(k,8)dfs(0,i,j,k,"",i,j); sort(v.begin(),v.end()); int p=0; r(i,v.size())p=max(p,(int)v[i].size()); if(v.size())r(i,v.size()){ if(v[i].size()==p){ cout<<v[i]<<endl; break; } } else cout<<0<<endl; } } ```
#include <algorithm> #include <functional> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <vector> #include <list> #include <stack> #include <queue> #include <map> #include <set> #include <bitset> #include <climits> #define all(c) (c).begin(), (c).end() #define rep(i,n) for(int i=0;i<(n);i++) #define pb(e) push_back(e) #define mp(a, b) make_pair(a, b) #define fr first #define sc second const int INF=100000000; int dx[] = {-1,0,1,1,1,0,-1,-1}; int dy[] = {1,1,1,0,-1,-1,-1,0}; using namespace std; typedef pair<int ,int > P; typedef long long ll; int H,W; string donut[11]; map<string, int> res; void dfs(string str,int sy,int sx, int y,int x,int a) { int ny = (y+dy[a]+H) % H; int nx = (x+dx[a]+W) % W; res[str]++; if(sy==ny && sx==nx) return; dfs(str+donut[ny][nx],sy,sx,ny,nx,a); } string cmp(string s1,string s2) { if(s1.size() > s2.size()) return s1; else if(s1.size() < s2.size()) return s2; else return s1 < s2 ? s1 : s2; } void solve() { res.clear(); rep(i,11) donut[i]=""; rep(i,H) cin>>donut[i]; rep(y,H) rep(x,W) { rep(a,8) { string tmp; tmp = donut[y][x]; dfs(tmp,y,x,y,x,a); } } string ans; for(const auto &it : res){ if(it.sc >= 2) { ans = cmp(ans,it.fr); } } if(ans.size() <= 2) ans = "0"; cout<<ans<<endl; } int main() { while(cin>>H>>W) { if(H+W==0) break; solve(); } return 0; }
### Prompt Please formulate a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <algorithm> #include <functional> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <vector> #include <list> #include <stack> #include <queue> #include <map> #include <set> #include <bitset> #include <climits> #define all(c) (c).begin(), (c).end() #define rep(i,n) for(int i=0;i<(n);i++) #define pb(e) push_back(e) #define mp(a, b) make_pair(a, b) #define fr first #define sc second const int INF=100000000; int dx[] = {-1,0,1,1,1,0,-1,-1}; int dy[] = {1,1,1,0,-1,-1,-1,0}; using namespace std; typedef pair<int ,int > P; typedef long long ll; int H,W; string donut[11]; map<string, int> res; void dfs(string str,int sy,int sx, int y,int x,int a) { int ny = (y+dy[a]+H) % H; int nx = (x+dx[a]+W) % W; res[str]++; if(sy==ny && sx==nx) return; dfs(str+donut[ny][nx],sy,sx,ny,nx,a); } string cmp(string s1,string s2) { if(s1.size() > s2.size()) return s1; else if(s1.size() < s2.size()) return s2; else return s1 < s2 ? s1 : s2; } void solve() { res.clear(); rep(i,11) donut[i]=""; rep(i,H) cin>>donut[i]; rep(y,H) rep(x,W) { rep(a,8) { string tmp; tmp = donut[y][x]; dfs(tmp,y,x,y,x,a); } } string ans; for(const auto &it : res){ if(it.sc >= 2) { ans = cmp(ans,it.fr); } } if(ans.size() <= 2) ans = "0"; cout<<ans<<endl; } int main() { while(cin>>H>>W) { if(H+W==0) break; solve(); } return 0; } ```
#include <iostream> #include <string> #include <vector> #include <set> using namespace std; #define rep(i, n) for(int i=0; i<(n); ++i) #define mp(a, b) make_pair(a, b) template<typename T, typename Compare = greater<T> > inline void chmax(T& t, T f, Compare comp){if(!comp(t, f))t = f;} int h, w; string solve(vector<string>& patterns){ string res = "0"; set<string> spells; rep(x, h)rep(y, w){ for(int dx=-1; dx<=1; ++dx){ for(int dy=-1; dy<=1; ++dy){ string spell = ""; spell += patterns[x][y]; for(int nx=(x+dx+h)%h, ny=(y+dy+w)%w; nx!=x || ny!=y; (nx+=(dx+h))%=h, (ny+=(dy+w))%=w){ spell += patterns[nx][ny]; if(!spells.insert(spell).second){ for(auto itr=spells.begin(); itr!=spells.end();){ if((*itr).size() < res.size())spells.erase(itr++); else itr++; } chmax(res, spell, [](string& s, string& t){return mp(t.size(), s) < mp(s.size(), t);}); } } } } } return res; } int main(){ while(cin >> h >> w, h|w){ vector<string> patterns(h); rep(i, h)cin >> patterns[i]; cout << solve(patterns) << '\n'; } return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <vector> #include <set> using namespace std; #define rep(i, n) for(int i=0; i<(n); ++i) #define mp(a, b) make_pair(a, b) template<typename T, typename Compare = greater<T> > inline void chmax(T& t, T f, Compare comp){if(!comp(t, f))t = f;} int h, w; string solve(vector<string>& patterns){ string res = "0"; set<string> spells; rep(x, h)rep(y, w){ for(int dx=-1; dx<=1; ++dx){ for(int dy=-1; dy<=1; ++dy){ string spell = ""; spell += patterns[x][y]; for(int nx=(x+dx+h)%h, ny=(y+dy+w)%w; nx!=x || ny!=y; (nx+=(dx+h))%=h, (ny+=(dy+w))%=w){ spell += patterns[nx][ny]; if(!spells.insert(spell).second){ for(auto itr=spells.begin(); itr!=spells.end();){ if((*itr).size() < res.size())spells.erase(itr++); else itr++; } chmax(res, spell, [](string& s, string& t){return mp(t.size(), s) < mp(s.size(), t);}); } } } } } return res; } int main(){ while(cin >> h >> w, h|w){ vector<string> patterns(h); rep(i, h)cin >> patterns[i]; cout << solve(patterns) << '\n'; } return 0; } ```
#include <bits/stdc++.h> #define For(i, a, b) for(int (i)=(int)(a); (i)<(int)(b); ++(i)) #define rFor(i, a, b) for(int (i)=(int)(a)-1; (i)>=(int)(b); --(i)) #define rep(i, n) For((i), 0, (n)) #define rrep(i, n) rFor((i), (n), 0) #define fi first #define se second using namespace std; typedef long long lint; typedef unsigned long long ulint; typedef pair<int, int> pii; template<class T> bool chmax(T &a, const T &b){if(a<b){a=b; return true;} return false;} template<class T> bool chmin(T &a, const T &b){if(a>b){a=b; return true;} return false;} template<class T> T div_floor(T a, T b){ if(b < 0) a *= -1, b *= -1; return a>=0 ? a/b : (a+1)/b-1; } template<class T> T div_ceil(T a, T b){ if(b < 0) a *= -1, b *= -1; return a>0 ? (a-1)/b+1 : a/b; } constexpr lint mod = 1e9+7; constexpr lint INF = mod * mod; constexpr int MAX = 300010; int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1}; int main(){ int h, w; while(scanf("%d%d", &h, &w) && h){ string s[h]; rep(i, h) cin >> s[i]; map<string, int> mp; rep(sx, h)rep(sy, w)rep(i, 8){ string tmp; int x = sx, y = sy; do{ tmp += s[x][y]; ++mp[tmp]; x = (x + dx[i] + h) % h; y = (y + dy[i] + w) % w; }while(x != sx || y != sy); } string ans = "0"; for(auto &p: mp)if(p.se >= 2){ if(ans.size() < p.fi.size() || (ans.size() == p.fi.size() && ans > p.fi)){ ans = p.fi; } } cout << ans << "\n"; } }
### Prompt Your challenge is to write a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> #define For(i, a, b) for(int (i)=(int)(a); (i)<(int)(b); ++(i)) #define rFor(i, a, b) for(int (i)=(int)(a)-1; (i)>=(int)(b); --(i)) #define rep(i, n) For((i), 0, (n)) #define rrep(i, n) rFor((i), (n), 0) #define fi first #define se second using namespace std; typedef long long lint; typedef unsigned long long ulint; typedef pair<int, int> pii; template<class T> bool chmax(T &a, const T &b){if(a<b){a=b; return true;} return false;} template<class T> bool chmin(T &a, const T &b){if(a>b){a=b; return true;} return false;} template<class T> T div_floor(T a, T b){ if(b < 0) a *= -1, b *= -1; return a>=0 ? a/b : (a+1)/b-1; } template<class T> T div_ceil(T a, T b){ if(b < 0) a *= -1, b *= -1; return a>0 ? (a-1)/b+1 : a/b; } constexpr lint mod = 1e9+7; constexpr lint INF = mod * mod; constexpr int MAX = 300010; int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1}; int main(){ int h, w; while(scanf("%d%d", &h, &w) && h){ string s[h]; rep(i, h) cin >> s[i]; map<string, int> mp; rep(sx, h)rep(sy, w)rep(i, 8){ string tmp; int x = sx, y = sy; do{ tmp += s[x][y]; ++mp[tmp]; x = (x + dx[i] + h) % h; y = (y + dy[i] + w) % w; }while(x != sx || y != sy); } string ans = "0"; for(auto &p: mp)if(p.se >= 2){ if(ans.size() < p.fi.size() || (ans.size() == p.fi.size() && ans > p.fi)){ ans = p.fi; } } cout << ans << "\n"; } } ```
//Name: The Sorcerer's Donut //Level: //Category: //Note: #include <iostream> #include <cstdio> #include <vector> #include <algorithm> #include <string> #include <array> #include <map> using namespace std; #define TIMES(i,n) for(int i = 0; i < (n); ++i) const int DR[] = { 0, -1, -1, -1, 0, 1, 1, 1 }; const int DC[] = { 1, 1, 0, -1, -1, -1, 0, 1 }; array<array<bool,20>,10> visited; string search(int r, int c, int dir, const vector<string> &s, map<string,int> &memo) { const int H = s.size(); const int W = s[0].size(); string res; TIMES(i, H) { TIMES(j, W) { visited[i][j] = false; } } while(!visited[r][c]) { visited[r][c] = true; res += s[r][c]; if(res.size() > 1) memo[res]++; r = (r+DR[dir]+H) % H; c = (c+DC[dir]+W) % W; } return res; } bool solve() { int H, W; cin >> H >> W; if(!H && !W) return false; vector<string> s(H); TIMES(i, H) { cin >> s[i]; } map<string,int> memo; for(int r = 0; r < H; ++r) { for(int c = 0; c < W; ++c) { for(int dir = 0; dir < 8; ++dir) { search(r, c, dir, s, memo); } } } string ans = ""; for(const auto &p : memo) { if(p.second < 2) continue; if(p.first.size() > ans.size() || (p.first.size() == ans.size() && p.first < ans)) { ans = p.first; } } if(ans == "") ans = "0"; cout << ans << endl; return true; } int main() { cin.tie(0); ios::sync_with_stdio(0); while(solve()) ; return 0; }
### Prompt Please create a solution in CPP to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp //Name: The Sorcerer's Donut //Level: //Category: //Note: #include <iostream> #include <cstdio> #include <vector> #include <algorithm> #include <string> #include <array> #include <map> using namespace std; #define TIMES(i,n) for(int i = 0; i < (n); ++i) const int DR[] = { 0, -1, -1, -1, 0, 1, 1, 1 }; const int DC[] = { 1, 1, 0, -1, -1, -1, 0, 1 }; array<array<bool,20>,10> visited; string search(int r, int c, int dir, const vector<string> &s, map<string,int> &memo) { const int H = s.size(); const int W = s[0].size(); string res; TIMES(i, H) { TIMES(j, W) { visited[i][j] = false; } } while(!visited[r][c]) { visited[r][c] = true; res += s[r][c]; if(res.size() > 1) memo[res]++; r = (r+DR[dir]+H) % H; c = (c+DC[dir]+W) % W; } return res; } bool solve() { int H, W; cin >> H >> W; if(!H && !W) return false; vector<string> s(H); TIMES(i, H) { cin >> s[i]; } map<string,int> memo; for(int r = 0; r < H; ++r) { for(int c = 0; c < W; ++c) { for(int dir = 0; dir < 8; ++dir) { search(r, c, dir, s, memo); } } } string ans = ""; for(const auto &p : memo) { if(p.second < 2) continue; if(p.first.size() > ans.size() || (p.first.size() == ans.size() && p.first < ans)) { ans = p.first; } } if(ans == "") ans = "0"; cout << ans << endl; return true; } int main() { cin.tie(0); ios::sync_with_stdio(0); while(solve()) ; return 0; } ```
#include <iostream> #include <vector> #include <algorithm> #include <map> #include <string> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) const int dx[8] = { 1,1,0,-1,-1,-1,0,1 }; const int dy[8] = { 0,1,1,1,0,-1,-1,-1 }; int w, h; char grid[10][20]; map<string, int> spell; void dfs(int sy, int sx, int y, int x, int d, string str) { spell[str]++; int ny = (y + dy[d] + h) % h; int nx = (x + dx[d] + w) % w; if (ny == sy&&nx == sx) { return; } dfs(sy, sx, ny, nx, d, str + grid[ny][nx]); } int main() { while (true) { cin >> h >> w; if (h == 0 && w == 0) { break; } spell.clear(); vector<vector<bool>> visited(h, vector<bool>(w, false)); rep(y, h) { rep(x, w) { cin >> grid[y][x]; } } rep(y, h) { rep(x, w) { rep(d, 8) { string str; dfs(y, x, y, x, d, str + grid[y][x]); } } } string ans; for (auto it = spell.begin(); it != spell.end(); it++) { if (it->second >= 2) { if (ans.size() < it->first.size()) { ans = it->first; } else if (ans.size() == it->first.size()) { if (it->first < ans) { ans = it->first; } } } } if (ans.size() != 1) { cout << ans << endl; } else { cout << 0 << endl; } } return 0; }
### Prompt Generate a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <algorithm> #include <map> #include <string> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) const int dx[8] = { 1,1,0,-1,-1,-1,0,1 }; const int dy[8] = { 0,1,1,1,0,-1,-1,-1 }; int w, h; char grid[10][20]; map<string, int> spell; void dfs(int sy, int sx, int y, int x, int d, string str) { spell[str]++; int ny = (y + dy[d] + h) % h; int nx = (x + dx[d] + w) % w; if (ny == sy&&nx == sx) { return; } dfs(sy, sx, ny, nx, d, str + grid[ny][nx]); } int main() { while (true) { cin >> h >> w; if (h == 0 && w == 0) { break; } spell.clear(); vector<vector<bool>> visited(h, vector<bool>(w, false)); rep(y, h) { rep(x, w) { cin >> grid[y][x]; } } rep(y, h) { rep(x, w) { rep(d, 8) { string str; dfs(y, x, y, x, d, str + grid[y][x]); } } } string ans; for (auto it = spell.begin(); it != spell.end(); it++) { if (it->second >= 2) { if (ans.size() < it->first.size()) { ans = it->first; } else if (ans.size() == it->first.size()) { if (it->first < ans) { ans = it->first; } } } } if (ans.size() != 1) { cout << ans << endl; } else { cout << 0 << endl; } } return 0; } ```
#include <iostream> #include <string> #include <set> using namespace std; string mp[11]; int w,h; set <string> cnt; string ans; void check(int x,int y){ string str; for(int i=-1;i<=1;i++) for(int j=-1;j<=1;j++){ if(i==0 && j==0) continue; str = mp[y][x]; int nx=(x+j+w)%w,ny=(y+i+h)%h; while(ny!=y || nx!=x){ str+=mp[ny][nx],nx=(nx+j+w)%w,ny=(ny+i+h)%h; if(cnt.count(str)){ if(str.size()>ans.size()) ans = str; else if(str.size()==ans.size()) ans = min(str,ans); } else cnt.insert(str); } } } int main(){ while(1) { cin >> h >> w; cnt.clear(); if(w == 0 && h == 0) break; for(int i=0;i<h;i++) cin >> mp[i]; ans = ""; for(int i=0;i<h;i++) for(int j=0;j<w;j++)check(j,i); if(ans.size()==0) ans = "0"; cout << ans << endl; } return 0; }
### Prompt Please create a solution in Cpp to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <set> using namespace std; string mp[11]; int w,h; set <string> cnt; string ans; void check(int x,int y){ string str; for(int i=-1;i<=1;i++) for(int j=-1;j<=1;j++){ if(i==0 && j==0) continue; str = mp[y][x]; int nx=(x+j+w)%w,ny=(y+i+h)%h; while(ny!=y || nx!=x){ str+=mp[ny][nx],nx=(nx+j+w)%w,ny=(ny+i+h)%h; if(cnt.count(str)){ if(str.size()>ans.size()) ans = str; else if(str.size()==ans.size()) ans = min(str,ans); } else cnt.insert(str); } } } int main(){ while(1) { cin >> h >> w; cnt.clear(); if(w == 0 && h == 0) break; for(int i=0;i<h;i++) cin >> mp[i]; ans = ""; for(int i=0;i<h;i++) for(int j=0;j<w;j++)check(j,i); if(ans.size()==0) ans = "0"; cout << ans << endl; } return 0; } ```
#include <bits/stdc++.h> #define syosu(x) fixed<<setprecision(x) using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; typedef pair<int,int> P; typedef pair<double,double> pdd; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<string> vs; typedef vector<P> vp; typedef vector<vp> vvp; typedef vector<pll> vpll; typedef pair<int,P> pip; typedef vector<pip> vip; const int inf=1<<29; const ll INF=1ll<<60; const double pi=acos(-1); const double eps=1e-9; const ll mod=1e9+7; //const int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1}; const int dx[8]={-1,0,1,0,-1,-1,1,1},dy[8]={0,-1,0,1,-1,1,-1,1}; const int N=16; int main(){ ios::sync_with_stdio(0); cin.tie(0); while(1){ int h,w; cin>>h>>w; if(h==0) break; vs a(h); for(auto &i:a) cin>>i; map<string,int> mp; for(int i=0;i<h;i++) for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ vvi b(h,vi(w)); int x=i,y=j; string s; while(!b[x][y]){ b[x][y]=1; s+=a[x][y]; x+=dx[k],y+=dy[k]; if(x>=h) x=0; if(x<0) x=h-1; if(y>=w) y=0; if(y<0) y=w-1; mp[s]++; } // cout<<i<<' '<<j<<' '<<k<<' '<<s<<endl; // mp[s]++; } } string res=""; for(auto p:mp) if(p.second>1&&p.first.size()>res.size()){ res=p.first; } if(res.size()<=1) res="0"; cout<<res<<endl; // cout<<mp["ABRACADABRA"]<<endl; } }
### Prompt Develop a solution in Cpp to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> #define syosu(x) fixed<<setprecision(x) using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; typedef pair<int,int> P; typedef pair<double,double> pdd; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<string> vs; typedef vector<P> vp; typedef vector<vp> vvp; typedef vector<pll> vpll; typedef pair<int,P> pip; typedef vector<pip> vip; const int inf=1<<29; const ll INF=1ll<<60; const double pi=acos(-1); const double eps=1e-9; const ll mod=1e9+7; //const int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1}; const int dx[8]={-1,0,1,0,-1,-1,1,1},dy[8]={0,-1,0,1,-1,1,-1,1}; const int N=16; int main(){ ios::sync_with_stdio(0); cin.tie(0); while(1){ int h,w; cin>>h>>w; if(h==0) break; vs a(h); for(auto &i:a) cin>>i; map<string,int> mp; for(int i=0;i<h;i++) for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ vvi b(h,vi(w)); int x=i,y=j; string s; while(!b[x][y]){ b[x][y]=1; s+=a[x][y]; x+=dx[k],y+=dy[k]; if(x>=h) x=0; if(x<0) x=h-1; if(y>=w) y=0; if(y<0) y=w-1; mp[s]++; } // cout<<i<<' '<<j<<' '<<k<<' '<<s<<endl; // mp[s]++; } } string res=""; for(auto p:mp) if(p.second>1&&p.first.size()>res.size()){ res=p.first; } if(res.size()<=1) res="0"; cout<<res<<endl; // cout<<mp["ABRACADABRA"]<<endl; } } ```
#include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; int main(){ int h,w; int dx[] = {-1,0,1,-1,1,-1,0,1}; int dy[] = {1,1,1,0,0,-1,-1,-1}; while(cin >> h >> w && h && w){ char c[11][21]; set<string> s; string ans = ""; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> c[i][j]; } } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ int x = j; int y = i; string str; str += c[y][x]; while(1){ x += dx[k]; y += dy[k]; if(x < 0) x = w - 1; else if(x >= w) x = 0; if(y < 0) y = h - 1; else if(y >= h) y = 0; if(x == j && y == i) break; else str += c[y][x]; if(!s.empty() && s.find(str) != s.end() && str.size() > ans.size()) ans = str; else if(!s.empty() && s.find(str) != s.end() && str.size() == ans.size() && str < ans) ans = str; else s.insert(str); } } } } if(ans != "") cout << ans << endl; else cout << "0" << endl; } return 0; }
### Prompt Create a solution in Cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; int main(){ int h,w; int dx[] = {-1,0,1,-1,1,-1,0,1}; int dy[] = {1,1,1,0,0,-1,-1,-1}; while(cin >> h >> w && h && w){ char c[11][21]; set<string> s; string ans = ""; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> c[i][j]; } } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ int x = j; int y = i; string str; str += c[y][x]; while(1){ x += dx[k]; y += dy[k]; if(x < 0) x = w - 1; else if(x >= w) x = 0; if(y < 0) y = h - 1; else if(y >= h) y = 0; if(x == j && y == i) break; else str += c[y][x]; if(!s.empty() && s.find(str) != s.end() && str.size() > ans.size()) ans = str; else if(!s.empty() && s.find(str) != s.end() && str.size() == ans.size() && str < ans) ans = str; else s.insert(str); } } } } if(ans != "") cout << ans << endl; else cout << "0" << endl; } return 0; } ```
#include<iostream> #include<algorithm> #include<vector> #include<string> #include<map> using namespace std; void chmax(string& s1, string& s2) { if (s1.size() > s2.size()) return; else if (s1.size() < s2.size()) { s1 = s2; return; } else { for (int i = 0; i < s1.size(); i++) { if (s1[i] > s2[i]) { s1 = s2; return; } else if (s1[i] < s2[i]) return; } } } bool is_palindrome(string s) { int n = s.size(); for (int i = 0; i < n / 2; i++) { if (s[i] != s[n - i - 1]) return false; } return true; } int dh[3] = {-1, 0, 1}, dw[3] = {-1, 0, 1}; void solve(int h, int w) { vector<string> grid(h); for (int i = 0; i < h; i++) { cin >> grid[i]; } vector<string> s; map<string, int> cnt; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { if (k == 1 && l == 1) continue; int now_h = i, now_w = j; string now_s; do { now_s.push_back(grid[now_h][now_w]); s.push_back(now_s); cnt[now_s]++; now_h = (now_h + dh[k] + h) % h; now_w = (now_w + dw[l] + w) % w; } while (now_h != i || now_w != j); } } } } sort(s.begin(), s.end()); s.erase(unique(s.begin(), s.end()), s.end()); string ans = ""; for (int i = 0; i < s.size(); i++) { if (s[i].size() == 1) continue; if (cnt[s[i]] < 2 && !is_palindrome(s[i])) continue; chmax(ans, s[i]); } if (ans == "") cout << 0 << endl; else cout << ans << endl; } int main() { cin.tie(0); ios::sync_with_stdio(false); int H, W; while (true) { cin >> H >> W; if (H == 0 && W == 0) break; solve(H, W); } return 0; }
### Prompt Construct a cpp code solution to the problem outlined: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<algorithm> #include<vector> #include<string> #include<map> using namespace std; void chmax(string& s1, string& s2) { if (s1.size() > s2.size()) return; else if (s1.size() < s2.size()) { s1 = s2; return; } else { for (int i = 0; i < s1.size(); i++) { if (s1[i] > s2[i]) { s1 = s2; return; } else if (s1[i] < s2[i]) return; } } } bool is_palindrome(string s) { int n = s.size(); for (int i = 0; i < n / 2; i++) { if (s[i] != s[n - i - 1]) return false; } return true; } int dh[3] = {-1, 0, 1}, dw[3] = {-1, 0, 1}; void solve(int h, int w) { vector<string> grid(h); for (int i = 0; i < h; i++) { cin >> grid[i]; } vector<string> s; map<string, int> cnt; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { if (k == 1 && l == 1) continue; int now_h = i, now_w = j; string now_s; do { now_s.push_back(grid[now_h][now_w]); s.push_back(now_s); cnt[now_s]++; now_h = (now_h + dh[k] + h) % h; now_w = (now_w + dw[l] + w) % w; } while (now_h != i || now_w != j); } } } } sort(s.begin(), s.end()); s.erase(unique(s.begin(), s.end()), s.end()); string ans = ""; for (int i = 0; i < s.size(); i++) { if (s[i].size() == 1) continue; if (cnt[s[i]] < 2 && !is_palindrome(s[i])) continue; chmax(ans, s[i]); } if (ans == "") cout << 0 << endl; else cout << ans << endl; } int main() { cin.tie(0); ios::sync_with_stdio(false); int H, W; while (true) { cin >> H >> W; if (H == 0 && W == 0) break; solve(H, W); } return 0; } ```
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef pair<int, int> pii; typedef long long ll; #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(),(a).rend() #define EXIST(s,e) ((s).find(e)!=(s).end()) #define FOR(i,a,b) for(int i=(a); i<(b); ++i) #define REP(i,n) FOR(i,0,n) int dy[]={-1,-1,-1,0,1,1,1,0}; int dx[]={-1,0,1,1,1,0,-1,-1}; int main(){ int h,w; while(cin>>h>>w,h|w){ vs f(h); REP(i,h){ cin>>f[i]; } string ans; map<string,int> cnt; REP(i,h){ REP(j,w){ REP(d,8){ int y=i,x=j; string tmp; do{ tmp+=f[y][x]; if(tmp.size()>=2){ cnt[tmp]++; if(cnt[tmp]>=2){ if(ans.size()<tmp.size()||(ans.size()==tmp.size()&&ans>tmp)){ ans=tmp; } } } y+=dy[d]; x+=dx[d]; if(y<0)y=h-1; if(x<0)x=w-1; if(y>=h)y=0; if(x>=w)x=0; }while(y!=i||x!=j); } } } if(ans.size()){ cout<<ans<<endl; }else{ cout<<0<<endl; } } }
### Prompt Your challenge is to write a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef pair<int, int> pii; typedef long long ll; #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(),(a).rend() #define EXIST(s,e) ((s).find(e)!=(s).end()) #define FOR(i,a,b) for(int i=(a); i<(b); ++i) #define REP(i,n) FOR(i,0,n) int dy[]={-1,-1,-1,0,1,1,1,0}; int dx[]={-1,0,1,1,1,0,-1,-1}; int main(){ int h,w; while(cin>>h>>w,h|w){ vs f(h); REP(i,h){ cin>>f[i]; } string ans; map<string,int> cnt; REP(i,h){ REP(j,w){ REP(d,8){ int y=i,x=j; string tmp; do{ tmp+=f[y][x]; if(tmp.size()>=2){ cnt[tmp]++; if(cnt[tmp]>=2){ if(ans.size()<tmp.size()||(ans.size()==tmp.size()&&ans>tmp)){ ans=tmp; } } } y+=dy[d]; x+=dx[d]; if(y<0)y=h-1; if(x<0)x=w-1; if(y>=h)y=0; if(x>=w)x=0; }while(y!=i||x!=j); } } } if(ans.size()){ cout<<ans<<endl; }else{ cout<<0<<endl; } } } ```
#include <iostream> #include <cstdio> #include <string> #include <set> #include <vector> #include <utility> using namespace std; set<string> Ws; set<string> W; const int dx[8] = {1, 1, 1, 0, 0, -1, -1, -1}; const int dy[8] = {1, 0, -1, 1, -1, 1, 0, -1}; typedef pair<int, string> spell; int main() { int h, w; while (scanf("%d%d", &h, &w) != EOF && w) { Ws.clear(); vector< vector<char> > table = vector< vector<char> >(h, vector<char>(w)); for (auto i=0; i<h; i++) { for (auto j=0; j<w; j++) { scanf(" %c", &table[i][j]); } } string MS = ""; int MSsize = 0; spell A = make_pair(-1*MSsize, MS); for (auto i=0; i<h; i++) { for (auto j=0; j<w; j++) { W.clear(); for (auto d=0; d<8; d++) { string S = ""; S += table[i][j]; vector< vector<bool> > visited = vector< vector<bool> >(h, vector<bool>(w, false)); visited[i][j] = true; int ni, nj; for (auto k=1; !visited[(ni = (h*w+i+dx[d]*k)%h)][(nj = (h*w+j+dy[d]*k)%w)]; k++) { visited[ni][nj] = true; S += table[ni][nj]; // cerr << S << endl; W.insert(S); } } for (auto k=W.begin(); k != W.end(); k++) { string S; if (Ws.find((S = *k)) != Ws.end()) { spell t; if ((t = make_pair(-1*(int)(S.size()), S)) < A) A = t; } else { Ws.insert(S); } } } } cout << (A.second == "" ? "0" : A.second) << endl; } return 0; }
### Prompt Create a solution in Cpp for the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <cstdio> #include <string> #include <set> #include <vector> #include <utility> using namespace std; set<string> Ws; set<string> W; const int dx[8] = {1, 1, 1, 0, 0, -1, -1, -1}; const int dy[8] = {1, 0, -1, 1, -1, 1, 0, -1}; typedef pair<int, string> spell; int main() { int h, w; while (scanf("%d%d", &h, &w) != EOF && w) { Ws.clear(); vector< vector<char> > table = vector< vector<char> >(h, vector<char>(w)); for (auto i=0; i<h; i++) { for (auto j=0; j<w; j++) { scanf(" %c", &table[i][j]); } } string MS = ""; int MSsize = 0; spell A = make_pair(-1*MSsize, MS); for (auto i=0; i<h; i++) { for (auto j=0; j<w; j++) { W.clear(); for (auto d=0; d<8; d++) { string S = ""; S += table[i][j]; vector< vector<bool> > visited = vector< vector<bool> >(h, vector<bool>(w, false)); visited[i][j] = true; int ni, nj; for (auto k=1; !visited[(ni = (h*w+i+dx[d]*k)%h)][(nj = (h*w+j+dy[d]*k)%w)]; k++) { visited[ni][nj] = true; S += table[ni][nj]; // cerr << S << endl; W.insert(S); } } for (auto k=W.begin(); k != W.end(); k++) { string S; if (Ws.find((S = *k)) != Ws.end()) { spell t; if ((t = make_pair(-1*(int)(S.size()), S)) < A) A = t; } else { Ws.insert(S); } } } } cout << (A.second == "" ? "0" : A.second) << endl; } return 0; } ```
#include <vector> #include <iostream> #include <utility> #include <algorithm> #include <string> #include <deque> #include <tuple> #include <queue> #include <functional> #include <cmath> #include <iomanip> #include <map> //cin.sync_with_stdio(false); //streambuf using namespace std; typedef long long ll; typedef pair<int, int> pii; int main() { int h, w; while (cin >> h >> w, h) { vector<string> map(h); for (auto &a : map)cin >> a; int dx[] = { 0,0,1,1,1,-1,-1,-1 }; int dy[] = { 1,-1,0,-1,1,0,1,-1 }; vector<tuple<string, int, int, int>> buf; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int d = 0; d < 8; d++) { buf.push_back(make_tuple((string)"" + map[i][j], j, i, d)); } } } int l = 1; for (;; l++) { sort(buf.begin(), buf.end()); vector<tuple<string, int, int, int>> buf2; for (int i = 1; i < buf.size(); i++) { if (get<0>(buf[i - 1]).size() < l)continue; if (get<0>(buf[i - 1]) == get<0>(buf[i]))buf2.push_back(buf[i - 1]); for (; i<buf.size()&&get<0>(buf[i - 1]) == get<0>(buf[i]); i++)buf2.push_back(buf[i]); } if (buf2.empty())break; buf = move(buf2); for (auto &a : buf) { string str; int x, y, d; tie(str, x, y, d) = a; int x1 = ((x + dx[d]*l) % w + w) % w; int y1 = ((y + dy[d]*l) % h + h) % h; if (x1 == x && y1 == y)continue; str += map[y1][x1]; a = make_tuple(str, x, y, d); } } if (l < 3)cout << 0 << endl; else { string str = get<0>(buf[0]); cout << str.substr(0, l-1) << endl; } } return 0; }
### Prompt Please create a solution in cpp to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <vector> #include <iostream> #include <utility> #include <algorithm> #include <string> #include <deque> #include <tuple> #include <queue> #include <functional> #include <cmath> #include <iomanip> #include <map> //cin.sync_with_stdio(false); //streambuf using namespace std; typedef long long ll; typedef pair<int, int> pii; int main() { int h, w; while (cin >> h >> w, h) { vector<string> map(h); for (auto &a : map)cin >> a; int dx[] = { 0,0,1,1,1,-1,-1,-1 }; int dy[] = { 1,-1,0,-1,1,0,1,-1 }; vector<tuple<string, int, int, int>> buf; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { for (int d = 0; d < 8; d++) { buf.push_back(make_tuple((string)"" + map[i][j], j, i, d)); } } } int l = 1; for (;; l++) { sort(buf.begin(), buf.end()); vector<tuple<string, int, int, int>> buf2; for (int i = 1; i < buf.size(); i++) { if (get<0>(buf[i - 1]).size() < l)continue; if (get<0>(buf[i - 1]) == get<0>(buf[i]))buf2.push_back(buf[i - 1]); for (; i<buf.size()&&get<0>(buf[i - 1]) == get<0>(buf[i]); i++)buf2.push_back(buf[i]); } if (buf2.empty())break; buf = move(buf2); for (auto &a : buf) { string str; int x, y, d; tie(str, x, y, d) = a; int x1 = ((x + dx[d]*l) % w + w) % w; int y1 = ((y + dy[d]*l) % h + h) % h; if (x1 == x && y1 == y)continue; str += map[y1][x1]; a = make_tuple(str, x, y, d); } } if (l < 3)cout << 0 << endl; else { string str = get<0>(buf[0]); cout << str.substr(0, l-1) << endl; } } return 0; } ```
#include <iostream> #include <string> #include <stdio.h> #include <set> using namespace std; #define dirmax 8 int l[2]; int dir[8][2] = { {0,1}, {1,0}, {-1,0}, {0,-1}, {1,1}, {-1,1}, {1,-1}, {-1,-1} }; string ans; void search( set<string> *v, int pos[2] , char ch[10][20]){ for(int i = 0; i < dirmax; i++) { string str; int cpos[] = { pos[0], pos[1] }; str += ch[pos[0]][pos[1]]; while( 1 ) { for(int j = 0; j < 2; j++) { cpos[j] += dir[i][j]; if( cpos[j] < 0 ) cpos[j] = l[j] - 1; if( cpos[j] >= l[j] ) cpos[j] = 0; } if( cpos[0] == pos[0] && cpos[1] == pos[1] ) break; str += ch[cpos[0]][cpos[1]]; if( v->find(str) != v->end() ) { if( ( str.length() > ans.length() ) || ( str.length() == ans.length() && str < ans ) ) { ans = str; } } else v->insert(str); } } } int main(void){ while(1){ cin >> l[0] >> l[1]; if( l[0] == 0 && l[1] == 0 ) break; char donut[10][20]; int pos[2]; ans = ""; set< string > strs; for(int i = 0; i < l[0]; i++) cin >> donut[i]; for(pos[0] = 0; pos[0] < l[0]; pos[0]++) for(pos[1] = 0; pos[1] < l[1]; pos[1]++) search( &strs, pos, donut ); if(ans == "") cout << 0 << endl; else cout << ans << endl; } return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <stdio.h> #include <set> using namespace std; #define dirmax 8 int l[2]; int dir[8][2] = { {0,1}, {1,0}, {-1,0}, {0,-1}, {1,1}, {-1,1}, {1,-1}, {-1,-1} }; string ans; void search( set<string> *v, int pos[2] , char ch[10][20]){ for(int i = 0; i < dirmax; i++) { string str; int cpos[] = { pos[0], pos[1] }; str += ch[pos[0]][pos[1]]; while( 1 ) { for(int j = 0; j < 2; j++) { cpos[j] += dir[i][j]; if( cpos[j] < 0 ) cpos[j] = l[j] - 1; if( cpos[j] >= l[j] ) cpos[j] = 0; } if( cpos[0] == pos[0] && cpos[1] == pos[1] ) break; str += ch[cpos[0]][cpos[1]]; if( v->find(str) != v->end() ) { if( ( str.length() > ans.length() ) || ( str.length() == ans.length() && str < ans ) ) { ans = str; } } else v->insert(str); } } } int main(void){ while(1){ cin >> l[0] >> l[1]; if( l[0] == 0 && l[1] == 0 ) break; char donut[10][20]; int pos[2]; ans = ""; set< string > strs; for(int i = 0; i < l[0]; i++) cin >> donut[i]; for(pos[0] = 0; pos[0] < l[0]; pos[0]++) for(pos[1] = 0; pos[1] < l[1]; pos[1]++) search( &strs, pos, donut ); if(ans == "") cout << 0 << endl; else cout << ans << endl; } return 0; } ```
#include <iostream> #include <vector> #include <queue> #include <cstring> #include <cstdio> #include <algorithm> #include <complex> #include <set> #include <map> #include <cmath> using namespace std; int dx[] = {-1,-1,-1,0,0,1,1,1}; int dy[] = {-1,0,1,-1,1,-1,0,1}; int main(){ int H,W; while(cin >> H >> W && H ){ vector<string> s(H); for(int i = 0 ; i < H ; i++) cin >> s[i]; map<string,int> answer; for(int i = 0 ; i < H ; i++){ for(int j = 0 ; j < W ; j++){ for(int d = 0 ; d < 8 ; d++){ string wow; int done[20][20] = {}; int x = j , y = i; while( done[y][x] == 0 ){ wow += s[y][x]; done[y][x] = true; answer[wow]++; x += dx[d]; y += dy[d]; x += W; y += H; x %= W; y %= H; } } } } int len = 0; for( map<string,int>::iterator it = answer.begin(); it != answer.end() ; it++){ if( it->second < 2 || it->first.size() < 2 ) continue; len = max( len , (int)it->first.size() ); } int flag = 0; for( map<string,int>::iterator it = answer.begin(); it != answer.end() ; it++){ if( it->second < 2 || it->first.size() < 2 ) continue; if( len == it->first.size() ){ cout << it->first << endl; flag = true; break; } } if(flag==0)cout << 0 << endl; } }
### Prompt In CPP, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <queue> #include <cstring> #include <cstdio> #include <algorithm> #include <complex> #include <set> #include <map> #include <cmath> using namespace std; int dx[] = {-1,-1,-1,0,0,1,1,1}; int dy[] = {-1,0,1,-1,1,-1,0,1}; int main(){ int H,W; while(cin >> H >> W && H ){ vector<string> s(H); for(int i = 0 ; i < H ; i++) cin >> s[i]; map<string,int> answer; for(int i = 0 ; i < H ; i++){ for(int j = 0 ; j < W ; j++){ for(int d = 0 ; d < 8 ; d++){ string wow; int done[20][20] = {}; int x = j , y = i; while( done[y][x] == 0 ){ wow += s[y][x]; done[y][x] = true; answer[wow]++; x += dx[d]; y += dy[d]; x += W; y += H; x %= W; y %= H; } } } } int len = 0; for( map<string,int>::iterator it = answer.begin(); it != answer.end() ; it++){ if( it->second < 2 || it->first.size() < 2 ) continue; len = max( len , (int)it->first.size() ); } int flag = 0; for( map<string,int>::iterator it = answer.begin(); it != answer.end() ; it++){ if( it->second < 2 || it->first.size() < 2 ) continue; if( len == it->first.size() ){ cout << it->first << endl; flag = true; break; } } if(flag==0)cout << 0 << endl; } } ```
#include "iostream" #include "climits" #include "list" #include "queue" #include "stack" #include "set" #include "functional" #include "algorithm" #include "string" #include "map" #include "unordered_map" #include "unordered_set" #include "iomanip" #include "cmath" #include "random" #include "bitset" #include "cstdio" #include "numeric" #include "cassert" #include "ctime" using namespace std; constexpr long long int MOD = 1000000007; //constexpr int MOD = 1000000007; //constexpr int MOD = 998244353; //constexpr long long int MOD = 998244353; constexpr double EPS = 1e-12; //int N, M, K, T, H, W, L, R; long long int N, M, K, T, H, W, L, R; int dx[] = { 1,1,1,0,-1,-1,-1,0 }; int dy[] = { 1,0,-1,-1,-1,0,1,1 }; struct Node { int x, y, d; Node(int a, int b, int c) { x = a, y = b, d = c; } bool operator<(const Node&n)const { return make_pair(x, y) < make_pair(n.x, n.y); } }; int main() { ios::sync_with_stdio(false); cin.tie(0); while (cin >> H >> W, H) { vector<string>s(H); for (auto &i : s)cin >> i; map<string, set<Node>>st; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { for (int k = 0; k < 8; k++) { string box; vector<vector<int>>visited(H, vector<int>(W)); int ny = i, nx = j; while (!visited[ny][nx]) { visited[ny][nx] = 1; box.push_back(s[ny][nx]); ny += dy[k]; nx += dx[k]; if (ny < 0)ny += H; if (ny >= H)ny -= H; if (nx < 0)nx += W; if (nx >= W)nx -= W; st[box].insert(Node(i, j, k)); } } } } string ans = ""; for (auto i : st) { if (i.second.size() == 1)continue; if (ans.size() < i.first.size())ans = i.first; } if (ans.size() <= 1) { cout << 0 << endl; } else cout << ans << endl; } }
### Prompt Please provide a Cpp coded solution to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include "iostream" #include "climits" #include "list" #include "queue" #include "stack" #include "set" #include "functional" #include "algorithm" #include "string" #include "map" #include "unordered_map" #include "unordered_set" #include "iomanip" #include "cmath" #include "random" #include "bitset" #include "cstdio" #include "numeric" #include "cassert" #include "ctime" using namespace std; constexpr long long int MOD = 1000000007; //constexpr int MOD = 1000000007; //constexpr int MOD = 998244353; //constexpr long long int MOD = 998244353; constexpr double EPS = 1e-12; //int N, M, K, T, H, W, L, R; long long int N, M, K, T, H, W, L, R; int dx[] = { 1,1,1,0,-1,-1,-1,0 }; int dy[] = { 1,0,-1,-1,-1,0,1,1 }; struct Node { int x, y, d; Node(int a, int b, int c) { x = a, y = b, d = c; } bool operator<(const Node&n)const { return make_pair(x, y) < make_pair(n.x, n.y); } }; int main() { ios::sync_with_stdio(false); cin.tie(0); while (cin >> H >> W, H) { vector<string>s(H); for (auto &i : s)cin >> i; map<string, set<Node>>st; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { for (int k = 0; k < 8; k++) { string box; vector<vector<int>>visited(H, vector<int>(W)); int ny = i, nx = j; while (!visited[ny][nx]) { visited[ny][nx] = 1; box.push_back(s[ny][nx]); ny += dy[k]; nx += dx[k]; if (ny < 0)ny += H; if (ny >= H)ny -= H; if (nx < 0)nx += W; if (nx >= W)nx -= W; st[box].insert(Node(i, j, k)); } } } } string ans = ""; for (auto i : st) { if (i.second.size() == 1)continue; if (ans.size() < i.first.size())ans = i.first; } if (ans.size() <= 1) { cout << 0 << endl; } else cout << ans << endl; } } ```
#include<iostream> #include<string> #include<vector> #include<set> using namespace std; int w,h; int dx[8]={0,1,1,1,0,-1,-1,-1}; int dy[8]={-1,-1,0,1,1,1,0,-1}; void solve(){ set<string> S; vector<string> V; for(int i=0;i<h;i++){ string s; cin>>s; V.push_back(s); } string res=""; for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ for(int r=0;r<8;r++){ int nx=x,ny=y; string read=""; while(!(nx==x && ny==y) || read.size()==0){ read+=V[ny][nx]; if(S.count(read)){ if(res.size()<read.size()) res=read; if(res.size()==read.size() && res>read) res=read; } S.insert(read); ny+=dy[r]; nx+=dx[r]; if(ny<0) ny=h-1; if(ny>=h) ny=0; if(nx<0) nx=w-1; if(nx>=w) nx=0; } } } } if(res.size()>1) cout<<res<<endl; else cout<<0<<endl; } int main() { while(cin>>h>>w){ if(h==0) break; solve(); } return 0; }
### Prompt Develop a solution in Cpp to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<string> #include<vector> #include<set> using namespace std; int w,h; int dx[8]={0,1,1,1,0,-1,-1,-1}; int dy[8]={-1,-1,0,1,1,1,0,-1}; void solve(){ set<string> S; vector<string> V; for(int i=0;i<h;i++){ string s; cin>>s; V.push_back(s); } string res=""; for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ for(int r=0;r<8;r++){ int nx=x,ny=y; string read=""; while(!(nx==x && ny==y) || read.size()==0){ read+=V[ny][nx]; if(S.count(read)){ if(res.size()<read.size()) res=read; if(res.size()==read.size() && res>read) res=read; } S.insert(read); ny+=dy[r]; nx+=dx[r]; if(ny<0) ny=h-1; if(ny>=h) ny=0; if(nx<0) nx=w-1; if(nx>=w) nx=0; } } } } if(res.size()>1) cout<<res<<endl; else cout<<0<<endl; } int main() { while(cin>>h>>w){ if(h==0) break; solve(); } return 0; } ```
#include<iostream> #include<cstdio> #include<string> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> using namespace std; typedef long long ll; const ll MOD = 1000000007; const ll INF = (ll)1000000007 * 1000000007; const double EPS = 1e-9; typedef pair<int, int> P; typedef unsigned int ui; #define stop char nyaa;cin>>nyaa; #define rep(i,n) for(int i=0;i<n;i++) #define per(i,n) for(int i=n-1;i>=0;i--) #define Rep(i,sta,n) for(int i=sta;i<n;i++) #define rep1(i,n) for(int i=1;i<=n;i++) #define per1(i,n) for(int i=n;i>=1;i--) int d1[8] = { 1,1,1,0,0,-1,-1,-1 }; int d2[8] = { 1,0,-1,1,-1,1,0,-1 }; int h, w; int fh(int x) { return (x% h+h)%h; } int fw(int x) { return (x%w + w) % w; } int main() { while (cin >> h >> w, h) { char t[20][20]; string s; rep(i, h) { cin >> s; rep(j, w) { t[i][j] = s[j]; } } vector<string>v; rep(i, h) { rep(j, w) { rep(k, 8) { string u; u = t[i][j]; int now = 1; while (!(fh(i + now*d1[k]) == i && fw(j + now*d2[k]) == j)) { u += t[fh(i + now * d1[k])][fw(j + now * d2[k])]; v.push_back(u); now++; } } } } sort(v.begin(), v.end()); int len = v.size(); ui ma = 0; string out = "0"; rep(i, len-1) { if (v[i] == v[i + 1] && ma < v[i].length()) { ma = v[i].length(); out = v[i]; } } cout << out << endl; } return 0; }
### Prompt Generate a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<cstdio> #include<string> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> using namespace std; typedef long long ll; const ll MOD = 1000000007; const ll INF = (ll)1000000007 * 1000000007; const double EPS = 1e-9; typedef pair<int, int> P; typedef unsigned int ui; #define stop char nyaa;cin>>nyaa; #define rep(i,n) for(int i=0;i<n;i++) #define per(i,n) for(int i=n-1;i>=0;i--) #define Rep(i,sta,n) for(int i=sta;i<n;i++) #define rep1(i,n) for(int i=1;i<=n;i++) #define per1(i,n) for(int i=n;i>=1;i--) int d1[8] = { 1,1,1,0,0,-1,-1,-1 }; int d2[8] = { 1,0,-1,1,-1,1,0,-1 }; int h, w; int fh(int x) { return (x% h+h)%h; } int fw(int x) { return (x%w + w) % w; } int main() { while (cin >> h >> w, h) { char t[20][20]; string s; rep(i, h) { cin >> s; rep(j, w) { t[i][j] = s[j]; } } vector<string>v; rep(i, h) { rep(j, w) { rep(k, 8) { string u; u = t[i][j]; int now = 1; while (!(fh(i + now*d1[k]) == i && fw(j + now*d2[k]) == j)) { u += t[fh(i + now * d1[k])][fw(j + now * d2[k])]; v.push_back(u); now++; } } } } sort(v.begin(), v.end()); int len = v.size(); ui ma = 0; string out = "0"; rep(i, len-1) { if (v[i] == v[i + 1] && ma < v[i].length()) { ma = v[i].length(); out = v[i]; } } cout << out << endl; } return 0; } ```
#include <iostream> #include <algorithm> #include <set> using namespace std; #define REP(i,x)for(__typeof(x) i=0;i<x;i++) string res; set<string> m; int H,W,dx,dy,min_len; char s[200]; string MAP[11]; bool visit[20][20]; void dfs(int x,int y,int k){ if(k==min_len){ if(m.count(string(s)))res=min(res,string(s)); m.insert(string(s)); }else if(k>min_len){ if(m.count(string(s)))res=string(s),min_len=k; m.insert(string(s)); } if(visit[y][x]) return; s[k]=MAP[y][x]; visit[y][x]=1; dfs((x + dx + W) % W, (y + dy + H) % H, k + 1); s[k]=0; visit[y][x]=0; } int main() { while(cin>>H>>W,H){ REP(i,H)cin>>MAP[i]; m.clear(); min_len=1; res="0"; REP(y,H)REP(x,W){ for(dx=-1;dx<=1;dx++){ for(dy=-1;dy<=1;dy++){ if(dx|dy)dfs(x,y,0); } } } cout<<res<<endl; } }
### Prompt Please provide a CPP coded solution to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <algorithm> #include <set> using namespace std; #define REP(i,x)for(__typeof(x) i=0;i<x;i++) string res; set<string> m; int H,W,dx,dy,min_len; char s[200]; string MAP[11]; bool visit[20][20]; void dfs(int x,int y,int k){ if(k==min_len){ if(m.count(string(s)))res=min(res,string(s)); m.insert(string(s)); }else if(k>min_len){ if(m.count(string(s)))res=string(s),min_len=k; m.insert(string(s)); } if(visit[y][x]) return; s[k]=MAP[y][x]; visit[y][x]=1; dfs((x + dx + W) % W, (y + dy + H) % H, k + 1); s[k]=0; visit[y][x]=0; } int main() { while(cin>>H>>W,H){ REP(i,H)cin>>MAP[i]; m.clear(); min_len=1; res="0"; REP(y,H)REP(x,W){ for(dx=-1;dx<=1;dx++){ for(dy=-1;dy<=1;dy++){ if(dx|dy)dfs(x,y,0); } } } cout<<res<<endl; } } ```
#include <cstdio> #include <cstring> #include <string> #include <iostream> #include <map> #include <vector> #include <algorithm> using namespace std; int h,w; char fie[11][21]; int dx[8]={1,0,-1,0,1,1,-1,-1}; int dy[8]={0,1,0,-1,1,-1,1,-1}; bool used[11][21]; vector<string> index2; string str; void dfs(int y,int x,int k){ if(used[y][x])return; used[y][x]=true; str+=fie[y][x]; index2.push_back(str); dfs((y+dy[k]+h)%h,(x+dx[k]+w)%w,k); } int main(void){ while(1){ scanf("%d %d%*c",&h,&w); if(h+w==0)break; index2.clear(); for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ scanf("%c",&fie[i][j]); } scanf("%*c"); } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ memset(used,false,sizeof(used)); str=""; dfs(i,j,k); } } } sort(index2.begin(),index2.end()); int res=index2.size(); index2.push_back("0"); for(int i=0;i<index2.size();i++){ if(index2[i].size()>=2){ if(index2[i]==index2[i-1] && index2[res].size()<index2[i].size())res=i; } } cout << index2[res] << endl; } return 0; }
### Prompt Please formulate a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstdio> #include <cstring> #include <string> #include <iostream> #include <map> #include <vector> #include <algorithm> using namespace std; int h,w; char fie[11][21]; int dx[8]={1,0,-1,0,1,1,-1,-1}; int dy[8]={0,1,0,-1,1,-1,1,-1}; bool used[11][21]; vector<string> index2; string str; void dfs(int y,int x,int k){ if(used[y][x])return; used[y][x]=true; str+=fie[y][x]; index2.push_back(str); dfs((y+dy[k]+h)%h,(x+dx[k]+w)%w,k); } int main(void){ while(1){ scanf("%d %d%*c",&h,&w); if(h+w==0)break; index2.clear(); for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ scanf("%c",&fie[i][j]); } scanf("%*c"); } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ memset(used,false,sizeof(used)); str=""; dfs(i,j,k); } } } sort(index2.begin(),index2.end()); int res=index2.size(); index2.push_back("0"); for(int i=0;i<index2.size();i++){ if(index2[i].size()>=2){ if(index2[i]==index2[i-1] && index2[res].size()<index2[i].size())res=i; } } cout << index2[res] << endl; } return 0; } ```
#include<iostream> #include<map> #include<vector> using namespace std; string s[10]; int h,w; int dx[]={0,1,0,-1,1,1,-1,-1},dy[]={1,0,-1,0,1,-1,1,-1}; int main() { while(cin>>h>>w,h) { for(int i=0;i<h;i++)cin>>s[i]; map<string,int>M; string ans="0"; for(int i=0;i<h;i++)for(int j=0;j<w;j++) { for(int r=0;r<8;r++) { string now=s[i].substr(j,1); int x=i+dx[r],y=j+dy[r]; x=(x+h)%h;y=(y+w)%w; while(x!=i||y!=j) { now+=s[x][y]; if(M[now]++==1) { if(now.size()>ans.size())ans=now; else if(ans.size()==now.size()&&ans>now)ans=now; } x+=dx[r],y+=dy[r]; x=(x+h)%h;y=(y+w)%w; } } } cout<<ans<<endl; } }
### Prompt In cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<map> #include<vector> using namespace std; string s[10]; int h,w; int dx[]={0,1,0,-1,1,1,-1,-1},dy[]={1,0,-1,0,1,-1,1,-1}; int main() { while(cin>>h>>w,h) { for(int i=0;i<h;i++)cin>>s[i]; map<string,int>M; string ans="0"; for(int i=0;i<h;i++)for(int j=0;j<w;j++) { for(int r=0;r<8;r++) { string now=s[i].substr(j,1); int x=i+dx[r],y=j+dy[r]; x=(x+h)%h;y=(y+w)%w; while(x!=i||y!=j) { now+=s[x][y]; if(M[now]++==1) { if(now.size()>ans.size())ans=now; else if(ans.size()==now.size()&&ans>now)ans=now; } x+=dx[r],y+=dy[r]; x=(x+h)%h;y=(y+w)%w; } } } cout<<ans<<endl; } } ```
#include <vector> #include <map> #include <set> #include <stack> #include <queue> #include <algorithm> #include <utility> #include <functional> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <ctime> #include <climits> #include <fstream> using namespace std; inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v;} template<class T> inline string toStr(T x) { ostringstream sout; sout << x; return sout.str();} typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef pair<int, int> pii; typedef long long ll; #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(),(a).rend() #define FOR(i,a,b) for(int i=(a);i<=(b);++i) #define REP(i,n) FOR(i,0,(n)-1) const double EPS = 1e-12; const double PI = acos(-1.0); const int INF = INT_MAX/10; int dx[] = {1, 1, 0, -1, -1, -1, 0, 1}; int dy[] = {0, 1, 1, 1, 0, -1, -1, -1}; string best(string a, string b) { if(a.length() < b.length()) { return b; } if(a.length() == b.length() && b < a) { return b; } return a; } int main() { int h, w; while(cin >> h >> w, h) { vs field(h); REP(i, h) { cin >> field[i]; } map<string, int> times; string ans; REP(i, h) { REP(j, w) { vvi visited(h, vi(w, -1)); REP(d, 8) { string tmp; int y = i, x = j; while(visited[y][x] != d) { tmp += field[y][x]; visited[y][x] = d; times[tmp]++; if(times[tmp] > 1) { ans = best(ans, tmp); } y = (y+dy[d]+h)%h; x = (x+dx[d]+w)%w; } } } } if(ans.length() < 2) { cout << 0 << endl; } else { cout << ans << endl; } } return 0; }
### Prompt Develop a solution in CPP to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <vector> #include <map> #include <set> #include <stack> #include <queue> #include <algorithm> #include <utility> #include <functional> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <ctime> #include <climits> #include <fstream> using namespace std; inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v;} template<class T> inline string toStr(T x) { ostringstream sout; sout << x; return sout.str();} typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef pair<int, int> pii; typedef long long ll; #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(),(a).rend() #define FOR(i,a,b) for(int i=(a);i<=(b);++i) #define REP(i,n) FOR(i,0,(n)-1) const double EPS = 1e-12; const double PI = acos(-1.0); const int INF = INT_MAX/10; int dx[] = {1, 1, 0, -1, -1, -1, 0, 1}; int dy[] = {0, 1, 1, 1, 0, -1, -1, -1}; string best(string a, string b) { if(a.length() < b.length()) { return b; } if(a.length() == b.length() && b < a) { return b; } return a; } int main() { int h, w; while(cin >> h >> w, h) { vs field(h); REP(i, h) { cin >> field[i]; } map<string, int> times; string ans; REP(i, h) { REP(j, w) { vvi visited(h, vi(w, -1)); REP(d, 8) { string tmp; int y = i, x = j; while(visited[y][x] != d) { tmp += field[y][x]; visited[y][x] = d; times[tmp]++; if(times[tmp] > 1) { ans = best(ans, tmp); } y = (y+dy[d]+h)%h; x = (x+dx[d]+w)%w; } } } } if(ans.length() < 2) { cout << 0 << endl; } else { cout << ans << endl; } } return 0; } ```
#include<bits/stdc++.h> #define rep(i,n)for(int i=0;i<(n);i++) using namespace std; char s[10][21]; bool used[10][20]; int main() { int h, w; while (scanf("%d%d", &h, &w), h) { rep(i, h)scanf("%s", s[i]); map<string, int>mp; rep(i, h)rep(j, w) { for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0)continue; string t; memset(used, 0, sizeof(used)); int x = i, y = j; while (!used[x][y]) { t += s[x][y]; used[x][y] = 1; x += dx; y += dy; x = (x + h) % h; y = (y + w) % w; mp[t]++; } } } } string ans = "0"; for (auto p : mp) { if (p.second > 1 && ans.size() < p.first.size())ans = p.first; } cout << ans << endl; } }
### Prompt Generate a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<bits/stdc++.h> #define rep(i,n)for(int i=0;i<(n);i++) using namespace std; char s[10][21]; bool used[10][20]; int main() { int h, w; while (scanf("%d%d", &h, &w), h) { rep(i, h)scanf("%s", s[i]); map<string, int>mp; rep(i, h)rep(j, w) { for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0)continue; string t; memset(used, 0, sizeof(used)); int x = i, y = j; while (!used[x][y]) { t += s[x][y]; used[x][y] = 1; x += dx; y += dy; x = (x + h) % h; y = (y + w) % w; mp[t]++; } } } } string ans = "0"; for (auto p : mp) { if (p.second > 1 && ans.size() < p.first.size())ans = p.first; } cout << ans << endl; } } ```
#include <bits/stdc++.h> using namespace std; int h, w; string spell[10]; int dx[] = {-1, 0, 1, 0, 1, -1, 1, -1}; int dy[] = {0, -1, 0, 1, -1, 1, 1, -1}; set<string> spellset; string ans; void cast(int sy, int sx, int y, int x, int d, string word) { if(spellset.count(word)){ if(ans.size() < word.size() || ans.size() == word.size() && ans > word){ ans = word; } } else { spellset.insert(word); } if(sy == y && sx == x) return; int ny = (y + dy[d] + h) % h, nx = (x + dx[d] + w) % w; cast(sy, sx, ny, nx, d, word + spell[y][x]); return; } int main() { while(cin >> h >> w, h || w){ spellset.clear(); for(int i = 0; i < h; i++) cin >> spell[i]; ans = ""; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ string word = ""; for(int k = 0; k < 8; k++){ int ny = (i + dy[k] + h) % h, nx = (j + dx[k] + w) % w; cast(i, j, ny, nx, k, word + spell[i][j]); } } } cout << (ans.size() > 1 ? ans:"0") << endl; } return 0; }
### Prompt Please create a solution in Cpp to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> using namespace std; int h, w; string spell[10]; int dx[] = {-1, 0, 1, 0, 1, -1, 1, -1}; int dy[] = {0, -1, 0, 1, -1, 1, 1, -1}; set<string> spellset; string ans; void cast(int sy, int sx, int y, int x, int d, string word) { if(spellset.count(word)){ if(ans.size() < word.size() || ans.size() == word.size() && ans > word){ ans = word; } } else { spellset.insert(word); } if(sy == y && sx == x) return; int ny = (y + dy[d] + h) % h, nx = (x + dx[d] + w) % w; cast(sy, sx, ny, nx, d, word + spell[y][x]); return; } int main() { while(cin >> h >> w, h || w){ spellset.clear(); for(int i = 0; i < h; i++) cin >> spell[i]; ans = ""; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ string word = ""; for(int k = 0; k < 8; k++){ int ny = (i + dy[k] + h) % h, nx = (j + dx[k] + w) % w; cast(i, j, ny, nx, k, word + spell[i][j]); } } } cout << (ans.size() > 1 ? ans:"0") << endl; } return 0; } ```
#include <iostream> #include <algorithm> #include <string> #include <map> #include <vector> using namespace std; struct Str2 { string s; Str2() {} Str2(string s) : s(s) {} bool operator < (const Str2 &str) const { if(s.size() != str.s.size()) return s.size() > str.s.size(); return s < str.s; } }; const int MAX_H = 20; const int MAX_W = MAX_H; int H, W; char G[MAX_H][MAX_W]; map<string, int> M; vector<Str2> V; string solve() { M.clear(); V.clear(); for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { for(int dx = -1; dx <= 1; ++dx) { for(int dy = -1; dy <= 1; ++dy) { if(dx == 0 && dy == 0) continue; int x = j; int y = i; string s = ""; do { s += G[y][x]; if(s.size() >= 2 && ++M[s] == 2) { V.push_back(Str2(s)); } int nx = (x+dx+W)%W; int ny = (y+dy+H)%H; x = nx; y = ny; } while(!(x == j && y == i)); } } } } if(V.size() == 0) return "0"; sort(V.begin(), V.end()); return V[0].s; } int main() { while(cin >> H >> W && (H | W)) { for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { cin >> G[i][j]; } } cout << solve() << endl; } return 0; }
### Prompt In CPP, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <algorithm> #include <string> #include <map> #include <vector> using namespace std; struct Str2 { string s; Str2() {} Str2(string s) : s(s) {} bool operator < (const Str2 &str) const { if(s.size() != str.s.size()) return s.size() > str.s.size(); return s < str.s; } }; const int MAX_H = 20; const int MAX_W = MAX_H; int H, W; char G[MAX_H][MAX_W]; map<string, int> M; vector<Str2> V; string solve() { M.clear(); V.clear(); for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { for(int dx = -1; dx <= 1; ++dx) { for(int dy = -1; dy <= 1; ++dy) { if(dx == 0 && dy == 0) continue; int x = j; int y = i; string s = ""; do { s += G[y][x]; if(s.size() >= 2 && ++M[s] == 2) { V.push_back(Str2(s)); } int nx = (x+dx+W)%W; int ny = (y+dy+H)%H; x = nx; y = ny; } while(!(x == j && y == i)); } } } } if(V.size() == 0) return "0"; sort(V.begin(), V.end()); return V[0].s; } int main() { while(cin >> H >> W && (H | W)) { for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) { cin >> G[i][j]; } } cout << solve() << endl; } return 0; } ```
#include "bits/stdc++.h" using namespace std; vector<string> v; int h,w; string s[10]; string search(int a,int b,int d) { int dirx[8]={1,1,0,-1,-1,-1,0,1}; int diry[8]={0,-1,-1,-1,0,1,1,1}; string ret; int i=a; int j=b; do{ ret+=s[i][j]; i+=dirx[d]; j+=diry[d]; if(i==-1) i=h-1; if(i==h) i=0; if(j==-1) j=w-1; if(j==w) j=0; }while(!(i==a && j==b)); return ret; } bool comp(string a,string b) { if(a.size()==b.size()) return a<b; else return a.size()>b.size(); } string itti(string a,string b) { string ret; for(int i=0;i<min(a.size(),b.size());i++) { if(a[i]!=b[i]) break; ret+=a[i]; } return ret; } int main() { while(1) { v.clear(); cin>>h>>w; if(h==0) break; for(int i=0;i<h;i++) cin>>s[i]; //すべての始点を調べる for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { for(int k=0;k<8;k++) v.push_back(search(i,j,k)); } } sort(v.begin(),v.end()); string ans="0"; for(int i=1;i<v.size();i++) { string tmp=itti(v[i],v[i-1]); if(comp(tmp,ans)) ans=tmp; } cout<<ans<<endl; } return 0; }
### Prompt Please create a solution in CPP to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include "bits/stdc++.h" using namespace std; vector<string> v; int h,w; string s[10]; string search(int a,int b,int d) { int dirx[8]={1,1,0,-1,-1,-1,0,1}; int diry[8]={0,-1,-1,-1,0,1,1,1}; string ret; int i=a; int j=b; do{ ret+=s[i][j]; i+=dirx[d]; j+=diry[d]; if(i==-1) i=h-1; if(i==h) i=0; if(j==-1) j=w-1; if(j==w) j=0; }while(!(i==a && j==b)); return ret; } bool comp(string a,string b) { if(a.size()==b.size()) return a<b; else return a.size()>b.size(); } string itti(string a,string b) { string ret; for(int i=0;i<min(a.size(),b.size());i++) { if(a[i]!=b[i]) break; ret+=a[i]; } return ret; } int main() { while(1) { v.clear(); cin>>h>>w; if(h==0) break; for(int i=0;i<h;i++) cin>>s[i]; //すべての始点を調べる for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { for(int k=0;k<8;k++) v.push_back(search(i,j,k)); } } sort(v.begin(),v.end()); string ans="0"; for(int i=1;i<v.size();i++) { string tmp=itti(v[i],v[i-1]); if(comp(tmp,ans)) ans=tmp; } cout<<ans<<endl; } return 0; } ```
#include <iostream> #include <set> #include <string> #include <algorithm> #define MAX 22 using namespace std; char f[MAX][MAX]; int dx[8]={1,1,0,-1,-1,-1,0,1}; //右から int dy[8]={0,1,1,1,0,-1,-1,-1}; int main(void) { int h,w; int i1,i2,i3; int x,y; string s; int len; while(1){ cin>>h>>w; if(h+w==0) break; for(i1=0;i1<h;i1++){ for(i2=0;i2<w;i2++){ cin>>f[i1][i2]; } } set<string> p; set<string> ok; len=0; for(i1=0;i1<h;i1++){ for(i2=0;i2<w;i2++){ for(i3=0;i3<8;i3++){ x=i2; y=i1; s=""; while(1){ s+=f[y][x]; if(s.size()!=1 && p.find(s)!=p.end()) { ok.insert(s); len=max(len,(int)s.size()); } else p.insert(s); x+=dx[i3]; y+=dy[i3]; if(x==w) x=0; if(y==h) y=0; if(x==-1) x=w-1; if(y==-1) y=h-1; if(x==i2 && y==i1) break; } } } } set<string>::iterator it; set<string> ans; for(it=ok.begin();it!=ok.end();it++){ if(len==(*it).size()) ans.insert((*it)); } if(ans.empty()) cout<<"0"<<endl; else cout<<(*ans.begin())<<endl; } return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <set> #include <string> #include <algorithm> #define MAX 22 using namespace std; char f[MAX][MAX]; int dx[8]={1,1,0,-1,-1,-1,0,1}; //右から int dy[8]={0,1,1,1,0,-1,-1,-1}; int main(void) { int h,w; int i1,i2,i3; int x,y; string s; int len; while(1){ cin>>h>>w; if(h+w==0) break; for(i1=0;i1<h;i1++){ for(i2=0;i2<w;i2++){ cin>>f[i1][i2]; } } set<string> p; set<string> ok; len=0; for(i1=0;i1<h;i1++){ for(i2=0;i2<w;i2++){ for(i3=0;i3<8;i3++){ x=i2; y=i1; s=""; while(1){ s+=f[y][x]; if(s.size()!=1 && p.find(s)!=p.end()) { ok.insert(s); len=max(len,(int)s.size()); } else p.insert(s); x+=dx[i3]; y+=dy[i3]; if(x==w) x=0; if(y==h) y=0; if(x==-1) x=w-1; if(y==-1) y=h-1; if(x==i2 && y==i1) break; } } } } set<string>::iterator it; set<string> ans; for(it=ok.begin();it!=ok.end();it++){ if(len==(*it).size()) ans.insert((*it)); } if(ans.empty()) cout<<"0"<<endl; else cout<<(*ans.begin())<<endl; } return 0; } ```
#include <iostream> #include <vector> #include <cstring> #include <string> #include <algorithm> #include <iomanip> #include <cmath> #include <cassert> #include <map> using namespace std; string b[10]; int dx[8] = { 1, 0, -1, 0, 1, 1, -1, -1 }; int dy[8] = { 0, 1, 0, -1, 1, -1, 1, -1 }; bool visit[10][20]; int main() { cin.tie(0); ios::sync_with_stdio(false); int h, w; while(cin >> h >> w, h | w) { for(int i = 0; i < h; i++) { cin >> b[i]; } map<string, int> m; for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { for(int k = 0; k < 8; k++) { int ny = y, nx = x; memset(visit, 0, sizeof visit); string s; while(!visit[ny][nx]) { visit[ny][nx] = true; s += b[ny][nx]; m[s]++; ny = (ny + dy[k] + h) % h; nx = (nx + dx[k] + w) % w; } } } } string ans; for(auto p : m) { if(p.second <= 1 || p.first.size() <= 1) continue; string s = p.first; if(ans.size() < s.size() || ans.size() == s.size() && ans > s) { ans = s; } } if(ans == "") ans = "0"; cout << ans << endl; } }
### Prompt Please formulate a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <cstring> #include <string> #include <algorithm> #include <iomanip> #include <cmath> #include <cassert> #include <map> using namespace std; string b[10]; int dx[8] = { 1, 0, -1, 0, 1, 1, -1, -1 }; int dy[8] = { 0, 1, 0, -1, 1, -1, 1, -1 }; bool visit[10][20]; int main() { cin.tie(0); ios::sync_with_stdio(false); int h, w; while(cin >> h >> w, h | w) { for(int i = 0; i < h; i++) { cin >> b[i]; } map<string, int> m; for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { for(int k = 0; k < 8; k++) { int ny = y, nx = x; memset(visit, 0, sizeof visit); string s; while(!visit[ny][nx]) { visit[ny][nx] = true; s += b[ny][nx]; m[s]++; ny = (ny + dy[k] + h) % h; nx = (nx + dx[k] + w) % w; } } } } string ans; for(auto p : m) { if(p.second <= 1 || p.first.size() <= 1) continue; string s = p.first; if(ans.size() < s.size() || ans.size() == s.size() && ans > s) { ans = s; } } if(ans == "") ans = "0"; cout << ans << endl; } } ```
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> #define REP(i,a,b) for(int i=int(a);i<int(b);i++) using namespace std; typedef long long int lli; int main () { int h, w; while (cin >> h >> w, h + w) { vector<vector<char>> spell(h, vector<char>(w)); REP (i, 0, h) REP (j, 0, w) cin >> spell[i][j]; map<string, int> ml; REP (i, 0, h) REP (j, 0, w) { REP (dy, -1, 2) REP (dx, -1, 2) { if (dx == 0 && dy == 0) continue; vector<vector<bool>> isAccess(h, vector<bool>(w, false)); int y = i, x = j; string temp = ""; REP (_, 0, w * h) { if (isAccess[y][x]) break; isAccess[y][x] = true; temp += spell[y][x]; ml[temp]++; y = (y + dy + h) % h; x = (x + dx + w) % w; } } } string ans = ""; for (auto s : ml) { if (s.second <= 1 || s.first.size() <= 1) continue; if (ans.size() < s.first.size()) ans = s.first; else if (ans.size() == s.first.size()) ans = min(ans, s.first); } cout << (ans.size() == 0 ? "0" : ans) << endl; } return 0; }
### Prompt In cpp, your task is to solve the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> #define REP(i,a,b) for(int i=int(a);i<int(b);i++) using namespace std; typedef long long int lli; int main () { int h, w; while (cin >> h >> w, h + w) { vector<vector<char>> spell(h, vector<char>(w)); REP (i, 0, h) REP (j, 0, w) cin >> spell[i][j]; map<string, int> ml; REP (i, 0, h) REP (j, 0, w) { REP (dy, -1, 2) REP (dx, -1, 2) { if (dx == 0 && dy == 0) continue; vector<vector<bool>> isAccess(h, vector<bool>(w, false)); int y = i, x = j; string temp = ""; REP (_, 0, w * h) { if (isAccess[y][x]) break; isAccess[y][x] = true; temp += spell[y][x]; ml[temp]++; y = (y + dy + h) % h; x = (x + dx + w) % w; } } } string ans = ""; for (auto s : ml) { if (s.second <= 1 || s.first.size() <= 1) continue; if (ans.size() < s.first.size()) ans = s.first; else if (ans.size() == s.first.size()) ans = min(ans, s.first); } cout << (ans.size() == 0 ? "0" : ans) << endl; } return 0; } ```
#include "bits/stdc++.h" #pragma warning(disable:4996) using namespace std; long long int gcd(long long int l, long long int r) { if (l > r)return gcd(r, l); else { if (r%l) { return gcd(l, r%l); } else { return l; } } } int dx[8] = { -1,-1,-1, 0, 1, 1, 1, 0 }; int dy[8] = { -1, 0, 1, 1, 1, 0,-1,-1 }; class Compare { public: //keiroが昇順に並ぶ bool operator()(const string&l, const string&r) { return l.size() == r.size() ? l<r : l.size() < r.size(); } }; int main() { while (1) { int H, W; cin >> H >> W; if (!H)break; vector<string>field; for (int i = 0; i < H; ++i) { string st; cin >> st; field.push_back(st); } int ytime = H; int xtime = W; int yxtime = H*W/ gcd(H,W); map<string, int>mp; for (int y = 0; y < H; ++y) { for (int x = 0; x < W; ++x) { for (int i = 0; i < 8; ++i) { int ny(y); int nx(x); int atime; if (i % 2==0) { atime = yxtime; } else if (i == 1 || i == 5) { atime = xtime; } else { atime = ytime; } string nst; for (int k = 0; k < atime; ++k) { nst += field[ny][nx]; if (k) { mp[nst]++; } ny = (ny + H + dy[i]) % H; nx = (nx + W + dx[i]) % W; } } } } string ans = "0"; int num = 0; for (auto it = mp.begin(); it != mp.end(); ++it) { if (it->second >= 2) { if (num < it->first.size()) { ans = it->first; num = it->first.size(); } } } cout << ans << endl; } return 0; }
### Prompt Generate a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include "bits/stdc++.h" #pragma warning(disable:4996) using namespace std; long long int gcd(long long int l, long long int r) { if (l > r)return gcd(r, l); else { if (r%l) { return gcd(l, r%l); } else { return l; } } } int dx[8] = { -1,-1,-1, 0, 1, 1, 1, 0 }; int dy[8] = { -1, 0, 1, 1, 1, 0,-1,-1 }; class Compare { public: //keiroが昇順に並ぶ bool operator()(const string&l, const string&r) { return l.size() == r.size() ? l<r : l.size() < r.size(); } }; int main() { while (1) { int H, W; cin >> H >> W; if (!H)break; vector<string>field; for (int i = 0; i < H; ++i) { string st; cin >> st; field.push_back(st); } int ytime = H; int xtime = W; int yxtime = H*W/ gcd(H,W); map<string, int>mp; for (int y = 0; y < H; ++y) { for (int x = 0; x < W; ++x) { for (int i = 0; i < 8; ++i) { int ny(y); int nx(x); int atime; if (i % 2==0) { atime = yxtime; } else if (i == 1 || i == 5) { atime = xtime; } else { atime = ytime; } string nst; for (int k = 0; k < atime; ++k) { nst += field[ny][nx]; if (k) { mp[nst]++; } ny = (ny + H + dy[i]) % H; nx = (nx + W + dx[i]) % W; } } } } string ans = "0"; int num = 0; for (auto it = mp.begin(); it != mp.end(); ++it) { if (it->second >= 2) { if (num < it->first.size()) { ans = it->first; num = it->first.size(); } } } cout << ans << endl; } return 0; } ```
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> using namespace std; const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1}; const int dx[] = {0, 0, 1, -1, 1, -1, -1, 1}; int h, w, sy, sx, max_size; map<string, int> mp; string table[15]; string str; void solve(char ch) { for(int i = 0; i < 8; i++) { int ny = sy; int nx = sx; str = ""; while(1) { str += table[ny][nx]; mp[str]++; if(mp[str] >= 2) max_size = max(max_size, (int)str.size()); int tmp_y = ny + dy[i]; int tmp_x = nx + dx[i]; if(tmp_y < 0) tmp_y = h - 1; if(tmp_x < 0) tmp_x = w - 1; if(tmp_y >= h) tmp_y = 0; if(tmp_x >= w) tmp_x = 0; ny = tmp_y; nx = tmp_x; if(tmp_y == sy && tmp_x == sx) break; } } } int main() { cin.tie(0); ios::sync_with_stdio(false); while(cin >> h >> w, h | w) { mp.clear(); str = ""; max_size = 2; for(int i = 0; i < h; i++) { cin >> table[i]; } for(int i = 0; i < h; i++) { for(int j = 0; j < w; j++) { sy = i; sx = j; solve(table[i][j]); } } bool flag = false; for(auto itr = mp.begin(); itr != mp.end(); itr++) { if(itr->second >= 2 && itr->first.size() == max_size) { flag = true; cout << itr->first << endl; break; } } if(!flag) cout << 0 << endl; } return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> using namespace std; const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1}; const int dx[] = {0, 0, 1, -1, 1, -1, -1, 1}; int h, w, sy, sx, max_size; map<string, int> mp; string table[15]; string str; void solve(char ch) { for(int i = 0; i < 8; i++) { int ny = sy; int nx = sx; str = ""; while(1) { str += table[ny][nx]; mp[str]++; if(mp[str] >= 2) max_size = max(max_size, (int)str.size()); int tmp_y = ny + dy[i]; int tmp_x = nx + dx[i]; if(tmp_y < 0) tmp_y = h - 1; if(tmp_x < 0) tmp_x = w - 1; if(tmp_y >= h) tmp_y = 0; if(tmp_x >= w) tmp_x = 0; ny = tmp_y; nx = tmp_x; if(tmp_y == sy && tmp_x == sx) break; } } } int main() { cin.tie(0); ios::sync_with_stdio(false); while(cin >> h >> w, h | w) { mp.clear(); str = ""; max_size = 2; for(int i = 0; i < h; i++) { cin >> table[i]; } for(int i = 0; i < h; i++) { for(int j = 0; j < w; j++) { sy = i; sx = j; solve(table[i][j]); } } bool flag = false; for(auto itr = mp.begin(); itr != mp.end(); itr++) { if(itr->second >= 2 && itr->first.size() == max_size) { flag = true; cout << itr->first << endl; break; } } if(!flag) cout << 0 << endl; } return 0; } ```
#include <iostream> #include <string> #include <set> #include <cstring> using namespace std; #define REP(i,x,n) for(int i = x; i < (int)(n); i++) #define rep(i,n) REP(i,0,n) static const int dx[] = {-1,-1,-1,0,0,1,1,1}; static const int dy[] = {-1,0,1,-1,1,-1,0,1}; int h,w; char D[10][20]; set<string> spell; string solve(){ spell.clear(); string ret = "0"; rep(i,h) rep(j,w){ int sx = i; int sy = j; rep(k,8){ int x = i; int y = j; string tmp; tmp += D[x][y]; while(true){ x = (x + h + dx[k]) % h; y = (y + w + dy[k]) % w; if(x == sx && y == sy) break; tmp += D[x][y]; if(spell.find(tmp) != spell.end()){ if(ret.size() == tmp.size()) ret = (ret < tmp) ? ret : tmp; else ret = (ret.size() < tmp.size()) ? tmp : ret; } else spell.insert(tmp); } } } return ret; } int main(){ while(cin >> h >> w && (h | w)){ rep(i,h) rep(j,w){ cin >> D[i][j]; } cout << solve() << endl; } return 0; }
### Prompt Your task is to create a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <string> #include <set> #include <cstring> using namespace std; #define REP(i,x,n) for(int i = x; i < (int)(n); i++) #define rep(i,n) REP(i,0,n) static const int dx[] = {-1,-1,-1,0,0,1,1,1}; static const int dy[] = {-1,0,1,-1,1,-1,0,1}; int h,w; char D[10][20]; set<string> spell; string solve(){ spell.clear(); string ret = "0"; rep(i,h) rep(j,w){ int sx = i; int sy = j; rep(k,8){ int x = i; int y = j; string tmp; tmp += D[x][y]; while(true){ x = (x + h + dx[k]) % h; y = (y + w + dy[k]) % w; if(x == sx && y == sy) break; tmp += D[x][y]; if(spell.find(tmp) != spell.end()){ if(ret.size() == tmp.size()) ret = (ret < tmp) ? ret : tmp; else ret = (ret.size() < tmp.size()) ? tmp : ret; } else spell.insert(tmp); } } } return ret; } int main(){ while(cin >> h >> w && (h | w)){ rep(i,h) rep(j,w){ cin >> D[i][j]; } cout << solve() << endl; } return 0; } ```
#include <bits/stdc++.h> #define fi first #define se second using namespace std; using P = pair<int,int>; int h,w; int d[2][8] = {{-1,-1,-1,0,0,1,1,1},{-1,0,1,-1,1,-1,0,1}}; vector<vector<P>> memo; vector<string> s; string solve(); int main() { while(1){ cin >> h >> w; if(h + w == 0)break; s.resize(h); for(int i = 0;i < h;++i) cin >> s[i]; cout << solve() << endl; } return 0; } string solve(){ string ans; memo.assign(26,vector<P>(0,{0,0})); for(int i = 0;i < h;++i) for(int j = 0;j < w;++j) memo[s[i][j]-'A'].push_back({i,j}); for(int alph = 0;alph < 26;++alph){ int memosize = memo[alph].size(); for(int j = 0;j < memosize;++j) for(int k = 0;k < memosize;++k){ P memoj = memo[alph][j],memok = memo[alph][k]; for(int dj = 0;dj < 8;++dj) for(int dk = 0;dk < 8;++dk){ P nowj = memoj,nowk = memok; string now; if(j == k && dj == dk)continue; while(s[nowj.fi][nowj.se] == s[nowk.fi][nowk.se]){ now += s[nowj.fi][nowj.se]; (nowj.fi += d[0][dj] + h) %= h; (nowj.se += d[1][dj] + w) %= w; (nowk.fi += d[0][dk] + h) %= h; (nowk.se += d[1][dk] + w) %= w; if(nowj == memoj && nowk == memok)break; } if(now.size() <= 1)continue; if(now.size() > ans.size() || (now.size() == ans.size() && now < ans)) ans = now; } } } return ans.size() == 0? "0":ans; }
### Prompt Your task is to create a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <bits/stdc++.h> #define fi first #define se second using namespace std; using P = pair<int,int>; int h,w; int d[2][8] = {{-1,-1,-1,0,0,1,1,1},{-1,0,1,-1,1,-1,0,1}}; vector<vector<P>> memo; vector<string> s; string solve(); int main() { while(1){ cin >> h >> w; if(h + w == 0)break; s.resize(h); for(int i = 0;i < h;++i) cin >> s[i]; cout << solve() << endl; } return 0; } string solve(){ string ans; memo.assign(26,vector<P>(0,{0,0})); for(int i = 0;i < h;++i) for(int j = 0;j < w;++j) memo[s[i][j]-'A'].push_back({i,j}); for(int alph = 0;alph < 26;++alph){ int memosize = memo[alph].size(); for(int j = 0;j < memosize;++j) for(int k = 0;k < memosize;++k){ P memoj = memo[alph][j],memok = memo[alph][k]; for(int dj = 0;dj < 8;++dj) for(int dk = 0;dk < 8;++dk){ P nowj = memoj,nowk = memok; string now; if(j == k && dj == dk)continue; while(s[nowj.fi][nowj.se] == s[nowk.fi][nowk.se]){ now += s[nowj.fi][nowj.se]; (nowj.fi += d[0][dj] + h) %= h; (nowj.se += d[1][dj] + w) %= w; (nowk.fi += d[0][dk] + h) %= h; (nowk.se += d[1][dk] + w) %= w; if(nowj == memoj && nowk == memok)break; } if(now.size() <= 1)continue; if(now.size() > ans.size() || (now.size() == ans.size() && now < ans)) ans = now; } } } return ans.size() == 0? "0":ans; } ```
#include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #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 <cstring> #include <sstream> #include <cassert> #include <ctime> #include <list> #include <numeric> #include <fstream> using namespace std; static const double EPS = 1e-8; typedef long long ll; typedef unsigned long long ull; typedef pair<ll,ll> PI; #ifndef M_PI const double M_PI=acos(-1.0); #endif #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 FORR(i,c) for(__typeof((c).rbegin())i=(c).rbegin();i!=(c).rend();++i) #define ALL(c) (c).begin(), (c).end() #define mp(a,b) make_pair(a,b) #define pb(a) push_back(a) #define SZ(a) (int((a).size())) #define F first #define S second void pkuassert(bool b){if(!b){int a=0;cout << 1/a << endl;}}; int dx[]={0,-1,0,1,1,1,-1,-1},dy[]={1,0,-1,0,1,-1,1,-1}; int n,m; string in[100]; void solve(){ vector<string> app; rep(i,n) cin >> in[i]; rep(i,n)rep(j,m){ rep(k,8){ int cx=i,cy=j; string str; do{ str += in[cx][cy]; cx += dx[k]; cy += dy[k]; if(cx<0) cx += n; if(cy<0) cy += m; if(cx>=n) cx -= n; if(cy>=m) cy -= m; }while(cx!=i || cy!=j); app.pb(str); } } sort(ALL(app)); string ans; rep(i,SZ(app)-1){ int le=0; while(le<SZ(app[i]) && le<SZ(app[i+1]) && app[i][le]==app[i+1][le]) ++le; if(SZ(ans)<le) ans = app[i].substr(0,le); } if(SZ(ans)>1) cout << ans << endl; else cout << 0 << endl; } int main(){ while(cin >> n >> m && n&&m) solve(); }
### Prompt Please create a solution in Cpp to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #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 <cstring> #include <sstream> #include <cassert> #include <ctime> #include <list> #include <numeric> #include <fstream> using namespace std; static const double EPS = 1e-8; typedef long long ll; typedef unsigned long long ull; typedef pair<ll,ll> PI; #ifndef M_PI const double M_PI=acos(-1.0); #endif #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 FORR(i,c) for(__typeof((c).rbegin())i=(c).rbegin();i!=(c).rend();++i) #define ALL(c) (c).begin(), (c).end() #define mp(a,b) make_pair(a,b) #define pb(a) push_back(a) #define SZ(a) (int((a).size())) #define F first #define S second void pkuassert(bool b){if(!b){int a=0;cout << 1/a << endl;}}; int dx[]={0,-1,0,1,1,1,-1,-1},dy[]={1,0,-1,0,1,-1,1,-1}; int n,m; string in[100]; void solve(){ vector<string> app; rep(i,n) cin >> in[i]; rep(i,n)rep(j,m){ rep(k,8){ int cx=i,cy=j; string str; do{ str += in[cx][cy]; cx += dx[k]; cy += dy[k]; if(cx<0) cx += n; if(cy<0) cy += m; if(cx>=n) cx -= n; if(cy>=m) cy -= m; }while(cx!=i || cy!=j); app.pb(str); } } sort(ALL(app)); string ans; rep(i,SZ(app)-1){ int le=0; while(le<SZ(app[i]) && le<SZ(app[i+1]) && app[i][le]==app[i+1][le]) ++le; if(SZ(ans)<le) ans = app[i].substr(0,le); } if(SZ(ans)>1) cout << ans << endl; else cout << 0 << endl; } int main(){ while(cin >> n >> m && n&&m) solve(); } ```
#include <algorithm> #include <iostream> #include <vector> #include <set> using namespace std; int di[] = {0, 0, 1, -1, 1, 1, -1, -1}; int dj[] = {1, -1, 0, 0, 1, -1, 1, -1}; int main() { int h, w; while (cin >> h >> w, h) { vector<string> s(h); for (auto &si: s) cin >> si; set<string> se; vector<string> res; for (int k = 0; k < 8; k++) { for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) { string tmp; int ni = i, nj = j; do { (ni += di[k] + h) %= h; (nj += dj[k] + w) %= w; tmp += s[ni][nj]; if (se.count(tmp)) res.emplace_back(tmp); else se.emplace(tmp); } while (ni != i || nj != j); } } int len = 0; for (auto &si: res) len = max(len, (int)si.size()); string ans = string(len, 'a'); for (auto &si: res) if (si.size() == len) ans = min(ans, si); if (len < 2) cout << 0 << endl; else cout << ans << endl; } return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <algorithm> #include <iostream> #include <vector> #include <set> using namespace std; int di[] = {0, 0, 1, -1, 1, 1, -1, -1}; int dj[] = {1, -1, 0, 0, 1, -1, 1, -1}; int main() { int h, w; while (cin >> h >> w, h) { vector<string> s(h); for (auto &si: s) cin >> si; set<string> se; vector<string> res; for (int k = 0; k < 8; k++) { for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) { string tmp; int ni = i, nj = j; do { (ni += di[k] + h) %= h; (nj += dj[k] + w) %= w; tmp += s[ni][nj]; if (se.count(tmp)) res.emplace_back(tmp); else se.emplace(tmp); } while (ni != i || nj != j); } } int len = 0; for (auto &si: res) len = max(len, (int)si.size()); string ans = string(len, 'a'); for (auto &si: res) if (si.size() == len) ans = min(ans, si); if (len < 2) cout << 0 << endl; else cout << ans << endl; } return 0; } ```
#include "bits/stdc++.h" #define REP(i,n) for(ll i=0;i<n;++i) #define RREP(i,n) for(ll i=n-1;i>=0;--i) #define FOR(i,m,n) for(ll i=m;i<n;++i) #define RFOR(i,m,n) for(ll i=n-1;i>=m;--i) #define ALL(v) (v).begin(),(v).end() #define PB(a) push_back(a) #define UNIQUE(v) v.erase(unique(ALL(v)),v.end()); #define DUMP(v) REP(i, (v).size()) { cout << v[i]; if (i != v.size() - 1)cout << " "; else cout << endl; } #define INF 1000000001ll #define MOD 1000000007ll #define EPS 1e-9 const int dx[8] = { 1,1,0,-1,-1,-1,0,1 }; const int dy[8] = { 0,1,1,1,0,-1,-1,-1 }; using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef pair<int, int> pii; typedef pair<ll, ll> pll; ll max(ll a, int b) { return max(a, ll(b)); } ll max(int a, ll b) { return max(ll(a), b); } ll min(ll a, int b) { return min(a, ll(b)); } ll min(int a, ll b) { return min(ll(a), b); } ///(´・ω・`)(´・ω・`)(´・ω・`)(´・ω・`)(´・ω・`)(´・ω・`)/// int main() { cin.tie(0); ios::sync_with_stdio(false); while (1) { int h, w; cin >> h >> w; if (!h)break; vector<string> v(h); REP(i, h)cin >> v[i]; set<string> st; string ans = ""; REP(i, h) { REP(j, w) { REP(k, 8) { int ni = i, nj = j; string s; s += v[i][j]; REP(l, INF) { if (!st.insert(s).second) { if (ans.size() < s.size())ans = s; else if (ans.size() == s.size() && ans > s)ans = s; } ni = (ni + dx[k] + h) % h, nj = (nj + dy[k] + w) % w; if (ni == i&&nj == j)break; s += v[ni][nj]; } } } } if (ans.size() <= 1)cout << 0 << endl; else cout << ans << endl; } return 0; }
### Prompt Your task is to create a CPP solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include "bits/stdc++.h" #define REP(i,n) for(ll i=0;i<n;++i) #define RREP(i,n) for(ll i=n-1;i>=0;--i) #define FOR(i,m,n) for(ll i=m;i<n;++i) #define RFOR(i,m,n) for(ll i=n-1;i>=m;--i) #define ALL(v) (v).begin(),(v).end() #define PB(a) push_back(a) #define UNIQUE(v) v.erase(unique(ALL(v)),v.end()); #define DUMP(v) REP(i, (v).size()) { cout << v[i]; if (i != v.size() - 1)cout << " "; else cout << endl; } #define INF 1000000001ll #define MOD 1000000007ll #define EPS 1e-9 const int dx[8] = { 1,1,0,-1,-1,-1,0,1 }; const int dy[8] = { 0,1,1,1,0,-1,-1,-1 }; using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef pair<int, int> pii; typedef pair<ll, ll> pll; ll max(ll a, int b) { return max(a, ll(b)); } ll max(int a, ll b) { return max(ll(a), b); } ll min(ll a, int b) { return min(a, ll(b)); } ll min(int a, ll b) { return min(ll(a), b); } ///(´・ω・`)(´・ω・`)(´・ω・`)(´・ω・`)(´・ω・`)(´・ω・`)/// int main() { cin.tie(0); ios::sync_with_stdio(false); while (1) { int h, w; cin >> h >> w; if (!h)break; vector<string> v(h); REP(i, h)cin >> v[i]; set<string> st; string ans = ""; REP(i, h) { REP(j, w) { REP(k, 8) { int ni = i, nj = j; string s; s += v[i][j]; REP(l, INF) { if (!st.insert(s).second) { if (ans.size() < s.size())ans = s; else if (ans.size() == s.size() && ans > s)ans = s; } ni = (ni + dx[k] + h) % h, nj = (nj + dy[k] + w) % w; if (ni == i&&nj == j)break; s += v[ni][nj]; } } } } if (ans.size() <= 1)cout << 0 << endl; else cout << ans << endl; } return 0; } ```
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <set> using namespace std; int main() { int dy[] = {-1, -1, 0, 1, 1, 1, 0, -1}; int dx[] = {0, 1, 1, 1, 0, -1, -1, -1}; for(;;){ int h, w; cin >> h >> w; if(h == 0) return 0; vector<string> grid(h); for(int i=0; i<h; ++i) cin >> grid[i]; set<string> ss; string ret; int maxLen = -1; for(int y=0; y<h; ++y){ for(int x=0; x<w; ++x){ for(int d=0; d<8; ++d){ int y1 = y; int x1 = x; string s; do{ s += grid[y1][x1]; y1 += dy[d] + h; x1 += dx[d] + w; y1 %= h; x1 %= w; }while(y1 != y || x1 != x); int n = s.size(); while(n >= max(maxLen, 2)){ string t = s.substr(0, n); if(ss.find(t) == ss.end()){ ss.insert(t); }else{ if(n > maxLen || (n == maxLen && t < ret)){ maxLen = n; ret = t; } break; } -- n; } } } } if(maxLen == -1) cout << 0 << endl; else cout << ret << endl; } }
### Prompt Your challenge is to write a cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <vector> #include <string> #include <algorithm> #include <set> using namespace std; int main() { int dy[] = {-1, -1, 0, 1, 1, 1, 0, -1}; int dx[] = {0, 1, 1, 1, 0, -1, -1, -1}; for(;;){ int h, w; cin >> h >> w; if(h == 0) return 0; vector<string> grid(h); for(int i=0; i<h; ++i) cin >> grid[i]; set<string> ss; string ret; int maxLen = -1; for(int y=0; y<h; ++y){ for(int x=0; x<w; ++x){ for(int d=0; d<8; ++d){ int y1 = y; int x1 = x; string s; do{ s += grid[y1][x1]; y1 += dy[d] + h; x1 += dx[d] + w; y1 %= h; x1 %= w; }while(y1 != y || x1 != x); int n = s.size(); while(n >= max(maxLen, 2)){ string t = s.substr(0, n); if(ss.find(t) == ss.end()){ ss.insert(t); }else{ if(n > maxLen || (n == maxLen && t < ret)){ maxLen = n; ret = t; } break; } -- n; } } } } if(maxLen == -1) cout << 0 << endl; else cout << ret << endl; } } ```
#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; struct bstr{ string str; bstr(string s){str=s;} bool operator<(const bstr& a) const{ return str.size()==a.str.size() ? (str.compare(a.str) < 0): str.size() > a.str.size(); } }; int main(){ int h,w; int i,j,k; int ai[]={ 1, 1, 1, 0, 0,-1,-1,-1}; int aj[]={ 1, 0,-1, 1,-1, 1, 0,-1}; cin >> h >> w; while(h!=0){ string str[10]; for(i=0;i<h;i++) cin >> str[i]; vector <bstr> li; vector <string> ans; int mal=1; for(i=0;i<h;i++){ //cout << i << endl; for(j=0;j<w;j++){ for(k=0;k<8;k++){ int bi=i,bj=j; string buf; buf += str[i][j]; bi+=ai[k];bj+=aj[k]; if(bi<0) bi=h-1; if(bi>=h) bi=0; if(bj<0) bj=w-1; if(bj>=w) bj=0; while(bi!=i||bj!=j){ buf+=str[bi][bj]; li.push_back(bstr(buf)); bi+=ai[k];bj+=aj[k]; if(bi<0) bi=h-1; if(bi>=h) bi=0; if(bj<0) bj=w-1; if(bj>=w) bj=0; } } } } sort(li.begin(),li.end()); for(i=0;i<li.size()-1;i++){ if(li[i].str==li[i+1].str) { ans.push_back(li[i].str); break; } } //for(i=0;i<li.size();i++) cout << li[i] << endl; sort(ans.begin(),ans.end()); //for(i=0;i<ans.size();i++) cout << ans[i] << endl; if(ans.size()!=0) cout << ans[0] << endl; else cout << 0 << endl; cin >> h >> w; } return 0; }
### Prompt Generate a Cpp solution to the following problem: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; struct bstr{ string str; bstr(string s){str=s;} bool operator<(const bstr& a) const{ return str.size()==a.str.size() ? (str.compare(a.str) < 0): str.size() > a.str.size(); } }; int main(){ int h,w; int i,j,k; int ai[]={ 1, 1, 1, 0, 0,-1,-1,-1}; int aj[]={ 1, 0,-1, 1,-1, 1, 0,-1}; cin >> h >> w; while(h!=0){ string str[10]; for(i=0;i<h;i++) cin >> str[i]; vector <bstr> li; vector <string> ans; int mal=1; for(i=0;i<h;i++){ //cout << i << endl; for(j=0;j<w;j++){ for(k=0;k<8;k++){ int bi=i,bj=j; string buf; buf += str[i][j]; bi+=ai[k];bj+=aj[k]; if(bi<0) bi=h-1; if(bi>=h) bi=0; if(bj<0) bj=w-1; if(bj>=w) bj=0; while(bi!=i||bj!=j){ buf+=str[bi][bj]; li.push_back(bstr(buf)); bi+=ai[k];bj+=aj[k]; if(bi<0) bi=h-1; if(bi>=h) bi=0; if(bj<0) bj=w-1; if(bj>=w) bj=0; } } } } sort(li.begin(),li.end()); for(i=0;i<li.size()-1;i++){ if(li[i].str==li[i+1].str) { ans.push_back(li[i].str); break; } } //for(i=0;i<li.size();i++) cout << li[i] << endl; sort(ans.begin(),ans.end()); //for(i=0;i<ans.size();i++) cout << ans[i] << endl; if(ans.size()!=0) cout << ans[0] << endl; else cout << 0 << endl; cin >> h >> w; } return 0; } ```
#include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; typedef unsigned long long ull; const int dy[8] = {1,1,1,0,0,-1,-1,-1}; const int dx[8] = {-1,0,1,-1,1,-1,0,1}; int h,w; string str[10]; void solve(){ int y, x, ansn = 0; string ans = "0"; set<string> s; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ string st; st += str[i][j]; y = i; x = j; while(1){ y = (y + h + dy[k]) % h; x = (x + w + dx[k]) % w; if(y == i && j == x) break; else st += str[y][x]; if(!s.empty() && s.find(st) != s.end()){ if(ansn < st.size() || ansn == st.size() && ans > st){ ans = st; ansn = st.size(); } } else s.insert(st); } } } } cout << ans << endl; } int main(){ while(cin >> h >> w && (h|w)){ for(int i=0;i<h;i++){ cin >> str[i]; } solve(); } }
### Prompt Construct a cpp code solution to the problem outlined: Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that your master was using. It was the time to try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he brought flour from the storage, and started kneading dough. The spell worked, and how fast he kneaded it! A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he still worked as fast as he could. If you could not stop him now, you would be choked in the kitchen filled with pieces of dough. Wait, didn't your master write his spells on his notebooks? You went to his den, and found the notebook that recorded the spell of cessation. But it was not the end of the story. The spell written in the notebook is not easily read by others. He used a plastic model of a donut as a notebook for recording the spell. He split the surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters (Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless. But you knew that he wrote the pattern so that the spell "appears" more than once (see the next paragraph for the precise conditions). The spell was not necessarily written in the left-to-right direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up, and the 4 diagonal directions. You should be able to find the spell as the longest string that appears more than once. Here, a string is considered to appear more than once if there are square sequences having the string on the donut that satisfy the following conditions. * Each square sequence does not overlap itself. (Two square sequences can share some squares.) * The square sequences start from different squares, and/or go to different directions. <image> | <image> | Figure B.1: The Sorcerer's Donut Before Filled with Letters, Showing the Mesh and 8 Possible Spell Directions | Figure B.2: The Sorcerer's Donut After Filled with Letters ---|--- Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards) that satisfies the first condition "appears" twice. The pattern on the donut is given as a matrix of letters as follows. ABCD EFGH IJKL Note that the surface of the donut has no ends; the top and bottom sides, and the left and right sides of the pattern are respectively connected. There can be square sequences longer than both the vertical and horizontal lengths of the pattern. For example, from the letter F in the above pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are as follows. FGHE FKDEJCHIBGLA FJB FIDGJAHKBELC FEHG FALGBIHCJEDK FBJ FCLEBKHAJGDI Please write a program that finds the magic spell before you will be choked with pieces of donuts dough. Input The input is a sequence of datasets. Each dataset begins with a line of two integers h and w, which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z, inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20. The end of the input is indicated by a line containing two zeros. Output For each dataset, output the magic spell. If there is more than one longest string of the same length, the first one in the dictionary order must be the spell. The spell is known to be at least two letters long. When no spell is found, output 0 (zero). Example Input 5 7 RRCABXT AABMFAB RROMJAC APTADAB YABADAO 3 13 ABCDEFGHIJKLM XMADAMIMADAMY ACEGIKMOQSUWY 3 4 DEFG ACAB HIJK 3 6 ABCDEF GHIAKL MNOPQR 10 19 JFZODYDXMZZPEYTRNCW XVGHPOKEYNZTQFZJKOD EYEHHQKHFZOVNRGOOLP QFZOIHRQMGHPNISHXOC DRGILJHSQEHHQLYTILL NCSHQMKHTZZIHRPAUJA NCCTINCLAUTFJHSZBVK LPBAUJIUMBVQYKHTZCW XMYHBVKUGNCWTLLAUID EYNDCCWLEOODXYUMBVN 0 0 Output ABRACADABRA MADAMIMADAM ABAC 0 ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ ### Response ```cpp #include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; typedef unsigned long long ull; const int dy[8] = {1,1,1,0,0,-1,-1,-1}; const int dx[8] = {-1,0,1,-1,1,-1,0,1}; int h,w; string str[10]; void solve(){ int y, x, ansn = 0; string ans = "0"; set<string> s; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ for(int k=0;k<8;k++){ string st; st += str[i][j]; y = i; x = j; while(1){ y = (y + h + dy[k]) % h; x = (x + w + dx[k]) % w; if(y == i && j == x) break; else st += str[y][x]; if(!s.empty() && s.find(st) != s.end()){ if(ansn < st.size() || ansn == st.size() && ans > st){ ans = st; ansn = st.size(); } } else s.insert(st); } } } } cout << ans << endl; } int main(){ while(cin >> h >> w && (h|w)){ for(int i=0;i<h;i++){ cin >> str[i]; } solve(); } } ```