mirror of
https://gitcode.com/Zengtudor/alg2025.git
synced 2025-09-04 01:01:43 +00:00
feat: 实现动态规划解决奶牛逃跑问题
添加P4267.cpp文件,实现动态规划算法计算奶牛逃跑序列的最小修改次数。算法使用二维DP数组存储状态,并通过预处理计算区间修改成本。解决给定n头奶牛在不同逃跑次数下的最小不一致数量问题。
This commit is contained in:
parent
91aa4d02bc
commit
52b2321a96
@ -1,3 +0,0 @@
|
||||
int main(){
|
||||
|
||||
}
|
74
src/8/29/P4267.cpp
Normal file
74
src/8/29/P4267.cpp
Normal file
@ -0,0 +1,74 @@
|
||||
/*
|
||||
|
||||
dp[i][j]=前i个牛发生j次逃跑时序列不一致的数量最小数目
|
||||
|
||||
dp[i][j]=min(dp[k][j-1]+cnt[k+1][i])
|
||||
|
||||
dp[i][j]=inf
|
||||
|
||||
dp[i][1]=cnt[1][i]
|
||||
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <vector>
|
||||
using ll = int64_t;
|
||||
|
||||
const ll inf=1e9;
|
||||
|
||||
#define p2v(arr)do{\
|
||||
std::cout<<#arr<<":\n";\
|
||||
for(auto&i:(arr)){\
|
||||
for(auto&j:i){\
|
||||
std::cout<<j<<", ";\
|
||||
}\
|
||||
std::cout<<"\n";\
|
||||
}\
|
||||
}while(0)
|
||||
|
||||
int main(){
|
||||
std::iostream::sync_with_stdio(false);
|
||||
std::cin.tie(nullptr);
|
||||
|
||||
ll n;
|
||||
std::cin>>n;
|
||||
std::vector<std::vector<ll>> dp(n+1,std::vector<ll>(n+1, inf)),
|
||||
cnt(n+1,std::vector<ll>(n+1));
|
||||
std::vector<ll> arr(n+1);
|
||||
for(ll i=1;i<=n;i++){
|
||||
std::cin>>arr[i];
|
||||
}
|
||||
/*
|
||||
cost[i][j] 表示在区间 [i, j] 内,假设第 i 天发生逃跑,
|
||||
并且在 (i, j] 区间内没有其他逃跑发生时,需要修改的记录数。
|
||||
*/
|
||||
for(ll i=1;i<=n;i++){
|
||||
ll mis=0;
|
||||
for(ll j=i;j<=n;j++){
|
||||
if(j-i!=arr[j]){
|
||||
mis++;
|
||||
}
|
||||
cnt[i][j]=mis;
|
||||
}
|
||||
}
|
||||
// p2v(cnt);
|
||||
for(ll i=1;i<=n;i++){
|
||||
dp[i][1]=cnt[1][i];
|
||||
}
|
||||
for(ll i=1;i<=n;i++){
|
||||
for(ll j=2;j<=n;j++){
|
||||
for(ll k=j-1;k<i;k++){
|
||||
dp[i][j]=std::min(
|
||||
dp[i][j],
|
||||
dp[k][j-1]+cnt[k+1][i]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for(ll j=1;j<=n;j++){
|
||||
std::cout<<dp[n][j]<<"\n";
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user