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:
from itertools import product


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 tuple(cnt)


def is_bipartite(n, links):
    fixed = [-1] * n
    l, r = 0, 0
    for i in range(n):
        if fixed[i] > -1:
            continue
        cnt = dfs(links, fixed, i)
        if cnt == False:
            return -1
        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: 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):
    if all(edge_exists[i][1:]):
        pass
    else:
        group[i] = 1
        break

q = deque()
q.append(1)
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)

Submission status: Wrong Answer

Solution code:
import numpy as np

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


# def graph_coloring(G, color):
#     N = len(G)
#     c = 1
#     color[0] = c
#     c += 1
#     # 彩色
#     for ix in range(N):
#         if color[ix] == 0:
#             color[ix] = c
#             c += 1
#
#         for n in range(ix, N):
#             if G[ix, n] == 1:
#                 if color[n] == 0:
#                     color[n] = color[ix] * -1
#                     # G, color = graph_coloring(G, n, color)
#                 elif color[ix] == color[n]:
#                     return G, None  # impossible to coloring
#                 else:
#                     pass
#
#     return G, color

def graph_coloring(G, color):
    N = len(G)

    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

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

    return G, 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 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

    G = 1 - G  # 補グラフ
    color = np.array([0 for _ in range(N)])

    G, color = graph_coloring(G, color=color)
    if color is None:
        return -1

    c = 1
    base = 0
    int_list = []
    while True:
        p = len(color[color == c])
        q = len(color[color == -c])
        if p == 0 and q == 0:
            break

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

        c += 1

    if int_list:
        int_list = sorted(int_list, reverse=True)
        for s in range((N - base) // 2, N - base):
            if partial_sum(int_list, target_sum=s):
                return c2(base + s) + c2(N - base - s)

    else:
        return c2(base) * 2


if __name__ == '__main__':
    print(main())

Submission status: Wrong Answer

Solution code:
from itertools import product


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 cnt


def is_biparate(n, links):
    fixed = [-1] * n
    can = []
    for i in range(n):
        if fixed[i] > -1:
            continue
        cnt = dfs(links, fixed, i)
        if cnt == False:
            return False
        can.append(cnt)
    mx = float('inf')
    for p in product(*can):
        s = sum(p)
        t = n - s
        tmx = max(s, t)
        mx = min(mx, tmx)

    mn = n - mx
    return (mx * (mx - 1) + mn * (mn - 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_biparate(n, links))

Submission status: Wrong Answer

Solution code:
import numpy as np

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


# def graph_coloring(G, color):
#     N = len(G)
#     c = 1
#     color[0] = c
#     c += 1
#     # 彩色
#     for ix in range(N):
#         if color[ix] == 0:
#             color[ix] = c
#             c += 1
#
#         for n in range(ix, N):
#             if G[ix, n] == 1:
#                 if color[n] == 0:
#                     color[n] = color[ix] * -1
#                     # G, color = graph_coloring(G, n, color)
#                 elif color[ix] == color[n]:
#                     return G, None  # impossible to coloring
#                 else:
#                     pass
#
#     return G, color

def graph_coloring(G, color):
    N = len(G)

    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

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

    return G, 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 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

    G = 1 - G  # 補グラフ
    color = np.array([0 for _ in range(N)])

    G, color = graph_coloring(G, color=color)
    if color is None:
        return -1
    # print(G, color)

    c = 1
    base = 0
    int_list = []
    while True:
        p = len(color[color == c])
        q = len(color[color == -c])
        if p == 0 and q == 0:
            break

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

        c += 1

    # print(base, int_list)

    for s in range((N - base) // 2, N - base):
        if partial_sum(int_list, target_sum=s):
            return c2(base + s) + c2(N - base - s)

    # print(color)
    #
    # p = len(color[color == 1])
    # q = len(color[color == -1])
    # m = len(color[color == 0])
    #
    # a = max(p, q)
    # b = min(p, q)
    # if a - b >= m:
    #     b += m
    #     return c2(a) + c2(b)
    #
    # else:
    #     m -= (a - b)
    #     b = a
    #     if m % 2:
    #         return c2(a + 1 + m // 2) + c2(b + m // 2)
    #     else:
    #         return c2(a + m // 2) + c2(b + m // 2)

if __name__ == '__main__':
    print(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 は使わない
group[1] = 1
edge_exists = [[False] * (N + 1) for _ in range(N + 1)]  # index 0 は使わない
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


q = deque()
q.append(1)
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)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3

def sm(n):
    a = 0
    while n >= 1:
        a += n
        n -= 1
    return a


def solve(N, G):
    unused = set(range(N))
    groups = []

    while unused:
        a = unused.pop()
        group = set([a])
        for b in range(N):
            if not G[a][b] or b not in unused:
                continue

            cxn = True
            for c in group:
                if not G[b][c]:
                    cxn = False
                    break

            if not cxn:
                continue

            group.add(b)
            unused.remove(b)
        groups.append(group)

    # print(groups)

    if len(groups) > 2:
        return -1

    if len(groups) == 2:
        g0 = groups[0]
        g1 = groups[1]

        return sm(len(g0) - 1) + sm(len(g1) - 1)

    best = sm(N - 1)
    for i in range(1, N):
        best = min(best, sm(i - 1) + sm(N - i - 1))
    return best


def main():
    N, M = [int(e) for e in input().split(' ')]
    G = [[False] * N for _ in range(N)]

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

    print(solve(N, G))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3

def sm(n):
    a = 0
    while n >= 1:
        a += n
        n -= 1
    return a


def solve(N, G):
    unused = set(range(N))
    groups = []

    while unused:
        a = unused.pop()
        group = set([a])
        for b in range(N):
            if not G[a][b] or b not in unused:
                continue

            cxn = True
            for c in group:
                if not G[b][c]:
                    cxn = False
                    break

            if not cxn:
                continue

            group.add(b)
            unused.remove(b)
        groups.append(group)

    # print(groups)

    if len(groups) > 2:
        return -1

    if len(groups) == 2:
        g0 = groups[0]
        g1 = groups[1]

        return sm(len(g0) - 1) + sm(len(g1) - 1)

    best = sm(N - 1)
    for i in range(1, N):
        best = min(best, sm(i - 1) * sm(N - i - 1))
    return best


def main():
    N, M = [int(e) for e in input().split(' ')]
    G = [[False] * N for _ in range(N)]

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

    print(solve(N, G))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations
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 validation(target:set,connections):
    for i,j in combinations(target,2):
        if not i in connections[j]:
            return False
    return True
def validation2(taregt:set,valied_set:set,connections):
    for i in taregt:
        for j in valied_set:
            if not i in connections[j]:
                raise

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:

            return
        i,j,k = res

        validation(i,connections)
        validation(j, connections)
        validation2(k,j,connections)
        validation2(k,i,connections)


        lst.append((len(i),len(j),k))
     
        free= lst[-1][2]
        if validation(free,connections):
            break
    dpt = set([(0,0)])
    for i,j,k in  lst:
        ndp= set()

        for k,l in dpt:
            ndp.add((i+k,j+l))
            ndp.add((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 > j:
            i,j = j,i
        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: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque
import sys
N, M = map(int, input().split())
edges = [list(range(N)) for i in range(N)]
for i in range(N):
    edges[i].remove(i)
for _ in range(M):
    a, b = map(int, input().split())
    edges[a-1].remove(b-1)
    edges[b-1].remove(a-1)
size = defaultdict(lambda: [0, 0])
color = [-1]*N
def set_color(root):
    
    que = deque([root])
    color[root] = 0
    size[root][0]+=1
    while que:
        v = que.pop()
        for nv in edges[v]:
            if color[nv]<0:
                c = 1- color[v]
                color[nv] = c
                size[root][c]+=1
                que.append(nv)
            elif color[nv] == color[v]:
                print(-1)
                sys.exit()
for i in range(N):
    if color[i]<0:
        set_color(i)
S = set([0])
for a, b in size.values():
    S = set(s+b for s in S)|set(s+a for s in S)
ans = min(x*(x-1)//2+(N-x)*(N-x-1)//2 for x in S)            
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# import math
# n,k = list(map(int,input().split()))
# print(math.ceil((n-1)/(k-1)))

n,m = list(map(int,input().split()))
road = {}
whole = []
for i in range(1,n+1):
    whole.append(i)
    road[i] = []
whole = set(whole)

for i in range(m):
    a,b = list(map(int, input().split()))
    road[a].append(b)
    road[b].append(a)

taka = []
hashi = []
used = []
no = 0
for x in road:
    l = []
    r = []
    l1 = []
    r1 = []
    if x in used:
        continue
    else:
        l.append(x)
        l1.append(x)
        used.append(x)
        for y in whole - set(road[x]):
            if y not in used:
                r.append(y)
                r1.append(y)
                used.append(y)
    while l1 != [] or r1 != []:
        while r1 != []:
            t = r1.pop()
            for y in whole-set(road[t]):
                if y not in used and y not in l:
                    l.append(y)
                    l1.append(y)
                    used.append(y)
        while l1 != []:
            t = l1.pop()
            for y in whole-set(road[t]):
                if y not in used and y not in r:
                    r.append(y)
                    r1.append(y)
                    used.append(y)

    for i in range(len(l)):
        for j in range(i+1,len(l)):
            if l[j] not in road[l[i]]:
                no = 1
                break
        if no == 1:break
    if no == 1:break
    for i in range(len(r)):
        for j in range(i+1,len(r)):
            if r[j] not in road[r[i]]:
                no = 1
                break
        if no == 1:break
    if no == 1:break

    taka.append(len(l))
    hashi.append(len(r))

if no == 1:print(-1)
else:
    res = [abs(taka[i]-hashi[i]) for i in range(len(taka))]
    res.sort(reverse=-1)
    delta = 0
    for x in res:
        if delta>0:delta-=x
        else:delta+=x
    left = (n+delta)/2
    right = (n-delta)/2
    result = int((left*(left-1)+right*(right-1))/2)
    print(result)

Submission status: Time Limit Exceeded

Solution code:
# 予想通りTLE
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 and h == 1:
            ans = 0
        elif a == 1 and h != 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: Time Limit Exceeded

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 for v in range(self.nvertices())]
        ccs = []
        for v in range(self.nvertices()):
            if not self.visited[v]:
                vs = self.__connectedcomp(v)
                cc = self.inducedsubgraph(vs)
                ccs.append(cc)
        self.visited = None
        return ccs

    # vを含む連結成分 (節点のリスト)
    def __connectedcomp(self, v):
        vs = []
        work = [v]
        while len(work) > 0:
            w = work[0]
            work = work[1:]
            if self.visited[w]: continue
            self.visited[w] = True
            vs.append(w)
            for u in range(self.nvertices()):
                if self.adj[w][u]:
                    work.append(u)
        return 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):
        color = [None for v in range(self.nvertices())]
        color[0] = 0
        work = [0]
        while len(work) > 0:
            w = work[0]
            work = work[1:]
            for u in range(self.nvertices()):
                if self.adj[w][u]:
                    if color[u] == None:
                        color[u] = 1 - color[w]
                        work.append(u)
                    elif color[u] != 1 - color[w]:
                        return False
        m = sum(1 for c in color if c == 0)
        n = sum(1 for c in color if c == 1)
        assert m + n == self.nvertices()
        return (max(m, n), min(m, n))

# 入力
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: Time Limit Exceeded

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)

#最大値選択
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: Time Limit Exceeded

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]))
lenDP = len(clusters) + 1
dp = [set() for _ in range(lenDP)]
dp[0].add(0)
for i in range(1,lenDP):
    s,t = clusters[i-1]
    for value in dp[i-1]:
        dp[i].add(value+s)
        dp[i].add(value+t)
