做题有个习惯,就是没通过一道题之后都会找下答案,对比一下我的代码还有没有可以在优化的地方,使他更简便
链接:http://acm.hdu.edu.cn/showproblem.php?pid=2016
我的代码是:
#include<stdio.h>
int main()
{
int n, a[100], t, i, b;
while(scanf("%d", &n) != EOF)
{
if(n<100)
{
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
t = a[0];
这里可以这样用:
for(i=0;i
for(j=i+1;j
if(a[i]>a[j])
{
t=a[j];
min=j;
}
for(i=1;i<n;i++)
{
if(a[i]<t)
{
t = a[i];
}
}
for(i=0;i<n;i++)
{
if(t == a[i])
{
b = i;
}
}
t = a[0];
a[0] = a[b];
a[b] = t;
b = 0;
for(i = 0;i<n;i++,b++)
{
if(b == n-1)
{
printf("%d\n", a[i]);
}
else printf("%d ", a[i]);
}
}
}
}
链接:http://acm.hdu.edu.cn/showproblem.php?pid=2021
思路:分别将工资以50和5来计算
#include<stdio.h>
int main()
{
int n, h, f, t, fm, tm, o;
int x, y, z, total, s;
int a[100];
int i;
while(scanf("%d", &n) != EOF)
{
if(n>0 && n<100)
{
total = 0;
for(i=0;i<n;i++)
{
h = f = t = fm = tm = o = 0;
scanf("%d", &a[i]);
x = a[i]/50;
if(x!=0 && x/2 == 0)
{
h = x/2; //100的张数
if(x == 1)
{
f++; //50的张数
}
}
else if(x/2 != 0)
{
h = (x-1)/2; //100的张数
f++; //50的张数
}
y = (a[i] - x*50)/5;
if(y != 0 &&y/2 == 0)
{
t = y/2; //10的张数
if(y==1)
{
fm++; //5的张数
}
}
else if(y/2 != 0)
{
t = (y-1)/2; //10的张数
fm++; //5的张数
}
if(y<10)
z = (a[i]-x*50-y*5);
if(z>0)
{
tm = z/2; //2的张数
o = a[i]-x*50-y*5-tm*2; //1的张数
}
s = h+f+t+fm+tm+o;
total += s;
}
printf("%d\n", total);
}
}
}
更简单的算法:
灵活的运用%余数
核心步骤为:
amount+=salary/100;//计算所需100块的数量
salary%=100;//十位和个位数
amount += salary/50 + salary%50/10; // 计算10和50的张数
salary %= 10 ; //个位数
amount += salary/5+salary%5/2+salary%5%2/1;//1.2.5的个数