遊戲添加推薦人系統,有一批推薦人 數字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()); }