Quantcast
Channel: 懒得折腾
Viewing all articles
Browse latest Browse all 764

Design and Analysis of Algorithm 2 Homework 6

$
0
0

Question 1

In this assignment you will implement one or more algorithms for the 2SAT problem. Here are 6 different 2SAT instances: #1 #2 #3 #4 #5 #6.The file format is as follows. In each instance, the number of variables and the number of clauses is the same, and this number is specified on the first line of the file. Each subsequent line specifies a clause via its two literals, with a number denoting the variable and a “-” sign denoting logical “not”. For example, the second line of the first data file is “-16808 75250″, which indicates the clause ¬x16808∨x75250.

Your task is to determine which of the 6 instances are satisfiable, and which are unsatisfiable. In the box below, enter a 6-bit string, where the ith bit should be 1 if the ith instance is satisfiable, and 0 otherwise. For example, if you think that the first 3 instances are satisfiable and the last 3 are not, then you should enter the string 111000 in the box below.

DISCUSSION: This assignment is deliberately open-ended, and you can implement whichever 2SAT algorithm you want. For example, 2SAT reduces to computing the strongly connected components of a suitable graph (with two vertices per variable and two directed edges per clause, you should think through the details). This might be an especially attractive option for those of you who coded up an SCC algorithm for Part I of this course. Alternatively, you can use Papadimitriou’s randomized local search algorithm. (The algorithm from lecture might be too slow; but perhaps there are some simple ways to ensure that it doesn’t run too long?) A third approach is via backtracking. In lecture we mentioned this approach only in passing; see the DPV book, for example, for more details.

 

import fileinput
import networkx as nx
#import number_strongly_connected_components from nx
i = 0
for i in range(1, 7):
	G=nx.DiGraph()
	k = 0
	for line in fileinput.input("2sat" + str(i) + ".txt"):
		k = k + 1
		if (k == 1):
			M = int(line)	
			continue	
		words = line.strip().split(" ")
		start = int(words[0].strip())
		end = int(words[1].strip())
		G.add_node(start)
		G.add_node(end)
		G.add_node(-start)
		G.add_node(-end)
		G.add_edge(-start,end)
		G.add_edge(-end,start)
	#print len(G.nodes())
	#print len(G.edges())
	resultList = nx.kosaraju_strongly_connected_components(G)
	strResult = "Success"
	for l in resultList:
		if(len(l) > 1):
			print l
			for x in l:
				for y in l:
					if (x == y):
						continue
					if (x == -y):
						strResult = "Failed"
	print str(i) + ": " + strResult



Viewing all articles
Browse latest Browse all 764

Trending Articles