- 论坛徽章:
- 0
|
回复 #1 hll 的帖子
应该按照重的先放把。
linux下代码如下
// g++ -o ball ball.cpp
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
class Ball;
class Balance {
int left, right;
int left_num;
int right_num;
public:
Balance() {
left = right = 0;
left_num = right_num = 0;
}
bool IsLeftWeight() {
if(left > right)
return true;
else
return false;
}
void Reset()
{
left = right = 0;
}
bool IsLeftFull()
{
return left_num >= 4;
}
int AddWeightOnLeft(bool Left, int weight) {
if(Left) {
left_num++;
left += weight;
cout << "Left now: "<< left << endl;
}
else {
right_num++;
right += weight;
cout << "Right now: "<< right << endl;
}
}
};
class Ball {
int weight;
public:
Ball() { weight = rand()%10000; }
friend ostream& operator<< (ostream &os, const class Ball &ball)
{ return os << ball.weight; }
friend bool operator > (Ball & ball1, Ball & ball2)
{
return ball1.weight > ball2.weight;
}
/*friend bool operator > (Ball * const ball1, Ball * const ball2)
{
return ball1->weight > ball2->weight;
}*/
Ball(int Weight) : weight(Weight) {}
int GetWeight() { return weight; }
};
int main()
{
srand(time(NULL));
Balance balance;
Ball balls[10];
Ball *ptrballs[10];
for(int i = 0; i < 10; i++)
{
cout << balls << '\t';
ptrballs = &balls;
}
cout << endl;
Ball *tmp;
for(int i = 0; i < 10; i++)
{
for(int j = i+1; j < 10; j++)
{
if(*(ptrballs) > *(ptrballs[j]))
{
tmp = ptrballs;
ptrballs = ptrballs[j];
ptrballs[j] = tmp;
}
}
}
for(int i = 0; i < 10; i++)
{
cout << *ptrballs << '\t';
}
cout << endl;
Ball *start;
for(int i = 9; i >= 0; i--)
{
start = ptrballs;
if(balance.IsLeftWeight() && !balance.IsLeftFull())
{
balance.AddWeightOnLeft(false, start->GetWeight());
}
else
balance.AddWeightOnLeft(true, start->GetWeight());
}
return 0;
}
[ 本帖最后由 bugboy_bugboy 于 2008-3-6 16:32 编辑 ] |
|