Codeforces 950B Intercepted Message 贪心

题目链接:Intercepted Message

题意

给定两个长度分别为 n , m 的序列 x 1 , x 2 , , x n y 1 , y 2 , , y m ,要将序列 X 和序列 Y 分别划分成若干段,使得序列 X 的第 i 段数字的和等于序列 Y 的第 i 段数字的和,问最多能够分成多少段。

输入

第一行为两个整数 n , m   ( 1 n , m 10 5 ) ,第二行为 n 个整数 x 1 , x 2 , , x n   ( 1 x i 10 6 ) ,第三行为 m 个整数 y 1 , y 2 , , y m   ( 1 y i 10 6 ) ,数据保证 i = 1 n x i = i = 1 m y i i = 1 n x i 10 6

输出

输出能够分割的最大段数。

样例

输入
7 6
2 5 3 1 11 4 4
7 8 2 4 1 8
输出
3
提示
3 段数字分别为: 2 + 5 = 7 , 15 = 3 + 1 + 11 = 8 + 2 + 4 + 1 , 4 + 4 = 8
输入
3 3
1 10 100
1 100 10
输出
2
提示
可以将第 1 个数字分为一段,后面 2 个数字分为一段,由于不能修改数字的顺序,所以我们不能将 1   10   100 分为 3 段。
输入
1 4
4
1 1 1 1
输出
1
提示
A 序列只有一个数字,所以只能分成 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;
}

猜你喜欢

转载自blog.csdn.net/CSDNjiangshan/article/details/81388693