游戏添加推荐人系统,有一批推荐人 数字id 信息数据存在一个 文本文件中算法
文件格式以下:c#
推荐人 空格 被推荐人spa
推荐人 空格 被推荐人游戏
推荐人 空格 被推荐人string
例如:hash
玩家it
|
aio
|
btable
|
cforeach
|
d
|
…
|
f
|
Id
|
1000
|
1001
|
1002
|
1004
|
…
|
1020
|
文件格式
|
说明
|
1000 1001 1000 1002 1001 1004 1004 1020 …
|
//a推荐了b //a推荐了c //b推荐了d //d推荐了f …
|
其中 a推荐了b ,a是b一级推荐人
b推荐了d ,a是d二级推荐人
d推荐了f ,a是f三级推荐人
超过三级推荐人不进行计算
系统支付推荐人奖励
奖励方式以下:
一级推荐人直接得到 10 金币
二级推荐人额外得到 5 金币
三级推荐人额外得到 1 金币
a推荐了b a+10金币
a推荐了c a+10金币
b推荐了d b+10金币, a+5金币
d推荐了f d+10金币, b+5金币, a+1金币
问题:以1000万行数据为例,使得程序能在10秒内算出系统所要支付的总金币数。
用c#解决的代码:
static void Main(string[] args) { Console.WriteLine("开始的时间" + DateTime.Now.ToString()); string filePath = "e:\\out10000000.data"; if (File.Exists(filePath) == false) { Console.WriteLine("文件不存在,请输入文件的位置:"); filePath = Console.ReadLine().ToString(); } StreamReader sr = new StreamReader(filePath); //改进的算法,用hash存,由于其键值不惟一 Hashtable table = new Hashtable(); while (true) { string str = sr.ReadLine(); if (str == null) { break; } string[] strSplit = str.Split(' '); //第一个参数为键值,不能重复 //给的第二行不重复因此做为键值 table.Add(int.Parse(strSplit[1]), int.Parse(strSplit[0])); } sr.Close(); //统计全部的结果 int sum = 0; int temp; //遍历全部的数据 foreach (DictionaryEntry de in table) { sum += 10; //判断是否有上一层节点 if (table.Contains(de.Value)) { sum += 5; temp = (int)table[de.Value]; //判断是否有上上层节点 if (table.Contains(temp)) { sum += 1; } } } Console.WriteLine(sum); Console.WriteLine("结束的时间:" + DateTime.Now.ToString()); }