合并数列

我懂了!这道题有大坑!看题目这个样例,我还以为是只能变动a数组,然他和b数组一样,但是其实是两个数组都能变动,而所有测试数据就是这样设置的!

亏我还以为自己聪明了不少,还自以为是前缀和呢,在那里嘎嘎写,结果一个都没过QwQ。

后面我知道怎么做了,但是不知道为什么还是不行,就是当我使用到while的时候,想直接一口气把连续的都加上的时候,为什么就不行了呢?求求大家如果有空的话麻烦帮小弟看看QAQ。下面是大错特错的核心代码:

//和正确答案的区别在于,这个代码将队首元素单独提取出来进行累加,直到sa==sb,比如现在sa>sb,那应该将sb累加,因为是连续的,所以第一个不满足sa>sb的情况一定是sa==sb的情况,但是这样通过率却为0...
	int sa, sb;
    int ans = 0;
    while (!a.empty())
    {
        sa = a.front();
        sb = b.front();
        a.pop();
        b.pop();
        while (sa > sb)
        {
            sb += b.front();
            b.pop();
            ans++;
        }
        while (sa < sb)
        {
            sa += a.front();
            a.pop();
            ans++;
        }
    }

AC:

#include <iostream>
#include <queue>
using namespace std;

queue<int>a;
queue<int>b;
int n, m;

int  main()
{
	cin >> n >> m;
	int t;
	for (int i = 0; i < n; i++)
	{
		cin >> t;
		a.push(t);
	}
	for (int i = 0; i < m; i++)
	{
		cin >> t;
		b.push(t);
	}
	int ans = 0;
	while (!a.empty())
	{
		if (a.front() == b.front())
		{
			a.pop();
			b.pop();
		}
		else if (a.front() > b.front())
		{
			int temp = b.front();
			b.pop();
			b.front() += temp;
			ans++;
		}
		else
		{
			int temp = a.front();
			a.pop();
			a.front() += temp;
			ans++;
		}

	}
	cout << ans;
	return 0;
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