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: Accepted

Solution code:
import queue
N,M=map(int,input().split())
G=[[1 for i in range(N)] for i in range(N)]
H=[[] for i in range(N)]
for i in range(N):
    G[i][i]-=1
for i in range(M):
    a,b=map(int,input().split())
    G[a-1][b-1]-=1
    G[b-1][a-1]-=1
for i in range(N):
    for j in range(N):
        if G[i][j]==1:
            H[i].append(j)
A=[[[],[]]]
k=0
q=queue.Queue()
reached=[0 for i in range(N)]
dist=[-1 for i in range(N)]
for i in range(N):
    if reached[i]==1:
        continue
    q.put(i)
    reached[i]=1
    dist[i]=0
    while(not(q.empty())):
        r=q.get()
        A[k][dist[r]].append(r)
        for p in H[r]:
            if reached[p]==0:
                q.put(p)
                dist[p]=(dist[r]+1)%2
                reached[p]=1
    k+=1
    A.append([[],[]])
for i in range(k):
    for j in range(2):
        for x in A[i][j]:
            for y in A[i][j]:
                if x==y:
                    continue
                if G[x][y]==1:
                    print(-1)
                    exit()
B=[]
for i in range(k):
    B.append((len(A[i][0]),len(A[i][1])))
dp=[[0 for i in range(N+1)] for i in range(k+1)]
dp[0][0]=1
for i in range(1,k+1):
    for j in range(N+1):
        if dp[i-1][j]==0:
            continue
        dp[i][j+B[i-1][0]]=1
        dp[i][j+B[i-1][1]]=1
delta=N
for i in range(N+1):
    if dp[k][i]==1:
        tmp=abs(N-2*i)
        if tmp<delta:
            delta=tmp
X=(N+delta)//2
Y=(N-delta)//2
print((X*(X-1)+Y*(Y-1))//2)

Submission status: Accepted

Solution code:
from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect
 
def read():
  return int(input())
 
def reads():
  return [int(x) for x in input().split()]

N, M = reads()
orig_edges = set()
for _ in range(M):
  A, B = reads()
  A, B = A-1, B-1
  orig_edges.add((A, B))
  orig_edges.add((B, A))

edges = [[] for _ in range(N)]
for A, B in combinations(range(N), 2):
  if (A, B) not in orig_edges:
    edges[A].append(B)
    edges[B].append(A)

remain = set(range(N))
color = [-1] * N

def walk(u, c, ctr, remain):
  if u in remain:
    remain.remove(u)
  if color[u] >= 0:
    if color[u] != c:
      print(-1); exit()
    return ctr

  color[u] = c; ctr[c] += 1
  for v in edges[u]:
    walk(v, 1-c, ctr, remain)
  return ctr

ps = []
while len(remain) > 0:
  s = remain.pop()
  p = walk(s, 0, [0, 0], remain)
  ps.append(p)

dp = set([0])
for a, b in ps:
  d = b - a
  dp = {x - d for x in dp} | {x + d for x in dp}
m = min(abs(x) for x in dp)
a, b = (N + m) // 2, (N - m) // 2
print(a*(a-1)//2 + b*(b-1)//2)

Submission status: Accepted

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))
#print(ans)
dp=[set() for i in range(len(ans)+1)]
dp[0].add(0)
L=N//2+1
for i in range(1,len(ans)+1):
    for a in dp[i-1]:
        if a+ans[i-1][0]<L:
            dp[i].add(a+ans[i-1][0])
        if a+ans[i-1][1]<L:
            dp[i].add(a+ans[i-1][1])
    #print(dp)
s = max(dp[len(ans)])
def dou(k):
    return (k*(k-1))//2
print(dou(s) + dou(N-s))

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
ROAD=[None]*M

for i in range(M):
    ROAD[i]=tuple(sorted(list(map(int,input().split()))))
  
import itertools

NOROAD=list(itertools.combinations(range(1,N+1),2))

NOROAD=set(NOROAD) - set(ROAD)

Group=[[i,[]] for i in range(N+1)]

def find(x):
    while Group[x][0] != x:
        x=Group[x][0]
    return x


