题目:http://acm.tju.edu.cn/toj/showp3243.html
题意:有n个村庄和n条路,第i条路连接村庄i和i%n+1,这样形成一个环,并且路是无向的。开始时路都是连通的。有两种操作,①指定某一条路,连通的变成不连通,或者不连通的变成连通。②询问你第i个村庄和第j个村庄是不是连通的额。
分析:这个题可以简单的理解为,1~n的序列里面,查询i~(j-1)里面的数字是否存在(即这段线路里面的某些路是不连通的),若存在则i与j不连通,否则连通。
树状数组代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e5+6;
int tree[maxn],visit[maxn],lowbit[maxn];
void GetLowbit()
{
for(int i=1;i<maxn;i++)
lowbit[i]=i&-i;
}
void update(int x,int v)
{
for(int i=x;i<maxn && i;i+=lowbit[i])
tree[i]+=v;
}
int query(int x)
{
int ret(0);
for(int i=x;i>0;i-=lowbit[i])
ret+=tree[i];
return ret;
}
int main()
{
GetLowbit();
int n,q,ncase,i,j,x,tp;
scanf("%d",&ncase);
while(ncase--)
{
scanf("%d%d",&n,&q);
memset(tree,0,sizeof(tree[0])*(n+2));
memset(visit,0,sizeof(visit[0])*(n+2));
while(q--)
{
scanf("%d",&tp);
if(tp==1)
{
scanf("%d%d",&i,&j);
if(i>j)
swap(i,j);
if(i==j || !(query(n)-query(j-1)+query(i-1))|| !(query(j-1)-query(i-1)))
puts("1");
else
puts("0");
}
else
{
scanf("%d",&x);
if(visit[x])
{
visit[x]=0;
update(x,-1);
}
else
{
visit[x]=1;
update(x,1);
}
}
}
}
return 0;
}
线段树代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e5+6;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
struct segtree
{
int tree[maxn<<2];
void build(int l,int r,int rt)
{
tree[rt]=0;
if(l==r)
return ;
int m=(l+r)>>1;
build(lson);
build(rson);
}
void update(int pos,int l,int r,int rt)
{
if(l==r)
{
if(tree[rt])
tree[rt]=0;
else
tree[rt]=1;
return ;
}
int m=(l+r)>>1;
if(pos<=m)
update(pos,lson);
else
update(pos,rson);
tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
int query(int L,int R,int l,int r,int rt)
{
if(L<=l && r<=R)
return tree[rt];
int m=(l+r)>>1,ret(0);
if(L<=m)
ret+=query(L,R,lson);
if(R>m)
ret+=query(L,R,rson);
return ret;
}
}T;
int main()
{
int ncase,i,j,x,tp,n,q;
scanf("%d",&ncase);
while(ncase--)
{
scanf("%d%d",&n,&q);
T.build(1,n,1);
while(q--)
{
scanf("%d",&tp);
if(tp==1)
{
scanf("%d%d",&i,&j);
if(i>j)
swap(i,j);
if(i==j || T.query(i,j-1,1,n,1)==0 || T.query(1,n,1,n,1)-T.query(i,j-1,1,n,1)==0)
puts("1");
else
puts("0");
}
else
{
scanf("%d",&x);
T.update(x,1,n,1);
}
}
}
return 0;
}