题意:有两个水壶,体积为A、B和无限量的水,在这两个水壶里相互倒水,判断怎么倒能到C体积的水
链接:http://poj.org/problem?id=3414
思路:dfs,每个水壶作为节点建图进行搜索
注意点:无
以下为AC代码:
Run ID | User | Problem | Result | Memory | Time | Language | Code Length | Submit Time |
13918617 | luminous11 | 3414 | Accepted | 780K | 0MS | G++ | 3598B | 2015-02-28 15:18:54 |
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <deque>
#include <list>
#include <cctype>
#include <algorithm>
#include <climits>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#define ll long long
#define ull unsigned long long
#define all(x) (x).begin(), (x).end()
#define clr(a, v) memset( a , v , sizeof(a) )
#define pb push_back
#define mp make_pair
#define read(f) freopen(f, "r", stdin)
#define write(f) freopen(f, "w", stdout)
using namespace std;
//const double pi = acos(-1);
//const double eps = 1e-10;
//const int dir[[4][2] = { 1,0, -1,0, 0,1, 0,-1 };
int b, c, a;
bool vis[105][105];
struct node{
int b, c;
string str;
node(){}
node ( int _b, int _c, string _str ) : b(_b), c(_c), str(_str) {}
};
string ans;
inline bool judge ( const node &tmp )
{
if ( tmp.b == a || tmp.c == a ){
ans = tmp.str;
return true;
}
else{
return false;
}
}
bool solve()
{
clr ( vis, 0 );
queue<node> q;
q.push ( node( 0, 0, "" ) );
while ( ! q.empty() ){
node tmp = q.front();
q. pop();
if ( judge ( tmp ) ){
return true;
}
// fill 1 '1
if ( tmp.b != b ){
if ( vis[b][tmp.c] == 0 ){
vis[b][tmp.c] = 1;
q.push ( node ( b, tmp.c, tmp.str + "1" ) );
}
}
// fill 2 '2
if ( tmp.c != c ){
if ( vis[tmp.b][c] == 0 ){
vis[tmp.b][c] = 1;
q.push ( node ( tmp.b, c, tmp.str + "2" ) );
}
}
// drop 1 '3
if ( tmp.b ){
if ( vis[0][tmp.c] == 0 ){
vis[0][tmp.c] = 1;
q.push ( node ( 0, tmp.c, tmp.str + "3" ) );
}
}
// drop 2 '4
if ( tmp.c ){
if ( vis[tmp.b][0] == 0 ){
vis[tmp.b][0] = 1;
q.push ( node ( tmp.b, 0, tmp.str + "4" ) );
}
}
// pour12 '5
if ( tmp.b && tmp.c != c ){
int t = min ( tmp.b, c - tmp.c );
if ( vis[tmp.b-t][tmp.c+t] == 0 ){
vis[tmp.b-t][tmp.c+t] = 1;
q.push ( node ( tmp.b-t, tmp.c+t, tmp.str + "5" ) );
}
}
// pour21 '6
if ( tmp.c && tmp.b != b ){
int t = min ( tmp.c, b - tmp.b );
if ( vis[tmp.b+t][tmp.c-t] == 0 ){
vis[tmp.b+t][tmp.c-t] = 1;
q. push ( node ( tmp.b+t, tmp.c-t, tmp.str + "6" ) );
}
}
}
return 0;
}
void print ()
{
cout << ans.size() << endl;
for ( int i = 0; i < ans.size(); i ++ ){
if ( ans[i] == '1' )
cout << "FILL(1)" << endl;
if ( ans[i] == '2' )
cout << "FILL(2)" << endl;
if ( ans[i] == '3' )
cout << "DROP(1)" << endl;
if ( ans[i] == '4' )
cout << "DROP(2)" << endl;
if ( ans[i] == '5' )
cout << "POUR(1,2)" << endl;
if ( ans[i] == '6' )
cout << "POUR(2,1)" << endl;
}
}
int main()
{
ios::sync_with_stdio( false );
//while ( cin >> b >> c >> a ){
cin >> b >> c >> a;
if ( solve() ){
print();
}
else{
cout << "impossible" << endl;
}
//}
return 0;
}