这题奇偶优化比一般排序要慢?
查看原帖
这题奇偶优化比一般排序要慢?
86971
TRZ_2007楼主2021/2/19 20:43

Rt,或者是我人傻常数大?

50pts:

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 9;

int a[N],n,m,cnt,sum[N],ans[N];
int len,l,r,nl,nr;

#define gc getchar
inline int read() {
	int c = gc(), t = 1, n = 0;
	while(isspace(c)) { c = gc(); }
	if(c == '-') { t = -1, c = gc(); }
	while(isdigit(c)) { n = n * 10 + c - '0', c = gc(); }
	return n * t;
}
#undef gc

struct node {
	int l,r,id,bl;
}q[N];

bool cmp1(node u,node v) {
	if(u.bl != v.bl) return u.bl < v.bl;
	else {
		if(u.bl & 1) return u.r < v.r;
		else return u.l > v.l;
	}
}

bool cmp2(node u,node v) {
	return u.bl == v.bl ? u.r < v.r : u.bl < v.bl;
}

inline void del(int p) {
	if(--sum[a[p]] == 0) --cnt; 
}

inline void add(int p) {
	if(++sum[a[p]] == 1) ++cnt;
}

int main() {
	n = read(); m = read();
	len = pow(n,0.5);
	for(int i = 1;i <= n;i++) a[i] = read();
	for(int i = 1;i <= m;i++) {
		l = read(); r = read();
		q[i].l = l; q[i].r = r; q[i].id = i; q[i].bl = (q[i].l - 1) / len + 1;
	}
	sort(q + 1,q + m + 1,cmp1);	//there
	l = 1; r = 0;
	for(int i = 1;i <= m;i++) {
		nl = q[i].l; nr = q[i].r;
		while(l < nl) del(l++);
		while(l > nl) add(--l);
		while(r > nr) del(r--);
		while(r < nr) add(++r);
		if(cnt == nr - nl + 1) ans[q[i].id] = 1;
	}
	for(int i = 1;i <= m;i++) {
		if(ans[i] == 1) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}

100pts:

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 9;

int a[N],n,m,cnt,sum[N],ans[N];
int len,l,r,nl,nr;

#define gc getchar
inline int read() {
	int c = gc(), t = 1, n = 0;
	while(isspace(c)) { c = gc(); }
	if(c == '-') { t = -1, c = gc(); }
	while(isdigit(c)) { n = n * 10 + c - '0', c = gc(); }
	return n * t;
}
#undef gc

struct node {
	int l,r,id,bl;
}q[N];

bool cmp1(node u,node v) {
	if(u.bl != v.bl) return u.bl < v.bl;
	else {
		if(u.bl & 1) return u.r < v.r;
		else return u.l > v.l;
	}
}

bool cmp2(node u,node v) {
	return u.bl == v.bl ? u.r < v.r : u.bl < v.bl;
}

inline void del(int p) {
	if(--sum[a[p]] == 0) --cnt; 
}

inline void add(int p) {
	if(++sum[a[p]] == 1) ++cnt;
}

int main() {
	n = read(); m = read();
	len = pow(n,0.5);
	for(int i = 1;i <= n;i++) a[i] = read();
	for(int i = 1;i <= m;i++) {
		l = read(); r = read();
		q[i].l = l; q[i].r = r; q[i].id = i; q[i].bl = (q[i].l - 1) / len + 1;
	}
	sort(q + 1,q + m + 1,cmp2);	//there
	l = 1; r = 0;
	for(int i = 1;i <= m;i++) {
		nl = q[i].l; nr = q[i].r;
		while(l < nl) del(l++);
		while(l > nl) add(--l);
		while(r > nr) del(r--);
		while(r < nr) add(++r);
		if(cnt == nr - nl + 1) ans[q[i].id] = 1;
	}
	for(int i = 1;i <= m;i++) {
		if(ans[i] == 1) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}

其中 cmp1 对应的是奇偶优化,cmp2 对应的是一般排序。

两份代码唯一的不同就是标注释的部分

2021/2/19 20:43
加载中...