Stanford公开课之算法:设计与分析——(第三周) Programming Question-3

该博客介绍了斯坦福大学公开课中关于简单无向图的编程问题。任务是针对一个包含200个顶点的图,使用随机收缩算法求解最小割,并要求多次运行以确保找到最小值。内容涉及到图的邻接列表表示,以及如何实现边的收缩操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question 1

Download the text file  here. (Right click and save link as)

The file contains the adjacency list representation of a simple undirected graph. There are 200 vertices labeled 1 to 200. The first column in the file represents the vertex label, and the particular row (other entries except the first column) tells all the vertices that the vertex is adjacent to. So for example, the  6th  row looks like : "6 155 56 52 120 ......". This just means that the vertex with label 6 is adjacent to (i.e., shares an edge with) the vertices with labels 155,56,52,120,......,etc

Your task is to code up and run the randomized contraction algorithm for the min cut problem and use it on the above graph to compute the min cut. (HINT: Note that you'll have to figure out an implementation of edge contractions. Initially, you might want to do this naively, creating a new graph from the old every time there's an edge contraction. But you should also think about more efficient implementations.) (WARNING: As per the video lectures, please make sure to run the algorithm many times with different random seeds, and remember the smallest cut that you ever find.) Write your numeric answer in the space provided. So e.g., if your answer is 5, just type 5 in the space provided.

图结构实现:

public class Graphs<T>
    {
        public enum GraphKind { DG, DN, UDG, UDN };
        private GraphKind kind;

        private Dictionary<T,Vertex<T>> vertices;
        public Dictionary<T, List<T>> edges;
        private List<Edge> edgesList;
        
        public Graphs(GraphKind kind)
        {
            this.kind = kind;
            vertices = new Dictionary<T, Graphs<T>.Vertex<T>>();
            edges = new Dictionary<T, List<T>>();
            edgesList = new List<Graphs<T>.Edge>();
        }

        private bool contains(T t)
        {
            return vertices.ContainsKey(t);
        }
        
        private Vertex<T> find(T t)
        {
            if (vertices.ContainsKey(t))
                return vertices[t];
            return null;
        }
        
        public void addEdge(T from, T to)
        {
            Vertex<T> fromVer = find(from);
            if (fromVer == null) return;
                //throw new ArgumentException("head vertex not exist!");

            Vertex<T> toVer = find(to);
            if (toVer == null) return;
                //throw new ArgumentException("tail vertex not exist!");

            if (edges.ContainsKey(from))
            {
                edges[from].Add(to);
            }
            else
            {
                edges.Add(from, new List<T>());
                edges[from].Add(to);
            }

            Edge e = new Graphs<T>.Edge(from, to);
            edgesList.Add(e);

            addDirectedEdge(fromVer, toVer);
            if (!from.Equals(to))
                addDirectedEdge(toVer, fromVer);
        }
        
        public void addDirectedEdge(Vertex<T> fromVer, Vertex<T> toVer)
        {
            if (fromVer.firstEdge == null)
            {
                fromVer.firstEdge = new Node(toVer);
            }
            else
            {
                Node tmp, node = fromVer.firstEdge;
                do
                {
                    //allow add parallel edges and self-loop
                    if (node.adj.id.Equals(toVer.id)) return;
                    //    throw new ArgumentException("add edges repeatedly!");
                    tmp = node;
                    node = node.next;
                } while (node != null);
                tmp.next = new Node(toVer);
            }
        }
       
        public void addVertex(T t)
        {
            Vertex<T> v = new Vertex<T>(t);
            if (contains(t))
                throw new ArgumentException("add node repeatedly!");
            vertices.Add(t, v);
        }
        
        public class Vertex<TValue>
        {
            public TValue id;
            public Node firstEdge;
            public bool visited;
            public Vertex(TValue id)
            {
                this.id = id;
            }
        }

        public class Node
        {
            public Vertex<T> adj;
            public Node next;
            public Node(Vertex<T> v)
            {
                adj = v;
            }
        }
        
        public class Edge
        {
            public T head;
            public T tail;
            public int eWeight;
            //public int nextEdge;
            public Edge(T v1, T v2)
            {
                this.head = v1;
                this.tail = v2;
            }
        }
    }

