没加启发式合并所以跑的好慢
这题还是有点 ex 的,考场调了我 1.5h。
写的是指针链表,虽然我也不知道为什么写指针。
回到正题,我们可以考虑把相同的分为一块,对于每个块维护以下这些值:
struct node{
int t,h,h1;//t是当前块头,h是总长度,h1是当前块长度
node *l,*r;//l是前一个块的指针,r是后一个块的指针
queue<pair<int,int> >q;//维护当前这个块组成它的块每一块的块头
node(){l = NULL,r = NULL,h = h1 = 0;}//构造函数
};然后暴力遍历块,求答即可。
比如如下数据:001111011
带上原数组的位置 123456789
一次操作后:01111
带上原数组的位置 24569
你会发现后四个一的位置不连续了,也就是说其实是由两块组成的,即 4 - 6 与 9 - 9。
这里有人就会将他们看成两块算,每次求前面一块是不是和当前块的组成数字,即 01 不同,这样做固然可以,但我们不考虑这样,我们合并两块。
p->l->h += p->r->h;//长度加起来
--cnt;//合并后块数-1
if(p->r->h > 0){
//这里其实应该启发式合并的,但因为链表本来跑的就快所以无所谓了。
p->l->q.push(make_pair(p->r->t,p->r->h1));
while(!p->r->q.empty()){
p->l->q.push(p->r->q.front());
p->r->q.pop();
}
};//后面是合并块的组成信息其实很简单对不对
最后是求答,先放求答函数:
void work(node *p){
if(p == NULL) return;
printf("%d ",p->t);
p->h--;
p->h1--;
if(p->h != 0){
if(p->h1 == 0){//当前块的小段无了,换下一段
if(!(p->q.empty())){
p->t = p->q.front().first;
p->h1 = p->q.front().second;
p->q.pop();
}
} else p->t++;
}
work(p->r);
}很容易理解,每次取块头,走完一小段走下一小段。
最后是激动人心的复杂度计算了,很容易发现最多有 次合并。(这里假设我们用了启发式合并),合并上复杂度为 。
又很容易发现最坏情况下遍历块是 的,
求答单次是 最多有 次求答所以是 。
最后复杂度为 。
其实理论上这个代码可以跑的很快但是我没加启发式合并所以憨了
最后上考场代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
int t,h,h1;
node *l,*r;
queue<pair<int,int> >q;
node(){l = NULL,r = NULL,h = h1 = 0;}
};
node *head,*wei;//头,尾指针(wei=尾·滑稽)
const int N = 200005;
int read(){
int x = 0,f = 1,ch = getchar();
for(;ch < '0' || ch > '9';ch = getchar()) if(ch == '-') f = -1;
for(;ch >= '0' && ch <= '9';ch = getchar()) x = x * 10 + ch - '0';
return x * f;
}
int n,a[N],cnt;
void work(node *p){
if(p == NULL) return;
printf("%d ",p->t);
p->h--;
p->h1--;
if(p->h != 0){
if(p->h1 == 0){
if(!(p->q.empty())){
p->t = p->q.front().first;
p->h1 = p->q.front().second;
p->q.pop();
}
} else p->t++;
}
work(p->r);
}
void update(node *p){
if(p == NULL) return;
//大家不要学我链表写的那么保守一堆判错,其实没必要,
if(p->h == 0){
--cnt;
if(p->l == NULL){
if(p->r != NULL){
p->r->l = NULL;
head = p->r;
delete p;//记得回收内存
update(p->r);
} else return;
}
else if(p->r == NULL){
if(p->l != NULL){
p->l->r = NULL;
wei = p->l;
delete p;//记得回收内存
return;
} else return;
} else {
p->l->h += p->r->h;
--cnt;
if(p->r->h > 0){
p->l->q.push(make_pair(p->r->t,p->r->h1));
while(!p->r->q.empty()){
p->l->q.push(p->r->q.front());
p->r->q.pop();
}
};
if(p->r->r == NULL){
p->l->r = NULL;
wei = p->l;
} else{
p->l->r = p->r->r;
p->r->r->l = p->l;
delete p->r;//记得回收内存
}
delete p;//记得回收内存
update(p->l);
}
} else update(p->r);
}
void init(node* p){//一个没有什么用的初始化函数
p->h1 = p->h;
if(p != wei) init(p->r);
}
int main(){
n = read();
for(int i = 1;i <= n;i++) a[i] = read();
//以下为预处理初始块
head = new node;
wei = head;
head->t = head->h = 1;
node *p;
++cnt;
for(int i = 2;i <= n;i++){
if(a[i] == a[i - 1]) wei->h += 1;
else {
p = new node;
p->l = wei;
wei->r = p;
p->t = i;
p->h = 1;
wei = p;
++cnt;
}
}
init(head);
//以下为四行的核心代码(滑稽
while(cnt){//直到没有块
work(head);//求答放前
printf("\n");
update(head);//合并在后
}
return 0;
}