[蓝桥杯]真题讲解:班级活动(贪心)
一、视频讲解
二、正解代码
1、C++
cpp
#include<bits/stdc++.h>
#define int long long
using namespace std;
signed main(){
int n, m; cin >> n >> m;
vector<int>a(n), b(m);
for(int i = 0; i < n; i ++)
cin >> a[i];
for(int j = 0; j < m; j ++)
cin >> b[j];
int p1 = 0, s1 = a[0], p2 = 0, s2 = b[0];
int ans = 0;
while(p1 < n || p2 < m) {
if(s1 < s2) {
p1 ++;
s1 += a[p1];
ans ++;
} else if(s1 > s2) {
p2 ++;
s2 += b[p2];
ans ++;
}else{
p1 ++;
p2 ++;
if(p1 < n)
s1 = a[p1];
if(p2 < m)
s2 = b[p2];
}
}
cout << ans << endl;
return 0;
}
2、python3
python
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
p1, s1, p2, s2 = 0, a[0], 0, b[0]
ans = 0
while p1 < n or p2 < m:
if s1 < s2:
p1 += 1
s1 += a[p1]
ans += 1
elif s1 > s2:
p2 += 1
s2 += b[p2]
ans += 1
else:
p1 += 1
p2 += 1
if p1 < n:
s1 = a[p1]
if p2 < m:
s2 = b[p2]
print(ans)
3、Java
java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
List<Integer> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
for(int i = 0; i < n; i ++) {
int x = sc.nextInt();
a.add(x);
}
for(int i = 0; i < m; i ++) {
int x = sc.nextInt();
b.add(x);
}
int p1 = 0, s1 = a.get(0), p2 = 0, s2 = b.get(0);
int ans = 0;
while(p1 < n || p2 < m) {
if(s1 < s2){
p1 ++;
s1 += a.get(p1);
ans ++;
}else if(s1 > s2){
p2 ++;
s2 += b.get(p2);
ans ++;
}else{
p1 ++;
p2 ++;
if(p1 < n)
s1 = a.get(p1);
if(p2 < m)
s2 = b.get(p2);
}
}
System.out.println(ans);
}
}