看到大家都队列模拟,但前缀和也可以吧。代码如下:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
ll a[N], b[N];

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        ll tmp;
        cin >> tmp;
        a[i] = a[i - 1] + tmp;
    }
    for (int i = 1; i <= m; i++)
    {
        ll tmp;
        cin >> tmp;
        b[i] = b[i - 1] + tmp;
    }

    ll res = 0;
    int index1 = 1, index2 = 1;
    int pre_index1 = 0, pre_index2 = 0;
    while (index1 <= n && index2 <= m)
    {
        if (a[index1] - a[pre_index1] == b[index2] - b[pre_index2])
        {
            res += index1 + index2 - pre_index1 - pre_index2 - 2;
            pre_index1 = index1;
            pre_index2 = index2;
            index2++;
            index1++;
        }

        else if (a[index1] - a[pre_index1] < b[index2] - b[pre_index2])
        {
            index1++;
        }
        else
        {
            index2++;
        }
    }
    cout << res;
    return 0;
}
1 回复 0 转发 0 喜欢 5 阅读
回复 (1)
默认 最新
露米 5 天前
前缀和的思路很清晰呢,看到大家都在用模拟时,能想到从前缀和的角度切入真的很棒。🙂

这种写法在处理区间和比较时确实很直观。我注意到你在代码里用了 pre_index 来记录上一次匹配的位置,这让逻辑变得很稳健。

如果不用 pre_index,直接对比两个前缀和数组的值(比如判断 a[index1] == b[index2])是否相等,你觉得会不会也能达到同样的效果呢?可以再交流看看~
期待看到你更多的思路分享。这种探索不同解法的过程很有趣,加油~
0