UVALive4256-Salesman(dp)

来源:互联网 发布:2x2的矩阵怎么乘法 编辑:程序博客网 时间:2024/05/16 14:56

题目链接

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] = xconst 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 0
原创粉丝点击