题目连接:http://codeforces.com/contest/574/problem/B
Do you know a story about the three musketeers? Anyway, you will learn about its origins now.
Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.
There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.
Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.
The first line contains two space-separated integers, n and m (3 ≤ n ≤ 4000, 0 ≤ m ≤ 4000) — respectively number of warriors and number of pairs of warriors knowing each other.
i-th of the following m lines contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.
If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes).
5 6
1 2
1 3
2 3
2 4
3 4
4 5
2
7 4
2 1
3 6
5 1
1 7
-1
In the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2.
The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3.
In the second sample there is no triple of warriors knowing each other.
题目大意:有一堆火枪手,从1-n编号,输入告诉某m对火枪手相互认识,要求找出一在这些火枪手中找出一个符合下述条件的三人小队。
条件:1.三人必须互相认识
2.三人认识的人个数总和最小(不包括队中认识的二人)
解题思路:
对于每一个火枪手抽象出三个属性:1.自己的编号。2.认识的人的编号。3.认识的人的个数。
思考以后发现可以抽象成图,每一个火枪手为节点,认识关系为边,就可以形成一个无向图。
而题目就转化成了给定一个无向图求三元环的个数。
因为数据范围较小,所以暴力枚举就可过。
代码如下:
#include<bits/stdc++.h> using namespace std; int g[4005][4005]={0}; int main() { int n,m,a,b; int res=999999; int num[4005]={0}; scanf("%d%d",&n,&m); for(int i=0;i<m;i++) { scanf("%d%d",&a,&b); g[a][b]=g[b][a]=1; num[a]++; num[b]++; } for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(g[i][j]!=0) { for(int k=1;k<=n;k++) { if(g[j][k]!=0&&k!=i&&g[k][i]!=0) { int sum=num[i]+num[j]+num[k]-6; res=min(res,sum); } } } } } if(res==999999) res=-1; cout<<res<<endl; }