当前位置: 首页 > news >正文

P5043 [BJOI2015]树的同构(树哈希模版)

*原题链接*

树哈希模版题

树哈希是解决树同构问题的利器,可以有效降低时间复杂度,简化操作。不过如果哈希方法不合适的话,很容易被卡。我写的是oiwiki上推荐的哈希方法。在此放上链接——树哈希

对于这道题,数据范围极小,可以暴力对每棵树每个点为根都进行一遍哈希,如果稍大的话,可以换根dp来优化,最后将多重集的哈希值算出来。如果会树哈希的话,这道题的代码也很好写。

时间复杂度O(mn),非常高效。

#include<cstdio>
#include<chrono>
#include<map>
#include<vector>
#include<iostream>
using namespace std;
#define ull unsigned long long
const int N=110;
const ull mask=chrono::steady_clock::now().time_since_epoch().count();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*10+ch-'0',ch=getchar();return x*f;
}int m,n;ull sub[N],root[N];
vector<int> edge[N];
map<ull,int> mp;ull shift(ull x){x^=mask;//亲测不异或mask也可以过x^=(x<<13);x^=(x>>7);x^=(x<<17);x^=mask;return x;
}void dpsub(int x){sub[x]=1;for(auto v:edge[x]){dpsub(v);sub[x]+=shift(sub[v]);}
}void dproot(int x){//换根dpfor(auto v:edge[x]){root[v]=sub[v]+shift(root[x]-shift(sub[v]));dproot(v);}
}int main(){m=read();for(int i=1;i<=m;i++){n=read();int rt;for(int j=1;j<=n;j++){int x=read();if(!x) rt=j;edge[x].push_back(j);}dpsub(rt);root[rt]=sub[rt];dproot(rt);ull hash=1;for(int j=1;j<=n;j++) hash+=shift(root[j]);//计算多重集的哈希值if(!mp.count(hash)) mp[hash]=i;cout<<mp[hash]<<endl;for(int j=1;j<=n;j++) edge[j].clear();//别忘了清空}return 0;
}


http://www.mrgr.cn/news/25962.html

相关文章:

  • 【鸿蒙开发从0到1 day10】
  • 美创获评CNVD年度原创漏洞发现贡献单位!
  • springboot-创建连接池
  • 派遣函数 - 跟踪IRP的利器/RPTrace
  • 新书速览|JavaScript前端开发与实例教程(微课视频版)(第2版)
  • Kafka 实战演练:创建、配置与测试 Kafka全面教程
  • 最好用的 Redis 可视化工具,不愧是官方出品,功能确实强大(带私活源码)
  • element select + tree
  • 跨境电商,一人搞定?自从有了这个AI工具,赚遍全球市场
  • Linux云计算 |【第三阶段】PROJECT1-DAY2
  • “xi” 和 “dbscan” 在OPTICS聚类中是什么意思
  • 提升LLM能力表现的四种AI代理策略
  • JavaScript控制语句和函数的使用
  • 2024年道路运输安全员考试题库及答案
  • SRT3D: A Sparse Region-Based 3D Object Tracking Approach for the Real World
  • C++速通LeetCode第6题-环形链表
  • 无人机建模详解!!!
  • 【机器学习】结构学习的基本概念以及基于约束的结构学习和基于评分的结构学习
  • EE trade:沙金是黄金吗
  • [网络]http/https的简单认识