题目概述
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.
Input
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.
Output
If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print “-1” (without the quotes).
链接
分析
数据不大,直接枚举,如果构成一个三元结构,就更新答案,j可以从i + 1枚举,因为有重复的情况,可以在时间复杂度上优化一个常数。感觉和floyd有点像。
代码
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 4005;
int n, m;
int ans = 0x3f3f3f3f;
int e[N][N], sum[N];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1, x, y; i <= m; ++i) {
scanf("%d%d", &x, &y);
e[x][y] = 1, e[y][x] = 1;
++sum[x], ++sum[y];
}
for (int i = 1; i <= n; ++i) {
for (int j = i + 1; j <= n; ++j) {
if (e[i][j])
for (int k = 1; k <= n && k != i && k != j; ++k) {
if (e[k][i] && e[k][j])
ans = min(ans, sum[i] + sum[j] + sum[k] - 6);
}
}
}
printf("%d", ans == 0x3f3f3f3f ? -1 : ans);
return 0;
}