80分,21~25TLE,求助
查看原帖
80分,21~25TLE,求助
602932
NumberTrart楼主2022/10/20 20:10

记忆化搜索,以类似链表的形式存储二叉树,各位大佬看看怎么优化能拿100分

#include<iostream>
#include<map>
#include<algorithm>
using namespace std;
struct node
{
    int id,lid=-1,rid=-1,num;
    void in(node* p)
    {
        id=this-p-2;
    }
} tree[1000005],nullnode;
bool operator ==(node x,node y)
{
    return x.id==y.id;
}
//记忆化DFS
map<int,map<int,bool>> same;
bool operator ^(node x,node y)
{
    if(x.id==y.id) return true;
    if(x==nullnode||y==nullnode) return false;
    if(same.count(x.id)&&same[x.id].count(y.id))
        return same[x.id][y.id];
    return same[x.id][y.id]=(x.num==y.num)&&(tree[x.lid+2]^tree[y.rid+2])&&(tree[x.rid+2]^tree[y.lid+2]);
}
map<int,int> dfs_memory;
int dfs(node x)
{
    if(x==nullnode) return 0;
    if(dfs_memory.count(x.id)) return dfs_memory[x.id];
    return dfs_memory[x.id]=1+dfs(tree[x.lid+2])+dfs(tree[x.rid+2]);
}
int n;
int maxx;
int main()
{
    cin>>n;
    for(int i=-1;i<=n;i++)
        tree[i+2].in(tree);
    nullnode=tree[1];
    for(int i=1;i<=n;i++)
        scanf("%d",&tree[i+2].num);
    for(int i=1;i<=n;i++)
        scanf("%d%d",&tree[i+2].lid,&tree[i+2].rid);
    for(int i=1;i<=n;i++)
        if(tree[tree[i+2].lid+2]^tree[tree[i+2].rid+2])
            maxx=max(maxx,dfs(tree[i+2]));
    cout<<maxx;
    return 0;
}

顺便分享一下,

map<type1,map<type2,type3>>

是我发明的二位map组

2022/10/20 20:10
加载中...