2013年9月4日

UVa 196 - Spreadsheet

#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <sstream>
#include <string>
using namespace std;

int grid[1000][18279];
char formula[1000][18279][100];
bool done[1000][18279];

int solve(int r, int c) {
  if (done[r][c]) {
    return grid[r][c];
  }
  for (int i = 0; formula[r][c][i]; i++) {
    if (formula[r][c][i] == '+' || formula[r][c][i] == '=') {
      formula[r][c][i] = ' ';
    }
  }
  istringstream ss(formula[r][c]);
  string s;
  int sum = 0;
  while (ss >> s) {
    int r = 0, c = 0;
    for (int i = 0; s[i]; i++) {
      if (isdigit(s[i])) {
        r = r * 10 + (s[i] - '0');
      } else {
        c = c * 26 + (s[i] - 'A' + 1);
      }
    }
    sum += solve(r, c);
  }
  done[r][c] = true;
  return (grid[r][c] = sum);
}

int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    int R, C;
    scanf("%d%d", &C, &R);
    for (int r = 1; r <= R; r++) {
      for (int c = 1; c <= C; c++) {
        scanf("%s", formula[r][c]);
        done[r][c] = false;
        if (isdigit(formula[r][c][0])) {
          done[r][c] = true;
          grid[r][c] = atoi(formula[r][c]);
        }
      }
    }
    for (int r = 1; r <= R; r++) {
      for (int c = 1; c <= C; c++) {
        printf("%d%s", solve(r, c), c == C ? "\n" : " ");
      }
    }
  }
  return 0;
}

沒有留言:

張貼留言