算一下复杂度。发现可以直接暴。对于u枚举a和b,判断一下是否连边,更新答案。
#include<bits/stdc++.h> using namespace std; int n,m; const int maxn = 4001; #define PB push_back vector<int> G[maxn]; bool g[maxn][maxn]; int deg[maxn]; const int INF = 0x3f3f3f3f; int main() { //freopen("in.txt","r",stdin); scanf("%d%d",&n,&m); for(int i = 0; i < m; i++){ int a,b;scanf("%d%d",&a,&b); deg[a]++; deg[b]++; g[a][b] = g[b][a] = true; G[a].PB(b); G[b].PB(a); } int ans = INF; for(int u = 1; u <= n; u++){ int sz = G[u].size(); for(int i = 0; i < sz; i++){ int a = G[u][i]; for(int j = i+1; j < sz; j++){ int b = G[u][j]; if(g[a][b]){ ans = min(ans,deg[u]+deg[a]+deg[b]-6); } } } } if(ans<INF){ printf("%d ",ans); }else printf("-1 "); return 0; }