C++中流输入输出比printf和scanf速度慢

今天在刷题时总是提示Time Limit EXceeded,题目是:热血大格斗 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
	int main()
{
		int number;
		multimap vip;
		typedef multimap mp;
		vip.insert(mp::value_type(100000000,1));
		cin >> number;
		int id, value;
		cin >> id >> value;
		vip.insert(mp::value_type(value, id));
		cout << id << " " << 1 << endl;
		for (int i = 1;i > id >> value;
			vip.insert(mp::value_type(value, id));
			mp::iterator p = vip.find(value);
			mp::iterator temp = p;
			mp::iterator temp1 = p;
			mp::iterator temp2 = p;
			mp::iterator temp3 = p;
			if (p == vip.begin())
				cout << id << " " << (++p)->second << endl;
			else if (p == vip.end())
				cout << id << " " << (--p)->second << endl;
			else if ((abs(value - (--temp1)->first) < abs(value - (++temp)->first))|| (abs(value - (--temp2)->first) == abs(value - (++temp3)->first)))
				cout << id << " " <<(--p)->second << endl;
			else
				cout << id << " " <<(++p)->second << endl;
		}
	    
	//	getchar();
		return 0;
}

然后提示超时了
 

百度了一下这道题的其他解法,算法思路都差不多。然后我把cin改成了scanf,cout改成了printf
时间就由1000ms降到了142ms,符合要求。


猜测是cin和cout有个缓冲区的存储操作耗时较长,所以对时间卡得紧的场合可以改用scanf和printf.

你可能感兴趣的:(C++中流输入输出比printf和scanf速度慢)