• Collecting Gold LightOJ


    Finally you found the city of Gold. As you are fond of gold, you start collecting them. But there are so much gold that you are getting tired collecting them.

    So, you want to find the minimum effort to collect all the gold.

    You can describe the city as a 2D grid, where your initial position is marked by an 'x'. An empty place will be denoted by a '.'. And the cells which contain gold will be denoted by 'g'. In each move you can go to all 8 adjacent places inside the city.

    Input

    Input starts with an integer T (≤ 100), denoting the number of test cases.

    Each case will start with a blank line and two integers, m and n (0 < m, n < 20) denoting the row and columns of the city respectively. Each of the next m lines will contain n characters describing the city. There will be exactly one 'x' in the city and at most 15 gold positions.

    Output

    For each case of input you have to print the case number and the minimum steps you have to take to collect all the gold and go back to 'x'.

    Sample Input

    2

    5 5

    x....

    g....

    g....

    .....

    g....

    5 5

    x....

    g....

    g....

    .....

    .....

    Sample Output

    Case 1: 8

    Case 2: 4

    题解:因为金矿最多有15个,所以强势转化成TSP问题。想到这点就行了。。。

     1 #include<cmath> 
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<iostream>
     5 #include<algorithm>
     6 #define INF 0x3f3f3f3f
     7 using namespace std;
     8 
     9 int n,p,q;
    10 int dp[1<<17][17],x[17],y[17];
    11 char s[25][25];
    12 
    13 int get(int i,int j){
    14     return max(abs(x[i]-x[j]),abs(y[i]-y[j]));
    15 }
    16 
    17 int DFS(int S,int v){
    18     if(dp[S][v]>=0) return dp[S][v];
    19     if(S==(1<<n)-1 && v==0) return dp[S][v]=0;
    20     int res=INF;
    21     for(int u=0;u<n;u++){
    22         if(S>>u & 1) continue; 
    23         res=min(res,DFS(S | 1<<u,u)+get(v,u));
    24     }
    25     return dp[S][v]=res;
    26 }
    27 
    28 int main()
    29 {   int kase;
    30     cin>>kase;
    31     for(int t=1;t<=kase;t++){
    32         cin>>p>>q;
    33         n=1;
    34         for(int i=1;i<=p;i++){
    35             scanf("%s",s[i]+1);
    36             for(int j=1;j<=q;j++){
    37                 if(s[i][j]=='x') x[0]=i,y[0]=j;
    38                 if(s[i][j]=='g') x[n]=i,y[n++]=j;
    39             }
    40         }
    41         memset(dp,-1,sizeof(dp));
    42         printf("Case %d: %d
    ",t,DFS(0,0));
    43     } 
    44     return 0;
    45 }
  • 相关阅读:
    Apache+Tomcat+Mysql+php整合jsp,php
    mysql数据类型详析(转)
    有向图(拓扑排序算法)
    FLEX获取GET数据
    Flex对象与组件的数据 双向绑定
    D3D学习摘记(I)中
    [转贴]深入理解Javascript闭包
    一个相当愚蠢的概念错误
    近日小记
    D3D学习摘记(I)上
  • 原文地址:https://www.cnblogs.com/zgglj-com/p/7340304.html
Copyright © 2020-2023  润新知