Shortest cycles in undirected graphs

Find the shortest cycle that contains a particular vertex on an undirected (and unweighted) chart $ s $It is usually said that a BFS is running $ s $ and the first time to find another visit, this is the smallest cycle length you want.

This does not seem to be true, quoted from https://www.cs.princeton.edu/courses/archive/spr08/cos226/exams/fin-f05-sol.pdf page 3:

Keep this in mind when you run BFS from $ s $ and stop once you visit a again
You may not get the vertex (using a previously unused edge)
shortest path contains $ s $,

Examples where this technique seems to be suggested: An efficient algorithm to find a shortest cycle including a specific vertex

Another technique, in which the shortest cycle in the entire diagram is determined by executing BFS from each vertex, seems to recognize only the shortest length +1 in a special case, as mentioned in this document: https: // link. springer.com/chapter /10.1007/978-3-540-78773-0_63 in the "unweighted case". on the other handHere (http://theory.stanford.edu/~virgi/cs267/lecture3.pdf) it is mentioned (first and second paragraph) that executing BFS results in every case from each vertex the shortest length (circumference). This is also mentioned in an archive (http://web.archive.org/web/20140513212046/https://webcourse.cs.technion.ac.il/234247/Winter2003-2004/ho/WCFiles/Girth.pdf) , ,

