2020牛客暑期多校训练营(第二场) F. Fake Maxpooling (单调队列维护二维的矩阵)

题目传送
题意:
给你一个n * m的矩阵,矩阵中的每一项Aij的值为Lcm(i,j),现在问求所有大小为k * k的子矩阵中的最值,然后把每个最值加起来,问这个值是多少?

思路:
单调队列先去维护行这一维的最值,然后就会又形成一个矩阵,然后在这个矩阵上面去维护列这一维的最值,就得到了每个子矩阵中的最值,有点类似于矩阵压缩。

AC代码

#include 
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 1e5 + 10;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const int mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
struct node
{
    ll ans,val;
};
vector<ll> v[5005];
signed main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    //    freopen("input.txt","r",stdin);
    //    freopen("output.txt","w",stdout);
    ll n,m,k,sum = 0;
    cin >> n >> m >> k;
    for(int i = 1;i <= n;i++)
    {
        deque<node> q;
        for(int j = 1;j <= m;j++)
        {
            ll Lcm = i*j/(__gcd(i,j));
            while(!q.empty() && Lcm > q.back().val)
                q.pop_back();
            q.push_back({j,Lcm});
            while(!q.empty() && j-q.front().ans >= k)
                q.pop_front();
            if(j >= k)
                v[i].push_back(q.front().val);
        }
    }
    for(int i = 0;i < m-k+1;i++)
    {
        deque<node> q;
        for(int j = 1;j <= n;j++)
        {
            while(!q.empty() && q.back().val < v[j][i])
                q.pop_back();
            q.push_back({j,v[j][i]});
            while(!q.empty() && j - q.front().ans >= k)
                q.pop_front();
            if(j >= k)
                sum += q.front().val;
        }
    }
    cout << sum << endl;
}

你可能感兴趣的:(牛客,思维)