每日好题
题目链接:https://codeforces.com/contest/747/problem/D
题目描述:
给你 n(<=2e5) 个数表示每天的温度 t[i] (-20<=t[i]<=20),到达目的地需要 n 天。
你有两个轮胎,雪地胎和普通胎。
雪地胎可以在任何温度行驶,但只能用 k(<=n) 天。(不一定要连续使用 k 天)
普通胎只能在温度不为负的时候行驶,使用天数无限制。
你一开始用的是普通胎。在每天开始可以选择更换为另一种轮胎。
问这 n 天需要最少换几次轮胎?若无法做到则输出 -1。
输入输出
输入 t=[-1,0,-1,0], k=3
输出 2
解释 前三天用雪地胎,最后一天用普通胎,因此第一天和最后一天要换轮胎
题解
看一下数据范围,这道题一开始想法是状态机DP,但是发现换不换轮胎对之前还有之后的决策都是有影响的,所以只能考虑贪心了。朴素的想法是低温雪地轮胎必须要用,中间合并尽可能多的区间,但是第一个区间必须更换雪地轮胎,同时最后一个区间也需要特判是否需要更换轮胎。如果中间区间可以合并,那么更换次数可以减少2.
// shiran
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, n) for (int i = a; i < n; i++)
#define per(i, n, a) for (int i = n - 1; i >= a; i--)
#define sz(x) (int)size(x)
#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define pb push_back
#define mk make_mair
typedef long long ll;
typedef pair<int, int> PII;
const int mod = 1e9+7;
const int N = 200010, M = 300010;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int n, k;
int a[N];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> k;
rep(i, 1, n + 1) cin >> a[i];
int cnt = 0, ans = 0, last = 0;
vector<int> v;
rep(i, 1, n + 1)
{
if (a[i] >= 0)
{
if (last && last + 1 == i)
ans ++ ;
continue;
}
cnt ++ ;
if (!last || last + 1 != i)
{
ans ++ ;
if (last)
v.pb(i - last - 1);
}
last = i;
}
if (cnt > k) puts("-1");
else
{
sort(all(v));
int j = 0;
k -= cnt;
while (j < sz(v) && k - v[j] >= 0)
{
ans -= 2, k -= v[j];
j ++ ;
}
if (ans > 1 && last < n && k - (n - last) >= 0)
ans --;
cout << ans << endl;
}
return 0;
}