题目链接:Intercepted Message
题意
给定两个长度分别为 的序列 和 ,要将序列 和序列 分别划分成若干段,使得序列 的第 段数字的和等于序列 的第 段数字的和,问最多能够分成多少段。
输入
第一行为两个整数 ,第二行为 个整数 ,第三行为 个整数 ,数据保证 且
输出
输出能够分割的最大段数。
样例
输入 |
---|
7 6 2 5 3 1 11 4 4 7 8 2 4 1 8 |
输出 |
3 |
提示 |
段数字分别为: 。 |
输入 |
---|
3 3 1 10 100 1 100 10 |
输出 |
2 |
提示 |
可以将第 个数字分为一段,后面 个数字分为一段,由于不能修改数字的顺序,所以我们不能将 分为 段。 |
输入 |
---|
1 4 4 1 1 1 1 |
输出 |
1 |
提示 |
序列只有一个数字,所以只能分成 段。 |
题解
类似于归并排序,给两个序列各加一个指针,分别移动,哪一个序列加的数字小于另一个序列的数,就将那个序列的指针往后移动,每次移动到相等,就将答案 。
过题代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iomanip>
using namespace std;
#define LL long long
const int maxn = 100000 + 100;
int n, m, cnt;
LL suma, sumb;
LL a[maxn], b[maxn];
int main() {
#ifdef LOCAL
freopen("test.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif // LOCAL
ios::sync_with_stdio(false);
while(scanf("%d%d", &n, &m) != EOF) {
for(int i = 0; i < n; ++i) {
scanf("%I64d", &a[i]);
}
for(int i = 0; i < m; ++i) {
scanf("%I64d", &b[i]);
}
cnt = 0;
int Index = 0;
suma = sumb = 0;
for(int i = 0; i < n; ++i) {
suma += a[i];
while(sumb < suma) {
sumb += b[Index];
++Index;
}
if(sumb == suma) {
++cnt;
suma = sumb = 0;
}
}
printf("%d\n", cnt);
}
return 0;
}