问题描述
最近我正在研究一个问题,但是我无法在时间限制内解决。问题如下:
问题:
Bob当前有N个空堆栈,编号从1到N。他进行了M次以下操作:选择2个两个数字L和R,然后向每个堆栈[L,L + 1,... R]加一个石头在这M个操作中,他想回答Q个问题:多少个堆栈中至少有H个石头?
输入格式
第一行包含N-堆栈数。
第二行包含M-操作数。
接下来的M行中的每行都由两个以空格分隔的整数L和R组成。
后跟整数Q-查询数量。
接下来的Q行中的每行都包含一个整数H。
约束: 1≤N≤1000000, 1≤M≤1000000, 1≤L≤R≤N, 1≤Q≤1000000, 1≤H≤N,
我的方法如下:
int main(){
int n,m,l,r,q,h;
cin >> n >> m;
vector<int>nums(n,0);
// processing vector based on instructions
for(int i=0; i<m; i++){
cin >> l >> r;
for(int j=l-1; j<r; j++)
nums[j]++;
}
//storing freq in map
map<int,int,greater<int>>count;
for(auto x: nums)
count[x]++;
// getting no. of queries
cin >> q;
vector<pair<int,int>>queries(q);
for(int i=0; i<q; i++){
cin >> h;//query height
queries[i] = make_pair(h,i);
}
sort(queries.begin(),queries.end(),greater<int>());
vector<int> res(q,0);
int q_index=0;
int c = 0;
for(auto&[key,val]:count){
while(k<q && key < queries[q_index].first){
res[queries[q_index].second] = c;
q_index++;
}
c+=val;
if(k == q){
break;
}
}
for(int x: res)cout << x << endl;
return 0;
}
这可以工作,但对于大型测试用例却失败。解决此类问题的方法应该是什么? TIA!
解决方法
除O(N ^ 2)循环外,主要问题可能是std::map
。
完全未经测试的代码
int main(){
int n,m,l,r,q,h;
cin >> n >> m;
vector<int>nums(n,0);
// processing vector based on instructions
for(int i=0; i<m; i++){
cin >> l >> r;
nums[l-1]++;
nums[r-1]--;
// saving O(N^2)
//for(int j=l-1; j<r; j++)
// nums[j]++;
} // O(N) down from O(N^2)
//storing freq in map --- This costs O(N K + N lg N) but the K is crushing as its allocations
//map<int,int,greater<int>>count;
//for(auto x: nums)
// count[x]++;
// add up the real height for each stack
std::partial_sum(nums.begin(),nums.end(),nums.begin()); // O(N)
std::sort(nums.begin(),nums.end()); // use radex sort instead if timelimit exceeded
// getting no. of queries
cin >> q;
//vector<pair<int,int>>queries(q);
vector<int>queries(q);
for(int i=0; i<q; i++){
cin >> h; //query height
queries[i] = h;
}
vector<int> res(q,0);
std::transform(queries.begin(),queries.end(),res.begin(),[&](int q){
auto i = std::lower_bound(nums.begin(),q); // binary search O(lg N)
return std::(i,nums.end());
} // O(N lg N)
for(int x: res)cout << x << "\r\n";//endl; // nevar use endl unless you really need it.
return 0;
}
添加一些const,constexp等以使其变得更好。
Radex排序为O(N),但启动时的K是有问题的,编写它的代码也不是简单的。
一个好问题是,您对查询进行排序然后通过使用.second以正确顺序放置的解决方案是否更好。