求代码速度优化(算法等,现TLE
  • 板块学术版
  • 楼主xu_zhihao
  • 当前回复3
  • 已保存回复3
  • 发布时间2024/7/3 17:36
  • 上次更新2024/7/3 20:44:09
查看原帖
求代码速度优化(算法等,现TLE
1063855
xu_zhihao楼主2024/7/3 17:36
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int n,m;
struct node{
	int x;
	int y;
};
node a[N];
inline bool cmp(node l,node r){
	return l.y<r.y;
}
inline int read(){
    int x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        ch=getchar();
    }
    while(ch>='0' && ch<='9'){
        x=x*10+ch-'0';
		ch=getchar();
    }
	return x;
}
inline void write(int x){
	if(x>9){
        write(x/10);
    }
    putchar(x%10+'0');
    return;
}
inline int check(int x,int y){
	int l=1,r=n,best=-1;
	while(l<=r){
		int mid=(l+r)/2;
		if(a[mid].y>=x){
			r=mid-1;
			best=mid;
		}
		else{
			l=mid+1;
		}
	}
	if(best==-1){
		return best;
	}
	//cout<<x<<" "<<y<<endl;
	for(int i=best;i<=n;i++){
		//cout<<a[i].x<<" "<<a[i].y<<"  ";
		if(a[i].x>=x && a[i].y<=y){
			//cout<<endl;
			return i;
		}
	}
	return -1;
}
int main(){
	n=read(),m=read();
	//cout<<n<<" "<<m<<endl;
	for(int i=1;i<=n;i++){
		a[i].x=read(),a[i].y=read();
		//cout<<a[i].x<<" "<<a[i].y<<endl;
	}
	sort(a,a+n,cmp);
	while(m--){
		int l=read(),r=read();
		int w=check(l,r);
		if(w==-1){
			write(0);
			putchar('\n');
			continue;
		}
		int k=w;
		int cnt=1;
		for(int i=w;i<=n;i++){
			//cout<<a[i].x<<" "<<a[i].y<<" "<<cnt<<endl;
			if(a[k].y>r){
				cnt--;
				break;
			}
			if(a[i].x>=a[k].y){
				cnt++;
				k=i;
			}
		}
		write(cnt);
		putchar('\n');
	}
}
2024/7/3 17:36
加载中...