for i in NOROAD:
    a,b=i
    #print(a,b)
    Group[a][1]+=[b]
    Group[b][1]+=[a]

    if find(a) != find(b):
        Group[find(a)][0]=min(find(a),find(b))
        Group[find(b)][0]=min(find(a),find(b))
        Group[a][0]=min(find(a),find(b))
        Group[b][0]=min(find(a),find(b))

GroupSORT=[[i,j[1]] for i,j in enumerate(Group)]
GroupSORT.sort(key=lambda x:len(x[1]))
NUMBERING=[[find(i),"none"] for i in range(N+1)]
CHECK=[0 for i in range(N+1)]

for i in range(N):
    if CHECK[find(GroupSORT[i][0])]==0:
        
        NUMBERING[GroupSORT[i][0]][1]=0
        CHECK[find(GroupSORT[i][0])]=1

CONDITION=1
#print(NUMBERING)


repeat_condition=1
while repeat_condition==1:

    repeat_condition=0

    for i in range(1,N+1):
        if NUMBERING[i][1]==0:
            for j in Group[i][1]:
                if NUMBERING[j][1]==0:
                    CONDITION=0
                    break
                elif NUMBERING[j][1]=="none":
                    NUMBERING[j][1]=1
                    repeat_condition=1

        if NUMBERING[i][1]==1:
            for j in Group[i][1]:
                if NUMBERING[j][1]==1:
                    CONDITION=0
                    break
                elif NUMBERING[j][1]=="none":
                    NUMBERING[j][1]=0
                    repeat_condition=1


import sys
if CONDITION==0:
    print(-1)
    sys.exit()

NUMBERS=set()
for i in range(1,len(NUMBERING)):
    NUMBERS=NUMBERS|{NUMBERING[i][0]}

count=[]
for i in NUMBERS:
    count+=[(i,NUMBERING.count([i,0]),NUMBERING.count([i,1]))]

DP=[set() for i in range(len(count))]
DP[0]={count[0][1],count[0][2]}

for i in range(1,len(count)):
    for k in DP[i-1]:
        DP[i]=DP[i]|{k+count[i][1],k+count[i][2]}

DIVIDE=list(DP[len(count)-1])
#print(DIVIDE)
for i in range(len(DIVIDE)):
    DIVIDE[i]=abs(DIVIDE[i]-N/2)

x=int(min(DIVIDE)+N/2)

