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

Solution (Python):
import sys
input = sys.stdin.readline

N, M = map(int, input().split())
G = [set() for _ in range(N)]
for _ in range(M):
    A, B = map(int, input().split())
    A -= 1
    B -= 1
    G[A].add(B)
    G[B].add(A)

G_comp = [[] for _ in range(N)]
for i in range(N):
    for j in range(N):
        if i != j and j not in G[i]:
            G_comp[i].append(j)

color = [-1] * N
A = []
dp = set([0])
for i in range(N):
    if color[i] != -1:
        continue
    cnt = [1, 0]
    color[i] = 0
    stack = [i]
    while stack:
        v = stack.pop()
        for u in G_comp[v]:
            if color[u] == -1:
                color[u] = 1 - color[v]
                stack.append(u)
                cnt[color[u]] += 1
            if color[u] == color[v]:
                print(-1)
                exit()
    ndp = set()
    for a in dp:
        ndp.add(a + cnt[0])
        ndp.add(a + cnt[1])
    dp = ndp
ans = float('inf')
for a in dp:
    ans = min(ans, a * (a - 1) // 2 + (N - a) * (N - a - 1) // 2)
print(ans)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

class UnionFind:
    def __init__(self, n):
        self.state = [-1] * n
        self.size_table = [1] * n
        
        

    def root(self, u):
        v = self.state[u]
        if v < 0: return u
        self.state[u] = res = self.root(v)
        return res

    def merge(self, u, v):
        ru = self.root(u)
        rv = self.root(v)
        if ru == rv: return
        du = self.state[ru]
        dv = self.state[rv]
        if du > dv: ru, rv = rv, ru
        if du == dv: self.state[ru] -= 1
        self.state[rv] = ru
        
        self.size_table[ru] += self.size_table[rv]
        return

    
    def size(self, u):
        return self.size_table[self.root(u)]

def ng():
    for u in range(n):
        for v in range(n):
            if v == u: continue
            if to[u][v]: continue
            if uf.root(u)==uf.root(v):return True
    return False

n,m=MI()
to=[[False]*n for _ in range(n)]
for _ in range(m):
    u,v=MI1()
    to[u][v]=to[v][u]=True

uf=UnionFind(n)
uncon=[-1]*n
for u in range(n):
    pv=-1
    for v in range(n):
        if v==u:continue
        if to[u][v]:continue
        if pv==-1:pv=v
        else:uf.merge(pv,v)
    uncon[u]=pv





if ng():
    print(-1)
    exit()

fin=[False]*n
free=0
ss=[]
for u in range(n):
    if uncon[u]==-1:
        free+=1
        continue
    r0=uf.root(u)
    if fin[r0]:continue
    r1=uf.root(uncon[u])
    fin[r0]=fin[r1]=True
    ss.append(abs(uf.size_table[r0]-uf.size_table[r1]))
cur=1<<1000
for s in ss:cur=cur<<s|cur>>s
cur>>=1000
d=(cur&-cur).bit_length()-1
d=max(0,d-free)
s0=(n-d)//2
s1=n-s0
print(s0*(s0-1)//2+s1*(s1-1)//2)

Solution (Python):
n, m = map(int, input().split())
adjList = [[0] * n for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    adjList[a][b] = 1
    adjList[b][a] = 1
def applyComp(a):
    for i in range(len(a)):
        for j in range(len(a[i])):
            a[i][j] = 1 - a[i][j]
applyComp(adjList)

visited = [0] * n
def dfs(u, parent=-1, color=1):
    if visited[u]:
        if visited[u] != color:
            print(-1)
            exit()
        return 0, 0
    visited[u] = color
    oneCount = 0
    twoCount = 0
    if color == 1:
        oneCount += 1
    else:
        twoCount += 1
    for v in range(n):
        if u == v or u == parent:
            continue
        if adjList[u][v]:
            p = dfs(v, u, 3 - color)
            oneCount += p[0]
            twoCount += p[1]
    return oneCount, twoCount
connSize = []
for i in range(n):
    if visited[i]:
        continue
    connSize.append(dfs(i))
dp = [False] * (n + 1)
dp[0] = True
for c1, c2 in connSize:
    ndp = [False] * (n + 1)
    for i in range(n + 1):
        if dp[i]:
            ndp[i+c1] = True
            ndp[i+c2] = True
    dp = ndp
print(min(sum(sz * (sz - 1) // 2 for sz in [sz1, n - sz1]) for sz1 in range(n+1) if dp[sz1]))

Solution (Python):
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
e = [set([x for x in range(1, N + 1) if i != x]) for i in range(N + 1)]
for _ in range(M):
  u, v = map(int, input().split())
  e[u].discard(v)
  e[v].discard(u)

cl = [0] * (N + 1)
dp = [0] * (N + 1)
dp[0] = 1
for x in range(1, N + 1):
  if cl[x]: continue
  s = [x]
  qs = []
  cl[x] = 1
  while len(s):
    p = s.pop()
    qs.append(p)
    for q in e[p]:
      if cl[q]:
        if cl[q] % 2 == cl[p] % 2:
          print(-1)
          exit(0)
        continue
      cl[q] = cl[p] % 2 + 1
      s.append(q)
  predp = dp[: ]
  for i in range(N, -1, -1):
    if dp[i] == 0: continue
    u = 0
    v = 0
    for q in qs:
      u += cl[q] % 2
      v += cl[q] % 2 == 0
    dp[i] -= predp[i]
    dp[i + u] += 1
    dp[i + v] += 1
  
res = N * (N - 1) // 2
for i in range(1, N + 1):
  if dp[i] == 0: continue
  u = i * (i - 1) // 2
  v = (N - i) * (N - i - 1) // 2
  res = min(res, u + v)
print(res)

Solution (Python):
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()
                if not used[v]:
                    color[v]=c
                    black+=(c==1)
                    white+=(c==-1)
                    used[v]=True
                    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)

Solution (Python):
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()
                color[v]=c
                black+=(not used[v])*(c==1)
                white+=(not used[v])*(c==-1)
                used[v]=True
                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)

Solution (Python):



















def main():
    from sys import stdin
    input = stdin.readline
    n, m = map(int, input().split())
    ab = [list(map(int, input().split())) for _ in [0]*m]

    rest = n  
    g = [set() for _ in [0]*n]
    [g[a-1].add(b-1) for a, b in ab]
    [g[b-1].add(a-1) for a, b in ab]
    s = set([i for i in range(n)])

    a_list, b_list = [], []
    while True:
        if m == rest*(rest-1)//2:
            break
        a = [-1, 10**10]
        for i in s:
            length = len(g[i])
            if length < a[1]:
                a = [i, length]
        a = a[0]
        b = [-1, 10**10]
        for i in s-g[a]-{a}:
            length = len(g[i])
            if length < b[1]:
                b = [i, length]
        b = b[0]
        a_set, b_set = {a}, {b}
        s.remove(a)
        s.remove(b)
        rest -= 2
        remain = set()  
        for i in s:
            flag_a = True
            for j in a_set:
                if j not in g[i]:
                    flag_a = False
                else:
                    g[i].remove(j)
                    g[j].remove(i)
                    m -= 1
            flag_b = True
            for j in b_set:
                if j not in g[i]:
                    flag_b = False
                else:
                    g[i].remove(j)
                    g[j].remove(i)
                    m -= 1
            if flag_a+flag_b == 0:
                print(-1)
                return
            elif flag_a*flag_b == 0:
                q = {i}
                flag = flag_a  
                while q:
                    qq = set()
                    while q:
                        i = q.pop()
                        if flag:
                            a_set.add(i)
                        else:
                            b_set.add(i)
                        for j in remain:
                            if j not in g[i]:
                                qq.add(j)
                            else:
                                g[i].remove(j)
                                g[j].remove(i)
                                m -= 1
                        for j in q:
                            g[i].remove(j)
                            g[j].remove(i)
                            m -= 1
                    for i in qq:
                        remain.remove(i)
                    flag ^= True
                    q = qq
            else:
                remain.add(i)
        for i in (a_set | b_set)-{a}-{b}:
            s.remove(i)
            rest -= 1

        a_list.append(len(a_set))
        b_list.append(len(b_set))

    k = len(a_list)
    dp = [False]*(n+1)
    dp[0] = True

    for i in range(k):
        a, b = a_list[i], b_list[i]
        dp2 = [False]*(n+1)
        for j in range(n-max(a, b)+1):
            dp2[j+a] |= dp[j]
            dp2[j+b] |= dp[j]
        dp = dp2

    ans = 10**10
    for j in range(rest+1):
        for i in range(n-j+1):
            if dp[i]:
                p = i+j
                q = n-p
                ans = min(ans, p*(p-1)//2+q*(q-1)//2)

    print(ans)


main()

Solution (Python):



















def main():
    from sys import stdin
    input = stdin.readline
    n, m = map(int, input().split())
    ab = [list(map(int, input().split())) for _ in [0]*m]

    rest = n  
    g = [set() for _ in [0]*n]
    [g[a-1].add(b-1) for a, b in ab]
    [g[b-1].add(a-1) for a, b in ab]
    s = set([i for i in range(n)])

    a_list, b_list = [], []
    while True:
        if m == rest*(rest-1)//2:
            break
        a = [-1, 10**10]
        for i in s:
            length = len(g[i])
            if length < a[1]:
                a = [i, length]
        a = a[0]
        b = [-1, 10**10]
        for i in s-g[a]-{a}:
            length = len(g[i])
            if length < b[1]:
                b = [i, length]
        b = b[0]
        a_set, b_set = {a}, {b}
        s.remove(a)
        s.remove(b)
        rest -= 2
        remain = set()  
        for i in s:
            flag_a = True
            for j in a_set:
                if j not in g[i]:
                    flag_a = False
                else:
                    g[i].remove(j)
                    g[j].remove(i)
                    m -= 1
            flag_b = True
            for j in b_set:
                if j not in g[i]:
                    flag_b = False
                else:
                    g[i].remove(j)
                    g[j].remove(i)
                    m -= 1
            if flag_a+flag_b == 0:
                print(-1)
                return
            elif flag_a*flag_b == 0:
                q = {i}
                flag = flag_a  
                while q:
                    qq = set()
                    while q:
                        i = q.pop()
                        if flag:
                            a_set.add(i)
                        else:
                            b_set.add(i)
                        for j in remain:
                            if j not in g[i]:
                                qq.add(j)
                            else:
                                g[i].remove(j)
                                g[j].remove(i)
                                m -= 1
                        for j in q:
                            g[i].remove(j)
                            g[j].remove(i)
                            m -= 1
                    for i in qq:
                        remain.remove(i)
                    flag ^= True
                    q = qq
            else:
                remain.add(i)
        for i in (a_set | b_set)-{a}-{b}:
            s.remove(i)
            rest -= 1

        a_list.append(len(a_set))
        b_list.append(len(b_set))

    k = len(a_list)
    dp = [False]*(n+1)
    dp[0] = True

    for i in range(k):
        a, b = a_list[i], b_list[i]
        dp2 = [False]*(n+1)
        for j in range(n-max(a, b)+1):
            dp2[j+a] |= dp[j]
            dp2[j+b] |= dp[j]
        dp = dp2

    ans = 10**10
    for j in range(rest+1):
        for i in range(n-j+1):
            if dp[i]:
                p = i+j
                q = n-p
                ans = min(ans, p*(p-1)//2+q*(q-1)//2)
    print(ans)


main()

Solution (Python):
def main():
    n, m = map(int, input().split())
    ab = [list(map(int, input().split())) for _ in [0]*m]

    n_hozon = n
    g = [set() for _ in [0]*n]
    [g[a-1].add(b-1) for a, b in ab]
    [g[b-1].add(a-1) for a, b in ab]
    s = set([i for i in range(n)])

    
    
    

    
    
    
    
    
    
    
    
    

    
    
    
    
    a_list, b_list = [], []
    while True:
        
        
        
        
        
        if m == n*(n-1)//2:
            break
        a = [-1, 10**10]
        for i in s:
            l = len(g[i])
            if l < a[1]:
                a = [i, l]
        a = a[0]
        b = [-1, 10**10]
        for i in s-g[a]-{a}:
            l = len(g[i])
            if l < b[1]:
                b = [i, l]
        b = b[0]
        
        a_set, b_set = {a}, {b}
        s.remove(a)
        s.remove(b)
        n -= 2
        remain = set()
        for i in s:
            flag_a = True
            for j in a_set:
                if j not in g[i]:
                    flag_a = False
                else:
                    g[i].remove(j)
                    g[j].remove(i)
                    m -= 1
            flag_b = True
            for j in b_set:
                if j not in g[i]:
                    flag_b = False
                else:
                    g[i].remove(j)
                    g[j].remove(i)
                    m -= 1
            
            if flag_a == flag_b == False:
                print(-1)
                return
            elif flag_a == False or flag_b == False:
                
                q = {i}
                flag = flag_a  
                while q:
                    
                    qq = set()
                    while q:
                        i = q.pop()
                        if flag:
                            a_set.add(i)
                        else:
                            b_set.add(i)
                        for j in remain:
                            if j not in g[i]:
                                qq.add(j)
                            else:
                                g[i].remove(j)
                                g[j].remove(i)
                                m -= 1
                        for j in q:
                            g[i].remove(j)
                            g[j].remove(i)
                            m -= 1
                    for i in qq:
                        remain.remove(i)
                    flag ^= True
                    q = qq
            else:
                remain.add(i)
            
        for i in (a_set | b_set)-{a}-{b}:
            s.remove(i)
            n -= 1

        a_list.append(len(a_set))
        b_list.append(len(b_set))

    m = n
    n = n_hozon
    k = len(a_list)

    if k == 1:
        dp = [False]*(n+1)
        a = a_list[0]
        b = b_list[0]
        ans = 10**10
        for i in range(m+1):
            ans = min(ans, (a+i)*(a+i-1)//2+(n-a-i)*(n-a-i-1)//2)
        print(ans)
        return

    dp = [False]*(n+1)
    dp[0] = True

    for i in range(k):
        a, b = a_list[i], b_list[i]
        maxab = max(a, b)
        dp2 = [False]*(n+1)
        for j in range(n-maxab+1):
            dp2[j+a] |= dp[j]
            dp2[j+b] |= dp[j]
        dp = dp2

    dp2 = [False]*(n+1)
    for j in range(m+1):
        for i in range(n-j+1):
            dp2[i+j] |= dp[i]
    ans = 10**10

    for i in range(n+1):
        if dp2[i] is False:
            continue
        j = n-i
        ans = min(ans, i*(i-1)//2+j*(j-1)//2)
    print(ans)


main()

Solution (Python):
import sys
input = sys.stdin.readline
from collections import *

def bfs(s):
    q = deque([s])
    color[s] = 1
    w, b = 1, 0
    
    while q:
        v = q.popleft()
        
        for nv in G[v]:
            if color[nv]==0:
                color[nv] = -color[v]
                q.append(nv)
                
                if color[nv]==1:
                    w += 1
                else:
                    b += 1
            else:
                if color[nv]==color[v]:
                    return -1, -1
    
    return w, b

N, M = map(int, input().split())
A = [[0]*N for _ in range(N)]

for _ in range(M):
    u, v = map(int, input().split())
    A[u-1][v-1] = 1
    A[v-1][u-1] = 1

G = [[] for _ in range(N)]

for i in range(N):
    for j in range(i+1, N):
        if A[i][j]==0:
            G[i].append(j)
            G[j].append(i)

color = [0]*N
ws, bs = [], []

for i in range(N):
    if color[i]==0:
        w, b = bfs(i)
        
        if w==-1:
            print(-1)
            exit()
        
        ws.append(w)
        bs.append(b)

dp = [[False]*(N+1) for _ in range(len(ws)+1)]
dp[0][0] = True

for i in range(len(ws)):
    for j in range(N+1):
        if j+ws[i]<=N:
            dp[i+1][j+ws[i]] |= dp[i][j]
        
        if j+bs[i]<=N:
            dp[i+1][j+bs[i]] |= dp[i][j]

ans = 10**18

for i in range(N+1):
    if dp[-1][i]:
        ans = min(ans, i*(i-1)//2+(N-i)*(N-i-1)//2)

print(ans)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007

n, m = LI()
G = [set(range(n)) for _ in range(n)]
for i in range(n):
    G[i].remove(i)

for _ in range(m):
    a, b = LI()
    G[a - 1].remove(b - 1)
    G[b - 1].remove(a - 1)

color = [0] * n
def bipartite_or_not(s):
    color[s] = 1
    dq = deque([s])
    b = 1
    w = 0
    while dq:
        u = dq.popleft()
        for v in G[u]:
            if color[v] and color[u] != color[v]:
                continue
            elif color[v] and color[u] == color[v]:
                print(-1)
                exit()
            color[v] = -color[u]
            if color[v] == 1:
                b += 1
            else:
                w += 1
            dq += [v]
    return b, w

bit = 1
for i in range(n):
    if color[i]:
        continue
    p, q = bipartite_or_not(i)
    bit = bit << p | bit << q

for j in range(n // 2, -1, -1):
    if bit >> j & 1:
        print(n * (n - 1) // 2 - j * (n - j))
        break

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007

n, m = LI()
G = [set(range(n)) for _ in range(n)]
for i in range(n):
    G[i].remove(i)

for _ in range(m):
    a, b = LI()
    G[a - 1].remove(b - 1)
    G[b - 1].remove(a - 1)

color = [0] * n
def bipartite_or_not(s):
    color[s] = 1
    dq = deque([s])
    b = 1
    w = 0
    while dq:
        u = dq.popleft()
        for v in G[u]:
            if color[v] and color[u] != color[v]:
                continue
            elif color[v] and color[u] == color[v]:
                print(-1)
                exit()
            color[v] = -color[u]
            if color[v] == 1:
                b += 1
            else:
                w += 1
            dq += [v]
    return b, w

bit = 1 << n
for i in range(n):
    if color[i]:
        continue
    x = bipartite_or_not(i)
    p, q = x
    d = abs(p - q)
    bit = bit << d | bit >> d

for j in range(n):
    if bit >> (n - j) & 1:
        y, z = (n + j) // 2, (n - j) // 2
        print(y * (y - 1) // 2 + z * (z - 1) // 2)
        break

Solution (Python):
import sys
input = sys.stdin.readline


def is_bipartite(graph, s):
    """二部グラフ判定する"""
    n = len(graph)
    col = [-1] * n
    col[s] = 0
    stack = [s]
    used[s] = True
    while stack:
        v = stack.pop()
        for nxt_v in graph[v]:
            used[nxt_v] = True
            if col[nxt_v] == -1:
                col[nxt_v] = col[v] ^ 1
                stack.append(nxt_v)
            elif col[nxt_v] ^ col[v] == 0:
                return False
    return True

def color_bipartite(graph, s):
    """二部グラフを彩色する"""
    n = len(graph)
    col = [-1] * n
    col[s] = 0
    stack = [s]
    while stack:
        v = stack.pop()
        for nxt_v in graph[v]:
            if col[nxt_v] == -1:
                col[nxt_v] = col[v] ^ 1
                stack.append(nxt_v)
    return col


n, m = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]

graph = [set() for i in range(n)]
for a, b in info:
    a -= 1
    b -= 1
    graph[a].add(b)
    graph[b].add(a)

comp_graph = [[] for i in range(n)]
for a in range(n):
    for b in range(n):
        if b in graph[a] or a == b:
            continue
        comp_graph[a].append(b)
        

cnt0 = []
cnt1 = []
used = [False] * n
for i in range(n):
    if used[i]:
        continue
    used[i] = True
    if not is_bipartite(comp_graph, i):
        print(-1)
        exit()
    col = color_bipartite(comp_graph, i)
    cnt0.append(col.count(0))
    cnt1.append(col.count(1))

dp = [[False] * (n + 1) for i in range(len(cnt0) + 1)]
dp[0][0] = True
for i in range(len(cnt0)):
    wei0 = cnt0[i]
    wei1 = cnt1[i]
    for w in range(n + 1):
        if w + wei0 < n + 1:
            dp[i + 1][w + wei0] = (dp[i][w] or dp[i + 1][w + wei0])
        if w + wei1 < n + 1:
            dp[i + 1][w + wei1] = (dp[i][w] or dp[i + 1][w + wei1])

ans = 10 ** 18
for num in range(n + 1):
    if dp[-1][num]:
        c0 = num
        c1 = n - num
        res = c0 * (c0 - 1) // 2 + c1 * (c1 - 1) // 2
        ans = min(ans, res)
print(ans)

Solution (Python):
"""
E問題
繋がっている都市同士は同じ州にあっても違う州にあってもよい→考えにくい
→「繋がっていない都市は必ず違う州にある」のほうが考えやすい
→繋がっていない都市にすべて辺を張って二部グラフが構成できるかどうかで判定できそう？
（必要条件ではあるけど十分条件であるかどうかはわからない）
→この条件だと同じ州にあるなら必ず任意の二都市間は繋がっているので十分条件も満たしてそう！
（∵繋がっていない都市に辺を張った時同じ州内に辺を持たないため）

（繋がっていない都市に辺を張った）グラフが連結⇒都市の選び方は高々1通り
連結でないなら複数の選び方が存在する
→最小となるような選び方はどのように決めればよいか？
→それぞれの連結成分ごとに、片方にai都市、もう片方にbi都市振り分けられるとすると
L = [[a1, b1], [a2, b2], ... , [ak, bk]]
とできて、(sum(A)+sum(B) == n)
s = Σ[i = 1 to k](aiかbiのどちらかを選んで足す)　としたときに
もっともsがn//2に近くなるようにsを選べばよく、これはdpでO(nk)でできる
"""
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
import numpy as np

n, m = map(int, input().split())
G = [{i for i in range(n) if i != j} for j in range(n)]
for _ in range(m):
  a, b = map(int, input().split())
  a -= 1
  b -= 1
  G[a].remove(b)
  G[b].remove(a)

seen = [-1]*n
L = []
def is_bipartite(v, color):
  seen[v] = color
  L[-1][color] += 1
  for i in G[v]:
    if seen[i] != -1:
      if seen[i] == color:
        return False
    else:
      if not is_bipartite(i, color^1):
        return False
  return True

for i in range(n):
  if seen[i] == -1:
    L.append([0, 0])
    if not is_bipartite(i, 0):
      print(-1)
      break
else:
  dp = np.zeros((len(L)+1, n+1), dtype=bool)
  dp[0, 0] = True
  for i, ab in enumerate(L):
    a, b = ab
    dp[i+1, a:] |= dp[i, :n+1-a]
    dp[i+1, b:] |= dp[i, :n+1-b]
  temp = n//2
  dp = dp[-1].tolist()
  while not dp[temp]:
    temp += 1
  r = n - temp
  print(temp*(temp-1)//2 + r*(r-1)//2)

Solution (Python):
import sys
input = sys.stdin.readline
from itertools import combinations
n,m = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(m)]
g2d = [[1 for i in range(n+1)] for j in range(n+1)]
for i in range(1,n+1):
  g2d[i][i] = 0
for a,b in ab:
  g2d[a][b] = 0
  g2d[b][a] = 0
graph = [[] for i in range(n+1)]
for i in range(1,n+1):
  for j in range(1,n+1):
    if g2d[i][j]:
      graph[i].append(j)
      graph[j].append(i)
vis = [-1]*(n+1)
oddeven = []
for i in range(1,n+1):
  if vis[i] == -1:
    stack = [i]
    vis[i] = 0
    odd = 0
    even = 1
    while stack:
      x = stack.pop()
      for y in graph[x]:
        if vis[y] == -1:
          vis[y] = vis[x]+1
          if vis[y]%2:
            odd += 1
          else:
            even += 1
          stack.append(y)
        elif (vis[y]-vis[x])%2 == 0:
          print(-1)
          exit()
    oddeven.append(abs(odd-even))
t = len(oddeven)
s = sum(oddeven)
dp = 1<<s
for x in oddeven:
  dp = (dp<<abs(x)) | (dp>>abs(x))
for i in range(s+1):
  if (dp&1<<(s-i))|(dp&1<<(s+i)):
    ex = i
    break
A,B = (n+ex)//2,(n-ex)//2
print(A*(A-1)//2+B*(B-1)//2)

Solution (Python):

"""
Writer:SPD_9X2
https://atcoder.jp/contests/arc099/tasks/arc099_c

なるべく均等に分けるのが正解
制約を受けるのはv-uの辺が存在しない場合
補グラフで考えると、辺がある2点は同じ側に属してはいけない、という問題になる

→2部グラフにならない連結成分がある場合-1

あとは、連結成分ごとにどちらに属すかを決め、その差を最小化すればよい
→dpで見つけられる！

"""
import sys
N,M = map(int,input().split())

AB = []
olis = [ [1] * N for i in range(N) ]
for i in range(N):
    olis[i][i] = 0

for i in range(M):

    A,B = map(int,input().split())
    A -= 1
    B -= 1
    olis[A][B] = 0
    olis[B][A] = 0

non_visit = [True] * N
state = [None] * N
dif = []
ns = [0,0]



def dfs(p,nst):

    if non_visit[p]:
        non_visit[p] = False
        state[p] = nst
        ns[nst] += 1
        
        for j in range(N):
            if p!=j and olis[p][j] == 1:
                dfs(j,nst^1)
    
    elif nst != state[p]:
        print (-1)
        sys.exit()

    return;

for i in range(N):

    ns = [0,0]

    if non_visit[i]:
        dfs(i,0)
        
        dif.append(abs(ns[0]-ns[1]))

dp = [False] * 1500
dp[0] = True

for i in dif:

    ndp = [False] * 1500

    for j in range(1500):

        if dp[j]:
            ndp[(j-i)%1500] = True
            ndp[(j+i)%1500] = True

    dp = ndp

for i in range(N):

    if dp[i] or dp[-1*i]:

        for j in range(N):

            if abs(N-j - j) == i:
                x = j
                y = N-j

                print (x*(x-1)//2 + y*(y-1)//2)
                sys.exit()