Problem:


Score : 700 points

Problem Statement

In the State of Takahashi in AtCoderian Federation, there are N cities, numbered 1, 2, ..., N.
M bidirectional roads connect these cities.
The i-th road connects City A_i and City B_i.
Every road connects two distinct cities.
Also, for any two cities, there is at most one road that directly connects them.

One day, it was decided that the State of Takahashi would be divided into two states, Taka and Hashi.
After the division, each city in Takahashi would belong to either Taka or Hashi.
It is acceptable for all the cities to belong Taka, or for all the cities to belong Hashi.
Here, the following condition should be satisfied:

Any two cities in the same state, Taka or Hashi, are directly connected by a road.

Find the minimum possible number of roads whose endpoint cities belong to the same state.
If it is impossible to divide the cities into Taka and Hashi so that the condition is satisfied, print -1.

Constraints

2 \leq N \leq 700

0 \leq M \leq N(N-1)/2

1 \leq A_i \leq N

1 \leq B_i \leq N

A_i \neq B_i

If i \neq j, at least one of the following holds: A_i \neq A_j and B_i \neq B_j.

If i \neq j, at least one of the following holds: A_i \neq B_j and B_i \neq A_j.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Print the answer.

Sample Input 1

5 5
1 2
1 3
3 4
3 5
4 5

Sample Output 1

4

For example, if the cities 1, 2 belong to Taka and the cities 3, 4, 5 belong to Hashi, the condition is satisfied.
Here, the number of roads whose endpoint cities belong to the same state, is 4.

Sample Input 2

5 1
1 2

Sample Output 2

-1

In this sample, the condition cannot be satisfied regardless of which cities belong to each state.

Sample Input 3

4 3
1 2
1 3
2 3

Sample Output 3

3

Sample Input 4

10 39
7 2
7 1
5 6
5 8
9 10
2 8
8 7
3 10
10 1
8 10
2 3
7 4
3 9
4 10
3 4
6 1
6 7
9 5
9 7
6 9
9 4
4 6
7 5
8 3
2 5
9 2
10 7
8 6
8 9
7 3
5 3
4 5
6 3
2 10
5 10
4 2
6 2
8 4
10 6

Sample Output 4

21



Sample input:
5 5
1 2
1 3
3 4
3 5
4 5


Sample output:
4

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
Bridges = [list(map(int, input().split())) for i in range(M)]

ans = float("inf")

for i in range(0, int((2**N)/2 + 2)):
    shu_list = [0] * (N - len(bin(i)[2:])) + [int(b) for b in bin(i)[2:]]
    taka = [l for l in range(1, N+1) if shu_list[l-1] == 1]
    hashi = [l for l in range(1, N+1) if shu_list[l-1] == 0]
    a = len(taka)
    h = len(hashi)
    if M < a*(a-1)/2 + h*(h-1)/2:
        continue
    else:
        taka_bridge = []
        hashi_bridge = []
        if a == 0:
            if M == a * (a - 1) / 2 + h * (h - 1) / 2:
                ans = min(ans, int(a * (a - 1) / 2 + h * (h - 1) / 2))
            else:
                continue
        elif a == 1:
            for b in Bridges:
                if b[0] in hashi and b[1] in hashi:
                    hashi_bridge.append(b[0])
                    hashi_bridge.append(b[1])
            if hashi == sorted(list(set(hashi_bridge)))\
                    and int(h * (h - 1)) / 2 == int(len(hashi_bridge) / 2):
                ans = min(ans, int(a * (a - 1) / 2 + h * (h - 1) / 2))
        elif a >= 2:
            for b in Bridges:
                if b[0] in taka and b[1] in taka:
                    taka_bridge.append(b[0])
                    taka_bridge.append(b[1])
                elif b[0] in hashi and b[1] in hashi:
                    hashi_bridge.append(b[0])
                    hashi_bridge.append(b[1])
            if taka == sorted(list(set(taka_bridge))) and hashi == sorted(list(set(hashi_bridge)))\
                    and int(a * (a - 1) / 2) == int(len(taka_bridge) / 2)\
                    and int(h * (h - 1) / 2) == int(len(hashi_bridge) / 2):
                ans = min(ans, int(a * (a - 1) / 2 + h * (h - 1) / 2))


if ans == float("inf"):
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M = map(int, input().split())
G0 = [set([i]) for i in range(N)]

A = set(range(N))

