[Title link] http://codeforces.com/contest/793/problem/D
[title]
Give you n points.
These n points.
From left to right, 1. n is arranged in order.
Then give you m directed edges.
Then let you choose k points from it.
A path formed by these k points;
And in the path, a visited point will not pass through twice or more;
For example, from 1 - > 3 (1 and 3 have been visited)
Then it's accessed from 3 - > 4 (1, 3, 4)
From 4 - > 2 (then it passes through Node 3, which has been visited before, so it is illegal)
This is not legal;
[Abstract]
After each walk, there is an interval to follow.
For example, the current interval is
[a,b]
Then you go from b to a,b to a location u (obviously left).
It corresponds to two states.
[a,u] and [u,b]
Here [a,u] can only go left, while [u,b] can only go right.
> interval DP;
Let f [i] [j] [k] [0.1]
Represents walking i edge, and then the current interval is j,k;
Then?
0 means that the current starting point is i, then go right.
1 indicates that the current starting point is j, then go left.
f[i][j][k][0]=min(f[i−1][j][u][1],f[i−1][u][k][0])+cost[j][u];
f[i][j][k][1]=min(f[i−1][j][u][1],f[i−1][u][k][0])+cost[j][u];
imax=k-1
Then for k=1, output 0 directly.
Otherwise, it would be better to update the answers while doing DP.
[Number Of WA]
0
[Complete code]
#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)
typedef pair<int,int> pii;
typedef pair<LL,LL> pll;
const int dx[9] = {0,1,0,-1,0,-1,-1,1,1};
const int dy[9] = {0,0,-1,0,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 100;
const int INF = 0x3f3f3f3f;
int n,k,m,f[N][N][N][2],ans=INF;
vector <pii> G[N];
int main()
{
//freopen("F:\\rush.txt","r",stdin);
ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
cin >> n >> k;
cin >> m;
if (k==1) return cout << 0 << endl,0;
rep1(i,1,m)
{
int x,y,z;
cin >> x >> y >> z;
G[x].pb(mp(y,z));
}
rep1(i,1,k-1)
{
rep2(l,n,0)
rep1(r,l+1,n+1)
{
f[i][l][r][0] = INF;
for (pii temp:G[l])
{
int y = temp.fi,cost = temp.se;
if (l<y && y < r)
{
f[i][l][r][0] = min(f[i][l][r][0],f[i-1][y][r][0]+cost);
f[i][l][r][0] = min(f[i][l][r][0],f[i-1][l][y][1]+cost);
}
}
f[i][l][r][1] = INF;
for (pii temp:G[r])
{
int y = temp.fi,cost = temp.se;
if (l<y && y < r)
{
f[i][l][r][1] = min(f[i][l][r][1],f[i-1][l][y][1]+cost);
f[i][l][r][1] = min(f[i][l][r][1],f[i-1][y][r][0]+cost);
}
}
if (i==k-1)
{
ans = min(ans,f[i][l][r][1]);
ans = min(ans,f[i][l][r][0]);
}
}
}
if (ans>=INF)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}