UESTC - 1039 Fabricate equation (DFS&模拟)

UESTC - 1039
Fabricate equation
Time Limit:                                                        1000MS                          Memory Limit: 65535KB   64bit IO Format:                            %lld & %llu                       

SubmitStatus

Description

Given an integer Y, you need to find the minimal integer K so that there exists a X satisfying X−Y=Z(Z≥0) and the number of different digit between X and Z is K under decimal system.

For example: Y=1, you can find a X=100 so that Z=99 and K is 3 due to 1≠0 and 0≠9. But for minimization, we should let X=1 so that Z=0 and K can just be 1.

Input

Only one integer Y(0≤Y≤1018).

Output

The minimal K.

Sample Input

1

191

Sample Output

1

2

Hint

Source

The 13th UESTC Programming Contest Preliminary
//题意:
给你一个Y,问通过X-Y=Z这个公式可以确定出来的X,Z每个位上的数字进行比较,最少有几个位上的数是不相等的。
//思路:
通过模拟可以发现规律,只有给定的Y中有0(取它本身),9(通过下一位进位)可以使得X和Z在对应位上获得相等的数字,所以每个位上模拟。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
int a[25];
int ans;
void dfs(int cur, int cnt, int tp, int kg)
{
	if(cur >= tp)
	{
		ans = max(ans, cnt);
		return;
	}
	if(a[cur] == 0)
	{
		if(kg != 9 && !(cur == tp - 2 && a[tp - 1] == 9))
			dfs(cur + 1, cnt + 1, tp, 0);
		else 
			dfs(cur + 1, cnt, tp, 1);
	}
	else if(a[cur] == 9)
	{
		if((kg == 1 || kg == 9) && cur != tp - 1 && cur != 0)
			dfs(cur + 1, cnt + 1, tp, 9);
		else
			dfs(cur + 1, cnt, tp, 1);
	}
	else
		dfs(cur + 1, cnt, tp, 1);
}
int main()
{
	LL Y;
	while(~scanf("%lld", &Y))
	{
		int tp = 0;
		while(Y)
		{
			a[tp++] = Y % 10;
			Y /= 10;
		}
		ans = 0;
		dfs(0, 0, tp, 1);
		printf("%d\n", tp - ans);
	}
	return 0;
}

//这是自己写的模拟的代码,一直WA4。。。,还不懂
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#define ll long long
using namespace std;
char a[20],b[20],s[20],ss[20];
int main()
{
	int i,j;
	while(scanf("%s",ss)!=EOF)
	{
		memset(a,'\0',sizeof(a));
		memset(b,'\0',sizeof(b));
		memset(s,'\0',sizeof(s));
		int len=strlen(ss),k=0;
		for(i=len-1;i>=0;i--)
			s[k++]=ss[i];
		if(s[0]!='0')
			a[0]=s[0]-1;
		else
			a[0]='0';
		
		int l,r;
		for(i=1;i<k-1;)
		{
			if(s[i]!='0')
			{
				a[i]=s[i]-1;
				i++;
			}
			else
			{
				l=i;
				while(s[i]=='0') i++;
				r=i;
				if(r-l<=1)
					a[l]='0';
				else
				{
					a[l]='1';
					for(j=l+1;j<r;j++)
						a[j]='0';
				}			
			}
		}
		a[k-1]=s[k-1]+1;
		ll n=0,m=0,nm;
		for(i=k-1;i>=0;i--)
			n=n*10+(a[i]-'0');
		for(i=0;i<len;i++)
			m=m*10+(ss[i]-'0');
		nm=n-m;
		k=0;
		while(nm)
		{
			b[k++]=nm%10+'0';
			nm/=10;
		}
		for(i=k;i<len;i++)
			b[i]='0';
		int cnt=0;
		for(i=0;i<len;i++)
			if(b[i]!=a[i])
				cnt++;
		if(ss[0]=='9')
			cnt++;
		printf("%d\n",cnt);
	}
	return 0;
}

你可能感兴趣的:(UESTC - 1039 Fabricate equation (DFS&模拟))