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:
def main():
    n, m = map(int, input().split())
    n_hozon = n
    N, M = [n], [m]

    ab = [list(map(int, input().split())) for _ in [0]*m]
    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)])

    # 題意：できるだけ辺が少なくなるように2つの完全グラフに分けたい
    # まず、2つの完全グラフに分けられるのかを調べる必要がある。
    # これが不可能であれば-1を出力して即座に終了。

    # 分けられるのであれば、できるだけ街の数を均等にしたい。
    # 以下のアルゴリズムを考える。
    # まずお互い繋がっていない都市の組A,Bを選ぶ。
    # すると、Aにしか繋がっていない街、Bにしか繋がっていない街、
    # 両方に繋がっている街の3グループに分かれる。
    # このうち、最後のグループについて、
    # 最初に戻って同様の処理を行う。
    # 街がなくなるか、両方に繋がっている街のグループが完全グラフに
    # なった時点で終了。

    # 上記のアルゴリズムにより、(A,B)の列と最後に残った街の数が求められる。
    # これをもとに、動的計画法で考えられる街の振り分け方を全て洗い出す。
    # 最も均等に近く振り分けた場合について、完全グラフの辺数を計算して
    # 出力すれば問題が解ける。
    a_list, b_list = [], []
    while True:
        n, m = N[0], M[0]
        #print(n, m)
        # print(s)
        # print(g)
        # 完全グラフかどうか
        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
        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:
                b_set.add(i)
            elif flag_b == False:
                a_set.add(i)
        remove_list = []
        for i in (a_set | b_set)-{a}-{b}:
            s.remove(i)
            for j in g[i]:
                remove_list.append((i, j))
            n -= 1
        for i, j in remove_list:
            g[i].remove(j)
            g[j].remove(i)
            m -= 1
        a_list.append(len(a_set))
        b_list.append(len(b_set))
        N, M = [n], [m]

    n = n_hozon
    k = len(a_list)
    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 dp[i] is False:
            continue
        j = n-i
        ans = min(ans, i*(i-1)//2+j*(j-1)//2)
    print(ans)


main()

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M = map(int, input().split())
e = dd(set)
for _ in range(M):
  u, v = map(int, input().split())
  e[u].add(v)
  e[v].add(u)
l = set()
r = set()

s = [1]
while len(s):
  x = s.pop()
  l.add(x)
  for y in e[x]:
    for z in l:
      if z in e[y]: continue
      break
    else:
      s.append(y)
for t in range(1, N + 1):
  if t in l: continue
  s.append(t)
  while len(s):
    x = s.pop()
    r.add(x)
    for y in e[x]:
      for z in r:
        if z in e[y]: continue
        break
      else:
        s.append(y)
  break

if len(l | r) < N:
  print(-1)
  exit(0)

res = float("inf")
m = len(l & r)
if len(r) == 0:
  m = len(l)
  r = l
for z in range(m + 1):
  x = len(l) - (m - z)
  y = len(r) - z
  res = min(res, x * (x - 1) // 2 + y * (y - 1) // 2)
print(res)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M = map(int, input().split())
e = dd(set)
for _ in range(M):
  u, v = map(int, input().split())
  e[u].add(v)
  e[v].add(u)
l = set()
r = set()

s = [1]
while len(s):
  x = s.pop()
  l.add(x)
  for y in e[x]:
    for z in l:
      if z in e[y]: continue
      break
    else:
      s.append(y)
for t in range(1, N + 1):
  if t in l: continue
  s.append(t)
  while len(s):
    x = s.pop()
    r.add(x)
    for y in e[x]:
      for z in r:
        if z in e[y]: continue
        break
      else:
        s.append(y)
  break

if len(l | r) < N:
  print(-1)
  exit(0)

res = float("inf")
m = len(l & r)
for z in range(m + 1):
  x = len(l)
  y = len(r) - z
  res = min(res, x * (x - 1) // 2 + y * (y - 1) // 2)
print(res)

Submission status: Wrong Answer

Solution code:
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=0):
    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()
    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

Submission status: Wrong Answer

Solution code:
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=0):
    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]:
                return False
            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()
    if not x:
        print(-1)
        exit()
    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

