前缀和|差分

发布于:2025-07-11 ⋅ 阅读:(14) ⋅ 点赞:(0)

题目:MT2047距离平方和

你有𝑛n个点,请编写一个程序,求这𝑛n个点的距离的平方和。

格式

输入格式:

第一行:一个整数𝑛(0≤𝑛≤100000)n(0≤n≤100000);
接下来𝑛n行:每行两个整数𝑥,𝑦x,y,表示该点坐标(−10000≤𝑥,𝑦≤10000)(−10000≤x,y≤10000)。

输出格式:

仅一行:所有点的距离的平方和。

样例 1

输入:

4
1 1
-1 -1
1 -1
-1 1

输出:

32
#include<bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    long long ans = 0; 
    long long sx = 0, sy = 0;  
    for (int i = 0; i < n; ++i) {
        int x, y;
        cin >> x >> y;
        ans += (n - 1LL) * (x*x + y*y) - 2 * (x*sx + y*sy);
        sx += x;
        sy += y;
    }
    cout << ans;
    return 0;
}

题目:MT2051矩形

给定一个N∗M的矩阵,11表示已经占用了,00表示没有被占用,求一个由00构成的矩阵,使其周长最大。

格式

输入格式:

第一行两个整数𝑛,𝑚n,m含义如上;
接下来𝑛n行每行𝑚m个数表示这个矩阵。

输出格式:

输出一个数,表示最大周长。

样例 1

输入:

3 3
000
010
000

输出:

8
样例 2

输入:

5 4
1100
0000
0000
0000
0000

输出:

16
#include<bits/stdc++.h>
using namespace std;
//二维前缀和模版题
int main( )
{
    int n,m;
    cin>>n>>m;
    int sum[30][30];
    memset(sum,0,sizeof(sum));
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            char x;
            cin>>x;
            sum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+x-'0';
        }
    }
    int maxn=0;
    for(int x1=1;x1<=n;x1++){
        for(int y1=1;y1<=m;y1++){
            for(int x2=x1;x2<=n;x2++){
                for(int y2=y1;y2<=m;y2++){
                    if(sum[x2][y2]-sum[x2][y1-1]-sum[x1-1][y2]+sum[x1-1][y1-1]>0)
                        continue; 
                        maxn=max(maxn,(x2-x1+1+y2-y1+1)*2);
                }
            }
        }
    }  
    cout<<maxn;
    return 0; 
}

知识点

memest :初始化数组或结构体。


网站公告

今日签到

点亮在社区的每一天
去签到