mirror of
https://gitcode.com/Zengtudor/alg2025.git
synced 2025-09-12 02:50:01 +00:00
feat: 添加P5017问题的动态规划解法
实现了一个基于深度优先搜索和记忆化的动态规划解决方案,用于解决P5017问题。该算法通过排序输入数据并利用记忆化技术优化计算,有效减少了重复计算,提高了效率。
This commit is contained in:
parent
777488a777
commit
8aba3d8e3d
46
src/9/11/P5017.cpp
Normal file
46
src/9/11/P5017.cpp
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
#include <algorithm>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <iostream>
|
||||||
|
#include <istream>
|
||||||
|
#include <vector>
|
||||||
|
using ll = int64_t;
|
||||||
|
|
||||||
|
ll n,m, maxt=0;
|
||||||
|
std::vector<ll> t;
|
||||||
|
std::vector<std::vector<ll>> mem;
|
||||||
|
|
||||||
|
static inline ll dfs(const ll cur,const ll st){
|
||||||
|
if(cur>=n+1)return 0;
|
||||||
|
if(st<t[cur]){
|
||||||
|
return dfs(cur,t[cur]);
|
||||||
|
}
|
||||||
|
if(mem[cur][st-t[cur]]){
|
||||||
|
return mem[cur][st-t[cur]];
|
||||||
|
}
|
||||||
|
ll j=cur;
|
||||||
|
ll sum=0;
|
||||||
|
while(j<=n && t[j]<=st){
|
||||||
|
sum+=t[j++];
|
||||||
|
}
|
||||||
|
ll best=st*(j-cur)-sum+dfs(j,st+m);
|
||||||
|
for(;j<=n;j++){
|
||||||
|
sum+=t[j];
|
||||||
|
best=std::min(best,t[j]*(j-cur+1)-sum+dfs(j+1,t[j]+m));
|
||||||
|
}
|
||||||
|
mem[cur][st-t[cur]]=best;
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
std::iostream::sync_with_stdio(false);
|
||||||
|
std::cin.tie(nullptr);
|
||||||
|
|
||||||
|
std::cin>>n>>m;
|
||||||
|
t.resize(n+1);
|
||||||
|
mem.resize(n+1,std::vector<ll>(maxt+m+1));
|
||||||
|
for(ll i=1;i<=n;i++){
|
||||||
|
std::cin>>t[i];
|
||||||
|
}
|
||||||
|
std::sort(t.begin()+1,t.begin()+1+n);
|
||||||
|
std::cout<<dfs(1,0)<<"\n";
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user