codeforces 1036D 貪心

個人博客鏈接:https://blog.nuoyanli.com/2020/03/25/cf_1036d/

題目鏈接

https://codeforces.com/problemset/problem/1036/D

題意

給你兩個數列,現在可以將數列中的連續的一些元素合併爲一個元素。你現在的任務就是對這兩個數列進行操作,使得這兩個數列相等。求序列相等的最大長度,如果不能相等輸出1-1

思路

  • 如果兩個數列和不一樣,答案肯定是1-1

  • 如果數列和一樣,則一定有答案,至少也是11,考慮貪心,直接從前到後枚舉:

    如果a[la]==b[lb],la++,lb++a[la]==b[lb],la++,lb++直接後移

    如果a[la]>b[lb],b[lb+1]+=b[lb],lb++,lenba[la]>b[lb],b[lb+1]+=b[lb],lb++,lenb--使小的那個合併到他的下一個

    同理:如果a[la]<b[lb],a[la+1]+=a[la],la++,lenaa[la]<b[lb],a[la+1]+=a[la],la++,lena--

最後lena(lenb)lena(lenb)就是答案。

參考代碼

#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false), cin.tie(0)
#define endl '\n'
#define PB push_back
#define FI first
#define SE second
#define m_p(a, b) make_pair(a, b)
const double pi = acos(-1.0);
const double eps = 1e-9;
typedef long long LL;
const int N = 1e6 + 10;
const int M = 1e5 + 10;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const double f = 2.32349;
LL a[N], b[N];
void solve() {
  IOS;
  int n, m;
  cin >> n;
  LL suma = 0, sumb = 0;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    suma += a[i];
  }
  cin >> m;
  for (int i = 1; i <= m; i++) {
    cin >> b[i];
    sumb += b[i];
  }
  if (suma != sumb) {
    cout << -1 << endl;
  } else {
    int ansn = n, ansm = m;
    int la = 1, lb = 1;
    while (la != n + 1 && lb != m + 1) {
      if (a[la] == b[lb]) {
        la++;
        lb++;
      } else if (a[la] < b[lb]) {
        a[la + 1] += a[la];
        la++;
        ansn--;
      } else {
        b[lb + 1] += b[lb];
        lb++;
        ansm--;
      }
    }
    cout << ansn << endl;
  }
}
signed main() {
  solve();
  return 0;
}
/*
49
18 1 7 2 1 1 50 22 8 2 2 1 30 2 46 10 1 4 5 18 25 21 38 11 2 15 29 8 7 2 45 12
14 16 16 23 11 1 1 4 48 18 3 1 1 23 4 10 7 50 5 25 34 22 19 4 4 2 40 52 1 4 1 3
47 9 4 1 8 47 4 5 1 1 9 22 9 2 2 1 1 48 7 2 8 16 4 2 41 12 3 30 21 10 2 2 5 1 31
13
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章