Submission status: Wrong Answer

Solution code:
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=0):
    color[s] = 1
    dq = deque([s])
    b = 1
    w = 0
    while dq:
        u = dq.popleft()
        for v in G[u]:
            if color[v]:
                continue
            elif color[v] == 0:
                color[v] = -color[u]
                if color[v] == 1:
                    b += 1
                else:
                    w += 1
                dq += [v]
            else:
                if color[u] == color[v]:
                    return False
    return b, w

bit = 1 << n
for i in range(n):
    if color[i]:
        continue
    x = bipartite_or_not()
    if not x:
        print(-1)
        exit()
    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

Submission status: Wrong Answer

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

flg = 0
visited = [0] * n
color = [0] * n

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

bit = 1 << n
for i in range(n):
    if color[i]:
        continue
    x = bipartite_or_not()
    if not x:
        print(-1)
        exit()
    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

Submission status: Wrong Answer

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

flg = 0
visited = [0] * n
color = [0] * n

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

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

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

Submission status: Wrong Answer

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

flg = 0
visited = [0] * n
color = [0] * n

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

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

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

Submission status: Wrong Answer

Solution code:
#クリーク二つで覆えるか
#各州の都市の数で未知の本数は決まるので均等に分ける
#小さいほうのmaxとるかn//2とn+1//2で分けるか
n,m = map(int, input().split( ))
N = [set() for i in range(n)]
for i in range(m):
    ai,bi = map(int, input().split( ))
    ai-=1;bi-=1
    N[ai].add(bi)
    N[bi].add(ai)
#0の属するqulique
q0 = {v for v in N[0]}
q0.add(0)

q_remove = set()
for v in q0:
    for u in q0:
        if u!=v and u not in N[v] and v not in q_remove:
            q_remove.add(u)
q_temp2 = {i for i in range(n)}^q_remove

q0 &= q_temp2

v = -1
for u in range(n):
    if u not in q0:
        v = u
        break
if v ==-1 and len(q0)<n:
    print(-1)
    exit()
q1 = {u for u in N[v]}
q1.add(v)
q_temp = set()
for v2 in q1:
    for u in q1:
        if u!= v2 and u not in N[v2] and v2 not in q_temp and v2 not in q0:
            q_temp.add(u)
q_temp2 = {i for i in range(n)}^q_temp
q1 &=q_temp2
Used = [1 if (u in q0 or u in q1) else 0 for u in range(n)]

for i in range(n):
    if not Used[i]:
        if len(q0)<n-1 and len(q1)<n-1:
            print(-1)
            exit()
