这个题比较简单,不需要多说,最直观的解法就是二分,思路很清晰,写起来也方便。但仅满足于这个是不够的,看了别人的代码,好像有O(n) 的解法,后来想了一下,的确可以,所以说,一道题可以有不同的解法。而且我个人认为,每一种解法,都是一种思想。
二分代码:
#include<iostream>
#include<cstdio>
#include<vector>
#include<stack>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<set>
#include<map>
using namespace std;
const int N=1002;
long long c[N];
bool ok(long long k,vector<int> &m,vector<int> &e,vector<long long> &ec)
{
for(unsigned int i=0;i<ec.size();++i)
c[i]=ec[i];
for(unsigned int i=0;i<m.size();++i)
{
long long tmp=k;
for(unsigned int j=0;tmp>0&&j<e.size();++j)
{
if(e[j]<=m[i])
{
if(c[j]<=tmp)
{
tmp-=c[j];
c[j]=0;
}else
{
c[j]-=tmp;
tmp=0;
}
}
}
}
for(unsigned int i=0;i<ec.size();++i)
if(c[i]>0)
return false;
return true;
}
class SpaceWarDiv1
{
public:
long long minimalFatigue(vector <int> m, vector <int> e, vector<long long> ec)
{
sort(m.begin(),m.end());
int M1=0;
for(unsigned int i=0;i<m.size();++i)
M1=max(M1,m[i]);
int M2=0;
for(unsigned int i=0;i<e.size();++i)
M2=max(M2,e[i]);
if(M1<M2)
return -1;
long long l=0;
long long r=0;
for(unsigned int i=0;i<ec.size();++i)
r+=ec[i];
while(l<=r)
{//cout<<l<<" "<<r<<endl;
long long mid=(l+r)/2;
if(ok(mid,m,e,ec))
r=mid-1;
else
l=mid+1;
}
return l;
}
};
O(n)代码:
#include<iostream>
#include<cstdio>
#include<vector>
#include<stack>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<set>
#include<map>
using namespace std;
const int N=52;
struct node
{
int e;
long long ec;
}a[N];
bool cmp(node x,node y)
{
return x.e<y.e;
}
class SpaceWarDiv1
{
public:
long long minimalFatigue(vector <int> m, vector <int> e, vector<long long> ec)
{
int len1=m.size();
int len2=e.size();
sort(m.begin(),m.end());
long long sum=0;
for(int i=0;i<len2;++i)
{
a[i].e=e[i];
a[i].ec=ec[i];
sum+=a[i].ec;
}
sort(a,a+len2,cmp);
if(m[len1-1]<a[len2-1].ec)
return -1;
int l=0;
long long M=0;
for(int i=0;i<len1;++i)
{
long long tmp=(sum/(len1-i));
if(sum%(len1-i)>0)
++tmp;
M=max(M,tmp);
while(l<len2&&m[i]>=a[l].e&&tmp>0)
{
if(a[l].ec>=tmp)
{
sum-=tmp;
a[l].ec-=tmp;
tmp=0;
}else
{
tmp-=a[l].ec;
sum-=a[l].ec;
a[l].ec=0;
}
if(a[l].ec==0)
++l;
}
}
return M;
}
};