Which of all algorithms / methods applies to:

  1. Can you find the cycle with the shortest length in an undirected diagram?
  2. Find the shortest length cycle that passes through a known vertex $ s $ in an undirected graph?
  3. Where is the trap in each of my comparisons and contrasts above? (I can't believe some of the above are even wrong …)

Note: A randomized sub-cubic algorithm appears to exist in Raphael Yuster's publication "A shortest cycle for each vertex of a graph": http://research.haifa.ac.il/~raphy/papers/all-cycles .pdf

co.combinatorics – Limit the number of k cycles in a graph

Fix them all $ k geq 3 $Suppose I have a simple undirected diagram $ G = (V, E) $, I want to limit the number of $ k $ drive in $ G $ as a function of $ | E | $, In particular, I would like to prove the following "presumed" statement:

W.T.S: Given, none $ G = (V, E) $, the number of $ k $in $ G $ is at most $ O (| E | ^ {k / 2}) $,

Clear $ binom {| V |} {k} $ is tight if we just wanted a limit in terms of $ | V | $, which is apparent from the full graphic $ | V | $ Corners. However, it is not as clear what a narrow upper limit is in terms of evidence $ | E | $, The intuition for the conjecture is, of course, that it is optimal up to a constant to arrange your edges in a complete graph (if $ k $ is even that you gain a constant by creating a full two-part diagram instead of a full diagram.

There seems to be some evidence of this fact for triangles (k = 3), for example https://math.stackexchange.com/questions/823481/number-of-triangles-in-a-graph-based-on– Number of edges. However, they do not clearly generalize to larger ones $ k $, In addition, I do not know any algorithms for enumeration of k cycles for k> 3, which are parameterized by $ | E | $ (whose term would provide an upper limit).

For my application, I actually only need limits for odd numbers $ k $, but it seems that every such proof should generalize to everyone $ k $, To put it bluntly, I'm only interested in asymtotic limits in terms of $ | E | $ (Getting tight constants seems a lot more difficult). Suggestions or tips that I missed would be greatly appreciated.

Permutations – Why do the triangle numbers initially form long cycles mod $ 2 ^ k $?

As with triangular numbers ($ text {mod} 2 ^ n $) as a permutation of $ {0,1,2, dots, 2 ^ n-1 } $ and what is the set of triangular numbers mod $ n $? , Mapping the integer $ n $ to the $ 0 le n lt2 ^ k $ to the rest of the corresponding triangle number $ frac12n (n + 1) $ modulo $ 2 ^ k $ results in a permutation. For example for $ k = $ 3:

$$
01234567 \
01362754
$$

I noticed $ k = 5 $, all elements except $ 0 $ and $ 1 $ (which are always mapped to themselves) form a single cycle of length $ 2 ^ k-2 $, The probability of an evenly random permutation of the length $ n $ consists of a single cycle $ frac1n $So if these permutations (except $ 0 $ and $ 1 $) could be regarded as uniformly random, the probability would only be $ frac12 cdot frac16 cdot frac1 {14} cdot frac1 {30} = frac1 {5040} $, Reason enough to check whether the pattern remains larger $ k $,

It turns out that this is not the case $ k = 6 $ there is a $ 3 $-Cycle: $ (4,10,55) $, Nevertheless, unusually long cycle lengths remain: for everyone $ k $ of $ 2 $ to $ 12 $, except for $ k = 7 $The largest cycle contains more than half of the elements, while the likelihood that this will happen in a random permutation is rough $ ln $ 2, Indeed, in $ 9 $ of these $ 11 $ Cases (all except $ k = 6 $ and $ k = 7 $) the largest cycle contains more than $ frac45 $ of the elements; The probability of this is approximate $ ln frac54 ca.0.223 $ per case, so the probability that it will at least happen $ 9 $ get out $ 11 $ is $ sum_ {k = 9} ^ {11} binom {11} k left ( ln frac54 right) ^ k left (1- ln frac54 right) ^ {11-k} approx5 cdot10 ^ {- 5} $,

However, this pattern does not continue either: $ k $ of $ 2 $ to $ 30 $, there are $ 21 $ Cases with cycles of more than half of the elements, which is beyond the expected number $ 29 ln2 approx. $ 20.1; and for $ k $ of $ 13 $ to $ 30 $ It is only $ 4 $ Cases with cycles of more than $ frac45 $ of items that is almost exactly the expected number $ 18 ln frac54 ca.4.0 $,

My question is: is there an explanation for this initial tendency to form long cycles? Or should we attribute it to a coincidence?

For simplicity, here is the code that I used to determine the cycle lengths, and here are the results up to $ k = $ 30:

4 : 2
8 : 6
16 : 14
32 : 30
64 : 40, 19, 3
128 : 55, 48, 14, 6, 3
256 : 247, 4, 3
512 : 488, 7, 6, 6, 3
1024 : 818, 157, 47
2048 : 1652, 371, 23
4096 : 4060, 25, 9
8192 : 3754, 3609, 412, 321, 79, 12, 3
16384 : 15748, 292, 190, 71, 24, 22, 13, 13, 9
32768 : 20161, 11349, 333, 305, 281, 218, 72, 44, 3
65536 : 20128, 17231, 16759, 8072, 2377, 579, 295, 60, 33
131072 : 85861, 26603, 9389, 3887, 3365, 682, 594, 488, 118, 49, 23, 6, 5
262144 : 159827, 89991, 5749, 5465, 592, 231, 118, 100, 42, 24, 3
524288 : 211265, 176243, 59029, 35639, 28496, 6122, 4245, 1239, 713, 632, 244, 146, 133, 59, 39, 36, 6
1048576 : 620076, 216520, 131454, 68118, 7535, 2111, 1235, 1028, 225, 213, 36, 20, 3
2097152 : 993084, 583840, 394263, 87941, 31835, 3389, 1648, 459, 306, 273, 45, 35, 14, 10, 8
4194304 : 1487646, 1119526, 942359, 429054, 118037, 64446, 28806, 3238, 323, 291, 186, 126, 118, 102, 12, 11, 10, 7, 4
8388608 : 2542051, 2462220, 2040680, 1138236, 93072, 45880, 19664, 16473, 14243, 6319, 2917, 2598, 2160, 1414, 514, 118, 23, 19, 5
16777216 : 12137774, 4004239, 271250, 253890, 43860, 33597, 25495, 4132, 2575, 157, 116, 67, 35, 9, 8, 6, 4
33554432 : 28169497, 2552414, 1401622, 1019221, 356682, 21006, 14735, 10242, 8223, 566, 135, 45, 21, 15, 6
67108864 : 32223531, 29360424, 3530597, 932310, 809707, 99109, 83093, 67418, 1612, 364, 248, 248, 166, 21, 14
134217728 : 87591110, 34361487, 3360928, 3343185, 3291274, 1345478, 353498, 323522, 158252, 47767, 17776, 11159, 5927, 2681, 2343, 530, 235, 208, 162, 84, 59, 31, 30
268435456 : 232647749, 24918738, 5559122, 3742461, 525140, 384941, 278834, 197080, 62977, 48736, 21684, 16632, 13525, 8993, 3073, 2721, 1625, 1262, 153, 5, 3
536870912 : 379598603, 129063661, 26279056, 665648, 483286, 222289, 137686, 106713, 94323, 80276, 59199, 41767, 15498, 10615, 5066, 2816, 2699, 1579, 113, 10, 7
1073741824 : 877039442, 181409872, 7571387, 6549459, 921247, 240525, 3924, 3416, 1602, 894, 54

Algorithms – strongly connected components of a graph, just a disjoint union of cycles

While reading corman book, I just came across examples to find strongly connected components in a directed graph. However, it turns out that it is a disjoint union of cycles. Is this true for all directed graphs?

What about two connected components? are they also disjoint union of cycles? Please correct me if I think wrong

java – Extract cycles from a directed graph with maximum degree 1 and perform a fixed coverage for cycles

I am trying to solve P1243E in an efficient way. The problem in simple terms is:

given $ k $ boxes, $ i $-th box with $ n_i $ numbers. All numbers are different. We have to select a number from each box and swap it so that after resetting exactly one number into a box, all boxes have the same total.

entrance: $ k $, then each line with $ n_i $ and boxing $ i $ Elements.

output: Yes / No – if such a rearrangement is possible, followed by each line containing the value to be dialed and the box ID.

My solution is:

First, check that the average is an integer that represents the sum of the individual boxes. Then, since each number is different, we can draw an edge of a number $ a $ in the box $ i $ to another number $ b $ in another box $ j $ when we sit down $ a $ in the box $ j $ and remove $ b $ then the sum of this box becomes equal to the average. For this we find the difference of the current sum in the box $ j $ and the average sum, if this is the same $ b-a $ then this will bring the box $ j $Sum to average. A permutation is a collection of cycles with different box IDs covering all box IDs. So we can just do DFS with backtracking to find such a collection of cycles.

The editorial suggests an even better method:

We can extract cycles from the graph and then convert the cycle into a set of elements containing the boxed IDs of the covered numbers. We can then do set cover for $ {1,2, … k } $ Use of these sets with a dynamic programming method.

So I came up with this code, which is pretty faithful to the editorial that goes with it $ sim 9 $ Seconds to execute, while the actual deadlines are $ 1 $ sec. When can performance improvements be made: (Just for confirmation, there are solutions in Java from others with the same logic, but $ sim 200 $ ms execution time)

import java.io.*;
import java.util.*;

public class P1243E {
    public static void main(String() args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        boolean debug = !Boolean.parseBoolean(System.getProperty("ONLINE_JUDGE"));
        solver.solve(in, out, debug);
        out.close();
    }

    static class Task {
        public void solve(InputReader in, PrintWriter out, boolean debug) {
            int k = in.nextInt();
            int()() boxes = new int(k)();
            HashMap nodes = new HashMap<>();
            long totSum = 0;
            long() boxSums = new long(k);
            for (int i = 0; i < k; i++) {
                int n = in.nextInt();
                int() box = new int(n);
                for (int j = 0; j < n; j++) {
                    int a = in.nextInt();
                    totSum += a;
                    boxSums(i) += a;
                    box(j) = a;
                    nodes.put(a, new Node(a, i));
                }
                boxes(i) = box;
            }
            if (totSum % k != 0) {
                out.println("No");
            } else {
                /* Calculate edges */
                long boxSum = totSum / k;
                long() delta = new long(k);
                for (int i = 0; i < k; i++) {
                    delta(i) = boxSum - boxSums(i);
                }
                HashSet remaining = new HashSet<>();
                for (int i = 0; i < k; i++) {
                    for (int boxVal : boxes(i)) {
                        Node currNode = nodes.get(boxVal);
                        long nextValLong = boxVal + delta(i);
                        if ((int) nextValLong != nextValLong) {
                            continue;
                        }
                        int nextVal = (int) nextValLong;
                        if (nodes.containsKey(nextVal)) {
                            Node nextNode = nodes.get(nextVal);
                            if (nextNode.boxId != i || nextVal == boxVal) {
                                currNode.next = nextNode;
                                remaining.add(currNode);
                            }
                        }

                    }
                }
                /* Extract Cycles */
                int max = (1 << k) - 1;
                HashMap> cycles = new HashMap<>();
                while (remaining.size() > 0) {
                    /* Get element */
                    Node top = remaining.iterator().next();
                    HashSet visited = new HashSet<>();
                    /* DFS from this element */
                    Node curr = top;
                    while (true) {
                        /* Process curr */
                        if (!visited.contains(curr)) {
                            visited.add(curr);
                            remaining.remove(curr);
                        } else {
                            /* Back edge */
                            int cycleID = 0;
                            ArrayList cycle = new ArrayList<>();
                            /* Extract cycle */
                            Node loop = curr;
                            boolean validCycle = true;
                            do {
                                if ((cycleID >> loop.boxId & 1) == 1) {
                                    validCycle = false;
                                    /* Dont add cycle, these nodes are already visited,
                                    so they will be removed anyways*/
                                    break;
                                }
                                cycleID |= 1 << loop.boxId;
                                cycle.add(loop);
                                loop = loop.prev;
                            } while (loop != curr && loop != null);
                            if (validCycle) {
                                cycles.putIfAbsent(cycleID, cycle);
                            }
                            /* Exit DFS */
                            break;
                        }
                        /* Check & Move pointer */
                        if (curr.next != null) {
                            /* set prev for this run */
                            curr.next.prev = curr;
                            /* move pointer */
                            curr = curr.next;
                        } else {
                            break;
                        }
                    }
                }
                /* Calculate Set Cover */
                boolean() covered = new boolean(max + 1);
                int() subCover = new int(max + 1);
                covered(0) = true;
                for (int i = 0; i <= max; i++) {
                    for (int j = i; j > 0; j = (j - 1) & i) {
                        if (cycles.containsKey(j) && covered(remove(i, j))) {
                            subCover(i) = j;
                            covered(i) = true;
                            break;
                        }
                    }
                }
                /* Print Solution */
                if (covered(max)) {
                    out.println("Yes");
                    Queue bfs = new LinkedList<>();
                    ArrayList solution = new ArrayList<>();
                    bfs.add(max);
                    while (bfs.size() > 0) {
                        int top = bfs.poll();
                        if (cycles.containsKey(top)) {
                            solution.addAll(cycles.get(top));
                        } else {
                            int sc = subCover(top);
                            bfs.add(sc);
                            bfs.add(remove(top, sc));
                        }
                    }
                    int() resultVal = new int(k);
                    int() resultId = new int(k);
                    for (Node p : solution) {
                        resultVal(p.boxId) = p.value;
                        resultId(p.next.boxId) = p.boxId + 1;
                    }
                    for (int i = 0; i < k; i++) {
                        out.println(resultVal(i) + " " + resultId(i));
                    }
                } else {
                    out.println("No");
                }
            }

        }


        private int remove(int i, int j) {
            return i & (~j);
        }


        private static class Node {
            int value;
            int boxId;
            Node next;
            Node prev;

            Node(int value, int boxId) {
                this.value = value;
                this.boxId = boxId;
            }

            @Override
            public boolean equals(Object o) {
                if (this == o) {
                    return true;
                }
                if (o == null) {
                    return false;
                }
                Node node = (Node) o;
                return value == node.value;
            }

            @Override
            public int hashCode() {
                return value;
            }

            @Override
            public String toString() {
                return (value % 1000) + "(" + boxId + ")";
            }
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public String nextLine() {
            try {
                return reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public int() nextIntArray(int n) {
            int() arr = new int(n);
            for (int i = 0; i < n; i++) {
                arr(i) = nextInt();
            }
            return arr;
        }

        public long() nextLongArray(int n) {
            long() arr = new long(n);
            for (int i = 0; i < n; i++) {
                arr(i) = nextLong();
            }
            return arr;
        }

    }

}

Regular Expressions with Cycles – Computer Science Stack Exchange

With a button one of the three positions A, B, C is selected.

The button can never be turned from A to C or from C to A without spending at least one second in position B. The initial position of the button may be A, B, C.

Specify a regular expression for this language.

I tried to start from B and ended up with the following:

BB * ((AA * (BB *) *) u (CC * (BB *) *) *

However, it seems impossible to express all possible transitions.

To combine specific hours with fees in Google Sheet (Dates + Cycles + Fees)

I try to prepare a hand to count fees based on cycles (given hours) to know how much time I have for an action.

For example, I have a virtual pet with a maximum of 1 500 000 support points. For example, every cycle (every 5 hours) consumes 44,000 points. If the spots end and no one feeds anymore, the pet dies in the next cycle after the last cycle.

I'm trying to prepare a leaf with the following cells:

  • Full date with hour of last feeding,
  • Days remain until the last cycle,
  • Full date with hour when the pet dies,
  • Actual status of the interpolation points (depending on the dynamic actual time).

Pet Consum Points, for example, after these hours:
03:00:00, 08:00:00, 13:00:00, 18:00:00, 23:00:00.

I'm stuck and do not know how to solve this problem. If you would help me, I would be very grateful.

Charge – Is the number of battery cycles stored on the battery or device?

I've downloaded a Phone INFO app that contains a number of statistics, especially "battery discharge cycles". I would like to know if this number is retrieved from the battery (ie H. It is only the number of cycles for the current battery) or from the phone (ie H. It is the sum of the cycles of all the batteries in the phone) , In other words, if I use a brand new battery, should I expect the number to drop to zero?

Context: I have a Samsung S6, where the battery can not be easily changed. I went to a telephone repair shop to have the battery replaced. I left it for one day and did not watch the process of replacement. Now I suspect that I was cheated and the battery was not changed. I want to confront the store and use the (still very high) cycle count as proof, so first I check my understanding.

python – finding all simple paths (without internal cycles) in a directed graph with a weight of> 1.0

Assume a directed graph, where each edge is weighted with something positive float,

Problem: find all simple paths (in other words, (0, 1, 2, 0) is
just while (0, 1, 0, 1, 2 0) is not internal (0, 1, 0)
Cycle) with length <= cutoff and "push" them pusher
Recalls.

P.S. There is a real-time engine that performs such traversals frequently, and the algorithm should be optimized to be as fast as possible. __total_weight_of is $ O (n) $ and not a topic for optimization, "as it is": Everything it does is only a multiple of the weights of the corresponding edges.

def algorithm(G, source_node, target_node, pusher, cutoff=5):
queue = deque(((source_node)) if source_node in G else deque())
while len(queue):
    path = queue.popleft()
    if len(path) == cutoff:  # no sense to keep this path, it not gonna fit the limit
        continue
    adjacency_nodes = G(path(-1))  # all the neighbours from the latest node in this path
    if not len(adjacency_nodes):  # deadend reached: you can't get any further from this node and it doesn't fit the requirement, so just forgetting it
        continue
    for adjacency_node in adjacency_nodes:
        extended_path = path.copy() + (adjacency_node)  # might some smart linked list do any better here?
        if adjacency_node == target_node and __total_weight_of(G=G, verticies_list=extended_path) > 1:
            pusher(extended_path)
        else:
            queue.append(extended_path)