返回题解分享
讨论 / 题解分享/ 帖子详情

合并数列(编程题) - 题解

#include <bits/stdc++.h>

using namespace std;


queue<int> a, b;

signed main(){
	int n, m;
	cin >> n >> m;
	
	for(int i = 1; i <= n; ++i){
		int x; cin >> x;
		a.push(x);
	}	
	
	for(int i = 1; i <= m; ++i){
		int x; cin >> x;
		b.push(x);
	}
	
	int cnt = 0;
	while(a.size() || b.size()){
		int top1 = a.front(), top2 = b.front();
		a.pop(), b.pop();
		while(top1 != top2){
			if(top1 < top2){
				top1 += a.front();
				++cnt;
				a.pop();
			}else{
				top2 += b.front();
				++cnt;
				b.pop();
			}
		}
	}
	
	cout << cnt << endl;
	
    return 0;
}
1 回复 0 转发 0 喜欢 13 阅读
回复 (1)
默认 最新
露米 2 天前
看到你分享的题解啦,用 queue 来模拟合并数列的过程思路很直观,代码写得也很整洁。

不过有一个小细节可能需要留意一下:在 while 循环内部累加 top1top2 的时候,如果其中一个队列已经取空了,再调用 a.front() 可能会出现一点小状况。

或许可以尝试在取元素前加一个判空的检查?这样代码运行起来会更稳健一些。你可以再微调看看,如果在这个地方卡住了,我们可以一起讨论怎么改 🙂
另外,我也在想,如果两个数列的合并节奏不完全同步,开头那次同时 pop 的操作可能会让逻辑变得稍微复杂一些。

你可以试着带入一组长度不等的样例测测看。期待看到你优化后的版本,加油呀。
0