codeforces 466C Number of Ways

本文介绍了一种将数组等分为三个连续子数组的方法,每个子数组的元素总和相等。通过两道示例题目详细解释了算法实现,并提供了两种不同的代码实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开链接

C. Number of Ways
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.

More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that .

Input

The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1]a[2], ..., a[n] (|a[i]| ≤  109) — the elements of array a.

Output

Print a single integer — the number of ways to split the array into three parts with the same sum.

Examples
input
5
1 2 3 0 3
output
2
input
4
0 1 -1 0
output
1
input
2
4 1
output
0
题意:将这个数组分成三段,每段的和相等,求有几种分法。

我自己没想出来,这个是我比较喜欢的一种

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
const int ma=5*1e5+10;
typedef long long ll;
using namespace std;
ll a[ma];
ll s=0,n;
vector<int>vec;
ll solve()
{
    if(s%3)
        return 0;
    s/=3;
    ll p=0;
    for(int i=0; i<n; i++)
    {
        p+=a[i];
        if(p==s)
            vec.push_back(i);
    }
    p=0;
    ll ans=0;
    for(int i=n-1;i>=0;i--)
    {
        p+=a[i];
        if(p==s)
            ans+=lower_bound(vec.begin(),vec.end(),i-1)-vec.begin();
    }
    return ans;
}
int main()
{
    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>a[i];
        s+=a[i];
    }
    cout<<solve()<<endl;
    return 0;
}
这个也能过,但是不明白all为0时,那个几种为什么是 (cnt-1)*(cnt-2)/2这个,如果你知道,欢迎评论,感激不尽。

#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
const int ma=500005;
ll a[ma],sum[ma];
int main()
{
    int n;
    cin>>n;
    sum[0]=0;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        sum[i]=sum[i-1]+a[i];
    }
    if(n==1)
        cout<<0<<endl;
    else
    {
        ll all=sum[n];
        if(all%3!=0)
            cout<<0<<endl;
        else if(all)
        {
            ll s=0;
            ll w1=all/3;
            ll w2=all/3*2;
            int cnt=0;
            for(int i=1;i<=n;i++)
            {
                if(sum[i]==w2)
                    s+=cnt;
                if(sum[i]==w1)
                    cnt++;
            }
            cout<<s<<endl;
        }
        else
        {
            ll cnt=0;
            for(int i=1;i<=n;i++)
            {
                if(sum[i]==0)
                    cnt++;
            }
            cout<<(cnt-1)*(cnt-2)/2<<endl;
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值