USACO Laserphones

USACO Laserphones

洛谷传送门

JDOJ传送门

Description

The cows have a new laser-based system so they can have casual
conversations while out in the pasture which is modeled as a W x H
grid of points (1 <= W <= 100; 1 <= H <= 100).

The system requires a sort of line-of-sight connectivity in order
to sustain communication. The pasture, of course, has rocks and
trees that disrupt the communication but the cows have purchased
diagonal mirrors ('/' and '' below) that deflect the laser beam
through a 90 degree turn. Below is a map that illustrates the
problem.

H is 8 and W is 7 for this map. The two communicating cows are
notated as 'C's; rocks and other blocking elements are notated as
'*'s:

7 . . . . . . .         7 . . . . . . .
6 . . . . . . C         6 . . . . . /-C
5 . . . . . . *         5 . . . . . | *
4 * * * * * . *         4 * * * * * | *
3 . . . . * . .         3 . . . . * | .
2 . . . . * . .         2 . . . . * | .
1 . C . . * . .         1 . C . . * | .
0 . . . . . . .         0 . -------/ .
  0 1 2 3 4 5 6           0 1 2 3 4 5 6

Determine the minimum number of mirrors M that must be installed
to maintain laser communication between the two cows, a feat which
is always possible in the given test data.

Input

* Line 1: Two space separated integers: W and H

* Lines 2..H+1: The entire pasture.

Output

* Line 1: A single integer: M

Sample Input

7 8 ....... ......C ......* ****. ...... ...... .C..*.. .......

Sample Output

3


最优解声明:

题解:

思路:

最优化——DP,走地图——搜索。DP+搜索:记忆化搜索。

然后就可以开始码了。

本题的坑点:m,n是反着读的。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,ans=10000;
char mp[110][110];
bool v[110][110];
int dp[110][110][5];
int dx[]={0,1,-1,0,0};
int dy[]={0,0,0,-1,1};
void dfs(int x,int y,int now,int d)
{
    if(d&&dp[x][y][d]<=now)
        return;
    if(d)
        dp[x][y][d]=now;
    if(mp[x][y]=='C')
    {
        ans=min(ans,now);
        return;
    }
    if(d)
    {
        int xx=x+dx[d];
        int yy=y+dy[d];
        if(xx>=1&&yy>=1&&xx<=n&&yy<=m&&!v[xx][yy]&&mp[xx][yy]!='*')
        {
            v[xx][yy]=1;
            dfs(xx,yy,now,d);
            v[xx][yy]=0;
        }
    }
    for(int i=1;i<=4;i++)
    {
        int xx=x+dx[i];
        int yy=y+dy[i];
        if(xx<1||yy<1||xx>n||yy>m||v[xx][yy]||mp[xx][yy]=='*')
            continue;
        v[xx][yy]=1;
        if(!d)
            dfs(xx,yy,now,i);
        else
            dfs(xx,yy,now+1,i);
        v[xx][yy]=0;
    }
}
int main()
{
    scanf("%d%d",&m,&n);
    for(int i=1;i<=n;i++)
        scanf("%s",mp[i]+1);
    memset(dp,127,sizeof(dp));
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        {
            if(mp[i][j]!='C')
                continue;
            v[i][j]=1;
            mp[i][j]='*';
            dfs(i,j,0,0);
            printf("%d",ans);
            return 0;
        }
}
原文地址:https://www.cnblogs.com/fusiwei/p/13860510.html