带分数(DFS+隔板法)

一、问题

在这里插入图片描述

二、暴力枚举

1、思路

可以先全排列出所有的情况,然后根据每一种情况再使用隔板法。

时间复杂度:
9 ! ∗ 9 ∗ C 8 2 = 9 ! ∗ 9 ∗ 4 ∗ 7 = 91445760 9!*9*C_8^2=9!*9*4*7= 9144 5760 9!9C82=9!947=91445760,大概是108的时间复杂度,恰好能在1秒之内算完。

2、代码

/*
DFS+隔板法:
9!*9*4*7=9144 5760=9*10^8=1^9
*/
#include<iostream>
using namespace std;
bool st[10];
int a[10];
int n;
int ans;

int qmi(int a,int b)
{
  int res=1;
  while(b)
  {
    if(b&1)res*=a;
    a*=a;
    b>>=1;
  }
  return res;
}

int cal(int x,int y)
{
  int res=0;
  for(int i=0;i<y-x+1;i++)
  {
    res+=a[x+i]*qmi(10,i);
  }
  return res;
}

void dfs(int u)
{
  if(u>=9)
  {
    for(int i=1;i<9;i++)
    {
      for(int j=i;j<8;j++)
      {
          int x1=cal(0,i-1);
          int x2=cal(i,j);
          int x3=cal(j+1,8);
          if(x2%x3==0&&n==(x1+x2/x3))
          {
            ans++;
          }
      }
    }
  }

  for(int i=1;i<=9;i++)
  {
    if(!st[i])
    {
      st[i]=true;
      a[u]=i;
      dfs(u+1);
      st[i]=false;
    }
  }
} 

int main()
{
  cin>>n;
  dfs(0);
  cout<<ans<<endl;
  return 0;
}

三、优化

1、思路

我们发现,我们去枚举了三个变量的所有可能,但是我们可以只枚举其中的两个,然后利用这两个数字算出第三个,再看第三个值的位数组成是否和前面的两个数的某位重复。

2、代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10;
int n;
bool st[N], backup[N];
int ans;
bool check(int a, int c)
{
    long long b = n * (long long)c - a * c;

    if (!a || !b || !c) return false;

    memcpy(backup, st, sizeof st);
    while (b)
    {
        int x = b % 10; 
        b /= 10;
        if (!x || backup[x]) return false;
        backup[x] = true;
    }

    for (int i = 1; i <= 9; i ++ )
        if (!backup[i])
            return false;

    return true;
}
void dfs_c(int u, int a, int c)
{
    if (u > 9) return;

    if (check(a, c)) ans ++ ;

    for (int i = 1; i <= 9; i ++ )
        if (!st[i])
        {
            st[i] = true;
            dfs_c(u + 1, a, c * 10 + i);
            st[i] = false;
        }
}
void dfs_a(int u, int a)
{
    if (a >= n) return;
    if (a) dfs_c(u, a, 0);

    for (int i = 1; i <= 9; i ++ )
        if (!st[i])
        {
            st[i] = true;
            dfs_a(u + 1, a * 10 + i);
            st[i] = false;
        }
}
int main()
{
    cin >> n;

    dfs_a(0, 0);

    cout << ans << endl;

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值