P1451 求细胞数量
题目链接:P1451 求细胞数量 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
bfs:
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
string s[105];
bool vis[105][105];
struct point {
int x, y;
};
int main() {
int n, m, ans = 0;
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> s[i];
}
queue<point>q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (s[i][j] != '0' && vis[i][j] == 0) {
ans++;
vis[i][j] = 1;
point p;
p.x = i, p.y = j;
q.push(p);
while (!q.empty()) {
for (int k = 0; k < 4; k++) {
int xx = q.front().x + dx[k];
int yy = q.front().y + dy[k];
if (xx >= 0 && xx < n && yy >= 0 && yy < m && vis[xx][yy] == 0 && s[xx][yy] != '0') {
point t;
t.x = xx, t.y = yy;
q.push(t);
vis[xx][yy] = 1;
}
}
q.pop();
}
}
}
}
cout << ans;
return 0;
}
P1460 [USACO2.1]健康的荷斯坦奶牛 Healthy Holsteins
题目链接:P1460 [USACO2.1]健康的荷斯坦奶牛 Healthy Holsteins - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
dfs:?
#include <iostream>
#include <cstring>
using namespace std;
int v, g, p = (1 << 29), cnt;
int a[30], t[30];
int b[20][30];
int ans[20], minn[20];
bool check() {
for (int i = 1; i <= v; i++) {
if (t[i] < a[i]) {
return false;
}
}
return true;
}
void dfs(int i) {
if (i > g ) {
if (p > cnt && check()) {
p = cnt;
for (int j = 1; j <= p; j++) {
ans[j] = minn[j];
}
}
return;
}
cnt++;
minn[cnt] = i;
for (int j = 1; j <= v; j++) {
t[j] += b[i][j];
}
dfs(i + 1);
minn[cnt] = 0;
cnt--;
for (int j = 1; j <= v; j++) {
t[j] -= b[i][j];
}
dfs(i + 1);
}
int main() {
cin >> v;
for (int i = 1; i <= v; i++) {
cin >> a[i];
}
cin >> g;
for (int i = 1; i <= g; i++) {
for (int j = 1; j <= v; j++) {
cin >> b[i][j];
}
}
dfs(1);
cout << p << ' ';
for (int i = 1; i <= p; i++) {
cout << ans[i] << ' ';
}
return 0;
}
P2372 yyy2015c01挑战算周长
题目链接:P2372 yyy2015c01挑战算周长 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
bfs:?
#include <iostream>
#include <queue>
using namespace std;
int dx[8] = {0, 0, 1, -1, 1, 1, -1, -1};
int dy[8] = {1, -1, 0, 0, -1, 1, 1, -1};
char mapp[30][30];
bool vis[30][30];
int main() {
int m, n, x, y, ans = 0;
queue<pair<int, int>>q;
cin >> m >> n >> x >> y;
for (int i = 0; i < m; i++) {
cin >> mapp[i];
}
q.push(make_pair(x - 1, y - 1));
vis[x - 1][y - 1] = 1;
while (!q.empty()) {
for (int i = 0; i < 8; i++) {
int xx = q.front().first + dx[i];
int yy = q.front().second + dy[i];
if (xx >= 0 && xx < m && yy >= 0 && yy < n && vis[xx][yy] == 0 && mapp[xx][yy] == 'X') {
vis[xx][yy] = 1;
q.push(make_pair(xx, yy));
}
}
q.pop();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (vis[i][j]) {
for (int k = 0; k < 4; k++) {
int xx = i + dx[k];
int yy = j + dy[k];
if (xx < 0 || xx >= m || yy < 0 || yy >= n || vis[xx][yy] == 0) {
ans++;
}
}
}
}
}
cout << ans;
return 0;
}
|