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

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_bipartite(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 -1
        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_bipartite(n, links))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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
        # cntはグループ数
        # self.cnt = 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.cnt -= 1
        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

#print(uf.state)
#print(uf.size_table)
#print(uncon)

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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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
  #print(dp)
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)

Submission status: Accepted

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

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

ans=[]
def is_bipartgraph():
    color=[0]*N
    used=[False]*N
    for i in range(N):
        if not used[i]:
            stack=[(i,1)]
            black=0
            white=0
            while stack:
                v,c=stack.pop()
                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)

Submission status: Accepted

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

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

ans=[]
def is_bipartgraph():
    color=[0]*N
    used=[False]*N
    for i in range(N):
        if not used[i]:
            stack=[(i,1)]
            black=0
            white=0
            while stack:
                v,c=stack.pop()
                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)

Submission status: Accepted

Solution code:
# 問題の趣旨：できるだけ辺が少なくなるように2つの完全グラフに分けたい
# まず、2つの完全グラフに分けられるのかを調べる必要がある。
# これが不可能であれば-1を出力して即座に終了。
# 分けられる場合は、できるだけ街の数を均等にしたい。

# 以下のアルゴリズムを考える。
# まずお互い繋がっていない都市の組A,Bを選ぶ。
# すると、Aにしか繋がっていない街、Bにしか繋がっていない街、
# 両方に繋がっている街の3グループに分かれる。
# 最初の2グループについてはグループのサイズを保存しておく。
# 最後のグループが空でない場合は、このグループに対してまた同様の処理を行う。
# 街がなくなるか、両方に繋がっている街のグループが
# 完全グラフになった時点で終了。

# 上記のアルゴリズムにより、グループのサイズの列と最後に残った街の数が求められる。
# これをもとに、動的計画法で考えられる街の振り分け方を全て洗い出す。
# 最も均等に近く振り分けた場合について、完全グラフの辺数を計算して
# 出力すれば問題が解ける。

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  # True→A、False→B
                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()

Submission status: Accepted

Solution code:
# 問題の趣旨：できるだけ辺が少なくなるように2つの完全グラフに分けたい
# まず、2つの完全グラフに分けられるのかを調べる必要がある。
# これが不可能であれば-1を出力して即座に終了。
# 分けられる場合は、できるだけ街の数を均等にしたい。

# 以下のアルゴリズムを考える。
# まずお互い繋がっていない都市の組A,Bを選ぶ。
# すると、Aにしか繋がっていない街、Bにしか繋がっていない街、
# 両方に繋がっている街の3グループに分かれる。
# 最初の2グループについてはグループのサイズを保存しておく。
# 最後のグループが空でない場合は、このグループに対してまた同様の処理を行う。
# 街がなくなるか、両方に繋がっている街のグループが
# 完全グラフになった時点で終了。

# 上記のアルゴリズムにより、グループのサイズの列と最後に残った街の数が求められる。
# これをもとに、動的計画法で考えられる街の振り分け方を全て洗い出す。
# 最も均等に近く振り分けた場合について、完全グラフの辺数を計算して
# 出力すれば問題が解ける。

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  # True→A、False→B
                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()

Submission status: Accepted

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

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

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

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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