1.搜索
先从最简单的dfs开始吧
洛谷1019单词接龙
瞎dfs即可
#include#include <string> #include #include using namespace std; int n, ans; string s[21]; int vis[21]; void dfs(int a, int len) { if (vis[a] == 2) return; ans = max(len, ans); vis[a]++; for (int i = 0; i < s[a].size(); i++) for (int j = 1; j <= n; j++) { if (i == 0 && a != 0) break; int l = i, r = 0; while(s[a][l] == s[j][r]) l++, r++; if (l == s[a].size()) dfs(j, len + s[j].size() - (s[a].size() - i)); } vis[a]--; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) cin >> s[i]; cin >> s[0]; dfs(0, 1); printf("%d", ans); return 0; }
一遍AC,感觉不错
2.bfs
luogu1443马的遍历
裸bfs题,但由于我太菜做了很久很久(真就癌症晚期
说一下我遇到的问题吧
1.忘了pop,然后就绝望tle,听到电脑风扇嗡嗡翁的响
2.是八种走路方法,不是四种
3.vis请在push的时候一起标记,不然就会出现同一个东西被丢进去一万次的尴尬局面,就会快乐tle
4.最后就是宽五格的问题,我最开始以为是printf("%d ", a)这种方法,发现自己WA的之后才知道需要printf("%-5d", a);
tip:%-md:输出格式为整形,长度为m(输出最小长度),左对齐;可用m表示你的3,4,5,121;
#include#include #include #include using namespace std; int n, m, x, y; const int N = 510; #define mp(a, b, c) make_pair(a, make_pair(b, c)) #define f first #define s second typedef pair <int, pair<int, int> > P; queue < P > Q; int move[8][2] = {{2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}}; int ans[N][N]; bool vis[N][N]; int main() { scanf("%d %d %d %d", &n, &m, &x, &y); Q.push(mp(0, x - 1, y - 1)); memset(ans, 0xffffffff, sizeof(ans)); vis[x - 1][y - 1] = true; while (!Q.empty()) { int a = Q.front().s.f; int b = Q.front().s.s; int step = Q.front().f; Q.pop(); ans[a][b] = step; for (int i = 0; i < 8; i++) { int mx = a + move[i][0]; int my = b + move[i][1]; if (mx >= n || mx < 0) continue; if (my >= m || my < 0) continue; if (!vis[mx][my]) { vis[mx][my] = true; Q.push(mp(step + 1, mx, my)); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) printf("%-5d", ans[i][j]); puts(""); } return 0; }
3.再来一次bfs吧
luogu1162填涂颜色
找联通块即可
#include#include using namespace std; const int N = 32; int map[N][N]; bool vis[N][N]; typedef pair <int, int> P; #define f first #define s second queue < P > Q; int move[4][2] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { scanf("%d", &map[i][j]); if (map[i][j]) vis[i][j] = true; } for (int i = 0; i < n; i++) { if (!map[i][0]) Q.push(make_pair(i, 0)), vis[i][0] = true; if (!map[i][n - 1]) Q.push(make_pair(i, n - 1)), vis[i][n - 1] = true; } for (int i = 1; i < n - 1; i++) { if (!map[0][i]) Q.push(make_pair(0, i)), vis[0][i] = true; if (!map[n - 1][i]) Q.push(make_pair(n - 1, i)), vis[n - 1][i] = true; } while (!Q.empty()) { P u = Q.front(); Q.pop(); for (int i = 0; i < 4; i++) { int mx = u.f + move[i][0]; int my = u.s + move[i][1]; if (mx >= n || mx < 0 || my >= n || my < 0) continue; if (!vis[mx][my]) { vis[mx][my] = 1; Q.push(make_pair(mx, my)); } } } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (!vis[i][j]) map[i][j] = 2; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%d ", map[i][j]); puts(""); } return 0; }