1. 程式人生 > >hdu6430樹上啟發式合併

hdu6430樹上啟發式合併

題解:因為這題我們只查詢不做修改,那麼在樹上做啟發式合併就會很方便並且時間複雜度做到查詢萬每課子樹最後的時間複雜度是nlogn就可以查詢每個結點為根的子樹資訊,每次標記一下0表示資訊不保留,1表示資訊保留,找最大公約數,我們用一個標記陣列把每個結點的因子都加一,因為因子個數最多100個所以時間複雜度是100nlogn,

#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#include<cstdio>
#include<cmath>
#include<set>
#include<map>
#include<complex>
#include<cstdlib>
#include<ctime>
#include<stack>
#include<bitset>
using namespace std;
#define mes(a,b) memset(a,b,sizeof(a))
#define rep(i,a,b) for(int i = a; i <= b; i++)
#define dec(i,a,b) for(int i = a; i >= b; i--)
#define pb push_back
#define mk make_pair
#define fi first
#define se second
#define ls rt<<1
#define rs rt<<1|1
#define lson ls,L,mid
#define rson rs,mid+1,R
#define lowbit(x) x&(-x)
typedef double db;
typedef long long int ll;
typedef pair<int,int> pii;
typedef complex<double> cd;
typedef unsigned long long ull;
const ll inf = 0x3f3f3f3f;
const int mx = 1e5+5;
const int mod = 1e9+7;
const int x_move[] = {1,-1,0,0,1,1,-1,-1};
const int y_move[] = {0,0,1,-1,1,-1,1,-1};
int n,m;
vector<int>d[mx];
vector<int>g[mx];
int vis[mx];
int sz[mx];
int son[mx];
int st[mx];
int ed[mx];
int val[mx];
int id[mx];
int pos;
int ans[mx];
void init(){
	for(int i = 1; i < mx; i++)
		for(int j = i; j < mx; j+=i)
			d[j].pb(i);
	for(int i = 1; i < mx; i++)
		reverse(d[i].begin(),d[i].end());
}
void dfs(int u){
	sz[u]  = 1;
	son[u] = 0;
	pos++;
	st[id[pos] = u] = pos;
	for(auto v: g[u]){
		dfs(v);
		sz[u] += sz[v];
		if(sz[son[u]]<sz[v])
			son[u] = v;
	}
	ed[u] = pos;
}
int query(int val){
	for(auto v: d[val])	{
		if(vis[v])
			return v;
	}
	return -1;
}
void update(int val,int p){
	for(auto v: d[val])
		vis[v] += p;
}
void DFS(int u,bool keep = false){
	for(auto v: g[u]){
		if(son[u]!=v)
			DFS(v);
	}
	if(son[u])
	DFS(son[u],1);
	for(auto v: g[u])if(son[u]!=v){
		for(int i = st[v]; i <= ed[v]; i++)
			ans[u] = max(ans[u],query(val[id[i]]));
		for(int i = st[v]; i <= ed[v]; i++)
			update(val[id[i]],1);
	}
	ans[u] = max(ans[u],query(val[u]));
	update(val[u],1);
	if(keep==false)
		for(int i = st[u]; i <= ed[u]; i++)
			update(val[id[i]],-1);
}
int main(){
	//freopen("test.in","r",stdin);
	//freopen("test.out","w",stdout);
	int t,q,ca = 1;
	init();
	while(scanf("%d",&n)!=EOF)	{
		for(int i = 1; i <= n; i++)
			g[i].clear(),ans[i] = -1;
		for(int i = 2; i <= n; i++){
			int u;
			scanf("%d",&u);
			g[u].pb(i);
		}
		for(int i = 1; i <= n; i++)
			scanf("%d",&val[i]);
		pos = 0;
		dfs(1);
		DFS(1,1);
		for(int i = 1; i <= n; i++)
			printf("%d\n",ans[i]);
	}
	return 0;
}