题目大概:
输入m磅粮食,n个房间,每个房间粮食兑换金钱的比例不同,输出能兑换的最多金钱。
思路:
分别用不同数组或向量存储数据,计算出每个房间的金钱兑换比例,排序一下,从最高的开始兑换。
感想:
这个题刚开始是c c++语言混合使用的,提交竟然发现编译错误,虽然两种语言混合使用方便许多,但以后还要尽可能用一种语言。
代码:
#include
<iostream>
#include <iomanip>
using namespace std ;
int main ()
{ double m ,n ;
while (cin >>m >>n )
{ if (m ==- 1 &&n ==- 1 ) break ;
d ouble a [ 1000 ],b [ 1000 ];
double c [ 1000 ],sum = 0 ;
for ( int i = 0 ;i <n ;i ++)
{cin >>a [i ]>>b [i ];c [i ]=a [i ]/b [i ];
}
for ( int i = 0 ;i <n -1 ;i ++)
{ for ( int t =i +1 ;t <n ;t ++)
{ if (c [i ]<c [t ]) { swap (c [i ],c [t ]);
swap (a [i ],a [t ]);
swap (b [i ],b [t ]);
}
}
}
for ( int i = 0 ;i <n ;i ++)
{ if (m >=b [i ]) {sum =sum +a [i ];m =m -b [i ]; }
else {sum =sum +(m /b [i ])*a [i ];m = 0 ; }
if (m == 0 ) break ;
}
cout << setiosflags (ios ::fixed );
cout << setprecision ( 3 )<<sum <<endl ;
}
return 0 ;
}
#include <iomanip>
using namespace std ;
int main ()
{ double m ,n ;
while (cin >>m >>n )
{ if (m ==- 1 &&n ==- 1 ) break ;
d ouble a [ 1000 ],b [ 1000 ];
double c [ 1000 ],sum = 0 ;
for ( int i = 0 ;i <n ;i ++)
{cin >>a [i ]>>b [i ];c [i ]=a [i ]/b [i ];
}
for ( int i = 0 ;i <n -1 ;i ++)
{ for ( int t =i +1 ;t <n ;t ++)
{ if (c [i ]<c [t ]) { swap (c [i ],c [t ]);
swap (a [i ],a [t ]);
swap (b [i ],b [t ]);
}
}
}
for ( int i = 0 ;i <n ;i ++)
{ if (m >=b [i ]) {sum =sum +a [i ];m =m -b [i ]; }
else {sum =sum +(m /b [i ])*a [i ];m = 0 ; }
if (m == 0 ) break ;
}
cout << setiosflags (ios ::fixed );
cout << setprecision ( 3 )<<sum <<endl ;
}
return 0 ;
}