首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

求算法解决思路

2012-04-06 
求算法ResidAttribute1Attribute2Attribute3Attribute4Attribute5Attribute6Attribute7Attribute810001白

求算法
Resid Attribute1 Attribute2 Attribute3 Attribute4 Attribute5 Attribute6 Attribute7 Attribute8
10001 白色 时尚 高端 女性 年轻 大学 广州 一年  
10002 黑色 耐用 高端 男性 中年 大学 广州 两年
10003 蓝色 时尚 低端 不限 年轻 中学 苏州 半年
10004 黑色 易耗 中端 男性 年轻 大学 东莞 一年 
....
....
....


以上为某商品的属性表。Resid表示商品ID,Attribute1、Attribute2、、、Attribute8为商品的八个属性。
现在想实现两两商品进行比较,计算其具有相同的属性个数。结果格式为(只显示有相同属性的主题组合):

Resid_1 Resid_2 similar_count
10001 10002 3
10001 10003 2
.....

[解决办法]
10001 白色 时尚 高端 女性 年轻 大学 广州 一年
10002 黑色 耐用 高端 男性 中年 大学 广州 两年
10003 蓝色 时尚 低端 不限 年轻 中学 苏州 半年
10004 黑色 易耗 中端 男性 年轻 大学 东莞 一年

我能想到个办法,不过不保证是最优~~

1、将每个属性用一个值表示,比如白色是1,黑色是2,蓝色是3,黑色是4;时尚是5,耐用是6,...,这样每条属性的记录都能得到一个唯一的字符串。这个变化需要O(n)的操作,n是记录的数量

2、将每条记录的属性字符串都hash了,然后每条记录都有一个hash值的属性了,并且这个hash值唯一。这步也需要O(n)的开销

3、然后寻找n条记录中具有相同hash的记录,就是所求了。这个可以用disjoint set结构来实现,会用到make_set, find 和 union三个操作。开销是log(n)

所以总的开销可以在O(n)时间内。

[解决办法]
for rec in select * from goods a full join goods b on a.Resid <> b.Resid loop
count := 0;
if rec.a_Attribute1 = rec.b_Attribute1 then
 count := count + 1
end if 
if rec.a_Attribute2 = rec.b_Attribute2 then
 count := count + 1
end if 
if rec.a_Attribute3 = rec.b_Attribute3 then
 count := count + 1
end if 
if rec.a_Attribute4 = rec.b_Attribute4 then
 count := count + 1
end if 
if rec.a_Attribute5 = rec.b_Attribute5 then
 count := count + 1
end if 
if rec.a_Attribute6 = rec.b_Attribute6 then
 count := count + 1
end if 
if rec.a_Attribute7 = rec.b_Attribute7 then
 count := count + 1
end if 
if rec.a_Attribute8 = rec.b_Attribute8 then
 count := count + 1
end if 
insert into t_result (Resid_1, Resid_2, similar_count) values (rec.a_resid, rec.b_resid, count);
commit;
end loop
我觉得这样可以。
让他自己和自己全连接,连接的条件是resid不相等,然后在遍历这个连接的结果集。触个字段去进行对比,相等则加1.最后将结果插入到t_result表格中。
再select * from t_result就可以得到你想要的结果。
[解决办法]
跟楼上想法差不多,利用搜索引擎倒排索引的原理。
1、先建立一个Map,key为属性,值为拥有这个属性的resid list;
2、遍历map中某个属性的list,两两组合就可以得到都拥有该属性的组合,然后统计一下即可。

热点排行