贪心是一种思维量很大的方法,对于求解最大值,最小值的问题,我们可以一般通过先猜后WA的来判断是否正确。
题目列表
- Least Prefix Sum
- Theofanis’ Nightmare
- Pinkie Pie Eats Patty-cakes
- Traps
- String Deletion
- Array Painting
- Tree Infection
Least Prefix Sum
题目:给定一个长度为n的数组a,和一个数字m。1<=m<=n<=1e5,-1e9<=a[i]<=1e9。操作一可以把数组的任意元素转成他的相反数。求使得pre_sum[m]为所有前缀和中的最小值。
思路:对于大于m的部分,我们只需要保证数组a[m:]的任意前缀和都大于零就行。参考加油站模型,反悔贪心。
对于小于m的部分,需要倒着考虑。
import sys
from heapq import heappop, heappush, heapify
input = lambda: sys.stdin.readline().rstrip('\r\n')
I = lambda: int(input())
MI = lambda: map(int, input().split())
GMI = lambda: map(lambda x: int(x) - 1, input().split())
LI = lambda: list(MI())
LGMI = lambda: list(GMI())
mod = 1000000007
mod2 = 998244353
tcn = I()
for _tcn_ in range(tcn):
n, m = MI()
a = LI()
pre_sum = [0] * (n + 1)
for i in range(n):
pre_sum[i + 1] = pre_sum[i] + a[i]
ans = 0
h = [-a[m - 1]]
tot = pre_sum[m]
for i in range(m - 1)[::-1]:
while pre_sum[i + 1] < tot:
x = heappop(h)
tot += 2 * x
ans += 1
heappush(h, -a[i])
h = []
tot = 0
for i in range(m, n, 1):
tot += a[i]
heappush(h, a[i])
while tot < 0:
x = heappop(h)
tot += 2 * (-x)
ans += 1
print(ans)
Theofanis Nightmare.
题意:给定一个长度为1e5的数组a,-1e8<a[i]<1e8,把数组分为k个子数组,求子数组下标(startwith=1)和子组数和乘积的最大值。
思路。先求后缀和数组,然后从左往右遍历,当后缀和大于零时,就分开成为新的子数组。
import sys
from functools import lru_cache
sys.stdin = open('./../input.txt', 'r')
I = lambda: int(input())
MI = lambda: map(int, input().split())
LI = lambda: list(map(int, input().split()))
tcn = I()
for _tcn_ in range(tcn):
N = I()
A = LI()
suf = [0] * (N + 1)
for i in range(N - 1, -1, -1):
suf[i] = suf[i + 1] + A[i]
ans = suf[0]
for i in range(1, N, 1):
if suf[i] > 0:
ans += suf[i]
print(ans)