POJ 3548Restoring the digits

来源:互联网 发布:中小学排课软件 编辑:程序博客网 时间:2024/04/28 04:35

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 1G 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]);}}


0 0