题目:
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int inf = 0x3f3f3f3f;
const int maxn = 4050;
int n,m,d[maxn];
bool g[maxn][maxn];
//一开始以为暴力的话是n^3会超时,后来看了题解原来前两层放上去之后加个剪枝,第三层的复杂度是加上去的而不是乘上去的
//即剪枝使得复杂度由O(N^3)降为O(N^2+NM)
int main(){//62 ms 18100 KB
int x,y;
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i){
scanf("%d%d",&x,&y);
g[x][y]=g[y][x]=1;
d[x]++;
d[y]++;
}
int ans=inf;
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(g[i][j] && d[i]+d[j]<=inf){//只有M个g[i][j]成立
for(int k=1;k<=n;++k){
if(g[i][k] && g[j][k]){
ans=min(ans,d[i]+d[j]+d[k]);
}
}
}
}
}
//相当于外面枚举N^2次,对于其中的M次才有第三层for 故复杂度为 O(N^2+M*N)
if(ans>=inf) puts("-1");
else printf("%d\n",ans-6);
return 0;
}