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



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])

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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):



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

    
    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)
        
        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

    
    
    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 = Graph(N, edges).complement()
ccs = g.connectedcomps()
bs  = [cc.isbipartite() for cc in ccs]
if not all(bs):
    print(-1)
    exit()



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 = abs(sum(diffs) - 2 * nearlyhalfdiff)


x = (N - diff) // 2
y = N - x


x = x * (x - 1) // 2
y = y * (y - 1) // 2

print(x + y)

Solution (Python):


import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq





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 
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)

Solution (Python):
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]))

Solution (Python):
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)

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]))

Solution (Python):

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

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)

Solution (Python):
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))

Solution (Python):
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)


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)

Solution (Python):
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())