public static void MainTest(string[] args) { Console.WriteLine($"Running {nameof(PacketProcessing)}"); int size = StdIn.ReadInt(); Buffer buffer = new Buffer(size); var requests = ReadQueries(); foreach (var response in ProcessRequests(buffer, requests)) { Console.WriteLine(response.Dropped ? -1 : response.StartTime); } IEnumerable <(int TimeOfArrival, int ProcessingTime)> ReadQueries() { int n = StdIn.ReadInt(); for (int i = 0; i < n; i++) { yield return(StdIn.ReadInt(), StdIn.ReadInt()); } } IEnumerable <(bool Dropped, int StartTime)> ProcessRequests(Buffer buffer, IEnumerable <(int TimeOfArrival, int ProcessingTime)> requests) { foreach (var request in requests) { yield return(buffer.Process(request)); } } }
private static void ShortestPath() { string filename = "mediumEWD.txt"; Scanner scanner = new Scanner(new StreamReader(File.OpenRead(filename))); IEdgeWeightedDIgraph G = new EdgeWeightedDigraph(scanner); StdOut.Print("输入一个边:"); int s = StdIn.ReadInt(); IShortestPath sp = new DijkstraSP(G, s); for (int t = 0; t < G.V; t++) { StdOut.Print(s + " to " + t); StdOut.Printf(" ({0}): ", sp.DistTo(t)); if (sp.HasPathTo(t)) { foreach (var e in sp.PathTo(t)) { StdOut.Print(e + " "); } } StdOut.Println(); } DijkstraAllPairsSP allPairsSP = new DijkstraAllPairsSP(G); StdOut.Println(); StdOut.Println(allPairsSP.Dist(1, 28)); //string filename2 = "tinyEWDAG.txt"; //scanner = new Scanner(new StreamReader(File.OpenRead(filename2))); //G = new EdgeWeightedDigraph(scanner); //IShortestPath sp2 = new AcyclicSP(G, s); //for (int t = 0; t < G.V; t++) //{ // StdOut.Print(s + " to " + t); // StdOut.Printf(" ({0}): ", sp2.DistTo(t)); // if (sp2.HasPathTo(t)) // foreach (var e in sp.PathTo(t)) // { // StdOut.Print(e + " "); // } // StdOut.Println(); //} //filename = "tinyEWDnc.txt"; //scanner = new Scanner(new StreamReader(File.OpenRead(filename))); //G = new EdgeWeightedDigraph(scanner); //sp = new BellmanFordSP(G, s); //for (int t = 0; t < G.V; t++) //{ // StdOut.Print(s + " to " + t); // StdOut.Printf(" ({0}): ", sp.DistTo(t)); // if (sp.HasPathTo(t)) // foreach (var e in sp.PathTo(t)) // { // StdOut.Print(e + " "); // } // StdOut.Println(); //} }
private static void DiGraph() { IDiGraph G = new DiGraph.DiGraph(new Scanner(new StreamReader(File.OpenRead("tinyDG.txt")))); Bag <int> sources = new Bag <int>(); StdOut.Println("搜索几个结点:"); int i = StdIn.ReadInt(); while (i-- > 0) { sources.Add(StdIn.ReadInt()); } DirectedDFS reachable = new DirectedDFS(G, sources); for (int v = 0; v < G.V; v++) { if (reachable.Marked(v)) { StdOut.Print(v + " "); } } //string filename = "jobs.txt"; //文件有问题 //string seperator = "/"; //SymbolDiGraph sg = new SymbolDiGraph(filename, seperator); //Topological topological = new Topological(sg.G); //foreach (int v in topological.Order) // StdOut.Println(sg.Name(v)); StdOut.Println(); StdOut.Println("强连通分量的数量"); ISCC scc = new KosarajuSCC(G); StdOut.Println(scc.Count); }
/**/ public static void main(string[] strarr) { string str = strarr[0]; string str2 = strarr[1]; SymbolGraph symbolGraph = new SymbolGraph(str, str2); Graph graph = symbolGraph.G(); while (StdIn.hasNextLine()) { string str3 = StdIn.readLine(); if (symbolGraph.contains(str3)) { int i = symbolGraph.index(str3); Iterator iterator = graph.adj(i).iterator(); while (iterator.hasNext()) { int i2 = ((Integer)iterator.next()).intValue(); StdOut.println(new StringBuilder().append(" ").append(symbolGraph.name(i2)).toString()); } } else { StdOut.println(new StringBuilder().append("input not contain '").append(str3).append("'").toString()); } } }
/** * Reads in a sequence of extended ASCII strings or non-negative ints from standard input; * American flag sorts them; * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); sort(a); // print results for (int i = 0; i < a.length; i++) StdOut.println(a[i]); }
/** * Reads the currency exchange table from standard input and * prints an arbitrage opportunity to standard output (if one exists). * * @param args the command-line arguments */ public static void main(String[] args) { // V currencies int V = StdIn.readInt(); String[] name = new String[V]; // create complete network EdgeWeightedDigraph G = new EdgeWeightedDigraph(V); for (int v = 0; v < V; v++) { name[v] = StdIn.readString(); for (int w = 0; w < V; w++) { double rate = StdIn.readDouble(); DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate)); G.addEdge(e); } } // find negative cycle BellmanFordSP spt = new BellmanFordSP(G, 0); if (spt.hasNegativeCycle()) { double stake = 1000.0; for (DirectedEdge e : spt.negativeCycle()) { StdOut.printf("%10.5f %s ", stake, name[e.from()]); stake *= Math.exp(-e.weight()); StdOut.printf("= %10.5f %s\n", stake, name[e.to()]); } } else { StdOut.println("No arbitrage opportunity"); } }
/** * Unit tests the {@code SuffixArrayx} data type. * * @param args the command-line arguments */ public static void main(String[] args) { String s = StdIn.readAll().replaceAll("\n", " ").trim(); SuffixArrayX suffix1 = new SuffixArrayX(s); SuffixArray suffix2 = new SuffixArray(s); boolean check = true; for (int i = 0; check && i < s.length(); i++) { if (suffix1.index(i) != suffix2.index(i)) { StdOut.println("suffix1(" + i + ") = " + suffix1.index(i)); StdOut.println("suffix2(" + i + ") = " + suffix2.index(i)); String ith = "\"" + s.substring(suffix1.index(i), Math.min(suffix1.index(i) + 50, s.length())) + "\""; String jth = "\"" + s.substring(suffix2.index(i), Math.min(suffix2.index(i) + 50, s.length())) + "\""; StdOut.println(ith); StdOut.println(jth); check = false; } } StdOut.println(" i ind lcp rnk select"); StdOut.println("---------------------------"); for (int i = 0; i < s.length(); i++) { int index = suffix2.index(i); String ith = "\"" + s.substring(index, Math.min(index + 50, s.length())) + "\""; int rank = suffix2.rank(s.substring(index)); assert s.substring(index).equals(suffix2.select(i)); if (i == 0) { StdOut.printf("%3d %3d %3s %3d %s\n", i, index, "-", rank, ith); } else { // int lcp = suffix.lcp(suffix2.index(i), suffix2.index(i-1)); int lcp = suffix2.lcp(i); StdOut.printf("%3d %3d %3d %3d %s\n", i, index, lcp, rank, ith); } } }
public static void main(String[] args) { // key = word, value = set of files containing that word ST<String, SET<File>> st = new ST<String, SET<File>>(); // create inverted index of all files StdOut.println("Indexing files"); for (String filename : args) { StdOut.println(" " + filename); File file = new File(filename); In in = new In(file); while (!in.isEmpty()) { String word = in.readString(); if (!st.contains(word)) st.put(word, new SET<File>()); SET<File> set = st.get(word); set.add(file); } } // read queries from standard input, one per line while (!StdIn.isEmpty()) { String query = StdIn.readString(); if (st.contains(query)) { SET<File> set = st.get(query); for (File file : set) { StdOut.println(" " + file.getName()); } } } }
public static void main(String[] args) { String filename = args[0]; String separator = args[1]; In in = new In(filename); ST<String, Queue<String>> st = new ST<String, Queue<String>>(); ST<String, Queue<String>> ts = new ST<String, Queue<String>>(); while (in.hasNextLine()) { String line = in.readLine(); String[] fields = line.split(separator); String key = fields[0]; for (int i = 1; i < fields.length; i++) { String val = fields[i]; if (!st.contains(key)) st.put(key, new Queue<String>()); if (!ts.contains(val)) ts.put(val, new Queue<String>()); st.get(key).enqueue(val); ts.get(val).enqueue(key); } } StdOut.println("Done indexing"); // read queries from standard input, one per line while (!StdIn.isEmpty()) { String query = StdIn.readLine(); if (st.contains(query)) for (String vals : st.get(query)) StdOut.println(" " + vals); if (ts.contains(query)) for (String keys : ts.get(query)) StdOut.println(" " + keys); } }
/** * Reads in a sequence of extended ASCII strings from standard input; * MSD radix sorts them; * and prints them to standard output in ascending order. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); int n = a.length; sort(a); for (int i = 0; i < n; i++) StdOut.println(a[i]); }
/** * Reads in a command-line integer and sequence of words from * standard input and prints out a word (whose length exceeds * the threshold) that occurs most frequently to standard output. * It also prints out the number of words whose length exceeds * the threshold and the number of distinct such words. * * @param args the command-line arguments */ public static void main(String[] args) { int distinct = 0, words = 0; int minlen = Integer.parseInt(args[0]); ST<String, Integer> st = new ST<String, Integer>(); // compute frequency counts while (!StdIn.isEmpty()) { String key = StdIn.readString(); if (key.length() < minlen) continue; words++; if (st.contains(key)) { st.put(key, st.get(key) + 1); } else { st.put(key, 1); distinct++; } } // find a key with the highest frequency count String max = ""; st.put(max, 0); for (String word : st.keys()) { if (st.get(word) > st.get(max)) max = word; } StdOut.println(max + " " + st.get(max)); StdOut.println("distinct = " + distinct); StdOut.println("words = " + words); }
public static void Main(string[] args) { int N = StdIn.ReadInt(); QuickFindUF uf = new QuickFindUF(N); // read in a sequence of pairs of integers (each in the range 0 to N-1), // calling find() for each pair: If the members of the pair are not already // call union() and print the pair. while (!StdIn.IsEmpty()) { int p = StdIn.ReadInt(); int q = StdIn.ReadInt(); if (uf.Connected(p, q)) { continue; } uf.Union(p, q); Console.WriteLine(p + " " + q); } Console.Write(uf.Count + " components"); }
/** * Reads in a social network from a file, and then repeatedly reads in * individuals from standard input and prints out their degrees of * separation. * Takes three command-line arguments: the name of a file, * a delimiter, and the name of the distinguished individual. * Each line in the file contains the name of a vertex, followed by a * list of the names of the vertices adjacent to that vertex, * separated by the delimiter. * * @param args the command-line arguments */ public static void main(String[] args) { String filename = args[0]; String delimiter = args[1]; String source = args[2]; // StdOut.println("Source: " + source); SymbolGraph sg = new SymbolGraph(filename, delimiter); Graph G = sg.graph(); if (!sg.contains(source)) { StdOut.println(source + " not in database."); return; } int s = sg.indexOf(source); BreadthFirstPaths bfs = new BreadthFirstPaths(G, s); while (!StdIn.isEmpty()) { String sink = StdIn.readLine(); if (sg.contains(sink)) { int t = sg.indexOf(sink); if (bfs.hasPathTo(t)) { for (int v : bfs.pathTo(t)) { StdOut.println(" " + sg.nameOf(v)); } } else { StdOut.println("Not connected"); } } else { StdOut.println(" Not in database."); } } }
void OnGUI() { if (Event.current.isKey && Event.current.type == EventType.KeyUp) { if (StdIn != null) { StdIn.Write((byte)Event.current.keyCode); } } Vector2 sizeOfCharacter = style.CalcSize(new GUIContent("M")); Vector2 kerningCheck = style.CalcSize(new GUIContent("MM")); float charWidth = kerningCheck.x - sizeOfCharacter.x; int max = Mathf.Min(Buffer.Count, Height + ScrollY); string text = GetGUIString(max); if (DisplayOntoGui) { float x = charWidth * (CursorX - ScrollX); float y = sizeOfCharacter.y * (CursorY - ScrollY); GUI.Label(new Rect(x, y, sizeOfCharacter.x, sizeOfCharacter.y), "<color=white>|</color>", style); GUI.Label(new Rect(0, 0, Screen.width, Screen.height), text, style); } else if (textMesh != null) { textMesh.text = text; } }
/** * Read the following commands: * init n v Initializes the array of size n with all v's * set a b c... Initializes the array with [a, b, c ...] * rsq a b Range Sum Query for the range [a, b] * rmq a b Range Min Query for the range [a, b] * up a b v Update the [a,b] portion of the array with value v. * exit * <p> * Example: * init * set 1 2 3 4 5 6 * rsq 1 3 * Sum from 1 to 3 = 6 * rmq 1 3 * Min from 1 to 3 = 1 * input up 1 3 * [3,2,3,4,5,6] * * @param args the command-line arguments */ public static void main(String[] args) { SegmentTree st = null; String cmd = "cmp"; while (true) { String[] line = StdIn.readLine().split(" "); if (line[0].equals("exit")) break; int arg1 = 0, arg2 = 0, arg3 = 0; if (line.length > 1) { arg1 = Integer.parseInt(line[1]); } if (line.length > 2) { arg2 = Integer.parseInt(line[2]); } if (line.length > 3) { arg3 = Integer.parseInt(line[3]); } if ((!line[0].equals("set") && !line[0].equals("init")) && st == null) { StdOut.println("Segment Tree not initialized"); continue; } int array[];
/**/ public static void main(string[] strarr) { Alphabet.__ <clinit>(); Alphabet alphabet = new Alphabet(strarr[0]); int num = alphabet.R(); int[] array = new int[num]; string @this = StdIn.readAll(); int num2 = java.lang.String.instancehelper_length(@this); for (int i = 0; i < num2; i++) { if (alphabet.contains(java.lang.String.instancehelper_charAt(@this, i))) { int[] arg_54_0 = array; int num3 = alphabet.toIndex(java.lang.String.instancehelper_charAt(@this, i)); int[] array2 = arg_54_0; array2[num3]++; } } for (int i = 0; i < num; i++) { StdOut.println(new StringBuilder().append(alphabet.toChar(i)).append(" ").append(array[i]).toString()); } }
/** * Reads a string from a file specified as the first * command-line argument; read an integer k specified as the * second command line argument; then repeatedly processes * use queries, printing all occurrences of the given query * string in the text string with k characters of surrounding * context on either side. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); int context = Integer.parseInt(args[1]); // read in text String text = in.readAll().replaceAll("\\s+", " "); int n = text.length(); // build suffix array SuffixArray sa = new SuffixArray(text); // find all occurrences of queries and give context while (StdIn.hasNextLine()) { String query = StdIn.readLine(); for (int i = sa.rank(query); i < n; i++) { int from1 = sa.index(i); int to1 = Math.min(n, from1 + query.length()); if (!query.equals(text.substring(from1, to1))) break; int from2 = Math.max(0, sa.index(i) - context); int to2 = Math.min(n, sa.index(i) + context + query.length()); StdOut.println(text.substring(from2, to2)); } StdOut.println(); } }
/**/ public static void main(string[] strarr) { In @in = new In(strarr[0]); int num = Integer.parseInt(strarr[1]); string text = java.lang.String.instancehelper_replaceAll(@in.readAll(), "\\s+", " "); int num2 = java.lang.String.instancehelper_length(text); SuffixArray suffixArray = new SuffixArray(text); while (StdIn.hasNextLine()) { string text2 = StdIn.readLine(); for (int i = suffixArray.rank(text2); i < num2; i++) { int num3 = suffixArray.index(i); int endIndex = java.lang.Math.min(num2, num3 + java.lang.String.instancehelper_length(text2)); if (!java.lang.String.instancehelper_equals(text2, java.lang.String.instancehelper_substring(text, num3, endIndex))) { break; } int beginIndex = java.lang.Math.max(0, suffixArray.index(i) - num); int endIndex2 = java.lang.Math.min(num2, suffixArray.index(i) + num + java.lang.String.instancehelper_length(text2)); StdOut.println(java.lang.String.instancehelper_substring(text, beginIndex, endIndex2)); } StdOut.println(); } }
/** * Unit tests the {@code TrieST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { // build symbol table from standard input TrieST<Integer> st = new TrieST<Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } // print results if (st.size() < 100) { StdOut.println("keys(\"\"):"); for (String key : st.keys()) { StdOut.println(key + " " + st.get(key)); } StdOut.println(); } StdOut.println("longestPrefixOf(\"shellsort\"):"); StdOut.println(st.longestPrefixOf("shellsort")); StdOut.println(); StdOut.println("longestPrefixOf(\"quicksort\"):"); StdOut.println(st.longestPrefixOf("quicksort")); StdOut.println(); StdOut.println("keysWithPrefix(\"shor\"):"); for (String s : st.keysWithPrefix("shor")) StdOut.println(s); StdOut.println(); StdOut.println("keysThatMatch(\".he.l.\"):"); for (String s : st.keysThatMatch(".he.l.")) StdOut.println(s); }
/** * Reads a 1D array of booleans from standard input and returns it. * * @return the 1D array of booleans */ public static boolean[] readBoolean1D() { int n = StdIn.readInt(); boolean[] a = new boolean[n]; for (int i = 0; i < n; i++) { a[i] = StdIn.readBoolean(); } return a; }
/** * Reads a 1D array of integers from standard input and returns it. * * @return the 1D array of integers */ public static int[] readInt1D() { int n = StdIn.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = StdIn.readInt(); } return a; }
/** * Reads a 1D array of doubles from standard input and returns it. * * @return the 1D array of doubles */ public static double[] readDouble1D() { int n = StdIn.readInt(); double[] a = new double[n]; for (int i = 0; i < n; i++) { a[i] = StdIn.readDouble(); } return a; }
/** * Reads a sequence of integers from standard input and * prints the number of inversions to standard output. * * @param args the command-line arguments */ public static void main(String[] args) { int[] a = StdIn.readAllInts(); int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; StdOut.println(Inversions.count(a)); StdOut.println(Inversions.count(b)); }
/**/ public static void main(string[] strarr) { string[] array = StdIn.readAllStrings(); Knuth.shuffle(array); for (int i = 0; i < array.Length; i++) { StdOut.println(array[i]); } }
static void Main(string[] args) { Stack <string> stack = new Stack <string>(); Queue <string> q = new Queue <string>(); Bag <string> b = new Bag <string>(); Deque <string> deque = new Deque <string>(); while (!StdIn.IsEmpty()) { string item = StdIn.ReadString(); b.Add(item); stack.Push(item); deque.PushLeft(item); if (!item.Equals("-")) { q.Enqueue(item); } //else if (!q.IsEmpty) //StdOut.Print(q.Dequeue() + " "); } stack.Reverse(); Queue <string> q2 = new Queue <string>(q); q.Reverse(); while (!q2.IsEmpty) { StdOut.Print(q2.Dequeue() + " "); } while (!q.IsEmpty) { StdOut.Print(q.Dequeue() + " "); } Stack <string> stack2 = new Stack <string>(stack); while (!stack.IsEmpty) { StdOut.Print(stack.Pop() + " "); } while (!stack2.IsEmpty) { StdOut.Print(stack2.Pop() + " "); } StdOut.Println(); while (!deque.IsEmpty) { StdOut.Print(deque.PopRight() + " "); } StdOut.Println(); foreach (var item in b) { StdOut.Print(item + " "); } }
/** * Unit tests the {@code BinarySearchST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); }
/** * Interprets the command-line argument as a regular expression * (supporting closure, binary or, parentheses, and wildcard) * reads in lines from standard input; writes to standard output * those lines that contain a substring matching the regular * expression. * * @param args the command-line arguments */ public static void main(String[] args) { String regexp = "(.*" + args[0] + ".*)"; NFA nfa = new NFA(regexp); while (StdIn.hasNextLine()) { String line = StdIn.readLine(); if (nfa.recognizes(line)) { StdOut.println(line); } } }
/** * Unit tests the {@code FarthestPair} data type. * Reads in an integer {@code n} and {@code n} points (specified by * their <em>x</em>- and <em>y</em>-coordinates) from standard input; * computes a farthest pair of points; and prints the pair to standard * output. * * @param args the command-line arguments */ public static void main(String[] args) { int n = StdIn.readInt(); Point2D[] points = new Point2D[n]; for (int i = 0; i < n; i++) { int x = StdIn.readInt(); int y = StdIn.readInt(); points[i] = new Point2D(x, y); } FarthestPair farthest = new FarthestPair(points); StdOut.println(farthest.distance() + " from " + farthest.either() + " to " + farthest.other()); }
/** * Unit tests the {@code LinearProbingHashST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { LinearProbingHashST<String, Integer> st = new LinearProbingHashST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } // print keys for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); }
/**/ public static void main(string[] strarr) { string[] array = StdIn.readAllStrings(); int num = array.Length; MSD.sort(array); for (int i = 0; i < num; i++) { StdOut.println(array[i]); } }