HDU 1495 非常可乐 (bfs,数论)

题面

Problem Description
大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。

Input
三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。

Output
如果能平分的话请输出最少要倒的次数,否则输出"NO"。

Sample Input
7 4 3
4 1 3
0 0 0

Sample Output
NO
3

思路

老实说,我不会,因为这题直接搜的话其实我感觉不大好写,网上查了的话,搜索和数论两种做法。首先讲下数论的做法,用到了扩展欧几里得和裴蜀定理。下面直接贴一下草稿吧。(更一下,这里最后一步笔误,是大于二分之(从c+d))

广搜的话,就是之间枚举每种情况,从谁倒向谁,在成功的时候退出并返回步数。

代码实现

数论代码

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
int gcd (int a,int b) {
   return b?gcd (b,a%b):a;
}
int main () {
  int s,n,m;
  while (cin>>s>>n>>m) {
     if (s==0&&m==0&&n==0) break;
     s/=gcd (n,m);
     if (s&1) cout<<"NO"<<endl;
     else  cout<<s-1<<endl;
  }
   return 0;
}

广搜代码

#include<cstdio>
#include<queue>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
const int maxn=110;
int v[5];
int vis[maxn][maxn][maxn];  //标记这个时刻的水位情况
struct node {
   int a[5];       //node表示当前情况下各个水杯的情况和所用步数
   int step;
}u;
void pour (int a,int b) {
   int sum=u.a[a]+u.a[b];
   if (sum>v[b]) {
      u.a[b]=v[b];
   }
   else u.a[b]=sum;
   u.a[a]=sum-u.a[b];
}
void bfs () {
    node st;
    st.a[1]=v[1];
    st.a[2]=0;
    st.a[3]=0;
    st.step=0;
    queue <node> q;
    vis[v[1]][v[2]][v[3]]=1;
    q.push(st);
    while (!q.empty ()) {
       node temp = q.front();
       q.pop();
       int i,j;
       if (temp.a[1]==temp.a[3]&&temp.a[2]==0) {
          cout<<temp.step<<endl;
          return ;
       }
       for (int i=1;i<4;i++) 
        for (int j=1;j<4;j++) {
           if (i!=j) {
              u=temp;
              pour(i,j);
              if (!vis[u.a[1]][u.a[2]][u.a[3]]) {
                 u.step++;
                 q.push (u);
                 vis[u.a[1]][u.a[2]][u.a[3]]=1;
              }
           }
        }
    }
   cout<<"NO"<<endl;
}
int main () {
  while (cin>>v[1]>>v[2]>>v[3]) {
     if (v[1]==0&&v[2]==0&&v[3]==0) break;
     if (v[1]%1) {
        cout<<"NO"<<endl;
        continue;
     }
     if (v[2]>v[3]) swap (v[2],v[3]);
     bfs ();
  }
   return 0;
}
posted @ 2020-07-05 11:46  Luglucky  阅读(172)  评论(1)    收藏  举报