水題必須的,果斷用struct排序再計算,第一次循環條件搞錯WA了一次。。。
[cpp]
#include<cstdio>
#include<algorithm>
#define MAXN 10000
using namespace std;
struct Room{
int j, f;
double value;
};
Room r[MAXN];
bool cmp(Room a, Room b)
{
return a.value > b.value;
}
int main()
{
int m, n;
while (scanf("%d%d", &m, &n) && m != -1 && n != -1)
{
for (int i = 0; i < n; i++)
{
scanf("%d%d", &r[i].j, &r[i].f);
r[i].value = (double) r[i].j / (double) r[i].f;
}
sort(r, r + n, cmp); //排序
double sum = 0;
for (int i = 0; i < n; i++)
if (m >= r[i].f)
sum += r[i].j, m -= r[i].f; //循環加進能全部拿到的東西
else
{
sum += (double) m * r[i].value; //最後一個房間只能拿一部分
break; //拿完跳出循環
}
printf("%.3f\n", sum);
}
return 0;
}
#include<cstdio>
#include<algorithm>
#define MAXN 10000
using namespace std;
struct Room{
int j, f;
double value;
};
Room r[MAXN];
bool cmp(Room a, Room b)
{
return a.value > b.value;
}
int main()
{
int m, n;
while (scanf("%d%d", &m, &n) && m != -1 && n != -1)
{
for (int i = 0; i < n; i++)
{
scanf("%d%d", &r[i].j, &r[i].f);
r[i].value = (double) r[i].j / (double) r[i].f;
}
sort(r, r + n, cmp); //排序
double sum = 0;
for (int i = 0; i < n; i++)
if (m >= r[i].f)
sum += r[i].j, m -= r[i].f; //循環加進能全部拿到的東西
else
{
sum += (double) m * r[i].value; //最後一個房間只能拿一部分
break; //拿完跳出循環
}
printf("%.3f\n", sum);
}
return 0;
}
慢慢地追隨E.star大神的腳步了。。。