#include<iostream>
#include<cstdio>
#include<map>
#include<cmath>
using namespace std;
int n;
map<int,int>stock;//键代表木材的长度,值代表该长度木材的数量
int main(){
int i;
int tm1,tm2;
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d %d",&tm1,&tm2);
if(tm1==1){
//添加木材
if(stock.count(tm2)){
cout<<"Already Exist"<<endl;
}
else{
stock[tm2]++;
}
}
else{
if(stock.empty()){//仓库为空
cout<<"Empty"<<endl;
}
else if(stock.count(tm2)){//仓库中有对应长度的木材
stock[tm2]--;
if(stock[tm2]==0){
stock.erase(tm2);//将最后一根取走后应该去除记录
}
cout<<tm2<<endl;
}
else{
//遍历寻找长度最接近的木材
int minn=1000000005;
int tmlen;
for(map<int,int>::iterator it=stock.begin();it!=stock.end();it++){
//由于map是按键升序排列,所以此处可以使用<号
if(abs(it->first-tm2)<minn){
minn=abs(it->first-tm2);
tmlen=it->first;
}
if(abs(it->first-tm2)==minn&&it->first<tmlen){
minn=abs(it->first-tm2);
tmlen=it->first;
}
}
stock[tmlen]--;
if(stock[tmlen]==0){
stock.erase(tmlen);
}
cout<<tmlen<<endl;
}
}
}
return 0;
}
当我把取木材第二个分支代码即
else if(stock.count(tm2)){//仓库中有对应长度的木材
stock[tm2]--;
if(stock[tm2]==0){
stock.erase(tm2);//将最后一根取走后应该去除记录
}
cout<<tm2<<endl;
}
变换成
else if(stock[tm2]){//仓库中有对应长度的木材
stock[tm2]--;
if(stock[tm2]==0){
stock.erase(tm2);//将最后一根取走后应该去除记录
}
cout<<tm2<<endl;
}
会有鬼畜情况发生,具体体现为使用案例测试而输出却为 3 3 3 3。查了下百度,也不是很懂为什么会出现如此差异,因此特发此贴求助各位大大,多谢各位来看此贴,谢谢