原题链接
https://www.acwing.com/problem/content/description/1638/
下面的代码只要数组再开大一个,开到10003就超时。
原来map数组用的哈希映射,必超时,改成数组,还是超时,最后把tool的哈希映射存到aa,bb变量中,还是超时,最后最后把数组缩到10002,终于过了
请问各位大佬还有哪里可以改进,实在是想不出来了
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<cstring>
using namespace std;
const int N=10002;//10003就超时啊
int l[N],r[N];
int m,n;
int pre[N],in[N],map[N];
int a,b;
int aa,bb;
unordered_map<int,int> tool;
bool leaf[N];
int build(int pl,int pr,int il,int ir)
{
int root= pre[pl];
int k=root;
if(k>il) l[root]=build(pl+1,pl+k-il,il,k-1);
if(k<ir) r[root]=build(pl+k-il+1,pr,k+1,ir);
return root;
}
int common(int root)
{
// cout<<aa<<' '<<bb<<endl;
if(root==aa||root==bb||root==0)
return root;
int ll=common(l[root]),rr=common(r[root]);
if((ll==aa&&rr==bb)||(ll==bb&&rr==aa))
return root;
if(ll!=0) return ll;
else return rr;
}
int main(){
cin>>m>>n;
for(int i=1;i<=n;i++)
{
cin>>pre[i];
in[i]=pre[i];
}
sort(in+1,in+n+1);
for(int i=1;i<=n;i++)
{
map[i]=in[i];
tool[in[i]]=i;
}
for(int i=1;i<=n;i++)
pre[i]=tool[pre[i]];
int root=build(1,n,1,n);
for(int i=0;i<m;i++)
{
cin>>a>>b;
if(tool.count(a)&&tool.count(b))
{ aa=tool[a],bb=tool[b];
int res=common(root);
if(res!=aa&&res!=bb)
printf("LCA of %d and %d is %d.\n",a,b,map[res]);
else if(res==aa)
printf("%d is an ancestor of %d.\n",map[res],b);
else if(res==bb)
printf("%d is an ancestor of %d.\n",map[res],a);
}
if(!tool.count(a)&&!tool.count(b))
printf("ERROR: %d and %d are not found.\n",a,b);
else if(!tool.count(a))
printf("ERROR: %d is not found.\n",a);
else if(!tool.count(b))
printf("ERROR: %d is not found.\n",b);
}
return 0;
}