【codeforces 793D】Presents in Bankopolis

【题目链接】:http://codeforces.com/contest/793/problem/D

【题意】

给你n个点,
这n个点
从左到右1..n依序排;
然后给你m条有向边;
然后让你从中选出k个点.
这k个点形成的一条路径;
且在路径中,一个被访问过的点不会经过两次或以上;
比如从1->3(1和3被访问过)
然后再从3->4(1,3,4都被访问过)
再从4->2(这时会又经过3号节点,而3号节点之前被访问过,所以不合法)
这就不是合法的;

【题解】

每次走完之后都有一个接下来能走的区间了;
比如当前走的区间为
[a,b]
然后你从b走到了a,b中的某个位置u(显然是往左走了);
则对应了两个状态
[a,u]和[u,b]
这里[a,u]只能是往左走的,而[u,b]只能是往右走的;
->区间DP;
设f[i][j][k][0..1]
表示走了i条边,然后当前能够走的区间为j,k;
然后
0表示当前起点在i,然后向右走;
1表示当前起点在j,然后向左走;
f[i][j][k][0]=min(f[i1][j][u][1],f[i1][u][k][0])+cost[j][u];
f[i][j][k][1]=min(f[i1][j][u][1],f[i1][u][k][0])+cost[j][u];
imax=k-1
然后对于k=1的情况直接输出0;
否则在做DP的过程中一边更新答案就好了

【Number Of WA

0

【完整代码】

#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;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626384.html