图的邻接表表示:

public class GraphList<T>
    {
        private Dictionary<T, List<T>> vertices;
        private List<T> index;
        private Graphs<T> g;
        public GraphList(Graphs<T> g)
        {
            this.g = g;
            init();
        }
        private void init()
        {
            initVertices();
            index = new List<T>();
            foreach (T t in vertices.Keys)
            {
                index.Add(t);
            }
        }

        public void initVertices()
        {
            vertices = new Dictionary<T, List<T>>();
            foreach (T t in g.edges.Keys)
            {
                vertices.Add(t, new List<T>());
                foreach (T j in g.edges[t])
                {
                    vertices[t].Add(j);
                }
            }
        }
        public bool Contains(T t)
        {
            return vertices.ContainsKey(t);
        }
        
        public void removeVertex(T t)
        {
            if (vertices.ContainsKey(t))
            {
                vertices.Remove(t);
                index.Remove(t);
            }
        }
        
        public void addVertex(T t)
        {
            if (Contains(t))
                throw new ArgumentException("add node repeatedly!");
            vertices.Add(t, new List<T>());
            index.Add(t);
        }

        public void addNode(T from, T to)
        {

            if (Contains(from))
            {
                vertices[from].Add(to);
            }
        }

        public void removeNode(T from, T to)
        {
            if (Contains(from))
            {
                while (vertices[from].IndexOf(to) > -1)
                {
                    vertices[from].Remove(to);
                }
            }
        }
        
        public void removeAllThisNode(T t)
        {
            foreach (T tv in vertices.Keys)
            {
                removeNode(tv, t);
            }
        }
        
        public void mergeVertices(T t1, T t2)
        {
            /* attach t2's nodes to t1
             * attach t1 to t2's nodes
             * delete t2 from vertices and other vertices' nodes
             */
            mergeVerticesNodes(t1, t2);
            removeVertex(t2);
            removeAllThisNode(t2);
            
        }
        
        private void mergeVerticesNodes(T t1, T t2)
        {
            /* attach t2's nodes to t1
             * attach t1 to t2's nodes
             */
            foreach (T t in vertices[t2])
            {
                //self-loop
                if(t.Equals(t1)) continue;
                vertices[t1].Add(t);
                vertices[t].Add(t1);
            }
        }

        public void RandomContraction()
        {
            init(); 
            int from=2, to=4;
            //mergeVertices(index[1], index[3]);
            while (index.Count > 2)
            {
                from = RandomUtil.Random(0, index.Count);
                //if (from == 199)
                    //Console.WriteLine();
                to = RandomUtil.Random(0, vertices[index[from]].Count);
                //Console.WriteLine("merge vertex{0} and vertex{1}", index[from], vertices[index[from]][to]);
                mergeVertices(index[from], vertices[index[from]][to]);
            }
        }
        
        public int min = 200;
        
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder("\r\n");
            int count = 0;
            foreach (T t in vertices.Keys)
            {
                count = 0;
                sb.Append(t).Append(":");
                foreach (T j in vertices[t])
                {
                    count++;
                    sb.Append(j).Append(" ");
                }
                sb.Append("\n");
                //Console.WriteLine("{0}:{1}", t, count);
                if(min>count)
                    min = count;
                sb.Append(count).Append("\r\n");
            }
            //Console.WriteLine();
            return sb.ToString();
        }

        public class Vertex<TValue>
        {
            public TValue id;
            public Node firstEdge;
            public bool visited;
            public Vertex(TValue id)
            {
                this.id = id;
            }
        }

        public class Node
        {
            public Vertex<T> adj;
            public Node next;
            public Node(Vertex<T> v)
            {
                adj = v;
            }
        }
    }

结果再次就不公布了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值