Lecture Sleep
题目
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.
Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka’s behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — ai during the i-th minute. Otherwise he writes nothing.
You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.
You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
Input
The first line of the input contains two integer numbers n and k (1 ≤ k ≤ n ≤ 10^5) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake.
The second line of the input contains n integer numbers a1, a2, … an (1 ≤ ai ≤ 10^4) — the number of theorems lecturer tells during the i-th minute.
The third line of the input contains n integer numbers t1, t2, … tn (0 ≤ ti ≤ 1) — type of Mishka’s behavior at the i-th minute of the lecture.
Output
Print only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
Example
input
6 3
1 3 5 2 5 4
1 1 0 1 0 0
output
16
思路
由题意要求从某个位置m开始,使t[m]~t[m+k-1]中非1元素全为1后,整体t[i]为1对应的所有a[i]累积值最大,并输出该最大值。因此必须从m=0开始枚举位置m,将每个位置所得的累积值相比较。
由于1 ≤ k ≤ n ≤ 10^5,k的范围可能非常大,如果直接双重循环,时间复杂度会很大,所以必须降低时间复杂度。
预先处理a[]数组中,对应t[]为0的元素,定义一个pre[]数组,pre[i]记录a[0]~a[i]中对应t[]=0的元素值之和。枚举位置时,pre[m+k-1]-pre[m-1]即可得到从m位置开始时对应t[]=0的元素值之和,再加上已经求好的整个a[]数组中原本就对应t[]为1的元素值之和,在每个位置m施加作用的累积结果。
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int a[maxn];
int t[maxn];
int pre[maxn];
int main()
{
int n,k;
int s=0;
int temp=0;
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++)
{
cin>>t[i];
if(t[i]) temp+=a[i];
}
memset(pre,0,sizeof(pre));
pre[0]=0;
for(int i=1;i<=n;i++)
{
if(t[i]) pre[i]=pre[i-1]+0;
if(!t[i]) pre[i]=pre[i-1]+a[i];
}
for(int i=1;i<=n;i++)
{
s=max(s,(pre[i+k-1]-pre[i-1]));
}
s+=temp;
cout<<s<<endl;
}
本文介绍了一个算法问题,即如何通过一次干预使朋友Mishka在数学讲座中记录最多定理。通过对讲座每分钟讲述定理数量及Mishka注意力状态的分析,采用预处理和滑动窗口的方法,有效地解决了此问题。
932

被折叠的 条评论
为什么被折叠?



