您的位置:首页 > 其它

UVA 215 Spreadsheet Calculator (模拟)

2015-11-11 23:19 357 查看
模拟题。每个单元格有表达式就dfs,如果有环那么就不能解析,可能会重复访问到不能解析的单元格,丢set里或者数组判下重复。

这种题首先框架要对,变量名不要取的太乱,细节比较多,知道的库函数越多越容易写。注意细节,注意格式。

/*********************************************************
*      --------------Tyrannosaurus---------              *
*   author AbyssalFish                                   *
**********************************************************/
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

const int R = 20, C = 10, LEN = 76;

struct Node
{
int n;
string s;
bool tp; //1 num 0 expr
Node(){ s.reserve(LEN); }
}nd[R][C];
int Err[R][C], kas_clk;

void readNd(int x,int y)
{
Node &u = nd[x][y];
getline(cin, u.s);
u.tp = !isalpha(u.s[0]);// - ,1, A
if(u.tp) {
stringstream ssin(u.s);
ssin>>u.n;
}
}

const int ErrorCode = 1<<30;

typedef pair<int,int> pii;
vector<pii > un_ev;

int vis[R][C], clk;
//parseNd
int dfs(int x,int y)
{
Node &u = nd[x][y];
if(u.tp) return u.n;
if(Err[x][y] == kas_clk) return ErrorCode;
if(vis[x][y] == clk) {
Err[x][y] = kas_clk;
un_ev.push_back(pii(x,y));
return ErrorCode;
}
vis[x][y] = clk;
int ans = 0, sz = u.s.size();
//stack<char> stk;
for(int i = 0; i < sz; i++){
if(isalpha(u.s[i])){
int val = dfs(u.s[i]-'A',u.s[i+1]-'0');
if(val == ErrorCode) {
if(Err[x][y] != kas_clk){
Err[x][y] = kas_clk;
un_ev.push_back(pii(x,y));
}
return ErrorCode;
}
char op = i?u.s[i-1]:'+';//stk.top(); stk.pop();
ans += op=='+'?val:-val;
i++;
}
else if(isdigit(u.s[i])){
int j = i+1;
while(j < sz && isdigit(u.s[j])) j++;
int val = atoi(u.s.substr(i,j).c_str());
ans += u.s[i-1]=='+'?val:-val;
i = j-1;
}
//if(s[i] == '+' || s[i] == '-'){
//}
}
u.tp = true;
return u.n = ans;
}

void init()
{
un_ev.reserve(R*C);
}

int r,c;
void solve()
{
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
readNd(i,j);
}
}
kas_clk++;
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++){
if(Err[i][j] != kas_clk){
clk++;
dfs(i,j);
}
}
if(un_ev.size()){
sort(un_ev.begin(),un_ev.end());
//un_ev.erase(unique(un_ev.begin(),un_ev.end()),un_ev.end());
for(auto p: un_ev){
int x = p.first, y = p.second;
printf("%c%c: %s\n",x+'A',y+'0',nd[x][y].s.c_str());
}
un_ev.clear();
}
else {
putchar(' ');
for(int j = 0; j < c; j++) printf("%6d",j);
puts("");
for(int i = 0; i < r; i++){
putchar(i+'A');
for(int j = 0; j < c; j++){
printf("%6d",nd[i][j].n);
}
puts("");
}
}
puts(""); //注意格式
}

//#define LOCAL
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif
//ios::sync_with_stdio(false);
//cin.tie(nullptr);
init();
while(scanf("%d%d\n",&r,&c),r+c){
solve();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: