codevs2800送外卖题解

来源:互联网 发布:iis php mysql 配置 编辑:程序博客网 时间:2024/06/12 01:41
  • 题目描述 Description
    有一个送外卖的,他手上有n份订单,他要把n份东西,分别送达n个不同的客户的手上。n个不同的客户分别在1~n个编号的城市中。送外卖的从0号城市出发,然后n个城市都要走一次(一个城市可以走多次),最后还要回到0点(他的单位),请问最短时间是多少。现在已知任意两个城市的直接通路的时间。

  • 输入描述 Input Description
    第一行一个正整数n (1<=n<=15)
    接下来是一个(n+1)*(n+1)的矩阵,矩阵中的数均为不超过10000的正整数。矩阵的i行j列表示第i-1号城市和j-1号城市之间直接通路的时间。当然城市a到城市b的直接通路时间和城市b到城市a的直接通路时间不一定相同,也就是说道路都是单向的。

  • 输出描述 Output Description
    一个正整数表示最少花费的时间

  • 样例输入 Sample Input
    3
    0 1 10 10
    1 0 1 2
    10 1 0 10
    10 2 10 0

  • 样例输出 Sample Output
    8

  • 数据范围及提示 Data Size & Hint
    1<=n<=15

  • 题解
    一看能走多次就先想用floyd求最短路,n才15~
    下面是状压DP。(第一次写,感觉考虑全所有的状态并设计一个正确的转移方程不是一件容易的事)
    我们令f[i][lst]表示第i个状态时走到了第lst个城市所花费的最小代价;其中把i转化为二进制数m,用数组p[]记录m中1的位置,那么i表示的状态就是p[]-1的所有城市均已走过而其他城市没有走过的状态,所以lst+1的位置在m中为1时才能转移;边界条件f[0][0]=0,其余是inf;最终状态是f[(1 << (n+1)-1][0]。

  • Code

#include <cstdio>#include <algorithm>#include <cstring>using namespace std;const int maxn = 16, oo = 1000000000;int map[maxn][maxn], f[1 << maxn][maxn], n;inline void init(){    scanf("%d", &n);    for(int i = 0; i <= n; ++i)    {        for(int j = 0; j <= n; ++j)        {            scanf("%d", &map[i][j]);        }    }    //以下是floyd    for(int k = 0; k <= n; ++k)    {        for(int i = 0; i <= n; ++i)        {            for(int j = 0; j <= n; ++j)            {                map[i][j] = min(map[i][j], map[i][k] + map[k][j]);            }        }    }}inline void work(){    memset(f, 127/3, sizeof(f));    f[0][0] = 0;    for(int i = 0; i < (1 << (n + 1)); ++i)    {        for(int lst = 0; lst <= n; ++lst)        {            if((i | (1 << lst)) == i)//最后到的城市在已到过的城市里,状态合法            {                for(int pre = 0; pre <= n; ++pre)                {                    f[i][lst] = min(f[i][lst], f[i - (1 << lst)][pre] + map[pre][lst]);                    //以前没到过lst,现通过pre到了lst                    f[i][lst] = min(f[i][lst], f[i][pre] + map[pre][lst]);                    //以前到过lst,现通过pre又到了lst                }            }        }    }    printf("%d", f[(1 << (n + 1)) - 1][0]);}int main(){    init();    work();    return 0;}
0 0