luogu P3941 入阵曲

嘟嘟嘟

这道题我觉得跟最大子矩阵那道题非常像,都是O(n4)二维前缀和暴力很好想,O(n3)正解需要点转化。

O(n4)暴力就不说啦,二维前缀和,枚举所有矩形,应该能得55分。

O(n3)需要用到降维的思想。先考虑这么个问题:对于一个序列,求区间和是k的倍数的区间个数。有点想法的暴力就是前缀和预处理,然后O(n2)枚举。那么能不能不枚举呢?观察会发现,任意两个 mod k余数相同的前缀和相减得到的区间,都能被k整除。有了这一点,这道题就变成求余数相同的前缀有多少对了。那么开一个数组dp[i]记录余数为 i 的前缀有多少个,则有dp[i] * (dp[i] - 1) / 2对。O(n)即可完成。

现在升级成二维。那么只要枚举矩形上下两条边,当这两条边固定的时候就变成了上述问题了。时间复杂度O(n3)。

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cmath>
 4 #include<algorithm>
 5 #include<cstring>
 6 #include<cstdlib>
 7 #include<cctype>
 8 #include<vector>
 9 #include<stack>
10 #include<queue>
11 using namespace std;
12 #define enter puts("") 
13 #define space putchar(' ')
14 #define Mem(a, x) memset(a, x, sizeof(a))
15 #define rg register
16 typedef long long ll;
17 typedef double db;
18 const int INF = 0x3f3f3f3f;
19 const db eps = 1e-8;
20 const int maxn = 405;
21 const int maxk = 1e6 + 5;
22 inline ll read()
23 {
24   ll ans = 0;
25   char ch = getchar(), last = ' ';
26   while(!isdigit(ch)) {last = ch; ch = getchar();}
27   while(isdigit(ch)) {ans = (ans << 1) + (ans << 3) + ch - '0'; ch = getchar();}
28   if(last == '-') ans = -ans;
29   return ans;
30 }
31 inline void write(ll x)
32 {
33   if(x < 0) x = -x, putchar('-');
34   if(x >= 10) write(x / 10);
35   putchar(x % 10 + '0');
36 }
37 
38 int n, m, K, a[maxn][maxn];
39 ll sum[maxn][maxn], ans = 0;
40 int dp[maxk], num[maxn], cnt = 0;
41 
42 int main()
43 {
44   n = read(), m = read(), K = read();
45   for(int i = 1; i <= n; ++i)
46     for(int j = 1; j <= m; ++j) a[i][j] = read();
47   for(int j = 1; j <= m; ++j)
48     for(int i = 1; i <= n; ++i) sum[j][i] = sum[j][i - 1] + a[i][j];
49   for(int i = 1; i <= n; ++i)
50     for(int j = i; j <= n; ++j)
51       {
52     cnt = 0;
53     num[++cnt] = 0; dp[0] = 1;
54     ll Sum = 0;
55     for(int k = 1; k <= m; ++k)
56       {
57         Sum += sum[k][j] - sum[k][i - 1];
58         int tp = Sum % K;
59         if(!dp[tp]) num[++cnt] = tp;
60         dp[tp]++;
61       }
62     for(int k = 1; k <= cnt; ++k)
63       {
64         ans += (ll)dp[num[k]] * (ll)(dp[num[k]] - 1) / 2;
65         dp[num[k]] = 0;
66       }
67       }
68   write(ans), enter;
69   return 0;
70 }
View Code
原文地址:https://www.cnblogs.com/mrclr/p/9872800.html