mn = min(len(q0),len(q1))
if mn<n//2:
    print(mn*(mn-1)//2+(n-mn)*(n-mn-1)//2)
else:
    t=n//2
    print(t*(t-1)//2+(n-t)*(n-t-1)//2)

Submission status: Wrong Answer

Solution code:
#クリーク二つで覆えるか
#各州の都市の数で未知の本数は決まるので均等に分ける
#小さいほうのmaxとるかn//2とn+1//2で分けるか
n,m = map(int, input().split( ))
N = [set() for i in range(n)]
for i in range(m):
    ai,bi = map(int, input().split( ))
    ai-=1;bi-=1
    N[ai].add(bi)
    N[bi].add(ai)
#0の属するqulique
q0 = {v for v in N[0]}
q0.add(0)

q_remove = set()
for v in q0:
    for u in q0:
        if u!=v and u not in N[v] and v not in q_remove:
            q_remove.add(u)
q_temp2 = {i for i in range(n)}^q_remove

q0 &= q_temp2

v = -1
for u in range(n):
    if u not in q0:
        v = u
        break
if v ==-1 and len(q0)<n:
    print(-1)
    exit()
q1 = {u for u in N[v]}
q1.add(v)
q_temp = set()
for v2 in q1:
    for u in q1:
        if u!= v2 and u not in N[v2] and v2 not in q_temp and v2 not in q1:
            q_temp.add(u)
q_temp2 = {i for i in range(n)}^q_temp
q1 &=q_temp2
Used = [1 if (u in q0 or u in q1) else 0 for u in range(n)]

for i in range(n):
    if not Used[i]:
        if len(q0)<n-1 and len(q1)<n-1:
            print(-1)
            exit()
mn = min(len(q0),len(q1))
if mn<n//2:
    print(mn*(mn-1)//2+(n-mn)*(n-mn-1)//2)
else:
    t=n//2
    print(t*(t-1)//2+(n-t)*(n-t-1)//2)

Submission status: Wrong Answer

Solution code:
#クリーク二つで覆えるか
#各州の都市の数で未知の本数は決まるので均等に分ける
#小さいほうのmaxとるかn//2とn+1//2で分けるか
n,m = map(int, input().split( ))
N = [set() for i in range(n)]
for i in range(m):
    ai,bi = map(int, input().split( ))
    ai-=1;bi-=1
    N[ai].add(bi)
    N[bi].add(ai)
#0の属するqulique
q0 = {v for v in N[0]}
q0.add(0)
q_remove = set()
for v in q0:
    for u in q0:
        if u!=v and u not in N[v] and v not in q_remove:
            q_remove.add(v)
q_temp2 = {i for i in range(n)}^q_remove
q0 &= q_temp2

v = -1
for u in range(n):
    if u not in q0:
        v = u
        break
if v ==-1 and len(q0)<n:
    print(-1)
    exit()

q1 = {u for u in N[v]}
q1.add(v)
q_temp = set()
for v in q1:
    for u in q1:
        if u!= v and u not in N[v] and u not in q_temp:
            q_temp.add(v)
q_temp2 = {i for i in range(n)}^q_temp
q1 &=q_temp2
Used = [1 if (u in q0 or u in q1) else 0 for u in range(n)]

for i in range(n):
    if not Used[i]:
        if len(q0)<n-1 and len(q1)<n-1:
            print(-1)
            exit()
mn = min(len(q0),len(q1))
if mn<n//2:
    print(mn*(mn-1)//2+(n-mn)*(n-mn-1)//2)
else:
    m=n//2
    print(m*(m-1)//2+(n-m)*(n-m-1)//2)

Submission status: Wrong Answer

Solution code:
#クリーク二つで覆えるか
#各州の都市の数で未知の本数は決まるので均等に分ける
#小さいほうのmaxとるかn//2とn+1//2で分けるか
n,m = map(int, input().split( ))
N = [set() for i in range(n)]
for i in range(m):
    ai,bi = map(int, input().split( ))
    ai-=1;bi-=1
    N[ai].add(bi)
    N[bi].add(ai)
#0の属するqulique
q0 = {v for v in N[0]}
q0.add(0)
q_remove = set()
for v in q0:
    for u in q0:
        if u!=v and u not in N[v] and v not in q_remove:
            print(u,v)
            q_remove.add(v)
q_temp2 = {i for i in range(n)}^q_remove
q0 &= q_temp2

v = -1
for u in range(n):
    if u not in q0:
        v = u
        break
if v ==-1 and len(q0)<n:
    print(-1)
    exit()

q1 = {u for u in N[v]}
q1.add(v)
q_temp = set()
for v in q1:
    for u in q1:
        if u!= v and u not in N[v] and u not in q_temp:
            q_temp.add(v)
q_temp2 = {i for i in range(n)}^q_temp
q1 &=q_temp2
Used = [1 if (u in q0 or u in q1) else 0 for u in range(n)]

for i in range(n):
    if not Used[i]:
        if len(q0)<n-1 and len(q1)<n-1:
            print(-1)
            exit()
mn = min(len(q0),len(q1))
if mn<n//2:
    print(mn*(mn-1)//2+(n-mn)*(n-mn-1)//2)
else:
    m=n//2
    print(m*(m-1)//2+(n-m)*(n-m-1)//2)

Submission status: Wrong Answer

Solution code:
import itertools
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

# MOD = 998244353


# つながってないところに辺を張る
# 二部グラフになるか
N, M = list(map(int, sys.stdin.buffer.readline().split()))
AB = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(M)]

edges = set()
for a, b in AB:
    a -= 1
    b -= 1
    edges.add((a, b))
    edges.add((b, a))

graph = [[] for _ in range(N)]
for a, b in itertools.combinations(range(N), r=2):
    if (a, b) not in edges:
        graph[a].append(b)
        graph[b].append(a)

ok = True
pairs = []
seen = [False] * N
for v in range(N):
    if seen[v]:
        continue
    evens = {v}
    odds = set()
    stack = [(v, True)]
    while stack:
        v, v_is_even = stack.pop()
        next_set = odds if v_is_even else evens
        for u in graph[v]:
            if u in next_set:
                continue
            next_set.add(u)
            stack.append((u, not v_is_even))
    if len(evens) + len(odds) != len(evens | odds):
        ok = False
        break
    pairs.append((len(evens), len(odds)))
    for v in evens:
        seen[v] = True
    for v in odds:
        seen[v] = True

# 二部グラフじゃないのが混じってた。ダメ
if not ok:
    print(-1)
    exit()
# pairs をどう分割するか
# どっちかを選んで作れる数を列挙する
can_make = [False] * (N + 1)
can_make[0] = True
for a, b in pairs:
    for i in reversed(range(len(can_make))):
        if can_make[i]:
            can_make[i + a] = True
            can_make[i + b] = True

ans = INF
for n in range(len(can_make)):
    if can_make[n]:
        m = N - n
        a = m * (m - 1) // 2
        b = n * (n - 1) // 2
        ans = min(ans, a + b)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
N,M=map(int,input().split())
data=[[0]*(N+1) for i in range(N+1)]
for i in range(M):
    A,B=map(int,input().split())
    data[A][B]=1
    data[B][A]=1
for i in range(1,N+1):
    data[i][i]=1
lst=[-1]*(N+1)
ddd=[]
for i in range(1,N+1):
    if lst[i]!=-1:
        continue
    else:
        lst[i]=0
        que=[i]
        count=[1,0]
        while que:
            h=[]
            for u in que:
                for j in range(1,N+1):
                    if data[u][j]==1:
                        continue
                    else:
                        if lst[j]==-1:
                            lst[j]=lst[u]^1
                            count[lst[j]]+=1
                            h.append(j)
                        elif lst[j]^lst[u]==0:
                            print(-1)
                            sys.exit()
            que=h
        ddd.append(count)
dp=[0]*(N+1)
dp[0]=1
for u in ddd:
    v=u[0]
    h=dp[:]
    for i in range(v,N+1):
        if dp[i-v]==1:
            h[i]=1
    v=u[1]
    for i in range(v,N+1):
        if dp[i-v]==1:
            h[i]=1
    dp=h
ans=0
for i in range(N+1):
    if dp[i]==1:
        if abs(N-2*ans)>abs(N-2*i):
            ans=i
qqq=N-ans
if qqq==0 or ans==0:
    print(N*(N-1)//2)
else:
    print(ans*(ans-1)//2+qqq*(qqq-1)//2)

Submission status: Wrong Answer

Solution code:
import sys

N,M=map(int,input().split())
data=[[0]*(N+1) for i in range(N+1)]
for i in range(M):
    A,B=map(int,input().split())
    data[A][B]=1
    data[B][A]=1
for i in range(1,N+1):
    data[i][i]=1

lst=[-1]*(N+1)
ddd=[]
for i in range(1,N+1):
    if lst[i]!=-1:
        continue
    else:
        lst[i]=0
        que=[i]
        count=[1,0]
        while que:
            h=[]
            for u in que:
                for j in range(1,N+1):
                    if data[u][j]==1:
                        continue
                    else:
                        if lst[j]==-1:
                            lst[j]=lst[u]^1
                            count[lst[j]]+=1
                            h.append(j)
                        elif lst[j]^lst[u]==0:
                            print(-1)
                            sys.exit()
            que=h
        ddd.append(count)

dp=[0]*(N+1)
dp[0]=1
for u in ddd:
    v=u[0]
    h=dp[:]
    for i in range(v,N+1):
        if dp[i-v]==1:
            h[i]=1
    dp=h
ans=0
for i in range(N+1):
    if dp[i]==1:
        if abs(N-2*ans)>abs(N-2*i):
            ans=i
qqq=N-ans
print(ans*(ans-1)//2+qqq*(qqq-1)//2)

Submission status: Wrong Answer

Solution code:

import math
import sys

def nCr(n,r):
    return math.factorial(n) // (math.factorial(n-r) * math.factorial(r))

def wantp(n):

    wpl = []
    while n != p[n]:
        wpl.append(n)
        n = p[n]

    for i in wpl:
        p[i] = n
    return n


N,M = map(int,input().split())

link = [[False] * N for i in range(N)]

for i in range(M):

    A,B = map(int,input().split())
    A -= 1
    B -= 1

    link[A][B] = True
    link[B][A] = True


#まず普通にUnion-Findする
p = [i for i in range(N)]
rank = [1] * N
for i in range(N):

    for j in range(N):

        if not link[i][j]:
            ip = wantp(i)
            jp = wantp(j)

            if ip != jp:

                if rank[ip] > rank[jp]:
                    p[jp] = ip
                elif rank[ip] < rank[jp]:
                    p[ip] = jp
                else:
                    p[ip] = jp
                    rank[jp] += 1
                    

dic = {} #親がキーで配列内に属す頂点を入れる(これで分類)

for i in range(N):
    np = wantp(i)
    if np not in dic:
        dic[np] = []
    dic[np].append(i)


side = [-1] * N #0と1サイドで分ける

for i in dic: #整合性の確認

    side[i] = 0
    for j in dic[i]:

        for k in dic[i]:
            if j != k and (not link[j][k]) and side[k] != -1:

                if side[j] == -1:
                    side[j] = side[k] ^ 1
                elif side[j] == side[k]:
                    print (-1)
                    sys.exit()

for i in dic: #整合性の確認2
    
    for j in dic[i]:

        for k in dic[i]:
            if j != k and (not link[j][k]) and side[k] != -1:

                if side[j] == side[k]:
                    print (-1)
                    sys.exit()



dic2 = {} #キーは先頭[0の数-1の数を入れる]

for i in range(N):
    np = wantp(i)
    if np not in dic2:
        dic2[np] = 0

    if side[i] == 0:
        dic2[np] += 1
    else:
        dic2[np] -= 1

allnum = [False] * 1401
allnum[0] = [True]

for i in dic2:
    dic2[i] = abs(dic2[i])

#dpで中心に一番近い数を求める

for i in dic2:
    nn = dic2[i]
    nall = [False] * 1401
    
    for j in range(1401):
        j -= 701
        if allnum[j]:
            nall[j + nn] = True
            nall[j - nn] = True

    allnum = nall.copy()

ans = float("inf")
for i in range(N):
    if nall[i] or nall[-1 * i]:
        a = (N-i) // 2
        b = (N+i) // 2

        nans = 0
        if a >= 2:
            nans += nCr(a,2)
        if b >= 2:
            nans += nCr(b,2)
        
        ans = min(nans,ans)

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