题目链接 :http://codeforces.com/problemset/problem/489/C
Description
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have lengthm and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
Input
The single line of the input contains a pair of integersm, s (1 ≤ m ≤ 100, 0 ≤ s ≤ 900) — the length and the sum of the digits of the required numbers.
Output
In the output print the pair of the required non-negative integer numbers — first the minimum possible number, then — the maximum possible number. If no numbers satisfying conditions required exist, print the pair of numbers "-1 -1" (without the quotes).
Sample Input
2 15
69 96
3 0
-1 -1
题意很简单,就是找出最小和最大的满足字符宽为s,和为m的数!!!注意坑点!!!要仔细考虑 0 0 和 -1 -1 的状况
思路:
由于字符宽度太大,采用字符串,a,b分别记最小的和最大的,要求就是a的头位元素尽量小,b的头位元素尽量大
代码一:
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#include <string>
int main()
{
int n, m;
scanf("%d%d", &n, &m);
if(n==1 && m==0)
{
printf("0 0\n");
return 0;
}
if(m<1 || m>n*9)
{
printf("-1 -1\n");
return 0;
}
string a="", b="";
for(int i=0;i<n;i++)
{
int x=min(9, m);
m-=x, a+=(x+'0');
}
b=a;
reverse(a.begin(), a.end());
if(a[0]=='0')
for(int i=0;i<n;i++)
if(a[i]!='0')
{
++a[0], --a[i];
break;
}
cout<<a<<' '<<b;
return 0;
}
代码二:
(与代码一思路差不多,但是显得繁琐很多)
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <time.h>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
#define pi 3.1415926535897932384626
#define eps 1e-8
#define N 1005
string s1, s2;
int main()
{
int m,s,s1,s2,i,a[105],b[105];
while(~scanf("%d%d",&m,&s))
{
if(m==1&&s==0)
{
printf("0 0\n");
continue;
}
else if(s==0||s>9*m)
{
printf("-1 -1\n");
continue;
}
else
{
s1=s2=s;
for(i=m-1;i>0;i--)
{
if(s1>9)
{
a[i]=9;
s1-=9;
}
else if(s1>1)
{
a[i]=s1-1;
s1=1;
}
else if(s1==1)
a[i]=0;
}
a[0]=s1;
for(i=0;i<m;i++)
{
if(s2>9)
{
b[i]=9;
s2-=9;
}
else if(s2>0)
{
b[i]=s2;
s2=0;
}
else if(s2==0)
b[i]=0;
}
}
for(i=0;i<m;i++)
printf("%d",a[i]);
printf(" ");
for(i=0;i<m;i++)
printf("%d",b[i]);
printf("\n");
}
return 0;
}