SPOJ COT2 Count on a tree II

You are given a tree with N nodes. The tree nodes are numbered from 1 to N. Each node has an integer weight.


We will ask you to perform the following operation:


u v : ask for how many different integers that represent the weight of nodes there are on the path from u to v.
Input


In the first line there are two integers N and M. (N <= 40000, M <= 100000)


In the second line there are N integers. The i-th integer denotes the weight of the i-th node.


In the next N-1 lines, each line contains two integers u v, which describes an edge (u, v).


In the next M lines, each line contains two integers u v, which means an operation asking for how many different integers that represent the weight of nodes there are on the path from u to v.


Output


For each operation, print its result.


Example


Input:
8 2
105 2 9 3 8 5 7 7
1 2
1 3
1 4
3 5
3 6
3 7
4 8
2 5
7 8
Output:
4

4

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

树上莫队+离散化+lca~

莫队真是太暴力了……

先把值离散化,然后对整棵树分块,块大小sqrt(n),询问离线,用块的顺序排序,每次暴力更新答案即可。

我的WA点:

1.lca里面写成了dep[fa[u][i]]<=dep[v]……果然板子是要多打的啊。

2.fa数组开成了17导致WA到飞起……什么原理?按理来说是算不到17的啊!

3.lca里面dep[1]=0,所以不能用for(int i=17;~i;i--) if(dep[fa[u][i]]>=dep[v]) u=fa[u][i];来去掉dep多出来的值!

(为什么注释掉的那种fa[]更新方式是WA的?求大神指点,感激不尽!)


#include
#include
#include
#include
using namespace std;

int n,m,a[40001],c[40001],pos[40001],fa[40001][18],dep[40001],fi[40001],cnt,tot,jin;
int num[40001],stk[40001],top,dfn[40001],ans[100001],ne[80001],now,tot1,w[80001],cntnum;
bool b[40001];

struct node{
	int x,y,id;
}que[100001];

int read()
{
	int x=0,f=1;char ch=getchar();
	while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}
	while(ch>='0' && ch<='9') {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return x*f;
}

void add(int u,int v)
{
	w[++cnt]=v;ne[cnt]=fi[u];fi[u]=cnt;
	w[++cnt]=u;ne[cnt]=fi[v];fi[v]=cnt;
}

void dfs(int u)
{
	dfn[u]=++cntnum;
	for(int i=1;1<=jin)
	  	{
	  		tot++;
	  		while(top!=now) pos[stk[top--]]=tot;
	  	}
	  }
	stk[++top]=u;
}

bool operator < (node u,node v)
{
	return pos[u.x]==pos[v.x] ? dfn[u.y]dep[v]) ox(u),u=fa[u][0];
	while(u!=v) ox(u),ox(v),u=fa[u][0],v=fa[v][0];
}

int main()
{
	tot1=n=read();m=read();
	for(int i=1;i<=n;i++) a[i]=c[i]=read();
	sort(c+1,c+n+1);
	tot1=unique(c+1,c+n+1)-c-1;
	for(int i=1;i<=n;i++) a[i]=lower_bound(c+1,c+tot1+1,a[i])-c;
	for(int i=1;ipos[y]) swap(x,y);
	}
	sort(que+1,que+m+1);
	int x=1,y=1;
	for(int i=1;i<=m;i++)
	{
		if(que[i].x!=x) chan(x,que[i].x),x=que[i].x;
		if(que[i].y!=y) chan(y,que[i].y),y=que[i].y;
		ans[que[i].id]=now+(num[a[lca(x,y)]]==0);
	}
	for(int i=1;i<=m;i++) printf("%d\n",ans[i]);
	return 0;
}


你可能感兴趣的:(其它OJ,莫队算法,倍增)