AcWing 1355. 母亲的牛奶(每日一题) - AcWing
所需知识:dfs,bfs
思路:遍历每一种情况,将所有情况标记,最后从小到大依次遍历,判断某点是否被标记,若被标记,则表示可以到这种情况,直接输出,若没被标记,则继续遍历,直到遍历完所有c可能的取值范围[0,C]
dfs代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 21;
int A,B,C;
bool vis[N][N][N];
void dfs(int a,int b,int c){
if(vis[a][b][c])return;
vis[a][b][c]=true;
dfs(a-min(a,B-b),min(B,a+b),c);
dfs(a-min(a,C-c),b,min(C,a+c));
dfs(min(A,a+b),b-min(b,A-a),c);
dfs(a,b-min(b,C-c),min(C,c+b));
dfs(min(A,a+c),b,c-min(c,A-a));
dfs(a,min(B,c+b),c-min(c,B-b));
}
int main()
{
cin>>A>>B>>C;
dfs(0,0,C);
for (int c = 0; c <= C; c ++ ){
for (int b = 0; b <= B; b ++ ){
if(vis[0][b][c])
{cout << c << ' ';
break;}
}
}
return 0;
}
bfs代码:(图的遍历)将每一种状态看作图中的每一个点,利用队列来实现图的遍历
#include <iostream>
#include <queue>
using namespace std;
const int N = 30;
int A,B,C;
bool st[N][N][N];
struct Node {
int a,b,c;
};
queue <Node> q;
void insert (int a,int b,int c) {
if (!st[a][b][c]) {
q.push ({a,b,c});
st[a][b][c] = true;
}
}
void bfs () {
q.push ({0,0,C});
st[0][0][C] = true;
while (!q.empty ()) {
auto [a,b,c] = q.front ();
q.pop ();
insert (a-min (a,B-b),min (a+b,B),c);
insert (a-min (a,C-c),b,min (a+c,C));
insert (min (a+b,A),b-min (b,A-a),c);
insert (a,b-min (b,C-c),min (b+c,C));
insert (min (a+c,A),b,c-min (c,A-a));
insert (a,min (b+c,B),c-min (c,B-b));
}
}
int main () {
cin >> A >> B >> C;
bfs ();
int ans = 0;
for (int c = 0;c <= C;c++) {
for (int b = 0;b <= B;b++) {
if (st[0][b][c]) {
cout << c << ' ';
break;
}
}
}
cout << endl;
return 0;
}