原题链接:https://vjudge.net/problem/UVA-215 分类:杂题 备注:模拟,水题
代码如下:
#include<cstdio> #include<string> #include<cstring> #include<iostream> #include<iomanip> using namespace std; const int inf = 0x3f3f3f3f; int row, col, ans[20][10], vis[2005]; string s[20][10]; bool isNum(string x) { for (int i = 0; i < x.length(); i++) if (isalpha(x[i]))return false; return true; } int toNum(string x) { int bef = -1, pos = 0, ret = 0, base = 1; while (pos < x.length()) { while (isdigit(x[pos]) && pos < x.length())pos++; int tmp = 0; for (int k = bef + 1; k < pos; k++) tmp = 10 * tmp + x[k] - '0'; ret += base * tmp; if (pos < x.length()) { if (x[pos] == '+')base = 1; else if (x[pos] == '-')base = -1; } bef = pos; pos++; } return ret; } int dfs(int r, int c, string x) { if (vis[r * 100 + c])return inf; vis[r * 100 + c] = 1; //printf("vis[%d]\n", r * 100 + c); int bef = -1, pos = 0, ret = 0; int base = 1; while (pos < x.length()) { while ((isalpha(x[pos]) || isdigit(x[pos])) && pos < x.length())pos++; if (isalpha(x[bef + 1])) {//是字母+数字 int i = x[bef + 1] - 'A'; int j = 0, tmp = 0; for (int k = bef + 2; k < pos; k++) j = j * 10 + x[k] - '0'; if (ans[i][j] == inf) { if (vis[i * 100 + j]) return inf; else { tmp = dfs(i, j, s[i][j]); if (tmp == inf)return inf; } ret += base * tmp; } else ret += base * ans[i][j]; } else { int tmp = 0; for (int k = bef + 1; k < pos; k++) tmp = tmp * 10 + x[k] - '0'; ret += base * tmp; } if (pos < x.length()) { if (x[pos] == '+')base = 1; else if (x[pos] == '-')base = -1; } bef = pos; pos++; } return ans[r][c] = ret; } int main(void) { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); while (cin >> row >> col && row) { memset(ans, inf, sizeof(ans)); memset(vis, 0, sizeof(vis)); for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) { cin >> s[i][j]; if (isNum(s[i][j])) ans[i][j] = toNum(s[i][j]); } bool over = true; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) { if (ans[i][j] == inf) { if (inf == dfs(i, j, s[i][j])) over = false; } } if (over) { cout << " "; for (int i = 0; i < col; i++)cout << setw(6) << i; cout << endl; for (int i = 0; i < row; i++) { cout << (char)(i + 'A'); for (int j = 0; j < col; j++) cout << setw(6) << ans[i][j]; cout << endl; } } else { for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) if (ans[i][j] == inf) cout << (char)(i + 'A') << j << ": " << s[i][j] << endl; } cout << endl; } return 0; }