Winter Is Coming(贪心)

D. Winter Is Coming
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day.

Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these k days form a continuous segment of days.

Before the first winter day Vasya still uses summer tires. It is possible to drive safely on summer tires any number of days when the average air temperature is non-negative. It is impossible to drive on summer tires at days when the average air temperature is negative.

Vasya can change summer tires to winter tires and vice versa at the beginning of any day.

Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.

Input

The first line contains two positive integers n and k (1 ≤ n ≤ 2·1050 ≤ k ≤ n) — the number of winter days and the number of days winter tires can be used. It is allowed to drive on winter tires at any temperature, but no more than k days in total.

The second line contains a sequence of n integers t1, t2, ..., tn ( - 20 ≤ ti ≤ 20) — the average air temperature in the i-th winter day.

Output

Print the minimum number of times Vasya has to change summer tires to winter tires and vice versa to drive safely during all winter. If it is impossible, print -1.

Examples
input
4 3
-5 20 -3 0
output
2
input
4 2
-5 20 -3 0
output
4
input
10 6
2 -5 1 3 0 0 -4 -3 1 0
output
3
思路:假设冬胎只在温度为负(天数为cnt)时使用,则轮胎更换次数为cnt*2;这是最多更换次数;这时,用剩下的可用天数去填两个温度为负时天气之间的间隔,每填一个更换次数就减少二,需要特判最后能否沿用,能则减一;优先填最小的间隔;

代码:

#include 
#include 
#include 
#include 
#include 
#define MAX 200000+5

using namespace std;

int day[MAX];
int num[MAX];
int sec[MAX];
int main(){

    int n, k;
    while(cin >> n >> k){
    int cnt=0;
    for(int i=0; i> day[i];
        if(day[i]<0){
            cnt++;
            num[cnt]=i;
        }
    }
    if(cnt>k){
        cout << -1 << endl;
        continue;
    }
    if(cnt==0){
        cout << 0 << endl;
        continue;
    }
    int ans=cnt*2;
    //cout << cnt << endl;
    for(int i=2; i<=cnt; i++){
        sec[i-1]=num[i]-num[i-1]-1;
        //cout << num[i] << endl;
    }
    sort(sec+1, sec+cnt);
    k-=cnt;
    for(int i=1; i=0){
            k-=sec[i];
            ans-=2;
        }
    }
    if(k>=n-num[cnt]-1) ans--;
    //cout << endl;
    cout << ans << endl;
    }

    return 0;
}




你可能感兴趣的:(Winter Is Coming(贪心))