for i in range(M):
    a, b = map(int, input().split())
    G0[a-1].add(b-1)
    G0[b-1].add(a-1)

G = [A - g for g in G0]

b = 1
c = [-1]*N
for i in range(N):
    if c[i] != -1:
        continue
    p = 0; s = 0
    que = deque([i])
    c[i] = 0
    while que:
        v = que.popleft()
        s += 1
        if c[v] == 0:
            p += 1
        for w in G[v]:
            if c[w] == -1:
                c[w] = c[v]^1
                que.append(w)
            elif c[w] == c[v]:
                print(-1)
                exit(0)
    b |= (b << p) | (b << (s-p))

ans = 10**18
for i in range(N):
    if (b >> i) & 1:
        ans = min(ans, i*(i-1)//2 + (N-i)*(N-i-1)//2)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M = map(int, input().split())
G0 = [set([i]) for i in range(N)]

A = set(range(N))

for i in range(M):
    a, b = map(int, input().split())
    G0[a-1].add(b-1)
    G0[b-1].add(a-1)

G = [A - g for g in G0]

b = 1 << ((N+1)//2)
c = [-1]*N
for i in range(N):
    if c[i] != -1:
        continue
    p = 0; s = 0
    que = deque([i])
    c[i] = 0
    while que:
        v = que.popleft()
        s += 1
        if c[v] == 0:
            p += 1
        for w in G[v]:
            if c[w] == -1:
                c[w] = c[v]^1
                que.append(w)
            elif c[w] == c[v]:
                print(-1)
                exit(0)
    b |= (b >> p) | (b >> (s-p))

p = N//2 - ((b & -b).bit_length()-1)
q = N - p
print(p*(p-1)//2 + q*(q-1)//2)

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M = map(int, input().split())
G0 = [set([i]) for i in range(N)]

A = set(range(N))

for i in range(M):
    a, b = map(int, input().split())
    G0[a-1].add(b-1)
    G0[b-1].add(a-1)

G = [A - g for g in G0]

b = 1 << (N//2)
c = [-1]*N
for i in range(N):
    if c[i] != -1:
        continue
    p = 0; s = 0
    que = deque([i])
    c[i] = 0
    while que:
        v = que.popleft()
        s += 1
        if c[v] == 0:
            p += 1
        for w in G[v]:
            if c[w] == -1:
                c[w] = c[v]^1
                que.append(w)
            elif c[w] == c[v]:
                print(-1)
                exit(0)
    b |= (b >> p) | (b >> (s-p))

p = N//2 - ((b & -b).bit_length()-1)
q = N - p
print(p*(p-1)//2 + q*(q-1)//2)

Submission status: Wrong Answer

Solution code:
n, m = map(int, raw_input().split())
mat = [([0] * n) for i in range(n)]
for i in range(m):
  a, b = map(int, raw_input().split())
  mat[a-1][b-1] = 1
  mat[b-1][a-1] = 1
for i in range(n):
  mat[i][i] = 1

visit = []
i = 0
type_1 = set([i])
type_2 = set()
next_list = []
false_flag = True
while len(visit) < n and false_flag:
  for j in range(n):
    if mat[i][j] == 0:
      if (i in type_1 and j in type_1) or (i in type_2 and j in type_2):
        false_flag = False
        break
      else:
        if i in type_1:
          type_2.add(j)
        else:
          type_1.add(j)
        if j not in visit and j not in next_list:
          next_list.append(j)
  visit.append(i)
  if next_list:
    i = next_list.pop(0)
  else:
    for k in range(n):
      if k not in visit:
        i = k
        type_1.add(i)
        break
if not false_flag:
  print(-1)
else:
  total = 0
  for a in type_1:
    for b in type_2:
      if mat[a][b] == 1:
        total += 1
  print(m - total)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
from operator import itemgetter
N,M = map(int,input().split())
table=[[1]*N for i in range(N)]
for i in range(N):
    table[i][i]=0
for i in range(M):
    a,b=map(int,input().split())
    table[a-1][b-1]=0
    table[b-1][a-1]=0
visit=[False]*N
color =[-1]*N
def f(i):
    q=deque()
    q.append(i)
    color[i]=0
    visit[i]=True
    r=[0,0]
    r[0]+=1
    while q:
        x= q.popleft()
        for j in range(N):
            if table[x][j]==0:
                continue
            if visit[j]:
                if (color[x]==color[j]):
                    print(-1)
                    sys.exit()
                continue
            q.append(j)
            color[j]=(color[x]+1)%2
            r[color[j]]+=1
            visit[j]=True
    return r
ans=[]
for i in range(N):
    if not visit[i]:
        ans.append(f(i))
r=sorted(ans,reverse=True)
r=sorted(ans,reverse=True,key = itemgetter(1))
for i in range(1,len(ans)):
    if r[0][0]>r[0][1]:
        r[0][0]+=min(r[i][0],r[i][1])
        r[0][1]+=max(r[i][0],r[i][1])
    else:
        r[0][0]+=max(r[i][0],r[i][1])
        r[0][1]+=min(r[i][0],r[i][1])
def dou(k):
    return (k*(k-1))//2
print(dou(r[0][0]) + dou(r[0][1]))

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
from operator import itemgetter
N,M = map(int,input().split())
table=[[1]*N for i in range(N)]
for i in range(N):
    table[i][i]=0
for i in range(M):
    a,b=map(int,input().split())
    table[a-1][b-1]=0
    table[b-1][a-1]=0
visit=[False]*N
color =[-1]*N
def f(i):
    q=deque()
    q.append(i)
    color[i]=0
    visit[i]=True
    r=[0,0]
    r[0]+=1
    while q:
        x= q.popleft()
        for j in range(N):
            if table[x][j]==0:
                continue
            if visit[j]:
                if (color[x]==color[j]):
                    print(-1)
                    sys.exit()
                continue
            q.append(j)
            color[j]=(color[x]+1)%2
            r[color[j]]+=1
            visit[j]=True
    return r
ans=[]
for i in range(N):
    if not visit[i]:
        ans.append(f(i))
r=sorted(ans,reverse=True)
#r=sorted(ans,reverse=True,key = itemgetter(1))
for i in range(1,len(ans)):
    if [0][0]>r[0][1]:
        r[0][0]+=min(r[i][0],r[i][1])
        r[0][1]+=max(r[i][0],r[i][1])
    else:
        r[0][0]+=max(r[i][0],r[i][1])
        r[0][1]+=min(r[i][0],r[i][1])
def dou(k):
    return (k*(k-1))//2
print(dou(r[0][0]) + dou(r[0][1]))

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
from operator import itemgetter
N,M = map(int,input().split())
table=[[1]*N for i in range(N)]
for i in range(N):
    table[i][i]=0
for i in range(M):
    a,b=map(int,input().split())
    table[a-1][b-1]=0
    table[b-1][a-1]=0
visit=[False]*N
color =[-1]*N
def f(i):
    q=deque()
    q.append(i)
    color[i]=0
    visit[i]=True
    r=[0,0]
    r[0]+=1
    while q:
        x= q.popleft()
        for j in range(N):
            if table[x][j]==0:
                continue
            if visit[j]:
                if (color[x]==color[j]):
                    print(-1)
                    sys.exit()
                continue
            q.append(j)
            color[j]=(color[x]+1)%2
            r[color[j]]+=1
            visit[j]=True
    return r
ans=[]
for i in range(N):
    if not visit[i]:
        ans.append(f(i))
ans=sorted(ans,reverse=True)
r=sorted(ans,reverse=True,key = itemgetter(1))
for i in range(1,len(ans)):
    if [0][0]>r[0][1]:
        r[0][0]+=min(r[i][0],r[i][1])
        r[0][1]+=max(r[i][0],r[i][1])
    else:
        r[0][0]+=max(r[i][0],r[i][1])
        r[0][1]+=min(r[i][0],r[i][1])
def dou(k):
    return (k*(k-1))//2
print(dou(r[0][0]) + dou(r[0][1]))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq

# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7

def solve(f):
    n, m = f.read_int_list()
    g = collections.defaultdict(list)
    for _ in xrange(m):
        a, b = f.read_int_list()
        g[a].append(b)
        g[b].append(a)

    both = set()
    a = set()
    b = set()
    for i in xrange(1,n+1):
        if len(g[i]) == n-1:
            both.add(i)
        else:
            if i in a:
                for j in xrange(1,n+1):
                    if i != j and j not in g[i]:
                        b.add(j)
            else:
                for j in xrange(1,n+1):
                    if i != j and j not in g[i]:
                        a.add(j)

    for i in xrange(1,n+1):
        if i in a and i in b:
            return -1

    ans = float('inf')
    na = len(a)
    nb = len(b)
    nboth = len(both)
    for i in xrange(len(both)+1):
        ans = min(ans, (na+i)*(na+i-1)/2 + (nb+nboth-i)*(nb+nboth+i-1)/2)

    return ans


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case #%d\n"%f.case, solve(f)
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M = map(int,input().split())
link = {}
for i in range(1,N+1):
    link[i] = [j for j in range(1,N+1) if j!=i]
for i in range(M):
    a,b = map(int,input().split())
    link[a].remove(b)
    link[b].remove(a)
clusters=[]
visited = set()
queue = deque()
for s in range(1,N+1):
    if s in visited:
        continue
    queue.appendleft(s)
    visited.add(s)
    clusterNum = {}
    clusterNum[0] = 0
    clusterNum[1] = 1
    parity = {}
    parity[s] = 1

    while queue:
        v = queue.pop()
        #print("Searching: " + str(v))
        #print("Parity = " + str(parity[v]))
        for w in link[v]:
            #print("Link: " + str(w))
            if w not in visited:
                #print("First visit: " + str(w))
                parity[w] = 1^parity[v]
                queue.appendleft(w)
                visited.add(w)
                clusterNum[parity[w]] += 1
            else:
                #print("Already visited: " + str(w))
                #print("Parity = " + str(parity[w]))
                if parity[w] == parity[v]:
                    print(-1)
                    exit()
    clusters.append((clusterNum[0],clusterNum[1]))
print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M = map(int,input().split())
link = {}
for i in range(1,N+1):
    link[i] = [j for j in range(1,N+1) if j!=i]
for i in range(M):
    a,b = map(int,input().split())
    link[a].remove(b)
    link[b].remove(a)
clusters=[]
visited = set()
queue = deque()
for s in range(1,N+1):
    if s in visited:
        continue
    queue.appendleft(s)
    visited.add(s)
    clusterNum = {}
    clusterNum[0] = 0
    clusterNum[1] = 1
    parity = {}
    parity[s] = 1

    while queue:
        v = queue.pop()
        #print("Searching: " + str(v))
        #print("Parity = " + str(parity[v]))
        for w in link[v]:
            #print("Link: " + str(w))
            if w not in visited:
                #print("First visit: " + str(w))
                parity[w] = 1^parity[v]
                queue.appendleft(w)
                visited.add(w)
                clusterNum[parity[w]] += 1
            else:
                #print("Already visited: " + str(w))
                #print("Parity = " + str(parity[w]))
                if parity[w] == parity[v]:
                    print(-1)
                    exit()
    clusters.append((clusterNum[0],clusterNum[1]))

#可能な州の数を計算するためのナップザックDP
lenDP = len(clusters) + 1
dp = [[0]*lenDP for _ in range(N+1)]
for i in range(lenDP):
    dp[0][i] = 1
for S in range(1,N+1):
    for j in range(1,lenDP):
        patterns = []
        diff0 = S - clusters[j-1][0]
        diff1 = S - clusters[j-1][1]
        if diff0 >= 0:
            patterns.append(dp[diff0][j-1])
        if diff1 >= 0:
            patterns.append(dp[diff1][j-1])
        dp[S][j] = sum(patterns)
#print(clusters)

#最大値選択
for S in range(N+1):
    print(dp[S])
candidate = N+1
diff = N+1
for S in range(N+1):
    if dp[S][lenDP-1] > 0 and abs(N/2 - S) < diff:
        diff = abs(N/2 - S)
        candidate = S
S = candidate
ans = S*(S-1)//2 + (N-S)*(N-S-1)//2
#print(S)
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
from collections import defaultdict


def ii():
    return int(input())


def lii():
    return list(map(int, input().split(' ')))


def lvi(N):
    l = []
    for _ in range(N):
        l.append(ii())
    return l


def lv(N):
    l = []
    for _ in range(N):
        l.append(input())
    return l


class UnionFind(object):

    def __init__(self, n):
        # 親のnodeを表す
        self.par = [i for i in range(n)]

    def root(self, x):
        if self.par[x] == x:
            return x
        else:
            # 経路圧縮
            self.par[x] = self.root(self.par[x])
            return self.par[x]

    def same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return

        self.par[x] = y



class UnionFindRankCount(UnionFind):

    def __init__(self, n):
        UnionFind.__init__(self, n)

        self.rank = [0 for _ in range(n)]
        self.count = [1 for _ in range(n)]

    def union(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.count[y] += self.count[x]
        else:
            self.par[y] = x
            self.count[x] += self.count[y]
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1


def graph_coloring(G):
    N = len(G)
    color = np.array([0 for _ in range(N)])

    def dfs(v, c):
        """
        :param v: node
        :param c: color (1 or -1)
        :return:
        """
        color[v] = c
        for j in range(N):
            if G[v, j] == 1:
                if color[j] == c:
                    # 隣が同じ色
                    return False
                elif color[j] == 0:
                    # まだ塗ってなければ塗る
                    if not dfs(j, c * -1):
                        return False

        # 全ての頂点を塗れた
        return True

    # # グラフが連結でない
    # for i in range(N):
    #     if color[i] == 0:
    #         if not dfs(i, 1):
    #             return None  # impossible

    # 連結の前提
    if not dfs(0, 1):
        return None

    return color


def c2(n):
    return n * (n-1) // 2


def partial_sum(integer_list, target_sum, i=0, sum_=0):
    if target_sum < sum_:
        return False

    if i == len(integer_list):
        return sum_ == target_sum

    if partial_sum(integer_list, target_sum, i + 1, sum_):
        return True

    if partial_sum(integer_list, target_sum, i + 1, sum_ + integer_list[i]):
        return True

    return False


def partial_sum_list(integer_list):
    B = sum(integer_list)
    N = len(integer_list)
    dp = np.zeros([N, B+1])
    dp[0][integer_list[0]] = 1

    for v in range(1, N):
        for b in range(B+1):
            w = integer_list[v]
            if dp[v-1, b]:
                dp[v, b] += dp[v-1, b]
                dp[v, b+w] += dp[v-1, b]

    return dp[-1]


def main(G):
    G = 1 - G  # 補グラフ

    u = UnionFindRankCount(N)
    for i in range(N):
        for j in range(i, N):
            if G[i, j]:
                u.union(i, j)

    d = defaultdict(list)
    for n in range(N):
        d[u.par[n]].append(n)

    base = 0
    int_list = []
    # print(G, d)
    for s in d.values():
        Gs = np.array(G[s][:, s])
        color = graph_coloring(Gs)

        if color is None:
            return -1

        p = len(color[color == 1])
        q = len(color) - p

        base += min(p, q)
        diff = max(p, q) - min(p, q)
        if diff > 0:
            int_list.append(diff)

    if int_list:
        res = partial_sum_list(int_list)

        for s in range(sum(int_list) // 2, sum(int_list)+1):
            if res[s]:
                return c2(base + s) + c2(N - base - s)

    else:
        return c2(base) * 2


def generate_graph2(N, M):
    l = []
    G = np.eye(N)
    for i in range(N):
        for j in range(i+1, N):
            if np.random.rand() <= 0.5:
                l.append([i, j])
            else:
                l.append([j, i])

    c = np.random.choice(range(len(l)), size=M, replace=False)
    for v in c:
        i, j = l[v]
        G[i, j] = 1
        G[j, i] = 1

    return G


if __name__ == '__main__':
    N, M = lii()
    G = np.eye(N)

    for _ in range(M):
        x, y = lii()
        G[x-1, y-1] = 1
        G[y-1, x-1] = 1
    print(main(G))
    #
    # for i in range(10000):
    #     N = np.random.randint(3, 4)
    #     M = np.random.randint(c2(N) - N, c2(N))
    #     G = generate_graph2(N, M)
    #     print(N, M, main(G), G)

Submission status: Wrong Answer

Solution code:
# E
from collections import deque
import numpy as np

N, M = map(int, input().split())
G = dict()
for i in range(1, N+1):
    G[i] = dict()
    for j in range(1, N+1):
        if i != j:
            G[i][j] = 1
            
for _ in range(M):
    a, b = map(int, input().split())
    _ = G[a].pop(b)
    _ = G[b].pop(a)
    
res_con = []

done_list = [1] + [0]*N



core = 1

while core != 0:
    
    # BFS
    queue = deque([core])    
    res_flag = True
    
    size_a = 1
    size_b = 0

    done_list[core] = 1
    while len(queue) > 0:
        a = queue.popleft()
        for b in G[a].keys():
            if done_list[b] == done_list[a]:
                res_flag = False
                break
            elif done_list[b] == 0:
                done_list[b] = -1*done_list[a]
                if done_list[a] == 1:
                    size_b += 1
                else:
                    size_a += 1
                queue.append(b)
    
    res_con.append([size_a, size_b])
    
        
    if res_flag == False:
        break
        
    
    core = 0
    for i in range(1, N+1):
        if done_list[i] == 0:
            core = i
            break
            
# summarize
if res_flag == False:
    res = 0
else:
    res_can_s = np.array([0])
    for rr in res_con:
        a = rr[0]
        b = rr[1]
        res_can_s = np.unique(np.concatenate([res_can_s + a, res_can_s + b]))
    res = ((res_can_s*(res_can_s - 1) // 2) + ((N - res_can_s)*(N - res_can_s + 1) // 2)).min()

if res_flag == False:
    print(-1)
else:
    print(res)

Submission status: Wrong Answer

Solution code:
import numpy as np
from collections import defaultdict


def ii():
    return int(input())


def lii():
    return list(map(int, input().split(' ')))


def lvi(N):
    l = []
    for _ in range(N):
        l.append(ii())
    return l


def lv(N):
    l = []
    for _ in range(N):
        l.append(input())
    return l


class UnionFind(object):

    def __init__(self, n):
        # 親のnodeを表す
        self.par = [i for i in range(n)]

    def root(self, x):
        if self.par[x] == x:
            return x
        else:
            # 経路圧縮
            self.par[x] = self.root(self.par[x])
            return self.par[x]

    def same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return

        self.par[x] = y



class UnionFindRankCount(UnionFind):

    def __init__(self, n):
        UnionFind.__init__(self, n)

        self.rank = [0 for _ in range(n)]
        self.count = [1 for _ in range(n)]

    def union(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.count[y] += self.count[x]
        else:
            self.par[y] = x
            self.count[x] += self.count[y]
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1


def graph_coloring(G):
    N = len(G)
    color = np.array([0 for _ in range(N)])

    def dfs(v, c):
        """
        :param v: node
        :param c: color (1 or -1)
        :return:
        """
        color[v] = c
        for j in range(N):
            if G[v, j] == 1:
                if color[j] == c:
                    # 隣が同じ色
                    return False
                elif color[j] == 0:
                    # まだ塗ってなければ塗る
                    if not dfs(j, c * -1):
                        return False

        # 全ての頂点を塗れた
        return True

    # # グラフが連結でない
    # for i in range(N):
    #     if color[i] == 0:
    #         if not dfs(i, 1):
    #             return None  # impossible

    # 連結の前提
    if not dfs(0, 1):
        return None

    return color


def c2(n):
    return n * (n-1) // 2


def partial_sum(integer_list, target_sum, i=0, sum_=0):
    if target_sum < sum_:
        return False

    if i == len(integer_list):
        return sum_ == target_sum

    if partial_sum(integer_list, target_sum, i + 1, sum_):
        return True

    if partial_sum(integer_list, target_sum, i + 1, sum_ + integer_list[i]):
        return True

    return False


def partial_sum_list(integer_list):
    B = sum(integer_list)
    N = len(integer_list)
    dp = np.zeros([N, B+1])
    dp[0][integer_list[0]] = 1

    for v in range(1, N):
        for b in range(B+1):
            w = integer_list[v]
            if dp[v-1, b]:
                dp[v, b] += dp[v-1, b]
                dp[v, b+w] += dp[v-1, b]

    return dp[-1]


def main(G):
    G = 1 - G  # 補グラフ

    u = UnionFindRankCount(N)
    for i in range(N):
        for j in range(i, N):
            if G[i, j]:
                u.union(i, j)

    d = defaultdict(list)
    for n in range(N):
        d[u.par[n]].append(n)

    base = 0
    int_list = []
    # print(G, d)
    for s in d.values():
        Gs = np.array(G[s][:, s])
        color = graph_coloring(Gs)

        if color is None:
            return -1

        p = len(color[color == 1])
        q = len(color) - p

        base += min(p, q)
        diff = max(p, q) - min(p, q)
        if diff > 0:
            int_list.append(diff)

    if int_list:
        res = partial_sum_list(int_list)

        for s in range(sum(int_list) // 2, sum(int_list)):
            if res[s]:
                return c2(base + s) + c2(N - base - s)

    else:
        return c2(base) * 2


def generate_graph2(N, M):
    l = []
    G = np.eye(N)
    for i in range(N):
        for j in range(i+1, N):
            if np.random.rand() <= 0.5:
                l.append([i, j])
            else:
                l.append([j, i])

    c = np.random.choice(range(len(l)), size=M, replace=False)
    for v in c:
        i, j = l[v]
        G[i, j] = 1
        G[j, i] = 1

    return G


if __name__ == '__main__':
    N, M = lii()
    G = np.eye(N)

    for _ in range(M):
        x, y = lii()
        G[x-1, y-1] = 1
        G[y-1, x-1] = 1
    print(main(G))

    # for i in range(10000):
    #     N = np.random.randint(2, 500)
    #     M = np.random.randint(c2(N) - N, c2(N))
    #     G = generate_graph2(N, M)
    #     print(N, M, main(G))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import numpy as np

class Impossible(ValueError):
    pass

def main():
    n, m, am, bm = read()
    c_adj_mat = get_c_adj_mat(n, m, am, bm)
    try:
        color = get_color(n, m, c_adj_mat)
        print(min_cut(color, n))
    except Impossible:
        print(-1)

def min_cut(color, n):
    cnts = [0, 0, 0]
    for c in color:
        assert c in [-1, 0, 1]
        cnts[c + 1] += 1
    smaller = min(n // 2, min(cnts[0], cnts[2]) + cnts[1])
    larger = n - smaller
    res = smaller * (smaller - 1) // 2
    res += larger * (larger - 1) // 2
    return res

def get_c_adj_mat(n, m, am, bm):
    c_adj_mat = [[False for i in range(n)] for j in range(n)]
    for i in range(n):
        c_adj_mat[i][i] = True
    for k in range(m):
        a0 = am[k] - 1
        b0 = bm[k] - 1
        c_adj_mat[a0][b0] = c_adj_mat[b0][a0] = True
    return np.invert(np.array(c_adj_mat))

def get_color(n, m, c_adj_mat):
    color = [0 for i in range(n)]
    if not np.any(c_adj_mat):
        return color
    flag = False
    for i in range(n):
        for j in range(n):
            if c_adj_mat[i, j]:
                flag = True
                break
        if flag:
            break
    assert flag
    color[i] = 1
    dfs(color, i, c_adj_mat, n)
    return color

def dfs(color, i, c_adj_mat, n):
    assert color[i] in [-1, 1]
    for j in range(n):
        if not c_adj_mat[i, j]:
            continue
        if j == i:
            continue
        if color[j] * color[i] == -1:
            continue
        elif color[j] * color[i] == 1:
            raise Impossible
        else:
            color[j] = -color[i]
            dfs(color, j, c_adj_mat, n)

def read():
    n, m = map(int, input().split())
    am = []
    bm = []
    for i in range(m):
        a, b = map(int, input().split())
        am.append(a)
        bm.append(b)
    return n, m, am, bm

main()

Submission status: Wrong Answer

Solution code:
from copy import deepcopy
import itertools
from bisect import bisect_left
from bisect import bisect_right
import math
from collections import deque


def read():
    return int(input())


def readmap():
    return map(int, input().split())


def readlist():
    return list(map(int, input().split()))


N, M = readmap()
group = [0] * (N+1)  # 0 未定 1, 2 確定  # index 0 は使わない
edge_exists = [[False] * (N + 1) for _ in range(N + 1)]  # index 0 は使わない
for i in range(N+1):
    edge_exists[i][i] = True

A = []
B = []
for _ in range(M):
    a, b = readmap()
    A.append(a)
    B.append(b)
    edge_exists[a][b] = True
    edge_exists[b][a] = True

if M == N * (N - 1) // 2:
    n = N // 2
    print(n*(n-1) // 2 + (N-n)*(N-n-1) // 2)
    quit()

for i in range(1, N+1):
    if all(edge_exists[i][1:]):
        pass
    else:
        group[i] = 1
        break

q = deque()
q.append(i)
while q:
    v = q.popleft()
    for w in range(1, N+1):
        if not edge_exists[v][w] and v != w:
            if group[w] != 0:
                if group[v] == group[w]:
                    print(-1)
                    quit()
                else:
                    pass
            else:
                group[w] = 3 - group[v]
                q.append(w)

num0 = group.count(0) - 1
num1 = group.count(1)
num2 = group.count(2)

while num0:
    if num1 <= num2:
        num1 += 1
        num0 -= 1
    else:
        num2 += 1
        num0 -= 1

print(num1*(num1-1)//2 + num2*(num2-1)//2)