集合映射为ID

 1 typedef set<int> Set;
 2 map<Set,int> IDcache;
 3 vector<Set> Setcache;
 4 
 5 int ID(Set x)
 6 {
 7       if(IDcache.count(x))  return IDcache[x];
 8       Setcache.push_back(x);
 9       return IDcache[x] = Setcache.size()-1;
10 }

map的作用是把集合映射成ID,第一个类型是经过“标准化”(如字符串经过了sort,里面的字符都是从小到大按字典序排序过)的,需要存放在vector里的东西,第二个则是int类型的ID;vector其实是一个列表,通过简单的ID下标访问可以轻松获取元素的原貌。

假设标准化函数为repr(),(字符串标准化示例实现见本段文字下方)则对于任意需要存放的元素x,IDcache[repr(x)]为map快速索引到的ID(ID即为他在vector中的下标),而Setcache[IDcache[repr(x)]]则是元素x的原型。

1 string repr(const string& s)
2 {
3     string ans = s;
4     for(int i = 0;i < ans.length();i ++)
5        ans[i] = tolower(ans[i]);
6     sort(ans.begin(),ans.end());
7     return ans;
8 }
原文地址:https://www.cnblogs.com/Asurudo/p/9628332.html