Codeforces 659F Polycarp and Hay【BFS】
来源:互联网 发布:守望先锋数据app 编辑:程序博客网 时间:2024/05/01 06:16
有毒,自从上次选拔赛(哭哭)一个垃圾bfs写错之后,每次写bfs都要WA几发。。。好吧,其实也就这一次。。。
小白说的对,还是代码能力不足。。。
非常不足。。。
题目链接:
http://codeforces.com/contest/659/problem/F
题意:
n*m的格子,每个格子一个数,必须从格子中减去任意一个小于等于这个数的数。
给定数字k,要求:
- 剩下的格子数字和为k。
- 所有非零的格子的数字应该相同。
- 至少一个格子的数字没有改变。
- 含有非零数字的格子应该连通。
分析:
枚举每个能被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\n"), 0; printf("YES\n"); 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? '\n':' '); else printf("0%c", j == m - 1?'\n':' '); } } return 0;}
0 0
- Codeforces 659F Polycarp and Hay【BFS】
- 【17.69%】【codeforces 659F】Polycarp and Hay
- Codeforces 659F Polycarp and Hay【思维+并查集+Bfs】
- Codeforces 659F Polycarp and Hay (排序+并查集)
- Codeforces Round #346 (Div. 2) F. Polycarp and Hay (并查集+bfs)★
- Codeforces Round #346 (Div. 2) F. Polycarp and Hay(并查集)
- codeforces round 346div2 Polycarp and Hay搜索+并查集
- codeforces 727F. Polycarp's problems
- CodeForces 864B Polycarp and Letters
- codeforces 864B 之 Polycarp and Letters
- codeforces 659F (并查集 bfs)
- Codeforces Round #436 (Div. 2) B. Polycarp and Letters
- Codeforces 659F F
- codeforces 727F. Polycarp's problems DP or 二分预处理答案
- B. Polycarp and Letters
- Polycarp and Letters
- B. Polycarp and Letters
- codeforces Polycarp at the Radio
- 位运算
- Camera使用setPreviewCallbackWithBuffer优化内存
- [iOS] 报错:Not a PNG file...
- 双向链表的实现
- UVA122(BFS)
- Codeforces 659F Polycarp and Hay【BFS】
- 利用PathFilter上传多个本地的文件
- 设计模式——访问器模式
- DialogFragment文档
- 【C++】int转换为string的两种方法(to_string、字符串流)
- 开发环境小结
- SQL pivot 行转列
- 浅谈Java泛型中的extends和super关键字
- 64. Minimum Path Sum