574B - Bear and Three Musketeers - CodeForces Solution


brute force dfs and similar graphs hashing *1500

Please click on ads to support us..

Python Code:

n, m=[int(k) for k in input().split()]
w=[]
for j in range(m):
    w.append([int(k) for k in input().split()])
q={}
rho={}
for j in range(m):
    if w[j][0] in q:
        q[w[j][0]].append(w[j][1])
    else:
        q[w[j][0]]=[w[j][1]]
    if w[j][1] in q:
        q[w[j][1]].append(w[j][0])
    else:
        q[w[j][1]]=[w[j][0]]
for j in q.keys():
    rho[j]=set(q[j])
c={}
for j in q.keys():
    c[j]=len(q[j])
mn=10**100
for j in q.keys():
    for k in range(c[j]-1):
        for l in range(k, c[j]):
            if q[j][k] in rho[q[j][l]]:
                mn=min(mn, c[j]+c[q[j][k]]+c[q[j][l]])

if mn>=10**100:
    print(-1)
else:
    print(mn-2*3)

C++ Code:

#include <bits/stdc++.h>

using namespace std;

#define       TASK  "TEST"
#define       lint  long long int
#define      sz(v)  (int(v.size()))
#define    ynif(c)  cout << ((c) ? "YES\n" : "NO\n")
#define     all(v)  v.begin(), v.end()
#define    rall(v)  v.rbegin(), v.rend()
#define    exetime  cerr << "Time elapsed: " << (1.0 * clock() / CLOCKS_PER_SEC) << "s"

bool know[4043][4043];
int n, m, deg[4043], u, v, Z;
vector <int> a[4043];

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    if (fopen(TASK".INP", "r")) {
        freopen(TASK".INP", "r", stdin);
        freopen(TASK".OUT", "w", stdout);
    }
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        cin >> u >> v;
        deg[u]++;
        deg[v]++;
        know[u][v] = know[v][u] = 1;
        a[u].push_back(v);
        a[v].push_back(u);
    }
    Z = -1;
    for (int i = 1; i <= n; i++)
        for (int j : a[i])
            for (int k : a[i])
                if (j != k && know[j][k]) {
                    int rec = deg[i] + deg[j] + deg[k] - 6;
                    if (Z == -1) Z = rec;
                    else Z = min(Z, rec);
                }
    cout << Z;
    return exetime, 0;
}


Comments

Submit
0 Comments
More Questions

124A - The number of positions
1041A - Heist
901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class
1107B - Digital root
25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies
1651C - Fault-tolerant Network
870A - Search for Pretty Integers
1174A - Ehab Fails to Be Thanos
1169A - Circle Metro
780C - Andryusha and Colored Balloons
1153A - Serval and Bus
1487C - Minimum Ties
1136A - Nastya Is Reading a Book
1353B - Two Arrays And Swaps
1490E - Accidental Victory
1335A - Candies and Two Sisters
96B - Lucky Numbers (easy)
1151B - Dima and a Bad XOR
1435B - A New Technique
1633A - Div 7
268A - Games
1062B - Math
1294C - Product of Three Numbers
749A - Bachgold Problem
1486B - Eastern Exhibition