Codeforces 659F Polycarp and Hay【BFS】

有毒,自从上次选拔赛(哭哭)一个垃圾bfs写错之后,每次写bfs都要WA几发。。。好吧,其实也就这一次。。。
小白说的对,还是代码能力不足。。。
非常不足。。。


题目链接:

http://codeforces.com/contest/659/problem/F

题意:

n*m的格子,每个格子一个数,必须从格子中减去任意一个小于等于这个数的数。
给定数字k,要求:

  1. 剩下的格子数字和为k。
  2. 所有非零的格子的数字应该相同。
  3. 至少一个格子的数字没有改变。
  4. 含有非零数字的格子应该连通。

分析:

枚举每个能被k整除以及整除后小于n*m的格子的数字,bfs找格子,看联通块是否满足条件。
之前没有加任何优化,TLE on 95。
后来另设一个数组,记录已经枚举过的数,遇到与之前相同的数,说明这个数不满足,可以直接跳过,不用考虑。

代码:

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 1e3 + 5;
#define x first
#define y second
#define sa(a) scanf("%d", &a)
#define sal(a) scanf("%I64d", &a)
typedef pair<int, int> pii;
int vis[maxn][maxn];
int a[maxn][maxn], c[maxn][maxn];
int m, n;
long long k;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, -1, 1};
bool bfs(pii pa, int res)
{
    queue<pii>q;
    memset(vis, false, sizeof(vis));
    vis[pa.x][pa.y] = true;
    q.push(pa);
    int cnt = 1;
    while(!q.empty()){
        pii t = q.front();q.pop();
        int x = t.x, y = t.y;
        if(cnt == res) return true;
        for(int i = 0; i < 4; i++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny]){
                if(a[nx][ny] < a[pa.x][pa.y]) continue;
                if(a[nx][ny] == a[pa.x][pa.y]) c[nx][ny] = 1;
                vis[nx][ny] =  true;
                cnt ++;
                q.push(pii(nx, ny));
                if(cnt == res) return true;
            }
        }
    }
    return false;
}
int solve()
{
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            if(c[i][j]) continue;
            long long cnt = k/ a[i][j];
            if(k % a[i][j] == 0 &&  cnt <= m * n){
                if(bfs(pii(i, j), cnt)) return a[i][j];
                }
            }
        }
    return -1;
}
int main (void)
{
    sa(n),sa(m),sal(k);
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            sa(a[i][j]);
        }
    }
    int ans = solve();
    if(ans == -1) return printf("NO
"), 0;
    printf("YES
");
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            if(vis[i][j]) printf("%d%c", ans, j == m - 1? '
':' ');
            else printf("0%c", j == m - 1?'
':' ');
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758681.html