超时20分的代码实用vector
存放结构体,然后写了一个cmp
结构体排序的函数,所有的结点都存在vector
数组中。
满分代码改为用优先队列存储结构体,直接在结构体内排序。
两种方法对于的查询逻辑都是一样的。
自认为这个代码的优点是:
1.使用优先队列存储结构体
2.对于删除操作,并没有选择查找需要删除的元素,我是建立了一个map,存储每一个元素是否在队列内(是否被删除),这样节省了很多时间,最后查询的时候直接判断该元素是否在队列内即可。
测试样例:
2 3
1 3
2 2
3 1
8
3 100 1 1
1 0 4 3
1 0 5 1
3 10 2 2
3 10 1 1
2 0 1
3 2 1 1
3 1 1 1
#include <bits/stdc++.h>
using namespace std;
struct node
{
int type,id,val;
node(int _t,int _i,int _v) : type(_t),id(_i),val(_v) {}
friend bool operator <(const node& a,const node& b)
{
if(a.val!=b.val) return a.val<b.val;
else if(a.val==a.val && a.type!=b.type) return a.type>b.type;
else if(a.val==a.val && a.type==b.type) return a.id>b.id;
}
};
priority_queue<node> q;
vector<int> res[51];
map<pair<int,int>,int> mp;
map<int,int> cnt;
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int m,n;
cin>>m>>n;
for(int i=0;i<n;i++)
{
int id,val;
cin>>id>>val;
for(int j=0;j<m;j++)
{
q.push(node(j,id,val));
pair<int,int> p=make_pair(j,id);
mp[p]=1;
}
}
int opnum,op,t,c,s;
cin>>opnum;
while(opnum--)
{
cin>>op;
if(op==1)
{
cin>>t>>c>>s;
q.push(node(t,c,s));
pair<int,int> p=make_pair(t,c);
mp[p]=1;
}
else if(op==2)
{
cin>>t>>c;
pair<int,int> p=make_pair(t,c);
mp[p]=0;
}
else if(op==3)
{
int k,ki;
for(int i=0;i<51;i++) cnt[i]=0;
for(int i=0;i<51;i++) res[i].clear();
cin>>k;
for(int i=0;i<m;i++)
{
cin>>ki; cnt[i]=ki;
}
int num=0;
priority_queue<node> tmp;
while(!q.empty() && k>0)
{
if(num==m) break;
node x=q.top();
int type=x.type;
int id=x.id;
pair<int,int> p=make_pair(type,id);
if(mp[p] && cnt[type])
{
cnt[type]--;
if(cnt[type]==0) num++;
k--;
res[type].push_back(id);
}
q.pop();
tmp.push(x);
}
while(!tmp.empty())
{
node x=tmp.top();
q.push(x);
tmp.pop();
}
for(int i=0;i<m;i++)
{
if(res[i].size()==0)
{
cout<<-1<<endl; continue;
}
for(auto v:res[i]) cout<<v<<" ";
cout<<endl;
}
}
}
return 0;
}