CF793D
每次的走一步,可以选择的区域就缩小,搜索很显然会T,此时加一个记忆化即可。搜索时以当前点,链长和可选区间为搜索状态。
AC代码
#include <bits/stdc++.h>
#define yes puts("yes");
#define inf 0x3f3f3f3f
#define linf 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define debug(x) cout<<"> "<< x<<endl;
#define endl '\n'
#define lowbit(x) x&-x
//#define int long long
using namespace std;
typedef pair<int,int> PII;
const int MAXN =10 + 2e5, mod = 1e9 + 7;
int dp[82][82][82][82];
void solve()
{
int N,M,K;
cin >> N >> K >> M;
vector<vector<int>> G(N + 1,vector<int>(N + 1, inf));
for(int i = 1;i <= M;i ++) {
int u,v,w;
cin >> u >> v >> w;
G[u][v] = min(G[u][v],w);
}
memset(dp,-1,sizeof dp);
function<int(int,int,int,int)> dfs = [&](int l,int r,int k,int u) {
if(k >= K) return 0;
if(dp[l][r][k][u] != -1) return dp[l][r][k][u];
dp[l][r][k][u] = inf;
for(int v = 1;v <= N;v ++) {
if(G[u][v] != -1 && l < v && v < r) {
if(u < v) {// u]....v
dp[l][r][k][u] = min(dp[l][r][k][u],dfs(u,r,k + 1,v) + G[u][v]);
}else {
dp[l][r][k][u] = min(dp[l][r][k][u],dfs(l,u,k + 1,v) + G[u][v]);
}
}
}
return dp[l][r][k][u];
};
int ans = inf;
for(int i = 1;i <= N;i ++) {
ans = min(ans,dfs(0,N + 1,1,i));
}
cout << (ans == inf ? -1 : ans) << endl;
}
signed main()
{
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
solve();
return 0;
}