您的位置:首页 > 其它

POJ 3548 Restoring the digits

2015-07-26 17:02 316 查看
Description

Let's consider arithmetic expressions (addition or subtraction) over non-negative decimal integers. The expression syntax is as follows:

the first operand;
the operator sign ('+' or '‑');
the second operand;
the character '=';
the result of the operation (sum or difference, according to the operator).

The operands don't exceed 999 999 999 . In case of subtraction the first operand should be greater than or equal to the second one. There are no spaces in the expression.

Upper-case Latin letters are substituted for some digits (possibly including insignificant zeroes) so that identical letters correspond to identical digits and different letters correspond to different digits. It is guaranteed that at least one such substitution
is made.

The task is to restore the substituted digits.

Input

The input contains only one line with the encoded arithmetic expression.

Output

The output consists of several lines. Each line describes one substitution and contains a letter and the corresponding digit. The letter and the digit should be separated by exactly one space. The strings should be sorted in the ascending order of letters.
Letters not used in the substitution should not be listed.

Sample Input

103K+G0G1=CG36


Sample Output

C 1
G 0
K 5

数据挺小的,直接暴力dfs
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<vector>
using namespace std;
const int maxn=205;
char s[maxn],a[maxn],c;
int b[maxn],tot,v[maxn],f[maxn];

bool check()
{
	for (int i=0;i<tot;i++) v[a[i]]=b[i];
	for (int i=0;i<10;i++) v[i+'0']=i;
	int x1,x2,x3,i,j,k;
	for (x3=x2=x1=i=0;s[i]!='+'&&s[i]!='-';i++) x1=x1*10+v[s[i]];
	for (j=i+1;s[j]!='=';j++) x2=x2*10+v[s[j]];
	for (k=j+1;s[k];k++) x3=x3*10+v[s[k]];
	if (s[i]=='+'&&x1+x2==x3) return true;
	if (s[i]=='-'&&x1-x2==x3) return true;
	return false;
}

bool dfs(int x)
{
	if (x==tot) return check();
	for (int i=0;i<10;i++)
	if (!f[i])
	{
		b[x]=i;
		f[i]=1;
		if (dfs(x+1)) return true;
		f[i]=0;
	}
	return false;
}

int main()
{
	while (~scanf("%s",s))
	{
		tot=0;
		memset(f,0,sizeof(f));
		for (char i='A';i<='Z';++i)
			for (int j=0;s[j];j++)
				if (i==s[j]) {a[tot++]=i; break;}
		dfs(0);
		for (int i=0;i<tot;i++)	printf("%c %d\n",a[i],b[i]);
	}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: