公共汽車,寫一個程式,告訴司機怎麼走能接到最多的乘客。
阿新 • • 發佈:2019-01-22
【問題描述】
一個城市的道路成了像棋盤那樣的網狀,南北向的路有n條,並由西向東從1標記到n,東西向的路有m條,並從南向北從1標記到m,每一個交叉點代表一個路口,有的路口有正在等車的乘客。一輛公共汽車將從(1,1)點駛到(n,m)點,車只能向東或者向北開.
寫一個程式,告訴司機怎麼走能接到最多的乘客。
【資料範圍限制】
100%的資料:1 <= n <= 103, 1 <= m <= 103, 1 <= k <= 103;
每個路口的乘客數量不超過1000000。
程式碼:
#region 公共汽車接最多人 public void GetBusMax() { int[,] road = null; int[,] MAX = null; int rows = 0; int conlums = 0; StreamReader sr = File.OpenText("bus.in"); StreamWriter sw = File.CreateText("bus.out"); string[] firstLine = sr.ReadLine().Split(" ".ToCharArray()); rows = int.Parse(firstLine[0]); conlums = int.Parse(firstLine[1]); int k = int.Parse(firstLine[2]); road = new int[rows + 1, conlums + 1]; MAX = new int[rows + 1, conlums + 1]; string strLine = null; int n = 0; int m = 0; while ((strLine = sr.ReadLine()) != null) { string[] str = strLine.Split(" ".ToCharArray()); n = int.Parse(str[0]); m = int.Parse(str[1]); k = int.Parse(str[2]); road[n, m] = k; } MAX[1, 1] = road[1, 1]; for (int i = 1; i < rows + 1; i++) { for (int j = 1; j < conlums + 1; j++) { if (i > 1 && j > 1) { if (MAX[i - 1, j] > MAX[i, j - 1]) { MAX[i, j] = MAX[i - 1, j] + road[i, j]; } else { MAX[i, j] = MAX[i, j - 1] + road[i, j]; } } else if (i > 1) { MAX[i, j] = MAX[i - 1, j] + road[i, j]; } else if (j > 1) { MAX[i, j] = MAX[i, j - 1] + road[i, j]; } else { MAX[1, 1] = road[1, 1]; } } } sw.WriteLine(MAX[rows, conlums]); sr.Close(); sw.Close(); } #endregion