您的位置:首页 > 其它

BZOJ1098: [POI2007]办公楼biu

2017-08-19 10:40 363 查看

BZOJ1098: [POI2007]办公楼biu

链表·乱搞

题解:

这真的是一道令人耳目一新的题!

首先很容易看出答案就是补图的连通块个数,但是补图有O(n2)条边啊QWQ

在不建立补图的情况下,对于一个点,遍历其原图中的边,哪些点没访问到,它们就是补图中能走到的点。很遗憾,这样还是O(n2)

我们发现“遍历所有点看哪个没访问到”这个步骤做了很多无用功,因为很多点可能已经确定了它们所属的连通块,这时候就应该将它们删去,免得重复检查。

链表就派上用场了。在bfs的过程中,每通过补图接触到一个点,立即将它删除。“遍历所有点看哪个没访问到”的时候只遍历链表中剩下的点。

删除点的时间复杂度高?(最坏每删一个可能O(n))没关系,加边的时候先排个序,让前向星的遍历顺序从小到大,就可以扫一次链表删除所有需要删的点了。

时间复杂度降到了O(n+m),因为每个点会访问它的所有边,并且只会被删除一次。

Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define D(x) cout<<#x<<" = "<<x<<"  "
#define E cout<<endl
using namespace std;
const int N = 100005;
const int M = 2000000;

int n,m,ans,sz,num
,vis
;

struct Edge{
int from,to,next;
} e[M*2], tp[M*2];
int head
, ec, tpcnt;
void addedge(int a,int b){
ec++; e[ec].to=b; e[ec].next=head[a]; head[a]=ec;
}
bool cmp(const Edge &a, const Edge &b){
return a.from > b.from || (a.from==b.from && a.to>b.to);
}

struct Node{
int l,r;
} g
;
void init(){
for(int i=0;i<=n+1;i++){
g[i].l=i-1; g[i].r=i+1;
}
g[0].l=0; g[n+1].r=n+1; sz=n;
}
void del(int p){
sz--; //D(p); E;
g[g[p].l].r=g[p].r;
g[g[p].r].l=g[p].l;
}

void bfs(int s){
queue<int> q; q.push(s); del(s);
while(!q.empty()){
int x=q.front(); q.pop();
//      D(x); E;
for(int i=head[x];i;i=e[i].next){
vis[e[i].to]=x;
}
for(int p=g[0].r;p!=n+1;p=g[p].r){
if(vis[p]!=x){
q.push(p);
del(p);
}
}
}
}

int main(){
scanf("%d%d",&n,&m);
int a,b;
for(int i=1;i<=m;i++){
scanf("%d%d",&a,&b);
tp[++tpcnt].from=a; tp[tpcnt].to=b;
tp[++tpcnt].from=b; tp[tpcnt].to=a;
}
sort(tp+1,tp+1+m*2,cmp);
for(int i=1;i<=m*2;i++){
addedge(tp[i].from,tp[i].to);
}

init(); int last=n;
while(g[0].r!=n+1){
bfs(g[0].r);
ans++; num[ans]=last-sz; last=sz;
//      D(ans); E;
}
sort(num+1,num+1+ans);
printf("%d\n",ans);
for(int i=1;i<=ans;i++) printf("%d ",num[i]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: