您的位置:首页 > 其它

Codeforces Round #377 D. Exams (二分)

2016-11-02 21:14 330 查看
Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects.
Subjects are numbered from 1 to m.

About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is
not allowed to pass more than one exam on any day.

On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest.

About each subject Vasiliy know a number ai —
the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary
to prepare continuously during ai days
for the exam number i. He can mix the order of preparation for exams in any way.

Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 105) —
the number of days in the exam period and the number of subjects.

The second line contains n integers d1, d2, ..., dn (0 ≤ di ≤ m),
where di is
the number of subject, the exam of which can be passed on the day number i. If di equals
0, it is not allowed to pass any exams on the day number i.

The third line contains m positive integers a1, a2, ..., am (1 ≤ ai ≤ 105),
where ai is
the number of days that are needed to prepare before passing the exam on the subject i.

Output

Print one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1.

Examples

input
7 2
0 1 0 2 1 0 2
2 1


output
5


input
10 3
0 0 1 2 3 0 2 0 1 2
1 1 4


output
9


input
5 1
1 1 1 1 1
5


output
-1


题目大意是有一个n天的考试时期,你有m科需要考,然后规定这n天某天只能考某一科,0表示这天不能考试,然后告诉你考每一科前需要复习多少天,问你最少要多少天你能考完所有的科目。

这个题目正面做很难做,所以用二分把他变成一个判定型的问题,从后往前判断每一科能不能考,最后如果所有科目都考完了,判定就成立。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

int n,m,l,r;
int d[100010],a[100010];

bool judge(int x)
{
int i;
int b[100010];
memset(b,0,sizeof(b));
int cnt = x - 1;
for(i=x;i>=1;i--)
{
cnt = min(cnt,i-1);
if (d[i] && !b[d[i]] && a[d[i]] <= cnt)
{
b[d[i]] = 1;
cnt -= a[d[i]] + 1;
}
}
for(i=1;i<=m;i++)
if(!b[i])
return false;
return true;

}
int binarysearch()
{
int ans = -1;
while(l <= r)
{
int mid = (l + r)/2;
if(judge(mid))
{
ans = mid;
r = mid - 1;
}
else
l = mid + 1;
}

return ans;
}
int main(void)
{
int i;
while(scanf("%d%d",&n,&m)==2)
{
for(i=1;i<=n;i++)
scanf("%d",&d[i]);
l = m;
r = n;
for(i=1;i<=m;i++)
scanf("%d",&a[i]);
int ans = binarysearch();
printf("%d\n",ans);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: