Dasha and Photos CodeForces - 761F (前缀优化)

大意: 给定n*m初始字符矩阵, 有k个新矩阵, 第$i$个矩阵是由初始矩阵区间赋值得到的, 求选择一个新矩阵, 使得其余新矩阵到它距离和最小.

 

字符集比较小, 可以考虑每次区间覆盖对每个字符的贡献. 区间覆盖转化为差分, 然后前缀和优化.

刚开始辅助数组开多了, 卡内存卡了好久. 看别人代码似乎可以再优化掉两个辅助数组.

 

#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#include <bitset>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
#define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;})
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;}
//head



const int M = 3e5+10, N = 1e3+10;
int n, m, k;
char s[N][N];
int l[M], l2[M], r[M], r2[M], e[M];
int c[26][N][N], d[26][N][N];
ll sum[N][N], val[26][N][N];
void upd(int c[N][N], int l, int r, int l2, int r2, int v) {
	c[l][r]+=v,c[l][r2+1]-=v,c[l2+1][r]-=v,c[l2+1][r2+1]+=v;
}
ll get(ll c[N][N], int id) {
	return c[l2[id]][r2[id]]-c[l[id]-1][r2[id]]-c[l2[id]][r[id]-1]+c[l[id]-1][r[id]-1];
}

int main() {
	scanf("%d%d%d", &n, &m, &k);
	REP(i,1,n) scanf("%s", s[i]+1);
	REP(i,1,n) REP(j,1,m) s[i][j]-='a';
	REP(i,1,k) {
		char cc;
		scanf("%d%d%d%d %c", l+i,r+i,l2+i,r2+i,&cc);
		e[i] = cc-'a';
		REP(t,0,25) upd(d[t],l[i],r[i],l2[i],r2[i],-1);
		REP(t,0,25) upd(c[t],l[i],r[i],l2[i],r2[i],abs(e[i]-t));
	}
	REP(i,1,n) REP(j,1,m) { 
		REP(t,0,25) {
			d[t][i][j] += d[t][i-1][j]+d[t][i][j-1]-d[t][i-1][j-1];
			c[t][i][j] += c[t][i-1][j]+c[t][i][j-1]-c[t][i-1][j-1];
			val[t][i][j] = (ll)(k+d[t][i][j])*abs(t-s[i][j])+c[t][i][j];
		}
		sum[i][j] = val[s[i][j]][i][j]+sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1];
		REP(t,0,25) val[t][i][j]+=val[t][i-1][j]+val[t][i][j-1]-val[t][i-1][j-1];
	}
	ll ans = 1e18;
	REP(i,1,k) ans=min(ans,sum[n][m]-get(sum,i)+get(val[e[i]],i));
	printf("%lld\n", ans);
}

 

上一篇:Police Stations CodeForces - 796D (bfs)


下一篇:数论杂谈——欧几里得算法及扩展欧几里得