星空 (狀壓dp)

星空

10.24

思路:
這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述這裏寫圖片描述

鏈接

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#define INF 0x3f3f3f3f
#define N 40010
#define P 18
using namespace std;

int n, k, m, cnt = 0;
bool a[N];
int dis[P][N], b[70];
pair <int, int> p[P];

queue <int> q;

void bfs(pair<int, int> st) {
    for(register int i=0; i<N; i++) dis[st.first][i] = INF;
    q.push(st.second);
    dis[st.first][st.second] = 0;
    while ( !q.empty() ) {
        int x = q.front(); q.pop();
        for(register int i=1; i<=m; i++) {
            if (x - b[i] >= 0 && dis[st.first][x - b[i]] > dis[st.first][x] + 1) {
                dis[st.first][x - b[i]] = dis[st.first][x] + 1;
                q.push(x - b[i]);
            }
            if (x + b[i] <= n && dis[st.first][x + b[i]] > dis[st.first][x] + 1) {
                dis[st.first][x + b[i]] = dis[st.first][x] + 1;
                q.push(x + b[i]);
            }//
        }
    }
}

int dp[1 << P];

int solve(int state) {
    if (dp[state] != -1) return dp[state];
    if (state == 0) return 0;
    int &ret = dp[state]; ret = INF;
    int x = 0; while (!(state & (1 << x))) x++;
    for(int i=x+1; i<2*k; i++)
        if (state & (1 << i)) ret = min(ret, solve(state ^ (1 << x) ^ (1 << i)) + dis[x][p[i].second]);
    return ret;
}

int main() {
    freopen("starlit.in", "r", stdin);
    freopen("starlit.out", "w", stdout);
    scanf("%d %d %d", &n, &k, &m);
    for(int i=1, x; i<=k; i++) scanf("%d", &x), a[x] = true;
    for(register int i=1; i<=m; i++) scanf("%d", &b[i]);
    for(int i=0; i<=n; i++) if (a[i] != a[i+1]) p[cnt] = pair<int, int> (cnt, i), cnt++;
    for(int i=0; i<cnt; i++) bfs(p[i]);
    memset(dp, -1, sizeof dp);
    int ans = solve((1 << cnt) - 1);
    if(ans != INF) printf("%d\n", ans);
    return 0;
}

發佈了308 篇原創文章 · 獲贊 25 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章