UVALive4256-Salesman(dp)

题目链接

http://acm.hust.edu.cn/vjudge/problem/21665

思路

状态:d[i][x]对第i个数,并且该数为x,修改的最少次数
转移方程:d[i][x] = min{d[i - 1][y] + (x == a[i] ? 0 : 1) | x == y || G[x][y]};

代码

#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;

#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
#define CLR(a, x) memset(a, x, sizeof(a))
#define FILL(a, n, x) for (int i = 0; i < n; i++) a[i] = x

const int maxn = 1005;
const int INF = 0x3e3e3e3e;
int G[maxn][maxn], d[maxn][maxn], a[maxn];
int n1, n, m;

int dp(int i, int x) {
    if (i == 1) return d[i][x] = (x == a[1] ? 0 : 1);
    if (d[i][x] >= 0) return d[i][x];
    d[i][x] = INF;
    for (int y = 1; y <= n1; y++) {
        if (x == y || G[x][y]) {
            if (x == a[i]) d[i][x] = min(d[i][x], dp(i - 1, y));
            else d[i][x] = min(d[i][x], dp(i - 1, y) + 1);
        }
    }
    return d[i][x];
}

int main() {
    int T;
    scan(T);
    while (T--) {
        CLR(G, 0);
        scan2(n1, m);
        for (int i = 0; i < m; i++) {
            int x, y;
            scan2(x, y);
            G[x][y] = G[y][x] = 1;
        }
        scan(n);
        for (int i = 1; i <= n; i++) scan(a[i]);
        CLR(d, -1);
        for (int xi = 1; xi <= n1; xi++) dp(n, xi);
        int res = INT_MAX;
        for (int xi = 1; xi <= n1; xi++) {
            if (d[n][xi] >= 0) res = min(res, d[n][xi]);
        }
        printf("%d\n", res);
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值