sicily 1093

其实这道题是很简单的题目,给4个区间,计算添加多少重量可以让运费最低,我的思路大概就是得到输入所在的区间,判断现在需要多少运费和增加到下一个区间所需要的运费的大小。我的程序逻辑判断上面并没有问题,但是一提交到sicily就WA,找了很久都没找到答案,后来询问了大牛牛,才知道原来问题出现在while( cin )这个语句上,废话不多说,下面是修改过后AC的代码:

//注意输入流的判断问题!!!

#include <iostream>
#include <queue>

using namespace std;

struct fit
{
	int weight;
	int rate;
};

int main()
{
	int number = 1;
	int w, r;
	while ( cin >> w )
	{
		cin >> r;
		fit standar[4];
		standar[0].weight = w;
		standar[0].rate = r;
		for ( int i = 1; i < 3; i++ )
		{
			cin >> standar[i].weight >> standar[i].rate;
		}
		cin >> standar[3].rate;
		standar[3].weight = 1001;

		int input;
		queue<int> inputs;
		while ( cin >> input && input != 0 )
		{
			inputs.push( input );
		}

		cout << "Set number " << number << ":" << endl;
		while ( !inputs.empty() )
		{
			input = inputs.front();
			inputs.pop();
			int oprice, nprice;
			int index;

			//得到输入所在的区间
			int i = 0;
			for ( i = 0; i < 4; i++ )
			{
				if ( input <= standar[i].weight )
				{
					index = i;
					break;
				}
			}
			oprice = input * standar[index].rate;

			//得到从index开始到最后的支出最少的价格
			int tempPos = index; 
			int tempPrice = oprice;
			for ( int j = index + 1; j < 4; j++ )
			{
				nprice = standar[j].rate * ( standar[j-1].weight + 1 );
				if ( tempPrice > nprice )
				{
					tempPrice = nprice;
					tempPos = j;
				}
			}

			if ( tempPos != index )
			{
				cout << "Weight (" << input << ") has best price $" << tempPrice << " (add " << standar[tempPos-1].weight + 1 - input << " pounds)" << endl;
			}
			else
			{
				cout << "Weight (" << input << ") has best price $" << oprice << " (add 0 pounds)" << endl;
			}
		}
		
		number++;
		cout << endl;
	}
	return 0;
}

下面说一下为什么while( cin >> XXX )能过那道题,而while( cin )就不能过:

在C++里面,cin是一个istream>>是输入流的符号(相当于一个函数),实际上是istream >> ( istream &cin, Object &object),>> 会返回一个istream ,while(cin)是上次读入返回的输入流,不会是NULL,所以还是进入了while循环,如果你在main函数第一行加上输入重定向:freopen("in.txt","r",stdin); 然后把输入放到in.txt里面,就会多输出一个“Set Number... ”,而while( cin >> XXX )读到文件结尾,会返回NULL,从而退出while循环,不会多输出那一行set number...。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值