这是我目前使用的方案,有什么更优的方案欢迎大家分享
使用StreamReader和StreamWriter进行输入和输出+自己解析字符串,例如P1253
public class P1253
{public static void Main(){using (StreamReader sr = new StreamReader(Console.OpenStandardInput())){using (StreamWriter sw = new StreamWriter(Console.OpenStandardOutput())){sw.AutoFlush = false; // 禁用自动刷新以提高性能int n = ReadInt(sr);int m = ReadInt(sr);var nums = new int[n];for (int i = 0; i < n; i++){nums[i] = ReadInt(sr);}SegmentTreeSetAndAdd segmentTree = new SegmentTreeSetAndAdd(n);segmentTree.Build(nums);for (int i = 0; i < m; i++){int op = ReadInt(sr);if (op == 1){segmentTree.SetRangeValue(ReadInt(sr), ReadInt(sr), ReadInt(sr));}else if (op == 2){segmentTree.AddRangeValue(ReadInt(sr), ReadInt(sr), ReadInt(sr));}else{var max = segmentTree.QueryMax(ReadInt(sr), ReadInt(sr));sw.WriteLine(max);}}sw.Flush(); // 最后手动刷新缓冲区}} }public static int ReadInt(StreamReader reader){int ans = 0;int read = reader.Read();bool sign = false;while (read > '9' || read < '0'){if (read == '-')sign = true;read = reader.Read();}while (read <= '9' && read >= '0'){ans = ans * 10 + read - '0';read = reader.Read();}if (sign)ans = -ans;return ans;}}
这是老的使用Console.ReadLine+Split的实现
public static void Main(){var headInput = Console.ReadLine().Trim();var headSpit = headInput.Split(' ');int n = int.Parse(headSpit[0]);int m = int.Parse(headSpit[1]);var arrayInput = Console.ReadLine().Trim();var arraySpit = arrayInput.Split(' ');var nums = new int[n];for (int i = 0; i < arraySpit.Length; i++){nums[i] = int.Parse(arraySpit[i]);}SegmentTreeSetAndAdd segmentTree = new SegmentTreeSetAndAdd(n);segmentTree.Build(nums);for (int i = 0; i < m; i++){var methodInput = Console.ReadLine().Trim();var methodSpit = methodInput.Split(' ');int op = int.Parse(methodSpit[0]);if (op == 1){segmentTree.SetRangeValue(int.Parse(methodSpit[1]), int.Parse(methodSpit[2]), int.Parse(methodSpit[3]));}else if (op == 2){segmentTree.AddRangeValue(int.Parse(methodSpit[1]), int.Parse(methodSpit[2]), int.Parse(methodSpit[3]));}else{var max = segmentTree.QueryMax(int.Parse(methodSpit[1]), int.Parse(methodSpit[2]));Console.WriteLine(max);}}}
效率对比
Console.ReadLine+Split
StreamReader+StreamWriter