思路
思路很简单,照例是debug半天Orz
1. typeN 0表示数字,1表示公式,op 1表示sum,2表示avg, 3表示std
2. 字符串+正则处理 x1,x2,y1,y2为了图方便用了pair来存
3. dfs搜索时,遇到数字直接返回w的值,遇到公式则会进入下一层dfs进行计算
4. 全遍历输出dfs
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<regex>
#include<math.h>
// #include<pair.h>
using namespace std;
#define x first
#define y second
typedef pair<int,int> PII;
typedef pair<PII,PII> PIIPII;
const int N = 55;
int n, m;
int typeN[N*N]; // 0 - number, 1
double w[N*N];
int op[N*N];
PIIPII p[N*N];
regex patt1("\\d+");
double dfs(int x_y)
{
if(typeN[x_y] == 0)
return w[x_y];
if(op[x_y] == 1)
{
int x1 = p[x_y].x.x, y1 = p[x_y].x.y, x2 = p[x_y].y.x, y2 = p[x_y].y.y;
for(int i = x1; i<=x2; i++)
for(int j = y1;j<=y2;j++)
w[x_y] += dfs(i*m+j);
typeN[x_y] = 0;
}
else if(op[x_y] == 2)
{
int x1 = p[x_y].x.x, y1 = p[x_y].x.y, x2 = p[x_y].y.x, y2 = p[x_y].y.y;
for(int i = x1; i<=x2; i++)
for(int j = y1;j<=y2;j++)
w[x_y] += dfs(i*m+j);
w[x_y] /= (x2-x1+1)*(y2-y1+1);
typeN[x_y] = 0;
}
else if(op[x_y] == 3)
{
double mean = 0;
int x1 = p[x_y].x.x, y1 = p[x_y].x.y, x2 = p[x_y].y.x, y2 = p[x_y].y.y;
int cnt = (x2-x1+1)*(y2-y1+1);
for(int i = x1; i<=x2; i++)
for(int j = y1;j<=y2;j++)
mean += dfs(i*m+j);
mean /= cnt;
x1 = p[x_y].x.x, y1 = p[x_y].x.y, x2 = p[x_y].y.x, y2 = p[x_y].y.y;
for(int i = x1; i<=x2; i++)
for(int j = y1;j<=y2;j++)
w[x_y] += (dfs(i*m+j)-mean)*(dfs(i*m+j)-mean);
w[x_y] = sqrt(w[x_y]/cnt);
typeN[x_y] = 0;
}
return w[x_y];
}
int main()
{
scanf("%d%d", &n,&m);
string temp;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
cin >> temp;
if(0 <= temp[0]-'0' && temp[0]-'0'<=9) typeN[i*m+j] = 0, w[i*m+j] = (double)stoi(temp);
else{
typeN[i*m+j] = 1;
if(temp.substr(0,3) == "SUM") op[i*m+j] = 1;
else if(temp.substr(0,3) == "AVG") op[i*m+j] = 2;
else op[i*m+j] = 3;
string::const_iterator iterStart = temp.begin();
string::const_iterator iterEnd = temp.end();
int a[4], idx = 0;
smatch result;
while (regex_search(iterStart, iterEnd, result, patt1))
{
a[idx++] = stoi(result[0]);
iterStart = result[0].second; //更新搜索起始位置,搜索剩下的字符串
}
p[i*m+j].x.x = a[0]-1;
p[i*m+j].x.y = a[1]-1;
p[i*m+j].y.x = a[2]-1;
p[i*m+j].y.y = a[3]-1;
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j <m ; j ++)
printf("%.2lf ",dfs(i*m+j));
printf("\n");
}
}