搜索与桶:

框架:

void search(int t)
{
  if(t > n)
  {
    //处理
    return;
  }
  for(int i = 0; i <= some_number/*随题目而变*/;i++)
    {
      //状态变化;
      search(t + 1);
      //回溯;
    }
}

源自于itbegin.com_C4_搜索

百钱百鸡:

原版:

#include<iostream>
using namespace std;

int main()
{
  for(int x = 0; x <= 20; x++)
    for(int y = 0; y <= 100 / 3; y++)
    {
      int z = 100 - x - y;
      if(5 * x + 3 * y + z / 3 == 100 && z % 3 == 0)
        cout << x << " " << y << " " << z << "\n";
    }
  return 0;
}

搜索:

#include<iostream>
using namespace std;

int a[4];
double b[4] = {0, 5, 3, 1.0 / 3};

int sum1, sum2;

void search(int t)
{
  if(t > 3)
  {
    if(sum1 == 100 && sum2 == 100)
      cout << a[1] << " " << a[2] << " " << a[3] << "\n";
    return;
  }
  for(int i = 0; i <= 100 / b[t]; i++)
  {
    if(t == 3 && i % 3 != 0) continue;
    a[t] = i;
    sum1 += i;
    sum2 += i * b[t];
    search(t + 1);
    sum1 -= i;
    sum2 -= i * b[t];
  }
}

int main()
{
  search(1);
  return 0;
}

砝码称重:

原版:

#include<iostream>
using namespace std;

bool func[1005];

int main()
{
  int a, b, c, d, e, f, t, total = 0;
  cin >> a >> b >> c >> d >> e >> f;
  for(int i = 0; i <= a; i++)
    for(int j = 0; j <= b; j++)
      for(int k = 0; k <= c; k++)
        for(int l = 0; l <= d; l++)
          for(int m = 0; m <= e; m++)
            for(int n = 0; n <= f; n++)
            {
              t = i + 2 * j + 3 * k + 5 * l + 10 * m + 20 * n;
              if(t <= 1000)
              {
                func[t] = 1;
              }
            }
  for(int i = 1; i <= 1000; i++)
    if(func[i] == 1) total++;
  cout << "Total=" << total;
  return 0;
}

搜索:

#include<iostream>
using namespace std;

int a[7], w[7] = {0, 1, 2, 3, 5, 10, 20}, cnt = 0, sum = 0;
bool to[1005];

void search(int t)
{
  if(t > 6)
  {
    to[sum] = 1;
    return;
  }
  for(int i = 0; i <= a[t]; i++)
  {
    sum += i * w[t];
    search(t + 1);
    sum -= i * w[t];
  }
}

int main()
{
  for(int i = 1; i <= 6; i++)
    cin >> a[i];
  search(1);
  for(int i = 1; i <= 1000; i++)
    if(to[i]) cnt++;
  cout << "Total=" << cnt;
  return 0;
}

选书-搜索

#include<iostream>
using namespace std;

int n, a[30], b[30][2], cnt;
bool to[30];

void search(int t)
{
  if(t > n)
  {
    cnt++;
    return;
  }
  for(int i = 0; i <= 1; i++)
  { 
  	if(to[b[t][i]]) continue;
  	to[b[t][i]] = true;
  	a[t] = b[t][i];
  	search(t + 1);
    to[b[t][i]] = false;
  	a[t] = 0;
  }
}

int main()
{
  cin >> n;
  for(int i = 1; i <= n; i++)
    cin >> b[i][0] >> b[i][1];
  search(1);
  cout << cnt;
  return 0;
}