这道题是我放了好久又做的
开始的时候觉得根本无从下手,也不知道找什么样的数据结构来装载这些值和表达式
这次写出来但有调试了很久的原因是我没有分清行和列的概念
但是一旦调试成功过了样例,代码基本上就没问题了
这道题我用了两种数据类型:lnode和node。node主要是装载表格的值和指针。lnode则是来装载表达式所表达出的链表。
#include <cstdio> #include <cstdlib> #include <cstring> int m, n; char s[1000]; struct lnode{ int _x, _y; lnode *next; }; struct node{ int data; lnode *next; }; node st[2000][2000]; void translate(node &p)//表达式翻译成链表 { int len = strlen(s), x = 0, y; lnode *q, *pq; for(int i = 1, j = 0;i<len;i++, j++) { x = 0; y = 0; while(s[i]>='A'&&s[i]<='Z') y = y*26+s[i++]-'A'+1; while(s[i]>='0'&&s[i]<='9') x = x*10+s[i++]-'0'; q = (lnode*)malloc(sizeof(lnode)); q->_x = x-1; q->_y = y-1; if(j==0) {p.next = q; pq = q;} else {pq->next = q; pq = q;} } pq->next = NULL; } int dfs(node &cur)//深搜求值 { int x, y, sum = 0; lnode *p = cur.next; for(;p;p = p->next) { x = p->_x; y = p->_y; if(st[x][y].data!=-1) sum+=st[x][y].data; else sum+=dfs(st[x][y]); } cur.data = sum; return sum; } int main () { int cas, tt; scanf("%d",&cas); while(cas--) { scanf("%d%d",&n,&m); getchar(); for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) { if(scanf("%d",&tt)!=0)//如果读取整数成功的话 { st[i][j].data = tt; st[i][j].next = NULL; } else//则把表达式读入到一个数组中 { scanf("%s",s); st[i][j].data = -1; translate(st[i][j]); } getchar(); } for(int i = 0; i < m; i++, printf("\n")) for(int j = 0; j < n; j++) { if(j) printf(" "); if(st[i][j].data!=-1) printf("%d",st[i][j].data); else printf("%d",dfs(st[i][j])); } } return 0; }