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.
AC代码:
思路就是二分然后一个个值拿去试,就是这样。judge()函数就是一个个拿去试。
# include <stdio.h>
# include <iostream>
# include <string.h>
# include <algorithm>
# include <queue>
using namespace std;
typedef long long int ll;
struct node{
int no;
int keepd;
};
int m, n;
node s[100010];
int d[100010], a[100010];
vector<int> v[100010];
int judge(int);
int main(){
int i, j, k;
scanf("%d%d", &n, &m);
for(i=1; i<=n; i++){
scanf("%d", &d[i]);
}
for(i=1; i<=m; i++){
scanf("%d", &a[i]);
}
for(i=1; i<=n; i++){
if(d[i]){
v[d[i]].push_back(i);
}
}
int b=1, e=n;
int ans=2000000000;
while(b<=e){
int mid=(b+e)/2;
if(judge(mid)){
e=mid-1;
if(mid<ans){
ans=mid;
}
}
else{
b=mid+1;
}
}
if(ans!=2000000000)
printf("%d", ans);
else
printf("-1");
return 0;
}
bool cmp(node a, node b){
return a.no<b.no;
}
int judge(int t){
for(int i=1; i<=m; i++){
int size=v[i].size();
if(size==0)return 0;
int temp=lower_bound(v[i].begin(), v[i].begin()+size, t)-v[i].begin();
if(temp==size){
s[i].no=v[i][size-1];
}
else{
if(t==v[i][temp]){
s[i].no=t;
}
else{
s[i].no=v[i][temp-1];
}
}
s[i].keepd=a[i];
}
sort(s+1, s+1+m, cmp);
int cnt=0;
s[0].no=0;
for(int i=1; i<=m; i++){
cnt=cnt+s[i].no-s[i-1].no-1;
if(cnt<s[i].keepd){
return 0;
}
cnt=cnt-s[i].keepd;
}
return 1;
}