产生数(Produce)(bfs,队列)

【题目描述】
给出一个整数n(n≤2000)和k个变换规则(k≤15)。规则:

① 1个数字可以变换成另1个数字;

② 规则中,右边的数字不能为零。

例如:n=234,k=2规则为

2 → 5

3 → 6

上面的整数234经过变换后可能产生出的整数为(包括原数)234,534,264,564共4种不同的产生数。

求经过任意次的变换(0次或多次),能产生出多少个不同的整数。仅要求输出不同整数个数。

【输入】
nkx1x2…xny1y2…yn
【输出】
格式为一个整数(满足条件的整数个数)。

【输入样例】
234
2
2 5
3 6
【输出样例】
4
题目分析:
一道很简单的广搜题,深搜也可以。但有一个地方处理的非常巧妙,详情见代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
const int N=1e9;
int n,a[101],b[101];
bool f[N];//用于标记,四位数的话会到一万
int ans=1,k;
void bfs()
{
    queue<int>m;
    m.push(n);
    f[n]=1;
    int w=1;
    while(!m.empty())//队列非空
    {
        int x=m.front();
        w=1;//位数,见下面
        while(x>0)
        {
            int temp=x%10;
            for(int i=1;i<=k;i++)
            {
                if(a[i]==temp)
                {
                    int y=m.front()+(b[i]-temp)*w;//很巧妙
                    //算出相差多少,再乘位数,加到队首元素上
                    //非常巧妙的处理
                    if(!f[y])//没有出现过这个数
                    {
                        ans++;
                        f[y]=true;//标记为出现过
                        m.push(y);
                    }
                }
            }
            x/=10;
            w*=10;//位数乘十
        }
        m.pop();//出队
    }
}
int main()
{
    cin>>n>>k;
    for(int i=1;i<=k;i++)
    {
        cin>>a[i]>>b[i];
    }
    bfs();
    cout<<ans<<endl;
    return 0;
}
发布了59 篇原创文章 · 获赞 58 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/amazingee/article/details/105187383
今日推荐