三羊献瑞

题目 三羊献瑞

image-2a63d8ca

思路分析

这道题刷真题卷的时候用的是纯暴力把每个数都套1~9

代码极其夸张 三羊献瑞

其实可以套用上一题的思路 因为每个字都在0~9之间 且不重复

所以可以先做出全排列 再想办法套给每个字

image-d0bb2f6c

代码实现

#include<bits/stdc++.h>

using namespace std;

const int N=10;

int alls[N];

bool st[N];

int ans;

void dfs(int u){

  if(u==9){

    int A=alls[0]*1000+alls[1]*100+alls[2]*10+alls[3];

    int B=alls[4]*1000+alls[5]*100+alls[6]*10+alls[1];

    int C=alls[4]*10000+alls[5]*1000+alls[2]*100+alls[1]*10+alls[7];

    if(A+B==C && B>1000)

      ans=B;

    return;

  }

  for(int i=0;i<=9;i++){

    if(!st[i]){

      st[i]=true;

      alls[u]=i;

      dfs(u+1);

      alls[u]=0;

      st[i]=false;

    }

  }

}

int main()

{

  dfs(0);

  cout<<ans;

  return 0;

}
#include<bits/stdc++.h>

using namespace std;

vector<int> alls={0,1,2,3,4,5,6,7,8,9};

int main()

{

  do{

    int A=alls[0]*1000+alls[1]*100+alls[2]*10+alls[3];

    int B=alls[4]*1000+alls[5]*100+alls[6]*10+alls[1];

    int C=alls[4]*10000+alls[5]*1000+alls[2]*100+alls[1]*10+alls[7];

    if(A+B==C && B>1000){

      cout<<B;

      return 0;

    }

  }while(next_permutation(alls.begin(),alls.end()));

  return 0;

}

同类题型

视频讲解


⬅️ 4、方格填数 🏠 00-刷题理模型 ➡️ 全排列(考虑顺序)