贪心算法
题意:找到m位数且各位的数字相加为s;
找最大值时,尽可能让9在高位后面尽可能补零;
找最小值时,尽可能让9在个位,最高位为1;
值得注意的是 m*9<s和m>=2&&s==0时要输出-1 -1 (被坑了QAQ)
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
bool compare(int a, int b)
{
return a>b;
}
int cmp(const void *a, const void *b)
{
return *(char *)a - *(char *)b;
}
bool composite(int i)
{
if (i == 1) return false;
else if (i == 2 || i == 3) return true;
else for (int j = 2;j<sqrt((float)i) + 1;j++)
{
if (i%j == 0)
return true;
}
return false;
}
int max(int a1, int a2)
{
return a1 = a1>a2 ? a1 : a2;
}
int father[1001];
void initial(int n)
{
for (int i = 1;i <= n;i++)
father[i] = i;
}
int find(int a)
{
while (father[a] != a)
a = father[a];
return a;
}
void combine(int a, int b)
{
int temp1 = find(a);
int temp2 = find(b);
if (temp1 != temp2)
father[temp1] = temp2;
}
int a[3];
int main()
{
ios::sync_with_stdio(false);
int m, s, a[101] = { 0 }, b[101] = { 0 };//分别是位数和加起来的值
while (cin >> m >> s)
{
int i = 0,j=0,temp1=s,temp2=m;
if (m == 1 && s == 0) cout << 0 << ' ' << 0 << endl;
else if (((m == 1) && s > 9)||(s==0)||m*9<s) cout << -1 << ' ' << -1 << endl;
else if (s > 9)
{
if (m == 1) cout << -1 << ' ' << -1 << endl;
else {
while (s > 9 && m > 0)
{
a[i] = 9;
m--;
s -= 9;
i++;
}
int u = i + m - 1;
if (m > 1) {
a[u] = 1;
a[i] = s - 1;
for (int k = i + 1;k < u;k++)
a[k] = 0;
}
else a[u] = s;
for (int k = u;k >= 0;k--)
cout << a[k];
printf(" ");
while (temp1 > 9 && temp2 > 0)
{
b[temp2 - 1] = 9;
temp2--;
temp1 -= 9;
j++;
}
int p = temp2 - 1;
b[p] = temp1;
for (int k = p + j;k >= 0;k--)
cout << b[k];
printf("\n");
}
}
else if (s <= 9)
{
if (m == 1) printf("%d %d\n", s, s);
else {
a[0] = s - 1;
a[m - 1] = 1;
for (int k = 1;k < m - 1;k++)
a[k] = 0;
b[m - 1] = s;
for (int k = m-1;k >= 0;k--)
cout << a[k];
printf(" ");
for (int k = m - 1;k >= 0;k--)
cout << b[k];
printf("\n");}
}
}
}