CodeForces 173B Chamber of Secrets (二分图+BFS)

题意:给定上一个n*m的矩阵,你从(1,1)这个位置发出水平向的光,碰到#可以选择四个方向同时发光,或者直接穿过去,

问你用最少的#使得光能够到达 (n,m)并且方向水平向右。

析:很明显的一个最短路,但是矩阵有点大啊。1000*1000,普通的肯定要超时啊,所以先通过#把该该图的行和列建立成二分图,

然后再跑最短路,这样就简单多了。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e17;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 2000 + 10;
const int mod = 1000000007;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
  return r >= 0 && r < n && c >= 0 && c < m;
}

char s[maxn];
vector<int> G[maxn];
bool vis[maxn];
int dp[maxn];

int bfs(){
  memset(dp, INF, sizeof dp);
  dp[1] = 0;
  vis[1] = true;
  queue<int> q;
  q.push(1);

  while(!q.empty()){
    int u = q.front();  q.pop();
    if(u == n)  return dp[u];
    for(int i = 0; i < G[u].size(); ++i){
      int v = G[u][i];
      if(dp[v] > dp[u] + 1){
        dp[v] = dp[u] + 1;
        if(vis[v])  continue;
        vis[v] = true;
        q.push(v);
      }
    }
  }
  return -1;
}

int main(){
  scanf("%d %d", &n, &m);
  for(int i = 1; i <= n; ++i){
    scanf("%s", s+1);
    for(int j = 1; j <= m; ++j)
      if(s[j] == '#'){
        G[i].push_back(j+n);
        G[j+n].push_back(i);
      }
  }
  printf("%d
", bfs());
  return 0;
}

  

原文地址:https://www.cnblogs.com/dwtfukgv/p/7160901.html