关于BFS与DFS
2024/7/18
电路维修
双端队列BFS
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define haha puts("")
#define ye puts("Yes")
#define no puts("No")
typedef pair<int, int> pii;
typedef unsigned long long ull;
const int N = 3e5 + 10;
const int M = 1010;
const double eps = 1e-8;
int dx[] = {-1, -1, 1, 1};
int dy[] = {-1, 1, 1, -1};
int n, m, k;
int ksm(int x, int y) {
int ans = 1;
while (y) {
if (y & 1)
ans = ans * x;
y >>= 1;
x = x * x;
}
return ans;
}
char a[M][M];
int dis[M][M];
int g[M][M];
char cp[] = {'\\', '/', '\\', '/'};
int ix[4] = {-1, -1, 0, 0};
int iy[4] = {-1, 0, 0, -1};
void bfs() {
memset(dis, 0x3f3f3f3f, sizeof dis);
deque<pii> dq;
dq.push_back({0, 0});
dis[0][0] = 0;
while (dq.size()) {
auto t = dq.front();
dq.pop_front();
int x = t.first, y = t.second;
for (int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 0 && xx <= n && yy >= 0 && yy <= m) {
int fx = x + ix[i], fy = y + iy[i];
int w = 0;
if (a[fx][fy] != cp[i]) w = 1;
if (dis[xx][yy] > dis[x][y] + w) {
dis[xx][yy] = dis[x][y] + w;
if (w == 1) dq.push_back({xx, yy});
else dq.push_front({xx, yy});
}
}
}
}
if (dis[n][m] > 1e18)
cout << "NO SOLUTION\n";
else
cout << dis[n][m] << '\n';
}
void solve() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
scanf("%s", &a[i]);
}
bfs();
}
signed main() {
// ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
// cin >> t;
while (t--)
solve();
}
记录一下\(2^n\)选点排列的\(dfs\)代码
void dfs(int u, int x) {
a[u] = x;
if (u == n) {
}
dfs(u + 1, 0);
dfs(u + 1, 1);
}
dfs(0,0)
P3052 [USACO12MAR] Cows in a Skyscraper G
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 10;
int n, m;
vector<int> a;
bool st[100];
int b[100];
int mx = 0;
int ab[100];
void dfs(int u, int x) {
b[u] = x;
if (u == a.size()) {
// for (int i = 1; i <= a.size(); i++) {
// cout << b[i] << ' ';
// }
// cout << '\n';
int sum = 0;
//求和
for (int i = 0; i < a.size(); i++) {
if (b[i + 1] == 1) {
sum += a[i];
}
}
//如果能行就找最大可能
if (sum <= m && sum > mx) {
mx = sum;
for (int i = 0; i <= 99; i++) ab[i] = 0;
//更新a数组的值
for (int i = 0; i < a.size(); i++) {
if (b[i + 1] == 1) ab[i + 1] = 1;
}
}
return;
}
dfs(u + 1, 0);
dfs(u + 1, 1);
}
signed main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a.push_back(x);
}
int f = 0;
while (1) {
f ++;
mx = 0;
for (int i = 1; i <= n; i++) st[i] = 0;
dfs(0, 0);
vector<int> ca;
for (int i = 0; i < a.size(); i++) {
if (ab[i + 1] == 0)
ca.push_back(a[i]);
}
a = ca;
if (a.size() == 0) break;
}
cout << f << '\n';
}