题目链接:点击打开链接
思路:个人觉得字符串的输入是个很头疼的问题,最终用s[1010][1010]来解决,s[i]就等于"+"或“-”或“=”或“?"或"n",最后一个字符串是n,将它转换为数字n,遍历一个s数组,得到“+”的个数cnt1和“-”的个数cnt2;
如果cnt1==0&&cnt2==0,意味着等式是? = n,输出n = n,即可;
第一个数肯定是被加起来的,所以cnt1+1个数被加起来,有cnt2个数被减掉,如果(cnt1+1)*n-cnt2*1<n的话肯定无解,同理(cnt1+1)-cnt2*n>n的话也无解;
反之一定有解,将cnt1+1个数保存在a[1010]中,将cnt2个数保存在b[1010]中,接下来是贪心的做法,先初始化a[1~cnt1+1]=1,b[1~cnt2]=1;
如果cnt1+1-cnt2>n,证明要减的更多,将他们尽可能均分给每一个减数:
cnt3=(cnt1+1-cnt2-n)/cnt2;
for(h=1;h<=cnt2;h++)
b[h]+=cnt3;
cnt3=(cnt1+1-cnt2-n)%cnt2;
if(cnt3>=1)
for(h=1;h<=cnt3;h++) b[h]++;
如果 cnt1+1-cnt2<n,证明要加的更多,同样的处理方法,这样可以保证每一个数都大于等于1且不会超过n:
cnt3=(n-(cnt1+1-cnt2))/(cnt1+1);
for(h=1;h<=cnt1+1;h++)
a[h]+=cnt3;
cnt3=n-(cnt1+1-cnt2)-cnt3*(cnt1+1);
for(h=1;h<=cnt3;h++) a[h]++;
下面附上AC代码:这题毕竟卡了很久,凌晨两点半睡不着又下床想了这种写法才过掉的
#include<stdio.h>
#include<string.h>
#include<math.h>
int main()
{
char s[1010][1010];int i=0,j,n=0,cnt1=0,cnt2=0,cnt3=1,a[1010],b[1010];
while(scanf("%s",s[i])!=EOF)
{
if(strcmp(s[i],"?")==0||strcmp(s[i],"+")==0||strcmp(s[i],"-")==0||strcmp(s[i],"=")==0) i++;
else break;
}
for(j=0;j<i;j++)
{
if(strcmp(s[j],"+")==0) cnt1++;
if(strcmp(s[j],"-")==0) cnt2++;
}
int len=strlen(s[i]);
for(j=len-1;j>=0;j--)
{
n+=(s[i][j]-'0')*cnt3;
cnt3*=10;
}
//printf("%d %d\n",cnt1,cnt2);
if(cnt1==0&&cnt2==0) printf("Possible\n%d = %d\n",n,n);
else if(n+n*cnt1-cnt2<n||1+cnt1-cnt2*n>n) printf("Impossible\n");
else
{
int h;
printf("Possible\n");
for(h=1;h<=cnt1+1;h++)
a[h]=1;
for(h=1;h<=cnt2;h++)
b[h]=1;
if(cnt1+1-cnt2>n)
{
cnt3=(cnt1+1-cnt2-n)/cnt2;
for(h=1;h<=cnt2;h++)
b[h]+=cnt3;
cnt3=(cnt1+1-cnt2-n)%cnt2;
if(cnt3>=1)
for(h=1;h<=cnt3;h++) b[h]++;
}
else if(cnt1+1-cnt2<n)
{
cnt3=(n-(cnt1+1-cnt2))/(cnt1+1);
for(h=1;h<=cnt1+1;h++)
a[h]+=cnt3;
cnt3=n-(cnt1+1-cnt2)-cnt3*(cnt1+1);
for(h=1;h<=cnt3;h++) a[h]++;
}
//for(h=1;h<=cnt1+1;h++) printf("%d ",a[h]);
printf("%d ",a[1]);
int m,x;m=2;x=1;
for(h=1;h<i-1;h++)
{
if(strcmp(s[h],"+")==0) printf("+ %d ",a[m++]);
if(strcmp(s[h],"-")==0) printf("- %d ",b[x++]);
}
printf("= %d\n",n);
}
}
//? + ? - ? - ? - ? - ? - ? = 5
//? + ? + ? + ? + ? + ? + ? + ? - ? = 5