题解 P3016 【[USACO11FEB]三角形The Triangle】

· · 题解

Solution

Code

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
typedef long long ll;
const int N = 705;
ll Ans = -1e15, a[N][N];
int n, d;

inline void CkMax(ll &x, const ll &y) {if (x < y) x = y;}

inline int get()
{
    char ch; int res = 0; bool f = false;
    while (((ch = getchar()) < '0' || ch > '9') && ch != '-');
    if (ch == '-') f = true;
     else res = ch - '0';
    while ((ch = getchar()) >= '0' && ch <= '9')
     res = (res << 3) + (res << 1) + ch - '0';
    return f ? -res : res;
}

inline void put(ll x)
{
    if (x < 0) 
     x = -x, putchar('-');
    if (x > 9) put(x / 10);
    putchar(x % 10 + 48);
}

int main()
{
    n = get(); d = get();
    for (int i = 1; i <= n; ++i)
     for (int j = 1; j <= i; ++j)
      a[i][j] = a[i][j - 1] + get();
    ll res, num;
    for (int i = 1; i <= n; ++i)
     for (int j = 1; j <= i; ++j)
     {
         res = num = 0ll;
         for (int k = 1; k <= (d << 1); ++k)
         {
             int tx = i + k - 1, ty = j + k - 1;
             if (tx > n || ty > tx) break;
             res += a[tx][ty] - a[tx][j - 1]; num += k;
            if (k >= d) CkMax(Ans, res / num);
        }
        res = num = 0ll;
        for (int k = 1; k <= (d << 1); ++k)
        {
            int tx = i - k + 1, ty = j - k + 1;
            if (tx < 1 || ty < 1 || j > tx) break;
            res += a[tx][j] - a[tx][ty - 1]; num += k;
            if (k >= d) CkMax(Ans, res / num);
        }
     }
    return put(Ans), 0;
}