/*
ID:boatswa2
PROG:preface
LANG:C++
*/
#include<stdio.h>
#include<iostream>
using namespace std;
int n;
int C=0,D=0,M=0,I=0,L=0,X=0,V=0;
char b[100];
void find(int temp)
{
int bl=0;
if(temp/1000)
{
int a=temp/1000;
temp-=a*1000;
for(int i=1;i<=a;i++)
b[bl++]='M';
}
if(temp/100)
{
int a=temp/100;
temp-=a*100;
if(a<=3)
{
for(int i=1;i<=a;i++)
b[bl++]='C';
}
else if(a==4)
{
b[bl++]='C';
b[bl++]='D';
}
else if(a>=5&&a<9)
{
b[bl++]='D';
for(int i=6;i<=a;i++)
b[bl++]='C';
}
else if(a==9)
{
b[bl++]='C';
b[bl++]='M';
}
}
if(temp/10)
{
int a=temp/10;
temp-=a*10;
if(a<=3)
{
for(int i=1;i<=a;i++)
b[bl++]='X';
}
else if(a==4)
{
b[bl++]='X';
b[bl++]='L';
}
else if(a>=5&&a<9)
{
b[bl++]='L';
for(int i=6;i<=a;i++)
b[bl++]='X';
}
else if(a==9)
{
b[bl++]='X';
b[bl++]='C';
}
}
if(temp)
{
if(temp<=3)
{
for(int i=1;i<=temp;i++)
b[bl++]='I';
}
else if(temp==4)
{
b[bl++]='I';
b[bl++]='V';
}
else if(temp>=5&&temp<9)
{
b[bl++]='V';
for(int i=6;i<=temp;i++)
b[bl++]='I';
}
else if(temp==9)
{
b[bl++]='I';
b[bl++]='X';
}
}
for(int i=0;i<bl;i++)
if(b[i]=='C')
C++;
else if(b[i]=='D')
D++;
else if(b[i]=='I')
I++;
else if(b[i]=='V')
V++;
else if(b[i]=='X')
X++;
else if(b[i]=='M')
M++;
else if(b[i]=='L')
L++;
}
int main()
{
freopen("preface.in","r",stdin);
freopen("preface.out","w",stdout);
cin>>n;
for(int i=1;i<=n;i++)
find(i);
if(I!=0)
cout<<"I"<<" "<<I<<endl;
if(V!=0)
cout<<"V"<<" "<<V<<endl;
if(X!=0)
cout<<"X"<<" "<<X<<endl;
if(L!=0)
cout<<"L"<<" "<<L<<endl;
if(C!=0)
cout<<"C"<<" "<<C<<endl;
if(D!=0)
cout<<"D"<<" "<<D<<endl;
if(M!=0)
cout<<"M"<<" "<<M<<endl;
}
如果你觉得上述的代码比较长、比较臃肿,那么看一下,一位大牛写的代码吧,很短、很快~(XEing)
/*
ID:boatswa2
PROG:preface
LANG:C++
*/
#include<stdio.h>
#include<assert.h>
int main()
{
FILE *fin,*fout;
int i,v,x,l,c,d,m,j,k,n;
fin=fopen("preface.in","r");
fout=fopen("preface.out","w");
assert(fin!=NULL && fout!=NULL);
fscanf(fin,"%d",&n);
i=0;
v=0;
x=0;
l=0;
c=0;
d=0;
m=0;
for (j=1;j<=n;j++)
{
k=j;
while (k>0)
{
if (k>=1000) {k-=1000;m++;}
if (k>=900 && k<1000) {k-=900;c++;m++;}
if (k>=500 && k<900) {k-=500;d++;}
if (k>=400 && k<500) {k-=400;c++;d++;}
if (k>=100 && k<400) {k-=100;c++;}
if (k>=90 && k<100) {k-=90;x++;c++;}
if (k>=50 && k<90) {k-=50;l++;}
if (k>=40 && k<50) {k-=40;x++;l++;}
if (k>=10 && k<40) {k-=10;x++;}
if (k>=9 && k<10) {k-=9;i++;x++;}
if (k>=5 && k<9) {k-=5;v++;}
if (k>=4 && k<5) {k-=4;i++;v++;}
if (k>=1 && k<4) {k-=1;i++;}
}
}
if (i!=0) fprintf(fout,"I %d\n",i);
if (v!=0) fprintf(fout,"V %d\n",v);
if (x!=0) fprintf(fout,"X %d\n",x);
if (l!=0) fprintf(fout,"L %d\n",l);
if (c!=0) fprintf(fout,"C %d\n",c);
if (d!=0) fprintf(fout,"D %d\n",d);
if (m!=0) fprintf(fout,"M %d\n",m);
}
其实还是抓住一点,搞清楚题意叙述的规则~