#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=1005;
const int maxk=300005;
int n,m,p,x1[maxk],y1[maxk],x2[maxk],y2[maxk];
ll tot[maxn][maxn][27],sum[maxn][maxn][27],res=1e15;
char s[maxn][maxn],op[maxk][2];
void add(int x1,int y1,int x2,int y2,int ch) {
++x2,++y2;
++tot[x1][y1][ch];
++tot[x2][y2][ch];
--tot[x1][y2][ch];
--tot[x2][y1][ch];
}
void get_pre_tot() {
for (int i=1;i<=n;++i)
for (int j=1;j<=m;++j)
for (int k=1;k<=26;++k)
tot[i][j][k]+=tot[i-1][j][k];
for (int i=1;i<=n;++i)
for (int j=1;j<=m;++j)
for (int k=1;k<=26;++k)
tot[i][j][k]+=tot[i][j-1][k];
}
void get_pre_sum() {
for (int i=1;i<=n;++i)
for (int j=1;j<=m;++j)
for (int k=0;k<=26;++k)
sum[i][j][k]+=sum[i-1][j][k];
for (int i=1;i<=n;++i)
for (int j=1;j<=m;++j)
for (int k=0;k<=26;++k)
sum[i][j][k]+=sum[i][j-1][k];
}
ll edge(int x1,int y1,int x2,int y2) {
return sum[x2][y2][0]-sum[x1][y2][0]-sum[x2][y1][0]+sum[x1][y1][0];
}
ll block(int x1,int y1,int x2,int y2,int i) {
return tot[x2][y2][i]-tot[x1][y2][i]-tot[x2][y1][i]+tot[x1][y1][i];
}
ll query(int x1,int y1,int x2,int y2,int ch) {
ll ret=0;
ret+=edge(0,0,n,y1-1);
ret+=edge(0,y2,n,m);
ret+=edge(0,y1-1,x1-1,y2);
ret+=edge(x2,y1-1,n,y2);
for (int i=1;i<=26;++i)
ret+=llabs(i-ch)*block(x1-1,y1-1,x2,y2,i);
return ret;
}
int main()
{
scanf("%d%d%d",&n,&m,&p);
for (int i=1;i<=n;++i)
scanf("%s",s[i]+1);
for (int i=0;i<p;++i) {
scanf("%d%d%d%d%s",&x1[i],&y1[i],&x2[i],&y2[i],op[i]);
add(x1[i],y1[i],x2[i],y2[i],op[i][0]-'a'+1);
}
get_pre_tot();
for (int i=1;i<=n;++i)
for (int j=1;j<=m;++j) {
for (int k=1;k<=26;++k) {
sum[i][j][0]+=sum[i][j][k]=llabs(s[i][j]-'a'+1-k)*tot[i][j][k];
tot[i][j][0]+=tot[i][j][k];
}
tot[i][j][s[i][j]-'a'+1]+=p-tot[i][j][0];
}
get_pre_sum();
get_pre_tot();
for (int i=0;i<p;++i)
res=min(res,query(x1[i],y1[i],x2[i],y2[i],op[i][0]-'a'+1));
printf("%I64d\n",res);
return 0;
}
Codeforces Round #394 (Div. 2) F. Dasha and Photos 二维前缀和 矩阵神器
最新推荐文章于 2024-07-08 09:59:31 发布