習題 6-13 電子表格計算器(Spreadsheet Calculator,ACM/ICPC World Finals 1992,UVa215)

原題鏈接: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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章