A clique is a subset of vertices of an undirected graph such that every two distinct vertices in the clique are adjacent. A maximal clique is a clique that cannot be extended by including one more adjacent vertex. (Quoted from https://en.wikipedia.org/wiki/Clique_(graph_theory))
Now it is your job to judge if a given subset of vertices can form a maximal clique.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers Nv (≤ 200), the number of vertices in the graph, and Ne, the number of undirected edges. Then Ne lines follow, each gives a pair of vertices of an edge. The vertices are numbered from 1 to Nv.
After the graph, there is another positive integer M (≤ 100). Then M lines of query follow, each first gives a positive number K (≤ Nv), then followed by a sequence of K distinct vertices. All the numbers in a line are separated by a space.
Output Specification:
For each of the M queries, print in a line Yes
if the given subset of vertices can form a maximal clique; or if it is a clique but not a maximal clique, print Not Maximal
; or if it is not a clique at all, print Not a Clique
.
Sample Input:
8 10
5 6
7 8
6 4
3 6
4 5
2 3
8 2
2 7
5 3
3 4
6
4 5 4 3 6
3 2 8 7
2 2 3
1 1
3 4 3 6
3 3 2 1
Sample Output:
Yes
Yes
Yes
Yes
Not Maximal
Not a Clique
题目大意
给定一个无向图,从中选出一些点集,如果这些点集中所有点两两有边相连,则称之为clique。
如果还能从无向图中选取点加入点集,依然是clique,则输出Not Maximal
如果不能再从无向图中选点加入点集,则输出Yes
如果不是clique,则输出Not a Clique
分析
首先遍历点集,判断是否两两点之间有边相连。之后遍历无向图中剩余的点,判断是否还能向点集中加入点仍然是clique。
一开始使用的是遍历点集,判断是否是clique,但是倒数第二个测试点运行超时。然后就改为判断所有点的非连接点的集合与点集本身是否有交集,如果有,则不是clique,如果没有,则是clique。
使用这个方法之后,虽然其他测试点增加了几毫秒,但是倒数第二个测试点150+MS通过。
Python实现
def main():
line = input().split(" ")
v, e = int(line[0]), int(line[1])
egle = [ [0 for x in range(v)] for x in range(v)]
for x in range(e):
line = input().split(" ")
a, b = int(line[0])-1, int(line[1])-1
egle[a][b], egle[b][a] = 1, 1
dic = {}
for i in range(v):
rest = [x for x in range(v) if egle[i][x] ==0 and x != i]
dic[i] = rest
m = int(input())
for x in range(m):
line = input().split(" ")
get = [int(x)-1 for x in line[1:]]
num = int(line[0])
temp = set()
for i in get:
temp = temp | set(dic[i])
if len(temp & set(get))!=0:
print("Not a Clique")
else:
rest = [ x for x in range(v) if x not in get]
flag = True
for i in rest:
f = [0 for q in range(num)]
for j in range(int(line[0])):
if egle[i][get[j]] == 1:
f[j] = 1
if sum(f) == num:
print("Not Maximal")
flag = False
break
if flag:
print("Yes")
if __name__ == "__main__":
main()