pat甲级1143 Lowest Common Ancestor (30分)
文章目录
1.超时算法(测试点4超时)
复杂度:
O
(
m
n
log
n
)
O(mn\log n)
O(mnlogn),最坏情况
(
O
(
m
n
2
)
)
(O(mn^2))
(O(mn2))(每个结点出度不超过1且m,n取最大时超时)
代码如下:
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
vector<int> pre;
unordered_map<int,int> pos;
void LCA(int preRoot,int preL,int preR,int a,int b)
{
int i=preRoot;
while(i<=preR) if(pre[++i]>=pre[preRoot]) break;//i是右子树根位置
if(preRoot==pos[a]) printf("%d is an ancestor of %d.\n",a,b);
else if(preRoot==pos[b]) printf("%d is an ancestor of %d.\n",b,a);
else if(pos[a]<i&&pos[b]<i) LCA(preRoot+1,preRoot+1,i-1,a,b);
else if(pos[a]>=i&&pos[b]>=i) LCA(i,i,preR,a,b);
else printf("LCA of %d and %d is %d.\n",a,b,pre[preRoot]);
}
int main()
{
int m,n,U,V;
cin>>m>>n;
pre.reserve(n+1);
for(int i=1;i<=n;++i)//不能从0开始,否则32行,33行条件判定语句出错
{
cin>>pre[i];
pos[pre[i]]=i;
}
for(int i=0;i<m;++i)
{
cin>>U>>V;
if(!pos[U]&&!pos[V]) printf("ERROR: %d and %d are not found.\n",U,V);
else if(!pos[U]||!pos[V]) printf("ERROR: %d is not found.\n",pos[U]?V:U);
else LCA(1,1,n,U,V);
}
return 0;
}
2.改进算法 ( O ( m n ) ) (O(mn)) (O(mn))
代码做点小手术:
void LCA(int preRoot,int preL,int preR,int a,int b)
{
int i=preRoot;
while(i<=preR) if(pre[++i]>=pre[preRoot]) break;//i是右子树根位置
if(preRoot==pos[a]) printf("%d is an ancestor of %d.\n",a,b);
else if(preRoot==pos[b]) printf("%d is an ancestor of %d.\n",b,a);
else if(pre[preRoot]在a,b之间) printf("LCA of %d and %d is %d.\n",a,b,pre[preRoot]);
else
{
LCA(preRoot+1,preRoot+1,i-1,a,b);
LCA(i,i,preR,a,b);
}
}
在基本不改变算法复杂度的情况下,可以看出,函数实际上是沿着pre元素顺序依次递归,因此没有必要寻找右子树根位置,代码可以改进如下:
柳神代码
尽管只是优化一下算法,但代码大大简化,并且从运行时间33ms来看,针对测试用例还是很快的。不过缺点就是考试时,臣妾办不到,算法优化太特例化了。更有效率的通用化解决LCA算法我想应该还有,但臣妾还在学习中…坐等大佬翻牌子:)
更新
3.Tarjan算法 ( O ( n + m ) ) (O(n+m)) (O(n+m))
膜拜一波大佬:
日沉云起