print(x*(x-1)//2+(N-x)*(N-x-1)//2)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)

N,M = map(int,input().split())
es = [tuple(map(lambda x:int(x)-1,input().split())) for i in range(M)]
gr = [[0 for j in range(N)] for i in range(N)]
for a,b in es:
    gr[a][b] = gr[b][a] = 1
compgr = [[] for i in range(N)]
for i in range(N-1):
    for j in range(i+1,N):
        if gr[i][j]: continue
        compgr[i].append(j)
        compgr[j].append(i)

colors = [0] * N
def dfs(v,color):
    colors[v] = color
    b,w = (1,0) if color==1 else (0,1)
    for to in compgr[v]:
        if colors[to] == color:
            print(-1)
            exit()
        elif colors[to] == 0:
            db,dw = dfs(to, -color)
            b += db
            w += dw
    return [b,w]

dp = set([0])
for i in range(N):
    if colors[i] != 0: continue
    b,w = dfs(i,1)
    dp2 = set()
    for n in dp:
        dp2.add(n+b)
        dp2.add(n+w)
    dp = dp2

ans = N*N
for a in dp:
    b = N-a
    tmp = a*(a-1)//2 + b*(b-1)//2
    ans = min(ans, tmp)
print(ans)

Submission status: Accepted

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: Accepted

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+1):
    if (b >> i) & 1:
        ans = min(ans, i*(i-1)//2 + (N-i)*(N-i-1)//2)
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Graph:
    def __init__(self, nvert, edges):
        self.adj = [[False] * nvert for i in range(nvert)]
        for e in edges:
            u, v = e
            self.adj[u][v] = True
            self.adj[v][u] = True

    def __str__(self):
        return str(self.adj)

    # 節点数
    def nvertices(self):
        return len(self.adj)

    # 補グラフ
    def complement(self):
        nv = len(self.adj)
        g  = Graph(nv, [])
        for u in range(nv):
            for v in range(nv):
                if u == v: continue
                g.adj[u][v] = not self.adj[u][v]
                g.adj[v][u] = not self.adj[v][u]
        return g

    # 連結成分であるグラフのリスト
    def connectedcomps(self):
        self.visited = [False] * self.nvertices()
        ccs = []
        for v in range(self.nvertices()):
            if not self.visited[v]:
                vs = []
                self.__connectedcomp(v, vs)
                cc = self.inducedsubgraph(vs)
                ccs.append(cc)
        self.visited = None
        return ccs

    # vを含む連結成分 (節点のリスト)
    def __connectedcomp(self, v, vs):
        if self.visited[v]: return
        self.visited[v] = True
        vs.append(v)
        for u in range(self.nvertices()):
            if self.adj[v][u]:
                self.__connectedcomp(u, vs)

    # 誘導部分グラフ
    def inducedsubgraph(self, vs):
        n = len(vs)
        # [3, 1, 4] -> {3:0, 1:1, 4:2}
        m = {}
        for i in range(n):
            m[vs[i]] = i

        sg = Graph(n, [])
        for v in vs:
            for u in range(self.nvertices()):
                if self.adj[v][u]:
                    sg.adj[m[v]][m[u]] = True
                    sg.adj[m[u]][m[v]] = True
        return sg

    # 2部グラフならば2グループの各節点数の組。2部グラフでなければFalse
    # 組を返すときは(大,小)の順
    def isbipartite(self):
        self.color = [None] * self.nvertices()
        self.color[0] = 0
        if not self.__isbipartite(0):
            return False
        m = sum(1 for c in self.color if c == 0)
        n = sum(1 for c in self.color if c == 1)
        assert m + n == self.nvertices()
        return (max(m, n), min(m, n))

    def __isbipartite(self, v):
        for u in range(self.nvertices()):
            if self.adj[v][u]:
                if self.color[u] == None:
                    self.color[u] = 1 - self.color[v]
                    if not self.__isbipartite(u):
                        return False
                elif self.color[u] != 1 - self.color[v]:
                    return False
        return True


# 入力
N, M = [int(w) for w in input().split()]
edges = []
for i in range(M):
    a, b = [int(w) for w in input().split()]
    edges.append((a - 1, b - 1))

# 入力されたグラフの補グラフ g が2部グラフ
g = Graph(N, edges).complement()
ccs = g.connectedcomps()
bs  = [cc.isbipartite() for cc in ccs]
if not all(bs):
    print(-1)
    exit()

# (連結成分が複数ある場合),
# 2グループの節点数の差が最小となるような分け方を求める
diffs = [t[0] - t[1] for t in bs]
sums = {0}
for d in diffs:
    newsums = set()
    for s in sums:
        newsums.add(s + d)
    sums.update(newsums)

halfdiff = sum(diffs)/2
nearlyhalfdiff = min((abs(s - halfdiff), s) for s in sums)[1]

# 節点数の差を最小にすると，その差はdiffになる
diff = abs(sum(diffs) - 2 * nearlyhalfdiff)

# グループの節点数 (x, y)
x = (N - diff) // 2
y = N - x

# 完全グラフの辺数
x = x * (x - 1) // 2
y = y * (y - 1) // 2

print(x + y)

Submission status: Accepted

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 = {}
    for i in xrange(1, n+1):
        g[i] = set(range(1, n+1))
        g[i].remove(i)
    for _ in xrange(m):
        a, b = f.read_int_list()
        g[a].remove(b)
        g[b].remove(a)

    c = [0]*(n+1)

    def dfs(v, ci):
        if c[v] == ci: return True
        if c[v] != 0 and c[v] != ci: return False
        c[v] = ci
        res = True
        for vi in g[v]:
            res &= dfs(vi, -ci)
        return res

    for i in xrange(1, n+1):
        if c[i] == 0:
            res = dfs(i, i)
            if not res: return -1

    cnt = collections.Counter(c[1:])
    grp = []
    for i in xrange(1,n+1):
        if cnt[i] > 0 or cnt[-i] > 0:
            grp.append((cnt[i], cnt[-i]))

    dp = [False] * (n+1)
    dp[0] = True
    for i,j in grp:
        dp2 = dp[:]
        for k in xrange(n+1):
            if dp[k]:
                dp2[k+i] = True
                dp2[k+j] = True
                if i > 0 and j > 0: dp2[k] = False
        dp = dp2

    ans = float('inf')
    for i in xrange(n+1):
        if dp[i]: ans = min(ans, i*(i-1)/2+(n-i)*(n-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: Accepted

Solution code:
import sys
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 = [False] * n
color = [-1] * n

def f(i):
  r = [1, 0]
  next_list = [i]
  color[i] = 0
  while next_list:
    i = next_list.pop(0)
    visit[i] = True
    for j in range(n):
      if mat[i][j] == 0:
        if color[i] == color[j]:
          print(-1)
          sys.exit()
          break
        else:
          if color[j] == -1:
            color[j] = 1 - color[i]
            r[color[j]] += 1
            next_list.append(j)
  return r

def dou(k):
    return (k*(k-1))//2
ans = []
for i in range(n):
  if not visit[i]:
    ans.append(f(i))

r=sorted(ans, reverse=True)
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])
print(dou(r[0][0]) + dou(r[0][1]))

Submission status: Accepted

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: Accepted

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: Accepted

Solution code:
def dfs(links, fixed, s):
    q = [(s, 0)]
    cnt = [0, 0]
    while q:
        v, c = q.pop()
        if fixed[v] > -1:
            if fixed[v] != c:
                return False
            continue
        fixed[v] = c
        cnt[c] += 1
        for u in links[v]:
            q.append((u, c ^ 1))
    return (max(cnt), min(cnt))


def is_bipartite(n, links):
    fixed = [-1] * n
    l, r = 0, 0
    can = []
    for i in range(n):
        if fixed[i] > -1:
            continue
        cnt = dfs(links, fixed, i)
        if cnt == False:
            return -1
        can.append(cnt)

    can.sort(reverse=True)
    for cnt in can:
        j = 0 if cnt[0] > cnt[1] else 1
        if l > r:
            j ^= 1
        l += cnt[j]
        r += cnt[j ^ 1]
    return (l * (l - 1) + r * (r - 1)) // 2


n, m = map(int, input().split())
links = [set(range(n)) - {i} for i in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    links[a].remove(b)
    links[b].remove(a)
print(is_bipartite(n, links))

Submission status: Accepted

Solution code:
N,M = map(int,input().split())

E = [[False]*N for _ in range(N)]

for n in range(N):
  E[n][n] = True

for _ in range(M):
  a,b = map(int,input().split())
  a,b = a-1,b-1
  E[a][b] = True
  E[b][a] = True


unvisited = set(range(N))
color = [None]*N
components = []

while unvisited:
  v0 = next(iter(unvisited))
  count = [0,0]

  stack = [(v0,False)]
  while stack:
    v,c = stack.pop()
    if color[v] is None:
      color[v] = c
      unvisited.discard(v)
      count[c] += 1
      for u,f in enumerate(E[v]):
        if not f:
          stack.append((u, not c))

    elif color[v] != c:
      print(-1)
      exit()

  components.append(count)

# DP
L = N//2+1
dp = [False]*L


dp[0] = True

for a,b in components:
  ndp = [False]*L
  for i,f in enumerate(dp):
    if f:
      if i+a < L:
        ndp[i+a] = True
      if i+b < L:
        ndp[i+b] = True
  dp = ndp

for i,f in zip(reversed(range(L)), reversed(dp)):
  if f:
    break
j = N - i

print(i*(i-1)//2 + j*(j-1)//2)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,m = LI()
    a = [LI_() for _ in range(m)]
    ss = [set() for _ in range(n)]
    for b,c in a:
        ss[b].add(c)
        ss[c].add(b)
    ts = [set(list(range(n))) - set([_]) for _ in range(n)]
    for i in range(n):
        ts[i] -= ss[i]

    d = []
    u = set()
    for i in range(n):
        if i in u:
            continue
        ab = set([i])
        nb = set([i])
        ac = set()
        nc = set()
        f = True
        while f:
            f = False
            k = set()
            nc = set()
            for j in nb:
                nc |= ts[j]
            nc -= ac
            ac |= nc
            nb = set()
            for j in nc:
                nb |= ts[j]
            nb -= ab
            ab |= nb
            if nb:
                f = True
        if ab & ac:
            return -1
        d.append((len(ab),len(ac)))
        u |= ab
        u |= ac
    r = set([0])
    for b,c in d:
        t = set()
        for k in r:
            t.add(k+b)
            t.add(k+c)
        r = t
    rr = inf
    for t in r:
        nt = n - t
        if t == 0 or nt == 0:
            continue
        tr = t * (t-1) // 2
        tr += nt * (nt-1) // 2
        if rr > tr:
            rr = tr
    return rr


print(main())

Submission status: Runtime Error

Solution code:
def spl(target:set,connections:list):
    Agroup = set()
    Bgroup = set()

    for i in target:
        if i in connections[0]:
            Agroup.add(i)
        else:
            Bgroup.add(i)
    Bcon= set(target)
    for i in Bgroup:
        Bcon &= connections[i]
    

    if not Bgroup.issubset(Bcon):
        print(-1)
        return
    
    bconwith0 = Bcon - Bgroup

    Agroup -= bconwith0

    Acon= set(target)
    for i in Agroup:
        Acon &= connections[i]

    if not Agroup.issubset(Acon):
        print(-1)
        return

    while len(bconwith0) != 0:
        ns = set()
        for i in bconwith0:
            if i in Acon:
                if i in Bcon:
                    ns.add(i)
                else:
                    Agroup.add(i)
                    Acon &= connections[i]
            else:
                if i in Bcon:
                    Bgroup.add(i)
                    Bcon &= connections[i]
                else:
                    print(-1)
                    return
        
        if bconwith0.__len__() == ns.__len__():
            break
        bconwith0= ns
    return(Agroup,Bgroup,bconwith0)

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

def resolve():
    N,M = map(int,input().split())

    connections = [set([i]) for i in range(N)]
    for i in range(M):
        A,B = map(int,input().split())
        connections[A-1].add(B-1)
        connections[B-1].add(A-1)
    
    free  = set(range(N))
    lst = []
    while len(free) !=0:
        res =spl(free,connections)
        if res==None:
            raise
            return
        i,j,k = res
        lst.append((len(i),len(j),k))

        if free.__len__() == lst[-1][2].__len__():
            break
        free= lst[-1][2]
    dpt = set([(0,0)])
    for i,j,_ in  lst:
        ndp= set()
        for k,l in dpt:
            ndp.add(tuple(sorted((i+k,j+l))))
            ndp.add(tuple(sorted((j+k,i+l))))
        dpt = ndp
    freec = lst[-1][2].__len__()

    dpt = list(dpt)
    dpt.sort(reverse=True)
    mn = float("inf")
    for i,j in dpt:
        if i+freec > j:
            i = N//2
            j = (N+1)//2
        else:
            i += freec
        if i+j != N:
            raise
        mn = min(mn,c2(i)+c2(j))


    print(mn)

if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
N,M=map(int,input().split())
edge=[set([]) for i in range(N)]
for i in range(M):
    a,b=map(int,input().split())
    edge[a-1].add(b-1)
    edge[b-1].add(a-1)

cedge=[[] for i in range(N)]
for i in range(N):
    for j in range(N):
        if j not in edge[i] and j!=i:
            cedge[i].append(j)

ans=[]
def is_bipartgraph():
    color=[0]*N
    used=[False]*N
    for i in range(N):
        if not used[i]:
            stack=[(i,1)]
            black=0
            white=0
            while stack:
                v,c=stack.pop()
                used[v]=True
                color[v]=c
                black+=(c==1)
                white+=(c==-1)
                for nv in cedge[v]:
                    if color[nv]==color[v]:
                        return False
                    elif color[nv]==0:
                        stack.append((nv,-c))
            ans.append([black,white])
    return True

if is_bipartgraph():
    dp=[[False for i in range(0,N+1)] for j in range(len(ans))]
    a,b=ans[0]
    dp[0][a],dp[0][b]=True,True
    for i in range(1,len(ans)):
        a,b=ans[i]
        for j in range(0,N+1):
            test=False
            if j>=a:
                test=test|dp[i-1][j-a]
            if j>=b:
                test=test|dp[i-1][j-b]
            dp[i][j]=test
    ans=0
    for i in range(0,N+1):
        if dp[-1][i] and abs(ans-N/2)>abs(i-N/2):
            ans=i
    ans2=N-ans
    print(ans*(ans-1)//2+ans2*(ans2-1)//2)
else:
    print(-1)