ans = min([(s*(s-1)+(N-s)*(N-s-1))//2 for s in dp[lenDP-1]])
print(ans)

Submission status: Time Limit Exceeded

Solution code:

n,m = input().split()
n,m = int(n),int(m)

dic = {}
taka = []
hasi = []
mini = n*n
mxlst = n

def f(tgt):
    global mini,mxlst
    taka_n = len(taka)
    hasi_n = len(hasi)
    if mxlst<max(taka_n,hasi_n):
        return
    if tgt>n:
        mini = min(mini,taka_n*(taka_n-1)//2+hasi_n*(hasi_n-1)//2)
        mxlst = min(mxlst,max(taka_n,hasi_n))
        return
    route_t = True
    route_h = True
    
    for i in taka:
        if i not in dic.get(tgt,[]):
            route_t = False
            break
    
    for i in hasi:
        if i not in dic.get(tgt,[]):
            route_h = False
            break
        
    if route_t:
        taka.append(tgt)
        f(tgt+1)
        taka.remove(tgt)
    if route_h:
        hasi.append(tgt)
        f(tgt+1)
        hasi.remove(tgt)

for i in range(m):
    a,b = input().split()
    a,b = int(a),int(b)
    dic.setdefault(a,[])
    dic.setdefault(b,[])
    dic[a].append(b)
    dic[b].append(a)

taka.append(1)
f(2)

if mini==n*n:
    print(-1)
else:
    print(mini)