buggy_code
stringlengths
11
625k
fixed_code
stringlengths
17
625k
bug_type
stringlengths
2
4.45k
language
int64
0
8
token_count
int64
5
200k
change_count
int64
0
100
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { string[] str = Console.ReadLine().Split(' '); var a = int.Parse(str[0]); var b = int.Parse(str[1]); var ab = a / b; Console.WriteLine(ab); } }
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { string[] str = Console.ReadLine().Split(' '); var a = int.Parse(str[0]); var b = int.Parse(str[1]); float ab = 1.0f * a / b; Console.WriteLine(ab); } }
[["-", 8, 196, 0, 197, 0, 198, 39, 216, 0, 217], ["+", 0, 195, 8, 196, 0, 197, 0, 198, 39, 199], ["+", 0, 200, 0, 212, 0, 16, 31, 16, 31, 250], ["+", 0, 200, 0, 212, 0, 16, 31, 16, 17, 48]]
8
83
4
using System; using static System.Console; using System.Linq; class Program { static void Main(string[] args) { int[] a = Console.ReadLine().Split().Select(int.Parse).ToArray(); WriteLine(a[0] / a[1]); } }
using System; using static System.Console; using System.Linq; class Program { static void Main(string[] args) { int[] a = Console.ReadLine().Split().Select(int.Parse).ToArray(); WriteLine((float)a[0] / a[1]); } }
[["+", 3, 4, 0, 28, 0, 16, 31, 74, 0, 24], ["+", 3, 4, 0, 28, 0, 16, 31, 74, 39, 199], ["+", 3, 4, 0, 28, 0, 16, 31, 74, 0, 25]]
8
68
3
using System; using System.Linq; public class c { public static void Main() { int[] TX = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); double ans = TX[0] / TX[1]; Console.WriteLine(ans); } }
using System; using System.Linq; public class c { public static void Main() { double[] TX = Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); double ans = TX[0] / TX[1]; Console.WriteLine(ans); } }
[["-", 8, 196, 0, 197, 0, 198, 39, 224, 39, 199], ["+", 8, 196, 0, 197, 0, 198, 39, 224, 39, 199], ["-", 205, 213, 3, 4, 0, 28, 0, 214, 205, 199], ["+", 205, 213, 3, 4, 0, 28, 0, 214, 205, 199]]
8
70
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AtcoderTemplateForCSharp { public class Program { public static void Main(string[] args) { var input = Console.ReadLine().Split(' ').Select(int.Parse); var t = input.ElementAt(0); var x = input.ElementAt(1); System.Console.WriteLine(t / x); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AtcoderTemplateForCSharp { public class Program { public static void Main(string[] args) { var input = Console.ReadLine().Split(' ').Select(int.Parse); var t = input.ElementAt(0); var x = input.ElementAt(1); Console.WriteLine(t / (double)x); } } }
[["-", 0, 1, 0, 213, 63, 214, 205, 214, 205, 22], ["-", 0, 1, 0, 213, 63, 214, 205, 214, 0, 131], ["+", 3, 4, 0, 28, 0, 16, 12, 74, 0, 24], ["+", 3, 4, 0, 28, 0, 16, 12, 74, 39, 199], ["+", 3, 4, 0, 28, 0, 16, 12, 74, 0, 25]]
8
102
5
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; namespace AtCoder { class Program { static void Main(string[] args) { var ir = new Resolver(new ConsoleReader()); Console.WriteLine(ir.Resolve()); } } public class Resolver { IInputReader InputReader { get; } public List<string> Messages { get; set; } = new List<string>(); int[] input; public void ParseLines() { input = InputReader.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray(); } public string Resolve() { return (input[0] / input[1]).ToString(); } public Resolver(IInputReader inputReader) { InputReader = inputReader; ParseLines(); } } public interface IInputReader { string ReadLine(); } class ConsoleReader : IInputReader { string IInputReader.ReadLine() { return Console.ReadLine(); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; namespace AtCoder { class Program { static void Main(string[] args) { var ir = new Resolver(new ConsoleReader()); Console.WriteLine(ir.Resolve()); } } public class Resolver { IInputReader InputReader { get; } public List<string> Messages { get; set; } = new List<string>(); float[] input; public void ParseLines() { input = InputReader.ReadLine().Split(' ').Select(x => float.Parse(x)).ToArray(); } public string Resolve() { return (input[0] / input[1]).ToString(); } public Resolver(IInputReader inputReader) { InputReader = inputReader; ParseLines(); } } public interface IInputReader { string ReadLine(); } class ConsoleReader : IInputReader { string IInputReader.ReadLine() { return Console.ReadLine(); } } }
[["-", 8, 201, 0, 124, 0, 198, 39, 224, 39, 199], ["+", 8, 201, 0, 124, 0, 198, 39, 224, 39, 199], ["-", 0, 28, 0, 218, 8, 213, 63, 214, 205, 199], ["+", 0, 28, 0, 218, 8, 213, 63, 214, 205, 199]]
8
215
4
using System; using System.Linq; namespace ABC117_A { class Program { static void Main(string[] args) { var TX = Console.ReadLine().Split().Select(int.Parse).ToArray(); Console.WriteLine(TX[0] / TX[1]); } } }
using System; using System.Linq; namespace ABC117_A { class Program { static void Main(string[] args) { var TX = Console.ReadLine().Split().Select(double.Parse).ToArray(); Console.WriteLine(TX[0] / TX[1]); } } }
[["-", 205, 213, 3, 4, 0, 28, 0, 214, 205, 199], ["+", 205, 213, 3, 4, 0, 28, 0, 214, 205, 199]]
8
66
2
using System; using System.Diagnostics; using System.IO; using System.Text; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; class Program { const string Yes = "Yes"; const string No = "No"; const long Mod = 1000000007; static void Main(string[] args) { #if DEBUG MyDebugger.Test(process, "../TextFile1.txt"); #else object ret = process(new StreamReader(Console.OpenStandardInput())); Console.WriteLine(ret); #endif } static object process(TextReader input) { var n = int.Parse(input.ReadLine()); var ary = ToIntArray(input.ReadLine(), n); var sum = ary.Sum(); for (int i = 0; i < n; i++) { var x = sum - ary[i]; if (ary[i] >= sum) return No; } return Yes; } static int[] ToIntArray(string strs, int n) { var ret = new int[n]; var spl = strs.Split(' '); for (int i = 0; i < n; i++) ret[i] = int.Parse(spl[i]); return ret; } }
using System; using System.Diagnostics; using System.IO; using System.Text; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; class Program { const string Yes = "Yes"; const string No = "No"; const long Mod = 1000000007; static void Main(string[] args) { #if DEBUG MyDebugger.Test(process, "../TextFile1.txt"); #else object ret = process(new StreamReader(Console.OpenStandardInput())); Console.WriteLine(ret); #endif } static object process(TextReader input) { var n = int.Parse(input.ReadLine()); var ary = ToIntArray(input.ReadLine(), n); var sum = ary.Sum(); for (int i = 0; i < n; i++) { var x = sum - ary[i]; if (ary[i] >= x) return No; } return Yes; } static int[] ToIntArray(string strs, int n) { var ret = new int[n]; var spl = strs.Split(' '); for (int i = 0; i < n; i++) ret[i] = int.Parse(spl[i]); return ret; } }
[["-", 0, 7, 8, 196, 0, 57, 15, 16, 12, 22], ["+", 0, 7, 8, 196, 0, 57, 15, 16, 12, 22]]
8
269
2
// Undone using System; using System.Linq; using System.Collections.Generic; using System.Collections; public class Program { public static void Main() { int[] line = ReadIntArray(); if (line.Max() * 2 < line.Sum()) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } private static string ReadStr() { return Console.ReadLine(); } private static int ReadInt() { return int.Parse(Console.ReadLine()); } private static double ReadDouble() { return double.Parse(Console.ReadLine()); } private static long ReadLong() { return long.Parse(Console.ReadLine()); } private static char ReadChar() { return Console.ReadLine()[0]; } private static string[] ReadStringArray() { return Console.ReadLine().Split(' '); } private static int[] ReadIntArray() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); } private static double[] ReadDoubleArray() { return Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); } private static long[] ReadLongArray() { return Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); } private static char[] ReadCharArray() { return Console.ReadLine().ToArray(); } private static string[] ReadCharStringArray() { return Console.ReadLine().ToCharArray().Select(c => c.ToString()).ToArray(); } }
// Undone using System; using System.Linq; using System.Collections.Generic; using System.Collections; public class Program { public static void Main() { ReadLine(); int[] line = ReadIntArray(); if (line.Max() * 2 < line.Sum()) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } private static string ReadLine() { return Console.ReadLine(); } private static int ReadInt() { return int.Parse(Console.ReadLine()); } private static double ReadDouble() { return double.Parse(Console.ReadLine()); } private static long ReadLong() { return long.Parse(Console.ReadLine()); } private static char ReadChar() { return Console.ReadLine()[0]; } private static string[] ReadStringArray() { return Console.ReadLine().Split(' '); } private static int[] ReadIntArray() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); } private static double[] ReadDoubleArray() { return Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); } private static long[] ReadLongArray() { return Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); } private static char[] ReadCharArray() { return Console.ReadLine().ToArray(); } private static string[] ReadCharStringArray() { return Console.ReadLine().ToCharArray().Select(c => c.ToString()).ToArray(); } }
[["+", 0, 195, 8, 196, 0, 1, 0, 213, 63, 22], ["+", 8, 196, 0, 1, 0, 213, 3, 4, 0, 24], ["+", 8, 196, 0, 1, 0, 213, 3, 4, 0, 25], ["+", 8, 201, 0, 195, 8, 196, 0, 1, 0, 35], ["-", 0, 208, 0, 235, 8, 201, 0, 195, 141, 22], ["+", 0, 208, 0, 235, 8, 201, 0, 195, 141, 22]]
8
361
6
using System; using System.Collections.Generic; namespace CompetitiveProgramming { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string[] list = Console.ReadLine().Split(); int sum = 0; int max = 0; for (var i = 0; i < n; i++) { int useNum = int.Parse(list[i]); sum += useNum; if (useNum > max) { max = useNum; } } if (max > sum - max) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } } }
using System; using System.Collections.Generic; namespace CompetitiveProgramming { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string[] list = Console.ReadLine().Split(); int sum = 0; int max = 0; for (var i = 0; i < n; i++) { int useNum = int.Parse(list[i]); sum += useNum; if (useNum > max) { max = useNum; } } if (max < sum - max) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } } }
[["-", 0, 195, 8, 196, 0, 57, 15, 16, 17, 47], ["+", 0, 195, 8, 196, 0, 57, 15, 16, 17, 18]]
8
144
2
using System; namespace AtCoder0205 { class Program { static void Main(string[] args) { int N = int.Parse(Console.ReadLine()); string[] s = Console.ReadLine().Split(' '); int total = 0; int max = 0; int x = 0; for (int i = 0; i < N; i++) { x = int.Parse(s[i]); total += x; if (max < x) max = x; } if (total > x * 2) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } }
using System; namespace AtCoder0205 { class Program { static void Main(string[] args) { int N = int.Parse(Console.ReadLine()); string[] s = Console.ReadLine().Split(' '); int total = 0; int max = 0; int x = 0; for (int i = 0; i < N; i++) { x = int.Parse(s[i]); total += x; if (max < x) max = x; } if (total > max * 2) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } }
[["-", 8, 196, 0, 57, 15, 16, 12, 16, 31, 22], ["+", 8, 196, 0, 57, 15, 16, 12, 16, 31, 22]]
8
138
2
using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Text; namespace AtCoder { public class Program { static int[] getKeys() { var Keys = Console.ReadLine().Split(' '); int N = Keys.Length; int[] Ns = new int[N]; for (int i = 0; i < N; i++) { Ns[i] = int.Parse(Keys[i]); } return Ns; } static int[] getKeys(char delimiter) { var Keys = Console.ReadLine().Split(delimiter); int N = Keys.Length; int[] Ns = new int[N]; for (int i = 0; i < N; i++) { Ns[i] = int.Parse(Keys[i]); } return Ns; } public static void Show<T>(T[,] map) { int H = map.GetLength(0); int W = map.GetLength(1); Console.WriteLine("-------------------------"); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { Console.Write(map[i, j] + " "); } Console.WriteLine(); } Console.WriteLine("-------------------------"); } public static void Show<T>(T[,] map, string delimiter) { int H = map.GetLength(0); int W = map.GetLength(1); Console.WriteLine("-------------------------"); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { Console.Write(map[i, j] + delimiter); } Console.WriteLine(); } Console.WriteLine("-------------------------"); } public static void Show<T>(IEnumerable<T> ts) { foreach (var item in ts) { Console.Write(item + " "); } Console.WriteLine(); } public static void Show<T>(IEnumerable<T> ts, string delimiter) { foreach (var item in ts) { Console.Write(item + delimiter); } Console.WriteLine(); } static void Main() { var Key = getKeys(); int L = Key.Max(); if (L < Key.Sum() - L) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } } }
using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Text; namespace AtCoder { public class Program { static int[] getKeys() { var Keys = Console.ReadLine().Split(' '); int N = Keys.Length; int[] Ns = new int[N]; for (int i = 0; i < N; i++) { Ns[i] = int.Parse(Keys[i]); } return Ns; } static int[] getKeys(char delimiter) { var Keys = Console.ReadLine().Split(delimiter); int N = Keys.Length; int[] Ns = new int[N]; for (int i = 0; i < N; i++) { Ns[i] = int.Parse(Keys[i]); } return Ns; } public static void Show<T>(T[,] map) { int H = map.GetLength(0); int W = map.GetLength(1); Console.WriteLine("-------------------------"); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { Console.Write(map[i, j] + " "); } Console.WriteLine(); } Console.WriteLine("-------------------------"); } public static void Show<T>(T[,] map, string delimiter) { int H = map.GetLength(0); int W = map.GetLength(1); Console.WriteLine("-------------------------"); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { Console.Write(map[i, j] + delimiter); } Console.WriteLine(); } Console.WriteLine("-------------------------"); } public static void Show<T>(IEnumerable<T> ts) { foreach (var item in ts) { Console.Write(item + " "); } Console.WriteLine(); } public static void Show<T>(IEnumerable<T> ts, string delimiter) { foreach (var item in ts) { Console.Write(item + delimiter); } Console.WriteLine(); } static void Main() { Console.ReadLine(); var Key = getKeys(); int L = Key.Max(); if (L < Key.Sum() - L) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } } }
[["+", 8, 196, 0, 1, 0, 213, 63, 214, 205, 22], ["+", 8, 196, 0, 1, 0, 213, 63, 214, 0, 131], ["+", 8, 196, 0, 1, 0, 213, 63, 214, 141, 22], ["+", 8, 196, 0, 1, 0, 213, 3, 4, 0, 24], ["+", 8, 196, 0, 1, 0, 213, 3, 4, 0, 25], ["+", 8, 201, 0, 195, 8, 196, 0, 1, 0, 35]]
8
548
6
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; namespace AtCoder { class Program { static void Main(string[] args) { var ir = new Resolver(new ConsoleReader()); Console.WriteLine(ir.Resolve()); } } public class Resolver { IInputReader InputReader { get; } public List<string> Messages { get; set; } = new List<string>(); int n; int[] input; public void ParseLines() { n = int.Parse(InputReader.ReadLine()); input = InputReader.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray(); } public string Resolve() { var max = input.ToList().OrderBy(x => -1).ToList(); if (max[0] < max.GetRange(1, n - 1).Sum()) return "Yes"; return "No"; } public Resolver(IInputReader inputReader) { InputReader = inputReader; ParseLines(); } } public interface IInputReader { string ReadLine(); } class ConsoleReader : IInputReader { string IInputReader.ReadLine() { return Console.ReadLine(); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; namespace AtCoder { class Program { static void Main(string[] args) { var ir = new Resolver(new ConsoleReader()); Console.WriteLine(ir.Resolve()); } } public class Resolver { IInputReader InputReader { get; } public List<string> Messages { get; set; } = new List<string>(); int n; int[] input; public void ParseLines() { n = int.Parse(InputReader.ReadLine()); input = InputReader.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray(); } public string Resolve() { var max = input.ToList().OrderBy(x => -x).ToList(); if (max[0] < max.GetRange(1, n - 1).Sum()) return "Yes"; return "No"; } public Resolver(IInputReader inputReader) { InputReader = inputReader; ParseLines(); } } public interface IInputReader { string ReadLine(); } class ConsoleReader : IInputReader { string IInputReader.ReadLine() { return Console.ReadLine(); } } }
[["-", 3, 4, 0, 28, 0, 218, 8, 241, 0, 203], ["+", 3, 4, 0, 28, 0, 218, 8, 241, 0, 22]]
8
267
2
using System; using System.Collections.Generic; using System.Linq; namespace Q2 { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var l = Console.ReadLine() .Split(' ') .Select(s => int.Parse(s)) .OrderByDescending(i => i); var longest = l.First(); var sumOfOther = l.Skip(1).Sum(); var answer = longest < sumOfOther ? "YES" : "NO"; Console.WriteLine(answer); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Q2 { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var l = Console.ReadLine() .Split(' ') .Select(s => int.Parse(s)) .OrderByDescending(i => i); var longest = l.First(); var sumOfOther = l.Skip(1).Sum(); var answer = longest < sumOfOther ? "Yes" : "No"; Console.WriteLine(answer); } } }
[["-", 0, 200, 0, 212, 0, 41, 64, 5, 0, 222], ["+", 0, 200, 0, 212, 0, 41, 64, 5, 0, 222], ["-", 0, 200, 0, 212, 0, 41, 75, 5, 0, 222], ["+", 0, 200, 0, 212, 0, 41, 75, 5, 0, 222]]
8
128
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Numerics; namespace PaizaSkillCheck { public class Program { public static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string[] line = Console.ReadLine().Split(' '); int sum = 0; int max = 0; for (int i = 0; i < line.Length; i++) { int v = int.Parse(line[i]); sum += v; max = Math.Max(max, v); } sum -= max; Console.WriteLine((sum > max) ? "yes" : "no"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Numerics; namespace PaizaSkillCheck { public class Program { public static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string[] line = Console.ReadLine().Split(' '); int sum = 0; int max = 0; for (int i = 0; i < line.Length; i++) { int v = int.Parse(line[i]); sum += v; max = Math.Max(max, v); } sum -= max; Console.WriteLine((sum > max) ? "Yes" : "No"); Console.ReadLine(); } } }
[["-", 3, 4, 0, 28, 0, 41, 64, 5, 0, 222], ["+", 3, 4, 0, 28, 0, 41, 64, 5, 0, 222], ["-", 3, 4, 0, 28, 0, 41, 75, 5, 0, 222], ["+", 3, 4, 0, 28, 0, 41, 75, 5, 0, 222]]
8
175
4
using System; using System.Collections.Generic; using System.Linq; namespace MyProgram { class AtCoder { static void Main() { var A = Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse); long N = A[0]; long M = A[1]; var X = Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse); if (N >= M) { Console.WriteLine("0"); return; } Array.Sort(X); var dist = new long[M - 1]; for (var i = 1; i < M; i++) { dist[i - 1] = X[i] - X[i - 1]; } Array.Sort(dist); long sum = 0; for (var i = 0; i < M - N - 1; i++) { sum += dist[i]; } System.Console.WriteLine(sum); } } }
using System; using System.Collections.Generic; using System.Linq; namespace MyProgram { class AtCoder { static void Main() { var A = Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse); long N = A[0]; long M = A[1]; var X = Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse); if (N >= M) { Console.WriteLine("0"); return; } Array.Sort(X); var dist = new long[M - 1]; for (var i = 1; i < M; i++) { dist[i - 1] = X[i] - X[i - 1]; } Array.Sort(dist); long sum = 0; for (var i = 0; i < M - N; i++) { sum += dist[i]; } System.Console.WriteLine(sum); } } }
[["-", 8, 196, 0, 7, 15, 16, 12, 16, 17, 33], ["-", 8, 196, 0, 7, 15, 16, 12, 16, 12, 203]]
8
216
2
using System; using System.Linq; namespace Streamline { class Program { static void Main(string[] args) { var nm = Console.ReadLine().Split().Select(int.Parse); var input = Console.ReadLine().Split().Select(int.Parse).OrderBy(i => i).ToArray(); int fullLenght = input[input.Length - 1] - input[0]; var diffrences = new int[input.Length - 1]; for (int i = 0, j = 1; i < input.Length - 2; i++, j++) { diffrences[i] = input[j] - input[i]; } Console.WriteLine( fullLenght - diffrences.OrderBy(d => -d).Take(nm.ElementAt(0) - 1).Sum()); } } }
using System; using System.Linq; namespace Streamline { class Program { static void Main(string[] args) { var nm = Console.ReadLine().Split().Select(int.Parse); var input = Console.ReadLine().Split().Select(int.Parse).OrderBy(i => i).ToArray(); int fullLenght = input[input.Length - 1] - input[0]; var diffrences = new int[input.Length - 1]; for (int i = 0, j = 1; i < input.Length - 1; i++, j++) { diffrences[i] = input[j] - input[i]; } Console.WriteLine( fullLenght - diffrences.OrderBy(d => -d).Take(nm.ElementAt(0) - 1).Sum()); } } }
[["-", 8, 196, 0, 7, 15, 16, 12, 16, 12, 203], ["+", 8, 196, 0, 7, 15, 16, 12, 16, 12, 203]]
8
183
2
using System; using System.Text; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; namespace AtCoder { public class Program { public static void Main(string[] args) { new Program().Solve(new ConsoleInput(Console.In, ' ')); } public void Solve(ConsoleInput cin) { var N = cin.ReadInt; var M = cin.ReadInt; var xs = new int[M]; for (int i = 0; i < M; i++) { xs[i] = cin.ReadInt; } xs = xs.OrderBy(x => x).ToArray(); int ret = 0; if (M == 1 || M <= N) { Console.Write(ret); return; } if (N == 1) { ret = xs[M] - xs[0]; Console.Write(ret); return; } var Ls = new int[M - 1]; for (int i = 0; i < M - 1; i++) { Ls[i] = (xs[i + 1] - xs[i]); } Ls = Ls.OrderBy(x => x).ToArray(); for (int i = 0; i < M - N; i++) { ret += Ls[i]; } Console.Write(ret); } } public class ConsoleInput { private readonly System.IO.TextReader _stream; private char _separator = ' '; private Queue<string> inputStream; public ConsoleInput(System.IO.TextReader stream, char separator = ' ') { this._separator = separator; this._stream = stream; inputStream = new Queue<string>(); } public string Read { get { if (inputStream.Count != 0) return inputStream.Dequeue(); string[] tmp = _stream.ReadLine().Split(_separator); for (int i = 0; i < tmp.Length; ++i) inputStream.Enqueue(tmp[i]); return inputStream.Dequeue(); } } public string ReadLine { get { return _stream.ReadLine(); } } public int ReadInt { get { return int.Parse(Read); } } public long ReadLong { get { return long.Parse(Read); } } public double ReadDouble { get { return double.Parse(Read); } } public string[] ReadStrArray(long N) { var ret = new string[N]; for (long i = 0; i < N; ++i) ret[i] = Read; return ret; } public int[] ReadIntArray(long N) { var ret = new int[N]; for (long i = 0; i < N; ++i) ret[i] = ReadInt; return ret; } public long[] ReadLongArray(long N) { var ret = new long[N]; for (long i = 0; i < N; ++i) ret[i] = ReadLong; return ret; } } }
using System; using System.Text; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; namespace AtCoder { public class Program { public static void Main(string[] args) { new Program().Solve(new ConsoleInput(Console.In, ' ')); } public void Solve(ConsoleInput cin) { var N = cin.ReadInt; var M = cin.ReadInt; var xs = new int[M]; for (int i = 0; i < M; i++) { xs[i] = cin.ReadInt; } xs = xs.OrderBy(x => x).ToArray(); int ret = 0; if (M == 1 || M <= N) { Console.Write(ret); return; } if (N == 1) { ret = xs[M - 1] - xs[0]; Console.Write(ret); return; } var Ls = new int[M - 1]; for (int i = 0; i < M - 1; i++) { Ls[i] = (xs[i + 1] - xs[i]); } Ls = Ls.OrderBy(x => x).ToArray(); for (int i = 0; i < M - N; i++) { ret += Ls[i]; } Console.Write(ret); } } public class ConsoleInput { private readonly System.IO.TextReader _stream; private char _separator = ' '; private Queue<string> inputStream; public ConsoleInput(System.IO.TextReader stream, char separator = ' ') { this._separator = separator; this._stream = stream; inputStream = new Queue<string>(); } public string Read { get { if (inputStream.Count != 0) return inputStream.Dequeue(); string[] tmp = _stream.ReadLine().Split(_separator); for (int i = 0; i < tmp.Length; ++i) inputStream.Enqueue(tmp[i]); return inputStream.Dequeue(); } } public string ReadLine { get { return _stream.ReadLine(); } } public int ReadInt { get { return int.Parse(Read); } } public long ReadLong { get { return long.Parse(Read); } } public double ReadDouble { get { return double.Parse(Read); } } public string[] ReadStrArray(long N) { var ret = new string[N]; for (long i = 0; i < N; ++i) ret[i] = Read; return ret; } public int[] ReadIntArray(long N) { var ret = new int[N]; for (long i = 0; i < N; ++i) ret[i] = ReadInt; return ret; } public long[] ReadLongArray(long N) { var ret = new long[N]; for (long i = 0; i < N; ++i) ret[i] = ReadLong; return ret; } } }
[["+", 31, 204, 206, 207, 0, 28, 0, 16, 17, 33], ["+", 31, 204, 206, 207, 0, 28, 0, 16, 12, 203]]
8
637
2
using System; using System.Linq; namespace ABC117_C { class Program { static void Main(string[] args) { var NM = Console.ReadLine().Split().Select(int.Parse).ToArray(); var N = NM[0]; var M = NM[1]; var X = Console.ReadLine().Split().Select(int.Parse).ToArray(); if (N == 1) { Console.WriteLine(0); return; } Array.Sort(X); long ans = 0; var dis = new long[M]; for (int i = 1; i < M; i++) { dis[i] = X[i] - X[i - 1]; } var ignore = dis.OrderByDescending(x => x).Take(N - 1).ToArray().Sum(); ans = dis.Sum() - ignore; Console.WriteLine(ans); } } }
using System; using System.Linq; namespace ABC117_C { class Program { static void Main(string[] args) { var NM = Console.ReadLine().Split().Select(int.Parse).ToArray(); var N = NM[0]; var M = NM[1]; var X = Console.ReadLine().Split().Select(int.Parse).ToArray(); if (M == 1 || N >= M) { Console.WriteLine(0); return; } Array.Sort(X); long ans = 0; var dis = new long[M]; for (int i = 1; i < M; i++) { dis[i] = X[i] - X[i - 1]; } var ignore = dis.OrderByDescending(x => x).Take(N - 1).ToArray().Sum(); ans = dis.Sum() - ignore; Console.WriteLine(ans); } } }
[["-", 0, 195, 8, 196, 0, 57, 15, 16, 31, 22], ["+", 8, 196, 0, 57, 15, 16, 31, 16, 31, 22], ["+", 0, 195, 8, 196, 0, 57, 15, 16, 17, 106], ["+", 8, 196, 0, 57, 15, 16, 12, 16, 31, 22], ["+", 8, 196, 0, 57, 15, 16, 12, 16, 17, 20], ["+", 8, 196, 0, 57, 15, 16, 12, 16, 12, 22]]
8
206
6
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; class Program { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } static void Solve() { var N = sc.ReadInt(); var K = sc.ReadLong(); var A = sc.ReadLongArray(N); var c0 = new int[60]; var c1 = new int[60]; foreach (var a in A) { for (int i = 0; i < 60; i++) { var x = (a >> i) & 1; if (x == 0) c0[i]++; else c1[i]++; } } // f(K) var ans = 0L; for (int i = 0; i < 60; i++) { if (((K >> i) & 1) == 1) { ans += (1L << i) * c0[i]; } else { ans += (1L << i) * c1[i]; } } for (int k = 60 - 1; k >= 0; k--) { if (((K >> k) & 1) == 0) continue; // Kのi桁目が1であり、初めて0になるとき var res = 0L; // k桁目まではビットを変更できない // k+1桁目以降はビットを自由に変更できる for (int i = 0; i < 60; i++) { var Ki = (K >> i) & 1; if (i > k) { // ビットを変更しない if (Ki == 1) res += (1L << i) * c0[i]; else res += (1L << i) * c1[i]; } else if (k == i) { // 1から0にする res += (1L << i) * c0[i]; } else { // より良いビットを選ぶ res += (1L << i) * Math.Max(c0[i], c1[i]); } } ans = Math.Max(ans, res); } Console.WriteLine(ans); } static Scanner sc = new Scanner(); } class Scanner { string[] S = new string[0]; int Index = 0; char[] Separators = new char[] { ' ' }; public string Next() { if (this.Index < this.S.Length) return this.S[this.Index++]; var line = ""; while (line == "") line = Console.ReadLine(); this.S = line.Split(this.Separators, StringSplitOptions.RemoveEmptyEntries); if (this.S.Length == 0) return this.Next(); this.Index = 0; return this.S[this.Index++]; } public string ReadStr() { return this.Next(); } public char ReadChar() { return this.Next()[0]; } public int ReadInt() { return int.Parse(this.Next()); } public uint ReadUInt() { return uint.Parse(this.Next()); } public long ReadLong() { return long.Parse(this.Next()); } public double ReadDouble() { return double.Parse(this.Next()); } public Tuple<int, int> ReadTup(int add = 0) { return Tuple.Create(this.ReadInt() + add, this.ReadInt() + add); } public Tuple<long, long> ReadTupLong(int add = 0) { return Tuple.Create(this.ReadLong() + add, this.ReadLong() + add); } public Tuple<int, int, int> ReadTup3(int add = 0) { return Tuple.Create(this.ReadInt() + add, this.ReadInt() + add, this.ReadInt() + add); } public Tuple<int, int, int, int> ReadTup4(int add = 0) { return Tuple.Create(this.ReadInt() + add, this.ReadInt() + add, this.ReadInt() + add, this.ReadInt() + add); } public int[] ReadIntArray(int n) { var array = new int[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadInt(); } return array; } public long[] ReadLongArray(int n) { var array = new long[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadLong(); } return array; } public double[] ReadDoubleArray(int n) { var array = new double[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadDouble(); } return array; } public char[] ReadCharArray(int n) { var array = new char[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadChar(); } return array; } public string[] ReadStrArray(int n) { var array = new string[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadStr(); } return array; } public Tuple<long, long>[] ReadTupLongArray(int n, int add = 0) { var array = new Tuple<long, long>[n]; for (int i = 0; i < n; i++) { array[i] = this.ReadTupLong(add); } return array; } public Tuple<int, int>[] ReadTupArray(int n, int add = 0) { var array = new Tuple<int, int>[n]; for (int i = 0; i < n; i++) { array[i] = this.ReadTup(add); } return array; } public Tuple<int, int, int>[] ReadTup3Array(int n, int add = 0) { var array = new Tuple<int, int, int>[n]; for (int i = 0; i < n; i++) { array[i] = this.ReadTup3(add); } return array; } public Tuple<int, int, int, int>[] ReadTup4Array(int n, int add = 0) { var array = new Tuple<int, int, int, int>[n]; for (int i = 0; i < n; i++) { array[i] = this.ReadTup4(add); } return array; } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; class Program { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } static void Solve() { var N = sc.ReadInt(); var K = sc.ReadLong(); var A = sc.ReadLongArray(N); var c0 = new int[60]; var c1 = new int[60]; foreach (var a in A) { for (int i = 0; i < 60; i++) { var x = (a >> i) & 1; if (x == 0) c0[i]++; else c1[i]++; } } // f(K) var ans = 0L; for (int i = 0; i < 60; i++) { if (((K >> i) & 1) == 1) { ans += (1L << i) * c0[i]; } else { ans += (1L << i) * c1[i]; } } for (int k = 60 - 1; k >= 0; k--) { if (((K >> k) & 1) == 0) continue; // Kのk桁目が1であり、初めて0になるとき var res = 0L; // k桁目まではビットを変更できない // k+1桁目以降はビットを自由に変更できる for (int i = 0; i < 60; i++) { var Ki = (K >> i) & 1; if (i > k) { // ビットを変更しない if (Ki == 1) res += (1L << i) * c0[i]; else res += (1L << i) * c1[i]; } else if (k == i) { // 1から0にする res += (1L << i) * c1[i]; } else { // より良いビットを選ぶ res += (1L << i) * Math.Max(c0[i], c1[i]); } } ans = Math.Max(ans, res); } Console.WriteLine(ans); } static Scanner sc = new Scanner(); } class Scanner { string[] S = new string[0]; int Index = 0; char[] Separators = new char[] { ' ' }; public string Next() { if (this.Index < this.S.Length) return this.S[this.Index++]; var line = ""; while (line == "") line = Console.ReadLine(); this.S = line.Split(this.Separators, StringSplitOptions.RemoveEmptyEntries); if (this.S.Length == 0) return this.Next(); this.Index = 0; return this.S[this.Index++]; } public string ReadStr() { return this.Next(); } public char ReadChar() { return this.Next()[0]; } public int ReadInt() { return int.Parse(this.Next()); } public uint ReadUInt() { return uint.Parse(this.Next()); } public long ReadLong() { return long.Parse(this.Next()); } public double ReadDouble() { return double.Parse(this.Next()); } public Tuple<int, int> ReadTup(int add = 0) { return Tuple.Create(this.ReadInt() + add, this.ReadInt() + add); } public Tuple<long, long> ReadTupLong(int add = 0) { return Tuple.Create(this.ReadLong() + add, this.ReadLong() + add); } public Tuple<int, int, int> ReadTup3(int add = 0) { return Tuple.Create(this.ReadInt() + add, this.ReadInt() + add, this.ReadInt() + add); } public Tuple<int, int, int, int> ReadTup4(int add = 0) { return Tuple.Create(this.ReadInt() + add, this.ReadInt() + add, this.ReadInt() + add, this.ReadInt() + add); } public int[] ReadIntArray(int n) { var array = new int[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadInt(); } return array; } public long[] ReadLongArray(int n) { var array = new long[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadLong(); } return array; } public double[] ReadDoubleArray(int n) { var array = new double[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadDouble(); } return array; } public char[] ReadCharArray(int n) { var array = new char[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadChar(); } return array; } public string[] ReadStrArray(int n) { var array = new string[n]; for (int i = 0; i < array.Length; i++) { array[i] = this.ReadStr(); } return array; } public Tuple<long, long>[] ReadTupLongArray(int n, int add = 0) { var array = new Tuple<long, long>[n]; for (int i = 0; i < n; i++) { array[i] = this.ReadTupLong(add); } return array; } public Tuple<int, int>[] ReadTupArray(int n, int add = 0) { var array = new Tuple<int, int>[n]; for (int i = 0; i < n; i++) { array[i] = this.ReadTup(add); } return array; } public Tuple<int, int, int>[] ReadTup3Array(int n, int add = 0) { var array = new Tuple<int, int, int>[n]; for (int i = 0; i < n; i++) { array[i] = this.ReadTup3(add); } return array; } public Tuple<int, int, int, int>[] ReadTup4Array(int n, int add = 0) { var array = new Tuple<int, int, int, int>[n]; for (int i = 0; i < n; i++) { array[i] = this.ReadTup4(add); } return array; } }
[["-", 0, 1, 0, 11, 12, 16, 12, 204, 205, 22], ["+", 0, 1, 0, 11, 12, 16, 12, 204, 205, 22]]
8
1,407
2
using System; using System.Text; using System.Collections.Generic; using static System.Math; using System.Linq; using static System.Array; namespace AtcoderExpress { class Program { static void Main(string[] args) { var NK = Console.ReadLine().Split(' ').Select(x => long.Parse(x)).ToArray(); var N = NK[0]; var K = NK[1]; var A = Console.ReadLine().Split(' ').Select(x => long.Parse(x)).ToArray(); //最大値を特定する var max = Max(A.Max(), K); var max2base = Convert.ToString(max, 2); var SumOfZero = new long[max2base.Length]; //各数値の2進数の情報を登録 for (int i = 0; i < N; i++) { var tmp = Convert.ToString(A[i], 2); // Console.WriteLine(tmp); for (int j = 0; j < max2base.Length; j++) { if (j < tmp.Length) { if (tmp[tmp.Length - 1 - j] == '0') { SumOfZero[max2base.Length - 1 - j]++; } } else { SumOfZero[N - 1 - j]++; } } } var ans = 0L; for (int i = 0; i < max2base.Length; i++) { // 1にできるかどうか var tmp = ans + (long)Pow(2, max2base.Length - 1 - i); if (tmp > K) { continue; } var ZeroOrOne = (SumOfZero[i] > N - SumOfZero[i]) ? 1 : 0; ans += ZeroOrOne * (long)Pow(2, max2base.Length - 1 - i); } // Console.WriteLine(len); ////愚直 // for (K = 1;K <= 100;K++) { // ans = 0; // for (int i = 1; i <= K; i++) // { // var tmp = 0L; // for (int j = 0; j < N; j++) // { // tmp += (A[j] ^ i); // } // ans = Max(ans, tmp); // } // Console.WriteLine(K+" "+ans); //} long ans2 = 0; for (int i = 0; i < N; i++) { ans2 += A[i] ^ ans; } Console.WriteLine(ans2); } } }
using System; using System.Text; using System.Collections.Generic; using static System.Math; using System.Linq; using static System.Array; namespace AtcoderExpress { class Program { static void Main(string[] args) { var NK = Console.ReadLine().Split(' ').Select(x => long.Parse(x)).ToArray(); var N = NK[0]; var K = NK[1]; var A = Console.ReadLine().Split(' ').Select(x => long.Parse(x)).ToArray(); //最大値を特定する var max = Max(A.Max(), K); var max2base = Convert.ToString(max, 2); var SumOfZero = new long[max2base.Length]; //各数値の2進数の情報を登録 for (int i = 0; i < N; i++) { var tmp = Convert.ToString(A[i], 2); // Console.WriteLine(tmp); for (int j = 0; j < max2base.Length; j++) { if (j < tmp.Length) { if (tmp[tmp.Length - 1 - j] == '0') { SumOfZero[max2base.Length - 1 - j]++; } } else { SumOfZero[max2base.Length - 1 - j]++; } } } var ans = 0L; for (int i = 0; i < max2base.Length; i++) { // 1にできるかどうか var tmp = ans + (long)Pow(2, max2base.Length - 1 - i); if (tmp > K) { continue; } var ZeroOrOne = (SumOfZero[i] > N - SumOfZero[i]) ? 1 : 0; ans += ZeroOrOne * (long)Pow(2, max2base.Length - 1 - i); } // Console.WriteLine(len); ////愚直 // for (K = 1;K <= 100;K++) { // ans = 0; // for (int i = 1; i <= K; i++) // { // var tmp = 0L; // for (int j = 0; j < N; j++) // { // tmp += (A[j] ^ i); // } // ans = Max(ans, tmp); // } // Console.WriteLine(K+" "+ans); //} long ans2 = 0; for (int i = 0; i < N; i++) { ans2 += A[i] ^ ans; } Console.WriteLine(ans2); } } }
[["-", 206, 207, 0, 28, 0, 16, 31, 16, 31, 22], ["+", 0, 28, 0, 16, 31, 16, 31, 214, 205, 22], ["+", 0, 28, 0, 16, 31, 16, 31, 214, 0, 131], ["+", 0, 28, 0, 16, 31, 16, 31, 214, 141, 22]]
8
422
4
// ReSharper disable ArrangeTypeMemberModifiers // ReSharper disable ConvertIfStatementToSwitchStatement // ReSharper disable FunctionRecursiveOnAllPaths // ReSharper disable InconsistentNaming // ReSharper disable InlineOutVariableDeclaration // ReSharper disable InvertIf // ReSharper disable JoinDeclarationAndInitializer // ReSharper disable MemberCanBeMadeStatic.Global // ReSharper disable MemberCanBeMadeStatic.Local // ReSharper disable NonReadonlyMemberInGetHashCode // ReSharper disable PossibleNullReferenceException // ReSharper disable RedundantUsingDirective // ReSharper disable SuggestVarOrType_BuiltInTypes // ReSharper disable SuggestVarOrType_Elsewhere // ReSharper disable TailRecursiveCall // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local // ReSharper disable UseObjectOrCollectionInitializert #if true && UTAKA_LOCAL //#if false #define UTAKA_DEBUG #endif using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Numerics; using System.Runtime.InteropServices; namespace UtakaApp { public partial class Program { //========================================================================================= // Answer //========================================================================================= public const string SiteName = "AtCoder"; public const string ContestName = "abc117"; public const string ProblemName = "D"; public void Solve() { int N = cin.ReadInt; long K = cin.ReadLong; long[] A = cin.ReadLongArray(N); long X = 0; bool smaller = false; for (int i = 60; i >= 1; i--) { if (!smaller) { if ((K & (1L << i)) == 0) { // 0にするしかない continue; } // 1にしてもよい } int count = 0; for (int j = 0; j < N; j++) { if ((A[j] & (1L << i)) != 0) { count++; } } if (count <= N / 2) { X |= 1L << i; } else { // Kだと1なところに0を使った。よって以降は0も1も自由に指定できる smaller = true; } } long sum = 0; for (int j = 0; j < N; j++) { sum += A[j] ^ X; } cou.WriteLine(sum); } } //========================================================================================= // Debug IO //========================================================================================= public partial class Program { //========================================================================================= // Main //========================================================================================= private readonly ConsoleInput cin; private readonly IConsole cou; public Program(ConsoleInput cin, IConsole cou) { this.cin = cin; this.cou = cou; } public static void Main(string[] args) { #if UTAKA_LOCAL //#if false new TestCaseCheckerForAtCoder().TestProblems(); #else var cin = new ConsoleInput(System.Console.In); var console = new MyConsole(); new Program(cin, console).Solve(); console.Flush(); #endif } //========================================================================================= // Library //========================================================================================= /// <summary> /// 要素数 (a, b) の、defaultValue で満たされた配列を作成します。 /// </summary> /// <typeparam name="T">配列の型</typeparam> /// <param name="a">1次元の要素数</param> /// <param name="b">2次元の要素数</param> /// <param name="defaultValue">デフォルト値</param> /// <returns>指定した条件で初期化された配列</returns> public static T[,] Array2D<T>(int a, int b, T defaultValue) where T : struct { var ret = new T[a, b]; for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { ret[i, j] = defaultValue; } } return ret; } public static T[,,] Array3D<T>(int a, int b, int c, T defaultValue) where T : struct { T[,,] ret = new T[a, b, c]; for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { for (int k = 0; k < c; k++) { ret[i, j, k] = defaultValue; } } } return ret; } /// <summary> /// 要素数 (a, b) の、defaultValue で満たされたJag配列を作成します。 /// </summary> /// <typeparam name="T">配列の型</typeparam> /// <param name="a">1次元の要素数</param> /// <param name="b">2次元の要素数</param> /// <param name="defaultValue">デフォルト値</param> /// <returns>指定した条件で初期化された配列</returns> public static T[][] JagArray2D<T>(int a, int b, T defaultValue) where T : struct { var ret = new T[a][]; for (int i = 0; i < a; i++) { var row = new T[b]; ret[i] = row; for (int j = 0; j < b; j++) { row[j] = defaultValue; } } return ret; } /// <summary> /// 要素数 (a, b) のdefault値で満たされたJag配列を作成します。 /// </summary> /// <typeparam name="T">配列の型</typeparam> /// <param name="a">1次元の要素数</param> /// <param name="b">2次元の要素数</param> /// <returns>初期化された配列</returns> public static T[][] JagArray2D<T>(int a, int b) where T : struct { var ret = new T[a][]; for (int i = 0; i < a; i++) { ret[i] = new T[b]; } return ret; } public static T[][][] JagArray3D<T>(int a, int b, int c, T defaultValue) where T : struct { var ret = new T[a][][]; for (int i = 0; i < a; i++) { T[][] aRow = new T[b][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[] bRow = new T[c]; aRow[j] = bRow; for (int k = 0; k < c; k++) { bRow[k] = defaultValue; } } } return ret; } public static T[][][] JagArray3D<T>(int a, int b, int c) where T : struct { var ret = new T[a][][]; for (int i = 0; i < a; i++) { T[][] aRow = new T[b][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[] bRow = new T[c]; aRow[j] = bRow; } } return ret; } public static T[][][][] JagArray4D<T>(int a, int b, int c, int d, T defaultValue) where T : struct { var ret = new T[a][][][]; for (int i = 0; i < a; i++) { T[][][] aRow = new T[b][][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[][] bRow = new T[c][]; aRow[j] = bRow; for (int k = 0; k < c; k++) { T[] cRow = new T[d]; bRow[k] = cRow; for (int l = 0; l < d; l++) { cRow[l] = defaultValue; } } } } return ret; } public static T[][][][] JagArray4D<T>(int a, int b, int c, int d) where T : struct { var ret = new T[a][][][]; for (int i = 0; i < a; i++) { T[][][] aRow = new T[b][][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[][] bRow = new T[c][]; aRow[j] = bRow; for (int k = 0; k < c; k++) { T[] cRow = new T[d]; bRow[k] = cRow; } } } return ret; } public static T[][][][][] JagArray5D<T>(int a, int b, int c, int d, int e, T defaultValue) where T : struct { var ret = new T[a][][][][]; for (int i = 0; i < a; i++) { T[][][][] aRow = new T[b][][][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[][][] bRow = new T[c][][]; aRow[j] = bRow; for (int k = 0; k < c; k++) { T[][] cRow = new T[d][]; bRow[k] = cRow; for (int l = 0; l < d; l++) { T[] dRow = new T[e]; cRow[l] = dRow; for (int m = 0; m < e; m++) { dRow[m] = defaultValue; } } } } } return ret; } public static T[][][][][] JagArray5D<T>(int a, int b, int c, int d, int e) where T : struct { var ret = new T[a][][][][]; for (int i = 0; i < a; i++) { T[][][][] aRow = new T[b][][][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[][][] bRow = new T[c][][]; aRow[j] = bRow; for (int k = 0; k < c; k++) { T[][] cRow = new T[d][]; bRow[k] = cRow; for (int l = 0; l < d; l++) { T[] dRow = new T[e]; cRow[l] = dRow; } } } } return ret; } /// <summary> /// ジャグ配列をコピーして返す。 /// </summary> public static T[][] CopyJagArray2D<T>(T[][] source) where T : struct { int len = source.Length; T[][] dest = new T[len][]; for (int i = 0; i < len; i++) { T[] inner = source[i]; int innerLength = inner.Length; T[] newer = new T[innerLength]; Array.Copy(inner, newer, innerLength); dest[i] = newer; } return dest; } } public static class UtakaExtentions { /// <summary> /// 配列をコピーします /// </summary> public static T[] Copy<T>(this IList<T> a) { T[] ret = new T[a.Count]; for (int i = 0; i < a.Count; i++) ret[i] = a[i]; return ret; } } public class ConsoleInput { private readonly char _separator = ' '; private readonly TextReader _stream; private readonly Queue<string> inputStream; public ConsoleInput(TextReader stream, char separator = ' ') { _separator = separator; _stream = stream; inputStream = new Queue<string>(); } public string Read { get { if (inputStream.Count != 0) { return inputStream.Dequeue(); } var tmp = _stream.ReadLine().Split(_separator); for (var i = 0; i < tmp.Length; ++i) { inputStream.Enqueue(tmp[i]); } return inputStream.Dequeue(); } } public string ReadLine => _stream.ReadLine(); public int ReadInt => int.Parse(Read); public long ReadLong => long.Parse(Read); public double ReadDouble => double.Parse(Read); public string[] ReadStrArray(long N) { var ret = new string[N]; for (long i = 0; i < N; ++i) { ret[i] = Read; } return ret; } public int[] ReadIntArray(long N) { var ret = new int[N]; for (long i = 0; i < N; ++i) { ret[i] = ReadInt; } return ret; } public long[] ReadLongArray(long N) { var ret = new long[N]; for (long i = 0; i < N; ++i) { ret[i] = ReadLong; } return ret; } } public interface IConsole { void Flush(); void Write(object obj); void Write(string str); void WriteLine(object obj); void WriteLine(string str); void WriteLine(); } public class MyConsole : IConsole { public MyConsole() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); } public void Flush() { Console.Out.Flush(); } public void Write(object obj) { Write(obj.ToString()); } public void Write(string str) { Console.Write(str); } public void WriteLine(object obj) { WriteLine(obj.ToString()); } public void WriteLine(string str) { Console.WriteLine(str); } public void WriteLine() { Console.WriteLine(); } } #if UTAKA_LOCAL public class DebugConsole : IConsole { private readonly StringBuilder mSb; public DebugConsole() { mSb = new StringBuilder(); } public void Flush() { // 何もしない } public void Write(object obj) { Write(obj.ToString()); } public void Write(string str) { mSb.Append(str); } public void WriteLine(object obj) { WriteLine(obj.ToString()); } public void WriteLine(string str) { mSb.AppendLine(str); } public void WriteLine() { mSb.AppendLine(); } public string GetAllOutput() { return mSb.ToString(); } } #endif #if UTAKA_LOCAL public class TestCaseCheckerForAtCoder { private string GetDirectoryPath() { var problemPart = string.IsNullOrEmpty(Program.ProblemName) ? "" : $"/{Program.ProblemName}"; return $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/AlgorithmPrac/{Program.SiteName}/{Program.ContestName}{problemPart}"; } private string GetInputFilePath(int testCaseNumber) { return $"{GetDirectoryPath()}/sample-{testCaseNumber}.in"; } private string GetOutputFilePath(int testCaseNumber) { return $"{GetDirectoryPath()}/sample-{testCaseNumber}.out"; } public bool TestProblem(int testCaseNumber) { var inputFilePath = GetInputFilePath(testCaseNumber); var outputFilePath = GetOutputFilePath(testCaseNumber); TextReader inputStream = new StreamReader(inputFilePath); var cin = new ConsoleInput(inputStream); var debugConsoleWriter = new DebugConsole(); new Program(cin, debugConsoleWriter).Solve(); var output = debugConsoleWriter.GetAllOutput(); TextReader outputStream = new StreamReader(outputFilePath); var outputAnswer = outputStream.ReadToEnd(); Dbg.WriteLine(output); Dbg.WriteLine(outputAnswer); var isCorrect = output == outputAnswer; return isCorrect; } public void TestProblems(int targetTestCaseNumber = -1) { if (targetTestCaseNumber >= 0) { Console.WriteLine( $"!!!!!!!!!!!! Check TestCase {targetTestCaseNumber} !!!!!!!!!!"); } bool isSuccessAll = true; int testCaseNumber = 0; while (true) { testCaseNumber++; if (targetTestCaseNumber >= 0 && targetTestCaseNumber != testCaseNumber) { continue; } var inputFileName = GetInputFilePath(testCaseNumber); if (!File.Exists(inputFileName)) { break; } Console.WriteLine( $"TestCase {testCaseNumber} ====================================================="); var result = TestProblem(testCaseNumber); if (result) { Console.WriteLine("Success"); } else { isSuccessAll = false; Console.WriteLine("Failure *****"); } } if (isSuccessAll) { Console.WriteLine("!!!!!!!!! All Success !!!!!!!!!"); } } } #endif public static class Dbg { [Conditional("UTAKA_DEBUG")] public static void WriteLine(string str) { Console.WriteLine(str); } [Conditional("UTAKA_DEBUG")] public static void Write(string str) { Console.Write(str); } } }
// ReSharper disable ArrangeTypeMemberModifiers // ReSharper disable ConvertIfStatementToSwitchStatement // ReSharper disable FunctionRecursiveOnAllPaths // ReSharper disable InconsistentNaming // ReSharper disable InlineOutVariableDeclaration // ReSharper disable InvertIf // ReSharper disable JoinDeclarationAndInitializer // ReSharper disable MemberCanBeMadeStatic.Global // ReSharper disable MemberCanBeMadeStatic.Local // ReSharper disable NonReadonlyMemberInGetHashCode // ReSharper disable PossibleNullReferenceException // ReSharper disable RedundantUsingDirective // ReSharper disable SuggestVarOrType_BuiltInTypes // ReSharper disable SuggestVarOrType_Elsewhere // ReSharper disable TailRecursiveCall // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local // ReSharper disable UseObjectOrCollectionInitializert #if true && UTAKA_LOCAL //#if false #define UTAKA_DEBUG #endif using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Numerics; using System.Runtime.InteropServices; namespace UtakaApp { public partial class Program { //========================================================================================= // Answer //========================================================================================= public const string SiteName = "AtCoder"; public const string ContestName = "abc117"; public const string ProblemName = "D"; public void Solve() { int N = cin.ReadInt; long K = cin.ReadLong; long[] A = cin.ReadLongArray(N); long X = 0; bool smaller = false; for (int i = 60; i >= 0; i--) { if (!smaller) { if ((K & (1L << i)) == 0) { // 0にするしかない continue; } // 1にしてもよい } int count = 0; for (int j = 0; j < N; j++) { if ((A[j] & (1L << i)) != 0) { count++; } } if (count <= N / 2) { X |= 1L << i; } else { // Kだと1なところに0を使った。よって以降は0も1も自由に指定できる smaller = true; } } long sum = 0; for (int j = 0; j < N; j++) { sum += A[j] ^ X; } cou.WriteLine(sum); } } //========================================================================================= // Debug IO //========================================================================================= public partial class Program { //========================================================================================= // Main //========================================================================================= private readonly ConsoleInput cin; private readonly IConsole cou; public Program(ConsoleInput cin, IConsole cou) { this.cin = cin; this.cou = cou; } public static void Main(string[] args) { #if UTAKA_LOCAL //#if false new TestCaseCheckerForAtCoder().TestProblems(); #else var cin = new ConsoleInput(System.Console.In); var console = new MyConsole(); new Program(cin, console).Solve(); console.Flush(); #endif } //========================================================================================= // Library //========================================================================================= /// <summary> /// 要素数 (a, b) の、defaultValue で満たされた配列を作成します。 /// </summary> /// <typeparam name="T">配列の型</typeparam> /// <param name="a">1次元の要素数</param> /// <param name="b">2次元の要素数</param> /// <param name="defaultValue">デフォルト値</param> /// <returns>指定した条件で初期化された配列</returns> public static T[,] Array2D<T>(int a, int b, T defaultValue) where T : struct { var ret = new T[a, b]; for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { ret[i, j] = defaultValue; } } return ret; } public static T[,,] Array3D<T>(int a, int b, int c, T defaultValue) where T : struct { T[,,] ret = new T[a, b, c]; for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { for (int k = 0; k < c; k++) { ret[i, j, k] = defaultValue; } } } return ret; } /// <summary> /// 要素数 (a, b) の、defaultValue で満たされたJag配列を作成します。 /// </summary> /// <typeparam name="T">配列の型</typeparam> /// <param name="a">1次元の要素数</param> /// <param name="b">2次元の要素数</param> /// <param name="defaultValue">デフォルト値</param> /// <returns>指定した条件で初期化された配列</returns> public static T[][] JagArray2D<T>(int a, int b, T defaultValue) where T : struct { var ret = new T[a][]; for (int i = 0; i < a; i++) { var row = new T[b]; ret[i] = row; for (int j = 0; j < b; j++) { row[j] = defaultValue; } } return ret; } /// <summary> /// 要素数 (a, b) のdefault値で満たされたJag配列を作成します。 /// </summary> /// <typeparam name="T">配列の型</typeparam> /// <param name="a">1次元の要素数</param> /// <param name="b">2次元の要素数</param> /// <returns>初期化された配列</returns> public static T[][] JagArray2D<T>(int a, int b) where T : struct { var ret = new T[a][]; for (int i = 0; i < a; i++) { ret[i] = new T[b]; } return ret; } public static T[][][] JagArray3D<T>(int a, int b, int c, T defaultValue) where T : struct { var ret = new T[a][][]; for (int i = 0; i < a; i++) { T[][] aRow = new T[b][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[] bRow = new T[c]; aRow[j] = bRow; for (int k = 0; k < c; k++) { bRow[k] = defaultValue; } } } return ret; } public static T[][][] JagArray3D<T>(int a, int b, int c) where T : struct { var ret = new T[a][][]; for (int i = 0; i < a; i++) { T[][] aRow = new T[b][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[] bRow = new T[c]; aRow[j] = bRow; } } return ret; } public static T[][][][] JagArray4D<T>(int a, int b, int c, int d, T defaultValue) where T : struct { var ret = new T[a][][][]; for (int i = 0; i < a; i++) { T[][][] aRow = new T[b][][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[][] bRow = new T[c][]; aRow[j] = bRow; for (int k = 0; k < c; k++) { T[] cRow = new T[d]; bRow[k] = cRow; for (int l = 0; l < d; l++) { cRow[l] = defaultValue; } } } } return ret; } public static T[][][][] JagArray4D<T>(int a, int b, int c, int d) where T : struct { var ret = new T[a][][][]; for (int i = 0; i < a; i++) { T[][][] aRow = new T[b][][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[][] bRow = new T[c][]; aRow[j] = bRow; for (int k = 0; k < c; k++) { T[] cRow = new T[d]; bRow[k] = cRow; } } } return ret; } public static T[][][][][] JagArray5D<T>(int a, int b, int c, int d, int e, T defaultValue) where T : struct { var ret = new T[a][][][][]; for (int i = 0; i < a; i++) { T[][][][] aRow = new T[b][][][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[][][] bRow = new T[c][][]; aRow[j] = bRow; for (int k = 0; k < c; k++) { T[][] cRow = new T[d][]; bRow[k] = cRow; for (int l = 0; l < d; l++) { T[] dRow = new T[e]; cRow[l] = dRow; for (int m = 0; m < e; m++) { dRow[m] = defaultValue; } } } } } return ret; } public static T[][][][][] JagArray5D<T>(int a, int b, int c, int d, int e) where T : struct { var ret = new T[a][][][][]; for (int i = 0; i < a; i++) { T[][][][] aRow = new T[b][][][]; ret[i] = aRow; for (int j = 0; j < b; j++) { T[][][] bRow = new T[c][][]; aRow[j] = bRow; for (int k = 0; k < c; k++) { T[][] cRow = new T[d][]; bRow[k] = cRow; for (int l = 0; l < d; l++) { T[] dRow = new T[e]; cRow[l] = dRow; } } } } return ret; } /// <summary> /// ジャグ配列をコピーして返す。 /// </summary> public static T[][] CopyJagArray2D<T>(T[][] source) where T : struct { int len = source.Length; T[][] dest = new T[len][]; for (int i = 0; i < len; i++) { T[] inner = source[i]; int innerLength = inner.Length; T[] newer = new T[innerLength]; Array.Copy(inner, newer, innerLength); dest[i] = newer; } return dest; } } public static class UtakaExtentions { /// <summary> /// 配列をコピーします /// </summary> public static T[] Copy<T>(this IList<T> a) { T[] ret = new T[a.Count]; for (int i = 0; i < a.Count; i++) ret[i] = a[i]; return ret; } } public class ConsoleInput { private readonly char _separator = ' '; private readonly TextReader _stream; private readonly Queue<string> inputStream; public ConsoleInput(TextReader stream, char separator = ' ') { _separator = separator; _stream = stream; inputStream = new Queue<string>(); } public string Read { get { if (inputStream.Count != 0) { return inputStream.Dequeue(); } var tmp = _stream.ReadLine().Split(_separator); for (var i = 0; i < tmp.Length; ++i) { inputStream.Enqueue(tmp[i]); } return inputStream.Dequeue(); } } public string ReadLine => _stream.ReadLine(); public int ReadInt => int.Parse(Read); public long ReadLong => long.Parse(Read); public double ReadDouble => double.Parse(Read); public string[] ReadStrArray(long N) { var ret = new string[N]; for (long i = 0; i < N; ++i) { ret[i] = Read; } return ret; } public int[] ReadIntArray(long N) { var ret = new int[N]; for (long i = 0; i < N; ++i) { ret[i] = ReadInt; } return ret; } public long[] ReadLongArray(long N) { var ret = new long[N]; for (long i = 0; i < N; ++i) { ret[i] = ReadLong; } return ret; } } public interface IConsole { void Flush(); void Write(object obj); void Write(string str); void WriteLine(object obj); void WriteLine(string str); void WriteLine(); } public class MyConsole : IConsole { public MyConsole() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); } public void Flush() { Console.Out.Flush(); } public void Write(object obj) { Write(obj.ToString()); } public void Write(string str) { Console.Write(str); } public void WriteLine(object obj) { WriteLine(obj.ToString()); } public void WriteLine(string str) { Console.WriteLine(str); } public void WriteLine() { Console.WriteLine(); } } #if UTAKA_LOCAL public class DebugConsole : IConsole { private readonly StringBuilder mSb; public DebugConsole() { mSb = new StringBuilder(); } public void Flush() { // 何もしない } public void Write(object obj) { Write(obj.ToString()); } public void Write(string str) { mSb.Append(str); } public void WriteLine(object obj) { WriteLine(obj.ToString()); } public void WriteLine(string str) { mSb.AppendLine(str); } public void WriteLine() { mSb.AppendLine(); } public string GetAllOutput() { return mSb.ToString(); } } #endif #if UTAKA_LOCAL public class TestCaseCheckerForAtCoder { private string GetDirectoryPath() { var problemPart = string.IsNullOrEmpty(Program.ProblemName) ? "" : $"/{Program.ProblemName}"; return $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/AlgorithmPrac/{Program.SiteName}/{Program.ContestName}{problemPart}"; } private string GetInputFilePath(int testCaseNumber) { return $"{GetDirectoryPath()}/sample-{testCaseNumber}.in"; } private string GetOutputFilePath(int testCaseNumber) { return $"{GetDirectoryPath()}/sample-{testCaseNumber}.out"; } public bool TestProblem(int testCaseNumber) { var inputFilePath = GetInputFilePath(testCaseNumber); var outputFilePath = GetOutputFilePath(testCaseNumber); TextReader inputStream = new StreamReader(inputFilePath); var cin = new ConsoleInput(inputStream); var debugConsoleWriter = new DebugConsole(); new Program(cin, debugConsoleWriter).Solve(); var output = debugConsoleWriter.GetAllOutput(); TextReader outputStream = new StreamReader(outputFilePath); var outputAnswer = outputStream.ReadToEnd(); Dbg.WriteLine(output); Dbg.WriteLine(outputAnswer); var isCorrect = output == outputAnswer; return isCorrect; } public void TestProblems(int targetTestCaseNumber = -1) { if (targetTestCaseNumber >= 0) { Console.WriteLine( $"!!!!!!!!!!!! Check TestCase {targetTestCaseNumber} !!!!!!!!!!"); } bool isSuccessAll = true; int testCaseNumber = 0; while (true) { testCaseNumber++; if (targetTestCaseNumber >= 0 && targetTestCaseNumber != testCaseNumber) { continue; } var inputFileName = GetInputFilePath(testCaseNumber); if (!File.Exists(inputFileName)) { break; } Console.WriteLine( $"TestCase {testCaseNumber} ====================================================="); var result = TestProblem(testCaseNumber); if (result) { Console.WriteLine("Success"); } else { isSuccessAll = false; Console.WriteLine("Failure *****"); } } if (isSuccessAll) { Console.WriteLine("!!!!!!!!! All Success !!!!!!!!!"); } } } #endif public static class Dbg { [Conditional("UTAKA_DEBUG")] public static void WriteLine(string str) { Console.WriteLine(str); } [Conditional("UTAKA_DEBUG")] public static void Write(string str) { Console.Write(str); } } }
[["-", 0, 195, 8, 196, 0, 7, 15, 16, 12, 203], ["+", 0, 195, 8, 196, 0, 7, 15, 16, 12, 203]]
8
3,145
2
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using static ABC117.Util; using static System.Console; #if DEBUG using System.Diagnostics; #endif namespace ABC117 { class Program { static void Main(string[] args) { #if DEBUG while (true) { #endif // EntranceExamination(); // 3m // Polygon(); // 13m // Streamline(); // 40m XXOR(); #if DEBUG } #endif } static void XXOR() { int maxDigit = 50; long[] input = ReadLongArray(); long K = input[0]; long N = input[1]; long[] A = ReadLongArray(); long[,] dp = new long[maxDigit + 1, 2]; ArrayInitialize(dp, -1); dp[0, 0] = 0; for (int d = 0; d < maxDigit; d++) { long mask = 1L << (maxDigit - d - 1); int num1 = 0; // d桁目の1の数 for (int i = 0; i < N; i++) if ((A[i] & mask) == mask) num1++; long cost0 = mask * num1; long cost1 = mask * (N - num1); // exact -> exact if (dp[d, 0] != -1) { if ((K & mask) == mask) ChMax(ref dp[d + 1, 0], dp[d, 0] + cost1); else ChMax(ref dp[d + 1, 0], dp[d, 0] + cost0); } // exact -> smaller if (dp[d, 0] != -1) { if ((K & mask) == mask) ChMax(ref dp[d + 1, 1], dp[d, 0] + cost0); } // smaller -> smaller if (dp[d, 1] != -1) { ChMax(ref dp[d + 1, 1], dp[d, 1] + Math.Max(cost0, cost1)); } } long ans = Math.Max(dp[maxDigit, 0], dp[maxDigit, 1]); WriteLine(ans); } static void Streamline() { int[] input = ReadIntArray(); int N = input[0]; int M = input[1]; int[] X = ReadIntArray(); Sort(X); int[] diffList = new int[M - 1]; for (int i = 0; i < M - 1; i++) { diffList[i] = X[i + 1] - X[i]; } ReverseSort(diffList); int ans = diffList.Skip(N - 1).Sum(); WriteLine(ans); } static void Polygon() { int N = ReadInt(); int[] L = ReadIntArray(); ReverseSort(L); int max = L[0]; int sum = L.Skip(1).Sum(); string ans = max < sum ? "Yes" : "No"; WriteLine(ans); } static void EntranceExamination() { int[] tmp = ReadIntArray(); int T = tmp[0]; int X = tmp[1]; WriteLine(T * 1.0m / X); } } #region ToolBox /// <summary> /// ユーティリティー /// </summary> public static class Util { // 10^10 * 2 public static readonly long INF = 20000000000; public static int ReadInt() { return int.Parse(Console.ReadLine()); } public static int[] ReadIntArray() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); } public static long ReadLong() { return long.Parse(Console.ReadLine()); } public static long[] ReadLongArray() { return Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); } public static string ReadString() { return Console.ReadLine(); } /// <summary> /// "00101001010"という様な入力をintの配列にして返す /// </summary> /// <returns></returns> public static int[] ReadIntArrayFromBinaryString() { return Console.ReadLine().Select(c => int.Parse(c.ToString())).ToArray(); } /// <summary> /// "00101001010"という様な入力をboolの配列にして返す /// </summary> /// <returns></returns> public static bool[] ReadBoolArrayFromBinaryString() { return Console.ReadLine().Select(c => c == '1').ToArray(); } /// <summary> /// ソートをして結果を返します。 /// 破壊的関数です。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] Sort<T>(T[] array) { Array.Sort<T>(array); return array; } /// <summary> /// 逆順ソートをして結果を返します。 /// 破壊的関数です。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] ReverseSort<T>(T[] array) { Array.Sort<T>(array); Array.Reverse(array); return array; } /// <summary> /// Rubyにあるようなやつ /// ex) 5.Times(i => Console.WriteLine(i)); /// </summary> /// <param name="times"></param> /// <param name="action"></param> public static void Times(this int times, Action<int> action) { for (int i = 0; i < times; i++) { action(i); } } /// <summary> /// 引数aと引数bの値を入れ替えます /// </summary> /// <typeparam name="T"></typeparam> /// <param name="a"></param> /// <param name="b"></param> public static void Swap<T>(ref T a, ref T b) { T _a = a; a = b; b = _a; } /// <summary> /// Console.WriteLineの自動フラッシュをしないようにする /// </summary> public static void DontAutoFlush() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); } public static void Flush() { Console.Out.Flush(); } /// <summary> /// 先頭と末尾に要素を増やした新しい配列を返します。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] AddHeadAndTail<T>(T[] array) { int len = array.Length; T[] res = new T[len + 2]; Array.Copy(array, 0, res, 1, len); return res; } /// <summary> /// 昇順ソート済みの配列を2分探索します。 /// 要素が見つからなかった場合はnより大きい数値の中で最小の数値のインデックスを返す。 /// </summary> /// <param name="array"></param> /// <param name="n"></param> /// <returns></returns> public static int BinarySearch(long[] array, long n) { int left = 0; int right = array.Length - 1; while (left <= right) { int mid = (right - left) / 2 + left; if (array[mid] == n) return mid; else if (n < array[mid]) right = mid - 1; else left = mid + 1; } return left; } public static int GCD(int a, int b) { return (b == 0) ? a : GCD(b, a % b); } public static int[] GetDivisor(int n) { double sqrt = Math.Sqrt(n); List<int> divisor = new List<int>(); for (int i = 1; i <= sqrt; i++) { if (n % i == 0) { divisor.Add(i); int tmp = n / i; if (tmp != i) { divisor.Add(tmp); } } } return Sort(divisor.ToArray()); } public static int[] LongToBinaryArray(long n) { List<int> lst = new List<int>(); while (n > 0) { int amari = (int)(n % 2); lst.Add(amari); n /= 2; } return lst.ToArray(); } public static long BinaryArrayToLong(int[] binaryArray) { long result = 0; long b = 1; int len = binaryArray.Length; for (int i = 0; i < len; i++) { result += binaryArray[i] * b; b *= 2; } return result; } public static void Deconstruct<T>(this T[] items, out T t0) { t0 = items.Length > 0 ? items[0] : default(T); } public static void Deconstruct<T>(this T[] items, out T t0, out T t1) { if (items.Length < 2) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; } public static void Deconstruct<T>(this T[] items, out T t0, out T t1, out T t2) { if (items.Length < 3) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; t2 = items[2]; } public static void Deconstruct<T>(this T[] items, out T t0, out T t1, out T t2, out T t3) { if (items.Length < 4) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; t2 = items[2]; t3 = items[3]; } public static void ArrayInitialize<T>(T[,] array, T value) { int len0 = array.GetLength(0); int len1 = array.GetLength(1); for (int i = 0; i < len0; i++) { for (int j = 0; j < len1; j++) { array[i, j] = value; } } } public static void ChMax(ref long a, long b) { if (a < b) a = b; } #if DEBUG static void SampleGenerator() { int A = 1000; int B = 1000; int Q = 1000; Random r = new Random(); StringBuilder sb = new StringBuilder(); sb.AppendLine(string.Format("{0} {1} {2}", A, B, Q)); A.Times(a => sb.AppendLine(((long)r.Next() * r.Next()).ToString())); B.Times(b => sb.AppendLine(((long)r.Next() * r.Next()).ToString())); Q.Times(q => sb.AppendLine(((long)r.Next() * r.Next()).ToString())); Debug.WriteLine(sb.ToString()); } #endif } /// <summary> /// HashSetにTupleを入れた時の、等値性判定方法の指定に使います。 /// HashSetのコンストラクタに渡して使います。 /// EqualsとGetHashCodeを提供します。 /// </summary> /// <typeparam name="T"></typeparam> public class EqualityComparer<T> : IEqualityComparer<T> { private Func<T, T, bool> _equals; private Func<T, int> _getHashCode; public EqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashCode) { _equals = equals; _getHashCode = getHashCode; } public bool Equals(T x, T y) { return _equals(x, y); } public int GetHashCode(T obj) { return _getHashCode(obj); } } /// <summary> /// UnionFindTree /// </summary> public class UnionFindTree { int[] Node; public UnionFindTree(int N) { Node = new int[N]; for (int i = 0; i < N; i++) { Node[i] = -1; } } public bool IsSameGroup(int x, int y) { return GetRoot(x) == GetRoot(y); } public bool Merge(int x, int y) { int xr = GetRoot(x); int yr = GetRoot(y); if (xr == yr) return false; // xが、大きなグループを示すようにSwapする(値が小さい方が大きなグループ) if (Node[xr] > Node[yr]) Swap(ref xr, ref yr); // グループの数を合算する Node[xr] += Node[yr]; // 根を張り替える Node[yr] = xr; return true; } public int Size(int x) { return -Node[GetRoot(x)]; } public int GetRoot(int n) { if (Node[n] < 0) { return n; } else { // 根を張りなおす。 Node[n] = GetRoot(Node[n]); return Node[n]; } } } /// <summary> /// PriorityQueue /// </summary> /// <typeparam name="T"></typeparam> public class PriorityQueue<T> where T : IComparable { private Comparison<T> _comparison = null; private int _type = 0; private T[] _heap; private int _sz = 0; private int _count = 0; /// <summary> /// Priority queue /// </summary> /// <param name="maxSize">max size</param> /// <param name="type">0: asc, 1:desc</param> public PriorityQueue(int maxSize, int type = 0) { _heap = new T[maxSize]; _type = type; } public PriorityQueue(int maxSize, Comparison<T> comparison) { _heap = new T[maxSize]; _comparison = comparison; } private int Compare(T x, T y) { if (_comparison != null) return _comparison(x, y); return _type == 0 ? x.CompareTo(y) : y.CompareTo(x); } public void Push(T x) { _count++; // node number var i = _sz++; while (i > 0) { // parent node number var p = (i - 1) / 2; if (Compare(_heap[p], x) <= 0) break; _heap[i] = _heap[p]; i = p; } _heap[i] = x; } public T Pop() { _count--; T ret = _heap[0]; T x = _heap[--_sz]; int i = 0; while (i * 2 + 1 < _sz) { // children int a = i * 2 + 1; int b = i * 2 + 2; if (b < _sz && Compare(_heap[b], _heap[a]) < 0) a = b; if (Compare(_heap[a], x) >= 0) break; _heap[i] = _heap[a]; i = a; } _heap[i] = x; return ret; } public int Count() { return _count; } public T Peek() { return _heap[0]; } public bool Contains(T x) { for (int i = 0; i < _sz; i++) if (x.Equals(_heap[i])) return true; return false; } public void Clear() { while (this.Count() > 0) this.Pop(); } public IEnumerator<T> GetEnumerator() { var ret = new List<T>(); while (this.Count() > 0) { ret.Add(this.Pop()); } foreach (var r in ret) { this.Push(r); yield return r; } } public T[] ToArray() { T[] array = new T[_sz]; int i = 0; foreach (var r in this) { array[i++] = r; } return array; } } #endregion }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using static ABC117.Util; using static System.Console; #if DEBUG using System.Diagnostics; #endif namespace ABC117 { class Program { static void Main(string[] args) { #if DEBUG while (true) { #endif // EntranceExamination(); // 3m // Polygon(); // 13m // Streamline(); // 40m XXOR(); #if DEBUG } #endif } static void XXOR() { int maxDigit = 50; long[] input = ReadLongArray(); long N = input[0]; long K = input[1]; long[] A = ReadLongArray(); long[,] dp = new long[maxDigit + 1, 2]; ArrayInitialize(dp, -1); dp[0, 0] = 0; for (int d = 0; d < maxDigit; d++) { long mask = 1L << (maxDigit - d - 1); int num1 = 0; // d桁目の1の数 for (int i = 0; i < N; i++) if ((A[i] & mask) == mask) num1++; long cost0 = mask * num1; long cost1 = mask * (N - num1); // exact -> exact if (dp[d, 0] != -1) { if ((K & mask) == mask) ChMax(ref dp[d + 1, 0], dp[d, 0] + cost1); else ChMax(ref dp[d + 1, 0], dp[d, 0] + cost0); } // exact -> smaller if (dp[d, 0] != -1) { if ((K & mask) == mask) ChMax(ref dp[d + 1, 1], dp[d, 0] + cost0); } // smaller -> smaller if (dp[d, 1] != -1) { ChMax(ref dp[d + 1, 1], dp[d, 1] + Math.Max(cost0, cost1)); } } long ans = Math.Max(dp[maxDigit, 0], dp[maxDigit, 1]); WriteLine(ans); } static void Streamline() { int[] input = ReadIntArray(); int N = input[0]; int M = input[1]; int[] X = ReadIntArray(); Sort(X); int[] diffList = new int[M - 1]; for (int i = 0; i < M - 1; i++) { diffList[i] = X[i + 1] - X[i]; } ReverseSort(diffList); int ans = diffList.Skip(N - 1).Sum(); WriteLine(ans); } static void Polygon() { int N = ReadInt(); int[] L = ReadIntArray(); ReverseSort(L); int max = L[0]; int sum = L.Skip(1).Sum(); string ans = max < sum ? "Yes" : "No"; WriteLine(ans); } static void EntranceExamination() { int[] tmp = ReadIntArray(); int T = tmp[0]; int X = tmp[1]; WriteLine(T * 1.0m / X); } } #region ToolBox /// <summary> /// ユーティリティー /// </summary> public static class Util { // 10^10 * 2 public static readonly long INF = 20000000000; public static int ReadInt() { return int.Parse(Console.ReadLine()); } public static int[] ReadIntArray() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); } public static long ReadLong() { return long.Parse(Console.ReadLine()); } public static long[] ReadLongArray() { return Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); } public static string ReadString() { return Console.ReadLine(); } /// <summary> /// "00101001010"という様な入力をintの配列にして返す /// </summary> /// <returns></returns> public static int[] ReadIntArrayFromBinaryString() { return Console.ReadLine().Select(c => int.Parse(c.ToString())).ToArray(); } /// <summary> /// "00101001010"という様な入力をboolの配列にして返す /// </summary> /// <returns></returns> public static bool[] ReadBoolArrayFromBinaryString() { return Console.ReadLine().Select(c => c == '1').ToArray(); } /// <summary> /// ソートをして結果を返します。 /// 破壊的関数です。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] Sort<T>(T[] array) { Array.Sort<T>(array); return array; } /// <summary> /// 逆順ソートをして結果を返します。 /// 破壊的関数です。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] ReverseSort<T>(T[] array) { Array.Sort<T>(array); Array.Reverse(array); return array; } /// <summary> /// Rubyにあるようなやつ /// ex) 5.Times(i => Console.WriteLine(i)); /// </summary> /// <param name="times"></param> /// <param name="action"></param> public static void Times(this int times, Action<int> action) { for (int i = 0; i < times; i++) { action(i); } } /// <summary> /// 引数aと引数bの値を入れ替えます /// </summary> /// <typeparam name="T"></typeparam> /// <param name="a"></param> /// <param name="b"></param> public static void Swap<T>(ref T a, ref T b) { T _a = a; a = b; b = _a; } /// <summary> /// Console.WriteLineの自動フラッシュをしないようにする /// </summary> public static void DontAutoFlush() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); } public static void Flush() { Console.Out.Flush(); } /// <summary> /// 先頭と末尾に要素を増やした新しい配列を返します。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] AddHeadAndTail<T>(T[] array) { int len = array.Length; T[] res = new T[len + 2]; Array.Copy(array, 0, res, 1, len); return res; } /// <summary> /// 昇順ソート済みの配列を2分探索します。 /// 要素が見つからなかった場合はnより大きい数値の中で最小の数値のインデックスを返す。 /// </summary> /// <param name="array"></param> /// <param name="n"></param> /// <returns></returns> public static int BinarySearch(long[] array, long n) { int left = 0; int right = array.Length - 1; while (left <= right) { int mid = (right - left) / 2 + left; if (array[mid] == n) return mid; else if (n < array[mid]) right = mid - 1; else left = mid + 1; } return left; } public static int GCD(int a, int b) { return (b == 0) ? a : GCD(b, a % b); } public static int[] GetDivisor(int n) { double sqrt = Math.Sqrt(n); List<int> divisor = new List<int>(); for (int i = 1; i <= sqrt; i++) { if (n % i == 0) { divisor.Add(i); int tmp = n / i; if (tmp != i) { divisor.Add(tmp); } } } return Sort(divisor.ToArray()); } public static int[] LongToBinaryArray(long n) { List<int> lst = new List<int>(); while (n > 0) { int amari = (int)(n % 2); lst.Add(amari); n /= 2; } return lst.ToArray(); } public static long BinaryArrayToLong(int[] binaryArray) { long result = 0; long b = 1; int len = binaryArray.Length; for (int i = 0; i < len; i++) { result += binaryArray[i] * b; b *= 2; } return result; } public static void Deconstruct<T>(this T[] items, out T t0) { t0 = items.Length > 0 ? items[0] : default(T); } public static void Deconstruct<T>(this T[] items, out T t0, out T t1) { if (items.Length < 2) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; } public static void Deconstruct<T>(this T[] items, out T t0, out T t1, out T t2) { if (items.Length < 3) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; t2 = items[2]; } public static void Deconstruct<T>(this T[] items, out T t0, out T t1, out T t2, out T t3) { if (items.Length < 4) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; t2 = items[2]; t3 = items[3]; } public static void ArrayInitialize<T>(T[,] array, T value) { int len0 = array.GetLength(0); int len1 = array.GetLength(1); for (int i = 0; i < len0; i++) { for (int j = 0; j < len1; j++) { array[i, j] = value; } } } public static void ChMax(ref long a, long b) { if (a < b) a = b; } #if DEBUG static void SampleGenerator() { int A = 1000; int B = 1000; int Q = 1000; Random r = new Random(); StringBuilder sb = new StringBuilder(); sb.AppendLine(string.Format("{0} {1} {2}", A, B, Q)); A.Times(a => sb.AppendLine(((long)r.Next() * r.Next()).ToString())); B.Times(b => sb.AppendLine(((long)r.Next() * r.Next()).ToString())); Q.Times(q => sb.AppendLine(((long)r.Next() * r.Next()).ToString())); Debug.WriteLine(sb.ToString()); } #endif } /// <summary> /// HashSetにTupleを入れた時の、等値性判定方法の指定に使います。 /// HashSetのコンストラクタに渡して使います。 /// EqualsとGetHashCodeを提供します。 /// </summary> /// <typeparam name="T"></typeparam> public class EqualityComparer<T> : IEqualityComparer<T> { private Func<T, T, bool> _equals; private Func<T, int> _getHashCode; public EqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashCode) { _equals = equals; _getHashCode = getHashCode; } public bool Equals(T x, T y) { return _equals(x, y); } public int GetHashCode(T obj) { return _getHashCode(obj); } } /// <summary> /// UnionFindTree /// </summary> public class UnionFindTree { int[] Node; public UnionFindTree(int N) { Node = new int[N]; for (int i = 0; i < N; i++) { Node[i] = -1; } } public bool IsSameGroup(int x, int y) { return GetRoot(x) == GetRoot(y); } public bool Merge(int x, int y) { int xr = GetRoot(x); int yr = GetRoot(y); if (xr == yr) return false; // xが、大きなグループを示すようにSwapする(値が小さい方が大きなグループ) if (Node[xr] > Node[yr]) Swap(ref xr, ref yr); // グループの数を合算する Node[xr] += Node[yr]; // 根を張り替える Node[yr] = xr; return true; } public int Size(int x) { return -Node[GetRoot(x)]; } public int GetRoot(int n) { if (Node[n] < 0) { return n; } else { // 根を張りなおす。 Node[n] = GetRoot(Node[n]); return Node[n]; } } } /// <summary> /// PriorityQueue /// </summary> /// <typeparam name="T"></typeparam> public class PriorityQueue<T> where T : IComparable { private Comparison<T> _comparison = null; private int _type = 0; private T[] _heap; private int _sz = 0; private int _count = 0; /// <summary> /// Priority queue /// </summary> /// <param name="maxSize">max size</param> /// <param name="type">0: asc, 1:desc</param> public PriorityQueue(int maxSize, int type = 0) { _heap = new T[maxSize]; _type = type; } public PriorityQueue(int maxSize, Comparison<T> comparison) { _heap = new T[maxSize]; _comparison = comparison; } private int Compare(T x, T y) { if (_comparison != null) return _comparison(x, y); return _type == 0 ? x.CompareTo(y) : y.CompareTo(x); } public void Push(T x) { _count++; // node number var i = _sz++; while (i > 0) { // parent node number var p = (i - 1) / 2; if (Compare(_heap[p], x) <= 0) break; _heap[i] = _heap[p]; i = p; } _heap[i] = x; } public T Pop() { _count--; T ret = _heap[0]; T x = _heap[--_sz]; int i = 0; while (i * 2 + 1 < _sz) { // children int a = i * 2 + 1; int b = i * 2 + 2; if (b < _sz && Compare(_heap[b], _heap[a]) < 0) a = b; if (Compare(_heap[a], x) >= 0) break; _heap[i] = _heap[a]; i = a; } _heap[i] = x; return ret; } public int Count() { return _count; } public T Peek() { return _heap[0]; } public bool Contains(T x) { for (int i = 0; i < _sz; i++) if (x.Equals(_heap[i])) return true; return false; } public void Clear() { while (this.Count() > 0) this.Pop(); } public IEnumerator<T> GetEnumerator() { var ret = new List<T>(); while (this.Count() > 0) { ret.Add(this.Pop()); } foreach (var r in ret) { this.Push(r); yield return r; } } public T[] ToArray() { T[] array = new T[_sz]; int i = 0; foreach (var r in this) { array[i++] = r; } return array; } } #endregion }
[["-", 8, 196, 0, 197, 0, 198, 0, 200, 141, 22], ["+", 8, 196, 0, 197, 0, 198, 0, 200, 141, 22]]
8
2,910
4
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var inputs = Console.ReadLine().Split(' '); var N = int.Parse(inputs[0]); var K = long.Parse(inputs[1]); inputs = Console.ReadLine().Split(' '); var A = new long[N]; for (int i = 0; i < N; i++) { A[i] = long.Parse(inputs[i]); } const int maxDigits = 4; long X = 0; // X <= K < 2^40のため、40桁が最大 // 10^3 < 2^10 = 1024 であるため // 10^12 = (10^3)^4 < (2^10)^4 = 2^40 for (int d = maxDigits; d >= 1; d--) { // 2進数でd桁目の値の1の数を数える long mask = 1; var oneCount = 0L; var shiftBit = d - 1; var k = (K >> shiftBit) & mask; for (int i = 0; i < N; i++) { // d桁の値を取り出す var value = (A[i] >> shiftBit) & mask; oneCount += value; } byte currentBit; // 0の数が多い if (oneCount < N - oneCount) { currentBit = 1; } else { // 1の数が多い currentBit = 0; } // 上位桁から決め手いくので、左シフトして今回分を加算する long preX = X; X = (X << 1) | currentBit; // Kの上位40~d桁目まで long comp = K >> shiftBit; // Kを超えてしまった場合、強制的に0にする if (X > comp) { currentBit = 0; X = (preX << 1) | currentBit; } } var f = 0L; for (int i = 0; i < N; i++) { f += X ^ A[i]; } Console.WriteLine(f); } }
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var inputs = Console.ReadLine().Split(' '); var N = int.Parse(inputs[0]); var K = long.Parse(inputs[1]); inputs = Console.ReadLine().Split(' '); var A = new long[N]; for (int i = 0; i < N; i++) { A[i] = long.Parse(inputs[i]); } const int maxDigits = 40; long X = 0; // X <= K < 2^40のため、40桁が最大 // 10^3 < 2^10 = 1024 であるため // 10^12 = (10^3)^4 < (2^10)^4 = 2^40 for (int d = maxDigits; d >= 1; d--) { // 2進数でd桁目の値の1の数を数える long mask = 1; var oneCount = 0L; var shiftBit = d - 1; var k = (K >> shiftBit) & mask; for (int i = 0; i < N; i++) { // d桁の値を取り出す var value = (A[i] >> shiftBit) & mask; oneCount += value; } byte currentBit; // 0の数が多い if (oneCount < N - oneCount) { currentBit = 1; } else { // 1の数が多い currentBit = 0; } // 上位桁から決めるので、左シフトして今回分を加算する long preX = X; X = (X << 1) | currentBit; // Kの上位40~d桁目まで long comp = K >> shiftBit; // Kを超えてしまった場合、強制的に0にする if (X > comp) { currentBit = 0; X = (preX << 1) | currentBit; } } var f = 0L; for (int i = 0; i < N; i++) { f += X ^ A[i]; } Console.WriteLine(f); } }
[["-", 0, 197, 0, 198, 0, 200, 0, 212, 0, 203], ["+", 0, 197, 0, 198, 0, 200, 0, 212, 0, 203]]
8
331
2
using System; using System.IO; using System.Linq; namespace D { internal class Program { static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; public static void Main(string[] args) { var line = Console.ReadLine().Split().Select(ulong.Parse).ToArray(); var n = line[0]; var k = line[1]; var an = Console.ReadLine().Split().Select(ulong.Parse).ToArray(); var aMax = an.Max(); var max = Math.Max(k, aMax); var tmp = 1UL; var maxDigits = 1UL; while (true) { tmp <<= 1; if (tmp > max) { break; } maxDigits++; } var mask = 1UL << (int)(maxDigits - 1); var result = 0UL; var x = 0UL; for (var i = 0UL; i < maxDigits; i++, mask >>= 1) { var zeroNum = 0UL; var oneNum = 0UL; foreach (var a in an) { if ((mask & a) != 0) { oneNum++; } else { zeroNum++; } } if (x + 1UL << (int)(maxDigits - i - 1) > k) { result += oneNum * (1UL << (int)(maxDigits - i - 1)); continue; } var maxNum = Math.Max(zeroNum, oneNum); result += maxNum * (1UL << (int)(maxDigits - i - 1)); if (zeroNum > oneNum) { x += 1UL << (int)(maxDigits - i - 1); } } Console.WriteLine(result); } } }
using System; using System.IO; using System.Linq; namespace D { internal class Program { static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; public static void Main(string[] args) { var line = Console.ReadLine().Split().Select(ulong.Parse).ToArray(); var n = line[0]; var k = line[1]; var an = Console.ReadLine().Split().Select(ulong.Parse).ToArray(); var aMax = an.Max(); var max = Math.Max(k, aMax); var tmp = 1UL; var maxDigits = 1UL; while (true) { tmp <<= 1; if (tmp > max) { break; } maxDigits++; } var mask = 1UL << (int)(maxDigits - 1); var result = 0UL; var x = 0UL; for (var i = 0UL; i < maxDigits; i++, mask >>= 1) { var zeroNum = 0UL; var oneNum = 0UL; foreach (var a in an) { if ((mask & a) != 0) { oneNum++; } else { zeroNum++; } } if ((x | (1UL << (int)(maxDigits - i - 1))) > k) { result += oneNum * (1UL << (int)(maxDigits - i - 1)); continue; } var maxNum = Math.Max(zeroNum, oneNum); result += maxNum * (1UL << (int)(maxDigits - i - 1)); if (zeroNum > oneNum) { x += 1UL << (int)(maxDigits - i - 1); } } Console.WriteLine(result); } } }
[["+", 8, 196, 0, 57, 15, 16, 31, 23, 0, 24], ["-", 0, 57, 15, 16, 31, 16, 31, 16, 17, 72], ["+", 0, 57, 15, 16, 31, 23, 0, 16, 17, 139], ["+", 15, 16, 31, 23, 0, 16, 12, 23, 0, 24], ["+", 12, 23, 0, 16, 12, 74, 51, 23, 0, 25], ["+", 15, 16, 31, 23, 0, 16, 12, 23, 0, 25]]
8
358
6
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AtCoderA { static void Main() { var sc = new Scanner(); long n = sc.NextLong(); long a = sc.NextLong(); long b = sc.NextLong(); long max = Math.Max(a, b); long min = Math.Max(0, a + b - n); string answer = max + " " + min; Console.WriteLine(answer); } class Scanner { private string[] _line; private int _index; private const char Separator = ' '; public Scanner() { _line = new string[0]; _index = 0; } public string Next() { while (_index >= _line.Length) { _line = Console.ReadLine().Split(Separator); _index = 0; } return _line[_index++]; } public int NextInt() => int.Parse(Next()); public long NextLong() => long.Parse(Next()); public double NextDouble() => double.Parse(Next()); public decimal NextDecimal() => decimal.Parse(Next()); public char NextChar() => Next()[0]; public char[] NextCharArray() => Next().ToCharArray(); public string[] Array() { _line = Console.ReadLine().Split(Separator); _index = _line.Length; return _line; } public int[] IntArray() => Array().Select(int.Parse).ToArray(); public long[] LongArray() => Array().Select(long.Parse).ToArray(); public double[] DoubleArray() => Array().Select(double.Parse).ToArray(); public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AtCoderA { static void Main() { var sc = new Scanner(); long n = sc.NextLong(); long a = sc.NextLong(); long b = sc.NextLong(); long max = Math.Min(a, b); long min = Math.Max(0, a + b - n); string answer = max + " " + min; Console.WriteLine(answer); } class Scanner { private string[] _line; private int _index; private const char Separator = ' '; public Scanner() { _line = new string[0]; _index = 0; } public string Next() { while (_index >= _line.Length) { _line = Console.ReadLine().Split(Separator); _index = 0; } return _line[_index++]; } public int NextInt() => int.Parse(Next()); public long NextLong() => long.Parse(Next()); public double NextDouble() => double.Parse(Next()); public decimal NextDecimal() => decimal.Parse(Next()); public char NextChar() => Next()[0]; public char[] NextCharArray() => Next().ToCharArray(); public string[] Array() { _line = Console.ReadLine().Split(Separator); _index = _line.Length; return _line; } public int[] IntArray() => Array().Select(int.Parse).ToArray(); public long[] LongArray() => Array().Select(long.Parse).ToArray(); public double[] DoubleArray() => Array().Select(double.Parse).ToArray(); public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray(); } }
[["-", 0, 200, 0, 212, 0, 213, 63, 214, 141, 22], ["+", 0, 200, 0, 212, 0, 213, 63, 214, 141, 22]]
8
407
2
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Numerics; using System.IO; using System.Runtime.InteropServices; using static System.Math; using static Math2; using static io; using static Utils; public class CompetitiveProgramming { public void Solve() { var N = Int1; var A = Str; var B = Str; var C = Str; int ans = 0; for (int i = 0; i < A.Length; ++i) { if (A[i] == B[i] && B[i] == C[i]) continue; else if (A[i] == B[i] || B[i] == C[i] && A[i] == C[i]) ++ans; else ans += 2; } Write(ans); } } public static class Math2 { public const int INF = 1 << 29; public const long INFL = 1L << 60; public const int MOD = 1000000007; public const int MOD2 = 998244353; public static long Pow(long i, long N, long MOD = 1000000007) { long res = 1; while (N > 0) { if ((N & 1) != 0) res = res * i % MOD; i = i * i % MOD; N >>= 1; } return res; } public static long GCD(long i, long N) { if (i > N) Swap(ref i, ref N); if (i == 0) return N; while (N != 0) { var r = i % N; i = N; N = r; } return i; } public static long LCM(long i, long N) => i * N / GCD(i, N); public static long Comb(long N, long R, int MOD = 1000000007) { long ret = 1; long x = 1; for (long i = N; i >= N - R + 1; --i) { ret = ret / x * i; ret %= MOD; x++; } return ret; } public static long Comb2(long N, long R) { long Nume = 1; long Deno = 1; if (R > N - R) Swap(ref N, ref R); for (long i = 1; i <= R; ++i) { Deno *= i; Nume *= N - i + 1; } return Deno / Nume; } public static Dictionary<long, int> PrimeFactorization(long N) { var ret = new Dictionary<long, int>(); for (long i = 2; i * i <= N; ++i) { int cnt = 0; while (N % i == 0) { cnt++; N /= i; } if (cnt != 0) ret[i] = cnt; } if (N >= 2) ret[N] = 1; return ret; } public static List<long> DivisorEnumrate(long N) { var ret = new List<long>(); for (long i = 1; i * i <= N; ++i) { if (N % i == 0) { ret.Add(i); ret.Add(N / i); } } return ret; } } public static class Utils { public static void Swap<T>(ref T A, ref T B) { T x = A; A = B; B = x; } public static int DigitSum(int N) { string s = N.ToString(); int ret = 0; for (int i = 0; i < s.Length; ++i) ret += s[i] - '0'; return ret; } } class Program { static void Main(string[] args) { var CompetitiveProgramming = new CompetitiveProgramming(); CompetitiveProgramming.Solve(); } } public static class io { public static string Str => Console.ReadLine(); public static string[] Strs => Str.Split(' '); public static long[] Longs => Strs.Select(long.Parse).ToArray(); public static int[] Ints => Strs.Select(int.Parse).ToArray(); public static char[] Chars => Str.ToArray(); public static double[] Doubles => Strs.Select(double.Parse).ToArray(); public static long Long1 => Longs[0]; public static int Int1 => Ints[0]; public static char Char1 => Chars[0]; public static double Double1 => Doubles[0]; public static long[] HorizontalRead(int N) { long[] A = new long[N]; for (int i = 0; i < N; ++i) A[i] = Long1; return A; } public static void Write(string a) => Console.WriteLine(a); public static void Write(params object[] i) => Write(string.Join(" ", i)); public static void Write<T>(IEnumerable<T> a) => Write(string.Join(" ", a)); public static void Horizontalwrite<T>(IEnumerable<T> a) { foreach (var z in a) Write(z); } public static void YN(bool i) { if (i) Write("Yes"); else Write("No"); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Numerics; using System.IO; using System.Runtime.InteropServices; using static System.Math; using static Math2; using static io; using static Utils; public class CompetitiveProgramming { public void Solve() { var N = Int1; var A = Str; var B = Str; var C = Str; int ans = 0; for (int i = 0; i < A.Length; ++i) { if (A[i] == B[i] && B[i] == C[i]) continue; else if (A[i] == B[i] || B[i] == C[i] || A[i] == C[i]) ++ans; else ans += 2; } Write(ans); } } public static class Math2 { public const int INF = 1 << 29; public const long INFL = 1L << 60; public const int MOD = 1000000007; public const int MOD2 = 998244353; public static long Pow(long i, long N, long MOD = 1000000007) { long res = 1; while (N > 0) { if ((N & 1) != 0) res = res * i % MOD; i = i * i % MOD; N >>= 1; } return res; } public static long GCD(long i, long N) { if (i > N) Swap(ref i, ref N); if (i == 0) return N; while (N != 0) { var r = i % N; i = N; N = r; } return i; } public static long LCM(long i, long N) => i * N / GCD(i, N); public static long Comb(long N, long R, int MOD = 1000000007) { long ret = 1; long x = 1; for (long i = N; i >= N - R + 1; --i) { ret = ret / x * i; ret %= MOD; x++; } return ret; } public static long Comb2(long N, long R) { long Nume = 1; long Deno = 1; if (R > N - R) Swap(ref N, ref R); for (long i = 1; i <= R; ++i) { Deno *= i; Nume *= N - i + 1; } return Deno / Nume; } public static Dictionary<long, int> PrimeFactorization(long N) { var ret = new Dictionary<long, int>(); for (long i = 2; i * i <= N; ++i) { int cnt = 0; while (N % i == 0) { cnt++; N /= i; } if (cnt != 0) ret[i] = cnt; } if (N >= 2) ret[N] = 1; return ret; } public static List<long> DivisorEnumrate(long N) { var ret = new List<long>(); for (long i = 1; i * i <= N; ++i) { if (N % i == 0) { ret.Add(i); ret.Add(N / i); } } return ret; } } public static class Utils { public static void Swap<T>(ref T A, ref T B) { T x = A; A = B; B = x; } public static int DigitSum(int N) { string s = N.ToString(); int ret = 0; for (int i = 0; i < s.Length; ++i) ret += s[i] - '0'; return ret; } } class Program { static void Main(string[] args) { var CompetitiveProgramming = new CompetitiveProgramming(); CompetitiveProgramming.Solve(); } } public static class io { public static string Str => Console.ReadLine(); public static string[] Strs => Str.Split(' '); public static long[] Longs => Strs.Select(long.Parse).ToArray(); public static int[] Ints => Strs.Select(int.Parse).ToArray(); public static char[] Chars => Str.ToArray(); public static double[] Doubles => Strs.Select(double.Parse).ToArray(); public static long Long1 => Longs[0]; public static int Int1 => Ints[0]; public static char Char1 => Chars[0]; public static double Double1 => Doubles[0]; public static long[] HorizontalRead(int N) { long[] A = new long[N]; for (int i = 0; i < N; ++i) A[i] = Long1; return A; } public static void Write(string a) => Console.WriteLine(a); public static void Write(params object[] i) => Write(string.Join(" ", i)); public static void Write<T>(IEnumerable<T> a) => Write(string.Join(" ", a)); public static void Horizontalwrite<T>(IEnumerable<T> a) { foreach (var z in a) Write(z); } public static void YN(bool i) { if (i) Write("Yes"); else Write("No"); } }
[["-", 0, 57, 75, 57, 15, 16, 12, 16, 17, 98], ["+", 8, 196, 0, 57, 75, 57, 15, 16, 17, 106]]
8
1,140
2
using System; class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string a = Console.ReadLine(); string b = Console.ReadLine(); string c = Console.ReadLine(); int count = 0; for (int i = 0; i < n; i++) { if (a.Substring(i, 1) == b.Substring(i, 1) && b.Substring(i, 1) == c.Substring(i, 1)) { } else if (a.Substring(i, 1) == b.Substring(i, 1) && b.Substring(i, 1) != c.Substring(i, 1)) { count++; } else if (a.Substring(i, 1) == c.Substring(i, 1) && b.Substring(i, 1) != c.Substring(i, 1)) { count++; } else if (b.Substring(i, 1) == c.Substring(i, 1) && a.Substring(i, 1) != b.Substring(i, 1)) { count++; } else { count = count + 2; } } Console.WriteLine(); } }
using System; class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string a = Console.ReadLine(); string b = Console.ReadLine(); string c = Console.ReadLine(); int count = 0; for (int i = 0; i < n; i++) { if (a.Substring(i, 1) == b.Substring(i, 1) && b.Substring(i, 1) == c.Substring(i, 1)) { } else if (a.Substring(i, 1) == b.Substring(i, 1) && b.Substring(i, 1) != c.Substring(i, 1)) { count++; } else if (a.Substring(i, 1) == c.Substring(i, 1) && b.Substring(i, 1) != c.Substring(i, 1)) { count++; } else if (b.Substring(i, 1) == c.Substring(i, 1) && a.Substring(i, 1) != b.Substring(i, 1)) { count++; } else { count = count + 2; } } Console.WriteLine(count); } }
[["+", 0, 1, 0, 213, 3, 4, 0, 28, 0, 22]]
8
267
1
using System; using System.Text; using System.Collections.Generic; using System.Collections; using System.Linq; using E = System.Linq.Enumerable; class Program { static char[] abc = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); static long mod = 1000000007; static void Main(string[] args) { var N = long.Parse(Console.ReadLine()); var A = new long[N]; var B = new long[N]; var dic = new SortedDictionary<int, long>(); for (int i = 0; i < N; i++) { var inp = Console.ReadLine().Split(' ').Select(x => long.Parse(x)).ToArray(); A[i] = inp[0]; B[i] = inp[1]; dic.Add(i, A[i] + B[i]); } var count = 0; long ans = 0; foreach (var item in dic.OrderBy((x) => x.Value)) { if (count % 2 == 0) { ans += A[item.Key]; } else { ans -= B[item.Key]; } count++; } Console.WriteLine(ans); } }
using System; using System.Text; using System.Collections.Generic; using System.Collections; using System.Linq; using E = System.Linq.Enumerable; class Program { static char[] abc = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); static long mod = 1000000007; static void Main(string[] args) { var N = long.Parse(Console.ReadLine()); var A = new long[N]; var B = new long[N]; var dic = new SortedDictionary<int, long>(); for (int i = 0; i < N; i++) { var inp = Console.ReadLine().Split(' ').Select(x => long.Parse(x)).ToArray(); A[i] = inp[0]; B[i] = inp[1]; dic.Add(i, A[i] + B[i]); } var count = 0; long ans = 0; foreach (var item in dic.OrderByDescending((x) => x.Value)) { if (count % 2 == 0) { ans += A[item.Key]; } else { ans -= B[item.Key]; } count++; } Console.WriteLine(ans); } }
[["-", 8, 196, 0, 210, 12, 213, 63, 214, 141, 22], ["+", 8, 196, 0, 210, 12, 213, 63, 214, 141, 22]]
8
270
2
using System; using System.Collections.Generic; using System.IO; using System.Linq; using static System.Math; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; using Library; namespace Program { public static class ProblemA { static bool SAIKI = false; static public int numberOfRandomCases = 0; static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker) {} static public void Solve() { var N = NN; var ABList = Repeat(0, N).Select(_ => new { A = NN, B = NN }).ToArray(); var ans = 0L; var flip = true; foreach (var item in ABList.OrderBy(e => e.A + e.B)) { if (flip) ans += item.A; else ans -= item.B; flip = !flip; } Console.WriteLine(ans); } class Printer : StreamWriter { public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } } public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; } public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; } } static LIB_FastIO fastio = new LIB_FastIODebug(); static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); } static long NN => fastio.Long(); static double ND => fastio.Double(); static string NS => fastio.Scan(); static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray(); static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray(); static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray(); static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred); static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n); static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c); static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift); static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e); static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector); static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e); static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector); static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase); static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } } static IEnumerator<uint> _xsi = _xsc(); static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } } } } namespace Library { class LIB_FastIO { public LIB_FastIO() { str = Console.OpenStandardInput(); } readonly Stream str; readonly byte[] buf = new byte[1024]; int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } byte read() { if (isEof) throw new EndOfStreamException(); if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } char Char() { byte b = 0; do b = read(); while (b < 33 || 126 < b); return (char)b; } virtual public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } virtual public long Long() { long ret = 0; byte b = 0; var ng = false; do b = read(); while (b != '-' && (b < '0' || '9' < b)); if (b == '-') { ng = true; b = read(); } for (; true; b = read()) { if (b < '0' || '9' < b) return ng ? -ret : ret; else ret = ret * 10 + b - '0'; } } virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); } } class LIB_FastIODebug : LIB_FastIO { Queue<string> param = new Queue<string>(); string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); } public LIB_FastIODebug() {} public override string Scan() => NextString(); public override long Long() => long.Parse(NextString()); public override double Double() => double.Parse(NextString()); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using static System.Math; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; using Library; namespace Program { public static class ProblemA { static bool SAIKI = false; static public int numberOfRandomCases = 0; static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker) {} static public void Solve() { var N = NN; var ABList = Repeat(0, N).Select(_ => new { A = NN, B = NN }).ToArray(); var ans = 0L; var flip = true; foreach (var item in ABList.OrderByDescending(e => e.A + e.B)) { if (flip) ans += item.A; else ans -= item.B; flip = !flip; } Console.WriteLine(ans); } class Printer : StreamWriter { public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } } public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; } public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; } } static LIB_FastIO fastio = new LIB_FastIODebug(); static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); } static long NN => fastio.Long(); static double ND => fastio.Double(); static string NS => fastio.Scan(); static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray(); static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray(); static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray(); static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred); static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n); static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c); static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift); static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e); static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector); static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e); static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector); static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase); static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } } static IEnumerator<uint> _xsi = _xsc(); static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } } } } namespace Library { class LIB_FastIO { public LIB_FastIO() { str = Console.OpenStandardInput(); } readonly Stream str; readonly byte[] buf = new byte[1024]; int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } byte read() { if (isEof) throw new EndOfStreamException(); if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } char Char() { byte b = 0; do b = read(); while (b < 33 || 126 < b); return (char)b; } virtual public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } virtual public long Long() { long ret = 0; byte b = 0; var ng = false; do b = read(); while (b != '-' && (b < '0' || '9' < b)); if (b == '-') { ng = true; b = read(); } for (; true; b = read()) { if (b < '0' || '9' < b) return ng ? -ret : ret; else ret = ret * 10 + b - '0'; } } virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); } } class LIB_FastIODebug : LIB_FastIO { Queue<string> param = new Queue<string>(); string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); } public LIB_FastIODebug() {} public override string Scan() => NextString(); public override long Long() => long.Parse(NextString()); public override double Double() => double.Parse(NextString()); } }
[["-", 8, 196, 0, 210, 12, 213, 63, 214, 141, 22], ["+", 8, 196, 0, 210, 12, 213, 63, 214, 141, 22]]
8
1,499
2
using Training20200612.Questions; using Training20200612.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Training20200612.Questions { public class QuestionA : AtCoderQuestionBase { public override IEnumerable<object> Solve(TextReader inputStream) { var n = inputStream.ReadInt(); var dishes = new Dish[n]; for (int i = 0; i < n; i++) { var ab = inputStream.ReadIntArray(); dishes[i] = new Dish(ab[0], ab[1]); } Array.Sort(dishes); long advantage = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) { advantage += dishes[i].Takahashi; } else { advantage -= dishes[i].Aoki; } } yield return advantage; } struct Dish : IComparable<Dish> { public long Takahashi { get; } public long Aoki { get; } public Dish(long takahashi, long aoki) { Takahashi = takahashi; Aoki = aoki; } public int CompareTo(Dish other) => -(Takahashi - Aoki).CompareTo(other.Takahashi - other.Aoki); } } } namespace Training20200612 { class Program { static void Main(string[] args) { IAtCoderQuestion question = new QuestionA(); // 問題に合わせて書き換え var answers = question.Solve(Console.In); foreach (var answer in answers) { Console.WriteLine(answer); } } } } #region Base Classes namespace Training20200612.Questions { public interface IAtCoderQuestion { IEnumerable<object> Solve(string input); IEnumerable<object> Solve(TextReader inputStream); } public abstract class AtCoderQuestionBase : IAtCoderQuestion { public IEnumerable<object> Solve(string input) { var stream = new MemoryStream(Encoding.Unicode.GetBytes(input)); var reader = new StreamReader(stream, Encoding.Unicode); return Solve(reader); } public abstract IEnumerable<object> Solve(TextReader inputStream); } } #endregion #region Extensions namespace Training20200612.Extensions { internal static class TextReaderExtensions { internal static int ReadInt(this TextReader reader) => int.Parse(ReadString(reader)); internal static long ReadLong(this TextReader reader) => long.Parse(ReadString(reader)); internal static double ReadDouble(this TextReader reader) => double.Parse(ReadString(reader)); internal static string ReadString(this TextReader reader) => reader.ReadLine(); internal static int[] ReadIntArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(int.Parse).ToArray(); internal static long[] ReadLongArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(long.Parse).ToArray(); internal static double[] ReadDoubleArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(double.Parse).ToArray(); internal static string[] ReadStringArray(this TextReader reader, char separator = ' ') => reader.ReadLine().Split(separator); } } #endregion
using Training20200612.Questions; using Training20200612.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Training20200612.Questions { public class QuestionA : AtCoderQuestionBase { public override IEnumerable<object> Solve(TextReader inputStream) { var n = inputStream.ReadInt(); var dishes = new Dish[n]; for (int i = 0; i < n; i++) { var ab = inputStream.ReadIntArray(); dishes[i] = new Dish(ab[0], ab[1]); } Array.Sort(dishes); long advantage = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) { advantage += dishes[i].Takahashi; } else { advantage -= dishes[i].Aoki; } } yield return advantage; } struct Dish : IComparable<Dish> { public long Takahashi { get; } public long Aoki { get; } public Dish(long takahashi, long aoki) { Takahashi = takahashi; Aoki = aoki; } public int CompareTo(Dish other) => -(Takahashi + Aoki).CompareTo(other.Takahashi + other.Aoki); } } } namespace Training20200612 { class Program { static void Main(string[] args) { IAtCoderQuestion question = new QuestionA(); // 問題に合わせて書き換え var answers = question.Solve(Console.In); foreach (var answer in answers) { Console.WriteLine(answer); } } } } #region Base Classes namespace Training20200612.Questions { public interface IAtCoderQuestion { IEnumerable<object> Solve(string input); IEnumerable<object> Solve(TextReader inputStream); } public abstract class AtCoderQuestionBase : IAtCoderQuestion { public IEnumerable<object> Solve(string input) { var stream = new MemoryStream(Encoding.Unicode.GetBytes(input)); var reader = new StreamReader(stream, Encoding.Unicode); return Solve(reader); } public abstract IEnumerable<object> Solve(TextReader inputStream); } } #endregion #region Extensions namespace Training20200612.Extensions { internal static class TextReaderExtensions { internal static int ReadInt(this TextReader reader) => int.Parse(ReadString(reader)); internal static long ReadLong(this TextReader reader) => long.Parse(ReadString(reader)); internal static double ReadDouble(this TextReader reader) => double.Parse(ReadString(reader)); internal static string ReadString(this TextReader reader) => reader.ReadLine(); internal static int[] ReadIntArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(int.Parse).ToArray(); internal static long[] ReadLongArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(long.Parse).ToArray(); internal static double[] ReadDoubleArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(double.Parse).ToArray(); internal static string[] ReadStringArray(this TextReader reader, char separator = ' ') => reader.ReadLine().Split(separator); } } #endregion
[["-", 0, 213, 63, 214, 205, 23, 0, 16, 17, 33], ["+", 0, 213, 63, 214, 205, 23, 0, 16, 17, 72], ["-", 0, 213, 3, 4, 0, 28, 0, 16, 17, 33], ["+", 0, 213, 3, 4, 0, 28, 0, 16, 17, 72]]
8
647
4
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Atcoder { class Program { public struct cuisine { public int takahashi; public int aoki; public int takahashi_gain; public cuisine(string input) { var split = input.Split().Select(int.Parse).ToArray(); this.takahashi = split[0]; this.aoki = split[1]; this.takahashi_gain = this.aoki - this.takahashi; } } static void Main(string[] args) { int N = int.Parse(Console.ReadLine()); cuisine[] cuisines = new cuisine[N]; for (int i = 0; i < N; i++) { cuisines[i] = new cuisine(Console.ReadLine()); } //準備完了 Array.Sort(cuisines, compare); //先行が食べる数 long output = 0; for (int i = 0; i < N; i++) { if (i % 2 == 0) { output += cuisines[i].takahashi; } else { output -= cuisines[i].aoki; } } Console.WriteLine(output); } public static int compare(cuisine x, cuisine y) { if (x.takahashi_gain > y.takahashi_gain) { return -1; } else if (x.takahashi_gain < y.takahashi_gain) { return 1; } else { if (x.takahashi > y.takahashi) return -1; else if (x.takahashi < y.takahashi) return 1; else return 0; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Atcoder { class Program { public struct cuisine { public int takahashi; public int aoki; public int takahashi_gain; public cuisine(string input) { var split = input.Split().Select(int.Parse).ToArray(); this.takahashi = split[0]; this.aoki = split[1]; this.takahashi_gain = this.aoki + this.takahashi; } } static void Main(string[] args) { int N = int.Parse(Console.ReadLine()); cuisine[] cuisines = new cuisine[N]; for (int i = 0; i < N; i++) { cuisines[i] = new cuisine(Console.ReadLine()); } //準備完了 Array.Sort(cuisines, compare); //先行が食べる数 long output = 0; for (int i = 0; i < N; i++) { if (i % 2 == 0) { output += cuisines[i].takahashi; } else { output -= cuisines[i].aoki; } } Console.WriteLine(output); } public static int compare(cuisine x, cuisine y) { if (x.takahashi_gain > y.takahashi_gain) { return -1; } else if (x.takahashi_gain < y.takahashi_gain) { return 1; } else { if (x.takahashi > y.takahashi) return -1; else if (x.takahashi < y.takahashi) return 1; else return 0; } } } }
[["-", 8, 196, 0, 1, 0, 11, 12, 16, 17, 33], ["+", 8, 196, 0, 1, 0, 11, 12, 16, 17, 72]]
8
332
2
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using static System.Math; public static class P { public static void Main() { int n = int.Parse(Console.ReadLine()); var dishes = Enumerable.Repeat(0, n) .Select(_ => Console.ReadLine().Split().Select(long.Parse).ToArray()) .OrderBy(x => x.Sum()) .ToArray(); Console.WriteLine(dishes.Where((_, ind) => ind % 2 == 0).Sum(x => x[0]) - dishes.Where((_, ind) => ind % 2 == 1).Sum(x => x[1])); } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using static System.Math; public static class P { public static void Main() { int n = int.Parse(Console.ReadLine()); var dishes = Enumerable.Repeat(0, n) .Select(_ => Console.ReadLine().Split().Select(long.Parse).ToArray()) .OrderByDescending(x => x.Sum()) .ToArray(); Console.WriteLine(dishes.Where((_, ind) => ind % 2 == 0).Sum(x => x[0]) - dishes.Where((_, ind) => ind % 2 == 1).Sum(x => x[1])); } }
[["-", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22], ["+", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22]]
8
200
2
using System; using System.Collections.Generic; using System.Linq; using System.Text; // using System.Numerics; using System.Runtime.CompilerServices; using System.Diagnostics; using ll=System.Int64; using static Contest_C.Lib_IO; using static Contest_C.Lib_Minifunc; public class Contest_C { public static void Main() { checked{ long n; Lib_IO.rm(out n); P<ll,ll>[] abl; rl(n,out abl); Array.Sort(abl,(x,y)=>(y.A+x.A).CompareTo(x.A+y.A)); ll ans = 0; for (int i = 0; i < n; i++) { if(i%2==0) ans+=abl[i].A; if(i%2==1) ans-=abl[i].B; } Lib_IO.wm(ans); } } #region BaseModule public static class Lib_Minifunc{ [MethodImpl(256)] public static void swap1<T>(ref T a, ref T b) { T t = a; a = b; b = t; } [MethodImpl(256)] public static void swap2<T>(ref T a, ref T b) where T : IComparable { if (a.CompareTo(b)==1) swap1(ref a, ref b); } // b の方が小さければ交換 [MethodImpl(256)] public static bool chmin<T>(ref T a, T b) where T : IComparable { if (a.CompareTo(b)== 1) { a = b; return true; } return false; } // b の方が小さければ a を更新 [MethodImpl(256)] public static bool chmax<T>(ref T a, T b) where T : IComparable { if (a.CompareTo(b)==-1) { a = b; return true; } return false; } // b の方が大きければ a を更新 [MethodImpl(256)] public static bool inside(long i, long n) => (0<=i&&i<n); [MethodImpl(256)] public static bool inside(long x, long y, long w, long h) => (inside(x,w)&&inside(y,h)); [MethodImpl(256)] public static T min<T>(params T[] a) where T : IComparable => a.Min(); [MethodImpl(256)] public static T max<T>(params T[] a) where T : IComparable => a.Max(); [MethodImpl(256)] public static long mod(long a, long m=MOD1) { var v = a%m; return (v<0?v+m:v); } [MethodImpl(256)] public static long ceiling(long a, long b) => (a%b==0?a/b:a/b+1); // 整数商の切り上げ [MethodImpl(256)] public static P<T,U> initp<T,U>(T a,U b) => new P<T,U>(a,b); [MethodImpl(256)] public static P<T,U,V> initp<T,U,V>(T a,U b,V c) => new P<T,U,V>(a,b,c); [MethodImpl(256)] public static P<T,U,V,W> initp<T,U,V,W>(T a,U b,V c,W d) => new P<T,U,V,W>(a,b,c,d); public static T[][] initm<T>(long len1,long len2,T val) where T : struct { var m = new T[len1][]; for (int i=0;i<m.Length;i++) m[i] = Enumerable.Repeat(val,(int)len2).ToArray(); return m; } public static T[][][] initm<T>(long len1,long len2,long len3,T val) where T : struct { var m = new T[len1][][]; for (int i=0;i<m.Length;i++) m[i] = initm(len2,len3,val); return m; } public const long MOD1 = 1000000007; // 10^9+7 public const double EPS1 = 1e-8; public const long INF1 = 1000000000000000; // 10^15 } public struct P<T,U> { public T A; public U B; public P(T a,U b) { A = a; B = b; } public static implicit operator KeyValuePair<T,U>(P<T,U> a) => new KeyValuePair<T,U>(a.A,a.B); public static implicit operator P<T,U>(KeyValuePair<T,U> a) => new P<T,U>(a.Key,a.Value); } public struct P<T,U,V> { public T A; public U B; public V C; public P(T a,U b,V c) { A = a; B = b; C = c; } } public struct P<T,U,V,W> { public T A; public U B; public V C; public W D; public P(T a,U b,V c,W d) { A = a; B = b; C = c; D = d; } } public static class Lib_IO { class Prt : System.IO.StreamWriter { public override IFormatProvider FormatProvider { get { return System.Globalization.CultureInfo.InvariantCulture; } } public Prt(System.IO.Stream s) : base(s,new UTF8Encoding(false,true)) {} public Prt(System.IO.Stream s,Encoding e) : base(s,e) {} } static Prt sw = new Prt(Console.OpenStandardOutput()); static char[] sp = new char[] {' '}; [MethodImpl(256)] static bool eq<T,U>() => typeof(T).Equals(typeof(U)); [MethodImpl(256)] static T ct<T,U>(U a) => (T)Convert.ChangeType(a,typeof(T)); [MethodImpl(256)] static T cv<T>(string s) => eq<T,int>() ? ct<T,int>(int.Parse(s)) : eq<T,long>() ? ct<T,long>(long.Parse(s)) : eq<T,double>() ? ct<T,double>(double.Parse(s,System.Globalization.CultureInfo.InvariantCulture)) : eq<T,char>() ? ct<T,char>(s[0]) : ct<T,string>(s); public static string[] rm<T>(out T a) { var z = Console.ReadLine().Split(sp,StringSplitOptions.RemoveEmptyEntries); a = cv<T>(z[0]); return z; } public static string[] rm<T,U>(out T a,out U b) { var z = rm<T>(out a); b = cv<U>(z[1]); return z; } public static string[] rm<T,U,V>(out T a,out U b,out V c) { var z = rm<T,U>(out a,out b); c = cv<V>(z[2]); return z; } public static string[] rm<T,U,V,W>(out T a,out U b,out V c,out W d) { var z = rm<T,U,V>(out a,out b,out c); d = cv<W>(z[3]); return z; } public static string[] rm<T,U,V,W,X>(out T a,out U b,out V c,out W d,out X e) { var z = rm<T,U,V,W>(out a,out b,out c,out d); e = cv<X>(z[4]); return z; } public static string[] rm<T,U,V,W,X,Y>(out T a,out U b,out V c,out W d,out X e,out Y f) { var z = rm<T,U,V,W,X>(out a,out b,out c,out d,out e); f = cv<Y>(z[5]); return z; } public static string[] ra<T>(out T[] a) { var z = Console.ReadLine().Split(sp,StringSplitOptions.RemoveEmptyEntries); a = z.Select(cv<T>).ToArray(); return z; } public static string[][] rl<T>(long n,out T[] a) { a = new T[n]; var y = new string[n][]; for(int i=0;i<n;i++) y[i] = rm(out a[i]); return y; } public static string[][] rl<T,U>(long n,out P<T,U>[] a) { a = new P<T,U>[n]; var y = new string[n][]; for(int i=0;i<n;i++) { T o; U p; y[i] = rm(out o,out p); a[i] = new P<T,U>(o,p); } return y; } public static string[][] rl<T,U,V>(long n,out P<T,U,V>[] a) { a = new P<T,U,V>[n]; var y = new string[n][]; for(int i=0;i<n;i++) { T o; U p; V q; y[i] = rm(out o,out p,out q); a[i] = new P<T,U,V>(o,p,q); } return y; } public static string[][] rl<T,U,V,W>(long n,out P<T,U,V,W>[] a) { a = new P<T,U,V,W>[n]; var y = new string[n][]; for(int i=0;i<n;i++) { T o; U p; V q; W r; y[i] = rm(out o,out p,out q,out r); a[i] = new P<T,U,V,W>(o,p,q,r); } return y; } public static string[][] rx<T>(long n,out T[][] a) { a = new T[n][]; var y = new string[n][]; for(int i=0;i<n;i++) y[i] = ra(out a[i]); return y; } static void wwp(Action act){ sw.AutoFlush = false; Console.SetOut(sw); act(); Console.Out.Flush(); sw.AutoFlush = true; Console.SetOut(sw); } [MethodImpl(256)] static string wfm(Type t) =>t.Equals(typeof(double)) ? "{0:F10}" : "{0}"; public static void wm(params object[] a) { wwp(()=>{ for(int i=0;i<a.Length;i++) { var f = wfm(a[i].GetType()) + ((i<a.Length-1) ? " " : Environment.NewLine); Console.Write(f,a[i]); } }); } public static void wa<T>(IList<T> a) { wwp(()=>{ var f = wfm(typeof(T)); var g = f + " "; var h = f + Environment.NewLine; for(int i=0;i<a.Count;i++) Console.Write(((i<a.Count-1) ? g : h),a[i]); }); } public static void wl<T>(IList<T> a) { wwp(()=>{ var f = wfm(typeof(T)) + Environment.NewLine; foreach(T x in a) Console.Write(f,x); }); } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Text; // using System.Numerics; using System.Runtime.CompilerServices; using System.Diagnostics; using ll=System.Int64; using static Contest_C.Lib_IO; using static Contest_C.Lib_Minifunc; public class Contest_C { public static void Main() { checked{ long n; Lib_IO.rm(out n); P<ll,ll>[] abl; rl(n,out abl); Array.Sort(abl,(x,y)=>(y.A+y.B).CompareTo(x.A+x.B)); ll ans = 0; for (int i = 0; i < n; i++) { if(i%2==0) ans+=abl[i].A; if(i%2==1) ans-=abl[i].B; } Lib_IO.wm(ans); } } #region BaseModule public static class Lib_Minifunc{ [MethodImpl(256)] public static void swap1<T>(ref T a, ref T b) { T t = a; a = b; b = t; } [MethodImpl(256)] public static void swap2<T>(ref T a, ref T b) where T : IComparable { if (a.CompareTo(b)==1) swap1(ref a, ref b); } // b の方が小さければ交換 [MethodImpl(256)] public static bool chmin<T>(ref T a, T b) where T : IComparable { if (a.CompareTo(b)== 1) { a = b; return true; } return false; } // b の方が小さければ a を更新 [MethodImpl(256)] public static bool chmax<T>(ref T a, T b) where T : IComparable { if (a.CompareTo(b)==-1) { a = b; return true; } return false; } // b の方が大きければ a を更新 [MethodImpl(256)] public static bool inside(long i, long n) => (0<=i&&i<n); [MethodImpl(256)] public static bool inside(long x, long y, long w, long h) => (inside(x,w)&&inside(y,h)); [MethodImpl(256)] public static T min<T>(params T[] a) where T : IComparable => a.Min(); [MethodImpl(256)] public static T max<T>(params T[] a) where T : IComparable => a.Max(); [MethodImpl(256)] public static long mod(long a, long m=MOD1) { var v = a%m; return (v<0?v+m:v); } [MethodImpl(256)] public static long ceiling(long a, long b) => (a%b==0?a/b:a/b+1); // 整数商の切り上げ [MethodImpl(256)] public static P<T,U> initp<T,U>(T a,U b) => new P<T,U>(a,b); [MethodImpl(256)] public static P<T,U,V> initp<T,U,V>(T a,U b,V c) => new P<T,U,V>(a,b,c); [MethodImpl(256)] public static P<T,U,V,W> initp<T,U,V,W>(T a,U b,V c,W d) => new P<T,U,V,W>(a,b,c,d); public static T[][] initm<T>(long len1,long len2,T val) where T : struct { var m = new T[len1][]; for (int i=0;i<m.Length;i++) m[i] = Enumerable.Repeat(val,(int)len2).ToArray(); return m; } public static T[][][] initm<T>(long len1,long len2,long len3,T val) where T : struct { var m = new T[len1][][]; for (int i=0;i<m.Length;i++) m[i] = initm(len2,len3,val); return m; } public const long MOD1 = 1000000007; // 10^9+7 public const double EPS1 = 1e-8; public const long INF1 = 1000000000000000; // 10^15 } public struct P<T,U> { public T A; public U B; public P(T a,U b) { A = a; B = b; } public static implicit operator KeyValuePair<T,U>(P<T,U> a) => new KeyValuePair<T,U>(a.A,a.B); public static implicit operator P<T,U>(KeyValuePair<T,U> a) => new P<T,U>(a.Key,a.Value); } public struct P<T,U,V> { public T A; public U B; public V C; public P(T a,U b,V c) { A = a; B = b; C = c; } } public struct P<T,U,V,W> { public T A; public U B; public V C; public W D; public P(T a,U b,V c,W d) { A = a; B = b; C = c; D = d; } } public static class Lib_IO { class Prt : System.IO.StreamWriter { public override IFormatProvider FormatProvider { get { return System.Globalization.CultureInfo.InvariantCulture; } } public Prt(System.IO.Stream s) : base(s,new UTF8Encoding(false,true)) {} public Prt(System.IO.Stream s,Encoding e) : base(s,e) {} } static Prt sw = new Prt(Console.OpenStandardOutput()); static char[] sp = new char[] {' '}; [MethodImpl(256)] static bool eq<T,U>() => typeof(T).Equals(typeof(U)); [MethodImpl(256)] static T ct<T,U>(U a) => (T)Convert.ChangeType(a,typeof(T)); [MethodImpl(256)] static T cv<T>(string s) => eq<T,int>() ? ct<T,int>(int.Parse(s)) : eq<T,long>() ? ct<T,long>(long.Parse(s)) : eq<T,double>() ? ct<T,double>(double.Parse(s,System.Globalization.CultureInfo.InvariantCulture)) : eq<T,char>() ? ct<T,char>(s[0]) : ct<T,string>(s); public static string[] rm<T>(out T a) { var z = Console.ReadLine().Split(sp,StringSplitOptions.RemoveEmptyEntries); a = cv<T>(z[0]); return z; } public static string[] rm<T,U>(out T a,out U b) { var z = rm<T>(out a); b = cv<U>(z[1]); return z; } public static string[] rm<T,U,V>(out T a,out U b,out V c) { var z = rm<T,U>(out a,out b); c = cv<V>(z[2]); return z; } public static string[] rm<T,U,V,W>(out T a,out U b,out V c,out W d) { var z = rm<T,U,V>(out a,out b,out c); d = cv<W>(z[3]); return z; } public static string[] rm<T,U,V,W,X>(out T a,out U b,out V c,out W d,out X e) { var z = rm<T,U,V,W>(out a,out b,out c,out d); e = cv<X>(z[4]); return z; } public static string[] rm<T,U,V,W,X,Y>(out T a,out U b,out V c,out W d,out X e,out Y f) { var z = rm<T,U,V,W,X>(out a,out b,out c,out d,out e); f = cv<Y>(z[5]); return z; } public static string[] ra<T>(out T[] a) { var z = Console.ReadLine().Split(sp,StringSplitOptions.RemoveEmptyEntries); a = z.Select(cv<T>).ToArray(); return z; } public static string[][] rl<T>(long n,out T[] a) { a = new T[n]; var y = new string[n][]; for(int i=0;i<n;i++) y[i] = rm(out a[i]); return y; } public static string[][] rl<T,U>(long n,out P<T,U>[] a) { a = new P<T,U>[n]; var y = new string[n][]; for(int i=0;i<n;i++) { T o; U p; y[i] = rm(out o,out p); a[i] = new P<T,U>(o,p); } return y; } public static string[][] rl<T,U,V>(long n,out P<T,U,V>[] a) { a = new P<T,U,V>[n]; var y = new string[n][]; for(int i=0;i<n;i++) { T o; U p; V q; y[i] = rm(out o,out p,out q); a[i] = new P<T,U,V>(o,p,q); } return y; } public static string[][] rl<T,U,V,W>(long n,out P<T,U,V,W>[] a) { a = new P<T,U,V,W>[n]; var y = new string[n][]; for(int i=0;i<n;i++) { T o; U p; V q; W r; y[i] = rm(out o,out p,out q,out r); a[i] = new P<T,U,V,W>(o,p,q,r); } return y; } public static string[][] rx<T>(long n,out T[][] a) { a = new T[n][]; var y = new string[n][]; for(int i=0;i<n;i++) y[i] = ra(out a[i]); return y; } static void wwp(Action act){ sw.AutoFlush = false; Console.SetOut(sw); act(); Console.Out.Flush(); sw.AutoFlush = true; Console.SetOut(sw); } [MethodImpl(256)] static string wfm(Type t) =>t.Equals(typeof(double)) ? "{0:F10}" : "{0}"; public static void wm(params object[] a) { wwp(()=>{ for(int i=0;i<a.Length;i++) { var f = wfm(a[i].GetType()) + ((i<a.Length-1) ? " " : Environment.NewLine); Console.Write(f,a[i]); } }); } public static void wa<T>(IList<T> a) { wwp(()=>{ var f = wfm(typeof(T)); var g = f + " "; var h = f + Environment.NewLine; for(int i=0;i<a.Count;i++) Console.Write(((i<a.Count-1) ? g : h),a[i]); }); } public static void wl<T>(IList<T> a) { wwp(()=>{ var f = wfm(typeof(T)) + Environment.NewLine; foreach(T x in a) Console.Write(f,x); }); } } #endregion }
[["-", 63, 214, 205, 23, 0, 16, 12, 214, 205, 22], ["+", 63, 214, 205, 23, 0, 16, 12, 214, 205, 22], ["-", 63, 214, 205, 23, 0, 16, 12, 214, 141, 22], ["+", 63, 214, 205, 23, 0, 16, 12, 214, 141, 22], ["-", 3, 4, 0, 28, 0, 16, 12, 214, 205, 22], ["+", 3, 4, 0, 28, 0, 16, 12, 214, 205, 22], ["-", 3, 4, 0, 28, 0, 16, 12, 214, 141, 22], ["+", 3, 4, 0, 28, 0, 16, 12, 214, 141, 22]]
8
2,778
8
using System; using System.Linq; namespace AtCoder { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var happiness = new Happiness[n]; for (var i = 0; i < n; i++) { var input = Console.ReadLine().Split(' '); happiness[i] = new Happiness(int.Parse(input[0]), int.Parse(input[1])); } var sorted = happiness.OrderBy(x => x.A + x.B).ToArray(); var a = sorted.Where((x, i) => i % 2 == 0).Sum(x => (long)x.A); var b = sorted.Where((x, i) => i % 2 == 1).Sum(x => (long)x.B); Console.WriteLine(a - b); } } class Happiness { public int A; public int B; public Happiness(int a, int b) { A = a; B = b; } } }
using System; using System.Linq; namespace AtCoder { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var happiness = new Happiness[n]; for (var i = 0; i < n; i++) { var input = Console.ReadLine().Split(' '); happiness[i] = new Happiness(int.Parse(input[0]), int.Parse(input[1])); } var sorted = happiness.OrderByDescending(x => x.A + x.B).ToArray(); var a = sorted.Where((x, i) => i % 2 == 0).Sum(x => (long)x.A); var b = sorted.Where((x, i) => i % 2 == 1).Sum(x => (long)x.B); Console.WriteLine(a - b); } } class Happiness { public int A; public int B; public Happiness(int a, int b) { A = a; B = b; } } }
[["-", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22], ["+", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22]]
8
237
2
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; namespace AtCoder { class Program { static void Main(string[] args) { var ir = new Resolver(new ConsoleReader()); Console.WriteLine(ir.Resolve()); } } public class Resolver { IInputReader InputReader { get; } public List<string> Messages { get; set; } = new List<string>(); int n; List<long[]> ls = new List<long[]>(); public void ParseLines() { n = int.Parse(InputReader.ReadLine()); foreach (var i in Enumerable.Range(0, n)) { ls.Add(InputReader.ReadLine() .Split(' ') .Select(x => long.Parse(x)) .ToArray()); } } public class Table { public long PointA { get; set; } = 0; IPerson A { get; } IPerson B { get; } int[] _dishes; public Table(IPerson a, IPerson b, int ndish) { this.A = a; this.B = b; this._dishes = Enumerable.Range(0, ndish).ToArray(); } public long CalculatePoint() { PointA += _dishes.Select(x => A.Taste[x] + B.Taste[x]) .OrderBy(x => x) .Where((x, i) => i % 2 == 0) .Sum(); PointA -= B.Taste.Values.Sum(x => x); return PointA; } } public interface IPerson { long HappyScore { get; set; } Dictionary<int, long> Taste { get; } } public class Person : IPerson { public Dictionary<int, long> Taste { get; } public long HappyScore { get; set; } = 0; public Person(Dictionary<int, long> taste) { Taste = taste; } public IEnumerator EatWith(Person other) { var tmp = Taste.Keys .ToDictionary( key => key, key => { return this.Taste[key] + other.Taste[key]; }) .OrderBy(x => x.Value) .ToList(); var i = 0; while (i < tmp.Count) { if (i % 2 == 0) { this.HappyScore += this.Taste[i]; } else { other.HappyScore += other.Taste[i]; } i++; yield return 0; } } } public string Resolve() { var a = new Person(Enumerable.Range(0, n).ToDictionary(i => i, i => ls[i][0])); var b = new Person(Enumerable.Range(0, n).ToDictionary(i => i, i => ls[i][1])); var table = new Table(a, b, n); return table.CalculatePoint().ToString(); } public Resolver(IInputReader inputReader) { InputReader = inputReader; ParseLines(); } } public interface IInputReader { string ReadLine(); } class ConsoleReader : IInputReader { string IInputReader.ReadLine() { return Console.ReadLine(); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; namespace AtCoder { class Program { static void Main(string[] args) { var ir = new Resolver(new ConsoleReader()); Console.WriteLine(ir.Resolve()); } } public class Resolver { IInputReader InputReader { get; } public List<string> Messages { get; set; } = new List<string>(); int n; List<long[]> ls = new List<long[]>(); public void ParseLines() { n = int.Parse(InputReader.ReadLine()); foreach (var i in Enumerable.Range(0, n)) { ls.Add(InputReader.ReadLine() .Split(' ') .Select(x => long.Parse(x)) .ToArray()); } } public class Table { public long PointA { get; set; } = 0; IPerson A { get; } IPerson B { get; } int[] _dishes; public Table(IPerson a, IPerson b, int ndish) { this.A = a; this.B = b; this._dishes = Enumerable.Range(0, ndish).ToArray(); } public long CalculatePoint() { PointA += _dishes.Select(x => A.Taste[x] + B.Taste[x]) .OrderBy(x => x) .Reverse() .Where((x, i) => i % 2 == 0) .Sum(); PointA -= B.Taste.Values.Sum(x => x); return PointA; } } public interface IPerson { long HappyScore { get; set; } Dictionary<int, long> Taste { get; } } public class Person : IPerson { public Dictionary<int, long> Taste { get; } public long HappyScore { get; set; } = 0; public Person(Dictionary<int, long> taste) { Taste = taste; } public IEnumerator EatWith(Person other) { var tmp = Taste.Keys .ToDictionary( key => key, key => { return this.Taste[key] + other.Taste[key]; }) .OrderBy(x => x.Value) .ToList(); var i = 0; while (i < tmp.Count) { if (i % 2 == 0) { this.HappyScore += this.Taste[i]; } else { other.HappyScore += other.Taste[i]; } i++; yield return 0; } } } public string Resolve() { var a = new Person(Enumerable.Range(0, n).ToDictionary(i => i, i => ls[i][0])); var b = new Person(Enumerable.Range(0, n).ToDictionary(i => i, i => ls[i][1])); var table = new Table(a, b, n); return table.CalculatePoint().ToString(); } public Resolver(IInputReader inputReader) { InputReader = inputReader; ParseLines(); } } public interface IInputReader { string ReadLine(); } class ConsoleReader : IInputReader { string IInputReader.ReadLine() { return Console.ReadLine(); } } }
[["+", 205, 213, 63, 214, 205, 213, 63, 214, 141, 22], ["+", 205, 213, 63, 214, 205, 213, 3, 4, 0, 24], ["+", 205, 213, 63, 214, 205, 213, 3, 4, 0, 25], ["+", 12, 213, 63, 214, 205, 213, 63, 214, 0, 131]]
8
672
4
using System.Linq; using System; public class P { public int a { get; set; } public int b { get; set; } } public class Hello { public static void Main() { var n = int.Parse(Console.ReadLine().Trim()); var ps = new P[n]; for (int i = 0; i < n; i++) { string[] line = Console.ReadLine().Trim().Split(' '); var a = int.Parse(line[0]); var b = int.Parse(line[1]); ps[i] = new P { a = a, b = b }; } var ans = getAns(ps, n); Console.WriteLine(ans); } static long getAns(P[] ps, int n) { var ps2 = ps.OrderBy(x => x.a + x.b).ToArray(); var ans = 0L; for (int i = 0; i < n; i++) if (i % 2 == 0) ans += ps2[i].a; else ans -= ps2[i].b; return ans; } }
using System.Linq; using System; public class P { public int a { get; set; } public int b { get; set; } } public class Hello { public static void Main() { var n = int.Parse(Console.ReadLine().Trim()); var ps = new P[n]; for (int i = 0; i < n; i++) { string[] line = Console.ReadLine().Trim().Split(' '); var a = int.Parse(line[0]); var b = int.Parse(line[1]); ps[i] = new P { a = a, b = b }; } var ans = getAns(ps, n); Console.WriteLine(ans); } static long getAns(P[] ps, int n) { var ps2 = ps.OrderByDescending(x => x.a + x.b).ToArray(); var ans = 0L; for (int i = 0; i < n; i++) if (i % 2 == 0) ans += ps2[i].a; else ans -= ps2[i].b; return ans; } }
[["-", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22], ["+", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22]]
8
254
2
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Runtime.CompilerServices; using static System.Console; using static System.Math; using static Macro; using static Extension; using static LinqExtension; using static HelpExtension; class AC { /*------------------------------------------------------------------*/ int N; long[] A, B; struct Ryori : IComparable<Ryori> { public long Takahashi; public long Aoki; public Ryori(long t, long a) { Takahashi = t; Aoki = a; } public int CompareTo(Ryori a) { var ryoriA = a.Takahashi + a.Aoki; var ryoriB = this.Takahashi + this.Aoki; if (ryoriA > ryoriB) return 1; if (ryoriA < ryoriB) return -1; return 0; } } void Solve() { N = io.Int; io.ini(out A, out B, N); var pq = new PriorityQueue<Ryori>(false); ZIP(A, B).Iter(x => { pq.Enqueue(new Ryori(x.Item1, x.Item2)); }); var Ts = 0L; var As = 0L; var isT = true; while (pq.Any) { var cur = pq.Dequeue(); if (isT) { Ts += cur.Takahashi; } else { As += cur.Aoki; } isT = !isT; } (Ts - As).Prt(); } /*------------------------------------------------------------------*/ void Test() { //--- TEST ---// } public static void Main(string[] args) => new AC().Stream(); const int INF = int.MaxValue / 2; IO io = new IO(); private void Stream() { /* var exStdIn = new System.IO.StreamReader("stdin.txt"); SetIn(exStdIn); Test(); */ Solve(); io.Flush(); } } class IO { #region INPUT #region FastRead private const int Size = 1 << 12; private readonly Stream _stream = OpenStandardInput(); private readonly byte[] _buffer = new byte[Size]; private int _ptr = 0, _buffLen = 0; private bool HasNextByte() { if (_ptr < _buffLen) return true; _ptr = 0; _buffLen = _stream.Read(_buffer, 0, Size); return _buffLen > 0; } private byte ReadByte() { if (HasNextByte()) return _buffer[_ptr++]; else // inputの末尾の改行がないとerror throw new EndOfStreamException(); } private bool IsAscii(int c) => '!' <= c && c <= '~'; private char NextChar() { var b = ReadByte(); while (!IsAscii(b)) b = ReadByte(); return (char)b; } private string Next() { var sb = new StringBuilder(); for (var b = NextChar(); IsAscii(b); b = (char)ReadByte()) sb.Append(b); return sb.ToString(); } public string String => Next(); public char Char => NextChar(); public int Int => int.Parse(Next()); public long Long => long.Parse(Next()); public double Double => double.Parse(Next()); #endregion #region LazyRead private void scan<T>(ref T x) { if (x is int) __refvalue(__makeref(x), int) = int.Parse(Next()); else if (x is long) __refvalue(__makeref(x), long) = long.Parse(Next()); else if (x is double) __refvalue(__makeref(x), double) = double.Parse(Next()); else if (x is char) __refvalue(__makeref(x), char) = NextChar(); else __refvalue(__makeref(x), string) = Next(); } public void i<T>(out T t) { t = default(T); scan(ref t); } public void i<T, TU>(out T t, out TU u) { i(out t); i(out u); } public void i<T, TU, TV>(out T t, out TU u, out TV v) { i(out t, out u); i(out v); } public void i<T, TU, TV, TW>(out T t, out TU u, out TV v, out TW w) { i(out t, out u); i(out v, out w); } public void i<T, TU, TV, TW, TX>(out T t, out TU u, out TV v, out TW w, out TX x) { i(out t, out u, out v); i(out w, out x); } public void i<T, TU, TV, TW, TX, TY>(out T t, out TU u, out TV v, out TW w, out TX x, out TY y) { i(out t, out u, out v); i(out w, out x, out y); } public void ini<T>(out T[] a, int n) { a = new T[n]; for (int i = 0; i < n; ++i) i<T>(out a[i]); } public void ini<T, TU>(out T[] a, out TU[] b, int n) { a = new T[n]; b = new TU[n]; for (int i = 0; i < n; ++i) i<T, TU>(out a[i], out b[i]); } public void ini<T, TU, TV>(out T[] a, out TU[] b, out TV[] c, int n) { a = new T[n]; b = new TU[n]; c = new TV[n]; for (var i = 0; i < n; ++i) i<T, TU, TV>(out a[i], out b[i], out c[i]); } public void ini<T, TU, TV, TW>(out T[] a, out TU[] b, out TV[] c, out TW[] d, int n) { a = new T[n]; b = new TU[n]; c = new TV[n]; d = new TW[n]; for (var i = 0; i < n; ++i) i<T, TU, TV, TW>(out a[i], out b[i], out c[i], out d[i]); } public void ini<T>(out T[,] a, int h, int w) { a = new T[h, w]; for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) i<T>(out a[i, j]); } #endregion #endregion #region OUTPUT private readonly StreamWriter _sw = new StreamWriter(OpenStandardOutput()) { #if DEBUG AutoFlush = true #else AutoFlush = false #endif }; public void Flush() => Out.Flush(); public void YN(bool f) => yn(f, "YES", "NO"); public void Yn(bool f) => yn(f, "Yes", "No"); public void yn(bool f, string y = "yes", string n = "no") => WriteLine(f ? y : n); #endregion public IO() { SetOut(_sw); } } static class Macro { public static void FOR(int a, int b, int n, Action<int> f) { for (var i = a; i < b; i += n) { try { f(i); } catch (IndexOutOfRangeException e) { #if DEBUG WriteLine($"IndexOutOfRange at [{i}]"); #endif } } } public static void FOR(int a, int b, Action<int> f) => FOR(a, b, 1, f); public static void REP(int a, Action<int> f) => FOR(0, a, 1, f); public static void REP(int a, int n, Action<int> f) => FOR(0, a, n, f); public static void FOREQ(int a, int b, Action<int> f) => FOR(a, b + 1, 1, f); public static void FOREQ(int a, int b, int n, Action<int> f) => FOR(a, b + 1, n, f); public static void REPEQ(int a, Action<int> f) => FOR(0, a + 1, 1, f); public static void REPEQ(int a, int n, Action<int> f) => FOR(0, a + 1, n, f); public static T MIN<T>(params T[] xs) => xs.Min(); public static T MAX<T>(params T[] xs) => xs.Max(); public static IEnumerable<Tuple<T, U>> ZIP<T, U>(IEnumerable<T> x, IEnumerable<U> y) => x.Zip(y, (i1, i2) => new Tuple<T, U>(i1, i2)); public static IEnumerable<Tuple<T, U, V>> ZIP<T, U, V>(IEnumerable<T> xs, IEnumerable<U> ys, IEnumerable<V> zs) { using (var eX = xs.GetEnumerator()) using ( var eY = ys.GetEnumerator()) using (var eZ = zs.GetEnumerator()) { while (eX.MoveNext() && eY.MoveNext() && eZ.MoveNext()) { yield return new Tuple<T, U, V>(eX.Current, eY.Current, eZ.Current); } } } } static class Extension { public static void Rep(this int a, Action<int> f) => FOR(0, a, 1, f); public static void Rep(this int a, int n, Action<int> f) => FOR(0, a, n, f); public static void RepEQ(this int a, Action<int> f) => FOR(0, a + 1, 1, f); public static void RepEQ(this int a, int n, Action<int> f) => FOR(0, a + 1, n, f); public static void Prt<T>(this T x) => WriteLine(x); public static void Prt<T>(this IEnumerable<T> xs) => xs.Iter(x => WriteLine(x)); public static void Prt_<T>(this IEnumerable<T> xs) { xs.Iter(x => Write($"{x} ")); WriteLine(); } public static bool IsOdd(this int x) => x % 2 != 0; public static bool IsOdd(this long x) => x % 2 != 0; } static class LinqExtension { public struct IndexedValue<T> { public int Index; public T Value; public IndexedValue(int index, T value) { this.Index = index; this.Value = value; } public override string ToString() { return string.Format("Index: {0}, Value: {1}", Index, Value); } } public struct Pair<T> { public T Fst; public T Snd; public Pair(T fst, T snd) { Fst = fst; Snd = snd; } public override string ToString() { return string.Format("({0}, {1})", Fst, Snd); } } public static IEnumerable<IndexedValue<T>> Indexed<T>(this IEnumerable<T> source) { return source.Select((value, index) => new IndexedValue<T>(index, value)); } public static void Iter<T>(this IEnumerable<T> source, Action<T> action) { foreach (var s in source) action(s); } public static IEnumerable<Pair<T>> PairWise<T>(this IEnumerable<T> source) { return source.Zip(source.Skip(1), (fst, snd) => new Pair<T>(fst, snd)); } private static IEnumerable<T> Init<T>(int size, Func<int, T> f) { for (var i = 0; i < size; ++i) yield return f(i); } public static IEnumerable<IEnumerable<T>> Windowed<T>(this IEnumerable<T> source, int size) { var tmpArr = new T[size]; var r = size - 1; var i = 0; using (var e = source.GetEnumerator()) { while (e.MoveNext()) { tmpArr[i] = e.Current; i = (i + 1) % size; if (r == 0) yield return Init<T>(size, j => tmpArr[(i + j) % size]); else r--; } } } public static IEnumerable<T> Sort<T>(this IEnumerable<T> source) => source.OrderBy(x => x); public static IEnumerable<T> Rev<T>(this IEnumerable<T> source) => Sort(source).Reverse(); public static IEnumerable<T> DistinctBy<T, U>(this IEnumerable<T> source, Func<T, U> groupBy, Func<IGrouping<U, T>, T> selectBy) => source.GroupBy(groupBy).Select(selectBy); public static IEnumerable<T> DistinctBy<T, U>(this IEnumerable<T> source, Func<T, U> groupBy) => source.DistinctBy(groupBy, x => x.First()); } static class HelpExtension { public class PriorityQueue<T> where T : IComparable<T> { private List<T> heap; private bool isAsc; private int size; public T Peek => heap[0]; public int Count => size; public bool Any => size > 0; public bool Empty => !Any; public PriorityQueue(bool isAsc = true) { this.isAsc = isAsc; size = 0; heap = new List<T>(); } public void Enqueue(T item) { heap.Add(item); var i = size++; while (i > 0) { var p = (i - 1) / 2; if (Compare(heap[p], item) <= 0) break; heap[i] = heap[p]; i = p; } heap[i] = item; } public T Dequeue() { var ret = heap[0]; var x = heap[--size]; var i = 0; while ((i << 1) + 1 < size) { var a = (i << 1) + 1; var b = (i << 1) + 2; if (b < size && Compare(heap[b], heap[a]) < 0) a = b; if (Compare(heap[a], x) >= 0) break; heap[i] = heap[a]; i = a; } heap[i] = x; heap.RemoveAt(size); return ret; } private int Compare(T x, T y) => isAsc ? x.CompareTo(y) : y.CompareTo(x); } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Runtime.CompilerServices; using static System.Console; using static System.Math; using static Macro; using static Extension; using static LinqExtension; using static HelpExtension; class AC { /*------------------------------------------------------------------*/ int N; long[] A, B; struct Ryori : IComparable<Ryori> { public long Takahashi; public long Aoki; public Ryori(long t, long a) { Takahashi = t; Aoki = a; } public int CompareTo(Ryori a) { var ryoriA = a.Takahashi + a.Aoki; var ryoriB = this.Takahashi + this.Aoki; if (ryoriA > ryoriB) return -1; if (ryoriA < ryoriB) return 1; return 0; } } void Solve() { N = io.Int; io.ini(out A, out B, N); var pq = new PriorityQueue<Ryori>(false); ZIP(A, B).Iter(x => { pq.Enqueue(new Ryori(x.Item1, x.Item2)); }); var Ts = 0L; var As = 0L; var isT = true; while (pq.Any) { var cur = pq.Dequeue(); if (isT) { Ts += cur.Takahashi; } else { As += cur.Aoki; } isT = !isT; } (Ts - As).Prt(); } /*------------------------------------------------------------------*/ void Test() { //--- TEST ---// } public static void Main(string[] args) => new AC().Stream(); const int INF = int.MaxValue / 2; IO io = new IO(); private void Stream() { /* var exStdIn = new System.IO.StreamReader("stdin.txt"); SetIn(exStdIn); Test(); */ Solve(); io.Flush(); } } class IO { #region INPUT #region FastRead private const int Size = 1 << 12; private readonly Stream _stream = OpenStandardInput(); private readonly byte[] _buffer = new byte[Size]; private int _ptr = 0, _buffLen = 0; private bool HasNextByte() { if (_ptr < _buffLen) return true; _ptr = 0; _buffLen = _stream.Read(_buffer, 0, Size); return _buffLen > 0; } private byte ReadByte() { if (HasNextByte()) return _buffer[_ptr++]; else // inputの末尾の改行がないとerror throw new EndOfStreamException(); } private bool IsAscii(int c) => '!' <= c && c <= '~'; private char NextChar() { var b = ReadByte(); while (!IsAscii(b)) b = ReadByte(); return (char)b; } private string Next() { var sb = new StringBuilder(); for (var b = NextChar(); IsAscii(b); b = (char)ReadByte()) sb.Append(b); return sb.ToString(); } public string String => Next(); public char Char => NextChar(); public int Int => int.Parse(Next()); public long Long => long.Parse(Next()); public double Double => double.Parse(Next()); #endregion #region LazyRead private void scan<T>(ref T x) { if (x is int) __refvalue(__makeref(x), int) = int.Parse(Next()); else if (x is long) __refvalue(__makeref(x), long) = long.Parse(Next()); else if (x is double) __refvalue(__makeref(x), double) = double.Parse(Next()); else if (x is char) __refvalue(__makeref(x), char) = NextChar(); else __refvalue(__makeref(x), string) = Next(); } public void i<T>(out T t) { t = default(T); scan(ref t); } public void i<T, TU>(out T t, out TU u) { i(out t); i(out u); } public void i<T, TU, TV>(out T t, out TU u, out TV v) { i(out t, out u); i(out v); } public void i<T, TU, TV, TW>(out T t, out TU u, out TV v, out TW w) { i(out t, out u); i(out v, out w); } public void i<T, TU, TV, TW, TX>(out T t, out TU u, out TV v, out TW w, out TX x) { i(out t, out u, out v); i(out w, out x); } public void i<T, TU, TV, TW, TX, TY>(out T t, out TU u, out TV v, out TW w, out TX x, out TY y) { i(out t, out u, out v); i(out w, out x, out y); } public void ini<T>(out T[] a, int n) { a = new T[n]; for (int i = 0; i < n; ++i) i<T>(out a[i]); } public void ini<T, TU>(out T[] a, out TU[] b, int n) { a = new T[n]; b = new TU[n]; for (int i = 0; i < n; ++i) i<T, TU>(out a[i], out b[i]); } public void ini<T, TU, TV>(out T[] a, out TU[] b, out TV[] c, int n) { a = new T[n]; b = new TU[n]; c = new TV[n]; for (var i = 0; i < n; ++i) i<T, TU, TV>(out a[i], out b[i], out c[i]); } public void ini<T, TU, TV, TW>(out T[] a, out TU[] b, out TV[] c, out TW[] d, int n) { a = new T[n]; b = new TU[n]; c = new TV[n]; d = new TW[n]; for (var i = 0; i < n; ++i) i<T, TU, TV, TW>(out a[i], out b[i], out c[i], out d[i]); } public void ini<T>(out T[,] a, int h, int w) { a = new T[h, w]; for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) i<T>(out a[i, j]); } #endregion #endregion #region OUTPUT private readonly StreamWriter _sw = new StreamWriter(OpenStandardOutput()) { #if DEBUG AutoFlush = true #else AutoFlush = false #endif }; public void Flush() => Out.Flush(); public void YN(bool f) => yn(f, "YES", "NO"); public void Yn(bool f) => yn(f, "Yes", "No"); public void yn(bool f, string y = "yes", string n = "no") => WriteLine(f ? y : n); #endregion public IO() { SetOut(_sw); } } static class Macro { public static void FOR(int a, int b, int n, Action<int> f) { for (var i = a; i < b; i += n) { try { f(i); } catch (IndexOutOfRangeException e) { #if DEBUG WriteLine($"IndexOutOfRange at [{i}]"); #endif } } } public static void FOR(int a, int b, Action<int> f) => FOR(a, b, 1, f); public static void REP(int a, Action<int> f) => FOR(0, a, 1, f); public static void REP(int a, int n, Action<int> f) => FOR(0, a, n, f); public static void FOREQ(int a, int b, Action<int> f) => FOR(a, b + 1, 1, f); public static void FOREQ(int a, int b, int n, Action<int> f) => FOR(a, b + 1, n, f); public static void REPEQ(int a, Action<int> f) => FOR(0, a + 1, 1, f); public static void REPEQ(int a, int n, Action<int> f) => FOR(0, a + 1, n, f); public static T MIN<T>(params T[] xs) => xs.Min(); public static T MAX<T>(params T[] xs) => xs.Max(); public static IEnumerable<Tuple<T, U>> ZIP<T, U>(IEnumerable<T> x, IEnumerable<U> y) => x.Zip(y, (i1, i2) => new Tuple<T, U>(i1, i2)); public static IEnumerable<Tuple<T, U, V>> ZIP<T, U, V>(IEnumerable<T> xs, IEnumerable<U> ys, IEnumerable<V> zs) { using (var eX = xs.GetEnumerator()) using ( var eY = ys.GetEnumerator()) using (var eZ = zs.GetEnumerator()) { while (eX.MoveNext() && eY.MoveNext() && eZ.MoveNext()) { yield return new Tuple<T, U, V>(eX.Current, eY.Current, eZ.Current); } } } } static class Extension { public static void Rep(this int a, Action<int> f) => FOR(0, a, 1, f); public static void Rep(this int a, int n, Action<int> f) => FOR(0, a, n, f); public static void RepEQ(this int a, Action<int> f) => FOR(0, a + 1, 1, f); public static void RepEQ(this int a, int n, Action<int> f) => FOR(0, a + 1, n, f); public static void Prt<T>(this T x) => WriteLine(x); public static void Prt<T>(this IEnumerable<T> xs) => xs.Iter(x => WriteLine(x)); public static void Prt_<T>(this IEnumerable<T> xs) { xs.Iter(x => Write($"{x} ")); WriteLine(); } public static bool IsOdd(this int x) => x % 2 != 0; public static bool IsOdd(this long x) => x % 2 != 0; } static class LinqExtension { public struct IndexedValue<T> { public int Index; public T Value; public IndexedValue(int index, T value) { this.Index = index; this.Value = value; } public override string ToString() { return string.Format("Index: {0}, Value: {1}", Index, Value); } } public struct Pair<T> { public T Fst; public T Snd; public Pair(T fst, T snd) { Fst = fst; Snd = snd; } public override string ToString() { return string.Format("({0}, {1})", Fst, Snd); } } public static IEnumerable<IndexedValue<T>> Indexed<T>(this IEnumerable<T> source) { return source.Select((value, index) => new IndexedValue<T>(index, value)); } public static void Iter<T>(this IEnumerable<T> source, Action<T> action) { foreach (var s in source) action(s); } public static IEnumerable<Pair<T>> PairWise<T>(this IEnumerable<T> source) { return source.Zip(source.Skip(1), (fst, snd) => new Pair<T>(fst, snd)); } private static IEnumerable<T> Init<T>(int size, Func<int, T> f) { for (var i = 0; i < size; ++i) yield return f(i); } public static IEnumerable<IEnumerable<T>> Windowed<T>(this IEnumerable<T> source, int size) { var tmpArr = new T[size]; var r = size - 1; var i = 0; using (var e = source.GetEnumerator()) { while (e.MoveNext()) { tmpArr[i] = e.Current; i = (i + 1) % size; if (r == 0) yield return Init<T>(size, j => tmpArr[(i + j) % size]); else r--; } } } public static IEnumerable<T> Sort<T>(this IEnumerable<T> source) => source.OrderBy(x => x); public static IEnumerable<T> Rev<T>(this IEnumerable<T> source) => Sort(source).Reverse(); public static IEnumerable<T> DistinctBy<T, U>(this IEnumerable<T> source, Func<T, U> groupBy, Func<IGrouping<U, T>, T> selectBy) => source.GroupBy(groupBy).Select(selectBy); public static IEnumerable<T> DistinctBy<T, U>(this IEnumerable<T> source, Func<T, U> groupBy) => source.DistinctBy(groupBy, x => x.First()); } static class HelpExtension { public class PriorityQueue<T> where T : IComparable<T> { private List<T> heap; private bool isAsc; private int size; public T Peek => heap[0]; public int Count => size; public bool Any => size > 0; public bool Empty => !Any; public PriorityQueue(bool isAsc = true) { this.isAsc = isAsc; size = 0; heap = new List<T>(); } public void Enqueue(T item) { heap.Add(item); var i = size++; while (i > 0) { var p = (i - 1) / 2; if (Compare(heap[p], item) <= 0) break; heap[i] = heap[p]; i = p; } heap[i] = item; } public T Dequeue() { var ret = heap[0]; var x = heap[--size]; var i = 0; while ((i << 1) + 1 < size) { var a = (i << 1) + 1; var b = (i << 1) + 2; if (b < size && Compare(heap[b], heap[a]) < 0) a = b; if (Compare(heap[a], x) >= 0) break; heap[i] = heap[a]; i = a; } heap[i] = x; heap.RemoveAt(size); return ret; } private int Compare(T x, T y) => isAsc ? x.CompareTo(y) : y.CompareTo(x); } }
[["+", 8, 196, 0, 57, 64, 37, 0, 241, 0, 33], ["-", 8, 196, 0, 57, 64, 37, 0, 241, 0, 33]]
8
3,269
2
using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace NIKKEI2019C { public class Program { void Solve(StreamScanner ss, StreamWriter sw) { //--------------------------------- var N = ss.Next(int.Parse); var D = ss.Next(long.Parse, 2, N) .Select(d => new { A = d[0], B = d[1] }) .ToArray(); var ret = 0L; var sorted = D.OrderBy(d => d.A + d.B).ToArray(); for (var i = 0; i < N; i++) { if (i % 2 == 0) ret += sorted[i].A; else ret -= sorted[i].B; } sw.WriteLine(ret); //--------------------------------- } static void Main() { var ss = new StreamScanner(new StreamReader(Console.OpenStandardInput())); var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; new Program().Solve(ss, sw); sw.Flush(); } static readonly Func<string, string> String = s => s; } public class StreamScanner { static readonly char[] Sep = { ' ' }; readonly Queue<string> buffer = new Queue<string>(); readonly TextReader textReader; public StreamScanner(TextReader textReader) { this.textReader = textReader; } public T Next<T>(Func<string, T> parser) { if (buffer.Count != 0) return parser(buffer.Dequeue()); var nextStrings = textReader.ReadLine().Split(Sep, StringSplitOptions.RemoveEmptyEntries); foreach (var nextString in nextStrings) buffer.Enqueue(nextString); return Next(parser); } public T[] Next<T>(Func<string, T> parser, int x) { var ret = new T[x]; for (var i = 0; i < x; ++i) ret[i] = Next(parser); return ret; } public T[][] Next<T>(Func<string, T> parser, int x, int y) { var ret = new T[y][]; for (var i = 0; i < y; ++i) ret[i] = Next(parser, x); return ret; } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace NIKKEI2019C { public class Program { void Solve(StreamScanner ss, StreamWriter sw) { //--------------------------------- var N = ss.Next(int.Parse); var D = ss.Next(long.Parse, 2, N) .Select(d => new { A = d[0], B = d[1] }) .ToArray(); var ret = 0L; var sorted = D.OrderByDescending(d => d.A + d.B).ToArray(); for (var i = 0; i < N; i++) { if (i % 2 == 0) ret += sorted[i].A; else ret -= sorted[i].B; } sw.WriteLine(ret); //--------------------------------- } static void Main() { var ss = new StreamScanner(new StreamReader(Console.OpenStandardInput())); var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; new Program().Solve(ss, sw); sw.Flush(); } static readonly Func<string, string> String = s => s; } public class StreamScanner { static readonly char[] Sep = { ' ' }; readonly Queue<string> buffer = new Queue<string>(); readonly TextReader textReader; public StreamScanner(TextReader textReader) { this.textReader = textReader; } public T Next<T>(Func<string, T> parser) { if (buffer.Count != 0) return parser(buffer.Dequeue()); var nextStrings = textReader.ReadLine().Split(Sep, StringSplitOptions.RemoveEmptyEntries); foreach (var nextString in nextStrings) buffer.Enqueue(nextString); return Next(parser); } public T[] Next<T>(Func<string, T> parser, int x) { var ret = new T[x]; for (var i = 0; i < x; ++i) ret[i] = Next(parser); return ret; } public T[][] Next<T>(Func<string, T> parser, int x, int y) { var ret = new T[y][]; for (var i = 0; i < y; ++i) ret[i] = Next(parser, x); return ret; } } }
[["-", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22], ["+", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22]]
8
496
2
using System; using System.Collections.Generic; using System.Linq; class C { static void Main() { var N = int.Parse(Console.ReadLine()); var AB = Enumerable.Range(0, N) .Select( i => Console.ReadLine().Split(' ').Select(long.Parse).ToList()) .ToList(); var diff = AB.Select((ab, i) => Tuple.Create(ab[0] + ab[1], ab[0], ab[1])) .OrderBy(d => d.Item1) .ToList(); long a = 0; long b = 0; for (int i = 0; i < N; i++) { if (i % 2 == 0) a += diff[i].Item2; else b += diff[i].Item3; } Console.WriteLine(a - b); } }
using System; using System.Collections.Generic; using System.Linq; class C { static void Main() { var N = int.Parse(Console.ReadLine()); var AB = Enumerable.Range(0, N) .Select( i => Console.ReadLine().Split(' ').Select(long.Parse).ToList()) .ToList(); var diff = AB.Select((ab, i) => Tuple.Create(ab[0] + ab[1], ab[0], ab[1])) .OrderByDescending(d => d.Item1) .ToList(); long a = 0; long b = 0; for (int i = 0; i < N; i++) { if (i % 2 == 0) a += diff[i].Item2; else b += diff[i].Item3; } Console.WriteLine(a - b); } }
[["-", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22], ["+", 0, 213, 63, 214, 205, 213, 63, 214, 141, 22]]
8
199
2
using System; using System.Collections.Generic; using System.Linq; static class MainClass { public struct City { public long num; public long year; public int ID; public City(long n, long y, int i) { num = n; year = y; ID = i; } } public static void Main(string[] args) { var N = long.Parse(Console.ReadLine()); var list = new List<long>(); var ans = 1; while (true) { ans++; N = N % 2 == 0 ? N / 2 : 3 * N + 1; if (list.Contains(N)) { Console.WriteLine(ans); return; } list.Add(N); } } }
using System; using System.Collections.Generic; using System.Linq; static class MainClass { public struct City { public long num; public long year; public int ID; public City(long n, long y, int i) { num = n; year = y; ID = i; } } public static void Main(string[] args) { var N = long.Parse(Console.ReadLine()); var list = new List<long>() { N }; var ans = 1; while (true) { ans++; N = N % 2 == 0 ? N / 2 : 3 * N + 1; if (list.Contains(N)) { Console.WriteLine(ans); return; } list.Add(N); } } }
[["+", 0, 200, 0, 212, 0, 230, 10, 229, 0, 45], ["+", 0, 200, 0, 212, 0, 230, 10, 229, 0, 22], ["+", 0, 200, 0, 212, 0, 230, 10, 229, 0, 46]]
8
159
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ABC116b { public static void Main() { int s = int.Parse(Console.ReadLine()); int cnt = 1; while (s > 4) { cnt++; if (s % 2 == 1) { s *= 3; s++; } else { s /= 2; } } int[] L = new int[6]; while (true) { if (L[s] == 1) { System.Console.WriteLine(cnt); Environment.Exit(0); } else { L[s] = 1; if (s % 2 == 1) { s *= 3; s++; } else { s /= 2; } } cnt++; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ABC116b { public static void Main() { int s = int.Parse(Console.ReadLine()); int cnt = 1; while (s > 4) { cnt++; if (s % 2 == 1) { s *= 3; s++; } else { s /= 2; } } int[] L = new int[100]; // Lが小さいとs==3でバグる while (true) { if (L[s] == 1) { System.Console.WriteLine(cnt); Environment.Exit(0); } else { L[s] = 1; if (s % 2 == 1) { s *= 3; s++; } else { s /= 2; } } cnt++; } } }
[["-", 0, 212, 0, 227, 39, 224, 225, 226, 0, 203], ["+", 0, 212, 0, 227, 39, 224, 225, 226, 0, 203]]
8
175
2
using System; using System.Numerics; using System.Collections.Generic; using System.IO; using System.Text; public class Solver { public void Solve() { int s = ri; int[] m = new int[1000001]; int a = s, t = 1; while (true) { if (m[a] > 0) { Console.WriteLine(m[a]); break; } m[a] = t++; a = (a % 2 == 0) ? a / 2 : 3 * a + 1; } } int ri { get { return sc.Integer(); } } long rl { get { return sc.Long(); } } double rd { get { return sc.Double(); } } string rs { get { return sc.Scan(); } } public StreamScanner sc = new StreamScanner(Console.OpenStandardInput()); private const int mod = 1000000007; int digit10(int n) { int p = 1; while (p <= n) { p *= 10; } return p % mod; } int abs(int n) { return (n > 0) ? n : -n; } int gcd(params int[] n) { int p = n[0]; for (int i = 1; i < n.Length; i++) { p = gcd(p, n[i]); } return p; } int gcd(int a, int b) { return (a == 0) ? b : gcd(b % a, a); } int lcm(params int[] n) { int p = n[0]; for (int i = 1; i < n.Length; i++) { p = lcm(p, n[i]); } return p; } int lcm(int a, int b) { return a * b / gcd(a, b); } int max(params int[] n) { int p = n[0]; for (int i = 1; i < n.Length; i++) { p = (p > n[i]) ? p : n[i]; } return p; } int min(params int[] n) { int p = n[0]; for (int i = 1; i < n.Length; i++) { p = (p < n[i]) ? p : n[i]; } return p; } void YN(bool t) { Console.WriteLine(t ? "YES" : "NO"); } void Yn(bool t) { Console.WriteLine(t ? "Yes" : "No"); } void yn(bool t) { Console.WriteLine(t ? "yes" : "no"); } string clip(string s, int start, int count) { if (start + count < s.Length) { s = s.Remove(start + count); } if (start > 0) { s = s.Remove(0, start); } return s; } } static class Program { static public void Main(string[] args) { Console.SetOut( new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }); var solver = new Solver(); solver.Solve(); Console.Out.Flush(); } } public class StreamScanner { public StreamScanner(Stream stream) { str = stream; } private readonly Stream str; private readonly byte[] buf = new byte[1024]; private int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } private byte read() { if (isEof) throw new EndOfStreamException(); if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } public char Char() { byte b = 0; do b = read(); while (b < 33 || 126 < b); return (char)b; } public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } public long Long() { long ret = 0; byte b = 0; var ng = false; do b = read(); while (b != '-' && (b < '0' || '9' < b)); if (b == '-') { ng = true; b = read(); } for (; true; b = read()) { if (b < '0' || '9' < b) return ng ? -ret : ret; else ret = ret * 10 + b - '0'; } } public int Integer() { return (int)Long(); } public double Double() { return double.Parse(Scan()); } }
using System; using System.Numerics; using System.Collections.Generic; using System.IO; using System.Text; public class Solver { public void Solve() { int s = ri; int[] m = new int[1000001]; int a = s, t = 1; while (true) { if (m[a] > 0) { Console.WriteLine(t); break; } m[a] = t++; a = (a % 2 == 0) ? a / 2 : 3 * a + 1; } } int ri { get { return sc.Integer(); } } long rl { get { return sc.Long(); } } double rd { get { return sc.Double(); } } string rs { get { return sc.Scan(); } } public StreamScanner sc = new StreamScanner(Console.OpenStandardInput()); private const int mod = 1000000007; int digit10(int n) { int p = 1; while (p <= n) { p *= 10; } return p % mod; } int abs(int n) { return (n > 0) ? n : -n; } int gcd(params int[] n) { int p = n[0]; for (int i = 1; i < n.Length; i++) { p = gcd(p, n[i]); } return p; } int gcd(int a, int b) { return (a == 0) ? b : gcd(b % a, a); } int lcm(params int[] n) { int p = n[0]; for (int i = 1; i < n.Length; i++) { p = lcm(p, n[i]); } return p; } int lcm(int a, int b) { return a * b / gcd(a, b); } int max(params int[] n) { int p = n[0]; for (int i = 1; i < n.Length; i++) { p = (p > n[i]) ? p : n[i]; } return p; } int min(params int[] n) { int p = n[0]; for (int i = 1; i < n.Length; i++) { p = (p < n[i]) ? p : n[i]; } return p; } void YN(bool t) { Console.WriteLine(t ? "YES" : "NO"); } void Yn(bool t) { Console.WriteLine(t ? "Yes" : "No"); } void yn(bool t) { Console.WriteLine(t ? "yes" : "no"); } string clip(string s, int start, int count) { if (start + count < s.Length) { s = s.Remove(start + count); } if (start > 0) { s = s.Remove(0, start); } return s; } } static class Program { static public void Main(string[] args) { Console.SetOut( new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }); var solver = new Solver(); solver.Solve(); Console.Out.Flush(); } } public class StreamScanner { public StreamScanner(Stream stream) { str = stream; } private readonly Stream str; private readonly byte[] buf = new byte[1024]; private int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } private byte read() { if (isEof) throw new EndOfStreamException(); if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } public char Char() { byte b = 0; do b = read(); while (b < 33 || 126 < b); return (char)b; } public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } public long Long() { long ret = 0; byte b = 0; var ng = false; do b = read(); while (b != '-' && (b < '0' || '9' < b)); if (b == '-') { ng = true; b = read(); } for (; true; b = read()) { if (b < '0' || '9' < b) return ng ? -ret : ret; else ret = ret * 10 + b - '0'; } } public int Integer() { return (int)Long(); } public double Double() { return double.Parse(Scan()); } }
[["-", 0, 213, 3, 4, 0, 28, 0, 204, 205, 22], ["-", 3, 4, 0, 28, 0, 204, 206, 207, 0, 70], ["-", 0, 28, 0, 204, 206, 207, 0, 28, 0, 22], ["-", 3, 4, 0, 28, 0, 204, 206, 207, 0, 73], ["+", 0, 1, 0, 213, 3, 4, 0, 28, 0, 22]]
8
1,070
5
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Console; using System.Text; using System.Threading.Tasks; using System.IO; using System.Diagnostics; class Program { public static Scanner input; static void Main() { input = new Scanner(); int first = input.Int(); var arr = new List<double>(); arr.Add(first); bool flag = true; while (flag) { if (arr.Count == 0) { arr.Add(first); } else { arr.Add(f(arr[arr.Count - 1])); } for (int a = 0; a < arr.Count - 1; a++) { if (arr[a] == arr[arr.Count - 1]) { WriteLine(arr.Count - 1); flag = false; break; } } } } static double f(double a) { if (a % 2 == 0) { return (double)(a / 2); } else { return (double)(3 * a + 1); } } } class Scanner { public Scanner() {} public void skip() { ReadLine(); return; } public string String() { return ReadLine(); } public string[] arrayString() { return ReadLine().Split(); } public int Int() { return int.Parse(ReadLine()); } public int[] arrayInt() { return ReadLine().Split().Select(i => int.Parse(i)).ToArray(); } public long Long() { return long.Parse(ReadLine()); } public long[] arrayLong() { return ReadLine().Split().Select(i => long.Parse(i)).ToArray(); } public double Double() { return double.Parse(ReadLine()); } public double[] arrayDouble() { return ReadLine().Split().Select(i => double.Parse(i)).ToArray(); } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Console; using System.Text; using System.Threading.Tasks; using System.IO; using System.Diagnostics; class Program { public static Scanner input; static void Main() { input = new Scanner(); int first = input.Int(); var arr = new List<double>(); arr.Add(first); bool flag = true; while (flag) { if (arr.Count == 0) { arr.Add(first); } else { arr.Add(f(arr[arr.Count - 1])); } for (int a = 0; a < arr.Count - 1; a++) { if (arr[a] == arr[arr.Count - 1]) { WriteLine(arr.Count); flag = false; break; } } } } static double f(double a) { if (a % 2 == 0) { return (double)(a / 2); } else { return (double)(3 * a + 1); } } } class Scanner { public Scanner() {} public void skip() { ReadLine(); return; } public string String() { return ReadLine(); } public string[] arrayString() { return ReadLine().Split(); } public int Int() { return int.Parse(ReadLine()); } public int[] arrayInt() { return ReadLine().Split().Select(i => int.Parse(i)).ToArray(); } public long Long() { return long.Parse(ReadLine()); } public long[] arrayLong() { return ReadLine().Split().Select(i => long.Parse(i)).ToArray(); } public double Double() { return double.Parse(ReadLine()); } public double[] arrayDouble() { return ReadLine().Split().Select(i => double.Parse(i)).ToArray(); } }
[["-", 0, 213, 3, 4, 0, 28, 0, 16, 17, 33], ["-", 0, 213, 3, 4, 0, 28, 0, 16, 12, 203]]
8
449
2
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // List<int> values = new List<int>(Console.ReadLine().Split(' ').Select(s // => int.Parse(s))); List<int> values = new List<int>(); string input = Console.ReadLine(); // int n = int.Parse(input.Split(' ')[0]); // int m = int.Parse(input.Split(' ')[1]); // int k = int.Parse(input.Split(' ')[2]); int n = int.Parse(input); List<int> values = new List<int>(); values.Add(n); int a = 1; if (n == 1) { Console.WriteLine(1); return; } if (n == 2) { Console.WriteLine(1); return; } while (n != 4) { if (n % 2 == 0) { n /= 2; } else { n = n * 3 + 1; } a++; } Console.WriteLine(a + 3); } }
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // List<int> values = new List<int>(Console.ReadLine().Split(' ').Select(s // => int.Parse(s))); List<int> values = new List<int>(); string input = Console.ReadLine(); // int n = int.Parse(input.Split(' ')[0]); // int m = int.Parse(input.Split(' ')[1]); // int k = int.Parse(input.Split(' ')[2]); int n = int.Parse(input); List<int> values = new List<int>(); values.Add(n); int a = 1; if (n == 1) { Console.WriteLine(4); return; } if (n == 2) { Console.WriteLine(4); return; } while (n != 4) { if (n % 2 == 0) { n /= 2; } else { n = n * 3 + 1; } a++; } Console.WriteLine(a + 3); } }
[["-", 0, 1, 0, 213, 3, 4, 0, 28, 0, 203], ["+", 0, 1, 0, 213, 3, 4, 0, 28, 0, 203]]
8
159
4
using System; using System.Linq; using System.Collections.Generic; namespace AtCoder { class Program { static void Main(string[] args) { var ir = new Resolver(new ConsoleReader()); Console.WriteLine(ir.Resolve()); } } public class Resolver { IInputReader InputReader { get; } public List<string> Messages { get; set; } = new List<string>(); int s; public void ParseLines() { s = int.Parse(InputReader.ReadLine()); } int myFunction(int n) { if (n % 2 == 0) return n / 2; return 3 * n + 1; } public string Resolve() { int i = 1; var nums = new List<int>(); nums.Add(s); while (true) { i++; s = myFunction(s); if (!nums.Contains(s)) break; nums.Add(s); } return i.ToString(); } public Resolver(IInputReader inputReader) { InputReader = inputReader; ParseLines(); } } public interface IInputReader { string ReadLine(); } class ConsoleReader : IInputReader { string IInputReader.ReadLine() { return Console.ReadLine(); } } }
using System; using System.Linq; using System.Collections.Generic; namespace AtCoder { class Program { static void Main(string[] args) { var ir = new Resolver(new ConsoleReader()); Console.WriteLine(ir.Resolve()); } } public class Resolver { IInputReader InputReader { get; } public List<string> Messages { get; set; } = new List<string>(); int s; public void ParseLines() { s = int.Parse(InputReader.ReadLine()); } int myFunction(int n) { if (n % 2 == 0) return n / 2; return 3 * n + 1; } public string Resolve() { int i = 1; var nums = new List<int>(); nums.Add(s); while (true) { i++; s = myFunction(s); if (nums.Contains(s)) break; nums.Add(s); } return i.ToString(); } public Resolver(IInputReader inputReader) { InputReader = inputReader; ParseLines(); } } public interface IInputReader { string ReadLine(); } class ConsoleReader : IInputReader { string IInputReader.ReadLine() { return Console.ReadLine(); } } }
[["-", 0, 52, 8, 196, 0, 57, 15, 241, 0, 111]]
8
259
1
using System; using System.Linq; using System.Collections.Generic; using System.IO; class Program { public static long Read() { return long.Parse(Console.ReadLine()); } public static long[] Reads() { return Console.ReadLine().Split().Select(long.Parse).ToArray(); } public static void Main() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); var n = Read(); var input = Reads(); var h = new long[n]; for (int i = 0; i < n; i++) h[i] = input[i]; long active = 0; long answer = 0; for (int i = 0; i < n; i++) { if (active >= h[i]) active = h[i]; else { answer = h[i] - active; active = h[i]; } } Console.WriteLine(answer); Console.Out.Flush(); } }
using System; using System.Linq; using System.Collections.Generic; using System.IO; class Program { public static long Read() { return long.Parse(Console.ReadLine()); } public static long[] Reads() { return Console.ReadLine().Split().Select(long.Parse).ToArray(); } public static void Main() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); var n = Read(); var input = Reads(); var h = new long[n]; for (int i = 0; i < n; i++) h[i] = input[i]; long active = 0; long answer = 0; for (int i = 0; i < n; i++) { if (active >= h[i]) active = h[i]; else { answer += h[i] - active; active = h[i]; } } Console.WriteLine(answer); Console.Out.Flush(); } }
[["-", 75, 196, 0, 1, 0, 11, 0, 202, 0, 32], ["+", 75, 196, 0, 1, 0, 11, 0, 202, 0, 107]]
8
232
2
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace C { public class Program { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } public static void Solve() { var n = int.Parse(Console.ReadLine()); var hi = Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray(); var current = new int[hi.Length]; Console.WriteLine(Dfs(current, hi, 0, hi.Length - 1)); } static int Dfs(int[] current, int[] target, int left, int right) { if (left == right) return target[left]; if (left > right) return 0; var min = 101; for (var i = left; i < right; i++) { min = Math.Min(min, target[i]); } if (min == 101) return 0; var mid = -1; for (var i = left; i <= right; i++) { current[i] += min; target[i] -= min; if (target[i] == 0) mid = i; } var leftValue = Dfs(current, target, left, mid - 1); var rightValue = Dfs(current, target, mid + 1, right); return min + leftValue + rightValue; } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace C { public class Program { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } public static void Solve() { var n = int.Parse(Console.ReadLine()); var hi = Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray(); var current = new int[hi.Length]; Console.WriteLine(Dfs(current, hi, 0, hi.Length - 1)); } static int Dfs(int[] current, int[] target, int left, int right) { if (left == right) return target[left]; if (left > right) return 0; var min = 101; for (var i = left; i <= right; i++) { min = Math.Min(min, target[i]); } if (min == 101) return 0; var mid = -1; for (var i = left; i <= right; i++) { current[i] += min; target[i] -= min; if (target[i] == 0) mid = i; } var leftValue = Dfs(current, target, left, mid - 1); var rightValue = Dfs(current, target, mid + 1, right); return min + leftValue + rightValue; } } }
[["-", 0, 195, 8, 196, 0, 7, 15, 16, 17, 18], ["+", 0, 195, 8, 196, 0, 7, 15, 16, 17, 19]]
8
341
2
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GrandGarden { class Program { static void Main(string[] args) { int N = int.Parse(Console.ReadLine()); string[] strList = Console.ReadLine().Split(' '); List<int> flower = new List<int>(); foreach (var str in strList) { flower.Add(int.Parse(str)); } int roundCount = 0; int dividedCount = 0; bool wateringFlg = false; int flowerMaxValue = flower.Max(); while (flowerMaxValue > 0) { wateringFlg = false; for (int i = 0; i < flower.Count; i++) { if (flower[i] - roundCount > 0) { if (i > 0 && flower[i - 1] - roundCount <= 0 && wateringFlg) { dividedCount++; wateringFlg = false; } else { wateringFlg = true; } } } roundCount++; flowerMaxValue -= 1; } Console.Write(roundCount + dividedCount); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GrandGarden { class Program { static void Main(string[] args) { int N = int.Parse(Console.ReadLine()); string[] strList = Console.ReadLine().Split(' '); List<int> flower = new List<int>(); foreach (var str in strList) { flower.Add(int.Parse(str)); } int roundCount = 0; int dividedCount = 0; bool wateringFlg = false; int flowerMaxValue = flower.Max(); while (flowerMaxValue > 0) { wateringFlg = false; for (int i = 0; i < flower.Count; i++) { if (flower[i] - roundCount > 0) { if (i > 0 && flower[i - 1] - roundCount <= 0 && wateringFlg) { dividedCount++; } else { wateringFlg = true; } } } roundCount++; flowerMaxValue--; } Console.Write(roundCount + dividedCount); Console.ReadKey(); } } }
[["-", 0, 57, 64, 196, 0, 1, 0, 11, 31, 22], ["-", 64, 196, 0, 1, 0, 11, 0, 202, 0, 32], ["-", 64, 196, 0, 1, 0, 11, 12, 211, 0, 147], ["-", 64, 196, 0, 57, 64, 196, 0, 1, 0, 35], ["-", 8, 196, 0, 1, 0, 11, 0, 202, 0, 110], ["-", 0, 52, 8, 196, 0, 1, 0, 11, 12, 203], ["+", 0, 52, 8, 196, 0, 1, 0, 223, 0, 68]]
8
237
7
using System; using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; namespace AtCoder { public class Program { public static void Main(string[] args) { new Program().Solve(new ConsoleInput(Console.In, ' ')); } public void Solve(ConsoleInput cin) { var n = cin.ReadInt; int count = 0; int prev = cin.ReadInt; for (int i = 1; i < n; i++) { var x = cin.ReadInt; if (prev > x) { count += x - prev; } prev = x; } count += prev; Console.WriteLine(count); return; } } public class ConsoleInput { private readonly System.IO.TextReader _stream; private char _separator = ' '; private Queue<string> inputStream; public ConsoleInput(System.IO.TextReader stream, char separator = ' ') { this._separator = separator; this._stream = stream; inputStream = new Queue<string>(); } public string Read { get { if (inputStream.Count != 0) return inputStream.Dequeue(); string[] tmp = _stream.ReadLine().Split(_separator); for (int i = 0; i < tmp.Length; ++i) inputStream.Enqueue(tmp[i]); return inputStream.Dequeue(); } } public string ReadLine { get { return _stream.ReadLine(); } } public int ReadInt { get { return int.Parse(Read); } } public long ReadLong { get { return long.Parse(Read); } } public double ReadDouble { get { return double.Parse(Read); } } public string[] ReadStrArray(long N) { var ret = new string[N]; for (long i = 0; i < N; ++i) ret[i] = Read; return ret; } public int[] ReadIntArray(long N) { var ret = new int[N]; for (long i = 0; i < N; ++i) ret[i] = ReadInt; return ret; } public long[] ReadLongArray(long N) { var ret = new long[N]; for (long i = 0; i < N; ++i) ret[i] = ReadLong; return ret; } public double[] ReadDoubleArray(long N) { var ret = new double[N]; for (long i = 0; i < N; ++i) ret[i] = ReadDouble; return ret; } } }
using System; using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; namespace AtCoder { public class Program { public static void Main(string[] args) { new Program().Solve(new ConsoleInput(Console.In, ' ')); } public void Solve(ConsoleInput cin) { var n = cin.ReadInt; int count = 0; int prev = cin.ReadInt; for (int i = 1; i < n; i++) { var x = cin.ReadInt; if (prev > x) { count += prev - x; } prev = x; } count += prev; Console.WriteLine(count); return; } } public class ConsoleInput { private readonly System.IO.TextReader _stream; private char _separator = ' '; private Queue<string> inputStream; public ConsoleInput(System.IO.TextReader stream, char separator = ' ') { this._separator = separator; this._stream = stream; inputStream = new Queue<string>(); } public string Read { get { if (inputStream.Count != 0) return inputStream.Dequeue(); string[] tmp = _stream.ReadLine().Split(_separator); for (int i = 0; i < tmp.Length; ++i) inputStream.Enqueue(tmp[i]); return inputStream.Dequeue(); } } public string ReadLine { get { return _stream.ReadLine(); } } public int ReadInt { get { return int.Parse(Read); } } public long ReadLong { get { return long.Parse(Read); } } public double ReadDouble { get { return double.Parse(Read); } } public string[] ReadStrArray(long N) { var ret = new string[N]; for (long i = 0; i < N; ++i) ret[i] = Read; return ret; } public int[] ReadIntArray(long N) { var ret = new int[N]; for (long i = 0; i < N; ++i) ret[i] = ReadInt; return ret; } public long[] ReadLongArray(long N) { var ret = new long[N]; for (long i = 0; i < N; ++i) ret[i] = ReadLong; return ret; } public double[] ReadDoubleArray(long N) { var ret = new double[N]; for (long i = 0; i < N; ++i) ret[i] = ReadDouble; return ret; } } }
[["-", 64, 196, 0, 1, 0, 11, 12, 16, 31, 22], ["-", 64, 196, 0, 1, 0, 11, 12, 16, 17, 33], ["+", 64, 196, 0, 1, 0, 11, 12, 16, 17, 33], ["+", 64, 196, 0, 1, 0, 11, 12, 16, 12, 22]]
8
531
4
using System; using System.Collections.Generic; using CompLib.Collections; using CompLib.Util; public class Program { private int N, K; private Sushi[] S; public void Solve() { var sc = new Scanner(); N = sc.NextInt(); K = sc.NextInt(); S = new Sushi[N]; for (int i = 0; i < N; i++) { S[i] = new Sushi(sc.NextInt(), sc.NextLong()); } Array.Sort(S, (l, r) => r.D.CompareTo(l.D)); // 食べる寿司 種類iをcnt[i]個食べる bool[] f = new bool[100001]; // Sの美味しさ上位K個選ぶ long sum = 0; long x = 0; var q = new Queue<long>(); for (int i = 0; i < K; i++) { sum += S[i].D; if (!f[S[i].T]) x++; else q.Enqueue(S[i].D); f[S[i].T] = true; } long ans = sum + x * x; for (int i = K; i < N && q.Count > 0; i++) { // iを食べても種類が増えない if (f[S[i].T]) continue; sum -= q.Dequeue(); sum += S[i].D; x++; f[S[i].T] = true; ans = Math.Max(ans, sum + x * x); } Console.WriteLine(ans); } public static void Main(string[] args) => new Program().Solve(); } // https://bitbucket.org/camypaper/complib namespace CompLib.Collections { using System; using System.Collections.Generic; #region PriorityQueue /// <summary> /// 指定した型のインスタンスを最も価値が低い順に取り出すことが可能な可変サイズのコレクションを表します. /// </summary> /// <typeparam name="T">優先度付きキュー内の要素の型を指定します.</typeparam> /// <remarks>内部的にはバイナリヒープによって実装されています.</remarks> public class PriorityQueue<T> { readonly List<T> heap = new List<T>(); readonly Comparison<T> cmp; /// <summary> /// デフォルトの比較子を使用してインスタンスを初期化します. /// </summary> /// <remarks>この操作は O(1) で実行されます.</remarks> public PriorityQueue() { cmp = Comparer<T>.Default.Compare; } /// <summary> /// デリゲートで表されるような比較関数を使用してインスタンスを初期化します. /// </summary> /// <param name="comparison"></param> /// <remarks>この操作は O(1) で実行されます.</remarks> public PriorityQueue(Comparison<T> comparison) { cmp = comparison; } /// <summary> /// 指定された比較子を使用してインスタンスを初期化します. /// </summary> /// <param name="comparer"></param> /// <remarks>この操作は O(1) で実行されます.</remarks> public PriorityQueue(IComparer<T> comparer) { cmp = comparer.Compare; } /// <summary> /// 優先度付きキューに要素を追加します. /// </summary> /// <param name="item">優先度付きキューに追加される要素</param> /// <remarks>最悪計算量 O(log N) で実行されます.</remarks> public void Enqueue(T item) { var pos = heap.Count; heap.Add(item); while (pos > 0) { var par = (pos - 1) / 2; if (cmp(heap[par], item) <= 0) break; heap[pos] = heap[par]; pos = par; } heap[pos] = item; } /// <summary> /// 優先度付きキューから最も価値が低い要素を削除し,返します. /// </summary> /// <returns>優先度付きキューから削除された要素.</returns> /// <remarks>最悪計算量 O(log N) で実行されます.</remarks> public T Dequeue() { var ret = heap[0]; var pos = 0; var x = heap[heap.Count - 1]; while (pos * 2 + 1 < heap.Count - 1) { var lch = pos * 2 + 1; var rch = pos * 2 + 2; if (rch < heap.Count - 1 && cmp(heap[rch], heap[lch]) < 0) lch = rch; if (cmp(heap[lch], x) >= 0) break; heap[pos] = heap[lch]; pos = lch; } heap[pos] = x; heap.RemoveAt(heap.Count - 1); return ret; } /// <summary> /// 優先度付きキューに含まれる最も価値が低い要素を削除せずに返します. /// </summary> /// <returns>優先度付きキューに含まれる最も価値が低い要素.</returns> /// <remarks>この操作は O(1) で実行されます.</remarks> public T Peek() { return heap[0]; } /// <summary> /// 優先度付きキュー内の要素の数を取得します. /// </summary> /// <returns>優先度付キュー内にある要素の数</returns> /// <remarks>最悪計算量 O(1) で実行されます.</remarks> public int Count { get { return heap.Count; } } /// <summary> /// 優先度付きキュー内に要素が存在するかどうかを O(1) で判定します. /// </summary> /// <returns>優先度付キュー内にある要素が存在するならば /// true,そうでなければ false.</returns> <remarks>この操作は O(1) /// で実行されます.</remarks> public bool Any() { return heap.Count > 0; } /// <summary> /// 優先度付きキューに含まれる要素を昇順に並べて返します. /// </summary> /// <remarks>この操作は計算量 O(N log N)で実行されます.</remarks> public T[] Items { get { var ret = heap.ToArray(); Array.Sort(ret, cmp); return ret; } } } #endregion } struct Sushi { public int T; public long D; public Sushi(int t, long d) { T = t; D = d; } } namespace CompLib.Util { using System; using System.Linq; class Scanner { private string[] _line; private int _index; private const char Separator = ' '; public Scanner() { _line = new string[0]; _index = 0; } public string Next() { while (_index >= _line.Length) { _line = Console.ReadLine().Split(Separator); _index = 0; } return _line[_index++]; } public int NextInt() => int.Parse(Next()); public long NextLong() => long.Parse(Next()); public double NextDouble() => double.Parse(Next()); public decimal NextDecimal() => decimal.Parse(Next()); public char NextChar() => Next()[0]; public char[] NextCharArray() => Next().ToCharArray(); public string[] Array() { _line = Console.ReadLine().Split(Separator); _index = _line.Length; return _line; } public int[] IntArray() => Array().Select(int.Parse).ToArray(); public long[] LongArray() => Array().Select(long.Parse).ToArray(); public double[] DoubleArray() => Array().Select(double.Parse).ToArray(); public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray(); } }
using System; using System.Collections.Generic; using CompLib.Collections; using CompLib.Util; public class Program { private int N, K; private Sushi[] S; public void Solve() { var sc = new Scanner(); N = sc.NextInt(); K = sc.NextInt(); S = new Sushi[N]; for (int i = 0; i < N; i++) { S[i] = new Sushi(sc.NextInt(), sc.NextLong()); } Array.Sort(S, (l, r) => r.D.CompareTo(l.D)); // 食べる寿司 種類iをcnt[i]個食べる bool[] f = new bool[100001]; // Sの美味しさ上位K個選ぶ long sum = 0; long x = 0; var q = new Stack<long>(); for (int i = 0; i < K; i++) { sum += S[i].D; if (!f[S[i].T]) x++; else q.Push(S[i].D); f[S[i].T] = true; } long ans = sum + x * x; for (int i = K; i < N && q.Count > 0; i++) { // iを食べても種類が増えない if (f[S[i].T]) continue; sum -= q.Pop(); sum += S[i].D; x++; f[S[i].T] = true; ans = Math.Max(ans, sum + x * x); } Console.WriteLine(ans); } public static void Main(string[] args) => new Program().Solve(); } // https://bitbucket.org/camypaper/complib namespace CompLib.Collections { using System; using System.Collections.Generic; #region PriorityQueue /// <summary> /// 指定した型のインスタンスを最も価値が低い順に取り出すことが可能な可変サイズのコレクションを表します. /// </summary> /// <typeparam name="T">優先度付きキュー内の要素の型を指定します.</typeparam> /// <remarks>内部的にはバイナリヒープによって実装されています.</remarks> public class PriorityQueue<T> { readonly List<T> heap = new List<T>(); readonly Comparison<T> cmp; /// <summary> /// デフォルトの比較子を使用してインスタンスを初期化します. /// </summary> /// <remarks>この操作は O(1) で実行されます.</remarks> public PriorityQueue() { cmp = Comparer<T>.Default.Compare; } /// <summary> /// デリゲートで表されるような比較関数を使用してインスタンスを初期化します. /// </summary> /// <param name="comparison"></param> /// <remarks>この操作は O(1) で実行されます.</remarks> public PriorityQueue(Comparison<T> comparison) { cmp = comparison; } /// <summary> /// 指定された比較子を使用してインスタンスを初期化します. /// </summary> /// <param name="comparer"></param> /// <remarks>この操作は O(1) で実行されます.</remarks> public PriorityQueue(IComparer<T> comparer) { cmp = comparer.Compare; } /// <summary> /// 優先度付きキューに要素を追加します. /// </summary> /// <param name="item">優先度付きキューに追加される要素</param> /// <remarks>最悪計算量 O(log N) で実行されます.</remarks> public void Enqueue(T item) { var pos = heap.Count; heap.Add(item); while (pos > 0) { var par = (pos - 1) / 2; if (cmp(heap[par], item) <= 0) break; heap[pos] = heap[par]; pos = par; } heap[pos] = item; } /// <summary> /// 優先度付きキューから最も価値が低い要素を削除し,返します. /// </summary> /// <returns>優先度付きキューから削除された要素.</returns> /// <remarks>最悪計算量 O(log N) で実行されます.</remarks> public T Dequeue() { var ret = heap[0]; var pos = 0; var x = heap[heap.Count - 1]; while (pos * 2 + 1 < heap.Count - 1) { var lch = pos * 2 + 1; var rch = pos * 2 + 2; if (rch < heap.Count - 1 && cmp(heap[rch], heap[lch]) < 0) lch = rch; if (cmp(heap[lch], x) >= 0) break; heap[pos] = heap[lch]; pos = lch; } heap[pos] = x; heap.RemoveAt(heap.Count - 1); return ret; } /// <summary> /// 優先度付きキューに含まれる最も価値が低い要素を削除せずに返します. /// </summary> /// <returns>優先度付きキューに含まれる最も価値が低い要素.</returns> /// <remarks>この操作は O(1) で実行されます.</remarks> public T Peek() { return heap[0]; } /// <summary> /// 優先度付きキュー内の要素の数を取得します. /// </summary> /// <returns>優先度付キュー内にある要素の数</returns> /// <remarks>最悪計算量 O(1) で実行されます.</remarks> public int Count { get { return heap.Count; } } /// <summary> /// 優先度付きキュー内に要素が存在するかどうかを O(1) で判定します. /// </summary> /// <returns>優先度付キュー内にある要素が存在するならば /// true,そうでなければ false.</returns> <remarks>この操作は O(1) /// で実行されます.</remarks> public bool Any() { return heap.Count > 0; } /// <summary> /// 優先度付きキューに含まれる要素を昇順に並べて返します. /// </summary> /// <remarks>この操作は計算量 O(N log N)で実行されます.</remarks> public T[] Items { get { var ret = heap.ToArray(); Array.Sort(ret, cmp); return ret; } } } #endregion } struct Sushi { public int T; public long D; public Sushi(int t, long d) { T = t; D = d; } } namespace CompLib.Util { using System; using System.Linq; class Scanner { private string[] _line; private int _index; private const char Separator = ' '; public Scanner() { _line = new string[0]; _index = 0; } public string Next() { while (_index >= _line.Length) { _line = Console.ReadLine().Split(Separator); _index = 0; } return _line[_index++]; } public int NextInt() => int.Parse(Next()); public long NextLong() => long.Parse(Next()); public double NextDouble() => double.Parse(Next()); public decimal NextDecimal() => decimal.Parse(Next()); public char NextChar() => Next()[0]; public char[] NextCharArray() => Next().ToCharArray(); public string[] Array() { _line = Console.ReadLine().Split(Separator); _index = _line.Length; return _line; } public int[] IntArray() => Array().Select(int.Parse).ToArray(); public long[] LongArray() => Array().Select(long.Parse).ToArray(); public double[] DoubleArray() => Array().Select(double.Parse).ToArray(); public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray(); } }
[["-", 0, 200, 0, 212, 0, 230, 39, 236, 141, 22], ["+", 0, 200, 0, 212, 0, 230, 39, 236, 141, 22], ["-", 0, 57, 75, 1, 0, 213, 63, 214, 141, 22], ["+", 0, 57, 75, 1, 0, 213, 63, 214, 141, 22], ["-", 0, 1, 0, 11, 12, 213, 63, 214, 141, 22], ["+", 0, 1, 0, 11, 12, 213, 63, 214, 141, 22]]
8
1,142
6
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Contest { class Scanner { public Scanner() { _stream = new StreamReader(Console.OpenStandardInput()); _pos = 0; _line = new string[0]; _separator = ' '; } private char _separator; private StreamReader _stream; private int _pos; private string[] _line; #region get a element public string Next() { if (_pos >= _line.Length) { _line = _stream.ReadLine().Split(_separator); _pos = 0; } return _line[_pos++]; } public int NextInt() { return int.Parse(Next()); } public long NextLong() { return long.Parse(Next()); } public double NextDouble() { return double.Parse(Next()); } #endregion #region convert array private int[] ToIntArray(string[] array) { var result = new int[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = int.Parse(array[i]); } return result; } private long[] ToLongArray(string[] array) { var result = new long[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = long.Parse(array[i]); } return result; } private double[] ToDoubleArray(string[] array) { var result = new double[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = double.Parse(array[i]); } return result; } #endregion #region get row elements #region get array public string[] Array() { if (_pos >= _line.Length) _line = _stream.ReadLine().Split(_separator); _pos = _line.Length; return _line; } public int[] IntArray() { return ToIntArray(Array()); } public long[] LongArray() { return ToLongArray(Array()); } public double[] DoubleArray() { return ToDoubleArray(Array()); } #endregion #region get 2 ~4 elements public void GetRow(out string a, out string b) { a = Next(); b = Next(); } public void GetRow(out string a, out string b, out string c) { a = Next(); b = Next(); c = Next(); } public void GetRow(out string a, out string b, out string c, out string d) { a = Next(); b = Next(); c = Next(); d = Next(); } public void GetIntRow(out int a, out int b) { a = NextInt(); b = NextInt(); } public void GetIntRow(out int a, out int b, out int c) { a = NextInt(); b = NextInt(); c = NextInt(); } public void GetIntRow(out int a, out int b, out int c, out int d) { a = NextInt(); b = NextInt(); c = NextInt(); d = NextInt(); } public void GetLongRow(out long a, out long b) { a = NextLong(); b = NextLong(); } public void GetLongRow(out long a, out long b, out long c) { a = NextLong(); b = NextLong(); c = NextLong(); } public void GetLongRow(out long a, out long b, out long c, out long d) { a = NextLong(); b = NextLong(); c = NextLong(); d = NextLong(); } public void GetDoubleRow(out double a, out double b) { a = NextDouble(); b = NextDouble(); } public void GetDoubleRow(out double a, out double b, out double c) { a = NextDouble(); b = NextDouble(); c = NextDouble(); } public void GetDoubleRow(out double a, out double b, out double c, out double d) { a = NextDouble(); b = NextDouble(); c = NextDouble(); d = NextDouble(); } #endregion #endregion #region get 2 ~4 column elements public void GetColumn(int n, out string[] a) { a = new string[n]; for (int i = 0; i < n; i++) { a[i] = Next(); } } public void GetColumn(int n, out string[] a, out string[] b) { a = new string[n]; b = new string[n]; for (int i = 0; i < n; i++) { GetRow(out a[i], out b[i]); } } public void GetColumn(int n, out string[] a, out string[] b, out string[] c) { a = new string[n]; b = new string[n]; c = new string[n]; for (int i = 0; i < n; i++) { GetRow(out a[i], out b[i], out c[i]); } } public void GetColumn(int n, out string[] a, out string[] b, out string[] c, out string[] d) { a = new string[n]; b = new string[n]; c = new string[n]; d = new string[n]; for (int i = 0; i < n; i++) { GetRow(out a[i], out b[i], out c[i], out d[i]); } } public void GetIntColumn(int n, out int[] a) { string[] sa; GetColumn(n, out sa); a = ToIntArray(sa); } public void GetIntColumn(int n, out int[] a, out int[] b) { string[] sa, sb; GetColumn(n, out sa, out sb); a = ToIntArray(sa); b = ToIntArray(sb); } public void GetIntColumn(int n, out int[] a, out int[] b, out int[] c) { string[] sa, sb, sc; GetColumn(n, out sa, out sb, out sc); a = ToIntArray(sa); b = ToIntArray(sb); c = ToIntArray(sc); } public void GetIntColumn(int n, out int[] a, out int[] b, out int[] c, out int[] d) { string[] sa, sb, sc, sd; GetColumn(n, out sa, out sb, out sc, out sd); a = ToIntArray(sa); b = ToIntArray(sb); c = ToIntArray(sc); d = ToIntArray(sd); } public void GetLongColumn(int n, out long[] a) { string[] sa; GetColumn(n, out sa); a = ToLongArray(sa); } public void GetLongColumn(int n, out long[] a, out long[] b) { string[] sa, sb; GetColumn(n, out sa, out sb); a = ToLongArray(sa); b = ToLongArray(sb); } public void GetLongColumn(int n, out long[] a, out long[] b, out long[] c) { string[] sa, sb, sc; GetColumn(n, out sa, out sb, out sc); a = ToLongArray(sa); b = ToLongArray(sb); c = ToLongArray(sc); } public void GetLongColumn(int n, out long[] a, out long[] b, out long[] c, out long[] d) { string[] sa, sb, sc, sd; GetColumn(n, out sa, out sb, out sc, out sd); a = ToLongArray(sa); b = ToLongArray(sb); c = ToLongArray(sc); d = ToLongArray(sd); } public void GetDoubleColumn(int n, out double[] a) { string[] sa; GetColumn(n, out sa); a = ToDoubleArray(sa); } public void GetDoubleColumn(int n, out double[] a, out double[] b) { string[] sa, sb; GetColumn(n, out sa, out sb); a = ToDoubleArray(sa); b = ToDoubleArray(sb); } public void GetDoubleColumn(int n, out double[] a, out double[] b, out double[] c) { string[] sa, sb, sc; GetColumn(n, out sa, out sb, out sc); a = ToDoubleArray(sa); b = ToDoubleArray(sb); c = ToDoubleArray(sc); } public void GetDoubleColumn(int n, out double[] a, out double[] b, out double[] c, out double[] d) { string[] sa, sb, sc, sd; GetColumn(n, out sa, out sb, out sc, out sd); a = ToDoubleArray(sa); b = ToDoubleArray(sb); c = ToDoubleArray(sc); d = ToDoubleArray(sd); } #endregion #region get matrix string[][] GetMatrix(int h) { string[][] result = new string[h][]; for (int i = 0; i < h; i++) { result[i] = Array(); } return result; } int[][] GetIntMatrix(int h) { int[][] result = new int [h][]; for (int i = 0; i < h; i++) { result[i] = IntArray(); } return result; } long[][] GetLongMatrix(int h) { long[][] result = new long [h][]; for (int i = 0; i < h; i++) { result[i] = LongArray(); } return result; } double[][] GetDoubleMatrix(int h) { double[][] result = new double [h][]; for (int i = 0; i < h; i++) { result[i] = DoubleArray(); } return result; } char[][] GetCharMatrix(int h) { char[][] result = new char [h][]; for (int i = 0; i < h; i++) { result[i] = Next().ToCharArray(); } return result; } #endregion } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> class PriorityQueue<T> { private readonly List<T> heap; private readonly Comparison<T> compare; private int size; public PriorityQueue() : this(Comparer<T>.Default) {} public PriorityQueue(IComparer<T> comparer) : this(16, comparer.Compare) {} public PriorityQueue(Comparison<T> comparison) : this(16, comparison) {} public PriorityQueue(int capacity, Comparison<T> comparison) { this.heap = new List<T>(capacity); this.compare = comparison; } public void Enqueue(T item) { this.heap.Add(item); var i = size++; while (i > 0) { var p = (i - 1) >> 1; if (compare(this.heap[p], item) <= 0) break; this.heap[i] = heap[p]; i = p; } this.heap[i] = item; } public T Dequeue() { var ret = this.heap[0]; var x = this.heap[--size]; var i = 0; while ((i << 1) + 1 < size) { var a = (i << 1) + 1; var b = (i << 1) + 2; if (b < size && compare(heap[b], heap[a]) < 0) a = b; if (compare(heap[a], x) >= 0) break; heap[i] = heap[a]; i = a; } heap[i] = x; heap.RemoveAt(size); return ret; } public T Peek() { return heap[0]; } public int Count { get { return size; } } public bool Any() { return size > 0; } } struct Sushi { public long T; public long D; } class Program { private int N, K; private Sushi[] S; private void Scan() { Scanner sc = new Scanner(); N = sc.NextInt(); K = sc.NextInt(); S = new Sushi[N]; for (int i = 0; i < N; i++) { sc.GetLongRow(out S[i].T, out S[i].D); } } PriorityQueue<Sushi> pq = new PriorityQueue<Sushi>((a, b) => -a.D.CompareTo(b.D)); PriorityQueue<Sushi> pq2 = new PriorityQueue<Sushi>((a, b) => a.D.CompareTo(b.D)); private Dictionary<long, int> map = new Dictionary<long, int>(); public void Solve() { Scan(); foreach (var sushi in S) { pq.Enqueue(sushi); } long DSum = 0; long TCnt = 0; for (int i = 0; i < K; i++) { var s = pq.Dequeue(); DSum += s.D; pq2.Enqueue(s); int o; map.TryGetValue(s.T, out o); map[s.T] = o + 1; } TCnt = map.Count; long ans = DSum + TCnt * TCnt; while (pq.Count > 0 && pq2.Count > 0) { while (pq2.Count > 0) { var s = pq2.Dequeue(); if (map[s.T] > 1) { while (pq.Count > 0) { var ss = pq.Dequeue(); int o; map.TryGetValue(ss.T, out o); if (o == 1) { TCnt++; DSum += ss.D; DSum -= s.D; ans = Math.Max(ans, DSum + TCnt * TCnt); map[s.T]--; map[ss.T] = 1; break; } } } } } Console.WriteLine(ans); } static void Main(string[] args) => new Program().Solve(); } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Contest { class Scanner { public Scanner() { _stream = new StreamReader(Console.OpenStandardInput()); _pos = 0; _line = new string[0]; _separator = ' '; } private char _separator; private StreamReader _stream; private int _pos; private string[] _line; #region get a element public string Next() { if (_pos >= _line.Length) { _line = _stream.ReadLine().Split(_separator); _pos = 0; } return _line[_pos++]; } public int NextInt() { return int.Parse(Next()); } public long NextLong() { return long.Parse(Next()); } public double NextDouble() { return double.Parse(Next()); } #endregion #region convert array private int[] ToIntArray(string[] array) { var result = new int[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = int.Parse(array[i]); } return result; } private long[] ToLongArray(string[] array) { var result = new long[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = long.Parse(array[i]); } return result; } private double[] ToDoubleArray(string[] array) { var result = new double[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = double.Parse(array[i]); } return result; } #endregion #region get row elements #region get array public string[] Array() { if (_pos >= _line.Length) _line = _stream.ReadLine().Split(_separator); _pos = _line.Length; return _line; } public int[] IntArray() { return ToIntArray(Array()); } public long[] LongArray() { return ToLongArray(Array()); } public double[] DoubleArray() { return ToDoubleArray(Array()); } #endregion #region get 2 ~4 elements public void GetRow(out string a, out string b) { a = Next(); b = Next(); } public void GetRow(out string a, out string b, out string c) { a = Next(); b = Next(); c = Next(); } public void GetRow(out string a, out string b, out string c, out string d) { a = Next(); b = Next(); c = Next(); d = Next(); } public void GetIntRow(out int a, out int b) { a = NextInt(); b = NextInt(); } public void GetIntRow(out int a, out int b, out int c) { a = NextInt(); b = NextInt(); c = NextInt(); } public void GetIntRow(out int a, out int b, out int c, out int d) { a = NextInt(); b = NextInt(); c = NextInt(); d = NextInt(); } public void GetLongRow(out long a, out long b) { a = NextLong(); b = NextLong(); } public void GetLongRow(out long a, out long b, out long c) { a = NextLong(); b = NextLong(); c = NextLong(); } public void GetLongRow(out long a, out long b, out long c, out long d) { a = NextLong(); b = NextLong(); c = NextLong(); d = NextLong(); } public void GetDoubleRow(out double a, out double b) { a = NextDouble(); b = NextDouble(); } public void GetDoubleRow(out double a, out double b, out double c) { a = NextDouble(); b = NextDouble(); c = NextDouble(); } public void GetDoubleRow(out double a, out double b, out double c, out double d) { a = NextDouble(); b = NextDouble(); c = NextDouble(); d = NextDouble(); } #endregion #endregion #region get 2 ~4 column elements public void GetColumn(int n, out string[] a) { a = new string[n]; for (int i = 0; i < n; i++) { a[i] = Next(); } } public void GetColumn(int n, out string[] a, out string[] b) { a = new string[n]; b = new string[n]; for (int i = 0; i < n; i++) { GetRow(out a[i], out b[i]); } } public void GetColumn(int n, out string[] a, out string[] b, out string[] c) { a = new string[n]; b = new string[n]; c = new string[n]; for (int i = 0; i < n; i++) { GetRow(out a[i], out b[i], out c[i]); } } public void GetColumn(int n, out string[] a, out string[] b, out string[] c, out string[] d) { a = new string[n]; b = new string[n]; c = new string[n]; d = new string[n]; for (int i = 0; i < n; i++) { GetRow(out a[i], out b[i], out c[i], out d[i]); } } public void GetIntColumn(int n, out int[] a) { string[] sa; GetColumn(n, out sa); a = ToIntArray(sa); } public void GetIntColumn(int n, out int[] a, out int[] b) { string[] sa, sb; GetColumn(n, out sa, out sb); a = ToIntArray(sa); b = ToIntArray(sb); } public void GetIntColumn(int n, out int[] a, out int[] b, out int[] c) { string[] sa, sb, sc; GetColumn(n, out sa, out sb, out sc); a = ToIntArray(sa); b = ToIntArray(sb); c = ToIntArray(sc); } public void GetIntColumn(int n, out int[] a, out int[] b, out int[] c, out int[] d) { string[] sa, sb, sc, sd; GetColumn(n, out sa, out sb, out sc, out sd); a = ToIntArray(sa); b = ToIntArray(sb); c = ToIntArray(sc); d = ToIntArray(sd); } public void GetLongColumn(int n, out long[] a) { string[] sa; GetColumn(n, out sa); a = ToLongArray(sa); } public void GetLongColumn(int n, out long[] a, out long[] b) { string[] sa, sb; GetColumn(n, out sa, out sb); a = ToLongArray(sa); b = ToLongArray(sb); } public void GetLongColumn(int n, out long[] a, out long[] b, out long[] c) { string[] sa, sb, sc; GetColumn(n, out sa, out sb, out sc); a = ToLongArray(sa); b = ToLongArray(sb); c = ToLongArray(sc); } public void GetLongColumn(int n, out long[] a, out long[] b, out long[] c, out long[] d) { string[] sa, sb, sc, sd; GetColumn(n, out sa, out sb, out sc, out sd); a = ToLongArray(sa); b = ToLongArray(sb); c = ToLongArray(sc); d = ToLongArray(sd); } public void GetDoubleColumn(int n, out double[] a) { string[] sa; GetColumn(n, out sa); a = ToDoubleArray(sa); } public void GetDoubleColumn(int n, out double[] a, out double[] b) { string[] sa, sb; GetColumn(n, out sa, out sb); a = ToDoubleArray(sa); b = ToDoubleArray(sb); } public void GetDoubleColumn(int n, out double[] a, out double[] b, out double[] c) { string[] sa, sb, sc; GetColumn(n, out sa, out sb, out sc); a = ToDoubleArray(sa); b = ToDoubleArray(sb); c = ToDoubleArray(sc); } public void GetDoubleColumn(int n, out double[] a, out double[] b, out double[] c, out double[] d) { string[] sa, sb, sc, sd; GetColumn(n, out sa, out sb, out sc, out sd); a = ToDoubleArray(sa); b = ToDoubleArray(sb); c = ToDoubleArray(sc); d = ToDoubleArray(sd); } #endregion #region get matrix string[][] GetMatrix(int h) { string[][] result = new string[h][]; for (int i = 0; i < h; i++) { result[i] = Array(); } return result; } int[][] GetIntMatrix(int h) { int[][] result = new int [h][]; for (int i = 0; i < h; i++) { result[i] = IntArray(); } return result; } long[][] GetLongMatrix(int h) { long[][] result = new long [h][]; for (int i = 0; i < h; i++) { result[i] = LongArray(); } return result; } double[][] GetDoubleMatrix(int h) { double[][] result = new double [h][]; for (int i = 0; i < h; i++) { result[i] = DoubleArray(); } return result; } char[][] GetCharMatrix(int h) { char[][] result = new char [h][]; for (int i = 0; i < h; i++) { result[i] = Next().ToCharArray(); } return result; } #endregion } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> class PriorityQueue<T> { private readonly List<T> heap; private readonly Comparison<T> compare; private int size; public PriorityQueue() : this(Comparer<T>.Default) {} public PriorityQueue(IComparer<T> comparer) : this(16, comparer.Compare) {} public PriorityQueue(Comparison<T> comparison) : this(16, comparison) {} public PriorityQueue(int capacity, Comparison<T> comparison) { this.heap = new List<T>(capacity); this.compare = comparison; } public void Enqueue(T item) { this.heap.Add(item); var i = size++; while (i > 0) { var p = (i - 1) >> 1; if (compare(this.heap[p], item) <= 0) break; this.heap[i] = heap[p]; i = p; } this.heap[i] = item; } public T Dequeue() { var ret = this.heap[0]; var x = this.heap[--size]; var i = 0; while ((i << 1) + 1 < size) { var a = (i << 1) + 1; var b = (i << 1) + 2; if (b < size && compare(heap[b], heap[a]) < 0) a = b; if (compare(heap[a], x) >= 0) break; heap[i] = heap[a]; i = a; } heap[i] = x; heap.RemoveAt(size); return ret; } public T Peek() { return heap[0]; } public int Count { get { return size; } } public bool Any() { return size > 0; } } struct Sushi { public long T; public long D; } class Program { private int N, K; private Sushi[] S; private void Scan() { Scanner sc = new Scanner(); N = sc.NextInt(); K = sc.NextInt(); S = new Sushi[N]; for (int i = 0; i < N; i++) { sc.GetLongRow(out S[i].T, out S[i].D); } } PriorityQueue<Sushi> pq = new PriorityQueue<Sushi>((a, b) => -a.D.CompareTo(b.D)); PriorityQueue<Sushi> pq2 = new PriorityQueue<Sushi>((a, b) => a.D.CompareTo(b.D)); private Dictionary<long, int> map = new Dictionary<long, int>(); public void Solve() { Scan(); foreach (var sushi in S) { pq.Enqueue(sushi); } long DSum = 0; long TCnt = 0; for (int i = 0; i < K; i++) { var s = pq.Dequeue(); DSum += s.D; pq2.Enqueue(s); int o; map.TryGetValue(s.T, out o); map[s.T] = o + 1; } TCnt = map.Count; long ans = DSum + TCnt * TCnt; while (pq.Count > 0 && pq2.Count > 0) { while (pq2.Count > 0) { var s = pq2.Dequeue(); if (map[s.T] > 1) { while (pq.Count > 0) { var ss = pq.Dequeue(); int o; map.TryGetValue(ss.T, out o); if (o == 0) { TCnt++; DSum += ss.D; DSum -= s.D; ans = Math.Max(ans, DSum + TCnt * TCnt); map[s.T]--; map[ss.T] = 1; break; } } } } } Console.WriteLine(ans); } static void Main(string[] args) => new Program().Solve(); } }
[["-", 0, 52, 8, 196, 0, 57, 15, 16, 12, 203], ["+", 0, 52, 8, 196, 0, 57, 15, 16, 12, 203]]
8
3,092
2
using System; using static System.Console; using static System.Math; using System.IO; using System.Collections.Generic; namespace I_am_the_green_coder { class Inonoa { // なんか入力用の関数作ったけどまだテストしてないので使う前に確かめて static void Main() { long[] nk = ILongs(); long n = nk[0]; long k = nk[1]; long[][] td = ILongLongs(n); Array.Sort(td, Compare); // for(int i=0;i<n;i++){ // Console.Write(td[i][0]); // Console.Write(" "); // Console.WriteLine(td[i][1]); //} HashSet<long> sset = new HashSet<long>(); bool[] kaburi = new bool[n]; long ans = 0; long ansppoi = 0; long syurui = k; for (long i = 0; i < k; i++) { ans += td[i][1]; ansppoi += td[i][1]; if (kaburi[i] = !sset.Add(td[i][0])) { syurui--; } } ans += syurui * syurui; ansppoi += syurui * syurui; long imal = k - 1; long imar = k; while (imal > -1 && imar < n) { if (kaburi[imal]) { if (sset.Add(td[imar][0])) { ansppoi -= td[imal][1]; ansppoi += td[imar][1]; ansppoi += 2 * syurui + 1; syurui++; if (ans < ansppoi) ans = ansppoi; } else { imar++; } } else { imal--; } } Console.WriteLine(ans); } static int Compare(long[] a, long[] b) { if (a[1] > b[1]) return -1; if (a[1] < b[1]) return 1; return 0; } static readonly long MOD = 1000000007; ///< summary>a_1, a_2, a_3, ...みたいなの</summary> static long[] ILongs() { string[] s = ReadLine().Split(); long[] re = new long[s.Length]; for (long i = 0; i < s.Length; i++) { re[i] = long.Parse(s[i]); } return re; } ///< summary>xooxoxoxxoxo...みたいなの</summary> static char[] IChars() { return ReadLine().ToCharArray(); } ///< summary>n m とかをちょっとはやくかくだけ</summary> static string[] IStrings() { return ReadLine().Split(); } ///< summary>n行の入力を取ったり</summary> static long[][] ILongLongs(long n) { long[][] re = new long [n][]; for (long i = 0; i < n; i++) { string[] s = ReadLine().Split(); re[i] = new long[s.Length]; for (long j = 0; j < s.Length; j++) { re[i][j] = long.Parse(s[j]); } } return re; } ///< summary>n行の文字列を取ったり</summary> static char[][] ICharsChars(long n) { char[][] re = new char [n][]; for (long i = 0; i < n; i++) { re[i] = ReadLine().ToCharArray(); } return re; } } }
using System; using static System.Console; using static System.Math; using System.IO; using System.Collections.Generic; namespace I_am_the_green_coder { class Inonoa { // なんか入力用の関数作ったけどまだテストしてないので使う前に確かめて static void Main() { long[] nk = ILongs(); long n = nk[0]; long k = nk[1]; long[][] td = ILongLongs(n); Array.Sort(td, Compare); // for(int i=0;i<n;i++){ // Console.Write(td[i][0]); // Console.Write(" "); // Console.WriteLine(td[i][1]); //} HashSet<long> sset = new HashSet<long>(); bool[] kaburi = new bool[n]; long ans = 0; long ansppoi = 0; long syurui = k; for (long i = 0; i < k; i++) { ans += td[i][1]; ansppoi += td[i][1]; if (kaburi[i] = !sset.Add(td[i][0])) { syurui--; } } ans += syurui * syurui; ansppoi += syurui * syurui; long imal = k - 1; long imar = k; while (imal > -1 && imar < n) { if (kaburi[imal]) { if (sset.Add(td[imar][0])) { ansppoi -= td[imal][1]; ansppoi += td[imar][1]; ansppoi += 2 * syurui + 1; syurui++; if (ans < ansppoi) ans = ansppoi; imal--; imar++; } else { imar++; } } else { imal--; } } Console.WriteLine(ans); } static int Compare(long[] a, long[] b) { if (a[1] > b[1]) return -1; if (a[1] < b[1]) return 1; return 0; } static readonly long MOD = 1000000007; ///< summary>a_1, a_2, a_3, ...みたいなの</summary> static long[] ILongs() { string[] s = ReadLine().Split(); long[] re = new long[s.Length]; for (long i = 0; i < s.Length; i++) { re[i] = long.Parse(s[i]); } return re; } ///< summary>xooxoxoxxoxo...みたいなの</summary> static char[] IChars() { return ReadLine().ToCharArray(); } ///< summary>n m とかをちょっとはやくかくだけ</summary> static string[] IStrings() { return ReadLine().Split(); } ///< summary>n行の入力を取ったり</summary> static long[][] ILongLongs(long n) { long[][] re = new long [n][]; for (long i = 0; i < n; i++) { string[] s = ReadLine().Split(); re[i] = new long[s.Length]; for (long j = 0; j < s.Length; j++) { re[i][j] = long.Parse(s[j]); } } return re; } ///< summary>n行の文字列を取ったり</summary> static char[][] ICharsChars(long n) { char[][] re = new char [n][]; for (long i = 0; i < n; i++) { re[i] = ReadLine().ToCharArray(); } return re; } } }
[["+", 0, 57, 64, 196, 0, 1, 0, 223, 0, 22], ["+", 0, 57, 64, 196, 0, 1, 0, 223, 0, 68], ["+", 64, 196, 0, 57, 64, 196, 0, 1, 0, 35], ["+", 0, 57, 64, 196, 0, 1, 0, 223, 0, 29]]
8
657
6
using System; using System.Collections.Generic; using System.Linq; namespace ABC116_D { class Program { static void Main(string[] args) { var NK = Console.ReadLine().Split().Select(long.Parse).ToArray(); var N = NK[0]; var K = NK[1]; var tds = new Model[N]; for (long i = 0; i < N; i++) { var inputtd = Console.ReadLine().Split().Select(long.Parse).ToArray(); tds[i] = new Model() { t = inputtd[0], d = inputtd[1] }; } tds = tds.OrderByDescending(x => x.d).ToArray(); long sum = 0; var type = new Dictionary<long, long>(); for (long i = 0; i < K; i++) { long tt = tds[i].t; if (type.ContainsKey(tt)) type[tt]++; else type.Add(tt, 1); sum += tds[i].d; } long res = (long)Math.Pow(type.Count(), 2) + sum; long last = K - 1; for (long i = K; i < N; i++) { var tt = tds[i].t; if (type.ContainsKey(tt)) continue; while (last > 0 && type[tds[last].t] <= 1) { last--; } if (last == 0) break; type[tds[last].t]--; type.Add(tt, 1); sum = sum - tds[last].d + tds[i].d; res = Math.Max(res, (long)Math.Pow(type.Count(), 2) + sum); } Console.WriteLine(res); } public class Model { public long d { get; set; } public long t { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; namespace ABC116_D { class Program { static void Main(string[] args) { var NK = Console.ReadLine().Split().Select(long.Parse).ToArray(); var N = NK[0]; var K = NK[1]; var tds = new Model[N]; for (long i = 0; i < N; i++) { var td = Console.ReadLine().Split().Select(long.Parse).ToArray(); tds[i] = new Model() { t = td[0], d = td[1] }; } tds = tds.OrderByDescending(x => x.d).ToArray(); long sum = 0; var type = new Dictionary<long, long>(); for (long i = 0; i < K; i++) { long tt = tds[i].t; if (type.ContainsKey(tt)) type[tt]++; else type.Add(tt, 1); sum += tds[i].d; } long res = (long)Math.Pow(type.Count(), 2) + sum; long last = K - 1; for (long i = K; i < N; i++) { var tt = tds[i].t; if (type.ContainsKey(tt)) continue; while (last > 0 && type[tds[last].t] <= 1) { last--; } if (last == 0) break; type[tds[last].t]--; type.Add(tt, 1); sum = sum - tds[last].d + tds[i].d; last--; res = Math.Max(res, (long)Math.Pow(type.Count(), 2) + sum); } Console.WriteLine(res); } public class Model { public long d { get; set; } public long t { get; set; } } } }
[["-", 8, 196, 0, 197, 0, 198, 0, 200, 141, 22], ["+", 8, 196, 0, 197, 0, 198, 0, 200, 141, 22], ["-", 12, 230, 10, 229, 0, 11, 12, 204, 205, 22], ["+", 12, 230, 10, 229, 0, 11, 12, 204, 205, 22], ["+", 8, 196, 0, 7, 8, 196, 0, 1, 0, 35], ["+", 0, 7, 8, 196, 0, 1, 0, 223, 0, 22], ["+", 0, 7, 8, 196, 0, 1, 0, 223, 0, 68]]
8
434
9
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] s = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); int[][] a = new int[s[0]][]; for (int i = 0; i < s[0]; i++) { a[i] = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); } Array.Sort(a, (u, v) => v[1] - u[1]); int[] h = new int[s[0] + 1]; long q = 0, t = 0, ans = 0; for (int i = 0, j = s[1] - 1; i < s[0]; i++) { if (i < s[1]) { if (h[a[i][0]] == 0) { t++; } h[a[i][0]]++; q += a[i][1]; } else if (h[a[i][0]] == 0) { while (j > 0 && h[a[j][0]] <= 1) { j--; } if (j == 0) { break; } h[a[j][0]]--; q -= a[j][1]; t++; h[a[i][0]]++; q += a[i][1]; } ans = Math.Max(ans, t * t + q); } Console.WriteLine("{0}", ans); } }
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] s = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); int[][] a = new int[s[0]][]; for (int i = 0; i < s[0]; i++) { a[i] = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); } Array.Sort(a, (u, v) => v[1] - u[1]); int[] h = new int[s[0] + 1]; long q = 0, t = 0, ans = 0; for (int i = 0, j = s[1] - 1; i < s[0]; i++) { if (i < s[1]) { if (h[a[i][0]] == 0) { t++; } h[a[i][0]]++; q += a[i][1]; } else if (h[a[i][0]] == 0) { while (j > 0 && h[a[j][0]] <= 1) { j--; } if (j == 0) { break; } h[a[j][0]]--; q -= a[j][1]; t++; j--; h[a[i][0]]++; q += a[i][1]; } ans = Math.Max(ans, t * t + q); } Console.WriteLine("{0}", ans); } }
[["+", 75, 57, 64, 196, 0, 1, 0, 223, 0, 22], ["+", 75, 57, 64, 196, 0, 1, 0, 223, 0, 68], ["+", 0, 57, 75, 57, 64, 196, 0, 1, 0, 35]]
8
369
3
using System; namespace AtCoder { class Program { static void Main(string[] args) { var inputs = Console.ReadLine().Split(' '); bool[] flags = new bool[4] { false, false, false, false }; foreach (var s in inputs) { switch (s) { case "1": if (!flags[0]) { flags[0] = true; } else { Console.WriteLine(No); return; } break; case "9": if (!flags[1]) { flags[1] = true; } else { Console.WriteLine(No); return; } break; case "7": if (!flags[2]) { flags[2] = true; } else { Console.WriteLine(No); return; } break; case "4": if (!flags[3]) { flags[3] = true; } else { Console.WriteLine(No); return; } break; default: Console.WriteLine(No); return; } } Console.WriteLine(Yes); return; } static string No = "NO"; static string Yes = "Yes"; } }
using System; namespace AtCoder { class Program { static void Main(string[] args) { var inputs = Console.ReadLine().Split(' '); bool[] flags = new bool[4] { false, false, false, false }; foreach (var s in inputs) { switch (s) { case "1": if (!flags[0]) { flags[0] = true; } else { Console.WriteLine(No); return; } break; case "9": if (!flags[1]) { flags[1] = true; } else { Console.WriteLine(No); return; } break; case "7": if (!flags[2]) { flags[2] = true; } else { Console.WriteLine(No); return; } break; case "4": if (!flags[3]) { flags[3] = true; } else { Console.WriteLine(No); return; } break; default: Console.WriteLine(No); return; } } Console.WriteLine(Yes); return; } static string No = "NO"; static string Yes = "YES"; } }
[["-", 0, 198, 0, 200, 0, 212, 0, 5, 0, 222], ["+", 0, 198, 0, 200, 0, 212, 0, 5, 0, 222]]
8
253
2
using System; public class Hello { public static void Main() { string[] a = Console.ReadLine().Trim().Split(' '); Array.Sort(a); if (a[0] == "1" && a[1] == "9" && a[2] == "7" && a[3] == "4") Console.WriteLine("YES"); else Console.WriteLine("NO"); } }
using System; public class Hello { public static void Main() { string[] a = Console.ReadLine().Trim().Split(' '); Array.Sort(a); if (a[0] == "1" && a[1] == "4" && a[2] == "7" && a[3] == "9") Console.WriteLine("YES"); else Console.WriteLine("NO"); } }
[["-", 31, 16, 31, 16, 12, 16, 12, 5, 0, 222], ["+", 31, 16, 31, 16, 12, 16, 12, 5, 0, 222], ["-", 0, 57, 15, 16, 12, 16, 12, 5, 0, 222], ["+", 0, 57, 15, 16, 12, 16, 12, 5, 0, 222]]
8
102
4
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; // KEYENCE Programming Contest 2019 // https://atcoder.jp/contests/keyence2019 namespace KeyenceContest2019_A { public class Solver : SolverBase { public void Run() { var ary = ReadIntArray(); bool foundA=false, foundB = false, foundC = false, foundD = false; foreach (var n in ary) { if (n == 1) foundA = true; if (n == 9) foundA = true; if (n == 7) foundA = true; if (n == 4) foundA = true; } if (foundA && foundB && foundC && foundD) WriteLine("YES"); else WriteLine("NO"); } #if !MYHOME public static void Main(string[] args) { new Solver().Run(); } #endif } public static class Util { public static string DumpToString<T>(IEnumerable<T> array) where T : IFormattable { var sb = new StringBuilder(); foreach (var item in array) { sb.Append(item); sb.Append(", "); } return sb.ToString(); } public static void InitArray<T>(T[] ary, T value) { for (int i = 0; i < ary.Length; i++) { ary[i] = value; } } public static void InitDP<T>(T[,] dp, T value) { for (int i = 0; i < dp.GetLength(0); i++) { for (int j = 0; j < dp.GetLength(1); j++) { dp[i, j] = value; } } } public static T Max<T>(params T[] nums) where T : IComparable { if (nums.Length == 0) return default(T); T max = nums[0]; for (int i = 1; i < nums.Length; i++) { max = max.CompareTo(nums[i]) > 0 ? max : nums[i]; } return max; } public static T Min<T>(params T[] nums) where T : IComparable { if (nums.Length == 0) return default(T); T min = nums[0]; for (int i = 1; i < nums.Length; i++) { min = min.CompareTo(nums[i]) < 0 ? min : nums[i]; } return min; } } public class SolverBase { virtual protected string ReadLine() => Console.ReadLine(); virtual protected int ReadInt() => int.Parse(ReadLine()); virtual protected long ReadLong() => long.Parse(ReadLine()); virtual protected string[] ReadStringArray() => ReadLine().Split(' '); virtual protected int[] ReadIntArray() => ReadLine().Split(' ').Select<string, int>(s => int.Parse(s)).ToArray(); virtual protected long[] ReadLongArray() => ReadLine().Split(' ').Select<string, long>(s => long.Parse(s)).ToArray(); virtual protected double[] ReadDoubleArray() => ReadLine().Split(' ').Select<string, double>(s => double.Parse(s)).ToArray(); virtual protected void WriteLine(string line) => Console.WriteLine(line); virtual protected void WriteLine(double d) => Console.WriteLine($"{d:F9}"); virtual protected void WriteLine<T>(T value) where T : IFormattable => Console.WriteLine(value); [Conditional("DEBUG")] protected void Dump(string s) => Console.WriteLine(s); [Conditional("DEBUG")] protected void Dump(char c) => Console.WriteLine(c); [Conditional("DEBUG")] protected void Dump(double d) => Console.WriteLine($"{d:F9}"); [Conditional("DEBUG")] protected void Dump<T>(IEnumerable<T> array) where T : IFormattable { string s = Util.DumpToString(array); // Consoleに出力すると、UnitTestの邪魔をしないというメリットあり。 Console.WriteLine(s); //_writer.WriteLine(s); } [Conditional("DEBUG")] protected void DumpGrid<T>(IEnumerable<IEnumerable<T>> arrayOfArray) where T : IFormattable { var sb = new StringBuilder(); foreach (var a in arrayOfArray) { sb.AppendLine(Util.DumpToString(a)); } // Consoleに出力すると、UnitTestの邪魔をしないというメリットあり。 Console.WriteLine(sb.ToString()); //_writer.WriteLine(sb.ToString()); } [Conditional("DEBUG")] protected void DumpDP<T>(T[,] dp) where T : IFormattable { var sb = new StringBuilder(); for (int i = 0; i < dp.GetLength(0); i++) { for (int j = 0; j < dp.GetLength(1); j++) { sb.Append(dp[i, j]); sb.Append(", "); } sb.AppendLine(); } Console.WriteLine(sb.ToString()); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; // KEYENCE Programming Contest 2019 // https://atcoder.jp/contests/keyence2019 namespace KeyenceContest2019_A { public class Solver : SolverBase { public void Run() { var ary = ReadIntArray(); bool foundA=false, foundB = false, foundC = false, foundD = false; foreach (var n in ary) { if (n == 1) foundA = true; if (n == 9) foundB = true; if (n == 7) foundC = true; if (n == 4) foundD = true; } if (foundA && foundB && foundC && foundD) WriteLine("YES"); else WriteLine("NO"); } #if !MYHOME public static void Main(string[] args) { new Solver().Run(); } #endif } public static class Util { public static string DumpToString<T>(IEnumerable<T> array) where T : IFormattable { var sb = new StringBuilder(); foreach (var item in array) { sb.Append(item); sb.Append(", "); } return sb.ToString(); } public static void InitArray<T>(T[] ary, T value) { for (int i = 0; i < ary.Length; i++) { ary[i] = value; } } public static void InitDP<T>(T[,] dp, T value) { for (int i = 0; i < dp.GetLength(0); i++) { for (int j = 0; j < dp.GetLength(1); j++) { dp[i, j] = value; } } } public static T Max<T>(params T[] nums) where T : IComparable { if (nums.Length == 0) return default(T); T max = nums[0]; for (int i = 1; i < nums.Length; i++) { max = max.CompareTo(nums[i]) > 0 ? max : nums[i]; } return max; } public static T Min<T>(params T[] nums) where T : IComparable { if (nums.Length == 0) return default(T); T min = nums[0]; for (int i = 1; i < nums.Length; i++) { min = min.CompareTo(nums[i]) < 0 ? min : nums[i]; } return min; } } public class SolverBase { virtual protected string ReadLine() => Console.ReadLine(); virtual protected int ReadInt() => int.Parse(ReadLine()); virtual protected long ReadLong() => long.Parse(ReadLine()); virtual protected string[] ReadStringArray() => ReadLine().Split(' '); virtual protected int[] ReadIntArray() => ReadLine().Split(' ').Select<string, int>(s => int.Parse(s)).ToArray(); virtual protected long[] ReadLongArray() => ReadLine().Split(' ').Select<string, long>(s => long.Parse(s)).ToArray(); virtual protected double[] ReadDoubleArray() => ReadLine().Split(' ').Select<string, double>(s => double.Parse(s)).ToArray(); virtual protected void WriteLine(string line) => Console.WriteLine(line); virtual protected void WriteLine(double d) => Console.WriteLine($"{d:F9}"); virtual protected void WriteLine<T>(T value) where T : IFormattable => Console.WriteLine(value); [Conditional("DEBUG")] protected void Dump(string s) => Console.WriteLine(s); [Conditional("DEBUG")] protected void Dump(char c) => Console.WriteLine(c); [Conditional("DEBUG")] protected void Dump(double d) => Console.WriteLine($"{d:F9}"); [Conditional("DEBUG")] protected void Dump<T>(IEnumerable<T> array) where T : IFormattable { string s = Util.DumpToString(array); // Consoleに出力すると、UnitTestの邪魔をしないというメリットあり。 Console.WriteLine(s); //_writer.WriteLine(s); } [Conditional("DEBUG")] protected void DumpGrid<T>(IEnumerable<IEnumerable<T>> arrayOfArray) where T : IFormattable { var sb = new StringBuilder(); foreach (var a in arrayOfArray) { sb.AppendLine(Util.DumpToString(a)); } // Consoleに出力すると、UnitTestの邪魔をしないというメリットあり。 Console.WriteLine(sb.ToString()); //_writer.WriteLine(sb.ToString()); } [Conditional("DEBUG")] protected void DumpDP<T>(T[,] dp) where T : IFormattable { var sb = new StringBuilder(); for (int i = 0; i < dp.GetLength(0); i++) { for (int j = 0; j < dp.GetLength(1); j++) { sb.Append(dp[i, j]); sb.Append(", "); } sb.AppendLine(); } Console.WriteLine(sb.ToString()); } } }
[["-", 8, 196, 0, 57, 64, 1, 0, 11, 31, 22], ["+", 8, 196, 0, 57, 64, 1, 0, 11, 31, 22]]
8
1,079
6
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AtCoderA { static void Main() { var sc = new Scanner(); string s = sc.Next(); for (int i = 0; i < s.Length; i++) { for (int j = 0; j < s.Length; i++) { string str = s.Substring(0, i) + s.Substring(j); if (str == "keyence") { Console.WriteLine("YES"); return; } } } Console.WriteLine("NO"); } class Scanner { private string[] _line; private int _index; private const char Separator = ' '; public Scanner() { _line = new string[0]; _index = 0; } public string Next() { while (_index >= _line.Length) { _line = Console.ReadLine().Split(Separator); _index = 0; } return _line[_index++]; } public int NextInt() => int.Parse(Next()); public long NextLong() => long.Parse(Next()); public double NextDouble() => double.Parse(Next()); public decimal NextDecimal() => decimal.Parse(Next()); public char NextChar() => Next()[0]; public char[] NextCharArray() => Next().ToCharArray(); public string[] Array() { _line = Console.ReadLine().Split(Separator); _index = _line.Length; return _line; } public int[] IntArray() => Array().Select(int.Parse).ToArray(); public long[] LongArray() => Array().Select(long.Parse).ToArray(); public double[] DoubleArray() => Array().Select(double.Parse).ToArray(); public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AtCoderA { static void Main() { var sc = new Scanner(); string s = sc.Next(); for (int i = 0; i < s.Length; i++) { for (int j = i; j < s.Length; j++) { string str = s.Substring(0, i) + s.Substring(j); if (str == "keyence") { Console.WriteLine("YES"); return; } } } Console.WriteLine("NO"); } class Scanner { private string[] _line; private int _index; private const char Separator = ' '; public Scanner() { _line = new string[0]; _index = 0; } public string Next() { while (_index >= _line.Length) { _line = Console.ReadLine().Split(Separator); _index = 0; } return _line[_index++]; } public int NextInt() => int.Parse(Next()); public long NextLong() => long.Parse(Next()); public double NextDouble() => double.Parse(Next()); public decimal NextDecimal() => decimal.Parse(Next()); public char NextChar() => Next()[0]; public char[] NextCharArray() => Next().ToCharArray(); public string[] Array() { _line = Console.ReadLine().Split(Separator); _index = _line.Length; return _line; } public int[] IntArray() => Array().Select(int.Parse).ToArray(); public long[] LongArray() => Array().Select(long.Parse).ToArray(); public double[] DoubleArray() => Array().Select(double.Parse).ToArray(); public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray(); } }
[["-", 0, 7, 10, 198, 0, 200, 0, 212, 0, 203], ["+", 0, 7, 10, 198, 0, 200, 0, 212, 0, 22], ["-", 0, 7, 8, 196, 0, 7, 26, 223, 0, 22], ["+", 0, 7, 8, 196, 0, 7, 26, 223, 0, 22]]
8
428
4
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using static System.Console; using static System.Math; namespace Atcoder { class Program { static StreamWriter sw = new StreamWriter(OpenStandardOutput()) { AutoFlush = false }; static void Main(string[] args) { try { SetOut(sw); Solve.Answer(); Out.Flush(); } catch (Exception ex) { WriteLine(ex.ToString()); Out.Flush(); } } } public class Solve { public static void Answer() { var s = ReadLine(); for (int i = 0; i < s.Length; i++) { for (int j = 0; j < s.Length; j++) { var newS = s.Substring(0, i) + s.Substring(i + j); if (newS == "keyence") { WriteLine("YES"); return; } } } WriteLine("NO"); } } public class IO { #region Input public static int RInt => int.Parse(ReadLine()); public static long RLong => long.Parse(ReadLine()); public static double RDouble => double.Parse(ReadLine()); public static string[] RSString => ReadLine().Split(); public static int[] RSInt => ReadLine().Split().Select(s => int.Parse(s)).ToArray(); public static long[] RSLong => ReadLine().Split().Select(s => long.Parse(s)).ToArray(); public static double[] RSDouble => ReadLine().Split().Select(s => double.Parse(s)).ToArray(); #endregion #region Output public static void OutJoinSpace<T>(IEnumerable<T> list) => WriteLine(string.Join(" ", list)); public static void WriteLineYes_or_No(bool flag) => WriteLine(flag ? "Yes" : "No"); public static void WriteLineYES_or_NO(bool flag) => WriteLine(flag ? "YES" : "NO"); #endregion } public class Mod { #region private readonly static long M = 1000000007; public static long Add(long a, long b) => (a * b) % M; public static long Sub(long a, long b) => (a - b) % M >= 0 ? (a - b) % M : (a - b) % M + M; public static long Multi(long a, long b) => (a * b) % M; #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using static System.Console; using static System.Math; namespace Atcoder { class Program { static StreamWriter sw = new StreamWriter(OpenStandardOutput()) { AutoFlush = false }; static void Main(string[] args) { try { SetOut(sw); Solve.Answer(); Out.Flush(); } catch (Exception ex) { WriteLine(ex.ToString()); Out.Flush(); } } } public class Solve { public static void Answer() { var s = ReadLine(); for (int i = 0; i < s.Length; i++) { for (int j = 0; i + j < s.Length; j++) { var newS = s.Substring(0, i) + s.Substring(i + j); if (newS == "keyence") { WriteLine("YES"); return; } } } WriteLine("NO"); } } public class IO { #region Input public static int RInt => int.Parse(ReadLine()); public static long RLong => long.Parse(ReadLine()); public static double RDouble => double.Parse(ReadLine()); public static string[] RSString => ReadLine().Split(); public static int[] RSInt => ReadLine().Split().Select(s => int.Parse(s)).ToArray(); public static long[] RSLong => ReadLine().Split().Select(s => long.Parse(s)).ToArray(); public static double[] RSDouble => ReadLine().Split().Select(s => double.Parse(s)).ToArray(); #endregion #region Output public static void OutJoinSpace<T>(IEnumerable<T> list) => WriteLine(string.Join(" ", list)); public static void WriteLineYes_or_No(bool flag) => WriteLine(flag ? "Yes" : "No"); public static void WriteLineYES_or_NO(bool flag) => WriteLine(flag ? "YES" : "NO"); #endregion } public class Mod { #region private readonly static long M = 1000000007; public static long Add(long a, long b) => (a * b) % M; public static long Sub(long a, long b) => (a - b) % M >= 0 ? (a - b) % M : (a - b) % M + M; public static long Multi(long a, long b) => (a * b) % M; #endregion } }
[["+", 8, 196, 0, 7, 15, 16, 31, 16, 31, 22], ["+", 8, 196, 0, 7, 15, 16, 31, 16, 17, 72]]
8
560
2
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Runtime.CompilerServices; using static System.Math; class P { static void Main() { int n = int.Parse(Console.ReadLine()); //全てに合格 int[] a = Console.ReadLine().Split().Select(int.Parse).ToArray(); int[] b = Console.ReadLine().Split().Select(int.Parse).ToArray(); int[] diff = a.Zip(b, (x, y) => x - y).ToArray(); int[] amari = diff.Where(x => x > 0).OrderByDescending(x => x).ToArray(); int[] dame = diff.Where(x => x < 0).ToArray(); Queue<long> q = new Queue<long>(); foreach (var item in amari) q.Enqueue((long)item); long currentCount = 0; long currentUsed = 0; foreach (var item in dame) { if (currentUsed + item < 0) { if (q.Count == 0) { Console.WriteLine(-1); return; } currentUsed += q.Dequeue(); currentCount++; } currentUsed += item; currentCount++; } Console.WriteLine(currentCount); } } static class Writer { public static void WriteLine<T>(this T item) => Console.WriteLine(item); public static void WriteLog<T>(this T item) => Debug.WriteLine(item); }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Runtime.CompilerServices; using static System.Math; class P { static void Main() { int n = int.Parse(Console.ReadLine()); //全てに合格 int[] a = Console.ReadLine().Split().Select(int.Parse).ToArray(); int[] b = Console.ReadLine().Split().Select(int.Parse).ToArray(); int[] diff = a.Zip(b, (x, y) => x - y).ToArray(); int[] amari = diff.Where(x => x > 0).OrderByDescending(x => x).ToArray(); int[] dame = diff.Where(x => x < 0).ToArray(); Queue<long> q = new Queue<long>(); foreach (var item in amari) q.Enqueue((long)item); long currentCount = 0; long currentUsed = 0; foreach (var item in dame) { while (currentUsed + item < 0) { if (q.Count == 0) { Console.WriteLine(-1); return; } currentUsed += q.Dequeue(); currentCount++; } currentUsed += item; currentCount++; } Console.WriteLine(currentCount); } } static class Writer { public static void WriteLine<T>(this T item) => Console.WriteLine(item); public static void WriteLog<T>(this T item) => Debug.WriteLine(item); }
[["-", 8, 196, 0, 210, 8, 196, 0, 57, 0, 121], ["+", 8, 196, 0, 210, 8, 196, 0, 52, 0, 89]]
8
363
2
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { int N = int.Parse(Console.ReadLine()); long[] A = new long[N]; long[] B = new long[N]; string[] str = Console.ReadLine().Split(); string[] str2 = Console.ReadLine().Split(); long Asum = 0; long Bsum = 0; long C = 0; int ct = 0; int[][] D = new int [N][]; for (var i = 0; i < N; i++) { A[i] = long.Parse(str[i]); Asum += A[i]; B[i] = long.Parse(str2[i]); Bsum += B[i]; if (B[i] > A[i]) { C += B[i] - A[i]; ct++; } D[i] = new int[2] { (int)(A[i] - B[i]), i }; } if (Asum >= Bsum) { Array.Sort(D, (x, y) => y[0] - x[0]); int cct = 0; while (C > 0) { C -= D[cct][0]; ct++; if (C <= 0) { break; } } Console.WriteLine(ct); } else { Console.WriteLine("-1"); } } }
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { int N = int.Parse(Console.ReadLine()); long[] A = new long[N]; long[] B = new long[N]; string[] str = Console.ReadLine().Split(); string[] str2 = Console.ReadLine().Split(); long Asum = 0; long Bsum = 0; long C = 0; int ct = 0; int[][] D = new int [N][]; for (var i = 0; i < N; i++) { A[i] = long.Parse(str[i]); Asum += A[i]; B[i] = long.Parse(str2[i]); Bsum += B[i]; if (B[i] > A[i]) { C += B[i] - A[i]; ct++; } D[i] = new int[2] { (int)(A[i] - B[i]), i }; } if (Asum >= Bsum) { Array.Sort(D, (x, y) => y[0] - x[0]); int cct = 0; while (C > 0) { C -= D[cct][0]; ct++; if (C <= 0) { break; } cct++; } Console.WriteLine(ct); } else { Console.WriteLine("-1"); } } }
[["+", 0, 52, 8, 196, 0, 1, 0, 223, 0, 22], ["+", 0, 52, 8, 196, 0, 1, 0, 223, 0, 29], ["+", 64, 196, 0, 52, 8, 196, 0, 1, 0, 35]]
8
330
3
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using static System.Console; using static System.Math; namespace AtCodeeeer { class AtCOOOOOOOOOOOder { static void Main(string[] args) { int n = int.Parse(ReadLine()); int[] ab = ReadLine().Split(' ').Select(int.Parse).ToArray(); int lowA = 0; int AandB = 0; int highB = 0; int[] s = ReadLine().Split(' ').Select(int.Parse).ToArray(); for (int i = 0; i < n; i++) { if (s[i] <= ab[0]) { lowA++; } else if (s[i] >= ab[1]) { highB++; } else AandB++; } WriteLine(Min(lowA, Min(AandB, highB))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using static System.Console; using static System.Math; namespace AtCodeeeer { class AtCOOOOOOOOOOOder { static void Main(string[] args) { int n = int.Parse(ReadLine()); int[] ab = ReadLine().Split(' ').Select(int.Parse).ToArray(); int lowA = 0; int AandB = 0; int highB = 0; int[] s = ReadLine().Split(' ').Select(int.Parse).ToArray(); for (int i = 0; i < n; i++) { if (s[i] <= ab[0]) { lowA++; } else if (s[i] > ab[1]) { highB++; } else AandB++; } WriteLine(Min(lowA, Min(AandB, highB))); } } }
[["-", 8, 196, 0, 57, 75, 57, 15, 16, 17, 20], ["+", 8, 196, 0, 57, 75, 57, 15, 16, 17, 47]]
8
207
2
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int N = int.Parse(Console.ReadLine()); string[] points = Console.ReadLine().Split(' '); int A = int.Parse(points[0]); int B = int.Parse(points[1]); List<int> score = Console.ReadLine() .Split(' ') .Select(x => int.Parse(x)) .OrderBy(x => x) .ToList(); var countA = score.Where(x => x >= A).Count(); var countB = score.Where(x => x < A && x <= B).Count(); var countC = score.Where(x => x >= B).Count(); int[] a = new int[] { countA, countB, countC }; int count = a.Min(); Console.WriteLine(count); } }
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int N = int.Parse(Console.ReadLine()); string[] points = Console.ReadLine().Split(' '); int A = int.Parse(points[0]); int B = int.Parse(points[1]); List<int> score = Console.ReadLine() .Split(' ') .Select(x => int.Parse(x)) .OrderBy(x => x) .ToList(); var countA = score.Where(x => x <= A).Count(); var countB = score.Where(x => x > A && x <= B).Count(); var countC = score.Where(x => x > B).Count(); int[] a = new int[] { countA, countB, countC }; int count = a.Min(); Console.WriteLine(count); } }
[["-", 3, 4, 0, 28, 0, 218, 8, 16, 17, 20], ["+", 3, 4, 0, 28, 0, 218, 8, 16, 17, 19], ["-", 0, 28, 0, 218, 8, 16, 31, 16, 17, 18], ["+", 0, 28, 0, 218, 8, 16, 31, 16, 17, 47], ["+", 3, 4, 0, 28, 0, 218, 8, 16, 17, 47]]
8
217
6
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var ab = Console.ReadLine().Split(' '); var a = int.Parse(ab[0]); var b = int.Parse(ab[1]); var pn = Console.ReadLine().Split(' '); var p = new List<int>(); foreach (var v in pn) { var v2 = int.Parse(v); p.Add(v2); } var count = p.Where(x => x <= a).Count(); var t = p.Where(x => x > a && x < b).Count(); if (count > t) count = t; t = p.Where(x => x > b).Count(); if (count > t) count = t; Console.WriteLine(count); } }
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var ab = Console.ReadLine().Split(' '); var a = int.Parse(ab[0]); var b = int.Parse(ab[1]); var pn = Console.ReadLine().Split(' '); var p = new List<int>(); foreach (var v in pn) { var v2 = int.Parse(v); p.Add(v2); } var count = p.Where(x => x <= a).Count(); var t = p.Where(x => x > a && x <= b).Count(); if (count > t) count = t; t = p.Where(x => x > b).Count(); if (count > t) count = t; Console.WriteLine(count); } }
[["-", 0, 28, 0, 218, 8, 16, 12, 16, 17, 18], ["+", 0, 28, 0, 218, 8, 16, 12, 16, 17, 19]]
8
223
2
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace B { public class Program { public static void Main(string[] args) { int n = RInt(); int[] borders = RIntAr(); int[] questions = RIntAr(); int a = questions.Count(x => x <= borders[0]); int b = questions.Count(x => x > borders[0] && x <= borders[1]); int c = questions.Count(x => x >= borders[1]); Console.WriteLine(Math.Min(a, Math.Min(b, c))); } static string RSt() { return Console.ReadLine(); } static int RInt() { return int.Parse(Console.ReadLine().Trim()); } static long RLong() { return long.Parse(Console.ReadLine().Trim()); } static double RDouble() { return double.Parse(Console.ReadLine()); } static string[] RStAr(char sep = ' ') { return Console.ReadLine().Trim().Split(sep); } static int[] RIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => int.Parse(e)); } static long[] RLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => long.Parse(e)); } static double[] RDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => double.Parse(e)); } static string WAr<T>(IEnumerable<T> array, string sep = " ") { return string.Join(sep, array.Select(x => x.ToString()).ToArray()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace B { public class Program { public static void Main(string[] args) { int n = RInt(); int[] borders = RIntAr(); int[] questions = RIntAr(); int a = questions.Count(x => x <= borders[0]); int b = questions.Count(x => borders[0] < x && x <= borders[1]); int c = questions.Count(x => x > borders[1]); Console.WriteLine(Math.Min(a, Math.Min(b, c))); } static string RSt() { return Console.ReadLine(); } static int RInt() { return int.Parse(Console.ReadLine().Trim()); } static long RLong() { return long.Parse(Console.ReadLine().Trim()); } static double RDouble() { return double.Parse(Console.ReadLine()); } static string[] RStAr(char sep = ' ') { return Console.ReadLine().Trim().Split(sep); } static int[] RIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => int.Parse(e)); } static long[] RLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => long.Parse(e)); } static double[] RDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => double.Parse(e)); } static string WAr<T>(IEnumerable<T> array, string sep = " ") { return string.Join(sep, array.Select(x => x.ToString()).ToArray()); } } }
[["-", 0, 28, 0, 218, 8, 16, 31, 16, 31, 22], ["-", 0, 28, 0, 218, 8, 16, 31, 16, 17, 47], ["+", 0, 28, 0, 218, 8, 16, 31, 16, 17, 18], ["+", 0, 28, 0, 218, 8, 16, 31, 16, 12, 22], ["-", 3, 4, 0, 28, 0, 218, 8, 16, 17, 20], ["+", 3, 4, 0, 28, 0, 218, 8, 16, 17, 47]]
8
437
6
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; static class Ex { public static int LowerBound<T>(this IList<T> a, T v) where T : IComparable<T> { if (a[0].CompareTo(v) >= 0) return 0; int l = 0, r = a.Count; while (r - l > 1) { int c = (r + l) / 2; if (a[c].CompareTo(v) < 0) l = c; else r = c; } return r; } } class TEST { static void Main() { Sol mySol = new Sol(); mySol.Solve(); } } class Sol { public void Solve() { long[][] S = new long [2][]; for (int i = 0; i < 2; i++) S[i] = new long[N + 1]; for (int i = 0; i < N; i++) { for (int j = 0; j < 2; j++) { S[j][i + 1] += S[j][i] + (i % 2 == j ? A[i] : 0); } } long[] ans = new long[Q]; for (int i = 0; i < Q; i++) { var x = X[i]; int idx = A.LowerBound(x); // Console.Error.WriteLine("idx:{0}",idx); if (idx == N) idx--; // Console.Error.WriteLine("tf:{0}",idx > 0 && Math.Abs(x - A[idx - 1]) <= // Math.Abs(x - A[idx])); if (idx > 0 && Math.Abs(x - A[idx - 1]) <= Math.Abs(x - A[idx])) idx--; // Console.Error.WriteLine("idx:{0}",idx); int l = 1, r = N; while (r - l > 1) { // 高橋君が右側c個取れる // atatataaAatttT c == 4 int c = (r + l) / 2; if (possible(c, idx, x, X)) { l = c; } else { r = c; } } // cerr << "i:" << i << " l:" << l << endl; long taka = (S[0][N] - S[0][N - l]) + (S[1][N] - S[1][N - l]); int rest = N - l - (l - 1); if (rest % 2 == 1) { taka += S[1][rest]; } else { taka += S[0][rest]; } // ll aoki = (S[0][N] + S[1][N]) - taka; ans[i] = taka; } Console.WriteLine(String.Join("\n", ans)); } bool possible(int c, int idx, long x, long[] a) { // 高橋君が右側c個取れる.青木君はidxから始まる // atatataaAatttT c == 4 int N = a.Length; if (c == 1) return true; if (N - c <= idx) return false; if (2 * c - 2 >= N) return false; // 高橋君が右側c-1個取り終わっていて, // 青木君がc-1個目としてA[N-c]を必ず取らなければいけない場合はfalse, // それ以外はtrue // 右にまだ余裕がある if (idx + (c - 2) < N - c) return true; // 右はN-c-1まで取っているとして,N-cを取るより左側をとる方が理にかなっている int nl = N - c - 1 - (c - 2); if (nl < 0) return false; if (Math.Abs(a[nl] - x) <= Math.Abs(a[N - c] - x)) return true; return false; } int N, Q; long[] A, X; public Sol() { var d = ria(); N = d[0]; Q = d[1]; A = rla(); X = new long[Q]; for (int i = 0; i < Q; i++) X[i] = rl(); } static String rs() { return Console.ReadLine(); } static int ri() { return int.Parse(Console.ReadLine()); } static long rl() { return long.Parse(Console.ReadLine()); } static double rd() { return double.Parse(Console.ReadLine()); } static String[] rsa(char sep = ' ') { return Console.ReadLine().Split(sep); } static int[] ria(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); } static long[] rla(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); } static double[] rda(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; static class Ex { public static int LowerBound<T>(this IList<T> a, T v) where T : IComparable<T> { if (a[0].CompareTo(v) >= 0) return 0; int l = 0, r = a.Count; while (r - l > 1) { int c = (r + l) / 2; if (a[c].CompareTo(v) < 0) l = c; else r = c; } return r; } } class TEST { static void Main() { Sol mySol = new Sol(); mySol.Solve(); } } class Sol { public void Solve() { long[][] S = new long [2][]; for (int i = 0; i < 2; i++) S[i] = new long[N + 1]; for (int i = 0; i < N; i++) { for (int j = 0; j < 2; j++) { S[j][i + 1] = S[j][i] + (i % 2 == j ? A[i] : 0); } } long[] ans = new long[Q]; for (int i = 0; i < Q; i++) { var x = X[i]; int idx = A.LowerBound(x); if (idx == N) idx--; if (idx > 0 && Math.Abs(x - A[idx - 1]) <= Math.Abs(x - A[idx])) idx--; int l = 1, r = N; while (r - l > 1) { // 高橋君が右側c個取れる // atatataaAatttT c == 4 int c = (r + l) / 2; if (possible(c, idx, x, A)) { l = c; } else { r = c; } } // cerr << "i:" << i << " l:" << l << endl; long taka = (S[0][N] - S[0][N - l]) + (S[1][N] - S[1][N - l]); int rest = N - l - (l - 1); if (rest % 2 == 1) { taka += S[1][rest]; } else { taka += S[0][rest]; } // ll aoki = (S[0][N] + S[1][N]) - taka; ans[i] = taka; } Console.WriteLine(String.Join("\n", ans)); } bool possible(int c, int idx, long x, long[] a) { // 高橋君が右側c個取れる.青木君はidxから始まる // atatataaAatttT c == 4 int N = a.Length; if (c == 1) return true; if (N - c <= idx) return false; if (2 * c - 2 >= N) return false; // 高橋君が右側c-1個取り終わっていて, // 青木君がc-1個目としてA[N-c]を必ず取らなければいけない場合はfalse, // それ以外はtrue // 右にまだ余裕がある if (idx + (c - 2) < N - c) return true; // 右はN-c-1まで取っているとして,N-cを取るより左側をとる方が理にかなっている int nl = N - c - 1 - (c - 2); if (nl < 0) return false; if (Math.Abs(a[nl] - x) <= Math.Abs(a[N - c] - x)) return true; return false; } int N, Q; long[] A, X; public Sol() { var d = ria(); N = d[0]; Q = d[1]; A = rla(); X = new long[Q]; for (int i = 0; i < Q; i++) X[i] = rl(); } static String rs() { return Console.ReadLine(); } static int ri() { return int.Parse(Console.ReadLine()); } static long rl() { return long.Parse(Console.ReadLine()); } static double rd() { return double.Parse(Console.ReadLine()); } static String[] rsa(char sep = ' ') { return Console.ReadLine().Split(sep); } static int[] ria(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); } static long[] rla(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); } static double[] rda(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); } }
[["-", 8, 196, 0, 1, 0, 11, 0, 202, 0, 107], ["+", 8, 196, 0, 1, 0, 11, 0, 202, 0, 32], ["-", 0, 57, 15, 213, 3, 4, 0, 28, 0, 22], ["+", 0, 57, 15, 213, 3, 4, 0, 28, 0, 22]]
8
978
4
using System; using System.Linq; using System.Numerics; class Program { static void Main() { var INF = (int)1e5; var N = int.Parse(Console.ReadLine()); var steps = Console.ReadLine().Split().Select(int.Parse).ToArray(); var dp = Enumerable.Repeat((int)INF, N + 1).ToArray(); dp[0] = 0; dp[1] = Math.Abs(steps[0] - steps[1]); for (int i = 2; i < N; i++) { dp[i] = Math.Min(dp[i - 1] + Math.Abs(steps[i] - steps[i - 1]), dp[i - 2] + Math.Abs(steps[i] - steps[i - 2])); } Console.WriteLine(N - 1); } }
using System; using System.Linq; using System.Numerics; class Program { static void Main() { var INF = (int)1e5; var N = int.Parse(Console.ReadLine()); var steps = Console.ReadLine().Split().Select(int.Parse).ToArray(); var dp = Enumerable.Repeat((int)INF, N + 1).ToArray(); dp[0] = 0; dp[1] = Math.Abs(steps[0] - steps[1]); for (int i = 2; i < N; i++) { dp[i] = Math.Min(dp[i - 1] + Math.Abs(steps[i] - steps[i - 1]), dp[i - 2] + Math.Abs(steps[i] - steps[i - 2])); } Console.WriteLine(dp[N - 1]); } }
[["+", 0, 213, 3, 4, 0, 28, 0, 204, 205, 22], ["+", 3, 4, 0, 28, 0, 204, 206, 207, 0, 70], ["+", 3, 4, 0, 28, 0, 204, 206, 207, 0, 73]]
8
201
3
using System; class c { static void Main() { int n = int.Parse(Console.ReadLine()); var h = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); var ans = new int[n]; ans[1] = Math.Abs(h[0] - h[1]); for (int i = 2; i < n; i++) { ans[i] = Math.Min(Math.Abs(h[i - 2] - h[i]) + ans[i - 2], Math.Abs(h[i - 1] - h[i] + ans[i - 1])); } Console.WriteLine(ans[n - 1]); } }
using System; class c { static void Main() { int n = int.Parse(Console.ReadLine()); var h = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); var ans = new int[n]; ans[1] = Math.Abs(h[0] - h[1]); for (int i = 2; i < n; i++) { ans[i] = Math.Min(Math.Abs(h[i - 2] - h[i]) + ans[i - 2], Math.Abs(h[i - 1] - h[i]) + ans[i - 1]); } Console.WriteLine(ans[n - 1]); } }
[["+", 0, 28, 0, 16, 31, 213, 3, 4, 0, 25], ["-", 3, 4, 0, 28, 0, 213, 3, 4, 0, 25]]
8
165
2
using System; using System.Linq; namespace AltCoder { public sealed class A_Frog1 { public static void Main() { long N = Convert.ToInt32(Console.ReadLine()); long[] heights = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => Convert.ToInt64(x)) .ToArray(); long[] d = new long[N]; d[0] = 0; d[1] = Math.Abs(heights[2] - heights[1]); for (long i = 2; i < N; i++) { d[i] = Math.Min(d[i - 1] + Math.Abs(heights[i] - heights[i - 1]), d[i - 2] + Math.Abs(heights[i] - heights[i - 2])); } Console.WriteLine(d[N - 1]); } } }
using System; using System.Linq; namespace AltCoder { public sealed class A_Frog1 { public static void Main() { long N = Convert.ToInt32(Console.ReadLine()); long[] heights = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => Convert.ToInt64(x)) .ToArray(); long[] d = new long[N]; d[0] = 0; d[1] = Math.Abs(heights[1] - heights[0]); for (long i = 2; i < N; i++) { d[i] = Math.Min(d[i - 1] + Math.Abs(heights[i] - heights[i - 1]), d[i - 2] + Math.Abs(heights[i] - heights[i - 2])); } Console.WriteLine(d[N - 1]); } } }
[["-", 0, 16, 31, 204, 206, 207, 0, 28, 0, 203], ["+", 0, 16, 31, 204, 206, 207, 0, 28, 0, 203], ["-", 0, 16, 12, 204, 206, 207, 0, 28, 0, 203], ["+", 0, 16, 12, 204, 206, 207, 0, 28, 0, 203]]
8
208
4
using System; using System.Text; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; namespace AtCoder { public class Program { public static void Main(string[] args) { new Program().Solve(new ConsoleInput(Console.In, ' ')); } public void Solve(ConsoleInput cin) { long N = cin.ReadLong; var h = cin.ReadLongArray(N); var costArray = new long[N]; for (var i = 0; i < N; i++) { costArray[i] = 100000; } costArray[0] = 0; ChMin(ref costArray[1], Math.Abs(h[1] - h[0])); for (var i = 2; i < N; i++) { ChMin(ref costArray[i], costArray[i - 1] + Math.Abs(h[i] - h[i - 1])); ChMin(ref costArray[i], costArray[i - 2] + Math.Abs(h[i] - h[i - 2])); } WriteLine(costArray[N - 1]); } static long GcdArray(long[] array) { var ans = array[0]; for (var i = 1; i < array.Length; i++) { ans = Gcd(ans, array[i]); } return ans; } static long Gcd(long a, long b) { var v = new[] { a, b }; while (v[1] != 0) { v = new[] { v[1], v[0] % v[1] }; } return v[0]; } static long Lcm(long a, long b) { return a / Gcd(a, b) * b; } static bool ChMin<Type>(ref Type a, Type b) where Type : IComparable { if (a.CompareTo(b) > 0) { a = b; return true; } return false; } static bool ChMax<Type>(ref Type a, Type b) where Type : IComparable { if (a.CompareTo(b) < 0) { a = b; return true; } return false; } } public class ConsoleInput { private readonly System.IO.TextReader _stream; private char _separator = ' '; private Queue<string> inputStream; public ConsoleInput(System.IO.TextReader stream, char separator = ' ') { this._separator = separator; this._stream = stream; inputStream = new Queue<string>(); } public string Read { get { if (inputStream.Count != 0) return inputStream.Dequeue(); string[] tmp = _stream.ReadLine().Split(_separator); for (int i = 0; i < tmp.Length; ++i) inputStream.Enqueue(tmp[i]); return inputStream.Dequeue(); } } public string ReadLine { get { return _stream.ReadLine(); } } public int ReadInt { get { return int.Parse(Read); } } public long ReadLong { get { return long.Parse(Read); } } public double ReadDouble { get { return double.Parse(Read); } } public string[] ReadStrArray(long N) { var ret = new string[N]; for (long i = 0; i < N; ++i) ret[i] = Read; return ret; } public int[] ReadIntArray(long N) { var ret = new int[N]; for (long i = 0; i < N; ++i) ret[i] = ReadInt; return ret; } public long[] ReadLongArray(long N) { var ret = new long[N]; for (long i = 0; i < N; ++i) ret[i] = ReadLong; return ret; } } // From // http://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx public class PriorityQueue<T> where T : IComparable<T> { private List<T> data; public PriorityQueue() { this.data = new List<T>(); } public void Enqueue(T item) { data.Add(item); int ci = data.Count - 1; // child index; start at end while (ci > 0) { int pi = (ci - 1) / 2; // parent index if (data[ci].CompareTo(data[pi]) >= 0) break; // child item is larger than (or equal) parent so we're done T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp; ci = pi; } } public T Dequeue() { // assumes pq is not empty; up to calling code int li = data.Count - 1; // last index (before removal) T frontItem = data[0]; // fetch the front data[0] = data[li]; data.RemoveAt(li); --li; // last index (after removal) int pi = 0; // parent index. start at front of pq while (true) { int ci = pi * 2 + 1; // left child index of parent if (ci > li) break; // no children so done int rc = ci + 1; // right child if (rc <= li && data[rc].CompareTo(data[ci]) < 0) // if there is a rc (ci + 1), and it is smaller // than left child, use the rc instead ci = rc; if (data[pi].CompareTo(data[ci]) <= 0) break; // parent is smaller than (or equal to) smallest child so done T tmp = data[pi]; data[pi] = data[ci]; data[ci] = tmp; // swap parent and child pi = ci; } return frontItem; } public T Peek() { T frontItem = data[0]; return frontItem; } public int Count() { return data.Count; } public override string ToString() { string s = ""; for (int i = 0; i < data.Count; ++i) s += data[i].ToString() + " "; s += "count = " + data.Count; return s; } public bool IsConsistent() { // is the heap property true for all data? if (data.Count == 0) return true; int li = data.Count - 1; // last index for (int pi = 0; pi < data.Count; ++pi) { // each parent index int lci = 2 * pi + 1; // left child index int rci = 2 * pi + 2; // right child index if (lci <= li && data[pi].CompareTo(data[lci]) > 0) return false; // if lc exists and it's greater than parent then bad. if (rci <= li && data[pi].CompareTo(data[rci]) > 0) return false; // check the right child too. } return true; // passed all checks } // IsConsistent } }
using System; using System.Text; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; namespace AtCoder { public class Program { public static void Main(string[] args) { new Program().Solve(new ConsoleInput(Console.In, ' ')); } public void Solve(ConsoleInput cin) { long N = cin.ReadLong; var h = cin.ReadLongArray(N); var costArray = new long[N]; for (var i = 0; i < N; i++) { costArray[i] = 1000000000; } costArray[0] = 0; ChMin(ref costArray[1], costArray[0] + Math.Abs(h[1] - h[0])); for (var i = 2; i < N; i++) { ChMin(ref costArray[i], costArray[i - 1] + Math.Abs(h[i] - h[i - 1])); ChMin(ref costArray[i], costArray[i - 2] + Math.Abs(h[i] - h[i - 2])); } WriteLine(costArray[N - 1]); } static long GcdArray(long[] array) { var ans = array[0]; for (var i = 1; i < array.Length; i++) { ans = Gcd(ans, array[i]); } return ans; } static long Gcd(long a, long b) { var v = new[] { a, b }; while (v[1] != 0) { v = new[] { v[1], v[0] % v[1] }; } return v[0]; } static long Lcm(long a, long b) { return a / Gcd(a, b) * b; } static bool ChMin<Type>(ref Type a, Type b) where Type : IComparable { if (a.CompareTo(b) > 0) { a = b; return true; } return false; } static bool ChMax<Type>(ref Type a, Type b) where Type : IComparable { if (a.CompareTo(b) < 0) { a = b; return true; } return false; } } public class ConsoleInput { private readonly System.IO.TextReader _stream; private char _separator = ' '; private Queue<string> inputStream; public ConsoleInput(System.IO.TextReader stream, char separator = ' ') { this._separator = separator; this._stream = stream; inputStream = new Queue<string>(); } public string Read { get { if (inputStream.Count != 0) return inputStream.Dequeue(); string[] tmp = _stream.ReadLine().Split(_separator); for (int i = 0; i < tmp.Length; ++i) inputStream.Enqueue(tmp[i]); return inputStream.Dequeue(); } } public string ReadLine { get { return _stream.ReadLine(); } } public int ReadInt { get { return int.Parse(Read); } } public long ReadLong { get { return long.Parse(Read); } } public double ReadDouble { get { return double.Parse(Read); } } public string[] ReadStrArray(long N) { var ret = new string[N]; for (long i = 0; i < N; ++i) ret[i] = Read; return ret; } public int[] ReadIntArray(long N) { var ret = new int[N]; for (long i = 0; i < N; ++i) ret[i] = ReadInt; return ret; } public long[] ReadLongArray(long N) { var ret = new long[N]; for (long i = 0; i < N; ++i) ret[i] = ReadLong; return ret; } } // From // http://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx public class PriorityQueue<T> where T : IComparable<T> { private List<T> data; public PriorityQueue() { this.data = new List<T>(); } public void Enqueue(T item) { data.Add(item); int ci = data.Count - 1; // child index; start at end while (ci > 0) { int pi = (ci - 1) / 2; // parent index if (data[ci].CompareTo(data[pi]) >= 0) break; // child item is larger than (or equal) parent so we're done T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp; ci = pi; } } public T Dequeue() { // assumes pq is not empty; up to calling code int li = data.Count - 1; // last index (before removal) T frontItem = data[0]; // fetch the front data[0] = data[li]; data.RemoveAt(li); --li; // last index (after removal) int pi = 0; // parent index. start at front of pq while (true) { int ci = pi * 2 + 1; // left child index of parent if (ci > li) break; // no children so done int rc = ci + 1; // right child if (rc <= li && data[rc].CompareTo(data[ci]) < 0) // if there is a rc (ci + 1), and it is smaller // than left child, use the rc instead ci = rc; if (data[pi].CompareTo(data[ci]) <= 0) break; // parent is smaller than (or equal to) smallest child so done T tmp = data[pi]; data[pi] = data[ci]; data[ci] = tmp; // swap parent and child pi = ci; } return frontItem; } public T Peek() { T frontItem = data[0]; return frontItem; } public int Count() { return data.Count; } public override string ToString() { string s = ""; for (int i = 0; i < data.Count; ++i) s += data[i].ToString() + " "; s += "count = " + data.Count; return s; } public bool IsConsistent() { // is the heap property true for all data? if (data.Count == 0) return true; int li = data.Count - 1; // last index for (int pi = 0; pi < data.Count; ++pi) { // each parent index int lci = 2 * pi + 1; // left child index int rci = 2 * pi + 2; // right child index if (lci <= li && data[pi].CompareTo(data[lci]) > 0) return false; // if lc exists and it's greater than parent then bad. if (rci <= li && data[pi].CompareTo(data[rci]) > 0) return false; // check the right child too. } return true; // passed all checks } // IsConsistent } }
[["-", 0, 7, 8, 196, 0, 1, 0, 11, 12, 203], ["+", 0, 7, 8, 196, 0, 1, 0, 11, 12, 203], ["+", 3, 4, 0, 28, 0, 16, 31, 204, 205, 22], ["+", 0, 28, 0, 16, 31, 204, 206, 207, 0, 70], ["+", 0, 16, 31, 204, 206, 207, 0, 28, 0, 203], ["+", 0, 28, 0, 16, 31, 204, 206, 207, 0, 73], ["+", 0, 213, 3, 4, 0, 28, 0, 16, 17, 72]]
8
1,336
7
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MainClass { public const long Giri = 1000000007; public static void Main(string[] args) { int n = Console.ReadLine().ToInt(); int[] bh = Input().ToInt(); int[] h = new int[n + 2]; Array.Copy(bh, 0, h, 0, n); int[] c = new int[n + 2]; for (int i = 1; i < n; i++) c[i] = 999999; for (int i = 0; i < n; i++) { c[i + 1] = Math.Min(c[i + 1], Math.Abs(h[i] - h[i + 1]) + c[i]); c[i + 2] = Math.Min(c[i + 2], Math.Abs(h[i] - h[i + 2]) + c[i]); } Console.WriteLine(c[n - 1]); } public static long GCD(long a, long b) { if (b == 1) return a; long p = b / a; return GCD(a, b - a * p); } public static string[] Input() { return Console.ReadLine().Split(' '); } public static int Clamp(int val, int max, int min = 0) { return Math.Min(max, Math.Max(min, val)); } } public static class Smarter { public static int ToInt(this string str) { return int.Parse(str); } public static long ToLong(this string str) { return long.Parse(str); } public static int[] ToInt(this string[] str) { int[] r = new int[str.Length]; for (int i = 0; i < str.Length; i++) r[i] = str[i].ToInt(); return r; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MainClass { public const long Giri = 1000000007; public static void Main(string[] args) { int n = Console.ReadLine().ToInt(); int[] bh = Input().ToInt(); int[] h = new int[n + 2]; Array.Copy(bh, 0, h, 0, n); int[] c = new int[n + 2]; for (int i = 1; i < n; i++) c[i] = 999999999; for (int i = 0; i < n; i++) { c[i + 1] = Math.Min(c[i + 1], Math.Abs(h[i] - h[i + 1]) + c[i]); c[i + 2] = Math.Min(c[i + 2], Math.Abs(h[i] - h[i + 2]) + c[i]); } Console.WriteLine(c[n - 1]); } public static long GCD(long a, long b) { if (b == 1) return a; long p = b / a; return GCD(a, b - a * p); } public static string[] Input() { return Console.ReadLine().Split(' '); } public static int Clamp(int val, int max, int min = 0) { return Math.Min(max, Math.Max(min, val)); } } public static class Smarter { public static int ToInt(this string str) { return int.Parse(str); } public static long ToLong(this string str) { return long.Parse(str); } public static int[] ToInt(this string[] str) { int[] r = new int[str.Length]; for (int i = 0; i < str.Length; i++) r[i] = str[i].ToInt(); return r; } }
[["-", 8, 196, 0, 7, 8, 1, 0, 11, 12, 203], ["+", 8, 196, 0, 7, 8, 1, 0, 11, 12, 203]]
8
447
2
using System; using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static void Main() { var N = int.Parse(ReadLine()); var h = ReadLine().Split().Select(int.Parse).ToArray(); if (N == 2) { WriteLine(Math.Abs(h[1] - h[0])); } var dp = new int[N]; dp[1] = Math.Abs(h[1] - h[0]); for (int i = 2; i < N; i++) { dp[i] = Math.Min(Math.Abs(h[i] - h[i - 1]) + dp[i - 1], Math.Abs(h[i] - h[i - 2]) + dp[i - 2]); } WriteLine(dp[N - 1]); } }
using System; using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static void Main() { var N = int.Parse(ReadLine()); var h = ReadLine().Split().Select(int.Parse).ToArray(); if (N == 2) { WriteLine(Math.Abs(h[1] - h[0])); return; } var dp = new int[N]; dp[1] = Math.Abs(h[1] - h[0]); for (int i = 2; i < N; i++) { dp[i] = Math.Min(Math.Abs(h[i] - h[i - 1]) + dp[i - 1], Math.Abs(h[i] - h[i - 2]) + dp[i - 2]); } WriteLine(dp[N - 1]); } }
[["+", 8, 196, 0, 57, 64, 196, 0, 37, 0, 38], ["+", 8, 196, 0, 57, 64, 196, 0, 37, 0, 35]]
8
205
2
using System; using System.Linq; namespace A_Frog_1 { class Program { static void Main(string[] args) { var N = int.Parse(Console.ReadLine()); var hi = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray(); var costs = new int[N]; costs[0] = 0; costs[1] = Math.Abs(hi[0] - hi[1]); for (int i = 2; i <= N; i++) { costs[i] = Math.Min(costs[i - 2] + Math.Abs(hi[i - 2] - hi[i]), costs[i - 1] + Math.Abs(hi[i - 1] - hi[i])); } Console.WriteLine(costs[N]); } } }
using System; using System.Linq; namespace A_Frog_1 { class Program { static void Main(string[] args) { var N = int.Parse(Console.ReadLine()); var hi = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray(); var costs = new int[N]; costs[0] = 0; costs[1] = Math.Abs(hi[0] - hi[1]); for (int i = 2; i <= N - 1; i++) { costs[i] = Math.Min(costs[i - 2] + Math.Abs(hi[i - 2] - hi[i]), costs[i - 1] + Math.Abs(hi[i - 1] - hi[i])); } Console.WriteLine(costs[N - 1]); } } }
[["+", 8, 196, 0, 7, 15, 16, 12, 16, 17, 33], ["+", 8, 196, 0, 7, 15, 16, 12, 16, 12, 203], ["+", 0, 204, 206, 207, 0, 28, 0, 16, 17, 33], ["+", 0, 204, 206, 207, 0, 28, 0, 16, 12, 203]]
8
193
4
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Competitive { internal class Solution { public int N; public long MOD = 1000000007; public int[] H; public long[] DP; public void Run() { N = Input.ReadInt(); H = Input.ReadIntArray(); DP = new long[N]; DP[0] = 0; DP[1] = H[1] - H[0]; for (int i = 2; i < N; i++) { DP[i] = Math.Min(DP[i - 2] + Math.Abs(H[i] - H[i - 2]), DP[i - 1] + Math.Abs(H[i] - H[i - 1])); } Console.WriteLine(DP[N - 1]); } } // libs ---------- // common ---------- internal static class Input { public static string ReadString() { string line = Console.ReadLine(); return line; } public static int ReadInt() { string line = Console.ReadLine(); return int.Parse(line); } public static int[] ReadIntArray() { string line = Console.ReadLine(); return line.Split(' ').Select(int.Parse).ToArray(); } public static long ReadLong() { string line = Console.ReadLine(); return long.Parse(line); } public static long[] ReadLongArray() { string line = Console.ReadLine(); return line.Split(' ').Select(long.Parse).ToArray(); } public static double[] ReadDoubleArray() { string line = Console.ReadLine(); return line.Split(' ').Select(double.Parse).ToArray(); } } internal class Program { public static void Main(string[] args) { var s = new Solution(); s.Run(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Competitive { internal class Solution { public int N; public long MOD = 1000000007; public int[] H; public long[] DP; public void Run() { N = Input.ReadInt(); H = Input.ReadIntArray(); DP = new long[N]; DP[0] = 0; DP[1] = Math.Abs(H[1] - H[0]); for (int i = 2; i < N; i++) { DP[i] = Math.Min(DP[i - 2] + Math.Abs(H[i] - H[i - 2]), DP[i - 1] + Math.Abs(H[i] - H[i - 1])); } Console.WriteLine(DP[N - 1]); } } // libs ---------- // common ---------- internal static class Input { public static string ReadString() { string line = Console.ReadLine(); return line; } public static int ReadInt() { string line = Console.ReadLine(); return int.Parse(line); } public static int[] ReadIntArray() { string line = Console.ReadLine(); return line.Split(' ').Select(int.Parse).ToArray(); } public static long ReadLong() { string line = Console.ReadLine(); return long.Parse(line); } public static long[] ReadLongArray() { string line = Console.ReadLine(); return line.Split(' ').Select(long.Parse).ToArray(); } public static double[] ReadDoubleArray() { string line = Console.ReadLine(); return line.Split(' ').Select(double.Parse).ToArray(); } } internal class Program { public static void Main(string[] args) { var s = new Solution(); s.Run(); } } }
[["+", 0, 1, 0, 11, 12, 213, 63, 214, 205, 22], ["+", 0, 1, 0, 11, 12, 213, 63, 214, 0, 131], ["+", 0, 1, 0, 11, 12, 213, 63, 214, 141, 22], ["+", 0, 1, 0, 11, 12, 213, 3, 4, 0, 24], ["+", 0, 1, 0, 11, 12, 213, 3, 4, 0, 25]]
8
419
5
using System; namespace AtCoder { class Program { static void Main(string[] args) { string[] input1 = Console.ReadLine().Split(' '); int n = int.Parse(input1[0]); int k = int.Parse(input1[1]); string[] input = Console.ReadLine().Split(' '); int[] dp = new int[n]; dp[0] = 0; dp[1] = Math.Abs(int.Parse(input[0]) - int.Parse(input[1])); for (int i = 2; i < n; i++) { int min = 200000; for (int j = i - 1; j >= Math.Max(0, i - k); j--) { min = Math.Min( min, Math.Abs(int.Parse(input[i]) - int.Parse(input[j])) + dp[j]); } dp[i] = min; } Console.WriteLine(dp[n - 1]); } } }
using System; namespace AtCoder { class Program { static void Main(string[] args) { string[] input1 = Console.ReadLine().Split(' '); int n = int.Parse(input1[0]); int k = int.Parse(input1[1]); string[] input = Console.ReadLine().Split(' '); int[] dp = new int[n]; dp[0] = 0; dp[1] = Math.Abs(int.Parse(input[0]) - int.Parse(input[1])); for (int i = 2; i < n; i++) { int min = 2147483647; for (int j = i - 1; j >= Math.Max(0, i - k); j--) { min = Math.Min( min, Math.Abs(int.Parse(input[i]) - int.Parse(input[j])) + dp[j]); } dp[i] = min; } Console.WriteLine(dp[n - 1]); } } }
[["-", 0, 197, 0, 198, 0, 200, 0, 212, 0, 203], ["+", 0, 197, 0, 198, 0, 200, 0, 212, 0, 203]]
8
238
2
using System; using System.Linq; using System.Numerics; class Program { static void Main() { var INF = (int)1e5; var line1 = Console.ReadLine().Split().Select(int.Parse).ToArray(); var N = line1[0]; var K = line1[1]; var steps = Console.ReadLine().Split().Select(int.Parse).ToArray(); var dp = Enumerable.Repeat((int)INF, N + 1).ToArray(); dp[0] = 0; dp[1] = Math.Abs(steps[0] - steps[1]); for (int i = 1; i < N; i++) { for (int j = 1; (i - j) >= 0 && j <= K; j++) { dp[i] = Math.Min(dp[i - j] + Math.Abs(steps[i] - steps[i - j]), dp[i]); } } Console.WriteLine(dp[N - 1]); } }
using System; using System.Linq; using System.Numerics; class Program { static void Main() { var INF = int.MaxValue; var line1 = Console.ReadLine().Split().Select(int.Parse).ToArray(); var N = line1[0]; var K = line1[1]; var steps = Console.ReadLine().Split().Select(int.Parse).ToArray(); var dp = Enumerable.Repeat((int)INF, N + 1).ToArray(); dp[0] = 0; dp[1] = Math.Abs(steps[1] - steps[0]); for (int i = 1; i < N; i++) { for (int j = 1; (i - j) >= 0 && j <= K; j++) { dp[i] = Math.Min(dp[i - j] + Math.Abs(steps[i] - steps[i - j]), dp[i]); } } Console.WriteLine(dp[N - 1]); } }
[["-", 0, 198, 0, 200, 0, 212, 0, 74, 0, 24], ["-", 0, 198, 0, 200, 0, 212, 0, 74, 0, 25], ["-", 0, 198, 0, 200, 0, 212, 0, 74, 51, 250], ["+", 0, 198, 0, 200, 0, 212, 0, 214, 0, 131], ["+", 0, 198, 0, 200, 0, 212, 0, 214, 141, 22], ["-", 0, 16, 31, 204, 206, 207, 0, 28, 0, 203], ["+", 0, 16, 31, 204, 206, 207, 0, 28, 0, 203], ["-", 0, 16, 12, 204, 206, 207, 0, 28, 0, 203], ["+", 0, 16, 12, 204, 206, 207, 0, 28, 0, 203]]
8
235
9
using System; namespace DS { class Program { static void Main(string[] args) { string[] nk = Console.ReadLine().ToString().Split(' '); int n = Convert.ToInt32(nk[0]); int k = Convert.ToInt32(nk[1]); string[] nums = Console.ReadLine().ToString().Split(' '); int[] stones = new int[n]; for (int i = 0; i < n; i++) stones[i] = Convert.ToInt32(nums[i]); int[] cost = new int[n]; cost[0] = 0; cost[1] = Math.Abs(stones[1] - stones[0]); for (int i = 2; i < n; i++) { cost[i] = stones[i]; for (int j = 1; j <= k && i - j >= 0; j++) { cost[i] = Math.Min(cost[i - j] + Math.Abs(stones[i] - stones[i - j]), cost[i]); } } Console.WriteLine(cost[n - 1]); } } }
using System; namespace DS { class Program { static void Main(string[] args) { string[] nk = Console.ReadLine().ToString().Split(' '); int n = Convert.ToInt32(nk[0]); int k = Convert.ToInt32(nk[1]); string[] nums = Console.ReadLine().ToString().Split(' '); int[] stones = new int[n]; for (int i = 0; i < n; i++) stones[i] = Convert.ToInt32(nums[i]); int[] cost = new int[n]; cost[0] = 0; cost[1] = Math.Abs(stones[1] - stones[0]); for (int i = 2; i < n; i++) { cost[i] = int.MaxValue; for (int j = 1; j <= k && i - j >= 0; j++) { cost[i] = Math.Min(cost[i - j] + Math.Abs(stones[i] - stones[i - j]), cost[i]); } } Console.WriteLine(cost[n - 1]); } } }
[["-", 8, 196, 0, 1, 0, 11, 12, 204, 205, 22], ["-", 0, 1, 0, 11, 12, 204, 206, 207, 0, 70], ["-", 0, 11, 12, 204, 206, 207, 0, 28, 0, 22], ["-", 0, 1, 0, 11, 12, 204, 206, 207, 0, 73], ["+", 8, 196, 0, 1, 0, 11, 12, 214, 205, 199], ["+", 8, 196, 0, 1, 0, 11, 12, 214, 0, 131], ["+", 8, 196, 0, 1, 0, 11, 12, 214, 141, 22]]
8
269
7
using System; using System.Collections.Generic; // list用 using System.Text; // StringBuilder用 using System.Collections; using System.Linq; class Program { static List<int> s = new List<int>(); static decimal result; static Hashtable ht = new Hashtable(); static StringBuilder sb = new StringBuilder(); static int N, M, K; static long[,] table; static void Main() { Read4(); Read2(); int[] check = new int[N]; check[0] = 0; for (int i = 1; i < N; i++) { int tmp = 10000; for (int j = 1; j <= K; j++) { if (i - j < 0) { break; } tmp = Math.Min(check[i - j] + Math.Abs(s[i] - s[i - j]), tmp); } check[i] = tmp; } Console.WriteLine(check[N - 1].ToString()); } static void Read1() // 1項 { string tmp = Console.ReadLine(); N = int.Parse(tmp); } static void Read2() //複数項(項目数N) { string[] tmp = Console.ReadLine().Split(' '); for (int i = 0; i < N; i++) { s.Add(int.Parse(tmp[i])); } } static void Read3() // 1行複数項 { string[] tmp = Console.ReadLine().Split(' '); for (int i = 0; i < tmp.Length; i++) { s.Add(int.Parse(tmp[i])); } } static void Read4() // NK1行 { string[] tmp = Console.ReadLine().Split(' '); N = int.Parse(tmp[0]); K = int.Parse(tmp[1]); } static void Read5() // N行K項 {} }
using System; using System.Collections.Generic; // list用 using System.Text; // StringBuilder用 using System.Collections; using System.Linq; class Program { static List<int> s = new List<int>(); static decimal result; static Hashtable ht = new Hashtable(); static StringBuilder sb = new StringBuilder(); static int N, M, K; static long[,] table; static void Main() { Read4(); Read2(); int[] check = new int[N]; check[0] = 0; for (int i = 1; i < N; i++) { int tmp = 2000000000; for (int j = 1; j <= K; j++) { if (i - j < 0) { break; } tmp = Math.Min(check[i - j] + Math.Abs(s[i] - s[i - j]), tmp); } check[i] = tmp; } Console.WriteLine(check[N - 1].ToString()); } static void Read1() // 1項 { string tmp = Console.ReadLine(); N = int.Parse(tmp); } static void Read2() //複数項(項目数N) { string[] tmp = Console.ReadLine().Split(' '); for (int i = 0; i < N; i++) { s.Add(int.Parse(tmp[i])); } } static void Read3() // 1行複数項 { string[] tmp = Console.ReadLine().Split(' '); for (int i = 0; i < tmp.Length; i++) { s.Add(int.Parse(tmp[i])); } } static void Read4() // NK1行 { string[] tmp = Console.ReadLine().Split(' '); N = int.Parse(tmp[0]); K = int.Parse(tmp[1]); } static void Read5() // N行K項 {} }
[["-", 0, 197, 0, 198, 0, 200, 0, 212, 0, 203], ["+", 0, 197, 0, 198, 0, 200, 0, 212, 0, 203]]
8
421
2
using System; using System.Text; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Math; namespace AtCoder { public class Program { public static void Main(string[] args) { int[] NM = ReadInts(); int[] h = ReadInts(); long[] cost = new long[NM[0]]; for (int i = 1; i < NM[0]; i++) { long minm = 10000; for (int j = Max(0, i - NM[1]); j < i; j++) { // Write(i+" "+j); minm = Min(cost[j] + Abs(h[j] - h[i]), minm); } cost[i] = minm; } Write(cost.Last()); } private static void Write<T>(IEnumerable<T> target, string sep = " ") { Console.WriteLine(string.Join(sep, target)); } private static void Write<T>(T str) { Console.WriteLine(str); } private static string[] ReadStrings() { return Console.ReadLine().Split(' '); } private static int ReadInt() { return int.Parse(Console.ReadLine()); } private static double ReadDouble() { return double.Parse(Console.ReadLine()); } private static int[] ReadInts() { return Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray(); } private static double[] ReadDoubles() { return Console.ReadLine().Split(' ').Select(x => double.Parse(x)).ToArray(); } } }
using System; using System.Text; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Math; namespace AtCoder { public class Program { public static void Main(string[] args) { int[] NM = ReadInts(); int[] h = ReadInts(); long[] cost = new long[NM[0]]; for (int i = 1; i < NM[0]; i++) { long minm = long.MaxValue; for (int j = Max(0, i - NM[1]); j < i; j++) { // Write(i+" "+j); minm = Min(cost[j] + Abs(h[j] - h[i]), minm); } cost[i] = minm; } Write(cost.Last()); } private static void Write<T>(IEnumerable<T> target, string sep = " ") { Console.WriteLine(string.Join(sep, target)); } private static void Write<T>(T str) { Console.WriteLine(str); } private static string[] ReadStrings() { return Console.ReadLine().Split(' '); } private static int ReadInt() { return int.Parse(Console.ReadLine()); } private static double ReadDouble() { return double.Parse(Console.ReadLine()); } private static int[] ReadInts() { return Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray(); } private static double[] ReadDoubles() { return Console.ReadLine().Split(' ').Select(x => double.Parse(x)).ToArray(); } } }
[["-", 0, 197, 0, 198, 0, 200, 0, 212, 0, 203], ["+", 0, 198, 0, 200, 0, 212, 0, 214, 205, 199], ["+", 0, 198, 0, 200, 0, 212, 0, 214, 0, 131], ["+", 0, 198, 0, 200, 0, 212, 0, 214, 141, 22]]
8
377
4
using System; using System.Linq; namespace A_Frog_2 { class Program { static void Main(string[] args) { var l1 = Console.ReadLine().Split(' '); var N = int.Parse(l1[0]); var K = int.Parse(l1[1]); var hi = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray(); var costs = new int[N]; costs[0] = 0; for (int i = 1; i <= K; i++) { costs[i] = Math.Abs(hi[0] - hi[i]); if (i == N - 1) break; } for (int i = K + 1; i <= N - 1; i++) { costs[i] = 10000; for (int j = 1; j <= K; j++) { costs[i] = Math.Min(costs[i], costs[i - j] + Math.Abs(hi[i] - hi[i - j])); } } Console.WriteLine(costs[N - 1]); } } }
using System; using System.Linq; namespace A_Frog_2 { class Program { static void Main(string[] args) { var l1 = Console.ReadLine().Split(' '); var N = int.Parse(l1[0]); var K = int.Parse(l1[1]); var hi = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray(); var costs = new long[N]; costs[0] = 0; for (int i = 1; i <= K; i++) { costs[i] = Math.Abs(hi[0] - hi[i]); if (i == N - 1) break; } for (int i = K + 1; i <= N - 1; i++) { costs[i] = long.MaxValue; for (int j = 1; j <= K; j++) { costs[i] = Math.Min(costs[i], costs[i - j] + Math.Abs(hi[i] - hi[i - j])); } } Console.WriteLine(costs[N - 1]); } } }
[["-", 0, 200, 0, 212, 0, 227, 39, 224, 39, 199], ["+", 0, 200, 0, 212, 0, 227, 39, 224, 39, 199], ["-", 0, 7, 8, 196, 0, 1, 0, 11, 12, 203], ["+", 8, 196, 0, 1, 0, 11, 12, 214, 205, 199], ["+", 8, 196, 0, 1, 0, 11, 12, 214, 0, 131], ["+", 8, 196, 0, 1, 0, 11, 12, 214, 141, 22]]
8
257
6
using System; public static class Solution { private static int[,] s_arr; private static int[,] s_memo; public static void Main() { int n = int.Parse(Console.ReadLine()); s_arr = new int[n, 3]; s_memo = new int[n, 3]; for (int i = 0; i < n; i++) { var ithDay = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); s_arr[i, 0] = ithDay[0]; s_arr[i, 1] = ithDay[1]; s_arr[i, 2] = ithDay[2]; s_memo[i, 0] = -1; s_memo[i, 1] = -1; s_memo[i, 2] = -1; } if (n == 1) { Console.WriteLine( Math.Max(s_arr[0, 0], Math.Max(s_arr[0, 1], s_arr[0, 2]))); } else { int max1 = s_arr[0, 0] + Solve(0, 1); // Solve(lastTakenActivity, startingDay); int max2 = s_arr[0, 1] + Solve(1, 1); // Solve(lastTakenActivity, startingDay); int max3 = s_arr[0, 2] + Solve(2, 1); // Solve(lastTakenActivity, startingDay); Console.WriteLine(Math.Max(max1, Math.Max(max2, max3))); } } private static int Solve(int lastTakenActivity, int startingDay) { if (s_memo[startingDay, lastTakenActivity] != -1) return s_memo[startingDay, lastTakenActivity]; int option1, option2, option1Index, option2Index; if (lastTakenActivity == 0) { option1 = s_arr[startingDay, 1]; option1Index = 1; option2 = s_arr[startingDay, 2]; option2Index = 2; } else if (lastTakenActivity == 1) { option1 = s_arr[startingDay, 0]; option1Index = 0; option2 = s_arr[startingDay, 2]; option2Index = 2; } else { option1 = s_arr[startingDay, 0]; option1Index = 0; option2 = s_arr[startingDay, 1]; option2Index = 1; } if (startingDay == s_arr.Length / 3 - 1) return Math.Max(option1, option2); // Array length returns n * m here. We // want n only, so divide by m = 3. return s_memo[lastTakenActivity, startingDay] = Math.Max(option1 + Solve(option1Index, startingDay + 1), option2 + Solve(option2Index, startingDay + 1)); } }
using System; public static class Solution { private static int[,] s_arr; private static int[,] s_memo; public static void Main() { int n = int.Parse(Console.ReadLine()); s_arr = new int[n, 3]; s_memo = new int[n, 3]; for (int i = 0; i < n; i++) { var ithDay = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); s_arr[i, 0] = ithDay[0]; s_arr[i, 1] = ithDay[1]; s_arr[i, 2] = ithDay[2]; s_memo[i, 0] = -1; s_memo[i, 1] = -1; s_memo[i, 2] = -1; } if (n == 1) { Console.WriteLine( Math.Max(s_arr[0, 0], Math.Max(s_arr[0, 1], s_arr[0, 2]))); } else { int max1 = s_arr[0, 0] + Solve(0, 1); // Solve(lastTakenActivity, startingDay); int max2 = s_arr[0, 1] + Solve(1, 1); // Solve(lastTakenActivity, startingDay); int max3 = s_arr[0, 2] + Solve(2, 1); // Solve(lastTakenActivity, startingDay); Console.WriteLine(Math.Max(max1, Math.Max(max2, max3))); } } private static int Solve(int lastTakenActivity, int startingDay) { if (s_memo[startingDay, lastTakenActivity] != -1) return s_memo[startingDay, lastTakenActivity]; int option1, option2, option1Index, option2Index; if (lastTakenActivity == 0) { option1 = s_arr[startingDay, 1]; option1Index = 1; option2 = s_arr[startingDay, 2]; option2Index = 2; } else if (lastTakenActivity == 1) { option1 = s_arr[startingDay, 0]; option1Index = 0; option2 = s_arr[startingDay, 2]; option2Index = 2; } else { option1 = s_arr[startingDay, 0]; option1Index = 0; option2 = s_arr[startingDay, 1]; option2Index = 1; } if (startingDay == s_arr.Length / 3 - 1) return Math.Max(option1, option2); // Array length returns n * m here. We // want n only, so divide by m = 3. return s_memo[startingDay, lastTakenActivity] = Math.Max(option1 + Solve(option1Index, startingDay + 1), option2 + Solve(option2Index, startingDay + 1)); } }
[["-", 0, 11, 31, 204, 206, 207, 0, 28, 0, 22], ["-", 0, 37, 0, 11, 31, 204, 206, 207, 0, 21], ["+", 0, 37, 0, 11, 31, 204, 206, 207, 0, 21], ["+", 0, 11, 31, 204, 206, 207, 0, 28, 0, 22]]
8
495
4
using System; using System.Linq; using System.Collections.Generic; using static System.Math; namespace C { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var abc = new int [n][]; var dp = new int [n][]; for (int i = 0; i < n; i++) { abc[i] = Console.ReadLine().Split().Select(int.Parse).ToArray(); dp[i] = new int[3] { 0, 0, 0 }; } dp[0] = abc[0]; for (int i = 1; i < n; i++) { for (int j = 0; j < 3; j++) { int cmax = 0; for (int k = 0; k < 3; k++) { if (j != k) { cmax = Max(cmax, dp[i - 1][j] + abc[i][k]); } } dp[i][j] = cmax; } } Console.WriteLine(dp.Last().Max()); } } }
using System; using System.Linq; using System.Collections.Generic; using static System.Math; namespace C { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var abc = new int [n][]; var dp = new int [n][]; for (int i = 0; i < n; i++) { abc[i] = Console.ReadLine().Split().Select(int.Parse).ToArray(); dp[i] = new int[3] { 0, 0, 0 }; } dp[0] = abc[0]; for (int i = 1; i < n; i++) { for (int j = 0; j < 3; j++) { int cmax = 0; for (int k = 0; k < 3; k++) { if (j != k) { cmax = Max(cmax, dp[i - 1][k] + abc[i][j]); } } dp[i][j] = cmax; } } Console.WriteLine(dp.Last().Max()); } } }
[["-", 0, 16, 31, 204, 206, 207, 0, 28, 0, 22], ["+", 0, 16, 31, 204, 206, 207, 0, 28, 0, 22], ["-", 0, 16, 12, 204, 206, 207, 0, 28, 0, 22], ["+", 0, 16, 12, 204, 206, 207, 0, 28, 0, 22]]
8
257
4
using System; using System.Linq; namespace C___Vacation { class Program { static void Main(string[] args) { var N = int.Parse(Console.ReadLine()); var vacation = new int[N + 1, 3]; for (int i = 1; i < N + 1; i++) { var Read = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray(); vacation[i, 0] = Read[0]; vacation[i, 1] = Read[1]; vacation[i, 2] = Read[2]; } var happiness = new long[N + 1, 3]; for (int i = 1; i < N + 1; i++) { happiness[i, 0] = Math.Max(happiness[i - 1, 1], happiness[i - 1, 2]) + vacation[i, 0]; happiness[i, 1] = Math.Max(happiness[i - 1, 0], happiness[i - 1, 2]) + vacation[i, 1]; happiness[i, 2] = Math.Max(happiness[i - 1, 0], happiness[i - 1, 1]) + vacation[1, 2]; } Console.WriteLine( Math.Max(happiness[N, 2], Math.Max(happiness[N, 0], happiness[N, 1]))); } } }
using System; using System.Linq; namespace C___Vacation { class Program { static void Main(string[] args) { var N = int.Parse(Console.ReadLine()); var vacation = new int[N + 1, 3]; for (int i = 1; i < N + 1; i++) { var Read = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray(); vacation[i, 0] = Read[0]; vacation[i, 1] = Read[1]; vacation[i, 2] = Read[2]; } var happiness = new long[N + 1, 3]; for (int i = 1; i < N + 1; i++) { happiness[i, 0] = Math.Max(happiness[i - 1, 1], happiness[i - 1, 2]) + vacation[i, 0]; happiness[i, 1] = Math.Max(happiness[i - 1, 0], happiness[i - 1, 2]) + vacation[i, 1]; happiness[i, 2] = Math.Max(happiness[i - 1, 0], happiness[i - 1, 1]) + vacation[i, 2]; } Console.WriteLine( Math.Max(happiness[N, 2], Math.Max(happiness[N, 0], happiness[N, 1]))); } } }
[["-", 12, 16, 12, 204, 206, 207, 0, 28, 0, 203], ["+", 12, 16, 12, 204, 206, 207, 0, 28, 0, 22]]
8
318
2
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; class TEST { static void Main() { Sol mySol = new Sol(); mySol.Solve(); } } class Sol { public void Solve() { long[][] dp = new long [3][]; for (int i = 0; i < 3; i++) { dp[i] = new long[N]; } dp[0][0] = A[0]; dp[1][0] = B[0]; dp[2][0] = C[0]; for (int i = 0; i < N - 1; i++) { dp[0][i + 1] = Math.Max(dp[0][i + 1], dp[1][i] + A[i + 1]); dp[0][i + 1] = Math.Max(dp[0][i + 1], dp[2][i] + A[i + 1]); dp[1][i + 1] = Math.Max(dp[0][i + 1], dp[0][i] + B[i + 1]); dp[1][i + 1] = Math.Max(dp[0][i + 1], dp[2][i] + B[i + 1]); dp[2][i + 1] = Math.Max(dp[0][i + 1], dp[0][i] + C[i + 1]); dp[2][i + 1] = Math.Max(dp[0][i + 1], dp[1][i] + C[i + 1]); } long ans = 0; for (int i = 0; i < 3; i++) ans = Math.Max(ans, dp[i][N - 1]); Console.WriteLine(ans); } int N; int[] A, B, C; public Sol() { N = ri(); A = new int[N]; B = new int[N]; C = new int[N]; for (int i = 0; i < N; i++) { var d = ria(); A[i] = d[0]; B[i] = d[1]; C[i] = d[2]; } } static String rs() { return Console.ReadLine(); } static int ri() { return int.Parse(Console.ReadLine()); } static long rl() { return long.Parse(Console.ReadLine()); } static double rd() { return double.Parse(Console.ReadLine()); } static String[] rsa(char sep = ' ') { return Console.ReadLine().Split(sep); } static int[] ria(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); } static long[] rla(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); } static double[] rda(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; class TEST { static void Main() { Sol mySol = new Sol(); mySol.Solve(); } } class Sol { public void Solve() { long[][] dp = new long [3][]; for (int i = 0; i < 3; i++) { dp[i] = new long[N]; } dp[0][0] = A[0]; dp[1][0] = B[0]; dp[2][0] = C[0]; for (int i = 0; i < N - 1; i++) { dp[0][i + 1] = Math.Max(dp[0][i + 1], dp[1][i] + A[i + 1]); dp[0][i + 1] = Math.Max(dp[0][i + 1], dp[2][i] + A[i + 1]); dp[1][i + 1] = Math.Max(dp[1][i + 1], dp[0][i] + B[i + 1]); dp[1][i + 1] = Math.Max(dp[1][i + 1], dp[2][i] + B[i + 1]); dp[2][i + 1] = Math.Max(dp[2][i + 1], dp[0][i] + C[i + 1]); dp[2][i + 1] = Math.Max(dp[2][i + 1], dp[1][i] + C[i + 1]); } long ans = 0; for (int i = 0; i < 3; i++) ans = Math.Max(ans, dp[i][N - 1]); Console.WriteLine(ans); } int N; int[] A, B, C; public Sol() { N = ri(); A = new int[N]; B = new int[N]; C = new int[N]; for (int i = 0; i < N; i++) { var d = ria(); A[i] = d[0]; B[i] = d[1]; C[i] = d[2]; } } static String rs() { return Console.ReadLine(); } static int ri() { return int.Parse(Console.ReadLine()); } static long rl() { return long.Parse(Console.ReadLine()); } static double rd() { return double.Parse(Console.ReadLine()); } static String[] rsa(char sep = ' ') { return Console.ReadLine().Split(sep); } static int[] ria(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); } static long[] rla(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); } static double[] rda(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); } }
[["-", 0, 204, 205, 204, 206, 207, 0, 28, 0, 203], ["+", 0, 204, 205, 204, 206, 207, 0, 28, 0, 203]]
8
767
8
using System; using System.Collections.Generic; using System.Linq; namespace D2 { class Program { static void Main() { var nw = Console.ReadLine().Split().Select(int.Parse).ToList(); var N = nw[0]; var W = nw[1]; var w = new List<int>(); var v = new List<int>(); w.Add(0); v.Add(0); for (int i = 0; i < N; ++i) { var nw2 = Console.ReadLine().Split().Select(int.Parse).ToList(); w.Add(nw2[0]); v.Add(nw2[1]); } var dp = new decimal[N + 10, W + 10]; for (int i = 1; i <= N; ++i) { for (int j = 0; j < 100000; ++j) { if (j - w[i] >= 0) dp[i, j] = Math.Max(dp[i - 1, j], dp[i - 1, j - w[i]] + v[i]); dp[i, j] = Math.Max(dp[i, j], dp[i - 1, j]); } } Console.WriteLine(dp[N, W]); } } }
using System; using System.Collections.Generic; using System.Linq; namespace D2 { class Program { static void Main() { var nw = Console.ReadLine().Split().Select(int.Parse).ToList(); var N = nw[0]; var W = nw[1]; var w = new List<int>(); var v = new List<int>(); w.Add(0); v.Add(0); for (int i = 0; i < N; ++i) { var nw2 = Console.ReadLine().Split().Select(int.Parse).ToList(); w.Add(nw2[0]); v.Add(nw2[1]); } var dp = new decimal[N + 10, W + 10]; for (int i = 1; i <= N; ++i) { for (int j = 0; j <= W; ++j) { if (j - w[i] >= 0) dp[i, j] = Math.Max(dp[i - 1, j], dp[i - 1, j - w[i]] + v[i]); dp[i, j] = Math.Max(dp[i, j], dp[i - 1, j]); } } Console.WriteLine(dp[N, W]); } } }
[["-", 0, 7, 8, 196, 0, 7, 15, 16, 17, 18], ["-", 0, 7, 8, 196, 0, 7, 15, 16, 12, 203], ["+", 0, 7, 8, 196, 0, 7, 15, 16, 17, 19], ["+", 0, 7, 8, 196, 0, 7, 15, 16, 12, 22]]
8
304
4
using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using static System.Console; using static System.Math; class Program { static void Main(string[] args) { int[] NW = ReadLineParseIntArray(); int N = NW[0]; int W = NW[1]; int[,] dp = new int[N + 1, W + 1]; for (int i = 0; i < N; i++) { int[] wv = ReadLineParseIntArray(); for (int w = 0; w <= W; w++) { if (w >= wv[0]) dp[i + 1, w] = Max(dp[i, w - wv[0]] + wv[1], dp[i, w]); else dp[i + 1, w] = dp[i, w]; } } WriteLine(dp[N, W]); } static int ReadLineParseInt() => int.Parse(ReadLine()); static int[] ReadLineParseIntArray() => ReadLine().Split(' ').Select(int.Parse).ToArray(); }
using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using static System.Console; using static System.Math; class Program { static void Main(string[] args) { int[] NW = ReadLineParseIntArray(); int N = NW[0]; int W = NW[1]; long[,] dp = new long[N + 1, W + 1]; for (int i = 0; i < N; i++) { int[] wv = ReadLineParseIntArray(); for (int w = 0; w <= W; w++) { if (w >= wv[0]) dp[i + 1, w] = Max(dp[i, w - wv[0]] + wv[1], dp[i, w]); else dp[i + 1, w] = dp[i, w]; } } WriteLine(dp[N, W]); } static int ReadLineParseInt() => int.Parse(ReadLine()); static int[] ReadLineParseIntArray() => ReadLine().Split(' ').Select(int.Parse).ToArray(); }
[["-", 8, 196, 0, 197, 0, 198, 39, 224, 39, 199], ["+", 8, 196, 0, 197, 0, 198, 39, 224, 39, 199], ["-", 0, 200, 0, 212, 0, 227, 39, 224, 39, 199], ["+", 0, 200, 0, 212, 0, 227, 39, 224, 39, 199]]
8
255
4
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var input = Console.ReadLine().Split().Select(int.Parse).ToArray(); var N = input[0]; var W = input[1]; var dp = new int[N + 1, W + 1]; var values = new int[N]; var weight = new int[N]; for (var i = 0; i < N; i++) { input = Console.ReadLine().Split().Select(int.Parse).ToArray(); weight[i] = input[0]; values[i] = input[1]; } /* * 3 8 3 30 4 50 5 60 */ /* * for (int sum_w = 0; sum_w <= W; ++sum_w) { // i 番目の品物を選ぶ場合 if (sum_w - weight[i] >= 0) { chmax(dp[i+1][sum_w], dp[i][sum_w - weight[i]] + value[i]); } */ for (var i = 0; i < N; i++) { for (var j = 0; j <= W; j++) { dp[i + 1, j] = dp[i, j]; if (j - weight[i] >= 0) { dp[i + 1, j] = Math.Max(dp[i + 1, j], dp[i, j - weight[i]] + values[i]); } } } Console.WriteLine(dp[N, W]); /* * 3 8 3 30 4 50 5 60 */ } }
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var input = Console.ReadLine().Split().Select(long.Parse).ToArray(); var N = input[0]; var W = input[1]; var dp = new long[N + 1, W + 1]; var values = new long[N]; var weight = new long[N]; for (var i = 0; i < N; i++) { input = Console.ReadLine().Split().Select(long.Parse).ToArray(); weight[i] = input[0]; values[i] = input[1]; } /* * 3 8 3 30 4 50 5 60 */ /* * for (int sum_w = 0; sum_w <= W; ++sum_w) { // i 番目の品物を選ぶ場合 if (sum_w - weight[i] >= 0) { chmax(dp[i+1][sum_w], dp[i][sum_w - weight[i]] + value[i]); } */ for (var i = 0; i < N; i++) { for (var j = 0; j <= W; j++) { dp[i + 1, j] = dp[i, j]; if (j - weight[i] >= 0) { dp[i + 1, j] = Math.Max(dp[i + 1, j], dp[i, j - weight[i]] + values[i]); } } } Console.WriteLine(dp[N, W]); /* * 3 8 3 30 4 50 5 60 */ } }
[["-", 205, 213, 3, 4, 0, 28, 0, 214, 205, 199], ["+", 205, 213, 3, 4, 0, 28, 0, 214, 205, 199], ["-", 0, 200, 0, 212, 0, 227, 39, 224, 39, 199], ["+", 0, 200, 0, 212, 0, 227, 39, 224, 39, 199]]
8
278
10
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] s = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); int N = s[0], W = s[1]; long[] dp = new long[W + 1]; for (int i = 1; i <= N; i++) { int[] q = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); int w = s[0], v = s[1]; for (int j = W; j >= w; j--) { dp[j] = Math.Max(dp[j], dp[j - w] + v); } } Console.WriteLine("{0}", dp[W]); } }
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] s = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); int N = s[0], W = s[1]; long[] dp = new long[W + 1]; for (int i = 1; i <= N; i++) { int[] q = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); int w = q[0], v = q[1]; for (int j = W; j >= w; j--) { dp[j] = Math.Max(dp[j], dp[j - w] + v); } } Console.WriteLine("{0}", dp[W]); } }
[["-", 0, 198, 0, 200, 0, 212, 0, 204, 205, 22], ["+", 0, 198, 0, 200, 0, 212, 0, 204, 205, 22]]
8
187
4
using System; using System.Collections.Generic; using System.Linq; class Program { static Scanner cin = new Scanner(); static void Main(string[] args) { int N = cin.Int(); int W = cin.Int(); var w = new int[N]; var v = new int[N]; for (int i = 0; i < N; i++) { w[i] = cin.Int(); v[i] = cin.Int(); } var dp = new int[110, 100010]; for (int i = 0; i < N; i++) { for (int j = 0; j <= W; j++) { //重さ if (j - w[i] >= 0) dp[i + 1, j] = Math.Max(dp[i + 1, j], dp[i, j - w[i]] + v[i]); dp[i + 1, j] = Math.Max(dp[i + 1, j], dp[i, j]); } } Console.WriteLine(dp[N, W]); Console.ReadLine(); } } class Scanner //標準入力 { string[] s; int i; char[] cs = new char[] { ' ' }; public Scanner() { s = new string[0]; i = 0; } public string next() { if (i < s.Length) return s[i++]; string st = Console.ReadLine(); while (st == "") st = Console.ReadLine(); s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries); if (s.Length == 0) return next(); i = 0; return s[i++]; } public int Int() { return int.Parse(next()); } public int[] ArrayInt(int N, int add = 0) { int[] Array = new int[N]; for (int i = 0; i < N; i++) { Array[i] = Int() + add; } return Array; } public long Long() { return long.Parse(next()); } public long[] ArrayLong(int N, long add = 0) { long[] Array = new long[N]; for (int i = 0; i < N; i++) { Array[i] = Long() + add; } return Array; } public double Double() { return double.Parse(next()); } public double[] ArrayDouble(int N, double add = 0) { double[] Array = new double[N]; for (int i = 0; i < N; i++) { Array[i] = Double() + add; } return Array; } }
using System; using System.Collections.Generic; using System.Linq; class Program { static Scanner cin = new Scanner(); static void Main(string[] args) { int N = cin.Int(); int W = cin.Int(); var w = new int[N]; var v = new int[N]; for (int i = 0; i < N; i++) { w[i] = cin.Int(); v[i] = cin.Int(); } var dp = new long[110, 100010]; for (int i = 0; i < N; i++) { for (int j = 0; j <= W; j++) { //重さ if (j - w[i] >= 0) dp[i + 1, j] = Math.Max(dp[i + 1, j], dp[i, j - w[i]] + v[i]); dp[i + 1, j] = Math.Max(dp[i + 1, j], dp[i, j]); } } Console.WriteLine(dp[N, W]); Console.ReadLine(); } } class Scanner //標準入力 { string[] s; int i; char[] cs = new char[] { ' ' }; public Scanner() { s = new string[0]; i = 0; } public string next() { if (i < s.Length) return s[i++]; string st = Console.ReadLine(); while (st == "") st = Console.ReadLine(); s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries); if (s.Length == 0) return next(); i = 0; return s[i++]; } public int Int() { return int.Parse(next()); } public int[] ArrayInt(int N, int add = 0) { int[] Array = new int[N]; for (int i = 0; i < N; i++) { Array[i] = Int() + add; } return Array; } public long Long() { return long.Parse(next()); } public long[] ArrayLong(int N, long add = 0) { long[] Array = new long[N]; for (int i = 0; i < N; i++) { Array[i] = Long() + add; } return Array; } public double Double() { return double.Parse(next()); } public double[] ArrayDouble(int N, double add = 0) { double[] Array = new double[N]; for (int i = 0; i < N; i++) { Array[i] = Double() + add; } return Array; } }
[["-", 0, 200, 0, 212, 0, 227, 39, 224, 39, 199], ["+", 0, 200, 0, 212, 0, 227, 39, 224, 39, 199]]
8
607
2
using System; using System.Collections.Generic; using System.Windows; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Atcoder { public class Program { static void Main(string[] args) { var r1 = ReadSplit(); var n = r1[0].ToLong(); var max = r1[1].ToLong(); var dp = new long [110][]; var w = new long[n]; var v = new long[n]; var INF = 999999999999; for (int i = 0; i < 110; i++) { dp[i] = new long[110000]; for (int j = 0; j < 110000; j++) { dp[i][j] = INF; } } for (int i = 0; i < n; i++) { var r2 = ReadSplit(); w[i] = r2[0].ToLong(); v[i] = r2[1].ToLong(); } var mV = v.Sum(); dp[0][0] = 0; for (int i = 0; i < n; i++) { for (long s = 0; s < mV; s++) { if (s - v[i] >= 0) { ChangeMin(ref dp[i + 1][s], dp[i][s - v[i]] + w[i]); } ChangeMin(ref dp[i + 1][s], dp[i][s]); } } long ans = 0; for (int i = 0; i < mV; i++) { if (dp[n][i] <= max) ans = i; } WriteRead(ans); } public static string Read() { return Console.ReadLine(); } public static string[] ReadSplit() { return Console.ReadLine().Split(' '); } public static void WriteRead(object str) { Console.WriteLine(str); Read(); } public static void Write(object str) { Console.WriteLine(str); } private static bool ChangeMin<T>(ref T a, T b) where T : IComparable { if (a.CompareTo(b) > 0) { a = b; return true; } return false; } private static bool ChangekMax<T>(ref T a, T b) where T : IComparable { if (b.CompareTo(a) > 0) { a = b; return true; } return false; } } } public static class Extentions { public static int ToInt32(this object obj) { return int.Parse(obj.ToString()); } public static long ToLong(this object obj) { return long.Parse(obj.ToString()); } public static decimal ToDecimal(this object obj) { return decimal.Parse(obj.ToString()); } public static double ToDouble(this object obj) { return double.Parse(obj.ToString()); } public static T2 GetValueZero<T1, T2>(this Dictionary<T1, T2> d, T1 key) where T2 : struct { T2 value; if (d.TryGetValue(key, out value)) { return value; } return new T2(); } }
using System; using System.Collections.Generic; using System.Windows; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Atcoder { public class Program { static void Main(string[] args) { var r1 = ReadSplit(); var n = r1[0].ToLong(); var max = r1[1].ToLong(); var dp = new long [110][]; var w = new long[n]; var v = new long[n]; var INF = 999999999999; for (int i = 0; i < 110; i++) { dp[i] = new long[110000]; for (int j = 0; j < 110000; j++) { dp[i][j] = INF; } } for (int i = 0; i < n; i++) { var r2 = ReadSplit(); w[i] = r2[0].ToLong(); v[i] = r2[1].ToLong(); } var mV = v.Sum(); dp[0][0] = 0; for (int i = 0; i < n; i++) { for (long s = 0; s <= mV; s++) { if (s - v[i] >= 0) { ChangeMin(ref dp[i + 1][s], dp[i][s - v[i]] + w[i]); } ChangeMin(ref dp[i + 1][s], dp[i][s]); } } long ans = 0; for (int i = 1; i <= mV; i++) { if (dp[n][i] <= max) ans = i; } WriteRead(ans); } public static string Read() { return Console.ReadLine(); } public static string[] ReadSplit() { return Console.ReadLine().Split(' '); } public static void WriteRead(object str) { Console.WriteLine(str); Read(); } public static void Write(object str) { Console.WriteLine(str); } private static bool ChangeMin<T>(ref T a, T b) where T : IComparable { if (a.CompareTo(b) > 0) { a = b; return true; } return false; } private static bool ChangekMax<T>(ref T a, T b) where T : IComparable { if (b.CompareTo(a) > 0) { a = b; return true; } return false; } } } public static class Extentions { public static int ToInt32(this object obj) { return int.Parse(obj.ToString()); } public static long ToLong(this object obj) { return long.Parse(obj.ToString()); } public static decimal ToDecimal(this object obj) { return decimal.Parse(obj.ToString()); } public static double ToDouble(this object obj) { return double.Parse(obj.ToString()); } public static T2 GetValueZero<T1, T2>(this Dictionary<T1, T2> d, T1 key) where T2 : struct { T2 value; if (d.TryGetValue(key, out value)) { return value; } return new T2(); } }
[["-", 0, 7, 8, 196, 0, 7, 15, 16, 17, 18], ["+", 0, 7, 8, 196, 0, 7, 15, 16, 17, 19], ["-", 0, 7, 10, 198, 0, 200, 0, 212, 0, 203], ["+", 0, 7, 10, 198, 0, 200, 0, 212, 0, 203], ["-", 0, 195, 8, 196, 0, 7, 15, 16, 17, 18], ["+", 0, 195, 8, 196, 0, 7, 15, 16, 17, 19]]
8
698
6
using System; using System.Linq; using System.Collections.Generic; namespace Algorithm { class Program { static void Main(string[] args) { var l = Console.ReadLine().Split().Select(int.Parse).ToArray(); int N = l[0], W = l[1]; var max = N * 1000; var dp = new long[N + 1, max + 1]; for (var i = 0; i <= N; i++) for (var j = 0; j <= max; j++) dp[i, j] = long.MaxValue / 2; dp[0, 0] = 0; for (var i = 0; i < N; i++) { var wv = Console.ReadLine().Split().Select(int.Parse).ToArray(); for (var j = 0; j <= max; j++) { if (j - wv[1] >= 0) { dp[i + 1, j] = Math.Min(dp[i, j], dp[i, j - wv[1]] + wv[0]); } else { dp[i + 1, j] = dp[i, j]; } } } for (int i = max; i >= 0; i--) { if (dp[N - 1, i] <= W) { Console.WriteLine(i); return; } } } } }
using System; using System.Linq; using System.Collections.Generic; namespace Algorithm { class Program { static void Main(string[] args) { var l = Console.ReadLine().Split().Select(int.Parse).ToArray(); int N = l[0], W = l[1]; var max = N * 1000; var dp = new long[N + 1, max + 1]; for (var i = 0; i <= N; i++) for (var j = 0; j <= max; j++) dp[i, j] = long.MaxValue / 2; dp[0, 0] = 0; for (var i = 0; i < N; i++) { var wv = Console.ReadLine().Split().Select(int.Parse).ToArray(); for (var j = 0; j <= max; j++) { if (j - wv[1] >= 0) { dp[i + 1, j] = Math.Min(dp[i, j], dp[i, j - wv[1]] + wv[0]); } else { dp[i + 1, j] = dp[i, j]; } } } for (int i = max; i >= 0; i--) { if (dp[N, i] <= W) { Console.WriteLine(i); return; } } } } }
[["-", 31, 204, 206, 207, 0, 28, 0, 16, 17, 33], ["-", 31, 204, 206, 207, 0, 28, 0, 16, 12, 203]]
8
311
2
using static System.Math; using System.Linq; using System; public class Hello { public static void Main() { string[] line = Console.ReadLine().Trim().Split(' '); var n = int.Parse(line[0]); var wmax = int.Parse(line[1]); var vaL = new int[n + 1]; var w = new int[n + 1]; var vmax = readData(vaL, w); var dp = new long[n + 1, n * vmax + 1]; setDP(dp); for (int i = 0; i < n; i++) for (int j = 0; j <= n * vmax; j++) if (j < vaL[i]) dp[i + 1, j] = dp[i, j]; else dp[i + 1, j] = Min(dp[i, j], dp[i, j - vaL[i]] + w[i]); var ans = 0; for (int i = 0; i <= n * vmax; i++) if (dp[n, i] <= wmax) ans = i; Console.WriteLine(ans); } public static int readData(int[] vaL, int[] w) { for (int i = 0; i < vaL.Length - 1; i++) { string[] line = Console.ReadLine().Trim().Split(' '); vaL[i] = int.Parse(line[1]); w[i] = int.Parse(line[0]); } return vaL.Max(); } public static void setDP(long[,] dp) { var imax = dp.GetLength(1); for (int i = 0; i < imax; i++) dp[0, i] = long.MaxValue; dp[0, 0] = 0; } }
using static System.Math; using System.Linq; using System; public class Hello { public static void Main() { string[] line = Console.ReadLine().Trim().Split(' '); var n = int.Parse(line[0]); var wmax = int.Parse(line[1]); var vaL = new int[n + 1]; var w = new int[n + 1]; var vmax = readData(vaL, w); var dp = new long[n + 1, n * vmax + 1]; setDP(dp); for (int i = 0; i < n; i++) for (int j = 0; j <= n * vmax; j++) if (j < vaL[i]) dp[i + 1, j] = dp[i, j]; else dp[i + 1, j] = Min(dp[i, j], dp[i, j - vaL[i]] + w[i]); var ans = 0; for (int i = 0; i <= n * vmax; i++) if (dp[n, i] <= wmax) ans = i; Console.WriteLine(ans); } public static int readData(int[] vaL, int[] w) { for (int i = 0; i < vaL.Length - 1; i++) { string[] line = Console.ReadLine().Trim().Split(' '); vaL[i] = int.Parse(line[1]); w[i] = int.Parse(line[0]); } return vaL.Max(); } public static void setDP(long[,] dp) { var imax = dp.GetLength(1); for (int i = 0; i < imax; i++) dp[0, i] = 99999999999; dp[0, 0] = 0; } }
[["-", 0, 7, 8, 1, 0, 11, 12, 214, 205, 199], ["-", 0, 7, 8, 1, 0, 11, 12, 214, 0, 131], ["-", 0, 7, 8, 1, 0, 11, 12, 214, 141, 22], ["+", 8, 196, 0, 7, 8, 1, 0, 11, 12, 203]]
8
417
4
using System; using System.Collections.Generic; using System.IO; using System.Linq; using static System.Math; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; using Library; namespace Program { public static class DPF { static bool SAIKI = false; static public int numberOfRandomCases = 0; static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker) {} static public void Solve() { var s = NS; var t = NS; var dp = new long[s.Length + 1, t.Length + 1]; for (var i = 1; i <= s.Length; i++) { for (var j = 1; j <= t.Length; j++) { dp[i, j] = Max(dp[i - 1, j], dp[i, j - 1]); if (s[i - 1] == t[j - 1]) { Chmax(ref dp[i, j], dp[i - 1, j - 1] + 1); } } } var tidx = t.Length; var ans = new List<char>(); for (var i = s.Length; i > 0; i--) { if (dp[i, tidx] != dp[i - 1, tidx]) { ans.Add(s[i - 1]); while (dp[i, tidx] == dp[i, tidx - 1]) --tidx; } } Console.WriteLine(new string(ans.ToArray().Reverse().ToArray())); } class Printer : StreamWriter { public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } } public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; } public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; } } static LIB_FastIO fastio = new LIB_FastIODebug(); static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); } static long NN => fastio.Long(); static double ND => fastio.Double(); static string NS => fastio.Scan(); static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray(); static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray(); static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray(); static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred); static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n); static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c); static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift); static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e); static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector); static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e); static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector); static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase); static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } } static IEnumerator<uint> _xsi = _xsc(); static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } } static bool Chmin(ref long x, long y) { if (x <= y) return false; x = y; return true; } static bool Chmax(ref long x, long y) { if (x >= y) return false; x = y; return true; } } } namespace Library { class LIB_FastIO { public LIB_FastIO() { str = Console.OpenStandardInput(); } readonly Stream str; readonly byte[] buf = new byte[1024]; int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } byte read() { if (isEof) throw new EndOfStreamException(); if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } char Char() { byte b = 0; do b = read(); while (b < 33 || 126 < b); return (char)b; } virtual public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } virtual public long Long() { long ret = 0; byte b = 0; var ng = false; do b = read(); while (b != '-' && (b < '0' || '9' < b)); if (b == '-') { ng = true; b = read(); } for (; true; b = read()) { if (b < '0' || '9' < b) return ng ? -ret : ret; else ret = ret * 10 + b - '0'; } } virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); } } class LIB_FastIODebug : LIB_FastIO { Queue<string> param = new Queue<string>(); string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); } public LIB_FastIODebug() {} public override string Scan() => NextString(); public override long Long() => long.Parse(NextString()); public override double Double() => double.Parse(NextString()); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using static System.Math; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; using Library; namespace Program { public static class DPF { static bool SAIKI = false; static public int numberOfRandomCases = 0; static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker) {} static public void Solve() { var s = NS; var t = NS; var dp = new long[s.Length + 1, t.Length + 1]; for (var i = 1; i <= s.Length; i++) { for (var j = 1; j <= t.Length; j++) { dp[i, j] = Max(dp[i - 1, j], dp[i, j - 1]); if (s[i - 1] == t[j - 1]) { Chmax(ref dp[i, j], dp[i - 1, j - 1] + 1); } } } var tidx = t.Length; var ans = new List<char>(); for (var i = s.Length; i > 0; i--) { if (dp[i, tidx] != dp[i - 1, tidx]) { ans.Add(s[i - 1]); while (dp[i, tidx] == dp[i, tidx - 1]) --tidx; --tidx; } } Console.WriteLine(new string(ans.ToArray().Reverse().ToArray())); } class Printer : StreamWriter { public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } } public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; } public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; } } static LIB_FastIO fastio = new LIB_FastIODebug(); static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); } static long NN => fastio.Long(); static double ND => fastio.Double(); static string NS => fastio.Scan(); static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray(); static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray(); static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray(); static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred); static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n); static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c); static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift); static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e); static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector); static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e); static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector); static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase); static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase); static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } } static IEnumerator<uint> _xsi = _xsc(); static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } } static bool Chmin(ref long x, long y) { if (x <= y) return false; x = y; return true; } static bool Chmax(ref long x, long y) { if (x >= y) return false; x = y; return true; } } } namespace Library { class LIB_FastIO { public LIB_FastIO() { str = Console.OpenStandardInput(); } readonly Stream str; readonly byte[] buf = new byte[1024]; int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } byte read() { if (isEof) throw new EndOfStreamException(); if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } char Char() { byte b = 0; do b = read(); while (b < 33 || 126 < b); return (char)b; } virtual public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } virtual public long Long() { long ret = 0; byte b = 0; var ng = false; do b = read(); while (b != '-' && (b < '0' || '9' < b)); if (b == '-') { ng = true; b = read(); } for (; true; b = read()) { if (b < '0' || '9' < b) return ng ? -ret : ret; else ret = ret * 10 + b - '0'; } } virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); } } class LIB_FastIODebug : LIB_FastIO { Queue<string> param = new Queue<string>(); string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); } public LIB_FastIODebug() {} public override string Scan() => NextString(); public override long Long() => long.Parse(NextString()); public override double Double() => double.Parse(NextString()); } }
[["+", 0, 57, 64, 196, 0, 1, 0, 241, 0, 68], ["+", 0, 57, 64, 196, 0, 1, 0, 241, 0, 22], ["+", 8, 196, 0, 57, 64, 196, 0, 1, 0, 35]]
8
1,708
3
using System; class Program { static void Main(string[] args) { string s = Console.ReadLine(); string t = Console.ReadLine(); int len_s = s.Length; int len_t = t.Length; // dpテーブルを用意する var dp = new int[len_s, len_t]; if (s[0] == t[0]) { dp[0, 0] = 1; } else { dp[0, 0] = 0; } //初期化できるところは初期化する for (int i = 1; i < len_s; i++) { if (s[i] == t[0]) { dp[i, 0] = 1; } else { dp[i, 0] = Math.Max(dp[i - 1, 0], dp[i, 0]); } } for (int j = 1; j < len_t; j++) { if (t[j] == s[0]) { dp[0, j] = 1; } else { dp[0, j] = Math.Max(dp[0, j - 1], dp[0, j]); } } // dp開始 for (int i = 1; i < len_s; i++) { for (int j = 1; j < len_t; j++) { int value = 0; if (s[i] == t[j]) { value = dp[i - 1, j - 1] + 1; } int value2 = dp[i - 1, j]; int value3 = dp[i, j - 1]; value = Math.Max(value, Math.Max(value2, value3)); dp[i, j] = value; } } // dpの復元 string ans = ""; int ind_i = len_s - 1; int ind_j = len_t - 1; while (true) { if (ind_i >= 1 && ind_j >= 1) { if (dp[ind_i, ind_j] == dp[ind_i, ind_j - 1]) { ind_j--; } else if (dp[ind_i, ind_j] == dp[ind_i - 1, ind_j]) { ind_i--; } else { ans = s[ind_i] + ans; ind_i--; ind_j--; } } //終了条件 if (ind_i == 0 && ind_j == 0) { if (dp[ind_i, ind_j] == 1) { ans = s[0] + ans; } break; } if (ind_j == 0) { if (dp[ind_i, 0] == 1 && dp[ind_i - 1, 0] == 0) { ans = t[0] + ans; break; } else { ind_i--; } } if (ind_i == 0) { if (dp[0, ind_j] == 1 && dp[0, ind_j - 1] == 0) { ans = s[0] + ans; break; } else { ind_j--; } } } Console.WriteLine(ans); } }
using System; class Program { static void Main(string[] args) { string s = Console.ReadLine(); string t = Console.ReadLine(); int len_s = s.Length; int len_t = t.Length; // dpテーブルを用意する var dp = new int[len_s, len_t]; if (s[0] == t[0]) { dp[0, 0] = 1; } else { dp[0, 0] = 0; } //初期化できるところは初期化する for (int i = 1; i < len_s; i++) { if (s[i] == t[0]) { dp[i, 0] = 1; } else { dp[i, 0] = Math.Max(dp[i - 1, 0], dp[i, 0]); } } for (int j = 1; j < len_t; j++) { if (t[j] == s[0]) { dp[0, j] = 1; } else { dp[0, j] = Math.Max(dp[0, j - 1], dp[0, j]); } } // dp開始 for (int i = 1; i < len_s; i++) { for (int j = 1; j < len_t; j++) { int value = 0; if (s[i] == t[j]) { value = dp[i - 1, j - 1] + 1; } int value2 = dp[i - 1, j]; int value3 = dp[i, j - 1]; value = Math.Max(value, Math.Max(value2, value3)); dp[i, j] = value; } } // dpの復元 string ans = ""; int ind_i = len_s - 1; int ind_j = len_t - 1; while (true) { if (ind_i >= 1 && ind_j >= 1) { if (dp[ind_i, ind_j] == dp[ind_i, ind_j - 1]) { ind_j--; } else if (dp[ind_i, ind_j] == dp[ind_i - 1, ind_j]) { ind_i--; } else { ans = s[ind_i] + ans; ind_i--; ind_j--; } } //終了条件 if (ind_i == 0 && ind_j == 0) { if (dp[ind_i, ind_j] == 1) { ans = s[0] + ans; } break; } else if (ind_j == 0) { if (dp[ind_i, ind_j] == 1 && dp[ind_i - 1, ind_j] == 0) { ans = t[0] + ans; break; } else { ind_i--; } } else if (ind_i == 0) { if (dp[ind_i, ind_j] == 1 && dp[ind_i, ind_j - 1] == 0) { ans = s[0] + ans; break; } else { ind_j--; } } } Console.WriteLine(ans); } }
[["+", 8, 196, 0, 52, 8, 196, 0, 57, 0, 95], ["-", 31, 16, 31, 204, 206, 207, 0, 28, 0, 203], ["+", 31, 16, 31, 204, 206, 207, 0, 28, 0, 22], ["-", 12, 16, 31, 204, 206, 207, 0, 28, 0, 203], ["+", 12, 16, 31, 204, 206, 207, 0, 28, 0, 22], ["+", 0, 52, 8, 196, 0, 57, 75, 57, 0, 95]]
8
602
10
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using static Ha2ne2Util.Cin; using static Ha2ne2Util.Util; using static System.Console; using static System.Math; using System.Collections; namespace ABC153 { class Program { static void Main(string[] args) { START: // A(); 20m // B(); 7m // C(); 42m // D(); 70m // E(); 70m -> 13m -> 5m // F(); 127m -> 27m -> F2(); #if DEBUG goto START; #endif } private static void F2() { string s = ReadString(); string t = ReadString(); int n = s.Length; int m = t.Length; long[,] dp = new long[n + 1, m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i - 1] == t[i - 1]) { dp[i, j] = dp[i - 1, j - 1] + 1; } else { dp[i, j] = Max(dp[i, j - 1], dp[i - 1, j]); } } } int x = n; int y = m; StringBuilder sb = new StringBuilder(); while (0 < x && 0 < y) { if (dp[x, y] == dp[x - 1, y]) { x--; } else if (dp[x, y] == dp[x, y - 1]) { y--; } else { x--; y--; sb.Append(s[x]); } } string ans = string.Concat(sb.ToString().Reverse()); WriteLine(ans); } private static void F() { string s = ReadString(); string t = ReadString(); int n = s.Length; int m = t.Length; long[,] dp = new long[n + 1, m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i - 1] == t[j - 1]) { dp[i, j] = dp[i - 1, j - 1] + 1; } else { dp[i, j] = Max(dp[i, j - 1], dp[i - 1, j]); } } } StringBuilder sb = new StringBuilder(); int x = n; int y = m; while (0 < x && 0 < y) { if (dp[x, y] == dp[x - 1, y]) x--; else if (dp[x, y] == dp[x, y - 1]) y--; else { x--; y--; sb.Append(s[x]); } } string ans = string.Concat(sb.ToString().Reverse()); WriteLine(ans); } private static void E() { long N = ReadLong(); long W = ReadLong(); long[] ws, vs; ReadArrays(out ws, out vs, N); long maxValue = 100000; long[,] dp = new long[N + 1, maxValue + 1]; FillArray(dp, INF); dp[0, 0] = 0; for (int i = 0; i < N; i++) { for (int j = 0; j <= maxValue; j++) { if (j - vs[i] >= 0) { dp[i + 1, j] = Min(dp[i, j], dp[i, j - vs[i]] + ws[i]); } else { dp[i + 1, j] = dp[i, j]; } } } long ans = 0; for (int i = 0; i <= maxValue; i++) { if (dp[N, i] <= W) ans = i; } WriteLine(ans); } class Jewel { public long w { get; set; } public long v { get; set; } } private static void D() { long N = ReadLong(); long W = ReadLong(); Jewel[] jewels = new Jewel[N]; for (int i = 0; i < N; i++) { var j = new Jewel(); j.w = ReadLong(); j.v = ReadLong(); jewels[i] = j; } long[,] dp = new long[N + 1, W + 1]; for (int i = 0; i < N; i++) { for (int w = 0; w <= W; w++) { if (w < jewels[i].w) { dp[i + 1, w] = dp[i, w]; } else { dp[i + 1, w] = Max(dp[i, w], dp[i, w - jewels[i].w] + jewels[i].v); } } } WriteLine(dp[N, W]); } private static void C() { long N = ReadLong(); long[] A = new long[N]; long[] B = new long[N]; long[] C = new long[N]; for (int i = 0; i < N; i++) { A[i] = ReadLong(); B[i] = ReadLong(); C[i] = ReadLong(); } long[,] dp = new long[N, 3]; dp[0, 0] = A[0]; dp[0, 1] = B[0]; dp[0, 2] = C[0]; for (int i = 0; i < N - 1; i++) { int ni = i + 1; // Aからの遷移 dp[ni, 1] = Max(dp[ni, 1], dp[i, 0] + B[ni]); dp[ni, 2] = Max(dp[ni, 2], dp[i, 0] + C[ni]); // Bからの遷移 dp[ni, 0] = Max(dp[ni, 0], dp[i, 1] + A[ni]); dp[ni, 2] = Max(dp[ni, 2], dp[i, 1] + C[ni]); // Cからの遷移 dp[ni, 0] = Max(dp[ni, 0], dp[i, 2] + A[ni]); dp[ni, 1] = Max(dp[ni, 1], dp[i, 2] + B[ni]); } long ans = Max(Max(dp[N - 1, 0], dp[N - 1, 1]), dp[N - 1, 2]); WriteLine(ans); } private static void B() { long N = ReadLong(); long K = ReadLong(); long[] H = ReadLongArray(); long[] dp = new long[N]; for (int i = 0; i < N; i++) dp[i] = long.MaxValue; dp[0] = 0; for (int i = 0; i < N; i++) { if (dp[i] == long.MaxValue) continue; for (int j = 1; j <= K; j++) { if (i + j < N) dp[i + j] = Min(dp[i + j], dp[i] + Abs(H[i] - H[i + j])); } } WriteLine(dp[N - 1]); } private static void A() { long N = ReadLong(); long[] H = ReadLongArray(); long[] dp = new long[N]; for (int i = 0; i < N; i++) dp[i] = long.MaxValue; dp[0] = 0; for (int i = 0; i < N; i++) { if (dp[i] == long.MaxValue) continue; if (i + 1 < N) dp[i + 1] = Min(dp[i + 1], dp[i] + Abs(H[i] - H[i + 1])); if (i + 2 < N) dp[i + 2] = Min(dp[i + 2], dp[i] + Abs(H[i] - H[i + 2])); } WriteLine(dp[N - 1]); } } } namespace Ha2ne2Util { public static class Cin { private static string[] Tokens { get; set; } private static int Pointer { get; set; } public static string Next() { if (Tokens == null || Tokens.Length <= Pointer) { Tokens = Console.ReadLine().Split(' '); Pointer = 0; } return Tokens[Pointer++]; } public static int ReadInt() { return int.Parse(Next()); } public static long ReadLong() { return long.Parse(Next()); } public static int[] ReadIntArray() { Tokens = null; return Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); } public static long[] ReadLongArray() { Tokens = null; return Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse); } public static void ReadArrays(out long[] a, out long[] b, long N) { a = new long[N]; b = new long[N]; for (int i = 0; i < N; i++) { a[i] = ReadLong(); b[i] = ReadLong(); } } public static void ReadArrays(out long[] a, out long[] b, out long[] c, long N) { a = new long[N]; b = new long[N]; c = new long[N]; for (int i = 0; i < N; i++) { a[i] = ReadLong(); b[i] = ReadLong(); c[i] = ReadLong(); } } public static int[][] ReadIntTable(int n) { Tokens = null; int[][] ret = new int [n][]; for (int i = 0; i < n; i++) { ret[i] = ReadIntArray(); } return ret; } public static long[][] ReadLongTable(long n) { Tokens = null; long[][] ret = new long [n][]; for (long i = 0; i < n; i++) { ret[i] = ReadLongArray(); } return ret; } public static string ReadString() { return Next(); } /// <summary> /// "00101001010"という様な入力をintの配列にして返す /// </summary> /// <returns></returns> public static int[] ReadIntArrayFromBinaryString() { Tokens = null; return Array.ConvertAll(Console.ReadLine().ToArray(), c => int.Parse(c.ToString())); } /// <summary> /// "00101001010"という様な入力をboolの配列にして返す /// </summary> /// <returns></returns> public static bool[] ReadBoolArrayFromBinaryString() { Tokens = null; return Console.ReadLine().Select(c => c == '1').ToArray(); } } /// <summary> /// ユーティリティー /// </summary> public static class Util { // 10^17 public static readonly long INF = (long)1e17; public static IEnumerable<int> Range(int end) { for (int i = 0; i < end; i++) { yield return i; } } public static IEnumerable<int> Range(int from, int end) { for (int i = from; i < end; i++) { yield return i; } } public static IEnumerable<int> Range(int from, int end, int step) { for (int i = from; i < end; i += step) { yield return i; } } /// <summary> /// ソートをして結果を返します。 /// 破壊的関数です。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] Sort<T>(T[] array) { Array.Sort<T>(array); return array; } /// <summary> /// 降順ソートをして結果を返します。 /// 破壊的関数です。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] SortDecend<T>(T[] array) { Array.Sort<T>(array); Array.Reverse(array); return array; } /// <summary> /// Rubyにあるようなやつ /// ex) 5.Times(i => Console.WriteLine(i)); /// </summary> /// <param name="times"></param> /// <param name="action"></param> public static void Times(this int times, Action<int> action) { for (int i = 0; i < times; i++) { action(i); } } /// <summary> /// 引数aと引数bの値を入れ替えます /// </summary> /// <typeparam name="T"></typeparam> /// <param name="a"></param> /// <param name="b"></param> public static void Swap<T>(ref T a, ref T b) { T _a = a; a = b; b = _a; } /// <summary> /// Console.WriteLineの自動フラッシュをしないようにする /// </summary> public static void DontAutoFlush() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); } public static void Flush() { Console.Out.Flush(); } /// <summary> /// 先頭と末尾に要素を増やした新しい配列を返します。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] AddHeadAndTail<T>(T[] array) { int len = array.Length; T[] res = new T[len + 2]; Array.Copy(array, 0, res, 1, len); return res; } /// <summary> /// 昇順ソート済みの配列を2分探索します。 /// 要素が見つからなかった場合はnより大きい数値の中で最小の数値のインデックスを返す。 /// </summary> /// <param name="array"></param> /// <param name="n"></param> /// <returns></returns> public static int BinarySearch(long[] array, long n) { int left = 0; int right = array.Length - 1; while (left <= right) { int mid = (right - left) / 2 + left; if (array[mid] == n) { return mid; } else if (n < array[mid]) { right = mid - 1; } else { left = mid + 1; } } return left; } public static int GCD(int a, int b) { return (b == 0) ? a : GCD(b, a % b); } public static int[] GetDivisor(int n) { double sqrt = Math.Sqrt(n); List<int> divisor = new List<int>(); for (int i = 1; i <= sqrt; i++) { if (n % i == 0) { divisor.Add(i); int tmp = n / i; if (tmp != i) { divisor.Add(tmp); } } } return Sort(divisor.ToArray()); } public static int[] LongToBinaryArray(long n) { List<int> lst = new List<int>(); while (n > 0) { int amari = (int)(n % 2); lst.Add(amari); n /= 2; } return lst.ToArray(); } public static long BinaryArrayToLong(int[] binaryArray) { long result = 0; long b = 1; int len = binaryArray.Length; for (int i = 0; i < len; i++) { result += binaryArray[i] * b; b *= 2; } return result; } public static void Deconstruct<T>(this T[] items, out T t0) { t0 = items.Length > 0 ? items[0] : default(T); } public static void Deconstruct<T>(this T[] items, out T t0, out T t1) { if (items.Length < 2) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; } public static void Deconstruct<T>(this T[] items, out T t0, out T t1, out T t2) { if (items.Length < 3) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; t2 = items[2]; } public static void Deconstruct<T>(this T[] items, out T t0, out T t1, out T t2, out T t3) { if (items.Length < 4) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; t2 = items[2]; t3 = items[3]; } public static void ArrayInitialize<T>(T[,] array, T value) { int len0 = array.GetLength(0); int len1 = array.GetLength(1); for (int i = 0; i < len0; i++) { for (int j = 0; j < len1; j++) { array[i, j] = value; } } } public static void ChMax(ref long a, long b) { if (a < b) a = b; } public static void ChMin(ref long a, long b) { if (a > b) a = b; } public readonly static int MOD = 1000000007; public static void ModAdd(ref long a, long b) { a += b; if (a >= MOD) a %= MOD; } public static T MinBy<T>(this IEnumerable<T> source, Func<T, long> conv) { T min = source.First(); long minValue = conv(min); foreach (T x in source.Skip(1)) { long n = conv(x); if (n < minValue) { min = x; } } return min; } public static T MaxBy<T>(this IEnumerable<T> source, Func<T, long> conv) { T min = source.First(); long maxValue = conv(min); foreach (T x in source.Skip(1)) { long n = conv(x); if (maxValue < n) { min = x; } } return min; } public static void FillArray<T>(T[] array, T value) { int max = array.Length; for (int i = 0; i < max; i++) { array[i] = value; } } public static void FillArray<T>(T[,] array, T value) { int max0 = array.GetLength(0); int max1 = array.GetLength(1); for (int i = 0; i < max0; i++) { for (int j = 0; j < max1; j++) { array[i, j] = value; } } } } /// <summary> /// HashSetにTupleを入れた時の、等値性判定方法の指定に使います。 /// HashSetのコンストラクタに渡して使います。 /// EqualsとGetHashCodeを提供します。 /// </summary> /// <typeparam name="T"></typeparam> public class EqualityComparer<T> : IEqualityComparer<T> { private Func<T, T, bool> _equals; private Func<T, int> _getHashCode; public EqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashCode) { _equals = equals; _getHashCode = getHashCode; } public bool Equals(T x, T y) { return _equals(x, y); } public int GetHashCode(T obj) { return _getHashCode(obj); } } /// <summary> /// UnionFindTree /// </summary> public class UnionFindTree { public int[] Node; public UnionFindTree(int N) { Node = new int[N]; for (int i = 0; i < N; i++) { Node[i] = -1; } } public bool IsSameGroup(int x, int y) { return GetRoot(x) == GetRoot(y); } public bool Merge(int x, int y) { int xr = GetRoot(x); int yr = GetRoot(y); if (xr == yr) return false; // xが、大きなグループを示すようにSwapする(値が小さい方が大きなグループ) if (Node[xr] > Node[yr]) Swap(ref xr, ref yr); // グループの数を合算する Node[xr] += Node[yr]; // 根を張り替える Node[yr] = xr; return true; } public int Size(int x) { return -Node[GetRoot(x)]; } public int GetRoot(int n) { if (Node[n] < 0) { return n; } else { // 根を張りなおす。 Node[n] = GetRoot(Node[n]); return Node[n]; } } } /// <summary> /// PriorityQueue /// </summary> /// <typeparam name="T"></typeparam> public class PriorityQueue<T> { private Comparison<T> _comparison = null; private int _type = 0; private T[] _heap; private int _sz = 0; private int _count = 0; /// <summary> /// Priority queue /// </summary> /// <param name="maxSize">max size</param> /// <param name="type">0: asc, 1:desc</param> public PriorityQueue(int maxSize, int type = 0) { _heap = new T[maxSize]; _type = type; } public PriorityQueue(int maxSize, Comparison<T> comparison) { _heap = new T[maxSize]; _comparison = comparison; } private int Compare(T x, T y) { return _comparison(x, y); // if (_comparison != null) return _comparison(x, y); // return _type == 0 ? x.CompareTo(y) : y.CompareTo(x); } public void Push(T x) { _count++; // node number var i = _sz++; while (i > 0) { // parent node number var p = (i - 1) / 2; if (Compare(_heap[p], x) <= 0) break; _heap[i] = _heap[p]; i = p; } _heap[i] = x; } public T Pop() { _count--; T ret = _heap[0]; T x = _heap[--_sz]; int i = 0; while (i * 2 + 1 < _sz) { // children int a = i * 2 + 1; int b = i * 2 + 2; if (b < _sz && Compare(_heap[b], _heap[a]) < 0) a = b; if (Compare(_heap[a], x) >= 0) break; _heap[i] = _heap[a]; i = a; } _heap[i] = x; return ret; } public int Count() { return _count; } public T Peek() { return _heap[0]; } public bool Contains(T x) { for (int i = 0; i < _sz; i++) if (x.Equals(_heap[i])) return true; return false; } public void Clear() { while (this.Count() > 0) this.Pop(); } public IEnumerator<T> GetEnumerator() { var ret = new List<T>(); while (this.Count() > 0) { ret.Add(this.Pop()); } foreach (var r in ret) { this.Push(r); yield return r; } } public T[] ToArray() { T[] array = new T[_sz]; int i = 0; foreach (var r in this) { array[i++] = r; } return array; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using static Ha2ne2Util.Cin; using static Ha2ne2Util.Util; using static System.Console; using static System.Math; using System.Collections; namespace ABC153 { class Program { static void Main(string[] args) { START: // A(); 20m // B(); 7m // C(); 42m // D(); 70m // E(); 70m -> 13m -> 5m // F(); 127m -> 27m -> F2(); #if DEBUG goto START; #endif } private static void F2() { string s = ReadString(); string t = ReadString(); int n = s.Length; int m = t.Length; long[,] dp = new long[n + 1, m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i - 1] == t[j - 1]) { dp[i, j] = dp[i - 1, j - 1] + 1; } else { dp[i, j] = Max(dp[i, j - 1], dp[i - 1, j]); } } } int x = n; int y = m; StringBuilder sb = new StringBuilder(); while (0 < x && 0 < y) { if (dp[x, y] == dp[x - 1, y]) { x--; } else if (dp[x, y] == dp[x, y - 1]) { y--; } else { x--; y--; sb.Append(s[x]); } } string ans = string.Concat(sb.ToString().Reverse()); WriteLine(ans); } private static void F() { string s = ReadString(); string t = ReadString(); int n = s.Length; int m = t.Length; long[,] dp = new long[n + 1, m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i - 1] == t[j - 1]) { dp[i, j] = dp[i - 1, j - 1] + 1; } else { dp[i, j] = Max(dp[i, j - 1], dp[i - 1, j]); } } } StringBuilder sb = new StringBuilder(); int x = n; int y = m; while (0 < x && 0 < y) { if (dp[x, y] == dp[x - 1, y]) x--; else if (dp[x, y] == dp[x, y - 1]) y--; else { x--; y--; sb.Append(s[x]); } } string ans = string.Concat(sb.ToString().Reverse()); WriteLine(ans); } private static void E() { long N = ReadLong(); long W = ReadLong(); long[] ws, vs; ReadArrays(out ws, out vs, N); long maxValue = 100000; long[,] dp = new long[N + 1, maxValue + 1]; FillArray(dp, INF); dp[0, 0] = 0; for (int i = 0; i < N; i++) { for (int j = 0; j <= maxValue; j++) { if (j - vs[i] >= 0) { dp[i + 1, j] = Min(dp[i, j], dp[i, j - vs[i]] + ws[i]); } else { dp[i + 1, j] = dp[i, j]; } } } long ans = 0; for (int i = 0; i <= maxValue; i++) { if (dp[N, i] <= W) ans = i; } WriteLine(ans); } class Jewel { public long w { get; set; } public long v { get; set; } } private static void D() { long N = ReadLong(); long W = ReadLong(); Jewel[] jewels = new Jewel[N]; for (int i = 0; i < N; i++) { var j = new Jewel(); j.w = ReadLong(); j.v = ReadLong(); jewels[i] = j; } long[,] dp = new long[N + 1, W + 1]; for (int i = 0; i < N; i++) { for (int w = 0; w <= W; w++) { if (w < jewels[i].w) { dp[i + 1, w] = dp[i, w]; } else { dp[i + 1, w] = Max(dp[i, w], dp[i, w - jewels[i].w] + jewels[i].v); } } } WriteLine(dp[N, W]); } private static void C() { long N = ReadLong(); long[] A = new long[N]; long[] B = new long[N]; long[] C = new long[N]; for (int i = 0; i < N; i++) { A[i] = ReadLong(); B[i] = ReadLong(); C[i] = ReadLong(); } long[,] dp = new long[N, 3]; dp[0, 0] = A[0]; dp[0, 1] = B[0]; dp[0, 2] = C[0]; for (int i = 0; i < N - 1; i++) { int ni = i + 1; // Aからの遷移 dp[ni, 1] = Max(dp[ni, 1], dp[i, 0] + B[ni]); dp[ni, 2] = Max(dp[ni, 2], dp[i, 0] + C[ni]); // Bからの遷移 dp[ni, 0] = Max(dp[ni, 0], dp[i, 1] + A[ni]); dp[ni, 2] = Max(dp[ni, 2], dp[i, 1] + C[ni]); // Cからの遷移 dp[ni, 0] = Max(dp[ni, 0], dp[i, 2] + A[ni]); dp[ni, 1] = Max(dp[ni, 1], dp[i, 2] + B[ni]); } long ans = Max(Max(dp[N - 1, 0], dp[N - 1, 1]), dp[N - 1, 2]); WriteLine(ans); } private static void B() { long N = ReadLong(); long K = ReadLong(); long[] H = ReadLongArray(); long[] dp = new long[N]; for (int i = 0; i < N; i++) dp[i] = long.MaxValue; dp[0] = 0; for (int i = 0; i < N; i++) { if (dp[i] == long.MaxValue) continue; for (int j = 1; j <= K; j++) { if (i + j < N) dp[i + j] = Min(dp[i + j], dp[i] + Abs(H[i] - H[i + j])); } } WriteLine(dp[N - 1]); } private static void A() { long N = ReadLong(); long[] H = ReadLongArray(); long[] dp = new long[N]; for (int i = 0; i < N; i++) dp[i] = long.MaxValue; dp[0] = 0; for (int i = 0; i < N; i++) { if (dp[i] == long.MaxValue) continue; if (i + 1 < N) dp[i + 1] = Min(dp[i + 1], dp[i] + Abs(H[i] - H[i + 1])); if (i + 2 < N) dp[i + 2] = Min(dp[i + 2], dp[i] + Abs(H[i] - H[i + 2])); } WriteLine(dp[N - 1]); } } } namespace Ha2ne2Util { public static class Cin { private static string[] Tokens { get; set; } private static int Pointer { get; set; } public static string Next() { if (Tokens == null || Tokens.Length <= Pointer) { Tokens = Console.ReadLine().Split(' '); Pointer = 0; } return Tokens[Pointer++]; } public static int ReadInt() { return int.Parse(Next()); } public static long ReadLong() { return long.Parse(Next()); } public static int[] ReadIntArray() { Tokens = null; return Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); } public static long[] ReadLongArray() { Tokens = null; return Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse); } public static void ReadArrays(out long[] a, out long[] b, long N) { a = new long[N]; b = new long[N]; for (int i = 0; i < N; i++) { a[i] = ReadLong(); b[i] = ReadLong(); } } public static void ReadArrays(out long[] a, out long[] b, out long[] c, long N) { a = new long[N]; b = new long[N]; c = new long[N]; for (int i = 0; i < N; i++) { a[i] = ReadLong(); b[i] = ReadLong(); c[i] = ReadLong(); } } public static int[][] ReadIntTable(int n) { Tokens = null; int[][] ret = new int [n][]; for (int i = 0; i < n; i++) { ret[i] = ReadIntArray(); } return ret; } public static long[][] ReadLongTable(long n) { Tokens = null; long[][] ret = new long [n][]; for (long i = 0; i < n; i++) { ret[i] = ReadLongArray(); } return ret; } public static string ReadString() { return Next(); } /// <summary> /// "00101001010"という様な入力をintの配列にして返す /// </summary> /// <returns></returns> public static int[] ReadIntArrayFromBinaryString() { Tokens = null; return Array.ConvertAll(Console.ReadLine().ToArray(), c => int.Parse(c.ToString())); } /// <summary> /// "00101001010"という様な入力をboolの配列にして返す /// </summary> /// <returns></returns> public static bool[] ReadBoolArrayFromBinaryString() { Tokens = null; return Console.ReadLine().Select(c => c == '1').ToArray(); } } /// <summary> /// ユーティリティー /// </summary> public static class Util { // 10^17 public static readonly long INF = (long)1e17; public static IEnumerable<int> Range(int end) { for (int i = 0; i < end; i++) { yield return i; } } public static IEnumerable<int> Range(int from, int end) { for (int i = from; i < end; i++) { yield return i; } } public static IEnumerable<int> Range(int from, int end, int step) { for (int i = from; i < end; i += step) { yield return i; } } /// <summary> /// ソートをして結果を返します。 /// 破壊的関数です。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] Sort<T>(T[] array) { Array.Sort<T>(array); return array; } /// <summary> /// 降順ソートをして結果を返します。 /// 破壊的関数です。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] SortDecend<T>(T[] array) { Array.Sort<T>(array); Array.Reverse(array); return array; } /// <summary> /// Rubyにあるようなやつ /// ex) 5.Times(i => Console.WriteLine(i)); /// </summary> /// <param name="times"></param> /// <param name="action"></param> public static void Times(this int times, Action<int> action) { for (int i = 0; i < times; i++) { action(i); } } /// <summary> /// 引数aと引数bの値を入れ替えます /// </summary> /// <typeparam name="T"></typeparam> /// <param name="a"></param> /// <param name="b"></param> public static void Swap<T>(ref T a, ref T b) { T _a = a; a = b; b = _a; } /// <summary> /// Console.WriteLineの自動フラッシュをしないようにする /// </summary> public static void DontAutoFlush() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); } public static void Flush() { Console.Out.Flush(); } /// <summary> /// 先頭と末尾に要素を増やした新しい配列を返します。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] AddHeadAndTail<T>(T[] array) { int len = array.Length; T[] res = new T[len + 2]; Array.Copy(array, 0, res, 1, len); return res; } /// <summary> /// 昇順ソート済みの配列を2分探索します。 /// 要素が見つからなかった場合はnより大きい数値の中で最小の数値のインデックスを返す。 /// </summary> /// <param name="array"></param> /// <param name="n"></param> /// <returns></returns> public static int BinarySearch(long[] array, long n) { int left = 0; int right = array.Length - 1; while (left <= right) { int mid = (right - left) / 2 + left; if (array[mid] == n) { return mid; } else if (n < array[mid]) { right = mid - 1; } else { left = mid + 1; } } return left; } public static int GCD(int a, int b) { return (b == 0) ? a : GCD(b, a % b); } public static int[] GetDivisor(int n) { double sqrt = Math.Sqrt(n); List<int> divisor = new List<int>(); for (int i = 1; i <= sqrt; i++) { if (n % i == 0) { divisor.Add(i); int tmp = n / i; if (tmp != i) { divisor.Add(tmp); } } } return Sort(divisor.ToArray()); } public static int[] LongToBinaryArray(long n) { List<int> lst = new List<int>(); while (n > 0) { int amari = (int)(n % 2); lst.Add(amari); n /= 2; } return lst.ToArray(); } public static long BinaryArrayToLong(int[] binaryArray) { long result = 0; long b = 1; int len = binaryArray.Length; for (int i = 0; i < len; i++) { result += binaryArray[i] * b; b *= 2; } return result; } public static void Deconstruct<T>(this T[] items, out T t0) { t0 = items.Length > 0 ? items[0] : default(T); } public static void Deconstruct<T>(this T[] items, out T t0, out T t1) { if (items.Length < 2) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; } public static void Deconstruct<T>(this T[] items, out T t0, out T t1, out T t2) { if (items.Length < 3) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; t2 = items[2]; } public static void Deconstruct<T>(this T[] items, out T t0, out T t1, out T t2, out T t3) { if (items.Length < 4) throw new ArgumentException(); t0 = items[0]; t1 = items[1]; t2 = items[2]; t3 = items[3]; } public static void ArrayInitialize<T>(T[,] array, T value) { int len0 = array.GetLength(0); int len1 = array.GetLength(1); for (int i = 0; i < len0; i++) { for (int j = 0; j < len1; j++) { array[i, j] = value; } } } public static void ChMax(ref long a, long b) { if (a < b) a = b; } public static void ChMin(ref long a, long b) { if (a > b) a = b; } public readonly static int MOD = 1000000007; public static void ModAdd(ref long a, long b) { a += b; if (a >= MOD) a %= MOD; } public static T MinBy<T>(this IEnumerable<T> source, Func<T, long> conv) { T min = source.First(); long minValue = conv(min); foreach (T x in source.Skip(1)) { long n = conv(x); if (n < minValue) { min = x; } } return min; } public static T MaxBy<T>(this IEnumerable<T> source, Func<T, long> conv) { T min = source.First(); long maxValue = conv(min); foreach (T x in source.Skip(1)) { long n = conv(x); if (maxValue < n) { min = x; } } return min; } public static void FillArray<T>(T[] array, T value) { int max = array.Length; for (int i = 0; i < max; i++) { array[i] = value; } } public static void FillArray<T>(T[,] array, T value) { int max0 = array.GetLength(0); int max1 = array.GetLength(1); for (int i = 0; i < max0; i++) { for (int j = 0; j < max1; j++) { array[i, j] = value; } } } } /// <summary> /// HashSetにTupleを入れた時の、等値性判定方法の指定に使います。 /// HashSetのコンストラクタに渡して使います。 /// EqualsとGetHashCodeを提供します。 /// </summary> /// <typeparam name="T"></typeparam> public class EqualityComparer<T> : IEqualityComparer<T> { private Func<T, T, bool> _equals; private Func<T, int> _getHashCode; public EqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashCode) { _equals = equals; _getHashCode = getHashCode; } public bool Equals(T x, T y) { return _equals(x, y); } public int GetHashCode(T obj) { return _getHashCode(obj); } } /// <summary> /// UnionFindTree /// </summary> public class UnionFindTree { public int[] Node; public UnionFindTree(int N) { Node = new int[N]; for (int i = 0; i < N; i++) { Node[i] = -1; } } public bool IsSameGroup(int x, int y) { return GetRoot(x) == GetRoot(y); } public bool Merge(int x, int y) { int xr = GetRoot(x); int yr = GetRoot(y); if (xr == yr) return false; // xが、大きなグループを示すようにSwapする(値が小さい方が大きなグループ) if (Node[xr] > Node[yr]) Swap(ref xr, ref yr); // グループの数を合算する Node[xr] += Node[yr]; // 根を張り替える Node[yr] = xr; return true; } public int Size(int x) { return -Node[GetRoot(x)]; } public int GetRoot(int n) { if (Node[n] < 0) { return n; } else { // 根を張りなおす。 Node[n] = GetRoot(Node[n]); return Node[n]; } } } /// <summary> /// PriorityQueue /// </summary> /// <typeparam name="T"></typeparam> public class PriorityQueue<T> { private Comparison<T> _comparison = null; private int _type = 0; private T[] _heap; private int _sz = 0; private int _count = 0; /// <summary> /// Priority queue /// </summary> /// <param name="maxSize">max size</param> /// <param name="type">0: asc, 1:desc</param> public PriorityQueue(int maxSize, int type = 0) { _heap = new T[maxSize]; _type = type; } public PriorityQueue(int maxSize, Comparison<T> comparison) { _heap = new T[maxSize]; _comparison = comparison; } private int Compare(T x, T y) { return _comparison(x, y); // if (_comparison != null) return _comparison(x, y); // return _type == 0 ? x.CompareTo(y) : y.CompareTo(x); } public void Push(T x) { _count++; // node number var i = _sz++; while (i > 0) { // parent node number var p = (i - 1) / 2; if (Compare(_heap[p], x) <= 0) break; _heap[i] = _heap[p]; i = p; } _heap[i] = x; } public T Pop() { _count--; T ret = _heap[0]; T x = _heap[--_sz]; int i = 0; while (i * 2 + 1 < _sz) { // children int a = i * 2 + 1; int b = i * 2 + 2; if (b < _sz && Compare(_heap[b], _heap[a]) < 0) a = b; if (Compare(_heap[a], x) >= 0) break; _heap[i] = _heap[a]; i = a; } _heap[i] = x; return ret; } public int Count() { return _count; } public T Peek() { return _heap[0]; } public bool Contains(T x) { for (int i = 0; i < _sz; i++) if (x.Equals(_heap[i])) return true; return false; } public void Clear() { while (this.Count() > 0) this.Pop(); } public IEnumerator<T> GetEnumerator() { var ret = new List<T>(); while (this.Count() > 0) { ret.Add(this.Pop()); } foreach (var r in ret) { this.Push(r); yield return r; } } public T[] ToArray() { T[] array = new T[_sz]; int i = 0; foreach (var r in this) { array[i++] = r; } return array; } } }
[["-", 12, 204, 206, 207, 0, 28, 0, 16, 31, 22], ["+", 12, 204, 206, 207, 0, 28, 0, 16, 31, 22]]
8
4,718
2
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_AtCoder { class Program { static void Main(string[] args) { string S = Console.ReadLine(); string T = Console.ReadLine(); int sn = S.Length; int tn = T.Length; // dp[i, j] := SのsnまでとTのtnまで文字列のLCS int[,] dp = new int[sn + 1, tn + 1]; for (int i = 1; i <= sn; i++) { for (int j = 1; j <= tn; j++) { if (S[i - 1] == T[j - 1]) { dp[i, j] = dp[i - 1, j - 1] + 1; } else { dp[i, j] = Math.Max(dp[i, j - 1], dp[i - 1, j]); } } } //復元 string lcs = ""; int si = sn; int ti = tn; while (si > 0 && tn > 0) { if (S[si - 1] == T[ti - 1]) { lcs = S[si - 1] + lcs; si--; ti--; } else { if (dp[si, ti] == dp[si - 1, ti]) si--; else ti--; } } Console.WriteLine(lcs); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_AtCoder { class Program { static void Main(string[] args) { string S = Console.ReadLine(); string T = Console.ReadLine(); int sn = S.Length; int tn = T.Length; // dp[i, j] := SのsnまでとTのtnまで文字列のLCS int[,] dp = new int[sn + 1, tn + 1]; for (int i = 1; i <= sn; i++) { for (int j = 1; j <= tn; j++) { if (S[i - 1] == T[j - 1]) { dp[i, j] = dp[i - 1, j - 1] + 1; } else { dp[i, j] = Math.Max(dp[i, j - 1], dp[i - 1, j]); } } } //復元 string lcs = ""; int si = sn; int ti = tn; while (si > 0 && ti > 0) { if (S[si - 1] == T[ti - 1]) { lcs = S[si - 1] + lcs; si--; ti--; } else { if (dp[si, ti] == dp[si - 1, ti]) si--; else ti--; } } Console.WriteLine(lcs); } } }
[["-", 8, 196, 0, 52, 15, 16, 12, 16, 31, 22], ["+", 8, 196, 0, 52, 15, 16, 12, 16, 31, 22]]
8
299
2
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace AtCoder { public class Program { static void Main(string[] args) { string s = Console.ReadLine(); string t = Console.ReadLine(); int[,] dp = new int[s.Length + 1, t.Length + 1]; for (int i = 0; i < s.Length; i++) { for (int j = 0; j < t.Length; j++) { if (s[i] == t[j]) { dp[i + 1, j + 1] = Math.Max(dp[i + 1, j + 1], dp[i, j] + 1); } dp[i + 1, j + 1] = Math.Max(dp[i + 1, j + 1], dp[i + 1, j]); dp[i + 1, j + 1] = Math.Max(dp[i + 1, j + 1], dp[i, j + 1]); } } { string ans = ""; int i = s.Length; int j = t.Length; while (i > 0 && j > 0) { if (dp[i - 1, j] == dp[i, j]) { i--; } else if (dp[i - 1, j] == dp[i, j]) { j--; } else { ans = s[i - 1] + ans; i--; j--; } } Console.WriteLine(ans); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace AtCoder { public class Program { static void Main(string[] args) { string s = Console.ReadLine(); string t = Console.ReadLine(); int[,] dp = new int[s.Length + 1, t.Length + 1]; for (int i = 0; i < s.Length; i++) { for (int j = 0; j < t.Length; j++) { if (s[i] == t[j]) { dp[i + 1, j + 1] = Math.Max(dp[i + 1, j + 1], dp[i, j] + 1); } dp[i + 1, j + 1] = Math.Max(dp[i + 1, j + 1], dp[i + 1, j]); dp[i + 1, j + 1] = Math.Max(dp[i + 1, j + 1], dp[i, j + 1]); } } { string ans = ""; int i = s.Length; int j = t.Length; while (i > 0 && j > 0) { if (dp[i - 1, j] == dp[i, j]) { i--; } else if (dp[i, j - 1] == dp[i, j]) { j--; } else { ans = s[i - 1] + ans; i--; j--; } } Console.WriteLine(ans); } } } }
[["-", 31, 204, 206, 207, 0, 28, 0, 16, 17, 33], ["-", 31, 204, 206, 207, 0, 28, 0, 16, 12, 203], ["+", 31, 204, 206, 207, 0, 28, 0, 16, 17, 33], ["+", 31, 204, 206, 207, 0, 28, 0, 16, 12, 203]]
8
353
4
using System; using System.Linq; //リストの使用 using System.Collections.Generic; using System.Text; //テキストの高速出力に必要 class Program { static void Main() { string s = Console.ReadLine(); string t = Console.ReadLine(); int ss = s.Length; int tt = t.Length; long[,] dp = new long[ss + 1, tt + 1]; for (int i = 1; i <= ss; i++) { for (int j = 1; j <= tt; j++) { dp[i, j] = Math.Max(dp[i, j - 1], dp[i - 1, j]); if (s[i - 1] == t[j - 1]) dp[i, j] = Math.Max(dp[i, j], dp[i - 1, j - 1] + 1); } } int memoA = ss; int memoB = tt; char[] answers = new char[dp[ss, tt]]; char[] answerMemos = new char[dp[ss, tt]]; int countMemo = 0; while (true) { if (dp[memoA, memoB] == 0) break; if (dp[memoA - 1, memoB] == dp[memoA, memoB]) memoA--; else if (dp[memoA - 1, memoB] == dp[memoA, memoB]) memoB--; else { answerMemos[countMemo] = s[memoA - 1]; memoA--; memoB--; countMemo++; } } for (int i = 0; i < answerMemos.Length; i++) { answers[i] = answerMemos[answerMemos.Length - 1 - i]; } if (answers.Length > 0) Console.WriteLine(string.Join("", answers)); else Console.WriteLine(); } }
using System; using System.Linq; //リストの使用 using System.Collections.Generic; using System.Text; //テキストの高速出力に必要 class Program { static void Main() { string s = Console.ReadLine(); string t = Console.ReadLine(); int ss = s.Length; int tt = t.Length; long[,] dp = new long[ss + 1, tt + 1]; for (int i = 1; i <= ss; i++) { for (int j = 1; j <= tt; j++) { dp[i, j] = Math.Max(dp[i, j - 1], dp[i - 1, j]); if (s[i - 1] == t[j - 1]) dp[i, j] = Math.Max(dp[i, j], dp[i - 1, j - 1] + 1); } } int memoA = ss; int memoB = tt; char[] answers = new char[dp[ss, tt]]; char[] answerMemos = new char[dp[ss, tt]]; int countMemo = 0; while (true) { if (dp[memoA, memoB] == 0) break; if (dp[memoA - 1, memoB] == dp[memoA, memoB]) memoA--; else if (dp[memoA, memoB - 1] == dp[memoA, memoB]) memoB--; else { answerMemos[countMemo] = s[memoA - 1]; memoA--; memoB--; countMemo++; } } for (int i = 0; i < answerMemos.Length; i++) { answers[i] = answerMemos[answerMemos.Length - 1 - i]; } if (answers.Length > 0) Console.WriteLine(string.Join("", answers)); else Console.WriteLine(); } }
[["-", 31, 204, 206, 207, 0, 28, 0, 16, 17, 33], ["-", 31, 204, 206, 207, 0, 28, 0, 16, 12, 203], ["+", 31, 204, 206, 207, 0, 28, 0, 16, 17, 33], ["+", 31, 204, 206, 207, 0, 28, 0, 16, 12, 203]]
8
390
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using static Input; using static Util; class Program { static int N, M; static Queue<int>[] G; static int[] T; static void INPUT() { N = NextInt(); M = NextInt(); G = new Queue<int>[M]; T = new int[N + 1]; for (int i = 0; i < M; i++) { G[i] = new Queue<int>(); } for (int i = 0; i < M; i++) { var s = NextInt(); var t = NextInt(); G[s].Enqueue(t); T[t]++; } } static void OUT() { var s = new Queue<int>(); var dp = new int[N + 1]; for (int i = 1; i < T.Length; i++) { if (T[i] == 0) s.Enqueue(i); } while (s.Count > 0) { var n = s.Dequeue(); foreach (var nn in G[n]) { T[nn]--; if (T[nn] == 0) s.Enqueue(nn); dp[nn] = dp[n] + 1; } } var max = 0; foreach (var nn in dp) { max = Math.Max(max, nn); } Console.WriteLine(max); } static void Main(string[] args) { #if DEBUG // TESTINPUT(); INPUT(); #else INPUT(); #endif OUT(); } static void TESTINPUT() {} } public class Input { public const long MOD = 1000000007; public const int INF = 1000000007; private static Queue<string> q = new Queue<string>(); private static void Confirm() { if (q.Count == 0) foreach (var s in Console.ReadLine().Split(' ')) q.Enqueue(s); } public static int NextInt() { Confirm(); return int.Parse(q.Dequeue()); } public static long NextLong() { Confirm(); return long.Parse(q.Dequeue()); } public static string NextString() { Confirm(); return q.Dequeue(); } public static double NextDouble() { Confirm(); return double.Parse(q.Dequeue()); } public static int[] LineInt() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); } public static long[] LineLong() { return Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); } public static string[] LineString() { return Console.ReadLine().Split(' ').ToArray(); } public static double[] LineDouble() { return Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); } } class Util {}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using static Input; using static Util; class Program { static int N, M; static Queue<int>[] G; static int[] T; static void INPUT() { N = NextInt(); M = NextInt(); G = new Queue<int>[N + 1]; T = new int[N + 1]; for (int i = 0; i <= N; i++) { G[i] = new Queue<int>(); } for (int i = 0; i < M; i++) { var s = NextInt(); var t = NextInt(); G[s].Enqueue(t); T[t]++; } } static void OUT() { var s = new Queue<int>(); var dp = new int[N + 1]; for (int i = 1; i < T.Length; i++) { if (T[i] == 0) s.Enqueue(i); } while (s.Count > 0) { var n = s.Dequeue(); foreach (var nn in G[n]) { T[nn]--; if (T[nn] == 0) s.Enqueue(nn); dp[nn] = dp[n] + 1; } } var max = 0; foreach (var nn in dp) { max = Math.Max(max, nn); } Console.WriteLine(max); } static void Main(string[] args) { #if DEBUG // TESTINPUT(); INPUT(); #else INPUT(); #endif OUT(); } static void TESTINPUT() {} } public class Input { public const long MOD = 1000000007; public const int INF = 1000000007; private static Queue<string> q = new Queue<string>(); private static void Confirm() { if (q.Count == 0) foreach (var s in Console.ReadLine().Split(' ')) q.Enqueue(s); } public static int NextInt() { Confirm(); return int.Parse(q.Dequeue()); } public static long NextLong() { Confirm(); return long.Parse(q.Dequeue()); } public static string NextString() { Confirm(); return q.Dequeue(); } public static double NextDouble() { Confirm(); return double.Parse(q.Dequeue()); } public static int[] LineInt() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); } public static long[] LineLong() { return Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); } public static string[] LineString() { return Console.ReadLine().Split(' ').ToArray(); } public static double[] LineDouble() { return Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); } } class Util {}
[["-", 0, 11, 12, 227, 39, 224, 225, 226, 0, 22], ["+", 12, 227, 39, 224, 225, 226, 0, 16, 31, 22], ["+", 12, 227, 39, 224, 225, 226, 0, 16, 17, 72], ["+", 12, 227, 39, 224, 225, 226, 0, 16, 12, 203], ["-", 0, 195, 8, 196, 0, 7, 15, 16, 17, 18], ["-", 0, 195, 8, 196, 0, 7, 15, 16, 12, 22], ["+", 0, 195, 8, 196, 0, 7, 15, 16, 17, 19], ["+", 0, 195, 8, 196, 0, 7, 15, 16, 12, 22]]
8
682
8
using System; public static class Solution { private static char[][] s_grid; private static int s_rows; private static int s_columns; private static int[,] s_memo; public static void Main() { int[] rc = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); s_rows = rc[0]; s_columns = rc[1]; s_grid = new char [s_rows][]; s_memo = new int[s_rows, s_columns]; for (int i = 0; i < s_rows; i++) { s_grid[i] = Console.ReadLine().ToCharArray(); for (int j = 0; j < s_columns; j++) s_memo[i, j] = -1; } Console.WriteLine(CountWaysUntilEnd(0, 0)); } // ONLY RIGHT AND DOWN. private static int CountWaysUntilEnd(int fromRow, int fromColumn) { if (fromRow == s_rows - 1 && fromColumn == s_columns - 1) { // already at end. return 1; } if (s_memo[fromRow, fromColumn] != -1) return s_memo[fromRow, fromColumn]; int right = 0; int down = 0; // If I can go down. if (fromRow < s_rows - 1 && s_grid[fromRow + 1][fromColumn] == '.') { down = CountWaysUntilEnd(fromRow + 1, fromColumn); } // If I can go right. if (fromColumn < s_columns - 1 && s_grid[fromRow][fromColumn + 1] == '.') { right = CountWaysUntilEnd(fromRow, fromColumn + 1); } return s_memo[fromRow, fromColumn] = (down + right); } }
using System; public static class Solution { private static char[][] s_grid; private static int s_rows; private static int s_columns; private static int[,] s_memo; public static void Main() { int[] rc = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); s_rows = rc[0]; s_columns = rc[1]; s_grid = new char [s_rows][]; s_memo = new int[s_rows, s_columns]; for (int i = 0; i < s_rows; i++) { s_grid[i] = Console.ReadLine().ToCharArray(); for (int j = 0; j < s_columns; j++) s_memo[i, j] = -1; } Console.WriteLine(CountWaysUntilEnd(0, 0)); } // ONLY RIGHT AND DOWN. private static int CountWaysUntilEnd(int fromRow, int fromColumn) { if (fromRow == s_rows - 1 && fromColumn == s_columns - 1) { // already at end. return 1; } if (s_memo[fromRow, fromColumn] != -1) return s_memo[fromRow, fromColumn]; int right = 0; int down = 0; // If I can go down. if (fromRow < s_rows - 1 && s_grid[fromRow + 1][fromColumn] == '.') { down = CountWaysUntilEnd(fromRow + 1, fromColumn); } // If I can go right. if (fromColumn < s_columns - 1 && s_grid[fromRow][fromColumn + 1] == '.') { right = CountWaysUntilEnd(fromRow, fromColumn + 1); } return s_memo[fromRow, fromColumn] = ((down + right) % 1000000007); } }
[["+", 0, 11, 12, 23, 0, 16, 31, 23, 0, 24], ["+", 0, 11, 12, 23, 0, 16, 31, 23, 0, 25], ["+", 0, 37, 0, 11, 12, 23, 0, 16, 17, 109], ["+", 0, 37, 0, 11, 12, 23, 0, 16, 12, 203]]
8
322
4