现在的位置: 首页 > 综合 > 正文

产生数

2018年01月17日 ⁄ 综合 ⁄ 共 937字 ⁄ 字号 评论关闭

题目描述
给出一个整数n(n<=2000)和k个变换规则(k≤15)。规则:
① 1个数字可以变换成另1个数字;
② 规则中,右边的数字不能为零。
例如:n=234,k=2规则为
2 → 5
3 → 6
上面的整数234经过变换后可能产生出的整数为(包括原数)234,534,264,564共4种不同的产生数。
求经过任意次的变换(0次或多次),能产生出多少个不同的整数。仅要求输出不同整数个数。
输入格式
n
k
x1 y1
x2 y2
… …
xn yn

输出
格式为一个整数(满足条件的整数个数)。
样例输入
234
2
2 5
3 6
样例输出

4

c++代码:

#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
int n,k;
int a[20],b[20];
bool f[10000];//数组千万不要开小了,因为数会变,4位数至少开1万 
queue<int> q;
void init();
void work();
int main()
{
	//freopen("produce5.in","r",stdin);
	init();
	work();	
	return 0;
}
void init()
{
	memset(f,0,sizeof(f));
	cin>>n;
	cin>>k;
	for(int i=1;i<=k;i++) cin>>a[i]>>b[i];	
}
void work()
{
	int tot=0;
	f[n]=true;//标记n已出现 
	q.push(n);//把n进队 
	tot++;	
	while(!q.empty())//队列非空 
	{
		int x=q.front();//对队首的每一位进行操作		
		int wei=1;//记录当前处理的是那一位,第一位时为1,第二位时时10……100				
		while(x>0)
		{
			int temp=x%10;//取个位			
			for(int i=1;i<=k;i++)
			{
				if(temp==a[i])
				{
					int p=q.front()+(b[i]-temp)*wei;//好好理解					
					if(!f[p])//如果p没出现过,进队,并设为已出现 
					{						
						q.push(p);
						f[p]=true;
						tot++;						
					}
				}
			}
			x=x/10;			
			wei*=10;
		}
		q.pop();
	}
	cout<<tot<<endl;
}
【上篇】
【下篇】

抱歉!评论已关闭.