简体   繁体   English

如何在图中找到“朋友三角”?

[英]How to find a "triangle of friends" in a graph?

I have names of people that are friends and I am looking for triangles of friends, if there are any.我有朋友的名字,我正在寻找朋友的三角形,如果有的话。 Example (names next to each other classify as friends, in the first row the first number represents the number of people and the second number represents number of friendships):示例(相邻的名字分类为朋友,第一行第一个数字代表人数,第二个数字代表好友数量):

6 7
mirko slavko
slavko janko
janko mirko
slavko luka
luka mirjana
mirjana ivana
ivana luka

In this example, janko - mirko - slavko is one and mirjana - luka - ivana is an another triangle.在这个例子中,janko - mirko - slavko 是一个,mirjana - luka - ivana 是另一个三角形。

I wrote a code which generates a 2d list which represents this graph.我写了一个代码来生成一个代表这个图的二维列表。

L = [input().split() for i in range (n)]
H=[]
for i in range(n):
    for j in range(2):
        if L[i][j] not in H:
            H.append(L[i][j])
H.sort()

for number, name in enumerate(H):
    for i in range (n):
        for j in range(2):
            L[i][j]=L[i][j].replace(name, str(number))
        
    
matrix = [[0 for i in range(m)] for j in range(m)]

for i, j in L:
    matrix[int(i)][int(j)]=matrix[int(j)][int(i)]=1


the graph looks like this (names are sorted alphabeticly, each row and column represent a name, 1 represents that a friendship exists, 0 represent that these two people aren't friends):图形看起来是这样的(名字按字母顺序排列,每一行和每一列代表一个名字,1代表存在友谊,0代表这两个人不是朋友):

[0, 0, 1, 1, 0, 0]  
[0, 0, 0, 0, 1, 1]  
[1, 0, 0, 1, 0, 1]  
[1, 0, 1, 0, 0, 0]  
[0, 1, 0, 0, 0, 1]  
[0, 1, 1, 0, 1, 0]  

My question is how to find a triangle with code??我的问题是如何用代码找到三角形?

The dead simple method would be死的简单方法是

  1. Create a dictionary whose key is the people's names, and the value is the set of friends of that person.创建一个字典,其键是人名,值是那个人的朋友 Make sure that if A is in the set of friends of B, that B is also in the set of friends of A.确保如果 A 在 B 的朋友集中,那么 B 也在 A 的朋友集中。

  2. For each pair of people A and B , see if friends[A].intersect(friends[B]) is empty.对于每一对人AB ,查看friends[A].intersect(friends[B])是否为空。

Most forms of the clique problem are difficult, the most general solutions are NP complete.大多数形式的集团问题都很困难,最通用的解决方案是 NP 完全的。 Therefore O(N**3) is probably the best you can do assuming the input representation is efficient, and since you already made the 2d matrix you are most of the way there.因此,假设输入表示是有效的,O(N**3) 可能是你能做的最好的,并且因为你已经制作了二维矩阵,所以你已经完成了大部分工作。

friends = [
     [0,1,1,0],
     [1,0,1,1],
     [1,1,0,0],
     [0,1,0,0]]
n = 4

for i in range(n):
    for j in range(i+1, n):
        if not friends[i][j]:
            continue
        for k in range(j+1, n):
            if friends[i][k] and friends[j][k]:
                print('friends!')
                print(i,j,k)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM