output
stringlengths
52
181k
instruction
stringlengths
296
182k
#include <bits/stdc++.h> class Solve { private: std::string inputStr; int64_t calcAdd(int& s_i) { int64_t ret{calcMulti(s_i)}; while (inputStr[s_i] == '+' || inputStr[s_i] == '-') { char ope{inputStr[s_i]}; s_i++; if (ope == '+') ret += calcMulti(s_i); else ret -= calcMulti(s_i); } return ret; } int64_t calcMulti(int& s_i) { int64_t ret{calcNum(s_i)}; while (inputStr[s_i] == '*' || inputStr[s_i] == '/') { char ope{inputStr[s_i]}; s_i++; if (ope == '*') ret *= calcNum(s_i); else ret /= calcNum(s_i); } return ret; } int64_t calcNum(int& s_i) { int64_t ret{}; if (inputStr[s_i] == '(') { s_i++; ret = calcAdd(s_i); s_i++; } else { while (isdigit(inputStr[s_i])) { ret = 10 * ret + inputStr[s_i] - '0'; s_i++; } } return ret; } public: bool is_last_query{}; Solve() { std::cin >> inputStr; int s_i{}; printf("%lld\n", calcAdd(s_i)); } }; int main() { int N; scanf("%d", &N); for (int i{}; i < N; i++) Solve(); return 0; }
### Prompt Generate a CPP solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <bits/stdc++.h> class Solve { private: std::string inputStr; int64_t calcAdd(int& s_i) { int64_t ret{calcMulti(s_i)}; while (inputStr[s_i] == '+' || inputStr[s_i] == '-') { char ope{inputStr[s_i]}; s_i++; if (ope == '+') ret += calcMulti(s_i); else ret -= calcMulti(s_i); } return ret; } int64_t calcMulti(int& s_i) { int64_t ret{calcNum(s_i)}; while (inputStr[s_i] == '*' || inputStr[s_i] == '/') { char ope{inputStr[s_i]}; s_i++; if (ope == '*') ret *= calcNum(s_i); else ret /= calcNum(s_i); } return ret; } int64_t calcNum(int& s_i) { int64_t ret{}; if (inputStr[s_i] == '(') { s_i++; ret = calcAdd(s_i); s_i++; } else { while (isdigit(inputStr[s_i])) { ret = 10 * ret + inputStr[s_i] - '0'; s_i++; } } return ret; } public: bool is_last_query{}; Solve() { std::cin >> inputStr; int s_i{}; printf("%lld\n", calcAdd(s_i)); } }; int main() { int N; scanf("%d", &N); for (int i{}; i < N; i++) Solve(); return 0; } ```
#include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) using namespace std; pair<int64_t,int> expr(const string &s, int i); pair<int64_t,int> num(const string &s, int i) { int64_t v = 0; while(i < s.size() && ('0' <= s[i] && s[i] <= '9')) { v *= 10; v += s[i] - '0'; ++i; } return make_pair(v, i); } pair<int64_t,int> factor(const string &s, int i) { if (s[i] == '(') { auto p = expr(s, i+1); ++p.second; return p; } else { return num(s, i); } } pair<int64_t,int> term(const string &s, int i) { int64_t val; tie(val, i) = factor(s, i); while(i < s.size() && (s[i] == '*' || s[i] == '/')) { int64_t val2; int j; tie(val2, j) = factor(s, i+1); if (s[i] == '*') val *= val2; else val /= val2; i = j; } return make_pair(val, i); } pair<int64_t,int> expr(const string &s, int i) { int64_t val; tie(val, i) = term(s, i); while(s[i] == '+' || s[i] == '-') { int64_t val2; int j; tie(val2, j) = term(s, i+1); if (s[i] == '+') val += val2; else val -= val2; i = j; } return make_pair(val, i); } int main() { int n; cin>>n; REP(ds,n) { string s; cin>>s; cout << expr(s, 0).first << endl; } return 0; }
### Prompt In cpp, your task is to solve the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) using namespace std; pair<int64_t,int> expr(const string &s, int i); pair<int64_t,int> num(const string &s, int i) { int64_t v = 0; while(i < s.size() && ('0' <= s[i] && s[i] <= '9')) { v *= 10; v += s[i] - '0'; ++i; } return make_pair(v, i); } pair<int64_t,int> factor(const string &s, int i) { if (s[i] == '(') { auto p = expr(s, i+1); ++p.second; return p; } else { return num(s, i); } } pair<int64_t,int> term(const string &s, int i) { int64_t val; tie(val, i) = factor(s, i); while(i < s.size() && (s[i] == '*' || s[i] == '/')) { int64_t val2; int j; tie(val2, j) = factor(s, i+1); if (s[i] == '*') val *= val2; else val /= val2; i = j; } return make_pair(val, i); } pair<int64_t,int> expr(const string &s, int i) { int64_t val; tie(val, i) = term(s, i); while(s[i] == '+' || s[i] == '-') { int64_t val2; int j; tie(val2, j) = term(s, i+1); if (s[i] == '+') val += val2; else val -= val2; i = j; } return make_pair(val, i); } int main() { int n; cin>>n; REP(ds,n) { string s; cin>>s; cout << expr(s, 0).first << endl; } return 0; } ```
/* <expr> ::= <term> [ ('+'|'-') <term> ]* <term> ::= <factor> [ ('*'|'/') <factor> ]* <factor> ::= <number> | '(' <expr> ')' <number> :== 1つ以上の数字 */ #include <iostream> #include <stdio.h> #include <vector> #include <string> #include <algorithm> using namespace std; int expr(string& s, int& i); int term(string& s, int& i); int factor(string& s, int& i); int number(string& s, int& i); int main(){ int n; cin >> n; for(int j = 0; j < n; j++){ string str; cin >> str; int i = 0; cout << expr(str, i) << endl; } return 0; } int expr(string& s, int& i){ int val = term(s, i); while(s[i] == '+' || s[i] == '-'){ char op = s[i++]; int val2 = term(s, i); if(op == '+') val += val2; else val -= val2; } return val; } int term(string& s, int& i){ int val = factor(s, i); while(s[i] == '*' || s[i] == '/'){ char op = s[i++]; int val2 = factor(s, i); if(op == '*') val *= val2; else val /= val2; } return val; } int factor(string& s, int& i){ if(isdigit(s[i])) return number(s, i); i++; int ret = expr(s, i); i++; return ret; } int number(string& s, int& i){ int n = s[i++] - '0'; while(isdigit(s[i])) n = n * 10 + s[i++] - '0'; return n; }
### Prompt Generate a Cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp /* <expr> ::= <term> [ ('+'|'-') <term> ]* <term> ::= <factor> [ ('*'|'/') <factor> ]* <factor> ::= <number> | '(' <expr> ')' <number> :== 1つ以上の数字 */ #include <iostream> #include <stdio.h> #include <vector> #include <string> #include <algorithm> using namespace std; int expr(string& s, int& i); int term(string& s, int& i); int factor(string& s, int& i); int number(string& s, int& i); int main(){ int n; cin >> n; for(int j = 0; j < n; j++){ string str; cin >> str; int i = 0; cout << expr(str, i) << endl; } return 0; } int expr(string& s, int& i){ int val = term(s, i); while(s[i] == '+' || s[i] == '-'){ char op = s[i++]; int val2 = term(s, i); if(op == '+') val += val2; else val -= val2; } return val; } int term(string& s, int& i){ int val = factor(s, i); while(s[i] == '*' || s[i] == '/'){ char op = s[i++]; int val2 = factor(s, i); if(op == '*') val *= val2; else val /= val2; } return val; } int factor(string& s, int& i){ if(isdigit(s[i])) return number(s, i); i++; int ret = expr(s, i); i++; return ret; } int number(string& s, int& i){ int n = s[i++] - '0'; while(isdigit(s[i])) n = n * 10 + s[i++] - '0'; return n; } ```
#include<iostream> #include<cassert> using namespace std; string s; size_t cur=0; int digit() { assert(isdigit(s[cur])); int n=s[cur]-'0'; cur=cur+1; return n; }; int number() { int n=digit(); while(cur<s.size()&&isdigit(s[cur])) n=n*10+digit(); return n; }; double expression(); double factor() { if(s[cur]!='(') return number(); cur++; double n=expression(); assert(s[cur]==')'); cur++; return n; }; double term() { double a=factor(); while(cur<s.size()&&(s[cur]=='*'||s[cur]=='/')) { char op=s[cur++]; int b=factor(); if(op=='*') a*=b; else a/=b; } return a; }; int main() { int n; cin>>n; for(int i=0;i<n;i++) { cur=0; cin>>s; s.resize(s.size()-1); cout<<expression()<<endl; } } double expression() { int a=term(); while((cur<s.size())&&(s[cur]=='+'||s[cur]=='-')) { char op=s[cur++]; int b=term(); if(op=='+') a+=b; else a-=b; } return a; }
### Prompt Create a solution in cpp for the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<cassert> using namespace std; string s; size_t cur=0; int digit() { assert(isdigit(s[cur])); int n=s[cur]-'0'; cur=cur+1; return n; }; int number() { int n=digit(); while(cur<s.size()&&isdigit(s[cur])) n=n*10+digit(); return n; }; double expression(); double factor() { if(s[cur]!='(') return number(); cur++; double n=expression(); assert(s[cur]==')'); cur++; return n; }; double term() { double a=factor(); while(cur<s.size()&&(s[cur]=='*'||s[cur]=='/')) { char op=s[cur++]; int b=factor(); if(op=='*') a*=b; else a/=b; } return a; }; int main() { int n; cin>>n; for(int i=0;i<n;i++) { cur=0; cin>>s; s.resize(s.size()-1); cout<<expression()<<endl; } } double expression() { int a=term(); while((cur<s.size())&&(s[cur]=='+'||s[cur]=='-')) { char op=s[cur++]; int b=term(); if(op=='+') a+=b; else a-=b; } return a; } ```
#include <cstdio> #include <cassert> #include <algorithm> using namespace std; char *pt; int parseAtom(); int parseExpr(); int parseTerm(); int parseAtom() { if('0' <= *pt && *pt <= '9') { int x = *pt-'0'; pt++; while('0' <= *pt && *pt <= '9') { x = x*10 + *pt-'0'; pt++; } return x; } if('(' == *pt) { pt++; int x = parseExpr(); assert(*pt == ')'); pt++; return x; } assert(false); return -1; } int parseExpr() { int x = parseTerm(); while(*pt == '+' || *pt == '-') { if(*pt == '+') { pt++; x += parseTerm(); } else { pt++; x -= parseTerm(); } } return x; } int parseTerm() { int x = parseAtom(); while(*pt == '*' || *pt == '/') { if(*pt == '*') { pt++; x *= parseAtom(); } else { pt++; x /= parseAtom(); } } return x; } int main() { int tc; scanf("%d", &tc); for(int tci = 0; tci < tc; tci++) { static char expr[200]; scanf(" %s", expr); pt = expr; int x = parseExpr(); assert(*pt == '='); printf("%d\n", x); } return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <cstdio> #include <cassert> #include <algorithm> using namespace std; char *pt; int parseAtom(); int parseExpr(); int parseTerm(); int parseAtom() { if('0' <= *pt && *pt <= '9') { int x = *pt-'0'; pt++; while('0' <= *pt && *pt <= '9') { x = x*10 + *pt-'0'; pt++; } return x; } if('(' == *pt) { pt++; int x = parseExpr(); assert(*pt == ')'); pt++; return x; } assert(false); return -1; } int parseExpr() { int x = parseTerm(); while(*pt == '+' || *pt == '-') { if(*pt == '+') { pt++; x += parseTerm(); } else { pt++; x -= parseTerm(); } } return x; } int parseTerm() { int x = parseAtom(); while(*pt == '*' || *pt == '/') { if(*pt == '*') { pt++; x *= parseAtom(); } else { pt++; x /= parseAtom(); } } return x; } int main() { int tc; scanf("%d", &tc); for(int tci = 0; tci < tc; tci++) { static char expr[200]; scanf(" %s", expr); pt = expr; int x = parseExpr(); assert(*pt == '='); printf("%d\n", x); } return 0; } ```
#include <iostream> #include <cctype> #include <string> using namespace std; string S; int cur = 0; int digit() { return S[cur++] - '0'; } int number() { int n = digit(); while(cur < S.size() && isdigit(S[cur])) n = n * 10 + digit(); return n; } int expression(); int factor() { if(S[cur] != '(') return number(); cur++; int n = expression(); cur++; return n; } int term() { int n = factor(); while(cur < S.size() && (S[cur] == '*' || S[cur] == '/')) { char op = S[cur++]; if(op == '*') n *= factor(); else n /= factor(); } return n; } int expression() { int n = term(); while(cur < S.size() && (S[cur] == '+' || S[cur] == '-')) { char op = S[cur++]; if(op == '+') n += term(); else n -= term(); } return n; } int main() { int n; cin >> n; for(int i = 0;i < n;i++) { cur = 0; cin >> S; S.erase(S.size() - 1); cout << expression() << endl; } }
### Prompt Create a solution in CPP for the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <cctype> #include <string> using namespace std; string S; int cur = 0; int digit() { return S[cur++] - '0'; } int number() { int n = digit(); while(cur < S.size() && isdigit(S[cur])) n = n * 10 + digit(); return n; } int expression(); int factor() { if(S[cur] != '(') return number(); cur++; int n = expression(); cur++; return n; } int term() { int n = factor(); while(cur < S.size() && (S[cur] == '*' || S[cur] == '/')) { char op = S[cur++]; if(op == '*') n *= factor(); else n /= factor(); } return n; } int expression() { int n = term(); while(cur < S.size() && (S[cur] == '+' || S[cur] == '-')) { char op = S[cur++]; if(op == '+') n += term(); else n -= term(); } return n; } int main() { int n; cin >> n; for(int i = 0;i < n;i++) { cur = 0; cin >> S; S.erase(S.size() - 1); cout << expression() << endl; } } ```
#include<iostream> #include<cctype> #include<cassert> using namespace std; string s; int cur; int factor(); char readchar(){ assert(cur <s.size()); char ret =s[cur]; cur += 1; return ret; } char peak(){ assert(cur<s.size()); return s[cur]; } int digit(){ assert(isdigit(peak())); int n = readchar() - '0'; return n; } int number(){ int n= digit(); while(cur<s.size()&&isdigit(peak())) n=n*10+digit(); return n; } int term(){ int a = factor(); while((cur <s.size()) && (peak()=='*' || peak() == '/')){ char op = readchar(); int b = factor(); if(op=='*') a*=b; else a/=b; } return a; } int expression(){ int a=term(); while((cur<s.size())&& (peak()=='+' || peak() == '-')){ char op = readchar(); int b= term(); if(op == '+') a+=b;else a-=b; } return a; } int factor(){ if(peak() != '(') return number(); cur += 1; int n = expression(); assert(peak() == ')'); cur+=1; return n; } int main(){ int n; cin>>n; for(int i=0;i<n;i++){ cur=0; cin>>s; s.resize(s.size()-1); cout<<expression() <<endl; } }
### Prompt Your task is to create a Cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<cctype> #include<cassert> using namespace std; string s; int cur; int factor(); char readchar(){ assert(cur <s.size()); char ret =s[cur]; cur += 1; return ret; } char peak(){ assert(cur<s.size()); return s[cur]; } int digit(){ assert(isdigit(peak())); int n = readchar() - '0'; return n; } int number(){ int n= digit(); while(cur<s.size()&&isdigit(peak())) n=n*10+digit(); return n; } int term(){ int a = factor(); while((cur <s.size()) && (peak()=='*' || peak() == '/')){ char op = readchar(); int b = factor(); if(op=='*') a*=b; else a/=b; } return a; } int expression(){ int a=term(); while((cur<s.size())&& (peak()=='+' || peak() == '-')){ char op = readchar(); int b= term(); if(op == '+') a+=b;else a-=b; } return a; } int factor(){ if(peak() != '(') return number(); cur += 1; int n = expression(); assert(peak() == ')'); cur+=1; return n; } int main(){ int n; cin>>n; for(int i=0;i<n;i++){ cur=0; cin>>s; s.resize(s.size()-1); cout<<expression() <<endl; } } ```
#include <iostream> #include <string> #include <cstdlib> using namespace std; int p; int exp(string str); int term(string str); int fact(string str); int exp(string str) { int val = term(str); while(str[p] == '+' || str[p] == '-'){ if(str[p++] == '+'){ val += term(str); } else { val -= term(str); } } return val; } int term(string str) { int val = fact(str); while(str[p] == '*' || str[p] == '/'){ if(str[p++] == '*'){ val *= fact(str); } else { val /= fact(str); } } return val; } int fact(string str) { int val = 0; if(str[p] == '('){ p++; val = exp(str); p++; } else { string s = ""; while('0' <= str[p] && str[p] <= '9'){ s += str[p++]; } if(s.size() > 0){ val = atoi(s.c_str()); } } return val; } int main() { int n; string str; while(cin >> n && n){ while(n--){ cin >> str; p = 0; cout << exp(str) << endl; } } return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> #include <cstdlib> using namespace std; int p; int exp(string str); int term(string str); int fact(string str); int exp(string str) { int val = term(str); while(str[p] == '+' || str[p] == '-'){ if(str[p++] == '+'){ val += term(str); } else { val -= term(str); } } return val; } int term(string str) { int val = fact(str); while(str[p] == '*' || str[p] == '/'){ if(str[p++] == '*'){ val *= fact(str); } else { val /= fact(str); } } return val; } int fact(string str) { int val = 0; if(str[p] == '('){ p++; val = exp(str); p++; } else { string s = ""; while('0' <= str[p] && str[p] <= '9'){ s += str[p++]; } if(s.size() > 0){ val = atoi(s.c_str()); } } return val; } int main() { int n; string str; while(cin >> n && n){ while(n--){ cin >> str; p = 0; cout << exp(str) << endl; } } return 0; } ```
#include <cstring> #include <cctype> #include <iostream> #include <cstdio> using namespace std; int exp(char* & p); int num(char* & p) { int ret = 0; while (isdigit(*p)) { ret *= 10; ret += *p - '0'; p++; } return ret; } int fac(char* & p) { int ret = 0; if (*p == '(') { p++; ret += exp(p); p++; } else { ret += num(p); } return ret; } int term(char* & p) { int ret = fac(p); while(1) { if (*p == '*') { p++; ret *= fac(p); } else if (*p == '/') { p++; ret /= fac(p); } else { break; } } return ret; } int exp(char* & p) { int ret = term(p); while(1) { if (*p == '+') { p++; ret += term(p); } else if (*p == '-') { p++; ret -= term(p); } else break; } return ret; } int eval(const string & s){ char* p = (char*)s.c_str(); return exp(p); } int eval(const char* str){ char* p = (char*)str; return exp(p); } using namespace std; int main(){ int n; cin >> n; cin.ignore(); while(n--){ char str[128]; gets(str); cout << eval(str) << endl; } return 0; }
### Prompt Create a solution in CPP for the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <cstring> #include <cctype> #include <iostream> #include <cstdio> using namespace std; int exp(char* & p); int num(char* & p) { int ret = 0; while (isdigit(*p)) { ret *= 10; ret += *p - '0'; p++; } return ret; } int fac(char* & p) { int ret = 0; if (*p == '(') { p++; ret += exp(p); p++; } else { ret += num(p); } return ret; } int term(char* & p) { int ret = fac(p); while(1) { if (*p == '*') { p++; ret *= fac(p); } else if (*p == '/') { p++; ret /= fac(p); } else { break; } } return ret; } int exp(char* & p) { int ret = term(p); while(1) { if (*p == '+') { p++; ret += term(p); } else if (*p == '-') { p++; ret -= term(p); } else break; } return ret; } int eval(const string & s){ char* p = (char*)s.c_str(); return exp(p); } int eval(const char* str){ char* p = (char*)str; return exp(p); } using namespace std; int main(){ int n; cin >> n; cin.ignore(); while(n--){ char str[128]; gets(str); cout << eval(str) << endl; } return 0; } ```
#include<string> #include<iostream> #include<cctype> using namespace std; typedef string::const_iterator State; int number(State &begin) { int ans = 0; bool flag = false; if (*begin == '-') flag = true, begin++; while (isdigit(*begin)) ans = ans * 10 + (*begin - '0'), begin++; if (flag) ans = -ans; return ans; } int expression(State &begin); int factor(State &begin) { int ans; if (*begin == '(') begin++, ans = expression(begin), begin++; else ans = number(begin); return ans; } int term(State &begin) { int ans = factor(begin); while (1) { if (*begin == '*') begin++, ans *= factor(begin); else if (*begin == '/') begin++, ans /= factor(begin); else return ans; //begin++; } } int expression(State &begin) { int ans = term(begin); while (1) { if (*begin == '+') begin++, ans += term(begin); else if (*begin == '-') begin++, ans -= term(begin); else return ans; //begin++; } } int main() { int n; string s; cin >> n; for (int i = 0; i < n; i++) { cin >> s; State temp = s.begin(); cout << expression(temp) << endl; } }
### Prompt Please provide a Cpp coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<string> #include<iostream> #include<cctype> using namespace std; typedef string::const_iterator State; int number(State &begin) { int ans = 0; bool flag = false; if (*begin == '-') flag = true, begin++; while (isdigit(*begin)) ans = ans * 10 + (*begin - '0'), begin++; if (flag) ans = -ans; return ans; } int expression(State &begin); int factor(State &begin) { int ans; if (*begin == '(') begin++, ans = expression(begin), begin++; else ans = number(begin); return ans; } int term(State &begin) { int ans = factor(begin); while (1) { if (*begin == '*') begin++, ans *= factor(begin); else if (*begin == '/') begin++, ans /= factor(begin); else return ans; //begin++; } } int expression(State &begin) { int ans = term(begin); while (1) { if (*begin == '+') begin++, ans += term(begin); else if (*begin == '-') begin++, ans -= term(begin); else return ans; //begin++; } } int main() { int n; string s; cin >> n; for (int i = 0; i < n; i++) { cin >> s; State temp = s.begin(); cout << expression(temp) << endl; } } ```
#include<iostream> #include<string> using namespace std; int expression(); int term(); int factor(); string exp; int p; int expression(){ int value = term(); while( exp[p] == '+' || exp[p] == '-' ){ if ( exp[p] == '+' ) { p++; value += term(); } else { p++; value -= term(); } } return value; } int term(){ int value = factor(); while( exp[p] == '*' || exp[p] == '/' ){ if ( exp[p] == '*' ) { p++; value *= factor(); } else { p++; value /= factor(); } } return value; } int factor(){ int value = 0; if ( exp[p] == '(' ){ p++; value = expression(); p++; } else { while( isdigit(exp[p]) ) { value = value*10 + exp[p++] - '0';} } return value; } int main(){ int tcase; cin >> tcase; for ( int i = 0; i < tcase; i++ ){ cin >> exp; p = 0; cout << expression() << endl; } return 0; }
### Prompt Your task is to create a cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<string> using namespace std; int expression(); int term(); int factor(); string exp; int p; int expression(){ int value = term(); while( exp[p] == '+' || exp[p] == '-' ){ if ( exp[p] == '+' ) { p++; value += term(); } else { p++; value -= term(); } } return value; } int term(){ int value = factor(); while( exp[p] == '*' || exp[p] == '/' ){ if ( exp[p] == '*' ) { p++; value *= factor(); } else { p++; value /= factor(); } } return value; } int factor(){ int value = 0; if ( exp[p] == '(' ){ p++; value = expression(); p++; } else { while( isdigit(exp[p]) ) { value = value*10 + exp[p++] - '0';} } return value; } int main(){ int tcase; cin >> tcase; for ( int i = 0; i < tcase; i++ ){ cin >> exp; p = 0; cout << expression() << endl; } return 0; } ```
#include <iostream> #include <cctype> using namespace std; typedef string::const_iterator State; int number(State &begin); int factor(State &begin); int term(State &begin); int expression(State &begin); int main(void){ int N; cin >> N; cin.ignore(); for(int i = 0; i < N; i++){ string Expression; getline(cin, Expression); State begin = Expression.begin(); int ans = expression(begin); cout << ans << endl; } return 0; } int number(State &begin){ int ret = 0; while(isdigit(*begin)){ ret = ret * 10; ret = ret + *begin - '0'; begin++; } return ret; } int factor(State &begin){ if(*begin == '('){ begin++; int ret = expression(begin); begin++; return ret; }else{ return number(begin); } } int term(State &begin){ int ret = factor(begin); while(true){ if(*begin == '*'){ begin++; ret = ret * factor(begin); }else if(*begin == '/'){ begin++; ret = ret / factor(begin); }else{ break; } } return ret; } int expression(State &begin){ int ret = term(begin); while(true){ if(*begin == '+'){ begin++; ret = ret + term(begin); }else if(*begin == '-'){ begin++; ret = ret - term(begin); }else{ break; } } return ret; }
### Prompt Construct a cpp code solution to the problem outlined: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <cctype> using namespace std; typedef string::const_iterator State; int number(State &begin); int factor(State &begin); int term(State &begin); int expression(State &begin); int main(void){ int N; cin >> N; cin.ignore(); for(int i = 0; i < N; i++){ string Expression; getline(cin, Expression); State begin = Expression.begin(); int ans = expression(begin); cout << ans << endl; } return 0; } int number(State &begin){ int ret = 0; while(isdigit(*begin)){ ret = ret * 10; ret = ret + *begin - '0'; begin++; } return ret; } int factor(State &begin){ if(*begin == '('){ begin++; int ret = expression(begin); begin++; return ret; }else{ return number(begin); } } int term(State &begin){ int ret = factor(begin); while(true){ if(*begin == '*'){ begin++; ret = ret * factor(begin); }else if(*begin == '/'){ begin++; ret = ret / factor(begin); }else{ break; } } return ret; } int expression(State &begin){ int ret = term(begin); while(true){ if(*begin == '+'){ begin++; ret = ret + term(begin); }else if(*begin == '-'){ begin++; ret = ret - term(begin); }else{ break; } } return ret; } ```
#include <iostream> #include <string> #include <cctype> using namespace std; int expr(string& s, int& i); int term(string& s, int& i); int factor(string& s, int& i); int number(string& s, int& i); int expr(string& s, int& i) { int val = term(s, i); while(s[i] == '+' || s[i] == '-') { char op = s[i]; i++; int val2 = term(s, i); if (op == '+') val += val2; else val -= val2; } return val; } int term(string& s, int& i) { int val = factor(s, i); while(s[i] == '*' || s[i] == '/') { char op = s[i]; i++; int val2 = factor(s, i); if (op == '*') val *= val2; else val /= val2; } return val; } int factor(string& s, int& i) { if (isdigit(s[i])) return number(s, i); // ここで構文が正しければ s[i] == '(' となる i++; // '('を読み飛ばす int ret = expr(s, i); i++; // ')'を読み飛ばす return ret; } int number(string& s, int& i) { int n = s[i++] - '0'; while(isdigit(s[i])) n = n*10 + s[i++] - '0'; return n; } int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { string str; cin >> str; int j = 0; cout << expr(str, j) << endl; } return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> #include <cctype> using namespace std; int expr(string& s, int& i); int term(string& s, int& i); int factor(string& s, int& i); int number(string& s, int& i); int expr(string& s, int& i) { int val = term(s, i); while(s[i] == '+' || s[i] == '-') { char op = s[i]; i++; int val2 = term(s, i); if (op == '+') val += val2; else val -= val2; } return val; } int term(string& s, int& i) { int val = factor(s, i); while(s[i] == '*' || s[i] == '/') { char op = s[i]; i++; int val2 = factor(s, i); if (op == '*') val *= val2; else val /= val2; } return val; } int factor(string& s, int& i) { if (isdigit(s[i])) return number(s, i); // ここで構文が正しければ s[i] == '(' となる i++; // '('を読み飛ばす int ret = expr(s, i); i++; // ')'を読み飛ばす return ret; } int number(string& s, int& i) { int n = s[i++] - '0'; while(isdigit(s[i])) n = n*10 + s[i++] - '0'; return n; } int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { string str; cin >> str; int j = 0; cout << expr(str, j) << endl; } return 0; } ```
#include <string> #include<cctype> #include<cstdio> using namespace std; typedef string::const_iterator State; class ParseError {}; int expression(State &begin); int number(State &begin){ int ret=0; while(isdigit(*begin)){ ret*=10; ret+=*begin-'0'; begin++; } return ret; } int factor(State &begin){ if(*begin=='('){ begin++; int ret = expression(begin); begin++; return ret; }else{ return number(begin); } } int term(State &begin){ int ret = factor(begin); for(;;){ if(*begin=='*'){ begin++; ret*=factor(begin); }else if(*begin=='/'){ begin++; ret/=factor(begin); }else{ break; } } return ret; } int expression(State &begin){ int ret=term(begin); for(;;){ if(*begin=='+'){ begin++; ret +=term(begin); }else if(*begin=='-'){ begin++; ret-=term(begin); }else{ break; } } return ret; } int main(){ int N; scanf("%d",&N); for(int i=0;i<N;i++){ char s[105]; scanf("%s",s); string S(s); State begin=S.begin(); int ans=expression(begin); printf("%d\n",ans); } return 0; }
### Prompt Develop a solution in CPP to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <string> #include<cctype> #include<cstdio> using namespace std; typedef string::const_iterator State; class ParseError {}; int expression(State &begin); int number(State &begin){ int ret=0; while(isdigit(*begin)){ ret*=10; ret+=*begin-'0'; begin++; } return ret; } int factor(State &begin){ if(*begin=='('){ begin++; int ret = expression(begin); begin++; return ret; }else{ return number(begin); } } int term(State &begin){ int ret = factor(begin); for(;;){ if(*begin=='*'){ begin++; ret*=factor(begin); }else if(*begin=='/'){ begin++; ret/=factor(begin); }else{ break; } } return ret; } int expression(State &begin){ int ret=term(begin); for(;;){ if(*begin=='+'){ begin++; ret +=term(begin); }else if(*begin=='-'){ begin++; ret-=term(begin); }else{ break; } } return ret; } int main(){ int N; scanf("%d",&N); for(int i=0;i<N;i++){ char s[105]; scanf("%s",s); string S(s); State begin=S.begin(); int ans=expression(begin); printf("%d\n",ans); } return 0; } ```
#include<bits/stdc++.h> using namespace std; using Int = long long; //BEGIN CUT HERE int expression(string,int&); int term(string,int&); int factor(string,int&); int number(string,int&); bool f; int expression(string s,int& p){ int res=term(s,p); while(p<(int)s.size()){ if(s[p]=='+'){ p++; res+=term(s,p); continue; } if(s[p]=='-'){ p++; res-=term(s,p); continue; } break; } return res; } int term(string s,int& p){ int res=factor(s,p); while(p<(int)s.size()){ if(s[p]=='*'){ p++; res*=factor(s,p); continue; } if(s[p]=='/'){ p++; int tmp=factor(s,p); if(tmp==0){ f=1; break; } res/=tmp; continue; } break; } return res; } int factor(string s,int& p){ int res; if(s[p]=='('){ p++; res=expression(s,p); p++; }else{ res=number(s,p); } return res; } int number(string s,int& p){ int res=0; while(p<(int)s.size()&&isdigit(s[p])) res=res*10+s[p++]-'0'; return res; } //END CUT HERE signed main(){ int n; cin>>n; while(n--){ string s; int p=0; cin>>s;s.pop_back(); cout<<expression(s,p)<<endl; } return 0; } /* verified on 2017/11/20 http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?lang=jp&id=0109 */
### Prompt Your challenge is to write a Cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<bits/stdc++.h> using namespace std; using Int = long long; //BEGIN CUT HERE int expression(string,int&); int term(string,int&); int factor(string,int&); int number(string,int&); bool f; int expression(string s,int& p){ int res=term(s,p); while(p<(int)s.size()){ if(s[p]=='+'){ p++; res+=term(s,p); continue; } if(s[p]=='-'){ p++; res-=term(s,p); continue; } break; } return res; } int term(string s,int& p){ int res=factor(s,p); while(p<(int)s.size()){ if(s[p]=='*'){ p++; res*=factor(s,p); continue; } if(s[p]=='/'){ p++; int tmp=factor(s,p); if(tmp==0){ f=1; break; } res/=tmp; continue; } break; } return res; } int factor(string s,int& p){ int res; if(s[p]=='('){ p++; res=expression(s,p); p++; }else{ res=number(s,p); } return res; } int number(string s,int& p){ int res=0; while(p<(int)s.size()&&isdigit(s[p])) res=res*10+s[p++]-'0'; return res; } //END CUT HERE signed main(){ int n; cin>>n; while(n--){ string s; int p=0; cin>>s;s.pop_back(); cout<<expression(s,p)<<endl; } return 0; } /* verified on 2017/11/20 http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?lang=jp&id=0109 */ ```
#include <iostream> #include <string> using namespace std; int p; string str; int Term(); int Factor(); int Elem(); int Digit(); int Term() { int a = Factor(); while (str[p] == '+' || str[p] == '-') { char c = str[p]; p++; // read [+-] int b = Factor(); if (c == '+') { a = a + b; } else { a = a - b; } } return a; } int Factor() { int a = Elem(); while (str[p] == '*' || str[p] == '/') { char c = str[p]; p++; // read [*/] int b = Elem(); if (c == '*') { a = a * b; } else { a = a / b; } } return a; } int Elem() { if (str[p] == '(') { p++; // read ( int a = Term(); p++; // read ) return a; } else { int a = 0; while (isdigit(str[p])) { int b = Digit(); a = 10 * a + b; } return a; } } int Digit() { int a = str[p] - '0'; p++; // read [0-9] return a; }; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> str; p = 0; cout << Term() << endl; } }
### Prompt Please provide a cpp coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> using namespace std; int p; string str; int Term(); int Factor(); int Elem(); int Digit(); int Term() { int a = Factor(); while (str[p] == '+' || str[p] == '-') { char c = str[p]; p++; // read [+-] int b = Factor(); if (c == '+') { a = a + b; } else { a = a - b; } } return a; } int Factor() { int a = Elem(); while (str[p] == '*' || str[p] == '/') { char c = str[p]; p++; // read [*/] int b = Elem(); if (c == '*') { a = a * b; } else { a = a / b; } } return a; } int Elem() { if (str[p] == '(') { p++; // read ( int a = Term(); p++; // read ) return a; } else { int a = 0; while (isdigit(str[p])) { int b = Digit(); a = 10 * a + b; } return a; } } int Digit() { int a = str[p] - '0'; p++; // read [0-9] return a; }; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> str; p = 0; cout << Term() << endl; } } ```
#include <iostream> #include <string> using namespace std; string str; int p; int exp(); int factor(); int term(); int factor() { int num=0; while('0' <= str[p] && str[p] <= '9') { num*=10; num += str[p] - '0'; p++; } // cout <<"one"<< num << endl; if(num != 0) return num; else if (str[p] == '('){ p++; num = exp(); } if(str[p] == ')'){ // cout <<"two"<< num << endl; p++; return num; } return 0; } int term(){ int val = factor(); while(str[p] == '*' || str[p] == '/') { if(str[p] == '*') { p++; val *= factor(); } else if(str[p] == '/'){ p++; val /= factor(); } } return val; } int exp() { int val = term(); while(str[p] == '+' || str[p] == '-') { if(str[p] == '+') { p++; val += term(); } else if(str[p] == '-'){ p++; val -= term(); } } return val; } int main() { int n; cin >> n; for(int i=0;i<n;i++) { p = 0; cin >> str; cout << exp() << endl; } return 0; }
### Prompt Please create a solution in cpp to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> using namespace std; string str; int p; int exp(); int factor(); int term(); int factor() { int num=0; while('0' <= str[p] && str[p] <= '9') { num*=10; num += str[p] - '0'; p++; } // cout <<"one"<< num << endl; if(num != 0) return num; else if (str[p] == '('){ p++; num = exp(); } if(str[p] == ')'){ // cout <<"two"<< num << endl; p++; return num; } return 0; } int term(){ int val = factor(); while(str[p] == '*' || str[p] == '/') { if(str[p] == '*') { p++; val *= factor(); } else if(str[p] == '/'){ p++; val /= factor(); } } return val; } int exp() { int val = term(); while(str[p] == '+' || str[p] == '-') { if(str[p] == '+') { p++; val += term(); } else if(str[p] == '-'){ p++; val -= term(); } } return val; } int main() { int n; cin >> n; for(int i=0;i<n;i++) { p = 0; cin >> str; cout << exp() << endl; } return 0; } ```
#include <iostream> #include <algorithm> #include <cassert> #include <cctype> #include <cstdio> #include <math.h> #include <map> #include <queue> #include <string> using namespace std; typedef long long ll; string S; size_t cur=0; int parse(); int digit(){ assert(isdigit(S[cur])); int n=S[cur]-'0'; cur++; return n; } int number(){ int n=digit(); while(cur<S.size()&&isdigit(S[cur])) n=n*10+digit(); return n; } int expression(); int factor(){ if(S[cur]!='(')return number(); cur++; int n=expression(); assert(S[cur]==')'); cur++; return n; } int term(){ int a=factor(); while(cur<S.size()&&(S[cur]=='*'||S[cur]=='/')){ char op=S[cur++]; int b=factor(); if(op=='*')a*=b; else a/=b; } return a; } int expression(){ int a=term(); while(cur<S.size()&&(S[cur]=='+'||S[cur]=='-')){ char op=S[cur++]; int b=term(); if(op=='+')a+=b; else a-=b; } return a; } int main() { int n; cin>>n; while(cin>>S){ cur=0; cout<<expression()<<endl; } }
### Prompt Generate a CPP solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <algorithm> #include <cassert> #include <cctype> #include <cstdio> #include <math.h> #include <map> #include <queue> #include <string> using namespace std; typedef long long ll; string S; size_t cur=0; int parse(); int digit(){ assert(isdigit(S[cur])); int n=S[cur]-'0'; cur++; return n; } int number(){ int n=digit(); while(cur<S.size()&&isdigit(S[cur])) n=n*10+digit(); return n; } int expression(); int factor(){ if(S[cur]!='(')return number(); cur++; int n=expression(); assert(S[cur]==')'); cur++; return n; } int term(){ int a=factor(); while(cur<S.size()&&(S[cur]=='*'||S[cur]=='/')){ char op=S[cur++]; int b=factor(); if(op=='*')a*=b; else a/=b; } return a; } int expression(){ int a=term(); while(cur<S.size()&&(S[cur]=='+'||S[cur]=='-')){ char op=S[cur++]; int b=term(); if(op=='+')a+=b; else a-=b; } return a; } int main() { int n; cin>>n; while(cin>>S){ cur=0; cout<<expression()<<endl; } } ```
#include<iostream> #include<string> #include<cassert> #include<cctype> #include<stdio.h> using namespace std; string S="4*(8+4+3)"; size_t cur=0; int expression(); //????????£?¨? //??°????????\??? int digit(){ assert(isdigit(S[cur])); int n=S[cur++]-'0'; return n; } //??°?????\??? int number(){ int n= digit(); while(cur<S.size() && isdigit(S[cur])) n=n*10+digit(); return n; } //()???????¨???? int factor(){ if(S[cur] !='(' ) return number(); else{ cur++; int n=expression(); assert(S[cur]==')'); cur++; return n; } } //*,/????????????????¨???? int term(){ int a=factor(); while(cur<S.size() && (S[cur]=='*' || S[cur]=='/')){ char op=S[cur++]; int b=factor(); if(op=='*') a *=b; else if(op=='/') a /=b; } return a; } //+,-????¨???? int expression(){ int sum=term(); while(S[cur]=='+' || S[cur]=='-'){ char op=S[cur++]; int b=term(); if(op=='+') sum+=b; else if(op=='-') sum -=b; } return sum; } int main(){ int N; cin >> N; for(int i=0;i<N;i++){ cur =0; cin >> S; S.resize(S.size()-1); //?????????=????????? cout<< expression() <<endl; } return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<string> #include<cassert> #include<cctype> #include<stdio.h> using namespace std; string S="4*(8+4+3)"; size_t cur=0; int expression(); //????????£?¨? //??°????????\??? int digit(){ assert(isdigit(S[cur])); int n=S[cur++]-'0'; return n; } //??°?????\??? int number(){ int n= digit(); while(cur<S.size() && isdigit(S[cur])) n=n*10+digit(); return n; } //()???????¨???? int factor(){ if(S[cur] !='(' ) return number(); else{ cur++; int n=expression(); assert(S[cur]==')'); cur++; return n; } } //*,/????????????????¨???? int term(){ int a=factor(); while(cur<S.size() && (S[cur]=='*' || S[cur]=='/')){ char op=S[cur++]; int b=factor(); if(op=='*') a *=b; else if(op=='/') a /=b; } return a; } //+,-????¨???? int expression(){ int sum=term(); while(S[cur]=='+' || S[cur]=='-'){ char op=S[cur++]; int b=term(); if(op=='+') sum+=b; else if(op=='-') sum -=b; } return sum; } int main(){ int N; cin >> N; for(int i=0;i<N;i++){ cur =0; cin >> S; S.resize(S.size()-1); //?????????=????????? cout<< expression() <<endl; } return 0; } ```
#include<iostream> #include<vector> #include<algorithm> #include<cassert> using namespace std; #define INF (1<<24) bool isNum(char ch){return ('0'<=ch&&ch<='9');} struct calcStr{ string s; int pos,len; void init(){ pos=0;len=s.size();} int head2Num(){ if(s[pos]=='('){pos++;return getAns();} bool f=false; if(s[pos]=='-'){f=true;pos++;} int res=0; while(pos<len){ if(isNum(s[pos])){ res*=10; res+=(s[pos]-'0'); pos++; }else break; } if(f)res*=-1; return res; } int getNum(){ int res=head2Num(),num; char ch; while(s[pos]=='*'||s[pos]=='/'){ ch=s[pos++]; num=head2Num(); if(ch=='*')res*=num; else if(ch=='/')res/=num; } return res; } int getAns(){ int res=getNum(),num; while(1){ if(s[pos]==')'){pos++;break;} if(s[pos]=='=')break; char ch=s[pos++]; num=getNum(); if(ch=='+')res+=num; else if(ch=='-')res-=num; else assert(0); } return res; } }; int main(){ int Tc;cin>>Tc; calcStr a; while(Tc--){ cin>>a.s; a.init(); cout<<a.getAns()<<endl; } return 0; }
### Prompt In CPP, your task is to solve the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<vector> #include<algorithm> #include<cassert> using namespace std; #define INF (1<<24) bool isNum(char ch){return ('0'<=ch&&ch<='9');} struct calcStr{ string s; int pos,len; void init(){ pos=0;len=s.size();} int head2Num(){ if(s[pos]=='('){pos++;return getAns();} bool f=false; if(s[pos]=='-'){f=true;pos++;} int res=0; while(pos<len){ if(isNum(s[pos])){ res*=10; res+=(s[pos]-'0'); pos++; }else break; } if(f)res*=-1; return res; } int getNum(){ int res=head2Num(),num; char ch; while(s[pos]=='*'||s[pos]=='/'){ ch=s[pos++]; num=head2Num(); if(ch=='*')res*=num; else if(ch=='/')res/=num; } return res; } int getAns(){ int res=getNum(),num; while(1){ if(s[pos]==')'){pos++;break;} if(s[pos]=='=')break; char ch=s[pos++]; num=getNum(); if(ch=='+')res+=num; else if(ch=='-')res-=num; else assert(0); } return res; } }; int main(){ int Tc;cin>>Tc; calcStr a; while(Tc--){ cin>>a.s; a.init(); cout<<a.getAns()<<endl; } return 0; } ```
#include <iostream> #include <vector> #include <queue> #include <string> #include <algorithm> #include <utility> #include <cstring> #include <cassert> using namespace std; #define REP(var, count) for(int var=0; var<count; var++) const char op[] = "()*/+-=N"; string line; int cur; char readchar() { return line[cur++]; } char peek() { return line[cur]; } int digit() { return readchar() - '0'; } int number() { int n = digit(); while ( peek() >= '0' && peek()<='9' ) { n = n*10 + digit(); } return n; } int expression(); int factor() { if ( peek() != '(' ) { return number(); } assert( readchar() == '(' ); int ret = expression(); assert( readchar() == ')' ); return ret; } int term() { int ret = factor(); while( peek() == '*' || peek() == '/' ) { char op = readchar(); int fac = factor(); if ( op == '*' ) { ret *= fac; } else { ret /= fac; } } return ret; } int expression() { int ret = term(); while( peek() == '+' || peek() == '-' ) { char op = readchar(); int ter = term(); if ( op == '+' ) { ret += ter; } else { ret -= ter; } } return ret; } int main(void) { int N; cin >> N; while(N--) { cin >> line; cur = 0; cout << expression() << endl; } }
### Prompt Your task is to create a cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <vector> #include <queue> #include <string> #include <algorithm> #include <utility> #include <cstring> #include <cassert> using namespace std; #define REP(var, count) for(int var=0; var<count; var++) const char op[] = "()*/+-=N"; string line; int cur; char readchar() { return line[cur++]; } char peek() { return line[cur]; } int digit() { return readchar() - '0'; } int number() { int n = digit(); while ( peek() >= '0' && peek()<='9' ) { n = n*10 + digit(); } return n; } int expression(); int factor() { if ( peek() != '(' ) { return number(); } assert( readchar() == '(' ); int ret = expression(); assert( readchar() == ')' ); return ret; } int term() { int ret = factor(); while( peek() == '*' || peek() == '/' ) { char op = readchar(); int fac = factor(); if ( op == '*' ) { ret *= fac; } else { ret /= fac; } } return ret; } int expression() { int ret = term(); while( peek() == '+' || peek() == '-' ) { char op = readchar(); int ter = term(); if ( op == '+' ) { ret += ter; } else { ret -= ter; } } return ret; } int main(void) { int N; cin >> N; while(N--) { cin >> line; cur = 0; cout << expression() << endl; } } ```
#include <bits/stdc++.h> using namespace std; typedef string::const_iterator State; int number(State &begin); int factor(State &begin); int term(State &begin); int expression(State &begin); int expression(State &begin) { int ret = term(begin); for (;;) { if (*begin == '+') { begin++; ret += term(begin); } else if (*begin == '-') { begin++; ret -= term(begin); } else { break; } } return ret; } int term(State &begin) { int ret = factor(begin); for (;;) { if (*begin == '*') { begin++; ret *= factor(begin); } else if (*begin == '/') { begin++; ret /= factor(begin); } else { break; } } return ret; } int factor(State &begin) { int ret = 0; if (*begin == '(') { begin++; ret = expression(begin); begin++; return ret; } else { ret = number(begin); } return ret; } int number(State &begin) { int ret = 0; while (isdigit(*begin)) { ret *= 10; ret += *begin - '0'; begin++; } return ret; } int main() { int N; cin >> N; cin.ignore(); for (int i = 0; i < N; i++) { string s; getline(cin, s); State begin = s.begin(); int ans = expression(begin); cout << ans << endl; } }
### Prompt Develop a solution in CPP to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef string::const_iterator State; int number(State &begin); int factor(State &begin); int term(State &begin); int expression(State &begin); int expression(State &begin) { int ret = term(begin); for (;;) { if (*begin == '+') { begin++; ret += term(begin); } else if (*begin == '-') { begin++; ret -= term(begin); } else { break; } } return ret; } int term(State &begin) { int ret = factor(begin); for (;;) { if (*begin == '*') { begin++; ret *= factor(begin); } else if (*begin == '/') { begin++; ret /= factor(begin); } else { break; } } return ret; } int factor(State &begin) { int ret = 0; if (*begin == '(') { begin++; ret = expression(begin); begin++; return ret; } else { ret = number(begin); } return ret; } int number(State &begin) { int ret = 0; while (isdigit(*begin)) { ret *= 10; ret += *begin - '0'; begin++; } return ret; } int main() { int N; cin >> N; cin.ignore(); for (int i = 0; i < N; i++) { string s; getline(cin, s); State begin = s.begin(); int ans = expression(begin); cout << ans << endl; } } ```
#include <string> #include <iostream> #include <cctype> using namespace std; int exp(const string& s, int& p); int term(const string& s, int& p); int fact(const string& s, int& p); int number(const string& s, int& p); int main() { int n; while (cin >> n) { for (int i = 0; i < n; ++i) { string s; cin >> s; s.erase(s.end()-1); int p = 0; cout << exp(s, p) << endl; } } return 0; } int exp(const string& s, int& p) { int ret = term(s, p); for ( ; ; ) { if (s[p] == '+') ret += term(s, ++p); else if (s[p] == '-') ret -= term(s, ++p); else break; } return ret; } int term(const string& s, int& p) { int ret = fact(s, p); for ( ; ; ) { if (s[p] == '*') ret *= fact(s, ++p); else if (s[p] == '/') ret /= fact(s, ++p); else break; } return ret; } int fact(const string& s, int& p) { int ret = 0; if (s[p] == '(') { ret = exp(s, ++p); ++p; } else { ret = number(s, p); } return ret; } int number(const string&s, int& p) { int ret = 0; while (isdigit(s[p])) { ret *= 10; ret += s[p] - '0'; ++p; } return ret; }
### Prompt Please formulate a CPP solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <string> #include <iostream> #include <cctype> using namespace std; int exp(const string& s, int& p); int term(const string& s, int& p); int fact(const string& s, int& p); int number(const string& s, int& p); int main() { int n; while (cin >> n) { for (int i = 0; i < n; ++i) { string s; cin >> s; s.erase(s.end()-1); int p = 0; cout << exp(s, p) << endl; } } return 0; } int exp(const string& s, int& p) { int ret = term(s, p); for ( ; ; ) { if (s[p] == '+') ret += term(s, ++p); else if (s[p] == '-') ret -= term(s, ++p); else break; } return ret; } int term(const string& s, int& p) { int ret = fact(s, p); for ( ; ; ) { if (s[p] == '*') ret *= fact(s, ++p); else if (s[p] == '/') ret /= fact(s, ++p); else break; } return ret; } int fact(const string& s, int& p) { int ret = 0; if (s[p] == '(') { ret = exp(s, ++p); ++p; } else { ret = number(s, p); } return ret; } int number(const string&s, int& p) { int ret = 0; while (isdigit(s[p])) { ret *= 10; ret += s[p] - '0'; ++p; } return ret; } ```
#include <cstdio> #include <iostream> #include <string> using namespace std; string str; int pos; int exp(void); int term(void); int factor(void); int main(){ int i,j,n,ans; cin >> n; for(i=0;i<n;i++){ cin >> str; str.erase(str.size()-1); pos = 0; ans = exp(); cout << ans << endl; str.clear(); } return 0; } int exp(void){ int x = term(); while(str[pos] == '+' || str[pos] == '-'){ char op = str[pos++]; if(op == '+') x += term(); else if(op == '-') x -= term(); } return x; } int term(void){ int x = factor(); while(str[pos] == '*' || str[pos] == '/'){ char op = str[pos++]; if(op == '*') x *= factor(); else if(op == '/') x /= factor(); } return x; } int factor(void){ int x=0,c; if(str[pos] == '('){ pos++; x = exp(); pos++; } else{ while(str[pos] >= '0' && str[pos] <= '9'){ x *= 10; x += str[pos++] - '0'; } } return x; }
### Prompt Please provide a Cpp coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <cstdio> #include <iostream> #include <string> using namespace std; string str; int pos; int exp(void); int term(void); int factor(void); int main(){ int i,j,n,ans; cin >> n; for(i=0;i<n;i++){ cin >> str; str.erase(str.size()-1); pos = 0; ans = exp(); cout << ans << endl; str.clear(); } return 0; } int exp(void){ int x = term(); while(str[pos] == '+' || str[pos] == '-'){ char op = str[pos++]; if(op == '+') x += term(); else if(op == '-') x -= term(); } return x; } int term(void){ int x = factor(); while(str[pos] == '*' || str[pos] == '/'){ char op = str[pos++]; if(op == '*') x *= factor(); else if(op == '/') x /= factor(); } return x; } int factor(void){ int x=0,c; if(str[pos] == '('){ pos++; x = exp(); pos++; } else{ while(str[pos] >= '0' && str[pos] <= '9'){ x *= 10; x += str[pos++] - '0'; } } return x; } ```
#include<stdio.h> #include<algorithm> #include<string> using namespace std; char str[200]; pair<int,int>ad(int a); pair<int,int>mul(int a); pair<int,int>fact(int a); pair<int,int>ad(int a){ pair<int,int> res=mul(a); while(str[res.second]=='+'||str[res.second]=='-'){ pair<int,int>v=mul(res.second+1); if(str[res.second]=='+')res.first+=v.first; else res.first-=v.first; res.second=v.second; } return res; } pair<int,int>mul(int a){ pair<int,int> res=fact(a); while(str[res.second]=='*'||str[res.second]=='/'){ pair<int,int>v=fact(res.second+1); if(str[res.second]=='*')res.first*=v.first; else res.first/=v.first; res.second=v.second; } return res; } pair<int,int>fact(int a){ if(str[a]=='('){ pair<int,int> res=ad(a+1); res.second++; return res; }else{ int val=0; while(isdigit(str[a])){ val=val*10+str[a++]-'0'; } return make_pair(val,a); } } int main(){ int a; scanf("%d",&a); while(a--){ scanf("%s",str); printf("%d\n",ad(0).first); } }
### Prompt Your task is to create a Cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<stdio.h> #include<algorithm> #include<string> using namespace std; char str[200]; pair<int,int>ad(int a); pair<int,int>mul(int a); pair<int,int>fact(int a); pair<int,int>ad(int a){ pair<int,int> res=mul(a); while(str[res.second]=='+'||str[res.second]=='-'){ pair<int,int>v=mul(res.second+1); if(str[res.second]=='+')res.first+=v.first; else res.first-=v.first; res.second=v.second; } return res; } pair<int,int>mul(int a){ pair<int,int> res=fact(a); while(str[res.second]=='*'||str[res.second]=='/'){ pair<int,int>v=fact(res.second+1); if(str[res.second]=='*')res.first*=v.first; else res.first/=v.first; res.second=v.second; } return res; } pair<int,int>fact(int a){ if(str[a]=='('){ pair<int,int> res=ad(a+1); res.second++; return res; }else{ int val=0; while(isdigit(str[a])){ val=val*10+str[a++]-'0'; } return make_pair(val,a); } } int main(){ int a; scanf("%d",&a); while(a--){ scanf("%s",str); printf("%d\n",ad(0).first); } } ```
#include <iostream> #include <cassert> #include <cctype> using namespace std; string S; size_t cur; int parse(); int expression(); int digit(){ assert(isdigit(S[cur])); int n = S[cur] - '0'; cur++; return n; } int number(){ int n = digit(); while(cur < S.size() && isdigit(S[cur])){ n = n * 10 + digit(); } return n; } int factor(){ if(S[cur] != '(') return number(); cur++; int n = expression(); assert(S[cur] == ')'); cur++; return n; } int term(){ int a = factor(); while(cur < S.size() && (S[cur] == '*' || S[cur] == '/')){ char op = S[cur++]; int b = factor(); if(op == '*') a *= b; else { assert(b != 0); a /= b; }; } return a; } int expression(){ int sum = term(); while(S[cur] == '+' || S[cur] == '-'){ char op = S[cur]; cur++; int b = term(); if (op == '+') sum += b; else sum -= b; } return sum; } int parse() { return expression(); } int main(){ int n; cin >> n; for(int i = 0; i < n; i++){ cin >> S; S.resize(S.size()-1); cur = 0; cout << expression() << endl; } }
### Prompt Develop a solution in cpp to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <cassert> #include <cctype> using namespace std; string S; size_t cur; int parse(); int expression(); int digit(){ assert(isdigit(S[cur])); int n = S[cur] - '0'; cur++; return n; } int number(){ int n = digit(); while(cur < S.size() && isdigit(S[cur])){ n = n * 10 + digit(); } return n; } int factor(){ if(S[cur] != '(') return number(); cur++; int n = expression(); assert(S[cur] == ')'); cur++; return n; } int term(){ int a = factor(); while(cur < S.size() && (S[cur] == '*' || S[cur] == '/')){ char op = S[cur++]; int b = factor(); if(op == '*') a *= b; else { assert(b != 0); a /= b; }; } return a; } int expression(){ int sum = term(); while(S[cur] == '+' || S[cur] == '-'){ char op = S[cur]; cur++; int b = term(); if (op == '+') sum += b; else sum -= b; } return sum; } int parse() { return expression(); } int main(){ int n; cin >> n; for(int i = 0; i < n; i++){ cin >> S; S.resize(S.size()-1); cur = 0; cout << expression() << endl; } } ```
#include<iostream> #include<string> #include<ctype.h> std::string s; std::string::iterator it; int term(); int fact(); // ?¨???? int expr() { int p = term(); // + or - while( *it == '+' || *it == '-' ){ if( *it == '+' ){ it++; int q = term(); p += q; } else{ it++; int q = term(); p -= q; } } return p; } // ???????¨???? int term() { int p = fact(); while( *it == '*' || *it == '/' ){ if( *it == '*' ){ it++; int q = fact(); p *= q; } else{ it++; int q = fact(); p /= q; } } return p; } // ??¬??§??? or ??°??? int fact() { if( *it == '(' ){ it++; int p = expr(); it++; return p; } else{ int p = 0; while( isdigit( *it ) ){ p *= 10; p += *it - '0'; it++; } return p; } } int main() { int n; std::cin >> n; while( n-- ){ std::cin >> s; s[s.size()-1] = '\0'; it = s.begin(); std::cout << expr() << std::endl; } return 0; }
### Prompt Develop a solution in Cpp to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<string> #include<ctype.h> std::string s; std::string::iterator it; int term(); int fact(); // ?¨???? int expr() { int p = term(); // + or - while( *it == '+' || *it == '-' ){ if( *it == '+' ){ it++; int q = term(); p += q; } else{ it++; int q = term(); p -= q; } } return p; } // ???????¨???? int term() { int p = fact(); while( *it == '*' || *it == '/' ){ if( *it == '*' ){ it++; int q = fact(); p *= q; } else{ it++; int q = fact(); p /= q; } } return p; } // ??¬??§??? or ??°??? int fact() { if( *it == '(' ){ it++; int p = expr(); it++; return p; } else{ int p = 0; while( isdigit( *it ) ){ p *= 10; p += *it - '0'; it++; } return p; } } int main() { int n; std::cin >> n; while( n-- ){ std::cin >> s; s[s.size()-1] = '\0'; it = s.begin(); std::cout << expr() << std::endl; } return 0; } ```
#include<iostream> #include<iomanip> #include<math.h> #include<algorithm> #include<string> #include<vector> #include<queue> #include<stack> #include<set> #include<map> #define REP(i, N) for(ll i = 0; i < N; ++i) #define FOR(i, a, b) for(ll i = a; i < b; ++i) #define ALL(a) (a).begin(),(a).end() #define pb push_back #define INF (long long)1000000000 #define MOD 1000000007 using namespace std; typedef long long ll; typedef pair<ll, ll> P; int dh[4] = {1, 0, -1, 0}; int dw[4] = {0, 1, 0, -1}; int roc = 0; string s; int insu(); int kou(); int shiki(); int insu() { if(s[roc] >= '0' && s[roc] <= '9') { int j = roc; while(roc < s.size() && s[roc] >= '0' && s[roc] <= '9') ++roc; return stoi(s.substr(j, roc - j)); } else { ++roc; int res = shiki(); ++roc; return res; } } int kou() { int res = insu(); while (s[roc] == '*' || s[roc] == '/') { if(s[roc] == '*') { ++roc; res *= insu(); } else { ++roc; res /= insu(); } } return res; } int shiki() { int res = kou(); while (s[roc] == '+' || s[roc] == '-') { if(s[roc] == '+') { ++roc; res += kou(); } else { ++roc; res -= kou(); } } return res; } int main(void) { int n; cin>>n; REP(roop, n) { roc = 0; cin>>s; s.pop_back(); cout<<shiki()<<endl; } }
### Prompt Your task is to create a cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<iomanip> #include<math.h> #include<algorithm> #include<string> #include<vector> #include<queue> #include<stack> #include<set> #include<map> #define REP(i, N) for(ll i = 0; i < N; ++i) #define FOR(i, a, b) for(ll i = a; i < b; ++i) #define ALL(a) (a).begin(),(a).end() #define pb push_back #define INF (long long)1000000000 #define MOD 1000000007 using namespace std; typedef long long ll; typedef pair<ll, ll> P; int dh[4] = {1, 0, -1, 0}; int dw[4] = {0, 1, 0, -1}; int roc = 0; string s; int insu(); int kou(); int shiki(); int insu() { if(s[roc] >= '0' && s[roc] <= '9') { int j = roc; while(roc < s.size() && s[roc] >= '0' && s[roc] <= '9') ++roc; return stoi(s.substr(j, roc - j)); } else { ++roc; int res = shiki(); ++roc; return res; } } int kou() { int res = insu(); while (s[roc] == '*' || s[roc] == '/') { if(s[roc] == '*') { ++roc; res *= insu(); } else { ++roc; res /= insu(); } } return res; } int shiki() { int res = kou(); while (s[roc] == '+' || s[roc] == '-') { if(s[roc] == '+') { ++roc; res += kou(); } else { ++roc; res -= kou(); } } return res; } int main(void) { int n; cin>>n; REP(roop, n) { roc = 0; cin>>s; s.pop_back(); cout<<shiki()<<endl; } } ```
#include <iostream> #include <cstdio> #include <cctype> #include <cassert> using namespace std; string S; size_t cur = 0; bool isdigit(char a){ if(a =='0' or a=='1' or a=='2' or a=='3' or a=='4' or a=='5' or a=='6' or a=='7' or a=='8' or a=='9'){ return true; } else return false; } int digit(){ int n = S[cur] - '0'; cur = cur + 1; return n; } int number(){ int n = digit(); while(cur < S.size() && isdigit(S[cur])) n = n*10 + digit(); return n; } int factor(); int term(){ int a = factor(); while(cur < S.size() && (S[cur] == '*'|| S[cur] == '/')){ char op = S[cur]; cur +=1; int b = factor(); if(op == '*') a *= b; else a /= b; } return a; } int expression(){ int a = term(); while(S[cur] == '+'|| S[cur] == '-'){ char op = S[cur]; cur += 1; int b = term(); if (op == '+') a += b; else a -= b; } return a; } int factor(){ if (S[cur] !='(') return number(); cur += 1; int n = expression(); assert(S[cur] == ')'); cur += 1; return n; } int main() { int N; cin >> N; for(int i=0; i<N; ++i){ cur = 0; cin >> S; S.resize(S.size()-1); cout << expression() << endl; } return 0; }
### Prompt Create a solution in Cpp for the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <cstdio> #include <cctype> #include <cassert> using namespace std; string S; size_t cur = 0; bool isdigit(char a){ if(a =='0' or a=='1' or a=='2' or a=='3' or a=='4' or a=='5' or a=='6' or a=='7' or a=='8' or a=='9'){ return true; } else return false; } int digit(){ int n = S[cur] - '0'; cur = cur + 1; return n; } int number(){ int n = digit(); while(cur < S.size() && isdigit(S[cur])) n = n*10 + digit(); return n; } int factor(); int term(){ int a = factor(); while(cur < S.size() && (S[cur] == '*'|| S[cur] == '/')){ char op = S[cur]; cur +=1; int b = factor(); if(op == '*') a *= b; else a /= b; } return a; } int expression(){ int a = term(); while(S[cur] == '+'|| S[cur] == '-'){ char op = S[cur]; cur += 1; int b = term(); if (op == '+') a += b; else a -= b; } return a; } int factor(){ if (S[cur] !='(') return number(); cur += 1; int n = expression(); assert(S[cur] == ')'); cur += 1; return n; } int main() { int N; cin >> N; for(int i=0; i<N; ++i){ cur = 0; cin >> S; S.resize(S.size()-1); cout << expression() << endl; } return 0; } ```
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define REP(i,n) FOR(i,0,n) int expr(string& s, int& i); int term(string& s, int& i); int factor(string& s, int& i); int number(string& s, int& i); int expr(string& s, int& i) { int val = term(s, i); while (s[i] == '+' || s[i] == '-') { char op = s[i++]; int val2 = term(s, i); if (op == '+') val += val2; else val -= val2; } return val; } int term(string& s, int& i) { int val = factor(s, i); while (s[i] == '*' || s[i] == '/') { char op = s[i++]; int val2 = factor(s, i); if (op == '*') val *= val2; else val /= val2; } return val; } int factor(string& s, int& i) { if (isdigit(s[i])) return number(s, i); i++; int res = expr(s, i); i++; return res; } int number(string& s, int& i) { int num = s[i++] - '0'; while (isdigit(s[i])) num = num*10 + s[i++] - '0'; return num; } int main() { int n; cin >> n; while (n--) { string str; cin >> str; str.erase(str.end() - 1); int i = 0; cout << expr(str, i) << endl; } return 0; }
### Prompt Your task is to create a cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define REP(i,n) FOR(i,0,n) int expr(string& s, int& i); int term(string& s, int& i); int factor(string& s, int& i); int number(string& s, int& i); int expr(string& s, int& i) { int val = term(s, i); while (s[i] == '+' || s[i] == '-') { char op = s[i++]; int val2 = term(s, i); if (op == '+') val += val2; else val -= val2; } return val; } int term(string& s, int& i) { int val = factor(s, i); while (s[i] == '*' || s[i] == '/') { char op = s[i++]; int val2 = factor(s, i); if (op == '*') val *= val2; else val /= val2; } return val; } int factor(string& s, int& i) { if (isdigit(s[i])) return number(s, i); i++; int res = expr(s, i); i++; return res; } int number(string& s, int& i) { int num = s[i++] - '0'; while (isdigit(s[i])) num = num*10 + s[i++] - '0'; return num; } int main() { int n; cin >> n; while (n--) { string str; cin >> str; str.erase(str.end() - 1); int i = 0; cout << expr(str, i) << endl; } return 0; } ```
#include<iostream> #include<string> #include<map> using namespace std; #define ans pair<int, int> string s; ans equation(int p); ans factor(int p); ans term(int p); int main(){ int n; cin >>n; while(n--){ cin >>s; ans r = equation(0); cout <<r.first<<endl; } return 0; } ans equation(int p){ ans r = factor(p); while(s[r.second] == '+' || s[r.second] == '-'){ ans r_dash = factor(r.second+1); if(s[r.second] == '+'){r.first += r_dash.first;} if(s[r.second] == '-'){r.first -= r_dash.first;} r.second = r_dash.second; } return r; } ans factor(int p){ ans r = term(p); while(s[r.second] == '*' || s[r.second] == '/'){ ans r_dash = term(r.second+1); if(s[r.second] == '*'){r.first *= r_dash.first;} if(s[r.second] == '/'){r.first /= r_dash.first;} r.second = r_dash.second; } return r; } ans term(int p){ if(s[p] == '('){ ans r = equation(p+1); r.second++; return r; } else{ int v = 0; while(isdigit(s[p])){ v = v*10+s[p++]-'0'; } return ans(v,p); } }
### Prompt Generate a cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<string> #include<map> using namespace std; #define ans pair<int, int> string s; ans equation(int p); ans factor(int p); ans term(int p); int main(){ int n; cin >>n; while(n--){ cin >>s; ans r = equation(0); cout <<r.first<<endl; } return 0; } ans equation(int p){ ans r = factor(p); while(s[r.second] == '+' || s[r.second] == '-'){ ans r_dash = factor(r.second+1); if(s[r.second] == '+'){r.first += r_dash.first;} if(s[r.second] == '-'){r.first -= r_dash.first;} r.second = r_dash.second; } return r; } ans factor(int p){ ans r = term(p); while(s[r.second] == '*' || s[r.second] == '/'){ ans r_dash = term(r.second+1); if(s[r.second] == '*'){r.first *= r_dash.first;} if(s[r.second] == '/'){r.first /= r_dash.first;} r.second = r_dash.second; } return r; } ans term(int p){ if(s[p] == '('){ ans r = equation(p+1); r.second++; return r; } else{ int v = 0; while(isdigit(s[p])){ v = v*10+s[p++]-'0'; } return ans(v,p); } } ```
#include<iostream> #include<string> #include<cassert> #include<cctype> using namespace std; string s; int cur=0; char readchar() { assert(cur<s.size()); char ret=s[cur]; cur+=1; return ret; } char peek() { assert(cur<s.size()); return s[cur]; } int digit() { assert(isdigit(peek())); int n = readchar() - '0'; return n; } int number() { int n=digit(); while (cur < s.size() && isdigit(peek())) n=n*10+digit(); return n; } int expression(); int factor() { if(peek()!='(') return number(); cur+=1; int n=expression(); assert(peek()==')'); cur+=1; return n; } int term() { int a=factor(); while((cur<s.size()) && (peek()=='*'||peek()=='/')) { char op=readchar(); int b=factor(); if(op =='*') a *=b; else a /=b; } return a; } int expression() { int a=term(); while(cur<s.size()&&(peek()=='+'||peek()=='-')) { char op=readchar(); int b=term(); if(op=='+') a +=b; else a -=b; } return a; } int parse() { return expression(); } int main() { int n,a; cin >> n; for(int i=0;i<n;i++) { cin >> s; cur=0; a=parse(); cout << a << endl; } }
### Prompt Construct a cpp code solution to the problem outlined: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<string> #include<cassert> #include<cctype> using namespace std; string s; int cur=0; char readchar() { assert(cur<s.size()); char ret=s[cur]; cur+=1; return ret; } char peek() { assert(cur<s.size()); return s[cur]; } int digit() { assert(isdigit(peek())); int n = readchar() - '0'; return n; } int number() { int n=digit(); while (cur < s.size() && isdigit(peek())) n=n*10+digit(); return n; } int expression(); int factor() { if(peek()!='(') return number(); cur+=1; int n=expression(); assert(peek()==')'); cur+=1; return n; } int term() { int a=factor(); while((cur<s.size()) && (peek()=='*'||peek()=='/')) { char op=readchar(); int b=factor(); if(op =='*') a *=b; else a /=b; } return a; } int expression() { int a=term(); while(cur<s.size()&&(peek()=='+'||peek()=='-')) { char op=readchar(); int b=term(); if(op=='+') a +=b; else a -=b; } return a; } int parse() { return expression(); } int main() { int n,a; cin >> n; for(int i=0;i<n;i++) { cin >> s; cur=0; a=parse(); cout << a << endl; } } ```
#include <cctype> #include <iostream> #include <string> typedef std::string::const_iterator State; using namespace std; int number(State &begin) { int ret = 0; while (isdigit(*begin)) { ret *= 10; ret += *begin - '0'; begin++; } return ret; } int factor(State &begin); int term(State &begin) { int ret = factor(begin); for (;;) { if (*begin == '*') { begin++; ret *= factor(begin); } else if (*begin == '/') { begin++; ret /= factor(begin); } else { break; } } return ret; } int expression(State &begin) { int ret = term(begin); for (;;) { if (*begin == '+') { begin++; ret += term(begin); } else if (*begin == '-') { begin++; ret -= term(begin); } else { break; } } return ret; } int factor(State &begin) { if (*begin == '(') { begin++; int ret = expression(begin); begin++; return ret; } else { return number(begin); } } int main() { int n; cin >> n; while (n--) { string s; cin >> s; State begin = s.begin(); cout << expression(begin) << endl; } return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <cctype> #include <iostream> #include <string> typedef std::string::const_iterator State; using namespace std; int number(State &begin) { int ret = 0; while (isdigit(*begin)) { ret *= 10; ret += *begin - '0'; begin++; } return ret; } int factor(State &begin); int term(State &begin) { int ret = factor(begin); for (;;) { if (*begin == '*') { begin++; ret *= factor(begin); } else if (*begin == '/') { begin++; ret /= factor(begin); } else { break; } } return ret; } int expression(State &begin) { int ret = term(begin); for (;;) { if (*begin == '+') { begin++; ret += term(begin); } else if (*begin == '-') { begin++; ret -= term(begin); } else { break; } } return ret; } int factor(State &begin) { if (*begin == '(') { begin++; int ret = expression(begin); begin++; return ret; } else { return number(begin); } } int main() { int n; cin >> n; while (n--) { string s; cin >> s; State begin = s.begin(); cout << expression(begin) << endl; } return 0; } ```
#include <bits/stdc++.h> using namespace std; class Calc{ public: string s; string::iterator it; Calc(string s) : s(s) { it = s.begin(); } int fact(){ int res = 0; if(*it == '('){ ++it; res = exp(); ++it; }else{ while(isdigit(*it)){ res *= 10; res += (*it-'0'); ++it; } } return res; } int term(){ int res = fact(); while(*it == '*' || *it == '/'){ if(*it == '*'){ ++it; res *= fact(); }else{ ++it; res /= fact(); } } return res; } int exp(){ int res = term(); while(*it == '+' || *it == '-'){ if(*it == '+'){ ++it; res += term(); }else{ ++it; res -= term(); } } return res; } }; int main(){ int N; cin >> N; while(N--){ string s; cin >> s; s.resize(s.size()-1); Calc calc(s); cout << calc.exp() << endl; } return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <bits/stdc++.h> using namespace std; class Calc{ public: string s; string::iterator it; Calc(string s) : s(s) { it = s.begin(); } int fact(){ int res = 0; if(*it == '('){ ++it; res = exp(); ++it; }else{ while(isdigit(*it)){ res *= 10; res += (*it-'0'); ++it; } } return res; } int term(){ int res = fact(); while(*it == '*' || *it == '/'){ if(*it == '*'){ ++it; res *= fact(); }else{ ++it; res /= fact(); } } return res; } int exp(){ int res = term(); while(*it == '+' || *it == '-'){ if(*it == '+'){ ++it; res += term(); }else{ ++it; res -= term(); } } return res; } }; int main(){ int N; cin >> N; while(N--){ string s; cin >> s; s.resize(s.size()-1); Calc calc(s); cout << calc.exp() << endl; } return 0; } ```
#include<string> #include<cctype> #include<stdio.h> using namespace std; int ex(char **b); int te(char **b); int fu(char **b); int num(char **b); int main(){ int n; char s[1000]; scanf("%d\n",&n); while(n--){ scanf("%s",s); char *p = s; printf("%d\n",ex(&p)); } } //和差 int ex(char **b){ int r=te(b); for(;;){ if(**b=='+')r+=te(&(++*b)); else if(**b=='-')r-=te(&(++*b)); else break; } return r; } //乗除 int te(char **b){ int r=fu(b); for(;;){ if(**b=='*')r*=fu(&(++*b)); else if(**b=='/')r/=fu(&(++*b)); else break; } return r; } //数字 int num(char **b){ int r=0,cnt=0; while(isdigit(**b)){ r*=10; r+=**b-'0'; ++*b; cnt++; } return r; } //括弧 int fu(char **b){ if(**b=='('){ int r=ex(&(++*b)); ++*b; return r; } else return num(b); }
### Prompt In CPP, your task is to solve the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<string> #include<cctype> #include<stdio.h> using namespace std; int ex(char **b); int te(char **b); int fu(char **b); int num(char **b); int main(){ int n; char s[1000]; scanf("%d\n",&n); while(n--){ scanf("%s",s); char *p = s; printf("%d\n",ex(&p)); } } //和差 int ex(char **b){ int r=te(b); for(;;){ if(**b=='+')r+=te(&(++*b)); else if(**b=='-')r-=te(&(++*b)); else break; } return r; } //乗除 int te(char **b){ int r=fu(b); for(;;){ if(**b=='*')r*=fu(&(++*b)); else if(**b=='/')r/=fu(&(++*b)); else break; } return r; } //数字 int num(char **b){ int r=0,cnt=0; while(isdigit(**b)){ r*=10; r+=**b-'0'; ++*b; cnt++; } return r; } //括弧 int fu(char **b){ if(**b=='('){ int r=ex(&(++*b)); ++*b; return r; } else return num(b); } ```
//????????? //??????00-440415D???Smart_Calculator.cpp #include <iostream> #include <string> #include <cassert> #include <cctype> #include <stdio.h> using namespace std; string S = "1+2*(3+4)"; size_t cur = 0; int expression(); int digit(){ assert(isdigit(S[cur])); int n = S[cur++]-'0'; return n; } int number(){ int n = digit(); while(cur<S.size() && isdigit(S[cur])){ n = n*10 + digit(); } return n; } int factor(){ if(S[cur] != '('){ return number(); }else{ cur++; int n = expression(); assert(S[cur]==')'); cur++; return n; } } //?????????????????????????????? int term(){ int a = factor(); while(cur < S.size() && (S[cur] == '*' || S[cur] == '/')){ char op = S[cur++]; int b = factor(); if(op == '*'){ a *= b; }else if(op == '/'){ a /= b; } } return a; } int expression(){ int sum = term(); while(S[cur] == '+' || S[cur] == '-'){ char op = S[cur++]; int b = term(); if(op == '+'){ sum += b; }else if(op == '-'){ sum -= b; } } return sum; } int main(){ int N; cin >> N; for(int i=0; i<N; i++){ cur = 0; cin >> S; S.resize(S.size()-1); cout << expression() << endl; } return 0; }
### Prompt Construct a Cpp code solution to the problem outlined: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp //????????? //??????00-440415D???Smart_Calculator.cpp #include <iostream> #include <string> #include <cassert> #include <cctype> #include <stdio.h> using namespace std; string S = "1+2*(3+4)"; size_t cur = 0; int expression(); int digit(){ assert(isdigit(S[cur])); int n = S[cur++]-'0'; return n; } int number(){ int n = digit(); while(cur<S.size() && isdigit(S[cur])){ n = n*10 + digit(); } return n; } int factor(){ if(S[cur] != '('){ return number(); }else{ cur++; int n = expression(); assert(S[cur]==')'); cur++; return n; } } //?????????????????????????????? int term(){ int a = factor(); while(cur < S.size() && (S[cur] == '*' || S[cur] == '/')){ char op = S[cur++]; int b = factor(); if(op == '*'){ a *= b; }else if(op == '/'){ a /= b; } } return a; } int expression(){ int sum = term(); while(S[cur] == '+' || S[cur] == '-'){ char op = S[cur++]; int b = term(); if(op == '+'){ sum += b; }else if(op == '-'){ sum -= b; } } return sum; } int main(){ int N; cin >> N; for(int i=0; i<N; i++){ cur = 0; cin >> S; S.resize(S.size()-1); cout << expression() << endl; } return 0; } ```
#include <iostream> #include <cassert> #include <cctype> using namespace std; string S; int cur; char readchar() { assert(cur<S.size()); char ret=S[cur]; cur++; return ret; } char peek() { assert(cur<S.size()); return S[cur]; } int digit() { assert(isdigit(peek())); int n=readchar()-'0'; return n; } int number() { int n=digit(); while(cur < S.size() && isdigit(peek())) { n=n*10+digit(); } return n; } //----------------- int factor(); int term() { int a=factor(); while(cur<S.size()&&(peek()=='*'||peek()=='/')) { char op=readchar(); int b=factor(); if(op=='*') a*=b; else a/=b; } return a; } int expression() { int a=term(); while(cur<S.size()&&(peek()=='+'||peek()=='-')) { char op=readchar(); int b=term(); if(op=='+')a+=b; else a-=b; } return a; } int factor() { if(peek()!='(')return number(); cur+=1; int n=expression(); assert(peek()==')'); cur+=1; return n; } int main() { int n; cin>>n; for(int i=0;i<n;i++) { cur=0; cin>>S; cout<<expression()<<endl; S.erase(S.begin(),S.end()); } return 0; }
### Prompt Construct a CPP code solution to the problem outlined: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <cassert> #include <cctype> using namespace std; string S; int cur; char readchar() { assert(cur<S.size()); char ret=S[cur]; cur++; return ret; } char peek() { assert(cur<S.size()); return S[cur]; } int digit() { assert(isdigit(peek())); int n=readchar()-'0'; return n; } int number() { int n=digit(); while(cur < S.size() && isdigit(peek())) { n=n*10+digit(); } return n; } //----------------- int factor(); int term() { int a=factor(); while(cur<S.size()&&(peek()=='*'||peek()=='/')) { char op=readchar(); int b=factor(); if(op=='*') a*=b; else a/=b; } return a; } int expression() { int a=term(); while(cur<S.size()&&(peek()=='+'||peek()=='-')) { char op=readchar(); int b=term(); if(op=='+')a+=b; else a-=b; } return a; } int factor() { if(peek()!='(')return number(); cur+=1; int n=expression(); assert(peek()==')'); cur+=1; return n; } int main() { int n; cin>>n; for(int i=0;i<n;i++) { cur=0; cin>>S; cout<<expression()<<endl; S.erase(S.begin(),S.end()); } return 0; } ```
#include <iostream> #include <string> #include <cctype> #include <cassert> using namespace std; string S; size_t cur = 0; int N; int parse(); char readchar(){ assert(cur < S.size()); return S[cur++]; } char peek(){ //assert(cur < S.size()); return S[cur]; } int digit(){ assert(isdigit(peek())); int n = readchar() - '0'; return n; } int number(){ int n = digit(); while (cur < S.size() && isdigit(peek())) { n = n*10 + digit(); } return n; } int expression(); int factor(){ if (peek() != '(') return number(); cur += 1; int n = expression(); assert(peek() == ')'); cur += 1; return n; } int term() { int a = factor(); while (cur < S.size() && (peek() == '*' || peek() == '/')){ char op = readchar(); int b = factor(); if (op == '*') a *= b; else a /= b; } return a; } int expression(){ int a = term(); while (cur < S.size() && (peek() == '+' || peek() == '-')){ char op = readchar(); int b = term(); if (op == '+') a += b; else a -= b; } return a; } int parse() { return expression(); } int main(){ cin >> N; for(int i = 0; i < N; i++){ cin >> S; cur = 0; int a = parse(); cout << a << endl; } }
### Prompt Your task is to create a Cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> #include <cctype> #include <cassert> using namespace std; string S; size_t cur = 0; int N; int parse(); char readchar(){ assert(cur < S.size()); return S[cur++]; } char peek(){ //assert(cur < S.size()); return S[cur]; } int digit(){ assert(isdigit(peek())); int n = readchar() - '0'; return n; } int number(){ int n = digit(); while (cur < S.size() && isdigit(peek())) { n = n*10 + digit(); } return n; } int expression(); int factor(){ if (peek() != '(') return number(); cur += 1; int n = expression(); assert(peek() == ')'); cur += 1; return n; } int term() { int a = factor(); while (cur < S.size() && (peek() == '*' || peek() == '/')){ char op = readchar(); int b = factor(); if (op == '*') a *= b; else a /= b; } return a; } int expression(){ int a = term(); while (cur < S.size() && (peek() == '+' || peek() == '-')){ char op = readchar(); int b = term(); if (op == '+') a += b; else a -= b; } return a; } int parse() { return expression(); } int main(){ cin >> N; for(int i = 0; i < N; i++){ cin >> S; cur = 0; int a = parse(); cout << a << endl; } } ```
#include <iostream> #include <string> #include <cstdio> #include <cctype> using namespace std; char s[200]; char *p; int E(); int F(); int T(); int N(); #ifdef DEBUG #define dump(s) cerr << s << endl #else #define dump(...) #endif int E(){ int res = F(); while(*p=='+' || *p=='-'){ if(*p=='+') p++, res += F(); else if(*p=='-') p++, res -= F(); } return res; } int F(){ int res = T(); while(*p=='*' || *p=='/'){ if(*p=='*') p++, res *= T(); else if(*p=='/') p++, res /= T(); } dump(res); return res; } int T(){ int res; if(*p=='(') p++, res = E(), p++; else res = N(); return res; } int N(){ int res = 0; while(isdigit(*p)){ res = res*10 + *p - '0'; p++; } return res; } int main(){ int n; cin >> n; for(int i=0;i<n;i++){ cin >> s; p = s; cout << E() << endl; } }
### Prompt Construct a Cpp code solution to the problem outlined: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> #include <cstdio> #include <cctype> using namespace std; char s[200]; char *p; int E(); int F(); int T(); int N(); #ifdef DEBUG #define dump(s) cerr << s << endl #else #define dump(...) #endif int E(){ int res = F(); while(*p=='+' || *p=='-'){ if(*p=='+') p++, res += F(); else if(*p=='-') p++, res -= F(); } return res; } int F(){ int res = T(); while(*p=='*' || *p=='/'){ if(*p=='*') p++, res *= T(); else if(*p=='/') p++, res /= T(); } dump(res); return res; } int T(){ int res; if(*p=='(') p++, res = E(), p++; else res = N(); return res; } int N(){ int res = 0; while(isdigit(*p)){ res = res*10 + *p - '0'; p++; } return res; } int main(){ int n; cin >> n; for(int i=0;i<n;i++){ cin >> s; p = s; cout << E() << endl; } } ```
#include <bits/stdc++.h> using namespace std; typedef int Int; typedef string::const_iterator Iter; Int eval(const string&); Int expr(Iter&); Int term(Iter&); Int factor(Iter&); Int number(Iter&); Int eval(const string &s){ Iter it = s.begin(); return expr(it); } Int expr(Iter &it){ Int res = term(it); while (true){ if (*it == '+'){ ++it; res += term(it); } else if (*it == '-'){ ++it; res -= term(it); } else return res; } } Int term(Iter &it){ Int res = factor(it); while (true){ if (*it == '*'){ ++it; res *= factor(it); } else if (*it == '/'){ ++it; res /= factor(it); } else return res; } } Int factor(Iter &it){ if (*it == '('){ ++it; Int res = expr(it); ++it; return res; } else return number(it); } Int number(Iter &it){ Int res = 0; while (isdigit(*it)){ res = res * 10 + (*it - '0'); ++it; } return res; } int main() { int n; cin >> n; cin.ignore(); for (int i = 0; i < n; i++){ string s; getline(cin, s); cout << eval(s) << endl; } }
### Prompt Generate a CPP solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef int Int; typedef string::const_iterator Iter; Int eval(const string&); Int expr(Iter&); Int term(Iter&); Int factor(Iter&); Int number(Iter&); Int eval(const string &s){ Iter it = s.begin(); return expr(it); } Int expr(Iter &it){ Int res = term(it); while (true){ if (*it == '+'){ ++it; res += term(it); } else if (*it == '-'){ ++it; res -= term(it); } else return res; } } Int term(Iter &it){ Int res = factor(it); while (true){ if (*it == '*'){ ++it; res *= factor(it); } else if (*it == '/'){ ++it; res /= factor(it); } else return res; } } Int factor(Iter &it){ if (*it == '('){ ++it; Int res = expr(it); ++it; return res; } else return number(it); } Int number(Iter &it){ Int res = 0; while (isdigit(*it)){ res = res * 10 + (*it - '0'); ++it; } return res; } int main() { int n; cin >> n; cin.ignore(); for (int i = 0; i < n; i++){ string s; getline(cin, s); cout << eval(s) << endl; } } ```
#define _USE_MATH_DEFINES #include<iostream> #include<cstdio> #include<algorithm> #include<climits> #include<string> #include<vector> #include<list> #include<map> #include<set> #include<cmath> #include<queue> #include<cstring> #include<stack> using namespace std; int p; string S; int num(); int factor(); int term(); int calc(); int num(){ int n = 0; while(p<S.size()-1){ if(isdigit(S[p])) n = n*10+S[p]-'0'; else break; p++; } return n; } int factor(){ int n; if(S[p]=='('){ p++; n = calc(); p++; } else n = num(); return n; } int term(){; int n = factor(); while(p<S.size()-1){ if(S[p]=='*') p++, n *= factor(); else if(S[p]=='/') p++, n /= factor(); else break; } return n; } int calc(){ int n = term(); while(p<S.size()-1){ if(S[p]=='+') p++, n += term(); else if(S[p]=='-') p++, n -= term(); else break; } return n; } int main(){ int N; cin>>N; for(int i=0;i<N;i++){ cin>>S; p = 0; printf("%d\n",calc()); } return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #define _USE_MATH_DEFINES #include<iostream> #include<cstdio> #include<algorithm> #include<climits> #include<string> #include<vector> #include<list> #include<map> #include<set> #include<cmath> #include<queue> #include<cstring> #include<stack> using namespace std; int p; string S; int num(); int factor(); int term(); int calc(); int num(){ int n = 0; while(p<S.size()-1){ if(isdigit(S[p])) n = n*10+S[p]-'0'; else break; p++; } return n; } int factor(){ int n; if(S[p]=='('){ p++; n = calc(); p++; } else n = num(); return n; } int term(){; int n = factor(); while(p<S.size()-1){ if(S[p]=='*') p++, n *= factor(); else if(S[p]=='/') p++, n /= factor(); else break; } return n; } int calc(){ int n = term(); while(p<S.size()-1){ if(S[p]=='+') p++, n += term(); else if(S[p]=='-') p++, n -= term(); else break; } return n; } int main(){ int N; cin>>N; for(int i=0;i<N;i++){ cin>>S; p = 0; printf("%d\n",calc()); } return 0; } ```
#include <iostream> #include <algorithm> #include <cstdlib> using namespace std; string s; string::iterator p; int fact(); int term(); int exp(); int fact() { int x; string num; while(isdigit(*p)) { num += *p; ++p; } if(num.size()) { x = atoi(num.c_str()); } else { ++p; x = exp(); ++p; } return x; } int term() { int x = fact(); while(*p == '*' || *p == '/') { if(*p == '*') { ++p; x *= fact(); } else { ++p; x /= fact(); } } return x; } int exp() { int x = term(); while(*p == '+' || *p == '-') { if(*p == '+') { ++p; x += term(); } else { ++p; x -= term(); } } return x; } int main() { int n; cin >> n; while(n--) { cin >> s; p = s.begin(); cout << exp() << endl; } return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <algorithm> #include <cstdlib> using namespace std; string s; string::iterator p; int fact(); int term(); int exp(); int fact() { int x; string num; while(isdigit(*p)) { num += *p; ++p; } if(num.size()) { x = atoi(num.c_str()); } else { ++p; x = exp(); ++p; } return x; } int term() { int x = fact(); while(*p == '*' || *p == '/') { if(*p == '*') { ++p; x *= fact(); } else { ++p; x /= fact(); } } return x; } int exp() { int x = term(); while(*p == '+' || *p == '-') { if(*p == '+') { ++p; x += term(); } else { ++p; x -= term(); } } return x; } int main() { int n; cin >> n; while(n--) { cin >> s; p = s.begin(); cout << exp() << endl; } return 0; } ```
#include <cstdio> #include <iostream> #include <algorithm> #include <string> using namespace std; int exp(); int term(); int fact(); string s; int id; int main(void){ int n; cin >> n; for(int i = 0; i < n; i++){ cin >> s; id = 0; cout << exp() << endl; } } int exp(){ int res = term(); while(1){ char c = s[id]; id++; if(c == '+') res += term(); else if(c == '-') res -= term(); else break; } return res; } int term(){ int res = fact(); while(1){ char c = s[id]; id++; if(c == '*') res *= fact(); else if(c=='/') res /= fact(); else break; } id--; return res; } int fact(){ char c = s[id]; id++; if(c == '(') return exp(); if(c == '+') return fact(); if(c == '-') return -fact(); int res = c - '0'; while(1){ c = s[id]; id++; if('0' <= c && c <= '9'){ res *= 10; res += c - '0'; } else break; } id--; return res; }
### Prompt Develop a solution in cpp to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <cstdio> #include <iostream> #include <algorithm> #include <string> using namespace std; int exp(); int term(); int fact(); string s; int id; int main(void){ int n; cin >> n; for(int i = 0; i < n; i++){ cin >> s; id = 0; cout << exp() << endl; } } int exp(){ int res = term(); while(1){ char c = s[id]; id++; if(c == '+') res += term(); else if(c == '-') res -= term(); else break; } return res; } int term(){ int res = fact(); while(1){ char c = s[id]; id++; if(c == '*') res *= fact(); else if(c=='/') res /= fact(); else break; } id--; return res; } int fact(){ char c = s[id]; id++; if(c == '(') return exp(); if(c == '+') return fact(); if(c == '-') return -fact(); int res = c - '0'; while(1){ c = s[id]; id++; if('0' <= c && c <= '9'){ res *= 10; res += c - '0'; } else break; } id--; return res; } ```
#include<iostream> #include<string> #include<cctype> #define REP(i,n) for(int i=0;i<(n);i++) using namespace std; typedef string::const_iterator State; int ctoi(const char &c) { return c - '0'; } int expression(State &); int term(State &); int factor(State &); int number(State &); int expression(State &itr) { int ret=term(itr); while (true) { if (*itr == '+') { itr++; ret = ret + term(itr); } else if (*itr == '-') { itr++; ret = ret - term(itr); } else { break; } } return ret; } int term(State &itr) { int ret=factor(itr); while (true) { if (*itr == '*') { itr++; ret = ret*factor(itr); } else if (*itr == '/') { itr++; ret = ret / factor(itr); } else { break; } } return ret; } int factor(State &itr) { int ret; if (*itr == '(') { itr++; ret = expression(itr); itr++; } else { ret = number(itr); } return ret; } int number(State &itr) { int ret = 0; while (isdigit(*itr)) { ret *= 10; ret += ctoi(*itr); itr++; } return ret; } int main() { int n; cin >> n; cin.ignore(); REP(i, n) { string str; getline(cin, str); State begin = str.begin(); int ans = expression(begin); cout << ans << endl; } return 0; }
### Prompt Generate a Cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<string> #include<cctype> #define REP(i,n) for(int i=0;i<(n);i++) using namespace std; typedef string::const_iterator State; int ctoi(const char &c) { return c - '0'; } int expression(State &); int term(State &); int factor(State &); int number(State &); int expression(State &itr) { int ret=term(itr); while (true) { if (*itr == '+') { itr++; ret = ret + term(itr); } else if (*itr == '-') { itr++; ret = ret - term(itr); } else { break; } } return ret; } int term(State &itr) { int ret=factor(itr); while (true) { if (*itr == '*') { itr++; ret = ret*factor(itr); } else if (*itr == '/') { itr++; ret = ret / factor(itr); } else { break; } } return ret; } int factor(State &itr) { int ret; if (*itr == '(') { itr++; ret = expression(itr); itr++; } else { ret = number(itr); } return ret; } int number(State &itr) { int ret = 0; while (isdigit(*itr)) { ret *= 10; ret += ctoi(*itr); itr++; } return ret; } int main() { int n; cin >> n; cin.ignore(); REP(i, n) { string str; getline(cin, str); State begin = str.begin(); int ans = expression(begin); cout << ans << endl; } return 0; } ```
#include<iostream> #include<sstream> using namespace std; bool isnum(string s){ for(int i = 0; i < s.length(); i++) if('0' > s[i] || s[i] > '9') return false; return true; } int solve(string s){ // cout << s << endl; // if(s[0] == '-') return -1*solve(s.substr(1)); if(isnum(s)){ stringstream ss(s); int tmp; ss >> tmp; return tmp; }else{ int para = 0; for(int i = s.length()-1; i >= 0; i--){ if(s[i] == '(') para++; if(s[i] == ')') para--; if((s[i] == '+' || s[i] == '-') && para == 0 && i) if(s[i] == '+') return solve(s.substr(0,i))+solve(s.substr(i+1)); else return solve(s.substr(0,i))-solve(s.substr(i+1)); } para = 0; for(int i = s.length()-1; i >= 0; i--){ if(s[i] == '(') para++; if(s[i] == ')') para--; if((s[i] == '*' || s[i] == '/') && para == 0 && i) if(s[i] == '*') return solve(s.substr(0,i))*solve(s.substr(i+1)); else return solve(s.substr(0,i))/solve(s.substr(i+1)); } if(s[0] == '(' && s[s.length()-1] == ')') return solve(s.substr(1,s.length()-2)); } } int main(){ int n; cin >> n; while(n--){ string s; cin >> s; if(s[0] == '-') cout << solve("0"+s.substr(0,s.length()-1)) << endl; else cout << solve(s.substr(0,s.length()-1)) << endl; } return 0; }
### Prompt In CPP, your task is to solve the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<sstream> using namespace std; bool isnum(string s){ for(int i = 0; i < s.length(); i++) if('0' > s[i] || s[i] > '9') return false; return true; } int solve(string s){ // cout << s << endl; // if(s[0] == '-') return -1*solve(s.substr(1)); if(isnum(s)){ stringstream ss(s); int tmp; ss >> tmp; return tmp; }else{ int para = 0; for(int i = s.length()-1; i >= 0; i--){ if(s[i] == '(') para++; if(s[i] == ')') para--; if((s[i] == '+' || s[i] == '-') && para == 0 && i) if(s[i] == '+') return solve(s.substr(0,i))+solve(s.substr(i+1)); else return solve(s.substr(0,i))-solve(s.substr(i+1)); } para = 0; for(int i = s.length()-1; i >= 0; i--){ if(s[i] == '(') para++; if(s[i] == ')') para--; if((s[i] == '*' || s[i] == '/') && para == 0 && i) if(s[i] == '*') return solve(s.substr(0,i))*solve(s.substr(i+1)); else return solve(s.substr(0,i))/solve(s.substr(i+1)); } if(s[0] == '(' && s[s.length()-1] == ')') return solve(s.substr(1,s.length()-2)); } } int main(){ int n; cin >> n; while(n--){ string s; cin >> s; if(s[0] == '-') cout << solve("0"+s.substr(0,s.length()-1)) << endl; else cout << solve(s.substr(0,s.length()-1)) << endl; } return 0; } ```
#include <iostream> #include <string> #include <queue> #include <vector> #include <cctype> using namespace std; typedef string::const_iterator State; int expression(State &begin); typedef string::const_iterator State; int expression(State &begin); int number(State &begin) { int ret = 0; for (; isdigit(*begin);) { ret *= 10; ret += *begin - '0'; begin++; } return ret; } int factor(State &begin) { int ret; if (*begin == '(') { begin++; ret = expression(begin); begin++; } else { return number(begin); } return ret; } int term(State &begin) { int ret = factor(begin); for (;;) { if (*begin == '*') { begin++; ret *= factor(begin); } else if (*begin == '/') { begin++; ret /= factor(begin); } else break; } return ret; } int expression(State &begin) { int ret = term(begin); for (;;) { if (*begin == '+') { begin++; ret += term(begin); } else if (*begin == '-') { begin++; ret -= term(begin); } else break; } return ret; } int main() { int N; cin >> N; cin.ignore(); for (int i = 0; i < N; i++) { string str; getline(cin, str); State s = str.begin(); cout << expression(s) << endl; } return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> #include <queue> #include <vector> #include <cctype> using namespace std; typedef string::const_iterator State; int expression(State &begin); typedef string::const_iterator State; int expression(State &begin); int number(State &begin) { int ret = 0; for (; isdigit(*begin);) { ret *= 10; ret += *begin - '0'; begin++; } return ret; } int factor(State &begin) { int ret; if (*begin == '(') { begin++; ret = expression(begin); begin++; } else { return number(begin); } return ret; } int term(State &begin) { int ret = factor(begin); for (;;) { if (*begin == '*') { begin++; ret *= factor(begin); } else if (*begin == '/') { begin++; ret /= factor(begin); } else break; } return ret; } int expression(State &begin) { int ret = term(begin); for (;;) { if (*begin == '+') { begin++; ret += term(begin); } else if (*begin == '-') { begin++; ret -= term(begin); } else break; } return ret; } int main() { int N; cin >> N; cin.ignore(); for (int i = 0; i < N; i++) { string str; getline(cin, str); State s = str.begin(); cout << expression(s) << endl; } return 0; } ```
#include<iostream> #include<string> using namespace std; string S; size_t cur; int digit(){ return S[cur++]-'0'; } int number(){ int n=digit(); while(cur<S.size()&&isdigit(S[cur])){ n=n*10+digit(); } return n; } int expression(); int factor(){ if(isdigit(S[cur]))return number(); cur++; int n=expression(); cur++; return n; } int term(){ int t=factor(); for(;cur<S.size()&&(S[cur]=='*'||S[cur]=='/');){ if(S[cur++]=='*')t*=factor(); else t/=factor(); } return t; } int expression(){ int t=term(); for(;cur<S.size()&&(S[cur]=='+'||S[cur]=='-');){ if(S[cur++]=='+')t+=term(); else t-=term(); } return t; } int main(){ int n; cin>>n; for(;n--;){ cur=0; cin>>S; cout<<expression()<<endl; } return 0; }
### Prompt Your task is to create a Cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<string> using namespace std; string S; size_t cur; int digit(){ return S[cur++]-'0'; } int number(){ int n=digit(); while(cur<S.size()&&isdigit(S[cur])){ n=n*10+digit(); } return n; } int expression(); int factor(){ if(isdigit(S[cur]))return number(); cur++; int n=expression(); cur++; return n; } int term(){ int t=factor(); for(;cur<S.size()&&(S[cur]=='*'||S[cur]=='/');){ if(S[cur++]=='*')t*=factor(); else t/=factor(); } return t; } int expression(){ int t=term(); for(;cur<S.size()&&(S[cur]=='+'||S[cur]=='-');){ if(S[cur++]=='+')t+=term(); else t-=term(); } return t; } int main(){ int n; cin>>n; for(;n--;){ cur=0; cin>>S; cout<<expression()<<endl; } return 0; } ```
#include <iostream> #include <string> #include <cctype> using namespace std; typedef string::const_iterator State; int expression(State &begin); int term(State &begin); int factor(State &begin); int number(State &begin); int expression(State &begin){ int ret=term(begin); while(true){ if(*begin == '+'){ begin++; ret+=term(begin); }else if(*begin == '-'){ begin++; ret-=term(begin); }else{ break; } } return ret; } int term(State &begin){ int ret=factor(begin); while(true){ if(*begin == '*'){ begin++; ret*=factor(begin); }else if(*begin == '/'){ begin++; ret/=factor(begin); }else{ break; } } return ret; } int number(State &begin){ int ret=0; while(isdigit(*begin)){ ret*=10; ret+= (*begin) -'0'; begin++; } return ret; } int factor(State &begin){ if(*begin == '('){ begin++; int ret=expression(begin); begin++; return ret; }else{ return number(begin); } } int main(){ int n; cin >> n; cin.ignore(); for(int i=0;i<n;i++){ string s; getline(cin,s); State begin=s.begin(); int ans=expression(begin); cout << ans << endl; } return 0; }
### Prompt In CPP, your task is to solve the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> #include <cctype> using namespace std; typedef string::const_iterator State; int expression(State &begin); int term(State &begin); int factor(State &begin); int number(State &begin); int expression(State &begin){ int ret=term(begin); while(true){ if(*begin == '+'){ begin++; ret+=term(begin); }else if(*begin == '-'){ begin++; ret-=term(begin); }else{ break; } } return ret; } int term(State &begin){ int ret=factor(begin); while(true){ if(*begin == '*'){ begin++; ret*=factor(begin); }else if(*begin == '/'){ begin++; ret/=factor(begin); }else{ break; } } return ret; } int number(State &begin){ int ret=0; while(isdigit(*begin)){ ret*=10; ret+= (*begin) -'0'; begin++; } return ret; } int factor(State &begin){ if(*begin == '('){ begin++; int ret=expression(begin); begin++; return ret; }else{ return number(begin); } } int main(){ int n; cin >> n; cin.ignore(); for(int i=0;i<n;i++){ string s; getline(cin,s); State begin=s.begin(); int ans=expression(begin); cout << ans << endl; } return 0; } ```
#include <iostream> #include <string> using namespace std; int n; string str; int number(int& i); int term(int& i); int expression(int& i); int factor(int& i); int number(int& i) { int ret = 0; while ('0' <= str[i] && str[i] <= '9') { ret *= 10; ret += str[i] - '0'; i++; } return ret; } int term(int& i) { int ret = factor(i); while (true) { if (str[i] == '*') { i++; ret *= factor(i); } else if (str[i] == '/') { i++; ret /= factor(i); } else { break; } } return ret; } int expression(int& i) { int ret = term(i); while (true) { if (str[i] == '+') { i++; ret += term(i); } else if (str[i] == '-') { i++; ret -= term(i); } else { break; } } return ret; } int factor(int& i) { int ret = 0; if (str[i] == '(') { i++; ret = expression(i); i++; } else { ret = number(i); } return ret; } int main() { cin >> n; while (n--) { cin >> str; int i = 0; cout << expression(i) << endl; } return 0; }
### Prompt Please formulate a cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> using namespace std; int n; string str; int number(int& i); int term(int& i); int expression(int& i); int factor(int& i); int number(int& i) { int ret = 0; while ('0' <= str[i] && str[i] <= '9') { ret *= 10; ret += str[i] - '0'; i++; } return ret; } int term(int& i) { int ret = factor(i); while (true) { if (str[i] == '*') { i++; ret *= factor(i); } else if (str[i] == '/') { i++; ret /= factor(i); } else { break; } } return ret; } int expression(int& i) { int ret = term(i); while (true) { if (str[i] == '+') { i++; ret += term(i); } else if (str[i] == '-') { i++; ret -= term(i); } else { break; } } return ret; } int factor(int& i) { int ret = 0; if (str[i] == '(') { i++; ret = expression(i); i++; } else { ret = number(i); } return ret; } int main() { cin >> n; while (n--) { cin >> str; int i = 0; cout << expression(i) << endl; } return 0; } ```
#include <iostream> #include <string> using namespace std; string s; bool isDigit(char c) { return (c >= '0' && c <= '9'); } int parseNumber(string &s, int &pos) { int ret = 0; while(1){ if(isDigit(s[pos])) ret *= 10, ret += s[pos]-'0'; else break; pos++; } return ret; } int parseExp(string &s, int &pos); int parseFactor(string &s, int &pos) { if(s[pos] == '('){ pos++; int ret = parseExp(s, pos); pos++; return ret; } else if(isDigit(s[pos])) return parseNumber(s, pos); } int parseTerm(string &s, int &pos) { int ret = 1; ret *= parseFactor(s, pos); while(1){ if(s[pos] == '*'){ pos++; ret *= parseFactor(s, pos); } else if(s[pos] == '/'){ pos++; ret /= parseFactor(s, pos); } else break; } return ret; } int parseExp(string &s, int &pos) { int ret = 0; ret += parseTerm(s, pos); while(1){ if(s[pos] == '+'){ pos++; ret += parseTerm(s, pos); } else if(s[pos] == '-'){ pos++; ret -= parseTerm(s, pos); } else break; } return ret; } int main(void) { int T; cin >> T; for(int t = 0; t < T; t++){ cin >> s; int pos = 0; cout << parseExp(s, pos) << endl; } return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> using namespace std; string s; bool isDigit(char c) { return (c >= '0' && c <= '9'); } int parseNumber(string &s, int &pos) { int ret = 0; while(1){ if(isDigit(s[pos])) ret *= 10, ret += s[pos]-'0'; else break; pos++; } return ret; } int parseExp(string &s, int &pos); int parseFactor(string &s, int &pos) { if(s[pos] == '('){ pos++; int ret = parseExp(s, pos); pos++; return ret; } else if(isDigit(s[pos])) return parseNumber(s, pos); } int parseTerm(string &s, int &pos) { int ret = 1; ret *= parseFactor(s, pos); while(1){ if(s[pos] == '*'){ pos++; ret *= parseFactor(s, pos); } else if(s[pos] == '/'){ pos++; ret /= parseFactor(s, pos); } else break; } return ret; } int parseExp(string &s, int &pos) { int ret = 0; ret += parseTerm(s, pos); while(1){ if(s[pos] == '+'){ pos++; ret += parseTerm(s, pos); } else if(s[pos] == '-'){ pos++; ret -= parseTerm(s, pos); } else break; } return ret; } int main(void) { int T; cin >> T; for(int t = 0; t < T; t++){ cin >> s; int pos = 0; cout << parseExp(s, pos) << endl; } return 0; } ```
#include"bits/stdc++.h" using namespace std; //define #define ALL(a) a.begin(),a.end() #define REP(i,n) for(int i=0;i<n;i++) #define RREP(i,n) for(int i=n-1;i>=0;i--) #define debug(x) if(1)cout<<#x<<":"<<x<<endl; #define DEBUG(x) if(1)cout<<#x<<":"<<x<<endl; #define ll long long //typedef typedef vector<int> vi; typedef vector<vector<int>> vvi; int formula(string &s, int &i); int term(string &s, int &i); int factor(string &s, int &i); int number(string &s, int &i); int main() { int n; cin >> n; for (int i = 0; i < n; i++) { string s; cin >> s; int num = 0; cout << formula(s, num) << endl; } return 0; } int formula(string &s, int &i) { int res = term(s, i); while(s[i]=='+' || s[i]=='-'){ char op = s[i]; i++; if (op == '+') { res += term(s, i); } else { res -= term(s, i); } } return res; } int term(string &s, int &i) { int res = factor(s, i); while (s[i] == '*' || s[i] == '/') { char op = s[i]; i++; if (op == '*') { res *= factor(s, i); } else { res /= factor(s, i); } } return res; } int factor(string &s, int &i) { int res; if (s[i] == '(') { i++; res = formula(s, i); i++; } else { res = number(s, i); } return res; } int number(string &s, int &i) { int res = 0; for (; isdigit(s[i]); i++) { res = (s[i]-'0')+ res * 10; } return res; }
### Prompt Develop a solution in cpp to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include"bits/stdc++.h" using namespace std; //define #define ALL(a) a.begin(),a.end() #define REP(i,n) for(int i=0;i<n;i++) #define RREP(i,n) for(int i=n-1;i>=0;i--) #define debug(x) if(1)cout<<#x<<":"<<x<<endl; #define DEBUG(x) if(1)cout<<#x<<":"<<x<<endl; #define ll long long //typedef typedef vector<int> vi; typedef vector<vector<int>> vvi; int formula(string &s, int &i); int term(string &s, int &i); int factor(string &s, int &i); int number(string &s, int &i); int main() { int n; cin >> n; for (int i = 0; i < n; i++) { string s; cin >> s; int num = 0; cout << formula(s, num) << endl; } return 0; } int formula(string &s, int &i) { int res = term(s, i); while(s[i]=='+' || s[i]=='-'){ char op = s[i]; i++; if (op == '+') { res += term(s, i); } else { res -= term(s, i); } } return res; } int term(string &s, int &i) { int res = factor(s, i); while (s[i] == '*' || s[i] == '/') { char op = s[i]; i++; if (op == '*') { res *= factor(s, i); } else { res /= factor(s, i); } } return res; } int factor(string &s, int &i) { int res; if (s[i] == '(') { i++; res = formula(s, i); i++; } else { res = number(s, i); } return res; } int number(string &s, int &i) { int res = 0; for (; isdigit(s[i]); i++) { res = (s[i]-'0')+ res * 10; } return res; } ```
#include <iostream> #include <string> #include <cctype> using namespace std; int cur; string s; int digit(); int number(); int factor(); int term(); int expression(); int digit() { return ( s[cur++] - '0' ); } int number() { int n = digit(); while ( isdigit( s[cur] ) ) n = n * 10 + digit(); return n; } int factor() { int n; if ( s[cur] == '(' ) { cur++; n = expression(); cur++; } else n = number(); return n; } int term() { int n = factor(); while ( s[cur] == '*' || s[cur] == '/' ) { cur++; if ( s[cur - 1] == '*' ) n *= factor(); else n /= factor(); } return n; } int expression() { int n = term(); while ( s[cur] == '+' || s[cur] == '-' ) { cur++; if ( s[cur - 1] == '+' ) n += term(); else n -= term(); } return n; } int main() { int n; cin >> n; for ( int i = 0; i < n; i++ ) { cur = 0; cin >> s; int m = expression(); cout << m << endl; } }
### Prompt Please formulate a Cpp solution to the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <string> #include <cctype> using namespace std; int cur; string s; int digit(); int number(); int factor(); int term(); int expression(); int digit() { return ( s[cur++] - '0' ); } int number() { int n = digit(); while ( isdigit( s[cur] ) ) n = n * 10 + digit(); return n; } int factor() { int n; if ( s[cur] == '(' ) { cur++; n = expression(); cur++; } else n = number(); return n; } int term() { int n = factor(); while ( s[cur] == '*' || s[cur] == '/' ) { cur++; if ( s[cur - 1] == '*' ) n *= factor(); else n /= factor(); } return n; } int expression() { int n = term(); while ( s[cur] == '+' || s[cur] == '-' ) { cur++; if ( s[cur - 1] == '+' ) n += term(); else n -= term(); } return n; } int main() { int n; cin >> n; for ( int i = 0; i < n; i++ ) { cur = 0; cin >> s; int m = expression(); cout << m << endl; } } ```
#include <iostream> #include <cctype> using namespace std; int expr(string& s,int& i); int term(string& s,int& i); int factor(string& s,int& i); int number(string& s,int& i); int expr(string& s,int& i){ int val = term(s,i); while(s[i]=='+' || s[i]=='-'){ char op = s[i]; i++; int val2 = term(s,i); if(op=='+')val += val2; else val -= val2; } return val; } int term(string& s,int& i){ int val = factor(s,i); while(s[i]=='*' || s[i]=='/'){ char op = s[i]; i++; int val2 = factor(s,i); if(op=='*')val *= val2; else val /= val2; } return val; } int factor(string& s,int& i){ if(isdigit(s[i]))return number(s,i); i++; int ret = expr(s,i); i++; return ret; } int number(string& s,int& i){ int n = s[i++] - '0'; while(isdigit(s[i])) n=n*10 + s[i++] - '0'; return n; } int main(void) { int n; cin >> n; for(int i=0;i<n;i++){ string str; cin >> str; int j=0; cout << expr(str,j) << endl; } }
### Prompt Develop a solution in Cpp to the problem described below: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include <iostream> #include <cctype> using namespace std; int expr(string& s,int& i); int term(string& s,int& i); int factor(string& s,int& i); int number(string& s,int& i); int expr(string& s,int& i){ int val = term(s,i); while(s[i]=='+' || s[i]=='-'){ char op = s[i]; i++; int val2 = term(s,i); if(op=='+')val += val2; else val -= val2; } return val; } int term(string& s,int& i){ int val = factor(s,i); while(s[i]=='*' || s[i]=='/'){ char op = s[i]; i++; int val2 = factor(s,i); if(op=='*')val *= val2; else val /= val2; } return val; } int factor(string& s,int& i){ if(isdigit(s[i]))return number(s,i); i++; int ret = expr(s,i); i++; return ret; } int number(string& s,int& i){ int n = s[i++] - '0'; while(isdigit(s[i])) n=n*10 + s[i++] - '0'; return n; } int main(void) { int n; cin >> n; for(int i=0;i<n;i++){ string str; cin >> str; int j=0; cout << expr(str,j) << endl; } } ```
#include<iostream> #include<string> #include<cctype> using namespace std; string s; long id; long ev1(void); long num(void){ long v=0; while(isdigit(s[id])){v=v*10+(s[id]-48);id++;} return v; } long ev3(void){ if(s[id]=='('){ id++; long v=ev1(); id++; return v; }else return num(); } long ev2(void){ long v=ev3(); while(1){ if(s[id]=='*'){id++;v*=ev3();} else if(s[id]=='/'){id++;v/=ev3();} else break; } return v; } long ev1(void){ long v=ev2(); while(1){ if(s[id]=='+'){id++;v+=ev2();} else if(s[id]=='-'){id++;v-=ev2();} else break; } return v; } int main(){ long n,i; cin>>n; for(i=0;i<n;i++){ cin>>s; id=0; cout<<ev1()<<endl; } return 0; }
### Prompt In cpp, your task is to solve the following problem: Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right. * You may assume that there is no division by zero. * All calculation is performed as integers, and after the decimal point should be truncated * Length of the expression will not exceed 100. * -1 × 109 ≤ intermediate results of computation ≤ 109 Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Example Input 2 4-2*3= 4*(8+4+3)= Output -2 60 ### Response ```cpp #include<iostream> #include<string> #include<cctype> using namespace std; string s; long id; long ev1(void); long num(void){ long v=0; while(isdigit(s[id])){v=v*10+(s[id]-48);id++;} return v; } long ev3(void){ if(s[id]=='('){ id++; long v=ev1(); id++; return v; }else return num(); } long ev2(void){ long v=ev3(); while(1){ if(s[id]=='*'){id++;v*=ev3();} else if(s[id]=='/'){id++;v/=ev3();} else break; } return v; } long ev1(void){ long v=ev2(); while(1){ if(s[id]=='+'){id++;v+=ev2();} else if(s[id]=='-'){id++;v-=ev2();} else break; } return v; } int main(){ long n,i; cin>>n; for(i=0;i<n;i++){ cin>>s; id=0; cout<<ev1()<<endl; } return 0; } ```
#include<iostream> #include<queue> using namespace std; struct Puzzle { char p[10][10]; }; queue<pair<Puzzle, int>>Q; queue<pair<int, int> >Q2; int blute_force(int h, int w, Puzzle x) { while (!Q.empty())Q.pop(); Q.push(make_pair(x, 0)); while (true) { Puzzle y = Q.front().first; int V = Q.front().second; Q.pop(); int a[3] = { 0,0,0 }; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (y.p[i][j] == 'R')a[0]++; if (y.p[i][j] == 'G')a[1]++; if (y.p[i][j] == 'B')a[2]++; } } if (a[0] == h*w || a[1] == h*w || a[2] == h*w)return V; char F[3] = { 'R','G','B' }; for (int i = 0; i < 3; i++) { if (F[i] == y.p[0][0])continue; int dx[4] = { 0,1,0,-1 }; int dy[4] = { 1,0,-1,0 }; Puzzle v = y; Q2.push(make_pair(0, 0)); v.p[0][0] = F[i]; while (!Q2.empty()) { int cx = Q2.front().first, cy = Q2.front().second; Q2.pop(); for (int j = 0; j < 4; j++) { int ex = cx + dx[j], ey = cy + dy[j]; if (ex < 0 || ey < 0 || ex >= h || ey >= w)continue; if (y.p[ex][ey] == y.p[0][0] && v.p[ex][ey] == y.p[ex][ey]) { Q2.push(make_pair(ex, ey)); v.p[ex][ey] = F[i]; } } } Q.push(make_pair(v, V + 1)); } } } int main() { while (true) { Puzzle x; int H, W; cin >> W >> H; if (W + H == 0)break; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> x.p[i][j]; } } cout << blute_force(H, W, x) << endl; } return 0; }
### Prompt Please provide a Cpp coded solution to the problem described below: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<queue> using namespace std; struct Puzzle { char p[10][10]; }; queue<pair<Puzzle, int>>Q; queue<pair<int, int> >Q2; int blute_force(int h, int w, Puzzle x) { while (!Q.empty())Q.pop(); Q.push(make_pair(x, 0)); while (true) { Puzzle y = Q.front().first; int V = Q.front().second; Q.pop(); int a[3] = { 0,0,0 }; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (y.p[i][j] == 'R')a[0]++; if (y.p[i][j] == 'G')a[1]++; if (y.p[i][j] == 'B')a[2]++; } } if (a[0] == h*w || a[1] == h*w || a[2] == h*w)return V; char F[3] = { 'R','G','B' }; for (int i = 0; i < 3; i++) { if (F[i] == y.p[0][0])continue; int dx[4] = { 0,1,0,-1 }; int dy[4] = { 1,0,-1,0 }; Puzzle v = y; Q2.push(make_pair(0, 0)); v.p[0][0] = F[i]; while (!Q2.empty()) { int cx = Q2.front().first, cy = Q2.front().second; Q2.pop(); for (int j = 0; j < 4; j++) { int ex = cx + dx[j], ey = cy + dy[j]; if (ex < 0 || ey < 0 || ex >= h || ey >= w)continue; if (y.p[ex][ey] == y.p[0][0] && v.p[ex][ey] == y.p[ex][ey]) { Q2.push(make_pair(ex, ey)); v.p[ex][ey] = F[i]; } } } Q.push(make_pair(v, V + 1)); } } } int main() { while (true) { Puzzle x; int H, W; cin >> W >> H; if (W + H == 0)break; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> x.p[i][j]; } } cout << blute_force(H, W, x) << endl; } return 0; } ```
#include <bits/stdc++.h> using namespace std; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; using vc = vector<vector<char>>; void dfs(vc &c, int y, int x, char oldc, char newc) { if(y < 0 || y >= c.size() || x < 0 || x >= c[0].size()) return; if(c[y][x] != oldc) return; c[y][x] = newc; for(int i = 0; i < 4; ++i) { int ny = y + dy[i], nx = x + dx[i]; dfs(c, ny, nx, oldc, newc); } } int main() { cin.tie(0); ios::sync_with_stdio(false); char tmp[] = {'R', 'G', 'B'}; int x, y; while(cin >> x >> y, y != 0) { vc c(y, vector<char>(x)); for(int i = 0; i < y; ++i) { for(int j = 0; j < x; ++j) { cin >> c[i][j]; } } int ans = 1e9; queue<vc> que; que.push(c); map<vc, int> mp; mp[c] = 0; while(!que.empty()) { vc s = que.front(); que.pop(); { bool ok = true; for(int i = 0; i < y; ++i) { for(int j = 0; j < x; ++j) { if(s[0][0] != s[i][j]) ok = false; } } if(ok) { ans = mp[s]; break; } } for(int i = 0; i < 3; ++i) { if(s[0][0] == tmp[i]) continue; vc nc = s; dfs(nc, 0, 0, s[0][0], tmp[i]); if(!mp.count(nc)) { mp[nc] = mp[s] + 1; que.push(nc); } } } cout << ans << endl; } }
### Prompt In cpp, your task is to solve the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; using vc = vector<vector<char>>; void dfs(vc &c, int y, int x, char oldc, char newc) { if(y < 0 || y >= c.size() || x < 0 || x >= c[0].size()) return; if(c[y][x] != oldc) return; c[y][x] = newc; for(int i = 0; i < 4; ++i) { int ny = y + dy[i], nx = x + dx[i]; dfs(c, ny, nx, oldc, newc); } } int main() { cin.tie(0); ios::sync_with_stdio(false); char tmp[] = {'R', 'G', 'B'}; int x, y; while(cin >> x >> y, y != 0) { vc c(y, vector<char>(x)); for(int i = 0; i < y; ++i) { for(int j = 0; j < x; ++j) { cin >> c[i][j]; } } int ans = 1e9; queue<vc> que; que.push(c); map<vc, int> mp; mp[c] = 0; while(!que.empty()) { vc s = que.front(); que.pop(); { bool ok = true; for(int i = 0; i < y; ++i) { for(int j = 0; j < x; ++j) { if(s[0][0] != s[i][j]) ok = false; } } if(ok) { ans = mp[s]; break; } } for(int i = 0; i < 3; ++i) { if(s[0][0] == tmp[i]) continue; vc nc = s; dfs(nc, 0, 0, s[0][0], tmp[i]); if(!mp.count(nc)) { mp[nc] = mp[s] + 1; que.push(nc); } } } cout << ans << endl; } } ```
#include<iostream> #include<vector> #include<queue> #include<set> #include<tuple> using namespace std; enum {STEP, FIELD}; typedef tuple<int, vector<vector<char>>> Node; int dx[4] = {0, 1, 0, -1}; int dy[4] = {-1, 0, 1, 0}; int w, h; void flood_fill(vector<vector<char>>& field, int y, int x, char color) { char from = field[y][x]; field[y][x] = color; for(int i = 0; i < 4; ++i) { int ny = y + dy[i]; int nx = x + dx[i]; if(ny < 0 || h <= ny || nx < 0 || w <= nx) continue; if(field[ny][nx] != from) continue; flood_fill(field, ny, nx, color); } } bool clear(const vector<vector<char>>& field) { for(int i = 0; i < h; ++i) for(int j = 0; j < w; ++j) if(field[i][j] != field[0][0]) return false; return true; } int bfs(const vector<vector<char>>& init_field) { set<vector<vector<char>>> visited; queue<Node> q; q.push(Node(0, init_field)); while(!q.empty()) { int step = get<STEP>(q.front()); auto field = get<FIELD>(q.front()); q.pop(); if(clear(field)) return step; if(visited.count(field)) continue; visited.insert(field); for(char color: {'R', 'G', 'B'}) { if(color == field[0][0]) continue; auto next_field = field; flood_fill(next_field, 0, 0, color); q.push(Node(step + 1, next_field)); } } return -1; } int main() { while(cin >> w >> h, w | h) { vector<vector<char>> field(h, vector<char>(w)); for(int i = 0; i < h; ++i) for(int j = 0; j < w; ++j) cin >> field[i][j]; cout << bfs(field) << endl; } }
### Prompt Please create a solution in cpp to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<vector> #include<queue> #include<set> #include<tuple> using namespace std; enum {STEP, FIELD}; typedef tuple<int, vector<vector<char>>> Node; int dx[4] = {0, 1, 0, -1}; int dy[4] = {-1, 0, 1, 0}; int w, h; void flood_fill(vector<vector<char>>& field, int y, int x, char color) { char from = field[y][x]; field[y][x] = color; for(int i = 0; i < 4; ++i) { int ny = y + dy[i]; int nx = x + dx[i]; if(ny < 0 || h <= ny || nx < 0 || w <= nx) continue; if(field[ny][nx] != from) continue; flood_fill(field, ny, nx, color); } } bool clear(const vector<vector<char>>& field) { for(int i = 0; i < h; ++i) for(int j = 0; j < w; ++j) if(field[i][j] != field[0][0]) return false; return true; } int bfs(const vector<vector<char>>& init_field) { set<vector<vector<char>>> visited; queue<Node> q; q.push(Node(0, init_field)); while(!q.empty()) { int step = get<STEP>(q.front()); auto field = get<FIELD>(q.front()); q.pop(); if(clear(field)) return step; if(visited.count(field)) continue; visited.insert(field); for(char color: {'R', 'G', 'B'}) { if(color == field[0][0]) continue; auto next_field = field; flood_fill(next_field, 0, 0, color); q.push(Node(step + 1, next_field)); } } return -1; } int main() { while(cin >> w >> h, w | h) { vector<vector<char>> field(h, vector<char>(w)); for(int i = 0; i < h; ++i) for(int j = 0; j < w; ++j) cin >> field[i][j]; cout << bfs(field) << endl; } } ```
#include<bits/stdc++.h> using namespace std; const int dy[] = { 0, 1, 0, -1}, dx[] = { 1, 0, -1, 0}; int H, W; bool isend(const string& str){ bool color; for(int i = 0; i < 3; i++){ if(count( str.begin(), str.end(), "RGB"[i]) == H * W) return true; } return false; } int getx( int pos){ return pos % W; } int gety( int pos){ return pos / W; } int getpos( int y, int x){ return y * W + x; } string change( string str, char pre, char c){ if(pre == c) return str; queue< int > que; que.push(0); str[0] = c; while(!que.empty()){ int p = que.front(); que.pop(); for(int i = 0; i < 4; i++){ int ny = gety(p) + dy[i], nx = getx(p) + dx[i]; if(ny < 0 || ny >= H || nx < 0 || nx >= W) continue; if(str[getpos(ny,nx)] != pre) continue; str[getpos(ny,nx)] = c; que.push(getpos(ny,nx)); } } return str; } int bfs(string str){ queue< string > que; map< string, int > used; que.push(str); used[str] = 0; while(!que.empty()){ string s = que.front(); que.pop(); if(isend(s)) return used[s]; for(int i = 0; i < 3; i++){ string newstr = change(s,s[0],"RGB"[i]); if(used.find(newstr) != used.end()) continue; used[newstr] = used[s] + 1; que.push(newstr); } } } int main(){ while( cin >> W >> H, W){ string mas; for(int i = 0; i < H; i++){ for(int j = 0; j < W; j++){ char c; cin >> c; mas += c; } } cout << bfs(mas) << endl; } }
### Prompt Your challenge is to write a cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<bits/stdc++.h> using namespace std; const int dy[] = { 0, 1, 0, -1}, dx[] = { 1, 0, -1, 0}; int H, W; bool isend(const string& str){ bool color; for(int i = 0; i < 3; i++){ if(count( str.begin(), str.end(), "RGB"[i]) == H * W) return true; } return false; } int getx( int pos){ return pos % W; } int gety( int pos){ return pos / W; } int getpos( int y, int x){ return y * W + x; } string change( string str, char pre, char c){ if(pre == c) return str; queue< int > que; que.push(0); str[0] = c; while(!que.empty()){ int p = que.front(); que.pop(); for(int i = 0; i < 4; i++){ int ny = gety(p) + dy[i], nx = getx(p) + dx[i]; if(ny < 0 || ny >= H || nx < 0 || nx >= W) continue; if(str[getpos(ny,nx)] != pre) continue; str[getpos(ny,nx)] = c; que.push(getpos(ny,nx)); } } return str; } int bfs(string str){ queue< string > que; map< string, int > used; que.push(str); used[str] = 0; while(!que.empty()){ string s = que.front(); que.pop(); if(isend(s)) return used[s]; for(int i = 0; i < 3; i++){ string newstr = change(s,s[0],"RGB"[i]); if(used.find(newstr) != used.end()) continue; used[newstr] = used[s] + 1; que.push(newstr); } } } int main(){ while( cin >> W >> H, W){ string mas; for(int i = 0; i < H; i++){ for(int j = 0; j < W; j++){ char c; cin >> c; mas += c; } } cout << bfs(mas) << endl; } } ```
#include <iostream> #include <algorithm> #include <queue> #include <cstring> using namespace std; typedef long long ll; const int INF = 1 << 25; int ans; int b[10][10]; int W, H; int dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 }; bool in(int x, int y) { return 0 <= x && x < W && 0 <= y && y < H; } void copy_board(int dst[10][10], int src[10][10]) { for(int i = 0; i < H; i++) { for(int j = 0; j < W; j++) { dst[i][j] = src[i][j]; } } } typedef pair<int, int> P; int vis[10][10]; void color(int b[10][10], int c) { memset(vis, 0, sizeof vis); int cc = b[0][0]; queue<P> q; q.push({ 0, 0 }); b[0][0] = c; while(q.size()) { int x = q.front().first, y = q.front().second; q.pop(); for(int k = 0; k < 4; k++) { int nx = x + dx[k], ny = y + dy[k]; if(in(nx, ny) && b[ny][nx] == cc && !vis[ny][nx]) { vis[ny][nx] = 1; b[ny][nx] = c; q.push({ nx, ny }); } } } } void dfs(int n) { if(n == 20 || ans < n) return; for(int c = 0; c < 3; c++) { int cnt = 0; for(int i = 0; i < H; i++) { cnt += count(b[i], b[i] + W, c); } if(cnt == H * W) { ans = min(ans, n); return; } } int tmp[10][10]; copy_board(tmp, b); for(int i = 0; i < 3; i++) { copy_board(b, tmp); if(b[0][0] != i) { color(b, i); dfs(n + 1); } } copy_board(b, tmp); } int main() { cin.tie(0); ios::sync_with_stdio(false); while(cin >> W >> H, W) { for(int i = 0; i < H; i++) { for(int j = 0; j < W; j++) { char c; cin >> c; if(c == 'R') b[i][j] = 0; if(c == 'G') b[i][j] = 1; if(c == 'B') b[i][j] = 2; } } ans = INF; dfs(0); cout << ans << endl; } }
### Prompt Your challenge is to write a Cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <algorithm> #include <queue> #include <cstring> using namespace std; typedef long long ll; const int INF = 1 << 25; int ans; int b[10][10]; int W, H; int dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 }; bool in(int x, int y) { return 0 <= x && x < W && 0 <= y && y < H; } void copy_board(int dst[10][10], int src[10][10]) { for(int i = 0; i < H; i++) { for(int j = 0; j < W; j++) { dst[i][j] = src[i][j]; } } } typedef pair<int, int> P; int vis[10][10]; void color(int b[10][10], int c) { memset(vis, 0, sizeof vis); int cc = b[0][0]; queue<P> q; q.push({ 0, 0 }); b[0][0] = c; while(q.size()) { int x = q.front().first, y = q.front().second; q.pop(); for(int k = 0; k < 4; k++) { int nx = x + dx[k], ny = y + dy[k]; if(in(nx, ny) && b[ny][nx] == cc && !vis[ny][nx]) { vis[ny][nx] = 1; b[ny][nx] = c; q.push({ nx, ny }); } } } } void dfs(int n) { if(n == 20 || ans < n) return; for(int c = 0; c < 3; c++) { int cnt = 0; for(int i = 0; i < H; i++) { cnt += count(b[i], b[i] + W, c); } if(cnt == H * W) { ans = min(ans, n); return; } } int tmp[10][10]; copy_board(tmp, b); for(int i = 0; i < 3; i++) { copy_board(b, tmp); if(b[0][0] != i) { color(b, i); dfs(n + 1); } } copy_board(b, tmp); } int main() { cin.tie(0); ios::sync_with_stdio(false); while(cin >> W >> H, W) { for(int i = 0; i < H; i++) { for(int j = 0; j < W; j++) { char c; cin >> c; if(c == 'R') b[i][j] = 0; if(c == 'G') b[i][j] = 1; if(c == 'B') b[i][j] = 2; } } ans = INF; dfs(0); cout << ans << endl; } } ```
#include<iostream> #include<queue> using namespace std; int x,y; struct grid{ char g[11][11]; int count; }; void DFS(grid& gr,char firstcell,char changecolor,int posx,int posy){ if(posx < 0 || posx >= x || posy < 0 || posy >= y || gr.g[posx][posy] != firstcell){ //if(gr.g[posx][posy] != firstcell){ return; } gr.g[posx][posy] = changecolor; DFS(gr,firstcell,changecolor,posx+1,posy); DFS(gr,firstcell,changecolor,posx-1,posy); DFS(gr,firstcell,changecolor,posx,posy+1); DFS(gr,firstcell,changecolor,posx,posy-1); } int main(){ while(1){ cin >> x >> y; if(x==0 && y==0){ break; } grid start; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ cin >> start.g[j][i]; } } char firstcell = start.g[0][0]; bool flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(start.g[j][i]!=firstcell){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << 0 << endl; continue; } start.count = 0; queue<grid> q; q.push(start); while(1){ grid BeforeGrid = q.front(); q.pop(); BeforeGrid.count++; grid tmp = BeforeGrid; firstcell = tmp.g[0][0]; if(firstcell != 'R'){ DFS(tmp,firstcell,'R',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='R'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = BeforeGrid; } if(firstcell != 'G'){ DFS(tmp,firstcell,'G',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='G'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = BeforeGrid; } if(firstcell != 'B'){ DFS(tmp,firstcell,'B',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='B'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); } } } return 0; }
### Prompt Develop a solution in cpp to the problem described below: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<queue> using namespace std; int x,y; struct grid{ char g[11][11]; int count; }; void DFS(grid& gr,char firstcell,char changecolor,int posx,int posy){ if(posx < 0 || posx >= x || posy < 0 || posy >= y || gr.g[posx][posy] != firstcell){ //if(gr.g[posx][posy] != firstcell){ return; } gr.g[posx][posy] = changecolor; DFS(gr,firstcell,changecolor,posx+1,posy); DFS(gr,firstcell,changecolor,posx-1,posy); DFS(gr,firstcell,changecolor,posx,posy+1); DFS(gr,firstcell,changecolor,posx,posy-1); } int main(){ while(1){ cin >> x >> y; if(x==0 && y==0){ break; } grid start; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ cin >> start.g[j][i]; } } char firstcell = start.g[0][0]; bool flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(start.g[j][i]!=firstcell){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << 0 << endl; continue; } start.count = 0; queue<grid> q; q.push(start); while(1){ grid BeforeGrid = q.front(); q.pop(); BeforeGrid.count++; grid tmp = BeforeGrid; firstcell = tmp.g[0][0]; if(firstcell != 'R'){ DFS(tmp,firstcell,'R',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='R'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = BeforeGrid; } if(firstcell != 'G'){ DFS(tmp,firstcell,'G',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='G'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = BeforeGrid; } if(firstcell != 'B'){ DFS(tmp,firstcell,'B',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='B'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); } } } return 0; } ```
// 2017/11/19 Tazoe #include <iostream> #include <queue> #include <string> #include <map> using namespace std; struct state{ string G; int N; }; bool is_over(string G) { bool flg = true; for(int i=1; i<G.size(); i++){ if(G[i]!=G[0]){ flg = false; break; } } return flg; } void DFS(char g[12][12], char F, char T, int x, int y) { if(g[y][x]!=F) return; g[y][x] = T; DFS(g, F, T, x-1, y); DFS(g, F, T, x+1, y); DFS(g, F, T, x, y-1); DFS(g, F, T, x, y+1); } string fill(string G, char C, int X, int Y) { char g[12][12]; for(int y=0; y<Y+2; y++){ for(int x=0; x<X+2; x++){ g[y][x] = 'N'; } } // ???????????????2?¬????????????? for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ g[y+1][x+1] = G[y*X+x]; } } DFS(g, G[0], C, 1, 1); // 2?¬???????????????????????????? for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ G[y*X+x] = g[y+1][x+1]; } } return G; } int main() { while(true){ int X, Y; cin >> X >> Y; if(X==0 && Y==0) break; string G = ""; for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ string c; cin >> c; G += c; } } queue<struct state> que; map<string, bool> memo; struct state now; now.G = G; now.N = 0; que.push(now); memo[now.G] = true; while(!que.empty()){ now = que.front(); que.pop(); if(is_over(now.G)){ cout << now.N << endl; break; } struct state nex1, nex2; if(now.G[0]=='R'){ nex1.G = fill(now.G, 'G', X, Y); nex2.G = fill(now.G, 'B', X, Y); nex1.N = nex2.N = now.N+1; } else if(now.G[0]=='G'){ nex1.G = fill(now.G, 'R', X, Y); nex2.G = fill(now.G, 'B', X, Y); nex1.N = nex2.N = now.N+1; } else if(now.G[0]=='B'){ nex1.G = fill(now.G, 'R', X, Y); nex2.G = fill(now.G, 'G', X, Y); nex1.N = nex2.N = now.N+1; } if(memo.find(nex1.G)==memo.end()){ que.push(nex1); memo[nex1.G] = true; } if(memo.find(nex2.G)==memo.end()){ que.push(nex2); memo[nex2.G] = true; } } } return 0; }
### Prompt Generate a cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp // 2017/11/19 Tazoe #include <iostream> #include <queue> #include <string> #include <map> using namespace std; struct state{ string G; int N; }; bool is_over(string G) { bool flg = true; for(int i=1; i<G.size(); i++){ if(G[i]!=G[0]){ flg = false; break; } } return flg; } void DFS(char g[12][12], char F, char T, int x, int y) { if(g[y][x]!=F) return; g[y][x] = T; DFS(g, F, T, x-1, y); DFS(g, F, T, x+1, y); DFS(g, F, T, x, y-1); DFS(g, F, T, x, y+1); } string fill(string G, char C, int X, int Y) { char g[12][12]; for(int y=0; y<Y+2; y++){ for(int x=0; x<X+2; x++){ g[y][x] = 'N'; } } // ???????????????2?¬????????????? for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ g[y+1][x+1] = G[y*X+x]; } } DFS(g, G[0], C, 1, 1); // 2?¬???????????????????????????? for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ G[y*X+x] = g[y+1][x+1]; } } return G; } int main() { while(true){ int X, Y; cin >> X >> Y; if(X==0 && Y==0) break; string G = ""; for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ string c; cin >> c; G += c; } } queue<struct state> que; map<string, bool> memo; struct state now; now.G = G; now.N = 0; que.push(now); memo[now.G] = true; while(!que.empty()){ now = que.front(); que.pop(); if(is_over(now.G)){ cout << now.N << endl; break; } struct state nex1, nex2; if(now.G[0]=='R'){ nex1.G = fill(now.G, 'G', X, Y); nex2.G = fill(now.G, 'B', X, Y); nex1.N = nex2.N = now.N+1; } else if(now.G[0]=='G'){ nex1.G = fill(now.G, 'R', X, Y); nex2.G = fill(now.G, 'B', X, Y); nex1.N = nex2.N = now.N+1; } else if(now.G[0]=='B'){ nex1.G = fill(now.G, 'R', X, Y); nex2.G = fill(now.G, 'G', X, Y); nex1.N = nex2.N = now.N+1; } if(memo.find(nex1.G)==memo.end()){ que.push(nex1); memo[nex1.G] = true; } if(memo.find(nex2.G)==memo.end()){ que.push(nex2); memo[nex2.G] = true; } } } return 0; } ```
#include<iostream> #include<cstring> #include<queue> #define INF 20 int field_x, field_y; int res = INF; bool check(int field[10][10]){ int r = 0, g = 0, b = 0; for (int i = 0; i < field_y; i++){ for (int j = 0; j < field_x; j++){ field[i][j] == 0 ? r++ : field[i][j] == 1 ? g++ : b++; } } int a = field_x*field_y; if (r == a || g == a || b == a)return true; return false; } void bfs(int(&field)[10][10], int color){ bool used[10][10]; memset(used, false, sizeof(used)); int dx[] = { 1, 0, -1, 0 }, dy[] = { 0, 1, 0, -1 }; typedef std::pair<int, int> P; std::queue<P>q; q.push(P(0, 0)); used[0][0] = true; while (!q.empty()){ P p = q.front(); q.pop(); for (int i = 0; i < 4; i++){ int nx = p.first + dx[i], ny = p.second + dy[i]; if (0 <= nx&&nx < field_x && 0 <= ny&&ny < field_y&&!used[ny][nx] && field[ny][nx] == field[0][0]){ field[ny][nx] = color; q.push(P(nx, ny)); used[ny][nx] = true; } } } field[0][0] = color; } void calc(int field[10][10], int count){ if (check(field)){ res = count; return; } if (count >= res)return; for (int i = 0; i < 3; i++){ if (field[0][0] == i)continue; int copy_field[10][10]; memcpy(copy_field, field, sizeof(copy_field)); bfs(copy_field, i); calc(copy_field, count + 1); } } int main(){ while (std::cin >> field_x >> field_y, field_x || field_y){ int field[10][10]; for (int i = 0; i < field_y; i++){ for (int j = 0; j < field_x; j++){ char c; std::cin >> c; c == 'R' ? field[i][j] = 0 : c == 'G' ? field[i][j] = 1 : field[i][j] = 2; } } calc(field, 0); std::cout << res << std::endl; res = INF; } return 0; }
### Prompt Construct a cpp code solution to the problem outlined: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<cstring> #include<queue> #define INF 20 int field_x, field_y; int res = INF; bool check(int field[10][10]){ int r = 0, g = 0, b = 0; for (int i = 0; i < field_y; i++){ for (int j = 0; j < field_x; j++){ field[i][j] == 0 ? r++ : field[i][j] == 1 ? g++ : b++; } } int a = field_x*field_y; if (r == a || g == a || b == a)return true; return false; } void bfs(int(&field)[10][10], int color){ bool used[10][10]; memset(used, false, sizeof(used)); int dx[] = { 1, 0, -1, 0 }, dy[] = { 0, 1, 0, -1 }; typedef std::pair<int, int> P; std::queue<P>q; q.push(P(0, 0)); used[0][0] = true; while (!q.empty()){ P p = q.front(); q.pop(); for (int i = 0; i < 4; i++){ int nx = p.first + dx[i], ny = p.second + dy[i]; if (0 <= nx&&nx < field_x && 0 <= ny&&ny < field_y&&!used[ny][nx] && field[ny][nx] == field[0][0]){ field[ny][nx] = color; q.push(P(nx, ny)); used[ny][nx] = true; } } } field[0][0] = color; } void calc(int field[10][10], int count){ if (check(field)){ res = count; return; } if (count >= res)return; for (int i = 0; i < 3; i++){ if (field[0][0] == i)continue; int copy_field[10][10]; memcpy(copy_field, field, sizeof(copy_field)); bfs(copy_field, i); calc(copy_field, count + 1); } } int main(){ while (std::cin >> field_x >> field_y, field_x || field_y){ int field[10][10]; for (int i = 0; i < field_y; i++){ for (int j = 0; j < field_x; j++){ char c; std::cin >> c; c == 'R' ? field[i][j] = 0 : c == 'G' ? field[i][j] = 1 : field[i][j] = 2; } } calc(field, 0); std::cout << res << std::endl; res = INF; } return 0; } ```
#include<iostream> #include<cstring> #include<map> #include<string> #include<queue> #include<algorithm> #define fr first #define sc second using namespace std; int x, y; string m; bool used[16][16]; typedef pair<string, int> Pi; bool check(string s) { for(int i = 1;i < x * y; i++) if(s[0] != s[i]) return false; return true; } void change(int nx, int ny, char color, string &s) { if(used[nx][ny]) return; used[nx][ny] = true; if(ny + 1 < y && s[(ny + 1) * x + nx] == s[ny * x + nx]) change(nx, ny + 1, color, s); if(nx + 1 < x && s[ny * x + nx + 1] == s[ny * x + nx]) change(nx + 1, ny, color, s); if(ny - 1 >= 0 && s[(ny - 1) * x + nx] == s[ny * x + nx]) change(nx, ny - 1, color, s); if(nx - 1 >= 0 && s[ny * x + nx - 1] == s[ny * x + nx]) change(nx - 1, ny, color, s); s[ny * x + nx] = color; return; } int bfs() { queue<Pi> que; que.push(make_pair(m, 0)); while(true){ Pi p = que.front(); que.pop(); string s, t; s = t = p.fr; if(check(s)) return p.sc; if(s[0] != 'R'){ memset(used, false, sizeof(used)); change(0, 0, 'R', s); que.push(make_pair(s, p.sc + 1)); s = t; } if(s[0] != 'G'){ memset(used, false, sizeof(used)); change(0, 0, 'G', s); que.push(make_pair(s, p.sc + 1)); s = t; } if(s[0] != 'B'){ memset(used, false, sizeof(used)); change(0, 0, 'B', s); que.push(make_pair(s, p.sc + 1)); s = t; } } } int main(void) { string c; while(cin >> x >> y, x || y){ m = ""; for(int i = 0;i < x * y; i++){ cin >> c; m += c; } cout << bfs() << endl; } }
### Prompt Your challenge is to write a cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<cstring> #include<map> #include<string> #include<queue> #include<algorithm> #define fr first #define sc second using namespace std; int x, y; string m; bool used[16][16]; typedef pair<string, int> Pi; bool check(string s) { for(int i = 1;i < x * y; i++) if(s[0] != s[i]) return false; return true; } void change(int nx, int ny, char color, string &s) { if(used[nx][ny]) return; used[nx][ny] = true; if(ny + 1 < y && s[(ny + 1) * x + nx] == s[ny * x + nx]) change(nx, ny + 1, color, s); if(nx + 1 < x && s[ny * x + nx + 1] == s[ny * x + nx]) change(nx + 1, ny, color, s); if(ny - 1 >= 0 && s[(ny - 1) * x + nx] == s[ny * x + nx]) change(nx, ny - 1, color, s); if(nx - 1 >= 0 && s[ny * x + nx - 1] == s[ny * x + nx]) change(nx - 1, ny, color, s); s[ny * x + nx] = color; return; } int bfs() { queue<Pi> que; que.push(make_pair(m, 0)); while(true){ Pi p = que.front(); que.pop(); string s, t; s = t = p.fr; if(check(s)) return p.sc; if(s[0] != 'R'){ memset(used, false, sizeof(used)); change(0, 0, 'R', s); que.push(make_pair(s, p.sc + 1)); s = t; } if(s[0] != 'G'){ memset(used, false, sizeof(used)); change(0, 0, 'G', s); que.push(make_pair(s, p.sc + 1)); s = t; } if(s[0] != 'B'){ memset(used, false, sizeof(used)); change(0, 0, 'B', s); que.push(make_pair(s, p.sc + 1)); s = t; } } } int main(void) { string c; while(cin >> x >> y, x || y){ m = ""; for(int i = 0;i < x * y; i++){ cin >> c; m += c; } cout << bfs() << endl; } } ```
#include<bits/stdc++.h> using namespace std; int x,y; struct grid{ char c[11][11]; int count; char bf; /*void operator=(grid& g2){ this->count = g2.count; this->bf = g2.bf; for(int i=0;i<x;i++){ for(int j=0;j<y;j++){ this->c[i][j] = g2.c[i][j]; } } }*/ }; void DFS(grid& g,char base,char change,int xp,int yp){ if(xp<0 || yp<0 || xp >= x || yp >= y || g.c[xp][yp] != base){ return; } g.c[xp][yp] = change; DFS(g,base,change,xp+1,yp); DFS(g,base,change,xp,yp+1); DFS(g,base,change,xp-1,yp); DFS(g,base,change,xp,yp-1); } int main(){ while(1){ cin >> x >> y; if(x==0&&y==0) break; grid g; for(int i=0;i<y;i++){ for(int j=0;j<x;j++){ cin >> g.c[j][i]; } } g.count = 0; g.bf = g.c[0][0]; queue<grid> q; q.push(g); while(!q.empty()){ g = q.front(); q.pop(); bool flag = true; for(int i=0;i<y;i++){ for(int j=0;j<x;j++){ if(g.c[0][0] != g.c[j][i]){ flag = false; } } } if(flag){ cout << g.count << endl; break; } g.count++; grid tmp = g; if(tmp.bf != 'R'){ DFS(tmp,tmp.c[0][0],'R',0,0); tmp.bf = 'R'; q.push(tmp); tmp = g; } if(tmp.bf != 'G'){ DFS(tmp,tmp.c[0][0],'G',0,0); tmp.bf = 'G'; q.push(tmp); tmp = g; } if(tmp.bf != 'B'){ DFS(tmp,tmp.c[0][0],'B',0,0); tmp.bf = 'B'; q.push(tmp); } } } }
### Prompt Please create a solution in CPP to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int x,y; struct grid{ char c[11][11]; int count; char bf; /*void operator=(grid& g2){ this->count = g2.count; this->bf = g2.bf; for(int i=0;i<x;i++){ for(int j=0;j<y;j++){ this->c[i][j] = g2.c[i][j]; } } }*/ }; void DFS(grid& g,char base,char change,int xp,int yp){ if(xp<0 || yp<0 || xp >= x || yp >= y || g.c[xp][yp] != base){ return; } g.c[xp][yp] = change; DFS(g,base,change,xp+1,yp); DFS(g,base,change,xp,yp+1); DFS(g,base,change,xp-1,yp); DFS(g,base,change,xp,yp-1); } int main(){ while(1){ cin >> x >> y; if(x==0&&y==0) break; grid g; for(int i=0;i<y;i++){ for(int j=0;j<x;j++){ cin >> g.c[j][i]; } } g.count = 0; g.bf = g.c[0][0]; queue<grid> q; q.push(g); while(!q.empty()){ g = q.front(); q.pop(); bool flag = true; for(int i=0;i<y;i++){ for(int j=0;j<x;j++){ if(g.c[0][0] != g.c[j][i]){ flag = false; } } } if(flag){ cout << g.count << endl; break; } g.count++; grid tmp = g; if(tmp.bf != 'R'){ DFS(tmp,tmp.c[0][0],'R',0,0); tmp.bf = 'R'; q.push(tmp); tmp = g; } if(tmp.bf != 'G'){ DFS(tmp,tmp.c[0][0],'G',0,0); tmp.bf = 'G'; q.push(tmp); tmp = g; } if(tmp.bf != 'B'){ DFS(tmp,tmp.c[0][0],'B',0,0); tmp.bf = 'B'; q.push(tmp); } } } } ```
#include <bits/stdc++.h> 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,0,0}; static const int dy[]={0,0,1,-1}; static const char color[]={'R','G','B'}; int n,m; int changeV; char G[10][10]; bool used[10][10]; struct State{ int push; char grid[10][10]; State(){} State(int p, char g[][10]){ push = p; rep(i,n) rep(j,m) grid[i][j] = g[i][j]; } }; bool check(){ char tmp = G[0][0]; rep(i,n){ rep(j,m){ if(G[i][j]!=tmp) return false; } } return true; } void dfs(int x, int y, int idx){ used[x][y] = true; rep(k,4){ int nx = x + dx[k]; int ny = y + dy[k]; if(0<=nx&&nx<n && 0<=ny&&ny<m && G[x][y]==G[nx][ny] && !used[nx][ny]){ dfs(nx,ny,idx); } } G[x][y] = color[idx]; } int solve(){ queue<State> q; q.push(State(0,G)); while(!q.empty()){ State st = q.front(); q.pop(); rep(k,3){ if(st.grid[0][0]!=color[k]){ memcpy(G,st.grid,sizeof(G)); memset(used,false,sizeof(used)); dfs(0,0,k); if(check()) return st.push + 1; if(G[0][0]==G[0][1] || G[0][0]==G[1][0]){ q.push(State(st.push + 1, G)); } } } } return -1; } int main(){ while(cin >> m >> n && (n|m)){ rep(i,n){ rep(j,m){ cin >> G[i][j]; } } int ans = 0; if(!check()) ans = solve(); cout << ans << endl; } return 0; }
### Prompt Construct a cpp code solution to the problem outlined: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <bits/stdc++.h> 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,0,0}; static const int dy[]={0,0,1,-1}; static const char color[]={'R','G','B'}; int n,m; int changeV; char G[10][10]; bool used[10][10]; struct State{ int push; char grid[10][10]; State(){} State(int p, char g[][10]){ push = p; rep(i,n) rep(j,m) grid[i][j] = g[i][j]; } }; bool check(){ char tmp = G[0][0]; rep(i,n){ rep(j,m){ if(G[i][j]!=tmp) return false; } } return true; } void dfs(int x, int y, int idx){ used[x][y] = true; rep(k,4){ int nx = x + dx[k]; int ny = y + dy[k]; if(0<=nx&&nx<n && 0<=ny&&ny<m && G[x][y]==G[nx][ny] && !used[nx][ny]){ dfs(nx,ny,idx); } } G[x][y] = color[idx]; } int solve(){ queue<State> q; q.push(State(0,G)); while(!q.empty()){ State st = q.front(); q.pop(); rep(k,3){ if(st.grid[0][0]!=color[k]){ memcpy(G,st.grid,sizeof(G)); memset(used,false,sizeof(used)); dfs(0,0,k); if(check()) return st.push + 1; if(G[0][0]==G[0][1] || G[0][0]==G[1][0]){ q.push(State(st.push + 1, G)); } } } } return -1; } int main(){ while(cin >> m >> n && (n|m)){ rep(i,n){ rep(j,m){ cin >> G[i][j]; } } int ans = 0; if(!check()) ans = solve(); cout << ans << endl; } return 0; } ```
#include <iostream> #include <algorithm> #include <string> #include <vector> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <cmath> #include <cstdio> #define FOR(i, a, b) for(int i = (a); i < (b); i++) #define rep(i, n) for(int i = 0; i < (n); i++) #define MP make_pair #define X first #define Y second #define all(v) v.begin(), v.end() #define rev(v) v.rbegin(), v.rend() using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> P; const int INF = 1<<29; string col = "RGB"; int w, h; char v[11][11]; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; int best; int fill(char col){ queue<P> q; q.push(MP(0, 0)); char c = v[0][0]; int cnt = 0; while(!q.empty()){ P p = q.front(); q.pop(); if(v[p.Y][p.X] != c) continue; v[p.Y][p.X] = col; cnt++; rep(d, 4){ int nx = p.X + dx[d], ny = p.Y + dy[d]; if(nx < 0 || nx >= w || ny < 0 || ny >= h) continue; q.push(MP(nx, ny)); } } return cnt; } int visit[11][11]; int count(){ memset(visit, 0, sizeof(visit)); queue<P> q; q.push(MP(0, 0)); char c = v[0][0]; int cnt = 0; while(!q.empty()){ P p = q.front(); q.pop(); if(visit[p.Y][p.X]) continue; visit[p.Y][p.X] = 1; cnt++; rep(d, 4){ int nx = p.X + dx[d], ny = p.Y + dy[d]; if(nx < 0 || nx >= w || ny < 0 || ny >= h) continue; if(v[ny][nx] == c) q.push(MP(nx, ny)); } } return cnt; } int dfs(int cnt, int depth){ if(best <= depth) return INF; if(cnt == w*h) return best = depth; int res = INF; char c = v[0][0]; char tmp[11][11]; memcpy(tmp, v, sizeof(v)); rep(i, 3){ char next = col[(i+depth)%3]; if(c == next) continue; fill(next); int ncnt = count(); if(cnt != ncnt) res = min(res, dfs(ncnt, depth+1)); memcpy(v, tmp, sizeof(v)); } return res; } int main(void){ while(cin >> w >> h, w|h){ best = w+h; rep(i, h) rep(j, w) cin >> v[i][j]; cout << dfs(count(), 0) << endl; } return 0; }
### Prompt Construct a CPP code solution to the problem outlined: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <algorithm> #include <string> #include <vector> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <cmath> #include <cstdio> #define FOR(i, a, b) for(int i = (a); i < (b); i++) #define rep(i, n) for(int i = 0; i < (n); i++) #define MP make_pair #define X first #define Y second #define all(v) v.begin(), v.end() #define rev(v) v.rbegin(), v.rend() using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> P; const int INF = 1<<29; string col = "RGB"; int w, h; char v[11][11]; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; int best; int fill(char col){ queue<P> q; q.push(MP(0, 0)); char c = v[0][0]; int cnt = 0; while(!q.empty()){ P p = q.front(); q.pop(); if(v[p.Y][p.X] != c) continue; v[p.Y][p.X] = col; cnt++; rep(d, 4){ int nx = p.X + dx[d], ny = p.Y + dy[d]; if(nx < 0 || nx >= w || ny < 0 || ny >= h) continue; q.push(MP(nx, ny)); } } return cnt; } int visit[11][11]; int count(){ memset(visit, 0, sizeof(visit)); queue<P> q; q.push(MP(0, 0)); char c = v[0][0]; int cnt = 0; while(!q.empty()){ P p = q.front(); q.pop(); if(visit[p.Y][p.X]) continue; visit[p.Y][p.X] = 1; cnt++; rep(d, 4){ int nx = p.X + dx[d], ny = p.Y + dy[d]; if(nx < 0 || nx >= w || ny < 0 || ny >= h) continue; if(v[ny][nx] == c) q.push(MP(nx, ny)); } } return cnt; } int dfs(int cnt, int depth){ if(best <= depth) return INF; if(cnt == w*h) return best = depth; int res = INF; char c = v[0][0]; char tmp[11][11]; memcpy(tmp, v, sizeof(v)); rep(i, 3){ char next = col[(i+depth)%3]; if(c == next) continue; fill(next); int ncnt = count(); if(cnt != ncnt) res = min(res, dfs(ncnt, depth+1)); memcpy(v, tmp, sizeof(v)); } return res; } int main(void){ while(cin >> w >> h, w|h){ best = w+h; rep(i, h) rep(j, w) cin >> v[i][j]; cout << dfs(count(), 0) << endl; } return 0; } ```
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <map> #include <queue> #include <deque> #include <complex> #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define FORE(i,a,b) for(int i=(a);i<=(b);i++) #define REP(i,a) FOR(i,0,a) using namespace std; typedef complex<int> cl; const int dx[]={1,0,-1,0},dy[]={0,1,0,-1},INF=1<<30; const char color[]{'R','G','B'}; int x,y,W,H; char maps[10][10]={}; bool draw(bool same[10][10]){ bool searched[10][10]={}; bool ans=false; searched[0][0]=1; queue<cl> qu; qu.push(cl(0,0)); while(!qu.empty()){ int w=qu.front().real(),h=qu.front().imag(); qu.pop(); REP(i,4){ int nx=w+dx[i],ny=h+dy[i]; if(nx<W&&ny<H&&nx>=0&&ny>=0) if((maps[ny][nx]==maps[0][0]||same[ny][nx])&& !searched[ny][nx]){ if(!same[ny][nx]) ans=true; same[ny][nx]=true; qu.push(cl(nx,ny)); searched[ny][nx]=true; } } } return ans; } int search(bool chan[10][10],int minium=INF){ char f=maps[0][0]; bool ans=true; REP(i,y) REP(j,x) if(!chan[i][j]) ans=false; if(ans) return 0; if(minium==0) return 1; REP(i,3){ if(color[i]==maps[0][0]) continue; bool same[10][10]={}; REP(j,10) REP(k,10) same[j][k]=chan[j][k]; maps[0][0]=color[i]; if(draw(same)) minium=min(minium,search(same,minium-1)); maps[0][0]=f; } return minium+1; } int main() { // your code goes here while(cin >> x >> y && x){ W=x; H=y; REP(i,y) REP(j,x) cin >> maps[i][j]; bool chan[10][10]={}; chan[0][0]=1; draw(chan); cout << search(chan) << endl; } return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <vector> #include <string> #include <algorithm> #include <map> #include <queue> #include <deque> #include <complex> #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define FORE(i,a,b) for(int i=(a);i<=(b);i++) #define REP(i,a) FOR(i,0,a) using namespace std; typedef complex<int> cl; const int dx[]={1,0,-1,0},dy[]={0,1,0,-1},INF=1<<30; const char color[]{'R','G','B'}; int x,y,W,H; char maps[10][10]={}; bool draw(bool same[10][10]){ bool searched[10][10]={}; bool ans=false; searched[0][0]=1; queue<cl> qu; qu.push(cl(0,0)); while(!qu.empty()){ int w=qu.front().real(),h=qu.front().imag(); qu.pop(); REP(i,4){ int nx=w+dx[i],ny=h+dy[i]; if(nx<W&&ny<H&&nx>=0&&ny>=0) if((maps[ny][nx]==maps[0][0]||same[ny][nx])&& !searched[ny][nx]){ if(!same[ny][nx]) ans=true; same[ny][nx]=true; qu.push(cl(nx,ny)); searched[ny][nx]=true; } } } return ans; } int search(bool chan[10][10],int minium=INF){ char f=maps[0][0]; bool ans=true; REP(i,y) REP(j,x) if(!chan[i][j]) ans=false; if(ans) return 0; if(minium==0) return 1; REP(i,3){ if(color[i]==maps[0][0]) continue; bool same[10][10]={}; REP(j,10) REP(k,10) same[j][k]=chan[j][k]; maps[0][0]=color[i]; if(draw(same)) minium=min(minium,search(same,minium-1)); maps[0][0]=f; } return minium+1; } int main() { // your code goes here while(cin >> x >> y && x){ W=x; H=y; REP(i,y) REP(j,x) cin >> maps[i][j]; bool chan[10][10]={}; chan[0][0]=1; draw(chan); cout << search(chan) << endl; } return 0; } ```
#include<cstdio> #include<cstring> #include<algorithm> #include<string> #include<queue> #define rep(i,a) for( int i = 0; i != (a); ++i ) const std::string RGB = "RGB"; int x, y; short fld[10][10]; struct State { short st[10][10]; int cnt; State( short fld[10][10], int cnt ) : cnt( cnt ) { rep( i, y ) rep( j, x ) st[i][j] = fld[i][j]; } }; void paint( int px, int py, int prvc, int c ) { static const int dx[4] = { 0, 1, 0, -1 }, dy[4] = { -1, 0, 1, 0 }; if( fld[py][px] != prvc ) return; fld[py][px] = c; rep( i, 4 ) { int nx = px+dx[i], ny = py+dy[i]; if( nx >= 0 && nx < x && ny >= 0 && ny < y && fld[ny][nx] == prvc ) paint( nx, ny, prvc, c ); } return; } int main() { while( scanf( "%d%d", &x, &y ), x|y ) { rep( i, y ) { rep( j, x ) { char ch[2]; scanf( "%s", ch ); fld[i][j] = RGB.find( ch ); } } std::queue<State> que; for( que.push( State( fld, 0 ) ); !que.empty(); que.pop() ) { State s = que.front(); bool fl = true; rep( i, y ) { rep( j, x ) { fl &= s.st[i][j] == s.st[0][0]; fld[i][j] = s.st[i][j]; } } if( fl ) { printf( "%d\n", s.cnt ); break; } rep( c, 3 ) { if( c == **s.st ) continue; if( c ) memcpy( fld, s.st, sizeof( fld ) ); paint( 0, 0, **fld, c ); que.push( State( fld, s.cnt+1 ) ); } } } return 0; }
### Prompt In cpp, your task is to solve the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<cstdio> #include<cstring> #include<algorithm> #include<string> #include<queue> #define rep(i,a) for( int i = 0; i != (a); ++i ) const std::string RGB = "RGB"; int x, y; short fld[10][10]; struct State { short st[10][10]; int cnt; State( short fld[10][10], int cnt ) : cnt( cnt ) { rep( i, y ) rep( j, x ) st[i][j] = fld[i][j]; } }; void paint( int px, int py, int prvc, int c ) { static const int dx[4] = { 0, 1, 0, -1 }, dy[4] = { -1, 0, 1, 0 }; if( fld[py][px] != prvc ) return; fld[py][px] = c; rep( i, 4 ) { int nx = px+dx[i], ny = py+dy[i]; if( nx >= 0 && nx < x && ny >= 0 && ny < y && fld[ny][nx] == prvc ) paint( nx, ny, prvc, c ); } return; } int main() { while( scanf( "%d%d", &x, &y ), x|y ) { rep( i, y ) { rep( j, x ) { char ch[2]; scanf( "%s", ch ); fld[i][j] = RGB.find( ch ); } } std::queue<State> que; for( que.push( State( fld, 0 ) ); !que.empty(); que.pop() ) { State s = que.front(); bool fl = true; rep( i, y ) { rep( j, x ) { fl &= s.st[i][j] == s.st[0][0]; fld[i][j] = s.st[i][j]; } } if( fl ) { printf( "%d\n", s.cnt ); break; } rep( c, 3 ) { if( c == **s.st ) continue; if( c ) memcpy( fld, s.st, sizeof( fld ) ); paint( 0, 0, **fld, c ); que.push( State( fld, s.cnt+1 ) ); } } } return 0; } ```
#include <iostream> #include <vector> #include <string> #include <map> #include <algorithm> using namespace std; typedef pair<int,int> P; const int MAX_W = 10; int w, h, ans; bool memo[MAX_W][MAX_W]; int dx[4] = {0,0,-1,1}; int dy[4] = {-1,1,0,0}; char C[3] = {'R','G','B'}; int c_to_n[256] = {0}; void debug(vector<string>& v, vector<string>& v_, int cnt=0){ cout << "[debug] cnt:" << cnt-1 << " -> " << cnt << endl; cout << "before:" << endl; for(int y=0 ; y < h ; y++ ){ cout << v[y] << endl; } cout << "after:" << endl; for(int y=0 ; y < h ; y++ ){ cout << v_[y] << endl; } cout << endl; } bool check(vector<string>& v, char c){ for(int y=0 ; y < h ; y++ ){ for(int x=0 ; x < w ; x++ ){ if( v[y][x] != c ){ return false; } } } return true; } void dfs(int x, int y, char c, vector<string>& v, vector<P>& vp){ memo[y][x] = true; if( v[y][x] == c ){ vp.push_back( P(x,y) ); } for(int i=0 ; i < 4 ; i++ ){ int mx = x + dx[i]; int my = y + dy[i]; if( mx < 0 || my < 0 || w <= mx || h <= my ) continue; if( !memo[my][mx] && v[my][mx] == c ){ dfs(mx,my,c,v,vp); } } } void solve(vector<string>& v, int cnt){ if( ans < cnt ) return; if( check(v,v[0][0]) ){ ans = min( ans , cnt ); return ; } for(int y=0 ; y < h ; y++ ){ for(int x=0 ; x < w ; x++ ){ memo[y][x] = false; } } vector<P> vp; dfs(0,0,v[0][0],v,vp); bool color[3] = {false}; for(int i=0 ; i < vp.size() ; i++ ){ for(int j=0 ; j < 4 ; j++ ){ int mx = vp[i].first + dx[j]; int my = vp[i].second + dy[j]; if( mx < 0 || my < 0 || w <= mx || h <= my ) continue; if( v[0][0] == v[my][mx] ) continue; color[ c_to_n[v[my][mx]] ] = true; if( (color[0] && color[1]) || (color[0] && color[2]) || (color[1] && color[2]) ){ break; } } if( (color[0] && color[1]) || (color[0] && color[2]) || (color[1] && color[2]) ){ break; } } for(int i=0 ; i < 3 ; i++ ){ if( !color[i] ) continue; //if( v[0][0] == C[i] ) continue; vector<string> next = v; for(int j=0 ; j < vp.size() ; j++ ){ next[ vp[j].second ][ vp[j].first ] = C[i]; } if( cnt+1 <= ans ){ //debug(v,next,cnt+1); solve(next,cnt+1); } } } int main(){ c_to_n['R'] = 0; c_to_n['G'] = 1; c_to_n['B'] = 2; while( cin >> w >> h , w || h ){ vector<string> v(h); for(int y=0 ; y < h ; y++ ){ v[y] = string(w,' '); for(int x=0 ; x < w ; x++ ){ cin >> v[y][x]; } } ans = min(w*h-1,17); solve(v,0); cout << ans << endl; } }
### Prompt Create a solution in cpp for the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <vector> #include <string> #include <map> #include <algorithm> using namespace std; typedef pair<int,int> P; const int MAX_W = 10; int w, h, ans; bool memo[MAX_W][MAX_W]; int dx[4] = {0,0,-1,1}; int dy[4] = {-1,1,0,0}; char C[3] = {'R','G','B'}; int c_to_n[256] = {0}; void debug(vector<string>& v, vector<string>& v_, int cnt=0){ cout << "[debug] cnt:" << cnt-1 << " -> " << cnt << endl; cout << "before:" << endl; for(int y=0 ; y < h ; y++ ){ cout << v[y] << endl; } cout << "after:" << endl; for(int y=0 ; y < h ; y++ ){ cout << v_[y] << endl; } cout << endl; } bool check(vector<string>& v, char c){ for(int y=0 ; y < h ; y++ ){ for(int x=0 ; x < w ; x++ ){ if( v[y][x] != c ){ return false; } } } return true; } void dfs(int x, int y, char c, vector<string>& v, vector<P>& vp){ memo[y][x] = true; if( v[y][x] == c ){ vp.push_back( P(x,y) ); } for(int i=0 ; i < 4 ; i++ ){ int mx = x + dx[i]; int my = y + dy[i]; if( mx < 0 || my < 0 || w <= mx || h <= my ) continue; if( !memo[my][mx] && v[my][mx] == c ){ dfs(mx,my,c,v,vp); } } } void solve(vector<string>& v, int cnt){ if( ans < cnt ) return; if( check(v,v[0][0]) ){ ans = min( ans , cnt ); return ; } for(int y=0 ; y < h ; y++ ){ for(int x=0 ; x < w ; x++ ){ memo[y][x] = false; } } vector<P> vp; dfs(0,0,v[0][0],v,vp); bool color[3] = {false}; for(int i=0 ; i < vp.size() ; i++ ){ for(int j=0 ; j < 4 ; j++ ){ int mx = vp[i].first + dx[j]; int my = vp[i].second + dy[j]; if( mx < 0 || my < 0 || w <= mx || h <= my ) continue; if( v[0][0] == v[my][mx] ) continue; color[ c_to_n[v[my][mx]] ] = true; if( (color[0] && color[1]) || (color[0] && color[2]) || (color[1] && color[2]) ){ break; } } if( (color[0] && color[1]) || (color[0] && color[2]) || (color[1] && color[2]) ){ break; } } for(int i=0 ; i < 3 ; i++ ){ if( !color[i] ) continue; //if( v[0][0] == C[i] ) continue; vector<string> next = v; for(int j=0 ; j < vp.size() ; j++ ){ next[ vp[j].second ][ vp[j].first ] = C[i]; } if( cnt+1 <= ans ){ //debug(v,next,cnt+1); solve(next,cnt+1); } } } int main(){ c_to_n['R'] = 0; c_to_n['G'] = 1; c_to_n['B'] = 2; while( cin >> w >> h , w || h ){ vector<string> v(h); for(int y=0 ; y < h ; y++ ){ v[y] = string(w,' '); for(int x=0 ; x < w ; x++ ){ cin >> v[y][x]; } } ans = min(w*h-1,17); solve(v,0); cout << ans << endl; } } ```
#include<iostream> #include<algorithm> #include<queue> #include<map> using namespace std; typedef pair<int, int> P; #define INF (1 << 30) int nowmax = INF, x, y; char c; int come[10][10]; int xs[] = {1, 0, -1, 0}, ys[] = {0, 1, 0, -1}; int dfs(int color[][10], int count = 0){ int res = nowmax; if(count >= res)return INF; for(int i = 0;i < 3;i++){ if(i == color[0][0])continue; int tmp[10][10]; int done = 1; for(int j = 0;j < y;j++) for(int k = 0;k < x;k++){ tmp[j][k] = color[j][k]; if(tmp[j][k] != color[0][0])done = 0; come[j][k] = 0; } if(done){ nowmax = min(nowmax, count); return count; } queue<P> q; q.push(P(0, 0)); int ok = 0; while(!q.empty()){ for(int j = q.size();j > 0;j--){ P t = q.front();q.pop(); int a = t.first, b = t.second; if(come[a][b])continue;come[a][b] = 1; if(tmp[a][b] == i)ok = 1; if(tmp[a][b] != color[0][0])continue; tmp[a][b] = i; for(int k = 0;k < 4;k++){ int tx = b + xs[k], ty = a + ys[k]; if(tx < 0 || tx >= x || ty < 0 || ty >= y)continue; q.push(P(ty, tx)); } } } if(ok){ res = min(res, dfs(tmp, count + 1)); nowmax = min(res, nowmax); } } return res; } int main(){ int color[10][10]; while(cin >> x >> y, x|y){ for(int i = 0;i < y;i++) for(int j = 0;j < x;j++){ cin >> c; if(c == 'R')color[i][j] = 0; if(c == 'G')color[i][j] = 1; if(c == 'B')color[i][j] = 2; } nowmax = INF; cout << dfs(color) << endl; } return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<algorithm> #include<queue> #include<map> using namespace std; typedef pair<int, int> P; #define INF (1 << 30) int nowmax = INF, x, y; char c; int come[10][10]; int xs[] = {1, 0, -1, 0}, ys[] = {0, 1, 0, -1}; int dfs(int color[][10], int count = 0){ int res = nowmax; if(count >= res)return INF; for(int i = 0;i < 3;i++){ if(i == color[0][0])continue; int tmp[10][10]; int done = 1; for(int j = 0;j < y;j++) for(int k = 0;k < x;k++){ tmp[j][k] = color[j][k]; if(tmp[j][k] != color[0][0])done = 0; come[j][k] = 0; } if(done){ nowmax = min(nowmax, count); return count; } queue<P> q; q.push(P(0, 0)); int ok = 0; while(!q.empty()){ for(int j = q.size();j > 0;j--){ P t = q.front();q.pop(); int a = t.first, b = t.second; if(come[a][b])continue;come[a][b] = 1; if(tmp[a][b] == i)ok = 1; if(tmp[a][b] != color[0][0])continue; tmp[a][b] = i; for(int k = 0;k < 4;k++){ int tx = b + xs[k], ty = a + ys[k]; if(tx < 0 || tx >= x || ty < 0 || ty >= y)continue; q.push(P(ty, tx)); } } } if(ok){ res = min(res, dfs(tmp, count + 1)); nowmax = min(res, nowmax); } } return res; } int main(){ int color[10][10]; while(cin >> x >> y, x|y){ for(int i = 0;i < y;i++) for(int j = 0;j < x;j++){ cin >> c; if(c == 'R')color[i][j] = 0; if(c == 'G')color[i][j] = 1; if(c == 'B')color[i][j] = 2; } nowmax = INF; cout << dfs(color) << endl; } return 0; } ```
#include <iostream> #include <algorithm> #include <queue> using namespace std; int xsize, ysize; char G[10][10]; bool used[10][10]; const char color[] = {'R', 'G', 'B'}; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; struct State { int push; char grid[10][10]; State(){}; State(int p, char g[][10]){ push = p; for(int i = 0; i < ysize; ++i){ for(int j = 0; j < xsize; ++j){ grid[j][i] = g[j][i]; } } } }; bool check(){ char tmp = G[0][0]; for(int i = 0; i < ysize; ++i){ for(int j = 0; j < xsize; ++j){ if(G[j][i] != tmp) return false; } } return true; } void dfs(int x, int y, int idx){ used[x][y] = true; for(int k = 0; k < 4; ++k){ int nx = x + dx[k]; int ny = y + dy[k]; if(0 <= nx && nx < xsize && 0 <= ny && ny < ysize && G[x][y] == G[nx][ny] && !used[nx][ny]){ dfs(nx, ny, idx); } } G[x][y] = color[idx]; } int main(){ cin.tie(0); ios::sync_with_stdio(false); while(cin >> xsize >> ysize && (xsize || ysize)){ for(int i = 0; i < ysize; ++i){ for(int j = 0; j < xsize; ++j){ cin >> G[j][i]; } } int ans = 0; if(!check()){ queue<State> q; q.push(State(0, G)); while(!q.empty() && ans == 0){ State st = q.front(); q.pop(); for(int k = 0; k < 3; ++k){ if(st.grid[0][0] != color[k]){ for(int i = 0; i < ysize; ++i){ for(int j = 0; j < xsize; ++j){ G[j][i] = st.grid[j][i]; used[j][i] = false; } } dfs(0, 0, k); if(check()){ ans = st.push + 1; break; } if(G[0][0] == G[0][1] || G[0][0] == G[1][0]){ q.push(State(st.push + 1, G)); } } } } } cout << ans << endl; } return 0; }
### Prompt Your challenge is to write a Cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <algorithm> #include <queue> using namespace std; int xsize, ysize; char G[10][10]; bool used[10][10]; const char color[] = {'R', 'G', 'B'}; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; struct State { int push; char grid[10][10]; State(){}; State(int p, char g[][10]){ push = p; for(int i = 0; i < ysize; ++i){ for(int j = 0; j < xsize; ++j){ grid[j][i] = g[j][i]; } } } }; bool check(){ char tmp = G[0][0]; for(int i = 0; i < ysize; ++i){ for(int j = 0; j < xsize; ++j){ if(G[j][i] != tmp) return false; } } return true; } void dfs(int x, int y, int idx){ used[x][y] = true; for(int k = 0; k < 4; ++k){ int nx = x + dx[k]; int ny = y + dy[k]; if(0 <= nx && nx < xsize && 0 <= ny && ny < ysize && G[x][y] == G[nx][ny] && !used[nx][ny]){ dfs(nx, ny, idx); } } G[x][y] = color[idx]; } int main(){ cin.tie(0); ios::sync_with_stdio(false); while(cin >> xsize >> ysize && (xsize || ysize)){ for(int i = 0; i < ysize; ++i){ for(int j = 0; j < xsize; ++j){ cin >> G[j][i]; } } int ans = 0; if(!check()){ queue<State> q; q.push(State(0, G)); while(!q.empty() && ans == 0){ State st = q.front(); q.pop(); for(int k = 0; k < 3; ++k){ if(st.grid[0][0] != color[k]){ for(int i = 0; i < ysize; ++i){ for(int j = 0; j < xsize; ++j){ G[j][i] = st.grid[j][i]; used[j][i] = false; } } dfs(0, 0, k); if(check()){ ans = st.push + 1; break; } if(G[0][0] == G[0][1] || G[0][0] == G[1][0]){ q.push(State(st.push + 1, G)); } } } } } cout << ans << endl; } return 0; } ```
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; const ld eps = 1e-9; //// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\b.txt" struct aa { vector<vector<char>>field; int time; }; const int dx[4] = { -1,0,1,0 }; const int dy[4] = { 0,1,0,-1 }; int W, H; vector<vector<char>>ch_color(vector<vector<char>>&field, int nextco) { queue<pair<int, int>>que; vector<vector<char>>nextfield(field); que.push(make_pair(0, 0)); vector<vector<int>>memo(H, vector<int>(W)); int fromco = field[0][0]; nextfield[0][0] = nextco; while (!que.empty()) { auto p(que.front()); que.pop(); for (int way = 0; way < 4; ++way) { const int nextx = p.first + dx[way]; const int nexty = p.second + dy[way]; if (nextx >= 0 && nextx < W&&nexty >= 0 && nexty < H) { if (memo[nexty][nextx])continue; else { memo[nexty][nextx] = true; if (field[nexty][nextx] == fromco) { nextfield[nexty][nextx] = nextco; que.push(make_pair(nextx, nexty)); } else { } } } } } return nextfield; } int main() { while (1) { cin >> W >> H; if (!W)break; queue<aa>que; set < vector<vector<char>>>aset; { vector<vector<char>>field(H, vector<char>(W)); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { char c; cin >> c; if (c == 'R')field[i][j] = 0; else if (c == 'B')field[i][j] = 1; else field[i][j] = 2; } } que.push(aa{ field,0 }); aset.emplace(field); } int ans; while (!que.empty()) { aa atop(que.front()); auto afield(atop.field); bool ok = true; for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (atop.field[i][j] != atop.field[0][0])ok = false; } } if (ok) { ans = atop.time; break; } que.pop(); for (int co = 0; co < 3; ++co) { if (co == afield[0][0])continue; else { vector<vector<char>>nextfield(ch_color(afield, co)); if (aset.find(nextfield) == aset.end()) { aset.emplace(nextfield); que.push(aa{ nextfield,atop.time + 1 }); } } } } cout << ans << endl; } return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; const ld eps = 1e-9; //// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\b.txt" struct aa { vector<vector<char>>field; int time; }; const int dx[4] = { -1,0,1,0 }; const int dy[4] = { 0,1,0,-1 }; int W, H; vector<vector<char>>ch_color(vector<vector<char>>&field, int nextco) { queue<pair<int, int>>que; vector<vector<char>>nextfield(field); que.push(make_pair(0, 0)); vector<vector<int>>memo(H, vector<int>(W)); int fromco = field[0][0]; nextfield[0][0] = nextco; while (!que.empty()) { auto p(que.front()); que.pop(); for (int way = 0; way < 4; ++way) { const int nextx = p.first + dx[way]; const int nexty = p.second + dy[way]; if (nextx >= 0 && nextx < W&&nexty >= 0 && nexty < H) { if (memo[nexty][nextx])continue; else { memo[nexty][nextx] = true; if (field[nexty][nextx] == fromco) { nextfield[nexty][nextx] = nextco; que.push(make_pair(nextx, nexty)); } else { } } } } } return nextfield; } int main() { while (1) { cin >> W >> H; if (!W)break; queue<aa>que; set < vector<vector<char>>>aset; { vector<vector<char>>field(H, vector<char>(W)); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { char c; cin >> c; if (c == 'R')field[i][j] = 0; else if (c == 'B')field[i][j] = 1; else field[i][j] = 2; } } que.push(aa{ field,0 }); aset.emplace(field); } int ans; while (!que.empty()) { aa atop(que.front()); auto afield(atop.field); bool ok = true; for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (atop.field[i][j] != atop.field[0][0])ok = false; } } if (ok) { ans = atop.time; break; } que.pop(); for (int co = 0; co < 3; ++co) { if (co == afield[0][0])continue; else { vector<vector<char>>nextfield(ch_color(afield, co)); if (aset.find(nextfield) == aset.end()) { aset.emplace(nextfield); que.push(aa{ nextfield,atop.time + 1 }); } } } } cout << ans << endl; } return 0; } ```
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Info{ char map[10][10]; }; struct Data{ Data(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; char base_map[10][10]; bool FLG; char to_color[3] = {'R','G','B'}; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void back_track(Info info,int depth,int max_depth){ if(FLG)return; if(depth == max_depth){ bool is_cleared = true; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ if(info.map[row][col] != info.map[0][0]){ is_cleared = false; break; } } if(!is_cleared)break; } if(is_cleared){ FLG = true; } return; } char pre_color = info.map[0][0]; queue<Data> Q; int adj_row,adj_col; for(int loop = 0; loop < 3; loop++){ if(to_color[loop] == pre_color)continue; Info next_info; for(int row = 0;row < H; row++){ for(int col = 0; col < W; col++){ next_info.map[row][col] = info.map[row][col]; } } next_info.map[0][0] = to_color[loop]; Q.push(Data(0,0)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ adj_row = Q.front().row + diff_row[i]; adj_col = Q.front().col + diff_col[i]; if(!rangeCheck(adj_row,adj_col))continue; if(next_info.map[adj_row][adj_col] == pre_color){ next_info.map[adj_row][adj_col] = to_color[loop]; Q.push(Data(adj_row,adj_col)); } } Q.pop(); } back_track(next_info,depth+1,max_depth); } } void func(){ char buf[2]; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ scanf("%s",buf); base_map[row][col] = buf[0]; } } FLG = false; int ans = 0; for(int i = 0; ; i++){ Info info; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ info.map[row][col] = base_map[row][col]; } } back_track(info,0,i); if(FLG){ ans = i; break; } } printf("%d\n",ans); } int main(){ while(true){ scanf("%d %d",&W,&H); if(W == 0 && H == 0)break; func(); } return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Info{ char map[10][10]; }; struct Data{ Data(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; char base_map[10][10]; bool FLG; char to_color[3] = {'R','G','B'}; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void back_track(Info info,int depth,int max_depth){ if(FLG)return; if(depth == max_depth){ bool is_cleared = true; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ if(info.map[row][col] != info.map[0][0]){ is_cleared = false; break; } } if(!is_cleared)break; } if(is_cleared){ FLG = true; } return; } char pre_color = info.map[0][0]; queue<Data> Q; int adj_row,adj_col; for(int loop = 0; loop < 3; loop++){ if(to_color[loop] == pre_color)continue; Info next_info; for(int row = 0;row < H; row++){ for(int col = 0; col < W; col++){ next_info.map[row][col] = info.map[row][col]; } } next_info.map[0][0] = to_color[loop]; Q.push(Data(0,0)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ adj_row = Q.front().row + diff_row[i]; adj_col = Q.front().col + diff_col[i]; if(!rangeCheck(adj_row,adj_col))continue; if(next_info.map[adj_row][adj_col] == pre_color){ next_info.map[adj_row][adj_col] = to_color[loop]; Q.push(Data(adj_row,adj_col)); } } Q.pop(); } back_track(next_info,depth+1,max_depth); } } void func(){ char buf[2]; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ scanf("%s",buf); base_map[row][col] = buf[0]; } } FLG = false; int ans = 0; for(int i = 0; ; i++){ Info info; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ info.map[row][col] = base_map[row][col]; } } back_track(info,0,i); if(FLG){ ans = i; break; } } printf("%d\n",ans); } int main(){ while(true){ scanf("%d %d",&W,&H); if(W == 0 && H == 0)break; func(); } return 0; } ```
#include<bits/stdc++.h> using namespace std; char fie[11][11]; bool used[11][11]; int X,Y; inline bool check(){ char c = fie[0][0]; for(int i=0;i<Y;i++) for(int j=0;j<X;j++) if( fie[j][i] != c ) return false; return true; } inline void temp(int (*tmp)[11] ){ for(int i=0;i<Y;i++) for(int j=0;j<X;j++) tmp[j][i] = fie[j][i]; } inline void rev(int (*tmp)[11] ){ for(int i=0;i<Y;i++) for(int j=0;j<X;j++) fie[j][i] = tmp[j][i]; } int dx[]={1,0,0,-1}; int dy[]={0,1,-1,0}; char dc[]="RGB"; inline bool zch(int x,int y){ return x < 0 || y < 0 || x >= X || y >= Y || used[x][y]; } inline bool ume(int x,int y,char c){ if( used[x][y] ) return false; used[x][y] = true; bool f = false; for(int i=0;i<4;i++){ int nx = x + dx[i], ny = y + dy[i]; if( zch( nx, ny ) ) continue; if( fie[nx][ny] == fie[x][y] ) f |= ume( nx,ny,c ); else if( fie[nx][ny] == c ) f = true; } fie[x][y] = c; return f; } inline void view(){ cout << "view" << endl; for(int i=0;i<Y;i++){ for(int j=0;j<X;j++) cout << fie[j][i]; cout << endl; } } int ans; inline int solve(int res){ if( ans == res ) return 0; if( check() ) { ans = res; return 0; } char c = fie[0][0]; int tmp[11][11]; temp(tmp); for(int i=0;i<3;i++){ if( dc[i] == c ) continue; memset(used,0,sizeof(used)); if( ume(0,0,dc[i]) ) solve(res+1); rev(tmp); } return res; } int main(){ while(cin >> X >> Y&&(X|Y) ){ for(int i=0;i<Y;i++) for(int j=0;j<X;j++) cin >> fie[j][i]; ans = 50; solve(0); cout << ans << endl; } }
### Prompt Your challenge is to write a Cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<bits/stdc++.h> using namespace std; char fie[11][11]; bool used[11][11]; int X,Y; inline bool check(){ char c = fie[0][0]; for(int i=0;i<Y;i++) for(int j=0;j<X;j++) if( fie[j][i] != c ) return false; return true; } inline void temp(int (*tmp)[11] ){ for(int i=0;i<Y;i++) for(int j=0;j<X;j++) tmp[j][i] = fie[j][i]; } inline void rev(int (*tmp)[11] ){ for(int i=0;i<Y;i++) for(int j=0;j<X;j++) fie[j][i] = tmp[j][i]; } int dx[]={1,0,0,-1}; int dy[]={0,1,-1,0}; char dc[]="RGB"; inline bool zch(int x,int y){ return x < 0 || y < 0 || x >= X || y >= Y || used[x][y]; } inline bool ume(int x,int y,char c){ if( used[x][y] ) return false; used[x][y] = true; bool f = false; for(int i=0;i<4;i++){ int nx = x + dx[i], ny = y + dy[i]; if( zch( nx, ny ) ) continue; if( fie[nx][ny] == fie[x][y] ) f |= ume( nx,ny,c ); else if( fie[nx][ny] == c ) f = true; } fie[x][y] = c; return f; } inline void view(){ cout << "view" << endl; for(int i=0;i<Y;i++){ for(int j=0;j<X;j++) cout << fie[j][i]; cout << endl; } } int ans; inline int solve(int res){ if( ans == res ) return 0; if( check() ) { ans = res; return 0; } char c = fie[0][0]; int tmp[11][11]; temp(tmp); for(int i=0;i<3;i++){ if( dc[i] == c ) continue; memset(used,0,sizeof(used)); if( ume(0,0,dc[i]) ) solve(res+1); rev(tmp); } return res; } int main(){ while(cin >> X >> Y&&(X|Y) ){ for(int i=0;i<Y;i++) for(int j=0;j<X;j++) cin >> fie[j][i]; ans = 50; solve(0); cout << ans << endl; } } ```
#include<stdio.h> #include<iostream> #include<memory.h> using namespace std ; int W , H ; char table[12][12] ; char C[] = {'R','G','B'} ; int dx[] = {-1,0,1,0} ; int dy[] = {0,-1,0,1} ; int Ans ; bool Check( char x[][12] ){ char d = x[0][0] ; for( int i=0 ; i<H ; i++ ){ for( int j=0 ; j<W ; j++ ){ if( d != x[i][j] ) return false ; } } return true ; } bool Range( int X , int Y , int k ){ if( Y+dy[k] < 0 || Y+dy[k] >= H || X+dx[k] < 0 || X+dx[k] >= W ){ return false ; }return true ; } void Change( int X , int Y , char Color , char P[][12] ){ int b = P[Y][X] ; P[Y][X] = Color ; for( int k=0 ; k<4 ; k++ ){ if( Range(X,Y,k) && P[Y+dy[k]][X+dx[k]] == b ){ Change( X+dx[k] , Y+dy[k] , Color , P ) ; } } } void Copy( char A[][12] , char B[][12] ){ for( int i=0 ; i<H ; i++ ){ for( int j=0 ; j<W ; j++ ){ A[i][j] = B[i][j] ; } } } void Search( char P[][12] , int cnt , int g ){ if( Check(P) ){ if( Ans==-1 || Ans > cnt ) Ans = cnt ; } if( Ans != -1 && Ans <= cnt+1 ) return ; char tmp[12][12] ; Copy( tmp , P ) ; for( int i=0 ; i<3 ; i++ ){ if( P[0][0] != C[(g+i)%3] ){ Change( 0 , 0 , C[(g+i)%3] , P ) ; Search( P , cnt+1 , (g+i)%3 ) ; Copy( P , tmp ) ; } } } int main(){ while( cin >> W >> H , W+H ){ for( int i=0 ; i<H ; i++ ){ for( int j=0 ; j<W ; j++ ){ cin >> table[i][j] ; } } Ans = -1 ; Search(table,0,0) ; cout << Ans << endl ; } return 0; }
### Prompt In Cpp, your task is to solve the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<stdio.h> #include<iostream> #include<memory.h> using namespace std ; int W , H ; char table[12][12] ; char C[] = {'R','G','B'} ; int dx[] = {-1,0,1,0} ; int dy[] = {0,-1,0,1} ; int Ans ; bool Check( char x[][12] ){ char d = x[0][0] ; for( int i=0 ; i<H ; i++ ){ for( int j=0 ; j<W ; j++ ){ if( d != x[i][j] ) return false ; } } return true ; } bool Range( int X , int Y , int k ){ if( Y+dy[k] < 0 || Y+dy[k] >= H || X+dx[k] < 0 || X+dx[k] >= W ){ return false ; }return true ; } void Change( int X , int Y , char Color , char P[][12] ){ int b = P[Y][X] ; P[Y][X] = Color ; for( int k=0 ; k<4 ; k++ ){ if( Range(X,Y,k) && P[Y+dy[k]][X+dx[k]] == b ){ Change( X+dx[k] , Y+dy[k] , Color , P ) ; } } } void Copy( char A[][12] , char B[][12] ){ for( int i=0 ; i<H ; i++ ){ for( int j=0 ; j<W ; j++ ){ A[i][j] = B[i][j] ; } } } void Search( char P[][12] , int cnt , int g ){ if( Check(P) ){ if( Ans==-1 || Ans > cnt ) Ans = cnt ; } if( Ans != -1 && Ans <= cnt+1 ) return ; char tmp[12][12] ; Copy( tmp , P ) ; for( int i=0 ; i<3 ; i++ ){ if( P[0][0] != C[(g+i)%3] ){ Change( 0 , 0 , C[(g+i)%3] , P ) ; Search( P , cnt+1 , (g+i)%3 ) ; Copy( P , tmp ) ; } } } int main(){ while( cin >> W >> H , W+H ){ for( int i=0 ; i<H ; i++ ){ for( int j=0 ; j<W ; j++ ){ cin >> table[i][j] ; } } Ans = -1 ; Search(table,0,0) ; cout << Ans << endl ; } return 0; } ```
#include <cstdio> #include <cstdlib> #include <cstring> #include <climits> #include <cmath> #include <cassert> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <numeric> #include <complex> #include <list> #include <stack> #include <queue> #include <set> #include <map> #include <bitset> #include <utility> #include <functional> #include <iterator> using namespace std; #define dump(n) cerr<<"# "<<#n<<"="<<(n)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define iter(c) __typeof__((c).begin()) #define foreach(i,c) for(iter(c) i=(c).begin();i!=(c).end();++i) #define all(c) (c).begin(),(c).end() #define mp make_pair typedef unsigned int uint; typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<string> vs; typedef pair<int,int> pii; typedef vector<char> vc; typedef vector<vc> vvc; char grid[10][10]; int h,w; void fill(char from,char to,int i,int j) { grid[i][j]=to; rep(k,4){ int ni=i+"\xff\x1\0\0"[k],nj=j+"\0\0\xff\x1"[k]; if(0<=ni && ni<h && 0<=nj && nj<w && grid[ni][nj]==from) fill(from,to,ni,nj); } } bool ok() { rep(i,h) rep(j,w) if(grid[i][j]!=grid[0][0]) return false; return true; } bool iddfs(int d,int dmax) { if(d>dmax) return false; if(ok()) return true; char g[10][10]; rep(i,h) rep(j,w) g[i][j]=grid[i][j]; rep(k,3){ char to="RGB"[k]; if(to==grid[0][0]) continue; fill(g[0][0],to,0,0); if(iddfs(d+1,dmax)) return true; rep(i,h) rep(j,w) grid[i][j]=g[i][j]; } return false; } int solve() { for(int i=0;;i++) if(iddfs(0,i)) return i; } int main() { while(cin>>w>>h,w|h){ rep(i,h) rep(j,w) cin>>grid[i][j]; cout<<solve()<<endl; } return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <cstdio> #include <cstdlib> #include <cstring> #include <climits> #include <cmath> #include <cassert> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <numeric> #include <complex> #include <list> #include <stack> #include <queue> #include <set> #include <map> #include <bitset> #include <utility> #include <functional> #include <iterator> using namespace std; #define dump(n) cerr<<"# "<<#n<<"="<<(n)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define iter(c) __typeof__((c).begin()) #define foreach(i,c) for(iter(c) i=(c).begin();i!=(c).end();++i) #define all(c) (c).begin(),(c).end() #define mp make_pair typedef unsigned int uint; typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<string> vs; typedef pair<int,int> pii; typedef vector<char> vc; typedef vector<vc> vvc; char grid[10][10]; int h,w; void fill(char from,char to,int i,int j) { grid[i][j]=to; rep(k,4){ int ni=i+"\xff\x1\0\0"[k],nj=j+"\0\0\xff\x1"[k]; if(0<=ni && ni<h && 0<=nj && nj<w && grid[ni][nj]==from) fill(from,to,ni,nj); } } bool ok() { rep(i,h) rep(j,w) if(grid[i][j]!=grid[0][0]) return false; return true; } bool iddfs(int d,int dmax) { if(d>dmax) return false; if(ok()) return true; char g[10][10]; rep(i,h) rep(j,w) g[i][j]=grid[i][j]; rep(k,3){ char to="RGB"[k]; if(to==grid[0][0]) continue; fill(g[0][0],to,0,0); if(iddfs(d+1,dmax)) return true; rep(i,h) rep(j,w) grid[i][j]=g[i][j]; } return false; } int solve() { for(int i=0;;i++) if(iddfs(0,i)) return i; } int main() { while(cin>>w>>h,w|h){ rep(i,h) rep(j,w) cin>>grid[i][j]; cout<<solve()<<endl; } return 0; } ```
#include<bits/stdc++.h> using namespace std; const int dy[]={-1,0,1,0},dx[]={0,-1,0,1}; int h,w; char fld[20][20]; int lim; void paint(int y,int x,char c,vector<int>&V){ char tmp=fld[y][x]; fld[y][x]=c; V.push_back(y*w+x); for(int d=0;d<4;d++){ int ny=y+dy[d],nx=x+dx[d]; if(ny<0||ny>=h||nx<0||nx>=w)continue; if(fld[ny][nx]==tmp)paint(ny,nx,c,V); } } bool dfs(int cnt){ char c=fld[0][0]; bool ok=1; for(int i=0;i<h;i++)for(int j=0;j<w;j++)if(fld[i][j]!=c)ok=0; if(ok)return 1; if(cnt>=lim)return 0; for(int i=0;i<3;i++)if(c!="RGB"[i]){ vector<int>V; paint(0,0,"RGB"[i],V); if(dfs(cnt+1))return 1; for(int j=0;j<V.size();j++)fld[V[j]/w][V[j]%w]=c; } return 0; } int main(){ while(cin>>w>>h,w||h){ for(int i=0;i<h;i++)for(int j=0;j<w;j++)cin>>fld[i][j]; for(lim=0;;lim++)if(dfs(0))break; cout<<lim<<endl; } }
### Prompt In cpp, your task is to solve the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<bits/stdc++.h> using namespace std; const int dy[]={-1,0,1,0},dx[]={0,-1,0,1}; int h,w; char fld[20][20]; int lim; void paint(int y,int x,char c,vector<int>&V){ char tmp=fld[y][x]; fld[y][x]=c; V.push_back(y*w+x); for(int d=0;d<4;d++){ int ny=y+dy[d],nx=x+dx[d]; if(ny<0||ny>=h||nx<0||nx>=w)continue; if(fld[ny][nx]==tmp)paint(ny,nx,c,V); } } bool dfs(int cnt){ char c=fld[0][0]; bool ok=1; for(int i=0;i<h;i++)for(int j=0;j<w;j++)if(fld[i][j]!=c)ok=0; if(ok)return 1; if(cnt>=lim)return 0; for(int i=0;i<3;i++)if(c!="RGB"[i]){ vector<int>V; paint(0,0,"RGB"[i],V); if(dfs(cnt+1))return 1; for(int j=0;j<V.size();j++)fld[V[j]/w][V[j]%w]=c; } return 0; } int main(){ while(cin>>w>>h,w||h){ for(int i=0;i<h;i++)for(int j=0;j<w;j++)cin>>fld[i][j]; for(lim=0;;lim++)if(dfs(0))break; cout<<lim<<endl; } } ```
#include<iostream> #include<queue> #include<vector> using namespace std; #define inRange(x,a,b) (a <= x && x < b) int dx[8] = {0,0,1,-1,1,1,-1,-1}; int dy[8] = {1,-1,0,0,1,-1,1,-1}; struct board{ int y, x; vector<vector<char>> v; board(int i, int j) : y(i), x(j) { v.resize(i, vector<char>(j)); } }; int main(){ int x, y; while(cin >> x >> y, x+y){ char mat[y][x]; board ini(y, x); for(int i = 0; i < y; i++){ for(int j = 0; j < x; j++){ cin >> mat[i][j]; ini.v[i][j] = mat[i][j]; } } queue<pair<int, board>> q; q.push({0, ini}); int ans = -1; while(ans == -1 && !q.empty()){ auto p = q.front(); q.pop(); int cnt = 0; char c = p.second.v[0][0]; for(int i = 0; i < y; i++){ for(int j = 0; j < x; j++){ if(c == p.second.v[i][j]) cnt++; } } if(cnt == x*y){ ans = p.first; break; } for(int i = 0; i < 3; i++){ char from = p.second.v[0][0], to = "RGB"[i]; if(from == to) continue; board next = p.second; queue<pair<int,int>> pq; pq.push({0,0}); while(!pq.empty()){ pair<int,int> now = pq.front(); pq.pop(); if(next.v[now.first][now.second] == to) continue; next.v[now.first][now.second] = to; for(int k = 0; k < 4; k++){ int ni = now.first + dx[k], nj = now.second + dy[k]; if(inRange(ni, 0, y) && inRange(nj, 0, x) && next.v[ni][nj] == from){ pq.push({ni,nj}); } } } cnt = 0; c = to; for(int i = 0; i < y; i++) for(int j = 0; j < x; j++) cnt += (next.v[i][j] == c); if(cnt == x*y){ ans = p.first+1; break; } q.push({p.first+1, next}); } } cout << ans << endl; } return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<queue> #include<vector> using namespace std; #define inRange(x,a,b) (a <= x && x < b) int dx[8] = {0,0,1,-1,1,1,-1,-1}; int dy[8] = {1,-1,0,0,1,-1,1,-1}; struct board{ int y, x; vector<vector<char>> v; board(int i, int j) : y(i), x(j) { v.resize(i, vector<char>(j)); } }; int main(){ int x, y; while(cin >> x >> y, x+y){ char mat[y][x]; board ini(y, x); for(int i = 0; i < y; i++){ for(int j = 0; j < x; j++){ cin >> mat[i][j]; ini.v[i][j] = mat[i][j]; } } queue<pair<int, board>> q; q.push({0, ini}); int ans = -1; while(ans == -1 && !q.empty()){ auto p = q.front(); q.pop(); int cnt = 0; char c = p.second.v[0][0]; for(int i = 0; i < y; i++){ for(int j = 0; j < x; j++){ if(c == p.second.v[i][j]) cnt++; } } if(cnt == x*y){ ans = p.first; break; } for(int i = 0; i < 3; i++){ char from = p.second.v[0][0], to = "RGB"[i]; if(from == to) continue; board next = p.second; queue<pair<int,int>> pq; pq.push({0,0}); while(!pq.empty()){ pair<int,int> now = pq.front(); pq.pop(); if(next.v[now.first][now.second] == to) continue; next.v[now.first][now.second] = to; for(int k = 0; k < 4; k++){ int ni = now.first + dx[k], nj = now.second + dy[k]; if(inRange(ni, 0, y) && inRange(nj, 0, x) && next.v[ni][nj] == from){ pq.push({ni,nj}); } } } cnt = 0; c = to; for(int i = 0; i < y; i++) for(int j = 0; j < x; j++) cnt += (next.v[i][j] == c); if(cnt == x*y){ ans = p.first+1; break; } q.push({p.first+1, next}); } } cout << ans << endl; } return 0; } ```
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() typedef long long ll; typedef pair<int,int> pii; const int INF = 1<<29; const double PI = acos(-1); const double EPS = 1e-8; bool visited[10][10]; int main() { int h,w; while(cin>>w>>h,h||w) { string s; REP(i,h)REP(j,w) { char c; cin>>c; s += string(1,c); } typedef pair<string, int> psi; queue<psi> Q; Q.push(psi(s,0)); int ans = -1; while(!Q.empty()) { psi p = Q.front(); Q.pop(); string s = p.first; int d = p.second; // REP(i,h) { // REP(j,w) cout << s[i*w+j]; // cout << endl; // }cout << endl; vector<pii> v; queue<pii> Q2; Q2.push(pii(0,0)); memset(visited,0,sizeof(visited)); visited[0][0] = 1; const int dy[] = {-1,0,1,0}; const int dx[] = {0,1,0,-1}; char col = s[0]; set<char> st; while(!Q2.empty()) { pii q = Q2.front(); Q2.pop(); v.push_back(q); REP(i,4) { int yy=q.first + dy[i]; int xx=q.second+dx[i]; if (yy<0||yy>=h||xx<0||xx>=w) continue; if (visited[yy][xx]) continue; if (s[yy*w+xx] == col) { visited[yy][xx] = 1; Q2.push(pii(yy,xx)); } else { st.insert(s[yy*w+xx]); } } } if (st.size() == 0) { ans = d; break; } FOR(it, st) { FOR(jt, v) { s[jt->first*w+jt->second] = *it; } Q.push(psi(s,d+1)); } } cout << ans << endl; } }
### Prompt Construct a cpp code solution to the problem outlined: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() typedef long long ll; typedef pair<int,int> pii; const int INF = 1<<29; const double PI = acos(-1); const double EPS = 1e-8; bool visited[10][10]; int main() { int h,w; while(cin>>w>>h,h||w) { string s; REP(i,h)REP(j,w) { char c; cin>>c; s += string(1,c); } typedef pair<string, int> psi; queue<psi> Q; Q.push(psi(s,0)); int ans = -1; while(!Q.empty()) { psi p = Q.front(); Q.pop(); string s = p.first; int d = p.second; // REP(i,h) { // REP(j,w) cout << s[i*w+j]; // cout << endl; // }cout << endl; vector<pii> v; queue<pii> Q2; Q2.push(pii(0,0)); memset(visited,0,sizeof(visited)); visited[0][0] = 1; const int dy[] = {-1,0,1,0}; const int dx[] = {0,1,0,-1}; char col = s[0]; set<char> st; while(!Q2.empty()) { pii q = Q2.front(); Q2.pop(); v.push_back(q); REP(i,4) { int yy=q.first + dy[i]; int xx=q.second+dx[i]; if (yy<0||yy>=h||xx<0||xx>=w) continue; if (visited[yy][xx]) continue; if (s[yy*w+xx] == col) { visited[yy][xx] = 1; Q2.push(pii(yy,xx)); } else { st.insert(s[yy*w+xx]); } } } if (st.size() == 0) { ans = d; break; } FOR(it, st) { FOR(jt, v) { s[jt->first*w+jt->second] = *it; } Q.push(psi(s,d+1)); } } cout << ans << endl; } } ```
#include<cstdio> #include<cstdlib> #include<ctime> #include<cmath> #include<cstring> #include<cctype> #include<complex> #include<iostream> #include<sstream> #include<algorithm> #include<functional> #include<vector> #include<string> #include<stack> #include<queue> #include<map> #include<set> #include<bitset> using namespace std; const int dx[] = {1,0,-1,0}; const int dy[] = {0,1,0,-1}; #define INF 1e+8 #define EPS 1e-10 #define PB push_back #define fi first #define se second #define ll long long #define reps(i,j,k) for(int i = (j); i < (k); i++) #define rep(i,j) reps(i,0,j) typedef pair<int,int> Pii; typedef vector<int> vi; class Data{ public: char field[10][10]; int cnt; Data(){} Data(char _field[10][10],int _cnt){ cnt = _cnt; rep(i,10){ rep(j,10){ field[i][j] = _field[i][j]; } } } }; bool check(char stage[10][10],int w,int h){ int top = stage[0][0]; rep(i,h){ rep(j,w){ if(top != stage[i][j])return false; } } return true; } void copy(char sub[2][10][10],char stage[10][10],int w,int h){ rep(i,h){ rep(j,w){ sub[0][i][j] = stage[i][j]; sub[1][i][j] = stage[i][j]; } } return ; } void dfs(int y,int x,bool memo[10][10],int w,int h,char stage[2][10][10],int col){ rep(i,4){ int nx = x + dx[i]; int ny = y + dy[i]; if(nx < 0 || nx > w-1 || ny < 0 || ny > h-1 || memo[ny][nx]==1 )continue; if(col == stage[0][ny][nx] || col == stage[1][ny][nx]){ stage[0][ny][nx] = (col+1)%3; stage[1][ny][nx] = (col+2)%3; memo[ny][nx] = 1; dfs(ny,nx,memo,w,h,stage,col); } } return ; } int bfs(char stage[10][10],int w,int h){ int ans = -1; queue < Data > Q; Q.push(Data(stage,0)); while( !Q.empty() ){ Data d = Q.front();Q.pop(); if(check(d.field,w,h)){ ans = d.cnt; break; } bool memo[10][10]={{0}}; char sub[2][10][10]={{0}}; copy(sub,d.field,w,h); memo[0][0] = 1; sub[0][0][0] = (d.field[0][0]+1)%3; sub[1][0][0] = (d.field[0][0]+2)%3; dfs(0,0,memo,w,h,sub,d.field[0][0]); Q.push(Data(sub[0],d.cnt+1)); Q.push(Data(sub[1],d.cnt+1)); } return ans; } int main(){ int w,h; while(scanf("%d%d",&w,&h),w){ char stage[10][10]; rep(i,h){ rep(j,w){ char tmp; scanf(" %c",&tmp); stage[i][j] = ((tmp == 'R')? 0 : (tmp == 'G') ? 1 : 2); } } int ans = bfs(stage,w,h); printf("%d\n",ans); } return 0; }
### Prompt Please provide a cpp coded solution to the problem described below: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<cstdio> #include<cstdlib> #include<ctime> #include<cmath> #include<cstring> #include<cctype> #include<complex> #include<iostream> #include<sstream> #include<algorithm> #include<functional> #include<vector> #include<string> #include<stack> #include<queue> #include<map> #include<set> #include<bitset> using namespace std; const int dx[] = {1,0,-1,0}; const int dy[] = {0,1,0,-1}; #define INF 1e+8 #define EPS 1e-10 #define PB push_back #define fi first #define se second #define ll long long #define reps(i,j,k) for(int i = (j); i < (k); i++) #define rep(i,j) reps(i,0,j) typedef pair<int,int> Pii; typedef vector<int> vi; class Data{ public: char field[10][10]; int cnt; Data(){} Data(char _field[10][10],int _cnt){ cnt = _cnt; rep(i,10){ rep(j,10){ field[i][j] = _field[i][j]; } } } }; bool check(char stage[10][10],int w,int h){ int top = stage[0][0]; rep(i,h){ rep(j,w){ if(top != stage[i][j])return false; } } return true; } void copy(char sub[2][10][10],char stage[10][10],int w,int h){ rep(i,h){ rep(j,w){ sub[0][i][j] = stage[i][j]; sub[1][i][j] = stage[i][j]; } } return ; } void dfs(int y,int x,bool memo[10][10],int w,int h,char stage[2][10][10],int col){ rep(i,4){ int nx = x + dx[i]; int ny = y + dy[i]; if(nx < 0 || nx > w-1 || ny < 0 || ny > h-1 || memo[ny][nx]==1 )continue; if(col == stage[0][ny][nx] || col == stage[1][ny][nx]){ stage[0][ny][nx] = (col+1)%3; stage[1][ny][nx] = (col+2)%3; memo[ny][nx] = 1; dfs(ny,nx,memo,w,h,stage,col); } } return ; } int bfs(char stage[10][10],int w,int h){ int ans = -1; queue < Data > Q; Q.push(Data(stage,0)); while( !Q.empty() ){ Data d = Q.front();Q.pop(); if(check(d.field,w,h)){ ans = d.cnt; break; } bool memo[10][10]={{0}}; char sub[2][10][10]={{0}}; copy(sub,d.field,w,h); memo[0][0] = 1; sub[0][0][0] = (d.field[0][0]+1)%3; sub[1][0][0] = (d.field[0][0]+2)%3; dfs(0,0,memo,w,h,sub,d.field[0][0]); Q.push(Data(sub[0],d.cnt+1)); Q.push(Data(sub[1],d.cnt+1)); } return ans; } int main(){ int w,h; while(scanf("%d%d",&w,&h),w){ char stage[10][10]; rep(i,h){ rep(j,w){ char tmp; scanf(" %c",&tmp); stage[i][j] = ((tmp == 'R')? 0 : (tmp == 'G') ? 1 : 2); } } int ans = bfs(stage,w,h); printf("%d\n",ans); } return 0; } ```
#include <iostream> #include <vector> #include <array> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <tuple> #include <bitset> #include <memory> #include <cmath> #include <algorithm> #include <functional> #include <iomanip> #include <numeric> #include <climits> #include <cfloat> struct Coordinate { int x, y; std::vector<Coordinate> neighbors() const { return std::vector<Coordinate>{ Coordinate{x + 1, y}, Coordinate{x - 1, y}, Coordinate{x, y + 1}, Coordinate{x, y - 1} }; } }; constexpr std::array<char, 3> Colors = { 'R', 'G', 'B' }; int min_step(std::vector<std::vector<char>>& state, const int current_step = 0, int current_min = 30) { if (current_step >= current_min) return current_min; if (std::all_of(state.begin(), state.end(), [&state](const std::vector<char>& line) {return std::all_of(line.begin(), line.end(), [&state](const char c) {return c == state[0][0]; }); })) return current_step; auto initial = state[0][0]; std::vector<std::vector<bool>> is_join(state.size(), std::vector<bool>(state.front().size(), false)); is_join[0][0] = true; std::queue<Coordinate> queue; queue.push(Coordinate{ 0, 0 }); while (!queue.empty()) { auto top = queue.front(); queue.pop(); for (auto next : top.neighbors()) if (0 <= next.y && next.y < state.size() && 0 <= next.x && next.x < state.front().size() && !is_join[next.y][next.x]) { if (state[next.y][next.x] == initial) { is_join[next.y][next.x] = true; queue.push(next); } } } auto diff = std::distance(Colors.begin(), std::find(Colors.begin(), Colors.end(), initial)); for (auto c = 1; c < 3; ++c) { for (auto i = 0; i < state.size(); ++i) for (auto j = 0; j < state[i].size(); ++j) { if (is_join[i][j]) state[i][j] = Colors[(c + diff) % 3]; } current_min = min_step(state, current_step + 1, current_min); } for (auto i = 0; i < state.size(); ++i) for (auto j = 0; j < state[i].size(); ++j) if (is_join[i][j]) state[i][j] = initial; return current_min; } int main() { std::cin.tie(0); std::cin.sync_with_stdio(false); while (true) { int x, y; std::cin >> x >> y; if (x == 0 && y == 0) break; std::vector<std::vector<char>> state(y, std::vector<char>(x)); for (auto& line : state) for (auto& cell : line) std::cin >> cell; std::cout << min_step(state) << '\n'; } }
### Prompt Please formulate a CPP solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <vector> #include <array> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <tuple> #include <bitset> #include <memory> #include <cmath> #include <algorithm> #include <functional> #include <iomanip> #include <numeric> #include <climits> #include <cfloat> struct Coordinate { int x, y; std::vector<Coordinate> neighbors() const { return std::vector<Coordinate>{ Coordinate{x + 1, y}, Coordinate{x - 1, y}, Coordinate{x, y + 1}, Coordinate{x, y - 1} }; } }; constexpr std::array<char, 3> Colors = { 'R', 'G', 'B' }; int min_step(std::vector<std::vector<char>>& state, const int current_step = 0, int current_min = 30) { if (current_step >= current_min) return current_min; if (std::all_of(state.begin(), state.end(), [&state](const std::vector<char>& line) {return std::all_of(line.begin(), line.end(), [&state](const char c) {return c == state[0][0]; }); })) return current_step; auto initial = state[0][0]; std::vector<std::vector<bool>> is_join(state.size(), std::vector<bool>(state.front().size(), false)); is_join[0][0] = true; std::queue<Coordinate> queue; queue.push(Coordinate{ 0, 0 }); while (!queue.empty()) { auto top = queue.front(); queue.pop(); for (auto next : top.neighbors()) if (0 <= next.y && next.y < state.size() && 0 <= next.x && next.x < state.front().size() && !is_join[next.y][next.x]) { if (state[next.y][next.x] == initial) { is_join[next.y][next.x] = true; queue.push(next); } } } auto diff = std::distance(Colors.begin(), std::find(Colors.begin(), Colors.end(), initial)); for (auto c = 1; c < 3; ++c) { for (auto i = 0; i < state.size(); ++i) for (auto j = 0; j < state[i].size(); ++j) { if (is_join[i][j]) state[i][j] = Colors[(c + diff) % 3]; } current_min = min_step(state, current_step + 1, current_min); } for (auto i = 0; i < state.size(); ++i) for (auto j = 0; j < state[i].size(); ++j) if (is_join[i][j]) state[i][j] = initial; return current_min; } int main() { std::cin.tie(0); std::cin.sync_with_stdio(false); while (true) { int x, y; std::cin >> x >> y; if (x == 0 && y == 0) break; std::vector<std::vector<char>> state(y, std::vector<char>(x)); for (auto& line : state) for (auto& cell : line) std::cin >> cell; std::cout << min_step(state) << '\n'; } } ```
#include <bitset> #include <vector> #include <map> #include <set> #include <stack> #include <queue> #include <cstring> #include <string> #include <sstream> #include <algorithm> #include <iomanip> #include <iostream> #define VARIABLE(x) cerr << #x << "=" << x << endl #define BINARY(x) cerr << #x << "=" << static_cast<bitset<16> >(x) << endl; #define rep(i,n) for(int i=0;i<(int)(n);i++) #define REP(i,m,n) for (int i=m;i<(int)(n);i++) #define if_range(x, y, w, h) if (0<=x && x<w && 0<=y && y<h) const int INF = 10000000; int dx[4]={1, 0, -1, 0}, dy[4]={0, 1, 0, -1}; using namespace std; typedef long long ll; typedef pair<int, int> P; const int MAX = 2*123500; /** Problem0243 : Filling Game **/ typedef struct { char field[10][10]; bool area[10][10]; int cost; } S; int w, h; string list = "RGB"; void bond(char f[10][10], bool b[10][10]) { bool vis[10][10]; queue<P> Q; fill(vis[0], vis[0]+10*10, false); Q.push(P(0, 0)); while (Q.size()) { P p = Q.front(); Q.pop(); if (vis[p.first][p.second]) continue; else vis[p.first][p.second]=true; rep(i, 4) { int nx=p.first+dx[i], ny=p.second+dy[i]; if_range(nx, ny, w, h) { if (f[nx][ny] == f[p.first][p.second]) { b[nx][ny] = true; Q.push(P(nx, ny)); } } } } } int main() { while (cin>>w>>h, h||w) { queue<S> Q; S first; rep(y, h) rep(x, w) { cin >> first.field[x][y]; first.area[x][y]=false; } first.area[0][0]=true; bond(first.field, first.area); rep(y, h) rep(x, w) { rep(i, 4) { int nx=x+dx[i], ny=y+dy[i]; if (0<=nx&&nx<w&&0<=ny&&ny<h&&first.area[x][y]&&first.field[0][0]==first.field[nx][ny]) first.area[nx][ny]=true; } } first.cost = 0; Q.push(first); while (Q.size()) { S s = Q.front(); bool flg=true; rep(y, h) { rep(x, w) { flg &= s.area[x][y]; } if (!flg) break; } if (flg) { cout << s.cost << endl; break; } rep(i, 3) { if (s.field[0][0]==list[i]) continue; rep(y, h) rep(x, w) { if (s.area[x][y]) s.field[x][y] = list[i]; } bond(s.field, s.area); s.cost++; Q.push(s); s = Q.front(); } Q.pop(); } } }
### Prompt Please provide a cpp coded solution to the problem described below: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <bitset> #include <vector> #include <map> #include <set> #include <stack> #include <queue> #include <cstring> #include <string> #include <sstream> #include <algorithm> #include <iomanip> #include <iostream> #define VARIABLE(x) cerr << #x << "=" << x << endl #define BINARY(x) cerr << #x << "=" << static_cast<bitset<16> >(x) << endl; #define rep(i,n) for(int i=0;i<(int)(n);i++) #define REP(i,m,n) for (int i=m;i<(int)(n);i++) #define if_range(x, y, w, h) if (0<=x && x<w && 0<=y && y<h) const int INF = 10000000; int dx[4]={1, 0, -1, 0}, dy[4]={0, 1, 0, -1}; using namespace std; typedef long long ll; typedef pair<int, int> P; const int MAX = 2*123500; /** Problem0243 : Filling Game **/ typedef struct { char field[10][10]; bool area[10][10]; int cost; } S; int w, h; string list = "RGB"; void bond(char f[10][10], bool b[10][10]) { bool vis[10][10]; queue<P> Q; fill(vis[0], vis[0]+10*10, false); Q.push(P(0, 0)); while (Q.size()) { P p = Q.front(); Q.pop(); if (vis[p.first][p.second]) continue; else vis[p.first][p.second]=true; rep(i, 4) { int nx=p.first+dx[i], ny=p.second+dy[i]; if_range(nx, ny, w, h) { if (f[nx][ny] == f[p.first][p.second]) { b[nx][ny] = true; Q.push(P(nx, ny)); } } } } } int main() { while (cin>>w>>h, h||w) { queue<S> Q; S first; rep(y, h) rep(x, w) { cin >> first.field[x][y]; first.area[x][y]=false; } first.area[0][0]=true; bond(first.field, first.area); rep(y, h) rep(x, w) { rep(i, 4) { int nx=x+dx[i], ny=y+dy[i]; if (0<=nx&&nx<w&&0<=ny&&ny<h&&first.area[x][y]&&first.field[0][0]==first.field[nx][ny]) first.area[nx][ny]=true; } } first.cost = 0; Q.push(first); while (Q.size()) { S s = Q.front(); bool flg=true; rep(y, h) { rep(x, w) { flg &= s.area[x][y]; } if (!flg) break; } if (flg) { cout << s.cost << endl; break; } rep(i, 3) { if (s.field[0][0]==list[i]) continue; rep(y, h) rep(x, w) { if (s.area[x][y]) s.field[x][y] = list[i]; } bond(s.field, s.area); s.cost++; Q.push(s); s = Q.front(); } Q.pop(); } } } ```
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> Pr; const char* color = "RGB"; const int dx[] = {-1, 0, 1, 0}; const int dy[] = {0, -1, 0, 1}; int h, w; vector<string> grid; bool change[10][10]; bool ok(int i, int j) { return i >= 0 && i < h && j >= 0 && j < w; } bool check(vector<string> grid) { for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ if (grid[0][0] != grid[i][j]) return false; } } return true; } bool search(int d, vector<string> grid) { if (check(grid)) return true; if (d == 0) return false; for (const char *col = color; *col != '\0'; col++){ if (grid[0][0] == *col) continue; vector<string> ngrid = grid; fill_n(*change, 100, false); change[0][0] = true; queue<Pr> que; for (que.push(Pr(0, 0)); que.size(); que.pop()){ Pr p = que.front(); ngrid[p.first][p.second] = *col; for (int dir = 0; dir < 4; dir++){ int nx = p.first + dx[dir]; int ny = p.second + dy[dir]; if (!ok(nx, ny)) continue; if (grid[nx][ny] != grid[0][0]) continue; if (change[nx][ny]) continue; change[nx][ny] = true; que.push(Pr(nx, ny)); } } if (search(d - 1, ngrid)) return true; } return false; } int solve() { for (int d = 0; ; d++){ if (search(d, grid)) return d; } } int main() { while (scanf("%d %d", &w, &h), w){ grid = vector<string>(h); for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ char c; scanf(" %c", &c); grid[i] += c; } } printf("%d\n", solve()); } }
### Prompt Please formulate a cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <bits/stdc++.h> using namespace std; typedef pair<int, int> Pr; const char* color = "RGB"; const int dx[] = {-1, 0, 1, 0}; const int dy[] = {0, -1, 0, 1}; int h, w; vector<string> grid; bool change[10][10]; bool ok(int i, int j) { return i >= 0 && i < h && j >= 0 && j < w; } bool check(vector<string> grid) { for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ if (grid[0][0] != grid[i][j]) return false; } } return true; } bool search(int d, vector<string> grid) { if (check(grid)) return true; if (d == 0) return false; for (const char *col = color; *col != '\0'; col++){ if (grid[0][0] == *col) continue; vector<string> ngrid = grid; fill_n(*change, 100, false); change[0][0] = true; queue<Pr> que; for (que.push(Pr(0, 0)); que.size(); que.pop()){ Pr p = que.front(); ngrid[p.first][p.second] = *col; for (int dir = 0; dir < 4; dir++){ int nx = p.first + dx[dir]; int ny = p.second + dy[dir]; if (!ok(nx, ny)) continue; if (grid[nx][ny] != grid[0][0]) continue; if (change[nx][ny]) continue; change[nx][ny] = true; que.push(Pr(nx, ny)); } } if (search(d - 1, ngrid)) return true; } return false; } int solve() { for (int d = 0; ; d++){ if (search(d, grid)) return d; } } int main() { while (scanf("%d %d", &w, &h), w){ grid = vector<string>(h); for (int i = 0; i < h; i++){ for (int j = 0; j < w; j++){ char c; scanf(" %c", &c); grid[i] += c; } } printf("%d\n", solve()); } } ```
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <memory.h> #include <queue> #include <cstdio> #include <cstdlib> #include <set> #include <map> #include <cctype> #include <iomanip> #include <sstream> #include <cctype> #include <fstream> #include <cmath> using namespace std; #define rep(i, n) for(int i = 0; i< (int)(n); i++) #define all(c) (c).begin(), (c).end() #define iter(c) __typeof((c).begin()) #define pb(e) push_back(e) #define foreach(c, i) for(iter(c) i = (c).begin(); i != c.end(); ++i) typedef long long ll; typedef pair<ll, ll> P; const int INF = 1000 * 1000 * 1000 + 7; const double EPS = 1e-10; int x, y; int grid[10][10]; int dr[] = {1, 0, -1, 0}; int dc[] = {0, -1, 0, 1}; bool goal(){ int a = grid[0][0]; rep(i, y)rep(j, x) if(a != grid[i][j]) return false; return true; } inline bool inside(int r, int c){ return 0 <= r && r < y && 0 <= c && c < x; } void change_color(int before, int after, int r, int c, bool change[10][10]){ grid[r][c] = after; change[r][c] = true; rep(i, 4){ int r2 = r + dr[i]; int c2 = c + dc[i]; if(inside(r2, c2) && grid[r2][c2] == before){ change_color(before, after, r2, c2, change); } } } void undo_change(int before, bool change[10][10]){ rep(i, y)rep(j, x){ if(change[i][j]) { change[i][j] = false; grid[i][j] = before; } } } bool dfs(int depth, int limit){ bool change[10][10]; memset(change, false, sizeof(change)); if(depth > limit) return false; /*cout << depth << " " << limit << " " << endl; rep(i, y) rep(j, x) cout << grid[i][j] << (j == x - 1 ? '\n' : ' ');*/ if(goal()) return true; int before = grid[0][0]; rep(after, 3){ if(after == before) continue; change_color(before, after, 0, 0, change); if(dfs(depth + 1, limit)) return true; undo_change(before, change); } return false; } int main(){ char ch; while(cin >> x >> y){ if(x == 0 && y == 0) break; rep(i, y)rep(j, x){ cin >> ch; if(ch == 'R') grid[i][j] = 0; if(ch == 'G') grid[i][j] = 1; if(ch == 'B') grid[i][j] = 2; } int depth = 0; while(!dfs(0, depth)){ depth++; } cout << depth << endl; } return 0; }
### Prompt Create a solution in CPP for the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <algorithm> #include <vector> #include <string> #include <memory.h> #include <queue> #include <cstdio> #include <cstdlib> #include <set> #include <map> #include <cctype> #include <iomanip> #include <sstream> #include <cctype> #include <fstream> #include <cmath> using namespace std; #define rep(i, n) for(int i = 0; i< (int)(n); i++) #define all(c) (c).begin(), (c).end() #define iter(c) __typeof((c).begin()) #define pb(e) push_back(e) #define foreach(c, i) for(iter(c) i = (c).begin(); i != c.end(); ++i) typedef long long ll; typedef pair<ll, ll> P; const int INF = 1000 * 1000 * 1000 + 7; const double EPS = 1e-10; int x, y; int grid[10][10]; int dr[] = {1, 0, -1, 0}; int dc[] = {0, -1, 0, 1}; bool goal(){ int a = grid[0][0]; rep(i, y)rep(j, x) if(a != grid[i][j]) return false; return true; } inline bool inside(int r, int c){ return 0 <= r && r < y && 0 <= c && c < x; } void change_color(int before, int after, int r, int c, bool change[10][10]){ grid[r][c] = after; change[r][c] = true; rep(i, 4){ int r2 = r + dr[i]; int c2 = c + dc[i]; if(inside(r2, c2) && grid[r2][c2] == before){ change_color(before, after, r2, c2, change); } } } void undo_change(int before, bool change[10][10]){ rep(i, y)rep(j, x){ if(change[i][j]) { change[i][j] = false; grid[i][j] = before; } } } bool dfs(int depth, int limit){ bool change[10][10]; memset(change, false, sizeof(change)); if(depth > limit) return false; /*cout << depth << " " << limit << " " << endl; rep(i, y) rep(j, x) cout << grid[i][j] << (j == x - 1 ? '\n' : ' ');*/ if(goal()) return true; int before = grid[0][0]; rep(after, 3){ if(after == before) continue; change_color(before, after, 0, 0, change); if(dfs(depth + 1, limit)) return true; undo_change(before, change); } return false; } int main(){ char ch; while(cin >> x >> y){ if(x == 0 && y == 0) break; rep(i, y)rep(j, x){ cin >> ch; if(ch == 'R') grid[i][j] = 0; if(ch == 'G') grid[i][j] = 1; if(ch == 'B') grid[i][j] = 2; } int depth = 0; while(!dfs(0, depth)){ depth++; } cout << depth << endl; } return 0; } ```
#include<iostream> #include<queue> using namespace std; struct grid{ char g[11][11]; int count; }; void DFS(grid& gr,char f,char c,int x,int y){ if(gr.g[x][y] != f){ return; } gr.g[x][y] = c; DFS(gr,f,c,x+1,y); DFS(gr,f,c,x-1,y); DFS(gr,f,c,x,y+1); DFS(gr,f,c,x,y-1); } int main(){ int x,y; while(1){ cin >> x >> y; if(x==0 && y==0){ break; } grid start; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ cin >> start.g[j][i]; } } char fc = start.g[0][0]; bool flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(start.g[j][i]!=fc){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << 0 << endl; continue; } start.count = 0; queue<grid> q; q.push(start); while(1){ grid bg = q.front(); q.pop(); bg.count++; grid tmp = bg; fc = tmp.g[0][0]; if(fc != 'R'){ DFS(tmp,fc,'R',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='R'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = bg; } if(fc != 'G'){ DFS(tmp,fc,'G',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='G'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = bg; } if(fc != 'B'){ DFS(tmp,fc,'B',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='B'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = bg; } } } return 0; }
### Prompt Develop a solution in cpp to the problem described below: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<queue> using namespace std; struct grid{ char g[11][11]; int count; }; void DFS(grid& gr,char f,char c,int x,int y){ if(gr.g[x][y] != f){ return; } gr.g[x][y] = c; DFS(gr,f,c,x+1,y); DFS(gr,f,c,x-1,y); DFS(gr,f,c,x,y+1); DFS(gr,f,c,x,y-1); } int main(){ int x,y; while(1){ cin >> x >> y; if(x==0 && y==0){ break; } grid start; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ cin >> start.g[j][i]; } } char fc = start.g[0][0]; bool flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(start.g[j][i]!=fc){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << 0 << endl; continue; } start.count = 0; queue<grid> q; q.push(start); while(1){ grid bg = q.front(); q.pop(); bg.count++; grid tmp = bg; fc = tmp.g[0][0]; if(fc != 'R'){ DFS(tmp,fc,'R',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='R'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = bg; } if(fc != 'G'){ DFS(tmp,fc,'G',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='G'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = bg; } if(fc != 'B'){ DFS(tmp,fc,'B',0,0); flag = true; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ if(tmp.g[j][i]!='B'){ flag = false; break; } } if(!flag){ break; } } if(flag){ cout << tmp.count << endl; break; } q.push(tmp); tmp = bg; } } } return 0; } ```
#include<iostream> #include<cstdio> #include<cstring> #include<map> #include<queue> #include<algorithm> #include<cassert> using namespace std; typedef pair<int,int> P; class state{ public: char f[11][11],c,l; state(){} state(int c,int l):c(c),l(l){}; }; char in[11][11]; state ne; bool used[11][11]; const int dx[4]={0,0,1,-1}; const int dy[4]={1,-1,0,0}; int n,m; int res; void dfs(int next,int prev,int x,int y){ if(x==0 && y==0){ memset(used,false,sizeof(used)); } ne.f[x][y]=next; used[x][y]=true; for(int i=0;i<4;i++){ int nx=x+dx[i],ny=y+dy[i]; if(nx>=0 && nx<n && ny>=0 && ny<m){ if(!used[nx][ny]){ used[nx][ny]=true; if(ne.f[nx][ny]==next){ } if(ne.f[nx][ny]==prev){ dfs(next,prev,nx,ny); } } } } } void cnt(int prev,int x,int y){ if(x==0 && y==0){ ne.l=0; memset(used,false,sizeof(used)); } ne.l++; used[x][y]=true; for(int i=0;i<4;i++){ int nx=x+dx[i],ny=y+dy[i]; if(nx>=0 && nx<n && ny>=0 && ny<m){ if(!used[nx][ny]){ used[nx][ny]=true; if(ne.f[nx][ny]==prev){ cnt(prev,nx,ny); } } } } } void bfs(state init){ queue<state> que; //map<state, bool> v; res=50; //v[ne]= true; que.push(init); while(que.size()){ state p=que.front(); que.pop(); if(p.c>=res)break; ne.c=p.c+1; for(int i=0;i<=2;i++){ memcpy(ne.f,p.f,sizeof(ne.f)); dfs(i,ne.f[0][0],0,0); cnt(ne.f[0][0],0,0); //if(!V[ne.f]){ if(ne.l==n*m)res=min(res,p.c+1); else if(ne.l>p.l)que.push(ne); // V[ne.f]=true; //} } } } int main(void){ while(1){ res=100; scanf("%d%d\n",&n,&m); if(n==0 && m==0)break; state init=state(0,1); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ cin >> in[j][i]; if(in[j][i]=='R')init.f[j][i]=0; if(in[j][i]=='G')init.f[j][i]=1; if(in[j][i]=='B')init.f[j][i]=2; } } memcpy(ne.f,init.f,sizeof(ne.f)); cnt(ne.f[0][0],0,0); if(ne.l==n*m)printf("0\n"); else{ bfs(init); printf("%d\n",res); } } return 0; }
### Prompt In CPP, your task is to solve the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<cstdio> #include<cstring> #include<map> #include<queue> #include<algorithm> #include<cassert> using namespace std; typedef pair<int,int> P; class state{ public: char f[11][11],c,l; state(){} state(int c,int l):c(c),l(l){}; }; char in[11][11]; state ne; bool used[11][11]; const int dx[4]={0,0,1,-1}; const int dy[4]={1,-1,0,0}; int n,m; int res; void dfs(int next,int prev,int x,int y){ if(x==0 && y==0){ memset(used,false,sizeof(used)); } ne.f[x][y]=next; used[x][y]=true; for(int i=0;i<4;i++){ int nx=x+dx[i],ny=y+dy[i]; if(nx>=0 && nx<n && ny>=0 && ny<m){ if(!used[nx][ny]){ used[nx][ny]=true; if(ne.f[nx][ny]==next){ } if(ne.f[nx][ny]==prev){ dfs(next,prev,nx,ny); } } } } } void cnt(int prev,int x,int y){ if(x==0 && y==0){ ne.l=0; memset(used,false,sizeof(used)); } ne.l++; used[x][y]=true; for(int i=0;i<4;i++){ int nx=x+dx[i],ny=y+dy[i]; if(nx>=0 && nx<n && ny>=0 && ny<m){ if(!used[nx][ny]){ used[nx][ny]=true; if(ne.f[nx][ny]==prev){ cnt(prev,nx,ny); } } } } } void bfs(state init){ queue<state> que; //map<state, bool> v; res=50; //v[ne]= true; que.push(init); while(que.size()){ state p=que.front(); que.pop(); if(p.c>=res)break; ne.c=p.c+1; for(int i=0;i<=2;i++){ memcpy(ne.f,p.f,sizeof(ne.f)); dfs(i,ne.f[0][0],0,0); cnt(ne.f[0][0],0,0); //if(!V[ne.f]){ if(ne.l==n*m)res=min(res,p.c+1); else if(ne.l>p.l)que.push(ne); // V[ne.f]=true; //} } } } int main(void){ while(1){ res=100; scanf("%d%d\n",&n,&m); if(n==0 && m==0)break; state init=state(0,1); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ cin >> in[j][i]; if(in[j][i]=='R')init.f[j][i]=0; if(in[j][i]=='G')init.f[j][i]=1; if(in[j][i]=='B')init.f[j][i]=2; } } memcpy(ne.f,init.f,sizeof(ne.f)); cnt(ne.f[0][0],0,0); if(ne.l==n*m)printf("0\n"); else{ bfs(init); printf("%d\n",res); } } return 0; } ```
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)n; ++i) #define REP(i,n) FOR(i,0,n) #define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cout<<*i<<" "; cout<<endl; } typedef long long ll; const int INF = 100000000; const double EPS = 1e-8; const int MOD = 1000000007; int W, H; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; struct S{ char grid[10][10]; int t; }; bool end(char grid[][10]){ REP(y, H) REP(x, W) if( grid[y][x] != grid[0][0]) return false; return true; } void filling(int x, int y, char from, char to, char grid[][10]){ grid[y][x] = to; REP(r, 4){ int nx = x + dx[r]; int ny = y + dy[r]; if(nx >= 0 && ny >= 0 && nx < W && ny < H && grid[ny][nx] == from){ grid[ny][nx] = to; filling(nx, ny, from, to, grid); } } } int main(){ while(cin>>W>>H && W){ S start; start.t = 0; REP(y, H)REP(x, W) cin>>start.grid[y][x]; queue<S> que; que.push(start); while(!que.empty()){ S s = que.front(); que.pop(); string color = "RGB"; if(end(s.grid)) { cout<<s.t<<endl; goto END; } REP(i, 3) if(color[i] != s.grid[0][0]){ S next = s; next.t += 1; filling(0, 0, s.grid[0][0], color[i], next.grid); que.push(next); } } END:; } return 0; }
### Prompt Please provide a CPP coded solution to the problem described below: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)n; ++i) #define REP(i,n) FOR(i,0,n) #define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cout<<*i<<" "; cout<<endl; } typedef long long ll; const int INF = 100000000; const double EPS = 1e-8; const int MOD = 1000000007; int W, H; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; struct S{ char grid[10][10]; int t; }; bool end(char grid[][10]){ REP(y, H) REP(x, W) if( grid[y][x] != grid[0][0]) return false; return true; } void filling(int x, int y, char from, char to, char grid[][10]){ grid[y][x] = to; REP(r, 4){ int nx = x + dx[r]; int ny = y + dy[r]; if(nx >= 0 && ny >= 0 && nx < W && ny < H && grid[ny][nx] == from){ grid[ny][nx] = to; filling(nx, ny, from, to, grid); } } } int main(){ while(cin>>W>>H && W){ S start; start.t = 0; REP(y, H)REP(x, W) cin>>start.grid[y][x]; queue<S> que; que.push(start); while(!que.empty()){ S s = que.front(); que.pop(); string color = "RGB"; if(end(s.grid)) { cout<<s.t<<endl; goto END; } REP(i, 3) if(color[i] != s.grid[0][0]){ S next = s; next.t += 1; filling(0, 0, s.grid[0][0], color[i], next.grid); que.push(next); } } END:; } return 0; } ```
#include <iostream> #include <cstdio> #include <cmath> #include <vector> #include <map> #include <stack> #include <queue> #include <algorithm> #include <set> #include <cassert> #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define REP(i,j) FOR(i,0,j) #define mp std::make_pair typedef long long ll; typedef unsigned long long ull; typedef std::pair<int,int> P; struct State{ int t, panel[10][10]; State(int _t, int (&_panel)[10][10]) :t(_t) { REP(i, 10){ REP(j, 10){ panel[i][j] = _panel[i][j]; } } } }; const int INF = 1001001001; // S N E W(南北東西) const int dx[8] = {0, 0, 1, -1, 1, 1, -1, -1}, dy[8] = {1, -1, 0, 0, 1, -1, 1, -1}; int W, H; int panel[10][10]; int nextColor(){ int res = 0; bool used[10][10]; REP(y, 10){ REP(x, 10){ used[y][x] = false; } } std::queue<P> q; q.push(mp(0, 0)); while(!q.empty()){ P p = q.front(); q.pop(); int x = p.first, y = p.second; if(used[y][x]){continue;} used[y][x] = true; REP(i, 4){ int nx = x + dx[i], ny = y + dy[i]; if(0 <= nx && nx < W && 0 <= ny && ny < H){ if(!used[ny][nx] && panel[ny][nx] == panel[0][0]){q.push(mp(nx, ny));} if(panel[ny][nx] != panel[0][0]){res |= 1 << panel[ny][nx];} } } } return res; } void changeColor(int c){ bool used[10][10]; REP(y, 10){ REP(x, 10){ used[y][x] = false; } } std::queue<P> q; q.push(mp(0, 0)); int prev_color = panel[0][0]; while(!q.empty()){ P p = q.front(); q.pop(); int x = p.first, y = p.second; if(used[y][x]){continue;} used[y][x] = true; panel[y][x] = c; REP(i, 4){ int nx = x + dx[i], ny = y + dy[i]; if(0 <= nx && nx < W && 0 <= ny && ny < H && !used[ny][nx] && panel[ny][nx] == prev_color){ q.push(mp(nx, ny)); } } } } int bfs(){ std::queue<State> q; q.push({0, panel}); while(!q.empty()){ State s = q.front(); q.pop(); REP(y, H){ REP(x, W){ panel[y][x] = s.panel[y][x]; } } int next_colors = nextColor(); if(next_colors == 0){return s.t;} REP(i, 3){ if(!(next_colors >> i & 1)){continue;} REP(y, H){ REP(x, W){ panel[y][x] = s.panel[y][x]; } } changeColor(i); q.push({s.t+1, panel}); } } } int dfs(){ int next_colors = nextColor(); if(next_colors == 0){return 0;} int _panel[10][10]; REP(y, H){ REP(x, W){ _panel[y][x] = panel[y][x]; } } int res = INF; REP(i, 3){ if(!(next_colors >> i & 1)){continue;} REP(y, H){ REP(x, W){ panel[y][x] = _panel[y][x]; } } changeColor(i); res = std::min(res, 1 + dfs()); } return res; } int main(){ while(std::cin >> W >> H, W){ REP(y, H){ REP(x, W){ char c; std::cin >> c; if(c == 'R'){panel[y][x] = 0;} if(c == 'G'){panel[y][x] = 1;} if(c == 'B'){panel[y][x] = 2;} } } std::cout << bfs() << std::endl; } }
### Prompt Please create a solution in Cpp to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <cstdio> #include <cmath> #include <vector> #include <map> #include <stack> #include <queue> #include <algorithm> #include <set> #include <cassert> #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define REP(i,j) FOR(i,0,j) #define mp std::make_pair typedef long long ll; typedef unsigned long long ull; typedef std::pair<int,int> P; struct State{ int t, panel[10][10]; State(int _t, int (&_panel)[10][10]) :t(_t) { REP(i, 10){ REP(j, 10){ panel[i][j] = _panel[i][j]; } } } }; const int INF = 1001001001; // S N E W(南北東西) const int dx[8] = {0, 0, 1, -1, 1, 1, -1, -1}, dy[8] = {1, -1, 0, 0, 1, -1, 1, -1}; int W, H; int panel[10][10]; int nextColor(){ int res = 0; bool used[10][10]; REP(y, 10){ REP(x, 10){ used[y][x] = false; } } std::queue<P> q; q.push(mp(0, 0)); while(!q.empty()){ P p = q.front(); q.pop(); int x = p.first, y = p.second; if(used[y][x]){continue;} used[y][x] = true; REP(i, 4){ int nx = x + dx[i], ny = y + dy[i]; if(0 <= nx && nx < W && 0 <= ny && ny < H){ if(!used[ny][nx] && panel[ny][nx] == panel[0][0]){q.push(mp(nx, ny));} if(panel[ny][nx] != panel[0][0]){res |= 1 << panel[ny][nx];} } } } return res; } void changeColor(int c){ bool used[10][10]; REP(y, 10){ REP(x, 10){ used[y][x] = false; } } std::queue<P> q; q.push(mp(0, 0)); int prev_color = panel[0][0]; while(!q.empty()){ P p = q.front(); q.pop(); int x = p.first, y = p.second; if(used[y][x]){continue;} used[y][x] = true; panel[y][x] = c; REP(i, 4){ int nx = x + dx[i], ny = y + dy[i]; if(0 <= nx && nx < W && 0 <= ny && ny < H && !used[ny][nx] && panel[ny][nx] == prev_color){ q.push(mp(nx, ny)); } } } } int bfs(){ std::queue<State> q; q.push({0, panel}); while(!q.empty()){ State s = q.front(); q.pop(); REP(y, H){ REP(x, W){ panel[y][x] = s.panel[y][x]; } } int next_colors = nextColor(); if(next_colors == 0){return s.t;} REP(i, 3){ if(!(next_colors >> i & 1)){continue;} REP(y, H){ REP(x, W){ panel[y][x] = s.panel[y][x]; } } changeColor(i); q.push({s.t+1, panel}); } } } int dfs(){ int next_colors = nextColor(); if(next_colors == 0){return 0;} int _panel[10][10]; REP(y, H){ REP(x, W){ _panel[y][x] = panel[y][x]; } } int res = INF; REP(i, 3){ if(!(next_colors >> i & 1)){continue;} REP(y, H){ REP(x, W){ panel[y][x] = _panel[y][x]; } } changeColor(i); res = std::min(res, 1 + dfs()); } return res; } int main(){ while(std::cin >> W >> H, W){ REP(y, H){ REP(x, W){ char c; std::cin >> c; if(c == 'R'){panel[y][x] = 0;} if(c == 'G'){panel[y][x] = 1;} if(c == 'B'){panel[y][x] = 2;} } } std::cout << bfs() << std::endl; } } ```
#include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace std; const int INF = INT_MAX / 4; string color = "RGB"; int dy[] = {0, 0, 1, -1}; int dx[] = {1, -1, 0, 0}; int w, h; map<vector<string>, int> memo; int solve(const vector<string>& s, int prevNum, int d) { if(d > 20) return INF; if(memo.find(s) != memo.end()) return memo[s]; int ret = INF; for(int i=0; i<3; ++i){ if(s[0][0] == color[i]) continue; char c = s[0][0]; vector<string> t = s; t[0][0] = color[i]; queue<pair<int, int> > q; q.push(make_pair(0, 0)); int n = 0; while(!q.empty()){ int y = q.front().first; int x = q.front().second; q.pop(); ++ n; for(int j=0; j<4; ++j){ int y2 = y + dy[j]; int x2 = x + dx[j]; if(y2 < 0 || y2 >= h || x2 < 0 || x2 >= w) continue; if(t[y2][x2] == c){ t[y2][x2] = color[i]; q.push(make_pair(y2, x2)); } } } if(n == prevNum) return memo[s] = INF; if(n == h * w) return memo[s] = 0; ret = min(ret, solve(t, n, d+1) + 1); } return memo[s] = ret; } int main() { for(;;){ cin >> w >> h; if(w == 0) return 0; vector<string> s(h, string(w, ' ')); for(int i=0; i<h; ++i){ for(int j=0; j<w; ++j){ cin >> s[i][j]; } } memo.clear(); cout << solve(s, -1, 0) << endl; } }
### Prompt Please create a solution in cpp to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace std; const int INF = INT_MAX / 4; string color = "RGB"; int dy[] = {0, 0, 1, -1}; int dx[] = {1, -1, 0, 0}; int w, h; map<vector<string>, int> memo; int solve(const vector<string>& s, int prevNum, int d) { if(d > 20) return INF; if(memo.find(s) != memo.end()) return memo[s]; int ret = INF; for(int i=0; i<3; ++i){ if(s[0][0] == color[i]) continue; char c = s[0][0]; vector<string> t = s; t[0][0] = color[i]; queue<pair<int, int> > q; q.push(make_pair(0, 0)); int n = 0; while(!q.empty()){ int y = q.front().first; int x = q.front().second; q.pop(); ++ n; for(int j=0; j<4; ++j){ int y2 = y + dy[j]; int x2 = x + dx[j]; if(y2 < 0 || y2 >= h || x2 < 0 || x2 >= w) continue; if(t[y2][x2] == c){ t[y2][x2] = color[i]; q.push(make_pair(y2, x2)); } } } if(n == prevNum) return memo[s] = INF; if(n == h * w) return memo[s] = 0; ret = min(ret, solve(t, n, d+1) + 1); } return memo[s] = ret; } int main() { for(;;){ cin >> w >> h; if(w == 0) return 0; vector<string> s(h, string(w, ' ')); for(int i=0; i<h; ++i){ for(int j=0; j<w; ++j){ cin >> s[i][j]; } } memo.clear(); cout << solve(s, -1, 0) << endl; } } ```
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() typedef long long ll; typedef pair<int,int> pii; const int INF = 1<<29; const double PI = acos(-1); const double EPS = 1e-8; int h,w; // ll encode(int a[10][10]) { // ll res = 0; // REP(i,h)REP(j,w) res = res*3+a[i][j]; // return res; // } // void decode(int a[10][10], ll e) { // for (int i=h-1; i>=0; --i) { // for (int j=w-1; j>=0; --j) { // a[i][j] = e%3; // e /= 3; // } // } // } typedef vector<int> vec; typedef vector<vec> mat; // int ba[10][10]; // int now[10][10]; // int nxt[10][10]; bool visited[10][10]; int dy[4] = {-1,0,1,0}; int dx[4] = {0,1,0,-1}; int ans; void dfs(mat now, int d) { // cout << d << endl; // REP(i,h) { // REP(j,w) cout << now[i][j]; // cout << endl; // } int col = now[0][0]; queue<pii> Q; Q.push(pii(0,0)); REP(i,h)REP(j,w)visited[i][j] = 0; visited[0][0] = 1; vector<pii> ps; bool ncol[3] = {}; while(!Q.empty()) { pii p = Q.front(); Q.pop(); ps.push_back(p); REP(i,4) { int y = p.first + dy[i]; int x = p.second + dx[i]; if (y<0||y>=h || x<0||x>=w)continue; if (now[y][x] != col) { ncol[now[y][x]] = 1; continue; } if (!visited[y][x]) { visited[y][x] = 1; Q.push(pii(y,x)); } } } if (ps.size() == h*w) { ans = min(ans,d); return; } if (d == ans-1) return; REP(k,3) { if (ncol[k] == 0) continue; FOR(it, ps) { now[it->first][it->second] = k; } dfs(now, d+1); } } int main() { while(cin>>w>>h,h||w) { mat ba(h,vec(w)); REP(i,h) { REP(j,w) { char c; cin >> c; if (c == 'R') ba[i][j] = 0; else if (c == 'G') ba[i][j] = 1; else ba[i][j] = 2; } } ans = 19; dfs(ba, 0); cout << ans << endl; } }
### Prompt Please create a solution in Cpp to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() typedef long long ll; typedef pair<int,int> pii; const int INF = 1<<29; const double PI = acos(-1); const double EPS = 1e-8; int h,w; // ll encode(int a[10][10]) { // ll res = 0; // REP(i,h)REP(j,w) res = res*3+a[i][j]; // return res; // } // void decode(int a[10][10], ll e) { // for (int i=h-1; i>=0; --i) { // for (int j=w-1; j>=0; --j) { // a[i][j] = e%3; // e /= 3; // } // } // } typedef vector<int> vec; typedef vector<vec> mat; // int ba[10][10]; // int now[10][10]; // int nxt[10][10]; bool visited[10][10]; int dy[4] = {-1,0,1,0}; int dx[4] = {0,1,0,-1}; int ans; void dfs(mat now, int d) { // cout << d << endl; // REP(i,h) { // REP(j,w) cout << now[i][j]; // cout << endl; // } int col = now[0][0]; queue<pii> Q; Q.push(pii(0,0)); REP(i,h)REP(j,w)visited[i][j] = 0; visited[0][0] = 1; vector<pii> ps; bool ncol[3] = {}; while(!Q.empty()) { pii p = Q.front(); Q.pop(); ps.push_back(p); REP(i,4) { int y = p.first + dy[i]; int x = p.second + dx[i]; if (y<0||y>=h || x<0||x>=w)continue; if (now[y][x] != col) { ncol[now[y][x]] = 1; continue; } if (!visited[y][x]) { visited[y][x] = 1; Q.push(pii(y,x)); } } } if (ps.size() == h*w) { ans = min(ans,d); return; } if (d == ans-1) return; REP(k,3) { if (ncol[k] == 0) continue; FOR(it, ps) { now[it->first][it->second] = k; } dfs(now, d+1); } } int main() { while(cin>>w>>h,h||w) { mat ba(h,vec(w)); REP(i,h) { REP(j,w) { char c; cin >> c; if (c == 'R') ba[i][j] = 0; else if (c == 'G') ba[i][j] = 1; else ba[i][j] = 2; } } ans = 19; dfs(ba, 0); cout << ans << endl; } } ```
// 2014/09/12 Tazoe #include <iostream> #include <queue> #include <string> #include <map> using namespace std; struct state{ string G; int N; }; bool is_over(string G) { bool flg = true; for(int i=1; i<G.size(); i++){ if(G[i]!=G[0]){ flg = false; break; } } return flg; } void DFS(char g[12][12], char F, char T, int x, int y) { if(g[y][x]!=F) return; g[y][x] = T; DFS(g, F, T, x-1, y); DFS(g, F, T, x+1, y); DFS(g, F, T, x, y-1); DFS(g, F, T, x, y+1); } string fill(string G, char C, int X, int Y) { char g[12][12]; for(int y=0; y<Y+2; y++){ for(int x=0; x<X+2; x++){ g[y][x] = 'N'; } } // 文字列から2次元配列へ for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ g[y+1][x+1] = G[y*X+x]; } } DFS(g, G[0], C, 1, 1); // 2次元配列から文字列へ for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ G[y*X+x] = g[y+1][x+1]; } } return G; } int main() { while(true){ int X, Y; cin >> X >> Y; if(X==0 && Y==0) break; string G = ""; for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ string c; cin >> c; G += c; } } queue<struct state> que; map<string, bool> memo; struct state ini; ini.G = G; ini.N = 0; que.push(ini); memo[ini.G] = true; while(!que.empty()){ struct state now = que.front(); que.pop(); if(is_over(now.G)){ cout << now.N << endl; break; } struct state nex1, nex2; if(now.G[0]=='R'){ nex1.G = fill(now.G, 'G', X, Y); nex2.G = fill(now.G, 'B', X, Y); nex1.N = nex2.N = now.N+1; } else if(now.G[0]=='G'){ nex1.G = fill(now.G, 'R', X, Y); nex2.G = fill(now.G, 'B', X, Y); nex1.N = nex2.N = now.N+1; } else if(now.G[0]=='B'){ nex1.G = fill(now.G, 'R', X, Y); nex2.G = fill(now.G, 'G', X, Y); nex1.N = nex2.N = now.N+1; } if(memo.find(nex1.G)==memo.end()){ que.push(nex1); memo[nex1.G] = true; } if(memo.find(nex2.G)==memo.end()){ que.push(nex2); memo[nex2.G] = true; } } } return 0; }
### Prompt Your challenge is to write a CPP solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp // 2014/09/12 Tazoe #include <iostream> #include <queue> #include <string> #include <map> using namespace std; struct state{ string G; int N; }; bool is_over(string G) { bool flg = true; for(int i=1; i<G.size(); i++){ if(G[i]!=G[0]){ flg = false; break; } } return flg; } void DFS(char g[12][12], char F, char T, int x, int y) { if(g[y][x]!=F) return; g[y][x] = T; DFS(g, F, T, x-1, y); DFS(g, F, T, x+1, y); DFS(g, F, T, x, y-1); DFS(g, F, T, x, y+1); } string fill(string G, char C, int X, int Y) { char g[12][12]; for(int y=0; y<Y+2; y++){ for(int x=0; x<X+2; x++){ g[y][x] = 'N'; } } // 文字列から2次元配列へ for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ g[y+1][x+1] = G[y*X+x]; } } DFS(g, G[0], C, 1, 1); // 2次元配列から文字列へ for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ G[y*X+x] = g[y+1][x+1]; } } return G; } int main() { while(true){ int X, Y; cin >> X >> Y; if(X==0 && Y==0) break; string G = ""; for(int y=0; y<Y; y++){ for(int x=0; x<X; x++){ string c; cin >> c; G += c; } } queue<struct state> que; map<string, bool> memo; struct state ini; ini.G = G; ini.N = 0; que.push(ini); memo[ini.G] = true; while(!que.empty()){ struct state now = que.front(); que.pop(); if(is_over(now.G)){ cout << now.N << endl; break; } struct state nex1, nex2; if(now.G[0]=='R'){ nex1.G = fill(now.G, 'G', X, Y); nex2.G = fill(now.G, 'B', X, Y); nex1.N = nex2.N = now.N+1; } else if(now.G[0]=='G'){ nex1.G = fill(now.G, 'R', X, Y); nex2.G = fill(now.G, 'B', X, Y); nex1.N = nex2.N = now.N+1; } else if(now.G[0]=='B'){ nex1.G = fill(now.G, 'R', X, Y); nex2.G = fill(now.G, 'G', X, Y); nex1.N = nex2.N = now.N+1; } if(memo.find(nex1.G)==memo.end()){ que.push(nex1); memo[nex1.G] = true; } if(memo.find(nex2.G)==memo.end()){ que.push(nex2); memo[nex2.G] = true; } } } return 0; } ```
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Info{ char map[10][10]; }; struct Data{ Data(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; bool FLG; char to_color[3] = {'R','G','B'}; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void back_track(Info info,int depth,int max_depth){ if(depth == max_depth){ bool is_cleared = true; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ if(info.map[row][col] != info.map[0][0]){ is_cleared = false; break; } } if(!is_cleared)break; } if(is_cleared){ FLG = true; } return; } char pre_color = info.map[0][0]; queue<Data> Q; int adj_row,adj_col; for(int loop = 0; loop < 3; loop++){ if(to_color[loop] == pre_color)continue; Info next_info; for(int row = 0;row < H; row++){ for(int col = 0; col < W; col++){ next_info.map[row][col] = info.map[row][col]; } } next_info.map[0][0] = to_color[loop]; Q.push(Data(0,0)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ adj_row = Q.front().row + diff_row[i]; adj_col = Q.front().col + diff_col[i]; if(!rangeCheck(adj_row,adj_col))continue; if(next_info.map[adj_row][adj_col] == pre_color){ next_info.map[adj_row][adj_col] = to_color[loop]; Q.push(Data(adj_row,adj_col)); } } Q.pop(); } back_track(next_info,depth+1,max_depth); } } void func(){ char buf[2]; Info first; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ scanf("%s",buf); first.map[row][col] = buf[0]; } } FLG = false; int ans = 0; for(int i = 0; ; i++){ back_track(first,0,i); if(FLG){ ans = i; break; } } printf("%d\n",ans); } int main(){ while(true){ scanf("%d %d",&W,&H); if(W == 0 && H == 0)break; func(); } return 0; }
### Prompt In Cpp, your task is to solve the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Info{ char map[10][10]; }; struct Data{ Data(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; bool FLG; char to_color[3] = {'R','G','B'}; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void back_track(Info info,int depth,int max_depth){ if(depth == max_depth){ bool is_cleared = true; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ if(info.map[row][col] != info.map[0][0]){ is_cleared = false; break; } } if(!is_cleared)break; } if(is_cleared){ FLG = true; } return; } char pre_color = info.map[0][0]; queue<Data> Q; int adj_row,adj_col; for(int loop = 0; loop < 3; loop++){ if(to_color[loop] == pre_color)continue; Info next_info; for(int row = 0;row < H; row++){ for(int col = 0; col < W; col++){ next_info.map[row][col] = info.map[row][col]; } } next_info.map[0][0] = to_color[loop]; Q.push(Data(0,0)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ adj_row = Q.front().row + diff_row[i]; adj_col = Q.front().col + diff_col[i]; if(!rangeCheck(adj_row,adj_col))continue; if(next_info.map[adj_row][adj_col] == pre_color){ next_info.map[adj_row][adj_col] = to_color[loop]; Q.push(Data(adj_row,adj_col)); } } Q.pop(); } back_track(next_info,depth+1,max_depth); } } void func(){ char buf[2]; Info first; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ scanf("%s",buf); first.map[row][col] = buf[0]; } } FLG = false; int ans = 0; for(int i = 0; ; i++){ back_track(first,0,i); if(FLG){ ans = i; break; } } printf("%d\n",ans); } int main(){ while(true){ scanf("%d %d",&W,&H); if(W == 0 && H == 0)break; func(); } return 0; } ```
#include <iostream> #include <queue> #include <utility> using namespace std; int main() { int x,y; while(cin>>x>>y&&x) { string m; for(int i=0;i<y;i++) { for(int l=0;l<x;l++) { string k;cin>>k; m+=k; } } typedef pair<string,int> psi; queue<psi> que;que.push(psi(m,0)); while(!que.empty()) { psi now=que.front();que.pop(); { bool ok=true; for(int i=0;i<now.first.size();i++)if(now.first[i]!=now.first[0])ok=false; if(ok) { cout<<now.second<<endl; break; } } { char s[4]="RGB"; for(int c=0;c<3;c++) { if(now.first[0]==s[c])continue; char b[20][20]={}; for(int i=1;i<=y;i++) { for(int j=1;j<=x;j++) { b[i][j]=now.first[(i-1)*x+(j-1)]; } } typedef pair<int,int> pii; queue<pii> Q;Q.push(pii(1,1)); int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0}; char ori=b[1][1]; b[1][1]=s[c]; while(!Q.empty()) { pii g = Q.front();Q.pop(); for(int i=0;i<4;i++) { if(b[g.first+dy[i]][g.second+dx[i]]==ori) { b[g.first+dy[i]][g.second+dx[i]]=s[c]; pii next; next.first=g.first+dy[i]; next.second=g.second+dx[i]; Q.push(next); } } } psi next; next.second=now.second+1; for(int i=1;i<=y;i++) { for(int j=1;j<=x;j++) { next.first+=b[i][j]; } } que.push(next); } } } } }
### Prompt Construct a CPP code solution to the problem outlined: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <queue> #include <utility> using namespace std; int main() { int x,y; while(cin>>x>>y&&x) { string m; for(int i=0;i<y;i++) { for(int l=0;l<x;l++) { string k;cin>>k; m+=k; } } typedef pair<string,int> psi; queue<psi> que;que.push(psi(m,0)); while(!que.empty()) { psi now=que.front();que.pop(); { bool ok=true; for(int i=0;i<now.first.size();i++)if(now.first[i]!=now.first[0])ok=false; if(ok) { cout<<now.second<<endl; break; } } { char s[4]="RGB"; for(int c=0;c<3;c++) { if(now.first[0]==s[c])continue; char b[20][20]={}; for(int i=1;i<=y;i++) { for(int j=1;j<=x;j++) { b[i][j]=now.first[(i-1)*x+(j-1)]; } } typedef pair<int,int> pii; queue<pii> Q;Q.push(pii(1,1)); int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0}; char ori=b[1][1]; b[1][1]=s[c]; while(!Q.empty()) { pii g = Q.front();Q.pop(); for(int i=0;i<4;i++) { if(b[g.first+dy[i]][g.second+dx[i]]==ori) { b[g.first+dy[i]][g.second+dx[i]]=s[c]; pii next; next.first=g.first+dy[i]; next.second=g.second+dx[i]; Q.push(next); } } } psi next; next.second=now.second+1; for(int i=1;i<=y;i++) { for(int j=1;j<=x;j++) { next.first+=b[i][j]; } } que.push(next); } } } } } ```
#include <iostream> #include <vector> #include <queue> #include <map> #include <cstring> using namespace std; using Mat = vector<vector<char>>; constexpr char col[] = {'R', 'G', 'B'}; constexpr int MAX = 10; constexpr int dx[] = {-1, 0, 1, 0}; constexpr int dy[] = {0, -1, 0, 1}; int W, H; Mat M; bool visited[MAX][MAX]; bool in_field(int x, int y) { return (0 <= x && x < W && 0 <= y && y < H); } void paint(Mat& m, int x, int y, char nc, char c) { if (visited[y][x]) return; visited[y][x] = 1; m[y][x] = nc; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (in_field(nx, ny) && m[ny][nx] == c) { paint(m, nx, ny, nc, c); } } } Mat get_next(const Mat& m, char c) { Mat res = m; memset(visited, 0, sizeof(visited)); paint(res, 0, 0, c, m[0][0]); return res; } bool reach(Mat& m) { char c = m[0][0]; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (m[i][j] != c) { return 0; } } } return 1; } int bfs() { queue<Mat> Q; Q.push(M); map<Mat, int> d; d[M] = 0; while (!Q.empty()) { Mat m = Q.front(); Q.pop(); if (reach(m)) return d[m]; for (int i = 0; i < 3; i++) { if (m[0][0] == col[i]) continue; Mat next = get_next(m, col[i]); if (d.count(next) == 0) { d[next] = d[m] + 1; Q.push(next); } } } return -1; } int main() { while (cin >> W >> H, W > 0) { M.resize(H); for (int i = 0; i < H; i++) { M[i].resize(W); for (int j = 0; j < W; j++) { cin >> M[i][j]; } } cout << bfs() << endl; } return 0; }
### Prompt Please formulate a Cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <vector> #include <queue> #include <map> #include <cstring> using namespace std; using Mat = vector<vector<char>>; constexpr char col[] = {'R', 'G', 'B'}; constexpr int MAX = 10; constexpr int dx[] = {-1, 0, 1, 0}; constexpr int dy[] = {0, -1, 0, 1}; int W, H; Mat M; bool visited[MAX][MAX]; bool in_field(int x, int y) { return (0 <= x && x < W && 0 <= y && y < H); } void paint(Mat& m, int x, int y, char nc, char c) { if (visited[y][x]) return; visited[y][x] = 1; m[y][x] = nc; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (in_field(nx, ny) && m[ny][nx] == c) { paint(m, nx, ny, nc, c); } } } Mat get_next(const Mat& m, char c) { Mat res = m; memset(visited, 0, sizeof(visited)); paint(res, 0, 0, c, m[0][0]); return res; } bool reach(Mat& m) { char c = m[0][0]; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (m[i][j] != c) { return 0; } } } return 1; } int bfs() { queue<Mat> Q; Q.push(M); map<Mat, int> d; d[M] = 0; while (!Q.empty()) { Mat m = Q.front(); Q.pop(); if (reach(m)) return d[m]; for (int i = 0; i < 3; i++) { if (m[0][0] == col[i]) continue; Mat next = get_next(m, col[i]); if (d.count(next) == 0) { d[next] = d[m] + 1; Q.push(next); } } } return -1; } int main() { while (cin >> W >> H, W > 0) { M.resize(H); for (int i = 0; i < H; i++) { M[i].resize(W); for (int j = 0; j < W; j++) { cin >> M[i][j]; } } cout << bfs() << endl; } return 0; } ```
#include<iostream> #include<vector> #include<algorithm> #include<string> using namespace std; int h,w,lim; int dx[4]={1,-1,0,0}; int dy[4]={0,0,1,-1}; char g[11][11]; string s="RGB"; void rev(int x,int y,vector<int>&p,char ch){ char tmp=g[y][x]; g[y][x]=ch; p.push_back(y*w+x); for(int i=0;i<4;i++){ int nx=x+dx[i],ny=y+dy[i]; if(nx<0 || ny<0 || w<=nx || h<=ny || g[ny][nx]!=tmp)continue; rev(nx,ny,p,ch); } } bool dfs(int d){ bool fg=true; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ fg&=(g[i][j]==g[0][0]); } } if(fg)return true; if(d>=lim)return false; for(int i=0;i<3;i++){ if(g[0][0]==s[i])continue; char tmp=g[0][0]; vector<int> p; rev(0,0,p,s[i]); if(dfs(d+1))return true; for(int j=0;j<p.size();j++){ g[p[j]/w][p[j]%w]=tmp; } } return false; } int main(void){ while(cin >> w >> h,w|h){ for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> g[i][j]; } } for(lim=0;;lim++){ if(dfs(0))break; } cout << lim << endl; } return 0; }
### Prompt Please create a solution in Cpp to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<vector> #include<algorithm> #include<string> using namespace std; int h,w,lim; int dx[4]={1,-1,0,0}; int dy[4]={0,0,1,-1}; char g[11][11]; string s="RGB"; void rev(int x,int y,vector<int>&p,char ch){ char tmp=g[y][x]; g[y][x]=ch; p.push_back(y*w+x); for(int i=0;i<4;i++){ int nx=x+dx[i],ny=y+dy[i]; if(nx<0 || ny<0 || w<=nx || h<=ny || g[ny][nx]!=tmp)continue; rev(nx,ny,p,ch); } } bool dfs(int d){ bool fg=true; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ fg&=(g[i][j]==g[0][0]); } } if(fg)return true; if(d>=lim)return false; for(int i=0;i<3;i++){ if(g[0][0]==s[i])continue; char tmp=g[0][0]; vector<int> p; rev(0,0,p,s[i]); if(dfs(d+1))return true; for(int j=0;j<p.size();j++){ g[p[j]/w][p[j]%w]=tmp; } } return false; } int main(void){ while(cin >> w >> h,w|h){ for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> g[i][j]; } } for(lim=0;;lim++){ if(dfs(0))break; } cout << lim << endl; } return 0; } ```
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <vector> #include <string> #include <map> #include <set> #include <queue> #include <stack> #include <algorithm> using namespace std; #define rep(i,j) REP((i), 0, (j)) #define REP(i,j,k) for(int i=(j);(i)<(k);++i) #define BW(a,x,b) ((a)<=(x)&&(x)<=(b)) #define ALL(v) (v).begin(), (v).end() #define LENGTHOF(x) (sizeof(x) / sizeof(*(x))) #define AFILL(a, b) fill((int*)a, (int*)(a + LENGTHOF(a)), b) #define MP make_pair #define PB push_back #define F first #define S second #define INF 1 << 30 #define EPS 1e-10 typedef pair<int, int> pi; typedef pair<int, pi> pii; typedef vector<int> vi; typedef queue<int> qi; typedef long long ll; int X, Y; int dx[] = {-1,0,1,0}, dy[] = {0,-1,0,1}; int res; int closed[16][16]; void filling(int s[16][16], int y, int x, int from, int to){ s[y][x] = to; rep(d, 4){ int ny = y + dy[d], nx = x + dx[d]; if(ny < 0 || ny >= Y || nx < 0 || nx >= X || s[ny][nx] != from) continue; filling(s, ny, nx, from, to); } return; } int check(int s[16][16]){ int p = s[0][0]; rep(i, Y) rep(j, X){ if(s[i][j] != p) return 0; } return 1; } void next(int from[16][16], int to1[16][16], int to2[16][16]){ int c1, c2; c1 = c2 = from[0][0]; c1 += 1; c2 += 2; c1 %= 3; c2 %= 3; rep(i, Y) rep(j, X){ to1[i][j] = to2[i][j] = from[i][j]; } queue<pi>open; open.push(pi(0, 0)); memset(closed, 0, sizeof(closed)); to1[0][0] = c1; to2[0][0] = c2; while(!open.empty()){ pi p = open.front(); open.pop(); rep(d, 4){ int ny = p.F + dy[d]; int nx = p.S + dx[d]; if(ny < 0 || nx < 0 || ny >= Y || nx >= X || closed[ny][nx] || from[0][0] != from[ny][nx]) continue; to1[ny][nx] = c1; to2[ny][nx] = c2; closed[ny][nx] = 1; open.push(pi(ny, nx)); } } } void dfs(int s[16][16], int n){ if(check(s)){ res = n; return; } if(res <= n) return; int n1[16][16]; int n2[16][16]; next(s, n1, n2); dfs(n1, n+1); dfs(n2, n+1); return; } int main(){ while(scanf("%d%d", &X, &Y) && X+Y){ int s[16][16]; getchar(); rep(i, Y) rep(j, X){ char c = getchar(); switch(c){ case 'R': s[i][j] = 0; break; case 'G': s[i][j] = 1; break; case 'B': s[i][j] = 2; break; } getchar(); } res = 18; dfs(s, 0); printf("%d\n", res); } return 0; }
### Prompt Your challenge is to write a cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <vector> #include <string> #include <map> #include <set> #include <queue> #include <stack> #include <algorithm> using namespace std; #define rep(i,j) REP((i), 0, (j)) #define REP(i,j,k) for(int i=(j);(i)<(k);++i) #define BW(a,x,b) ((a)<=(x)&&(x)<=(b)) #define ALL(v) (v).begin(), (v).end() #define LENGTHOF(x) (sizeof(x) / sizeof(*(x))) #define AFILL(a, b) fill((int*)a, (int*)(a + LENGTHOF(a)), b) #define MP make_pair #define PB push_back #define F first #define S second #define INF 1 << 30 #define EPS 1e-10 typedef pair<int, int> pi; typedef pair<int, pi> pii; typedef vector<int> vi; typedef queue<int> qi; typedef long long ll; int X, Y; int dx[] = {-1,0,1,0}, dy[] = {0,-1,0,1}; int res; int closed[16][16]; void filling(int s[16][16], int y, int x, int from, int to){ s[y][x] = to; rep(d, 4){ int ny = y + dy[d], nx = x + dx[d]; if(ny < 0 || ny >= Y || nx < 0 || nx >= X || s[ny][nx] != from) continue; filling(s, ny, nx, from, to); } return; } int check(int s[16][16]){ int p = s[0][0]; rep(i, Y) rep(j, X){ if(s[i][j] != p) return 0; } return 1; } void next(int from[16][16], int to1[16][16], int to2[16][16]){ int c1, c2; c1 = c2 = from[0][0]; c1 += 1; c2 += 2; c1 %= 3; c2 %= 3; rep(i, Y) rep(j, X){ to1[i][j] = to2[i][j] = from[i][j]; } queue<pi>open; open.push(pi(0, 0)); memset(closed, 0, sizeof(closed)); to1[0][0] = c1; to2[0][0] = c2; while(!open.empty()){ pi p = open.front(); open.pop(); rep(d, 4){ int ny = p.F + dy[d]; int nx = p.S + dx[d]; if(ny < 0 || nx < 0 || ny >= Y || nx >= X || closed[ny][nx] || from[0][0] != from[ny][nx]) continue; to1[ny][nx] = c1; to2[ny][nx] = c2; closed[ny][nx] = 1; open.push(pi(ny, nx)); } } } void dfs(int s[16][16], int n){ if(check(s)){ res = n; return; } if(res <= n) return; int n1[16][16]; int n2[16][16]; next(s, n1, n2); dfs(n1, n+1); dfs(n2, n+1); return; } int main(){ while(scanf("%d%d", &X, &Y) && X+Y){ int s[16][16]; getchar(); rep(i, Y) rep(j, X){ char c = getchar(); switch(c){ case 'R': s[i][j] = 0; break; case 'G': s[i][j] = 1; break; case 'B': s[i][j] = 2; break; } getchar(); } res = 18; dfs(s, 0); printf("%d\n", res); } return 0; } ```
#include<iostream> #include<sstream> #include<vector> #include<algorithm> #include<set> #include<map> #include<queue> #include<complex> #include<cstdio> #include<cstdlib> #include<cstring> #include<cassert> using namespace std; #define rep(i,n) for(int i=0;i<(int)n;i++) #define each(i,c) for(__typeof(c.begin()) i=c.begin();i!=c.end();i++) #define pb push_back #define mp make_pair #define all(c) c.begin(),c.end() #define dbg(x) cerr<<__LINE__<<": "<<#x<<" = "<<(x)<<endl typedef vector<int> vi; typedef pair<int,int> pi; typedef long long ll; const int inf=(int)1e9; const double EPS=1e-9, INF=1e12; const int dy[] = {-1, 0, 1, 0}, dx[] = {0, -1, 0, 1}; int w, h, lim; char c[10][10]; void nul(int y, int x, char col){ char tmp = c[y][x]; c[y][x] = col; rep(d, 4){ int ny = y + dy[d], nx = x + dx[d]; if(0 <= ny && ny < h && 0 <= nx && nx < w && c[ny][nx] == tmp) nul(ny, nx, col); } } bool rec(int step){ bool ok = 1; rep(i, h) rep(j, w) if(c[i][j] != c[0][0]) ok = 0; if(ok) return 1; if(step < lim){ char p[10][10]; rep(it, 3){ if("RGB"[it] == c[0][0]) continue; rep(i, h) rep(j, w) p[i][j] = c[i][j]; nul(0, 0, "RGB"[it]); if(rec(step + 1)) return 1; rep(i, h) rep(j, w) c[i][j] = p[i][j]; } } return 0; } int main(){ while(cin >> w >> h, h){ rep(i, h) rep(j, w) cin >> c[i][j]; for(lim = 0; lim < 20; lim++){ if(rec(0)) break; } cout << lim << endl; } return 0; }
### Prompt In CPP, your task is to solve the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<iostream> #include<sstream> #include<vector> #include<algorithm> #include<set> #include<map> #include<queue> #include<complex> #include<cstdio> #include<cstdlib> #include<cstring> #include<cassert> using namespace std; #define rep(i,n) for(int i=0;i<(int)n;i++) #define each(i,c) for(__typeof(c.begin()) i=c.begin();i!=c.end();i++) #define pb push_back #define mp make_pair #define all(c) c.begin(),c.end() #define dbg(x) cerr<<__LINE__<<": "<<#x<<" = "<<(x)<<endl typedef vector<int> vi; typedef pair<int,int> pi; typedef long long ll; const int inf=(int)1e9; const double EPS=1e-9, INF=1e12; const int dy[] = {-1, 0, 1, 0}, dx[] = {0, -1, 0, 1}; int w, h, lim; char c[10][10]; void nul(int y, int x, char col){ char tmp = c[y][x]; c[y][x] = col; rep(d, 4){ int ny = y + dy[d], nx = x + dx[d]; if(0 <= ny && ny < h && 0 <= nx && nx < w && c[ny][nx] == tmp) nul(ny, nx, col); } } bool rec(int step){ bool ok = 1; rep(i, h) rep(j, w) if(c[i][j] != c[0][0]) ok = 0; if(ok) return 1; if(step < lim){ char p[10][10]; rep(it, 3){ if("RGB"[it] == c[0][0]) continue; rep(i, h) rep(j, w) p[i][j] = c[i][j]; nul(0, 0, "RGB"[it]); if(rec(step + 1)) return 1; rep(i, h) rep(j, w) c[i][j] = p[i][j]; } } return 0; } int main(){ while(cin >> w >> h, h){ rep(i, h) rep(j, w) cin >> c[i][j]; for(lim = 0; lim < 20; lim++){ if(rec(0)) break; } cout << lim << endl; } return 0; } ```
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Info{ char map[10][10]; }; struct Data{ Data(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; char base_map[10][10]; bool FLG; char to_color[3] = {'R','G','B'}; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void back_track(Info info,int depth,int max_depth){ if(FLG)return; if(depth == max_depth){ bool is_cleared = true; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ if(info.map[row][col] != info.map[0][0]){ is_cleared = false; break; } } if(!is_cleared)break; } if(is_cleared){ FLG = true; return; } } char pre_color = info.map[0][0]; queue<Data> Q; int adj_row,adj_col; for(int loop = 0; loop < 3; loop++){ if(to_color[loop] == pre_color)continue; Info next_info; for(int row = 0;row < H; row++){ for(int col = 0; col < W; col++){ next_info.map[row][col] = info.map[row][col]; } } next_info.map[0][0] = to_color[loop]; Q.push(Data(0,0)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ adj_row = Q.front().row + diff_row[i]; adj_col = Q.front().col + diff_col[i]; if(!rangeCheck(adj_row,adj_col))continue; if(next_info.map[adj_row][adj_col] == pre_color){ next_info.map[adj_row][adj_col] = to_color[loop]; Q.push(Data(adj_row,adj_col)); } } Q.pop(); } if(depth < max_depth){ back_track(next_info,depth+1,max_depth); } } } void func(){ char buf[2]; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ scanf("%s",buf); base_map[row][col] = buf[0]; } } FLG = false; int ans = 0; for(int i = 0; ; i++){ Info info; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ info.map[row][col] = base_map[row][col]; } } back_track(info,0,i); if(FLG){ ans = i; break; } } printf("%d\n",ans); } int main(){ while(true){ scanf("%d %d",&W,&H); if(W == 0 && H == 0)break; func(); } return 0; }
### Prompt Your task is to create a Cpp solution to the following problem: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Info{ char map[10][10]; }; struct Data{ Data(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; char base_map[10][10]; bool FLG; char to_color[3] = {'R','G','B'}; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void back_track(Info info,int depth,int max_depth){ if(FLG)return; if(depth == max_depth){ bool is_cleared = true; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ if(info.map[row][col] != info.map[0][0]){ is_cleared = false; break; } } if(!is_cleared)break; } if(is_cleared){ FLG = true; return; } } char pre_color = info.map[0][0]; queue<Data> Q; int adj_row,adj_col; for(int loop = 0; loop < 3; loop++){ if(to_color[loop] == pre_color)continue; Info next_info; for(int row = 0;row < H; row++){ for(int col = 0; col < W; col++){ next_info.map[row][col] = info.map[row][col]; } } next_info.map[0][0] = to_color[loop]; Q.push(Data(0,0)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ adj_row = Q.front().row + diff_row[i]; adj_col = Q.front().col + diff_col[i]; if(!rangeCheck(adj_row,adj_col))continue; if(next_info.map[adj_row][adj_col] == pre_color){ next_info.map[adj_row][adj_col] = to_color[loop]; Q.push(Data(adj_row,adj_col)); } } Q.pop(); } if(depth < max_depth){ back_track(next_info,depth+1,max_depth); } } } void func(){ char buf[2]; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ scanf("%s",buf); base_map[row][col] = buf[0]; } } FLG = false; int ans = 0; for(int i = 0; ; i++){ Info info; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ info.map[row][col] = base_map[row][col]; } } back_track(info,0,i); if(FLG){ ans = i; break; } } printf("%d\n",ans); } int main(){ while(true){ scanf("%d %d",&W,&H); if(W == 0 && H == 0)break; func(); } return 0; } ```
#include<stdio.h> #include<algorithm> #include<queue> using namespace std; int dx[]={1,0,0,-1}; int dy[]={0,1,-1,0}; struct wolf{ int m[10][10]; wolf(){for(int i=0;i<10;i++)for(int j=0;j<10;j++)m[i][j]=0;} }; int st[10][10]; char str[2]; int a,b; int ret; void solve(int t,wolf w){ //printf("%d\n",t); //fflush(stdout); if(t>=ret)return; bool ok=true; for(int i=0;i<b;i++) for(int j=0;j<a;j++) if(w.m[i][j]!=w.m[0][0])ok=false; if(ok){ ret=t; return; } for(int i=1;i<4;i++){ if(w.m[0][0]==i)continue; wolf D=w; queue<pair<int,int> >Q; Q.push(make_pair(0,0)); D.m[0][0]=i; while(Q.size()){ int row=Q.front().first; int col=Q.front().second; Q.pop(); for(int j=0;j<4;j++) if(0<=row+dx[j]&&row+dx[j]<b&&0<=col+dy[j]&&col+dy[j]<a&&w.m[0][0]==D.m[row+dx[j]][col+dy[j]]){ Q.push(make_pair(row+dx[j],col+dy[j])); D.m[row+dx[j]][col+dy[j]]=i; } } solve(t+1,D); } } int main(){ while(scanf("%d%d",&a,&b),a){ for(int i=0;i<b;i++) for(int j=0;j<a;j++){ scanf("%s",str); if(str[0]=='R')st[i][j]=1; if(str[0]=='G')st[i][j]=2; if(str[0]=='B')st[i][j]=3; } ret=a+b; wolf S; for(int i=0;i<b;i++) for(int j=0;j<a;j++) S.m[i][j]=st[i][j]; for(int i=0;;i++){ ret=i+1; solve(0,S); if(ret<=i)break; } printf("%d\n",ret); } }
### Prompt Construct a CPP code solution to the problem outlined: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include<stdio.h> #include<algorithm> #include<queue> using namespace std; int dx[]={1,0,0,-1}; int dy[]={0,1,-1,0}; struct wolf{ int m[10][10]; wolf(){for(int i=0;i<10;i++)for(int j=0;j<10;j++)m[i][j]=0;} }; int st[10][10]; char str[2]; int a,b; int ret; void solve(int t,wolf w){ //printf("%d\n",t); //fflush(stdout); if(t>=ret)return; bool ok=true; for(int i=0;i<b;i++) for(int j=0;j<a;j++) if(w.m[i][j]!=w.m[0][0])ok=false; if(ok){ ret=t; return; } for(int i=1;i<4;i++){ if(w.m[0][0]==i)continue; wolf D=w; queue<pair<int,int> >Q; Q.push(make_pair(0,0)); D.m[0][0]=i; while(Q.size()){ int row=Q.front().first; int col=Q.front().second; Q.pop(); for(int j=0;j<4;j++) if(0<=row+dx[j]&&row+dx[j]<b&&0<=col+dy[j]&&col+dy[j]<a&&w.m[0][0]==D.m[row+dx[j]][col+dy[j]]){ Q.push(make_pair(row+dx[j],col+dy[j])); D.m[row+dx[j]][col+dy[j]]=i; } } solve(t+1,D); } } int main(){ while(scanf("%d%d",&a,&b),a){ for(int i=0;i<b;i++) for(int j=0;j<a;j++){ scanf("%s",str); if(str[0]=='R')st[i][j]=1; if(str[0]=='G')st[i][j]=2; if(str[0]=='B')st[i][j]=3; } ret=a+b; wolf S; for(int i=0;i<b;i++) for(int j=0;j<a;j++) S.m[i][j]=st[i][j]; for(int i=0;;i++){ ret=i+1; solve(0,S); if(ret<=i)break; } printf("%d\n",ret); } } ```
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Info{ char map[10][10]; }; struct Data{ Data(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; char base_map[10][10]; bool FLG; char to_color[3] = {'R','G','B'}; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void back_track(Info info,int depth,int max_depth){ if(FLG)return; if(depth == max_depth){ bool is_cleared = true; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ if(info.map[row][col] != info.map[0][0]){ is_cleared = false; break; } } if(!is_cleared)break; } if(is_cleared){ FLG = true; } return; } char pre_color = info.map[0][0]; queue<Data> Q; int adj_row,adj_col; for(int loop = 0; loop < 3; loop++){ if(to_color[loop] == pre_color)continue; Info next_info; for(int row = 0;row < H; row++){ for(int col = 0; col < W; col++){ next_info.map[row][col] = info.map[row][col]; } } next_info.map[0][0] = to_color[loop]; Q.push(Data(0,0)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ adj_row = Q.front().row + diff_row[i]; adj_col = Q.front().col + diff_col[i]; if(!rangeCheck(adj_row,adj_col))continue; if(next_info.map[adj_row][adj_col] == pre_color){ next_info.map[adj_row][adj_col] = to_color[loop]; Q.push(Data(adj_row,adj_col)); } } Q.pop(); } if(depth < max_depth){ back_track(next_info,depth+1,max_depth); } } } void func(){ char buf[2]; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ scanf("%s",buf); base_map[row][col] = buf[0]; } } FLG = false; int ans = 0; for(int i = 0; ; i++){ Info info; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ info.map[row][col] = base_map[row][col]; } } back_track(info,0,i); if(FLG){ ans = i; break; } } printf("%d\n",ans); } int main(){ while(true){ scanf("%d %d",&W,&H); if(W == 0 && H == 0)break; func(); } return 0; }
### Prompt Construct a cpp code solution to the problem outlined: The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows. * The screen has a 2D grid of X columns x Y rows. * The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B). * There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color. * When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color. It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps. As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time. <image> input Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format: X Y c1,1 c2,1 ... cX,1 c1,2 c2,2 ... cX,2 :: c1, Y c2, Y ... cX, Y The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks. output Outputs the minimum number of button operations on one line for each dataset. Example Input 3 3 R G B G G G G B B 2 4 R G G G R B B R 4 3 G G B R G R R G B G G R 0 0 Output 2 4 4 ### Response ```cpp #include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Info{ char map[10][10]; }; struct Data{ Data(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; }; int H,W; int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0}; char base_map[10][10]; bool FLG; char to_color[3] = {'R','G','B'}; bool rangeCheck(int row,int col){ if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true; else{ return false; } } void back_track(Info info,int depth,int max_depth){ if(FLG)return; if(depth == max_depth){ bool is_cleared = true; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ if(info.map[row][col] != info.map[0][0]){ is_cleared = false; break; } } if(!is_cleared)break; } if(is_cleared){ FLG = true; } return; } char pre_color = info.map[0][0]; queue<Data> Q; int adj_row,adj_col; for(int loop = 0; loop < 3; loop++){ if(to_color[loop] == pre_color)continue; Info next_info; for(int row = 0;row < H; row++){ for(int col = 0; col < W; col++){ next_info.map[row][col] = info.map[row][col]; } } next_info.map[0][0] = to_color[loop]; Q.push(Data(0,0)); while(!Q.empty()){ for(int i = 0; i < 4; i++){ adj_row = Q.front().row + diff_row[i]; adj_col = Q.front().col + diff_col[i]; if(!rangeCheck(adj_row,adj_col))continue; if(next_info.map[adj_row][adj_col] == pre_color){ next_info.map[adj_row][adj_col] = to_color[loop]; Q.push(Data(adj_row,adj_col)); } } Q.pop(); } if(depth < max_depth){ back_track(next_info,depth+1,max_depth); } } } void func(){ char buf[2]; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ scanf("%s",buf); base_map[row][col] = buf[0]; } } FLG = false; int ans = 0; for(int i = 0; ; i++){ Info info; for(int row = 0; row < H; row++){ for(int col = 0; col < W; col++){ info.map[row][col] = base_map[row][col]; } } back_track(info,0,i); if(FLG){ ans = i; break; } } printf("%d\n",ans); } int main(){ while(true){ scanf("%d %d",&W,&H); if(W == 0 && H == 0)break; func(); } return 0; } ```