input
stringlengths
20
127k
target
stringlengths
20
119k
problem_id
stringlengths
6
6
import sys input = sys.stdin.readline N, W = list(map(int, input().split())) wv = [[int(i) for i in input().split()] for _ in range(N)] def knapsack(i, w) : if i == N : return 0 M = knapsack(i + 1, w) if w >= wv[i][0] : M = max(M, knapsack(i + 1, w - wv[i][0]) + wv[i][1]) return M print((knapsack(0, W)))
import sys input = sys.stdin.readline N, W = list(map(int, input().split())) wv = [[int(i) for i in input().split()] for _ in range(N)] s = [[] for _ in range(4)] w0 = wv[0][0] for w, v in wv : s[w-w0].append(v) for i in range(4) : s[i].sort(reverse=True) s[i] = [0] + s[i] for j in range(1, len(s[i])) : s[i][j] += s[i][j-1] M = 0 for i0 in range(len(s[0])) : for i1 in range(len(s[1])) : for i2 in range(len(s[2])) : for i3 in range(len(s[3])) : if i0*w0+i1*(w0+1)+i2*(w0+2)+i3*(w0+3) <= W : M = max(M, s[0][i0]+s[1][i1]+s[2][i2]+s[3][i3]) print(M)
p03732
# -*- coding: utf-8 -*- """ 参考:https://img.atcoder.jp/arc073/editorial.pdf    https://ei1333.hateblo.jp/entry/2017/05/01/004235    https://atcoder.jp/contests/abc060/submissions/3782609 ・公式解 ・累積和あり """ import sys def input(): return sys.stdin.readline().strip() sys.setrecursionlimit(10 ** 9) from collections import defaultdict N, W = list(map(int, input().split())) wN = [0] * N vN = [[] for i in range(4)] for i in range(N): w, v = list(map(int, input().split())) if i == 0: offset = w vN[w-offset].append(v) # 重さ毎のリストを降順ソート for i in range(4): # 空リストのままだとこの後ループを回ってくれないので、[0]を追加する vN[i] = [0] + sorted(vN[i], reverse=True) # 累積和 for i in range(4): for j in range(1, len(vN[i])): vN[i][j] = vN[i][j-1] + vN[i][j] ans = 0 for i in range(len(vN[0])): for j in range(len(vN[1])): for k in range(len(vN[2])): for l in range(len(vN[3])): # 重さリミットを超えるパターンは対象外 if offset * i + (offset+1) * j + (offset+2) * k + (offset+3) * l > W: continue ans = max(vN[0][i] + vN[1][j] + vN[2][k] + vN[3][l], ans) print(ans)
# -*- coding: utf-8 -*- """ 参考:https://atcoder.jp/contests/abc060/submissions/3958560 ・前から普通にDPもdictでやってみる。 """ import sys def input(): return sys.stdin.readline().strip() sys.setrecursionlimit(10 ** 9) from collections import defaultdict N, W = list(map(int, input().split())) wN = [0] * N vN = [0] * N for i in range(N): wN[i], vN[i] = list(map(int, input().split())) # 重さの添字にはdictを使う dp = [defaultdict(int) for i in range(N+1)] dp[0][0] = 0 for i in range(N): for k, v in list(dp[i].items()): # 重さの条件がOKなら、今回の値を足したケースを次のステップに送る if k + wN[i] <= W: dp[i+1][k+wN[i]] = max(dp[i][k] + vN[i], dp[i+1][k+wN[i]]) # 足さないケースを送る dp[i+1][k] = max(dp[i][k], dp[i+1][k]) # 最適が重さWを全て使った場合とは限らないのでNステップ目のmaxを取る print((max(dp[N].values())))
p03732
import sys from collections import defaultdict, deque def main(): input = sys.stdin.readline N, W = list(map(int, input().split())) A = [tuple(map(int, input().split())) for _ in range(N)] d = defaultdict(lambda: 0) q = deque() for a in A: while len(q) > 0: w0, v0 = q.popleft() w1 = w0 + a[0] v1 = v0 + a[1] if w1 <= W: d[w1] = max(d[w1], v1) d[w0] = max(d[w0], v0) if a[0] <= W: q.append(a) for key in list(d.keys()): q.append((key, d[key])) ans = 0 for key in list(d.keys()): ans = max(ans, d[key]) return ans if __name__ == '__main__': print((main()))
# Editorial import sys from itertools import accumulate def main(): input = sys.stdin.readline N, W = list(map(int, input().split())) V = [[] for _ in range(4)] w0, v0 = list(map(int, input().split())) V[0].append(v0) for _ in range(N-1): w, v = list(map(int, input().split())) V[w-w0].append(v) for i in range(4): V[i] = list(accumulate([0] + sorted(V[i], key=lambda x: -x))) ans = 0 for i in range(len(V[0])): for j in range(len(V[1])): for k in range(len(V[2])): weight = w0 * i + (w0 + 1) * j + (w0 + 2) * k if weight <= W: l = min(len(V[3]) - 1, (W - weight) // (w0 + 3)) ans = max(ans, V[0][i] + V[1][j] + V[2][k] + V[3][l]) return ans if __name__ == '__main__': print((main()))
p03732
from collections import defaultdict N,W=list(map(int,input().split())) a=defaultdict(lambda:[]) for i in range(N): w,v=list(map(int,input().split())) a[w]=a[w]+[v] for i,j in list(a.items()): a[i]=sorted(j,reverse=True) lst=[] for i,j in list(a.items()): lst.append( (i,len(j)) ) max_val=0 if len(lst)==1: w1=lst[0][0] c1=lst[0][1] for i in range(c1+1): if i*w1<=W: max_val=max(max_val, sum(a[w1][:i])) elif len(lst)==2: w1=lst[0][0]; w2=lst[1][0] c1=lst[0][1]; c2=lst[1][1] for i in range(c1+1): for j in range(c2+1): if i*w1+j*w2<=W: max_val=max(max_val, sum(a[w1][:i])+sum(a[w2][:j])) elif len(lst)==3: w1=lst[0][0]; w2=lst[1][0]; w3=lst[2][0] c1=lst[0][1]; c2=lst[1][1]; c3=lst[2][1] for i in range(c1+1): for j in range(c2+1): for k in range(c3+1): if i*w1+j*w2+k*w3<=W: max_val=max(max_val, sum(a[w1][:i])+sum(a[w2][:j])+sum(a[w3][:k])) elif len(lst)==4: w1=lst[0][0]; w2=lst[1][0]; w3=lst[2][0]; w4=lst[3][0] c1=lst[0][1]; c2=lst[1][1]; c3=lst[2][1]; c4=lst[3][1] for i in range(c1+1): for j in range(c2+1): for k in range(c3+1): for m in range(c4+1): if i*w1+j*w2+k*w3+m*w4<=W: max_val=max(max_val, sum(a[w1][:i])+sum(a[w2][:j])+sum(a[w3][:k])+sum(a[w4][:m])) print(max_val)
from collections import defaultdict N,W=list(map(int,input().split())) wv=[] for i in range(N): w,v=list(map(int,input().split())) wv.append((w,v)) dp=defaultdict(lambda: 0) # Weight:Value dp[0]=0 for w1,v1 in wv: d=dp.copy() for w,v in list(dp.items()): dp[w+w1]=max( dp[w+w1], d[w]+v1 ) l1=[x for x in list(dp.items()) if x[0]<=W] print(sorted(l1, key=lambda x: x[1],reverse=True)[0][1])
p03732
N, W = list(map(int, input().split())) data = tuple(tuple(map(int, input().split())) for _ in range(N)) table = [dict() for _ in range(N + 1)] table[0][0] = 0 for n in range(N): weight, value = data[n] for w, now in list(table[n].items()): table[n + 1][w] = max(table[n + 1].get(w, 0), now) if w + weight <= W: table[n + 1][w + weight] = max(table[n + 1].get(w + weight, 0), now + value) print((max(table[N].values())))
N, W = list(map(int, input().split())) data = tuple(tuple(map(int, input().split())) for _ in range(N)) d = {0: 0} for n in range(N): weight, value = data[n] for w, now in list(d.copy().items()): if w + weight <= W: d[w + weight] = max(d.get(w + weight, 0), now + value) print((max(d.values())))
p03732
#入力 n, W=list(map(int, input().split())) w,v=[],[] for i in range(n): a,b=list(map(int,input().split())) w.append(a) v.append(b) # i番目以降から重さの総和がj 以下になるように選んだ時の重量 def rec(i,j): #既に計算されているなら、メモdp[][]を受け取る if dp[i][j]>=0: return dp[i][j] if i==n:#もう品物がないから終わり res=0 elif w[i]>j:#i番目の荷物は入らないから次へ res= rec(i+1,j) else:#i番目の荷物が入る場合と入らない場合の両方を試す res=max(rec(i+1,j), rec(i+1,j-w[i]) +v[i]) dp[i][j]=res return res dp=[[-1 for i in range(W+1)] for j in range(n+1)]#メモの初期化 print((rec(0,W)))
N, W = list(map(int, input().split())) value_table = [[] for i in range(4)] for i in range(N): w, v = list(map(int,input().split())) if i == 0: w1 = w value_table[w-w1] += [v] [value_table[i].sort(reverse=True) for i in range(4)] ans = 0 value_table_ruiseki = [[0] for i in range(4)] for i in range(4): for v in value_table[i]: value_table_ruiseki[i] += [value_table_ruiseki[i][-1] + v] ans = 0 for i, iv in enumerate(value_table_ruiseki[0]): for j, jv in enumerate(value_table_ruiseki[1]): for k, kv in enumerate(value_table_ruiseki[2]): for ell, ellv in enumerate(value_table_ruiseki[3]): weight = i*w1 + j*(w1+1) + k*(w1+2) + ell*(w1+3) value = iv + jv + kv + ellv if weight <=W: ans = max(ans, value) print(ans)
p03732
N,W=list(map(int,input().split())) v=[[],[],[],[]] kosu=[0,0,0,0] kr=list(map(int,input().split())) v[0].append(kr[1]) w0=kr[0] for i in range(1,N): kr=list(map(int,input().split())) v[kr[0]-w0].append(kr[1]) for i in range(4): v[i].sort() v[i].reverse() kos=[len(v[0]),len(v[1]),len(v[2]),len(v[3])] def toru(a,b,c,d,nw): max=0 if a<kos[0] and W>=nw+w0 and max<toru(a+1,b,c,d,nw+w0)+v[0][a]: max=toru(a+1,b,c,d,nw+w0)+v[0][a] if b<kos[1] and W>=nw+w0+1 and max<toru(a,b+1,c,d,nw+w0+1)+v[1][b]: max=toru(a,b+1,c,d,nw+w0+1)+v[1][b] if c<kos[2] and W>=nw+w0+2 and max<toru(a,b,c+1,d,nw+w0+2)+v[2][c]: max=toru(a,b,c+1,d,nw+w0+2)+v[2][c] if d<kos[3] and W>=nw+w0+3 and max<toru(a,b,c,d+1,nw+w0+3)+v[3][d]: max=toru(a+1,b,c,d+1,nw+w0+3)+v[3][d] return max maxv=toru(0,0,0,0,0) print(maxv)
N,W=list(map(int,input().split())) v=[[],[],[],[]] kosu=[0,0,0,0] kr=list(map(int,input().split())) v[0].append(kr[1]) w0=kr[0] for i in range(1,N): kr=list(map(int,input().split())) v[kr[0]-w0].append(kr[1]) for i in range(4): v[i].sort() v[i].reverse() kos=[len(v[0]),len(v[1]),len(v[2]),len(v[3])] kk=[-1]*((kos[0]+1)*(kos[1]+1)*(kos[2]+1)*(kos[3]+1)) def toru(a,b,c,d,nw): global kk if kk[a+(kos[0]+1)*(b+((kos[1]+1)*(c+(kos[2]+1)*d)))]!=-1: return kk[a+(kos[0]+1)*(b+((kos[1]+1)*(c+(kos[2]+1)*d)))] max=0 if a<kos[0] and W>=nw+w0 and max<toru(a+1,b,c,d,nw+w0)+v[0][a]: max=toru(a+1,b,c,d,nw+w0)+v[0][a] if b<kos[1] and W>=nw+w0+1 and max<toru(a,b+1,c,d,nw+w0+1)+v[1][b]: max=toru(a,b+1,c,d,nw+w0+1)+v[1][b] if c<kos[2] and W>=nw+w0+2 and max<toru(a,b,c+1,d,nw+w0+2)+v[2][c]: max=toru(a,b,c+1,d,nw+w0+2)+v[2][c] if d<kos[3] and W>=nw+w0+3 and max<toru(a,b,c,d+1,nw+w0+3)+v[3][d]: max=toru(a,b,c,d+1,nw+w0+3)+v[3][d] kk[a+(kos[0]+1)*(b+((kos[1]+1)*(c+(kos[2]+1)*d)))]=max return max maxv=toru(0,0,0,0,0) print(maxv)
p03732
n,W = list(map(int,input().split())) w = [0]*n v = [0]*n for i in range(n): w[i],v[i] = list(map(int,input().split())) x = w[0] for i in range(n): w[i] -= x dp = [[[0]*(4*n+1) for _ in range(n+1)] for _ in range(n+1)] for i in range(n): for j in range(i+1): for k in range(4*n+1): if (j+1)*x+k <= W and k-w[i] >= 0: dp[i+1][j+1][k] = max(dp[i+1][j+1][k],dp[i][j][k-w[i]]+v[i]) dp[i+1][j][k] = max(dp[i+1][j][k],dp[i][j][k]) """ for i in range(n+1): print(i,"///////////////////////////////////////////////") for j in range(n+1): print(dp[i][j]) """ print((max(max(dp[n][j]) for j in range(n+1))))
n,W = list(map(int,input().split())) lst = [[0]*(n+1) for _ in range(4)] for i in range(n): w,v = list(map(int,input().split())) if i == 0: x = w lst[w-x].append(v) for i in range(4): lst[i].sort(reverse=True) for j in range(n): lst[i][j+1] += lst[i][j] ans = 0 for a in range(n+1): for b in range(n+1-a): for c in range(n+1-a-b): if x*a+(x+1)*b+(x+2)*c > W: continue d = max((W-x*a-(x+1)*b-(x+2)*c)//(x+3),0) sumv = 0 for i,j in enumerate((a,b,c,d)): if j == 0: continue sumv += lst[i][j-1] ans = max(sumv,ans) print(ans)
p03732
N, W = list(map(int, input().split())) weights = [] values = [] for i in range(N): lst = [int(e) for e in input().split()] weights.append(lst[0]) values.append(lst[1]) #df = np.array(ary) def rec(i, j): if i == N: return 0 elif j < weights[i]: return rec(i+1, j) else: return max(rec(i+1, j), rec(i+1, j-weights[i]) + values[i]) print((rec(0, W)))
N, W = list(map(int, input().split())) weights = [] values = [] for i in range(N): lst = [int(e) for e in input().split()] weights.append(lst[0]) values.append(lst[1]) dp = [{} for j in range(N+1)] def rec(i, j): if j in dp[i]: return dp[i][j] res = 0 if i == N: res = 0 elif j < weights[i]: res = rec(i+1, j) else: res = max( rec(i+1, j), rec(i+1, j-weights[i]) + values[i] ) dp[i][j] = res return res print((rec(0, W)))
p03732
from collections import * N,W = list(map(int,input().split())) dp = defaultdict(int) dp[0] = 0 for n in range(N): w,v = list(map(int,input().split())) for k,b in list(dp.copy().items()): if k+w<=W: dp[k+w] = max(dp[k+w],b+v) print((max(dp.values())))
from collections import * N,W = list(map(int,input().split())) dp = defaultdict(int) dp[0] = 0 for n in range(N): w1,v1 = list(map(int,input().split())) for w2,v2 in list(dp.copy().items()): if w1+w2<=W: dp[w1+w2] = max(dp[w1+w2],v1+v2) print((max(dp.values())))
p03732
from collections import defaultdict n, W = list(map(int, input().split())) dd = defaultdict(list) for i in range(n): weight, value = list(map(int, input().split())) dd[weight].append(value) a = min(dd.keys()) b, c, d = a+1, a+2, a+3 Vcum = defaultdict(lambda: [0]) for k in [a, b, c, d]: s = 0 dd[k].sort(reverse=True) for val in dd[k]: s += val Vcum[k].append(s) ans = 0 for w in range(len(dd[a])+1): for x in range(len(dd[b])+1): for y in range(len(dd[c])+1): for z in range(len(dd[d])+1): if W < a*w+b*x+c*y+d*z: continue val = Vcum[a][w]+Vcum[b][x]+Vcum[c][y]+Vcum[d][z] ans = max(ans, val) print(ans)
from collections import defaultdict n, W = list(map(int, input().split())) dd = defaultdict(list) for i in range(n): weight, value = list(map(int, input().split())) dd[weight].append(value) a = min(dd.keys()) b, c, d = a+1, a+2, a+3 Vcum = defaultdict(lambda: [0]) for k in [a, b, c, d]: s = 0 dd[k].sort(reverse=True) for val in dd[k]: s += val Vcum[k].append(s) ans = 0 for w in range(len(dd[a])+1): for x in range(len(dd[b])+1): for y in range(len(dd[c])+1): if W < a*w+b*x+c*y: break z = min((W-a*w-b*x-c*y)//d, len(dd[d])) val = Vcum[a][w]+Vcum[b][x]+Vcum[c][y]+Vcum[d][z] ans = max(ans, val) print(ans)
p03732
n, W = list(map(int, input().split())) wv = [list(map(int, input().split())) for _ in range(n)] dp = [[[-1] * (3 * n + 1) for _ in range(n + 1)] for _ in range(n + 1)] dp[0][0][0] = 0 w1 = wv[0][0] for i, (w, v) in enumerate(wv): for j in range(i + 1): for k in range(3 * n + 1): if dp[i][j][k] != -1: dp[i+1][j][k] = max(dp[i+1][j][k], dp[i][j][k]) w_diff = w - w1 if j + 1 <= n and k + w_diff <= 3 * n: dp[i+1][j+1][k+w_diff] = max(dp[i+1][j+1][k+w_diff], dp[i][j][k] + v) ans = 0 for j in range(n + 1): w_diff_mx = min(W - w1 * j, 3 * n) for k in range(w_diff_mx + 1): ans = max(ans, dp[n][j][k]) print(ans)
from itertools import accumulate n, W = list(map(int, input().split())) wv = [list(map(int, input().split())) for _ in range(n)] w1 = wv[0][0] weights = [[] for _ in range(4)] for w, v in wv: w_diff = w - w1 weights[w_diff].append(v) for i in range(4): weights[i].sort(reverse=True) acc = [[0] + list(accumulate(li)) for li in weights] ans = 0 for i, e1 in enumerate(acc[0]): for j, e2 in enumerate(acc[1]): for k, e3 in enumerate(acc[2]): for l, e4 in enumerate(acc[3]): if w1 * i + (w1 + 1) * j + (w1 + 2) * k + (w1 + 3) * l <= W: ans = max(ans, e1 + e2 + e3 + e4) print(ans)
p03732
from itertools import accumulate n, W = list(map(int, input().split())) wv = [list(map(int, input().split())) for _ in range(n)] w1 = wv[0][0] weights = [[] for _ in range(4)] for w, v in wv: w_diff = w - w1 weights[w_diff].append(v) for i in range(4): weights[i].sort(reverse=True) acc = [[0] + list(accumulate(li)) for li in weights] ans = 0 for i, e1 in enumerate(acc[0]): for j, e2 in enumerate(acc[1]): for k, e3 in enumerate(acc[2]): for l, e4 in enumerate(acc[3]): if w1 * i + (w1 + 1) * j + (w1 + 2) * k + (w1 + 3) * l <= W: ans = max(ans, e1 + e2 + e3 + e4) print(ans)
from itertools import accumulate n, W = list(map(int, input().split())) wv = [list(map(int, input().split())) for _ in range(n)] w1 = wv[0][0] weights = [[] for _ in range(4)] for w, v in wv: w_diff = w - w1 weights[w_diff].append(v) for i in range(4): weights[i].sort(reverse=True) acc = [[0] + list(accumulate(li)) for li in weights] l3 = len(weights[3]) ans = 0 for i, e1 in enumerate(acc[0]): for j, e2 in enumerate(acc[1]): for k, e3 in enumerate(acc[2]): w_sm = w1 * i + (w1 + 1) * j + (w1 + 2) * k if w_sm > W: break l = min((W - w_sm) // (w1 + 3), l3) val = acc[0][i] + acc[1][j] + acc[2][k] + acc[3][l] ans = max(ans, val) print(ans)
p03732
N, W = list(map(int, input().split())) wv = [list(map(int, input().split())) for i in range(N)] w1 = wv[0][0] w_to_idx = {0:0} idx_to_w = {0:0} idx_W = 0 def calc(): global w_to_idx, idx_to_w, idx_W idx = 1 w_max = 0 for i in range(1, N+1): w = w1*i for j in range(3*i + 1): ww = w + j if ww in w_to_idx: continue w_to_idx[ww] = idx idx_to_w[idx] = ww if w_max < ww <= W: w_max = ww idx_W = idx idx += 1 calc() n = len(w_to_idx) dp = [[0]*n for i in range(N+1)] for i, (w, v) in enumerate(wv, 1): for j in range(n): dp[i][j] = dp[i-1][j] ww = idx_to_w[j] if ww >= w and ww-w in w_to_idx: jj = w_to_idx[ww - w] dp[i][j] = max(dp[i][j], dp[i-1][jj] + v) print((max(dp[-1][:idx_W+1])))
from itertools import accumulate N, W = list(map(int, input().split())) wv = {} w1 = 0 for i in range(N): w, v = list(map(int, input().split())) if i == 0: w1 = w if w in wv: wv[w].append(v) else: wv[w] = [v] for w in wv: wv[w].sort(reverse=True) wv[w] = [0] + list(accumulate(wv[w])) w2 = w1+1; w3 = w1+2; w4 = w1+3 for w in [w1, w1+1, w1+2, w1+3]: if w not in wv: wv[w] = [0] ans = 0 for n1 in range(len(wv[w1])): for n2 in range(len(wv[w2])): for n3 in range(len(wv[w3])): for n4 in range(len(wv[w4])): w = w1*n1 + w2*n2 + w3*n3 + w4*n4 if w <= W: ans = max(ans, wv[w1][n1]+wv[w2][n2]+wv[w3][n3]+wv[w4][n4]) print(ans)
p03732
def d_simple_knapsack(N, W, Baggage): from collections import defaultdict # dp[w]:ナップサックに重さがwになるように荷物を入れたときの価値の最大値 dp = defaultdict(int) dp[0] = 0 # 重さ0で達成できる価値は0とする for w, v in Baggage: # dpの各要素(現時点におけるナップサック内の荷物の重さ)に対して、 # 注目した荷物を入れても重さがWを超えなければ、 # ナップサックに荷物を入れて価値の最大値を更新する tmp = defaultdict(int) # 価値の最大値を更新できた荷物の重さの情報 for kw, kv in list(dp.items()): if kw + w <= W: if kw + w in dp: tmp[kw + w] = max(dp[kw + w], kv + v) else: tmp[kw + w] = kv + v for key, value in list(tmp.items()): dp[key] = value ans = max(dp.values()) return ans N, W = [int(i) for i in input().split()] Baggage = [[int(i) for i in input().split()] for j in range(N)] print((d_simple_knapsack(N, W, Baggage)))
def d_simple_knapsack(N, W, Baggage): from collections import defaultdict # dp[w]:ナップサックに重さがwになるように荷物を入れたときの価値の最大値 dp = defaultdict(int) dp[0] = 0 # 重さ0で達成できる価値は0とする for w, v in Baggage: # dpの各要素(現時点におけるナップサック内の荷物の重さ)に対して、 # 注目した荷物を入れても重さがWを超えなければ、 # ナップサックに荷物を入れて価値の最大値を更新する latest_dp = list(dp.items()) for kw, kv in latest_dp: if kw + w <= W: dp[kw + w] = max(dp[kw + w], kv + v) ans = max(dp.values()) return ans N, W = [int(i) for i in input().split()] Baggage = [[int(i) for i in input().split()] for j in range(N)] print((d_simple_knapsack(N, W, Baggage)))
p03732
import sys read = sys.stdin.read readline = sys.stdin.readline readlines = sys.stdin.readlines sys.setrecursionlimit(10 ** 9) INF = 1 << 60 MOD = 1000000007 def solve1(N, W, weight, value): dp = [[0] * (W + 1) for _ in range(N + 1)] for i in range(N): for w in range(W + 1): if w - weight[i] >= 0: dp[i + 1][w] = dp[i][w - weight[i]] + value[i] if dp[i + 1][w] < dp[i][w]: dp[i + 1][w] = dp[i][w] return dp[N][W] def solve2(N, W, weight, value): w0 = weight[0] M = W // w0 if M == 0: return 0 weight_adj = [w - w0 for w in weight] w_total = sum(weight_adj) dp = [[[0] * (w_total + 1) for j in range(N + 1)] for i in range(M + 1)] for i in range(M): for j in range(N): for w in range(w_total + 1): if w - weight_adj[j] >= 0: dp[i + 1][j + 1][w] = dp[i][j][w - weight_adj[j]] + value[j] if dp[i + 1][j + 1][w] < dp[i + 1][j][w]: dp[i + 1][j + 1][w] = dp[i + 1][j][w] if dp[i + 1][j + 1][w] < dp[i][j + 1][w]: dp[i + 1][j + 1][w] = dp[i][j + 1][w] return max(dp[M][N][min(W - w0 * M, w_total)], dp[M - 1][N][min(W - w0 * (M - 1), w_total)]) def main(): N, W, *wv = list(map(int, read().split())) weight = wv[::2] value = wv[1::2] if weight[0] < 500: ans = solve1(N, W, weight, value) else: ans = solve2(N, W, weight, value) print(ans) return if __name__ == '__main__': main()
import sys from itertools import accumulate read = sys.stdin.read readline = sys.stdin.readline readlines = sys.stdin.readlines sys.setrecursionlimit(10 ** 9) INF = 1 << 60 MOD = 1000000007 def main(): N, W, *wv = list(map(int, read().split())) w0 = wv[0] weight = [[] for _ in range(4)] for w, v in zip(*[iter(wv)] * 2): weight[w - w0].append(v) for i in range(4): weight[i].sort(reverse=True) csum = [[0] for _ in range(4)] for i in range(4): csum[i].extend(accumulate(weight[i])) def dfs(w, v, idx): if idx == 4: return v ans = 0 for i in range(len(csum[idx])): if w + (w0 + idx) * i > W: break ans = max(ans, dfs(w + (w0 + idx) * i, v + csum[idx][i], idx + 1)) return ans print((dfs(0, 0, 0))) return if __name__ == '__main__': main()
p03732
import sys from itertools import accumulate read = sys.stdin.read readline = sys.stdin.readline readlines = sys.stdin.readlines sys.setrecursionlimit(10 ** 9) INF = 1 << 60 MOD = 1000000007 def main(): N, W, *WV = list(map(int, read().split())) weight = WV[::2] value = WV[1::2] w_min = min(weight) items = [[] for _ in range(4)] for w, v in zip(weight, value): items[w - w_min].append(v) for i in range(4): items[i].sort(reverse=True) csums = [0] * 4 for i in range(4): csums[i] = [0] csums[i].extend(accumulate(items[i])) def rec(i, vec): if i == 4: ans = 0 w_total = 0 for j in range(4): w_total += (w_min + j) * vec[j] if w_total > W: return -1 for j in range(4): ans += csums[j][vec[j]] return ans ans = 0 for j in range(len(csums[i])): vec.append(j) ans = max(ans, rec(i + 1, vec)) vec.pop() return ans print((rec(0, []))) return if __name__ == '__main__': main()
import sys from itertools import accumulate read = sys.stdin.read readline = sys.stdin.readline readlines = sys.stdin.readlines sys.setrecursionlimit(10 ** 9) INF = 1 << 60 MOD = 1000000007 def main(): N, W, *WV = list(map(int, read().split())) weight = WV[::2] value = WV[1::2] w_min = min(weight) items = [[] for _ in range(4)] for w, v in zip(weight, value): items[w - w_min].append(v) for i in range(4): items[i].sort(reverse=True) csums = [0] * 4 for i in range(4): csums[i] = [0] csums[i].extend(accumulate(items[i])) def rec(i, w, v): if i == 4: if w <= W: return v else: return -1 ans = 0 for j in range(len(csums[i])): ans = max(ans, rec(i + 1, w + (w_min + i) * j, v + csums[i][j])) return ans print((rec(0, 0, 0))) return if __name__ == '__main__': main()
p03732
n, w = list(map(int, input().split())) items = [list(map(int, input().split())) for _ in range(n)] if w < items[0][0] : print((0)) exit() w_sum = 0 v_sum = 0 for i in range(n): w_sum += items[i][0] v_sum += items[i][1] if w >= w_sum: print(v_sum) exit() dp = {} #for j in range(1,w+1): for j in range(items[0][0],w+1): for i in range(1,n+1): if j-items[i-1][0] >= 0: if str(i-1)+":"+str(j) not in dp: dp[str(i - 1) + ":" + str(j)] = 0 if str(i-1)+":"+str(j-items[i-1][0]) not in dp: dp[str(i - 1) + ":" + str(j - items[i - 1][0])] = 0 dp[str(i)+":"+str(j)] = max(dp[str(i-1)+":"+str(j)],dp[str(i-1)+":"+str(j-items[i-1][0])]+items[i-1][1]) else: if str(i-1)+":"+str(j) not in dp: dp[str(i - 1) + ":" + str(j)] = 0 dp[str(i)+":"+str(j)] = dp[str(i-1)+":"+str(j)] print((dp[str(n)+":"+str(w)]))
N,W=list(map(int,input().split())) dp=[[-1]*301 for i in range(N+1)] dp[0][0]=0 for i in range(N): w,v=list(map(int,input().split())) if i==0: base=w for i in range(N)[::-1]: for j in range(301)[::-1]: if dp[i][j]!=-1: dp[i+1][j+w-base]=max(dp[i][j]+v,dp[i+1][j+w-base]) ans=0 for index,item in enumerate(dp): if W-index*base+1<=0: break ans=max(max(item[:W-index*base+1]),ans) print(ans)
p03732
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1]) wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): if wv[i][0]==w0: k=wv[i][1]+x[0][-1] l=len(x[0]) if l*w0<=w:x[0].append(k) elif wv[i][0]==w0+1: k=wv[i][1]+x[1][-1] l=len(x[1]) if l*(w0+1)<=w:x[1].append(k) elif wv[i][0]==w0+2: k=wv[i][1]+x[2][-1] l=len(x[2]) if l*(w0+2)<=w:x[2].append(k) else: k=wv[i][1]+x[3][-1] l=len(x[3]) if l*(w0+3)<=w:x[3].append(k) #print(x) ma=0 for i in range(len(x[0])): for j in range(len(x[1])): for k in range(len(x[2])): for l in range(len(x[3])): ma_sub=0 if i*w0+j*(w0+1)+k*(w0+2)+l*(w0+3)<=w: ma_sub+=x[0][i] ma_sub+=x[1][j] ma_sub+=x[2][k] ma_sub+=x[3][l] ma=max(ma,ma_sub) print(ma)
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1]) wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): if wv[i][0]==w0: k=wv[i][1]+x[0][-1] l=len(x[0]) if l*w0<=w:x[0].append(k) elif wv[i][0]==w0+1: k=wv[i][1]+x[1][-1] l=len(x[1]) if l*(w0+1)<=w:x[1].append(k) elif wv[i][0]==w0+2: k=wv[i][1]+x[2][-1] l=len(x[2]) if l*(w0+2)<=w:x[2].append(k) else: k=wv[i][1]+x[3][-1] l=len(x[3]) if l*(w0+3)<=w:x[3].append(k) #print(x) ma=0 for i in range(len(x[0])): for j in range(len(x[1])): for k in range(len(x[2])): for l in range(len(x[3])): if i*w0+j*(w0+1)+k*(w0+2)+l*(w0+3)<=w: ma_sub=0 ma_sub+=x[0][i] ma_sub+=x[1][j] ma_sub+=x[2][k] ma_sub+=x[3][l] ma=max(ma,ma_sub) else: break print(ma)
p03732
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1]) wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): if wv[i][0]==w0: k=wv[i][1]+x[0][-1] l=len(x[0]) if l*w0<=w:x[0].append(k) elif wv[i][0]==w0+1: k=wv[i][1]+x[1][-1] l=len(x[1]) if l*(w0+1)<=w:x[1].append(k) elif wv[i][0]==w0+2: k=wv[i][1]+x[2][-1] l=len(x[2]) if l*(w0+2)<=w:x[2].append(k) else: k=wv[i][1]+x[3][-1] l=len(x[3]) if l*(w0+3)<=w:x[3].append(k) #print(x) ma=0 for i in range(len(x[0])): for j in range(len(x[1])): for k in range(len(x[2])): for l in range(len(x[3])): if i*w0+j*(w0+1)+k*(w0+2)+l*(w0+3)<=w: ma_sub=0 ma_sub+=x[0][i] ma_sub+=x[1][j] ma_sub+=x[2][k] ma_sub+=x[3][l] ma=max(ma,ma_sub) else: break print(ma)
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1]) wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): if wv[i][0]==w0: k=wv[i][1]+x[0][-1] l=len(x[0]) if l*w0<=w:x[0].append(k) elif wv[i][0]==w0+1: k=wv[i][1]+x[1][-1] l=len(x[1]) if l*(w0+1)<=w:x[1].append(k) elif wv[i][0]==w0+2: k=wv[i][1]+x[2][-1] l=len(x[2]) if l*(w0+2)<=w:x[2].append(k) else: k=wv[i][1]+x[3][-1] l=len(x[3]) if l*(w0+3)<=w:x[3].append(k) #print(x) ma=0 for i in range(len(x[0])): for j in range(len(x[1])): for k in range(len(x[2])): for l in range(len(x[3])): if i*w0+j*(w0+1)+k*(w0+2)+l*(w0+3)<=w: ma_sub=x[0][i]+x[1][j]+x[2][k]+x[3][l] ma=max(ma,ma_sub) else: break print(ma)
p03732
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1]) wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): if wv[i][0]==w0: k=wv[i][1]+x[0][-1] l=len(x[0]) if l*w0<=w:x[0].append(k) elif wv[i][0]==w0+1: k=wv[i][1]+x[1][-1] l=len(x[1]) if l*(w0+1)<=w:x[1].append(k) elif wv[i][0]==w0+2: k=wv[i][1]+x[2][-1] l=len(x[2]) if l*(w0+2)<=w:x[2].append(k) else: k=wv[i][1]+x[3][-1] l=len(x[3]) if l*(w0+3)<=w:x[3].append(k) #print(x) ma=0 for i in range(len(x[3])): for j in range(len(x[2])): for k in range(len(x[1])): for l in range(len(x[0])): if i*(w0+3)+j*(w0+2)+k*(w0+1)+l*w0<=w: ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][l] ma=max(ma,ma_sub) else: break print(ma)
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1]) wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): if wv[i][0]==w0: k=wv[i][1]+x[0][-1] l=len(x[0]) if l*w0<=w:x[0].append(k) elif wv[i][0]==w0+1: k=wv[i][1]+x[1][-1] l=len(x[1]) if l*(w0+1)<=w:x[1].append(k) elif wv[i][0]==w0+2: k=wv[i][1]+x[2][-1] l=len(x[2]) if l*(w0+2)<=w:x[2].append(k) else: k=wv[i][1]+x[3][-1] l=len(x[3]) if l*(w0+3)<=w:x[3].append(k) #print(x) ma=0 for i in range(len(x[3])): for j in range(len(x[2])): for k in range(len(x[1])): #for l in range(len(x[0])): d=w-(i*(w0+3)+j*(w0+2)+k*(w0+1)) if d>=0: ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,len(x[0])-1)] ma=max(ma,ma_sub) print(ma)
p03732
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1])#reverse wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): z=wv[i][0]-w0 k=wv[i][1]+x[z][-1] l=len(x[z]) if l*wv[i][0]<=w: x[z].append(k) ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) for i in range(l3): for j in range(l2): for k in range(l1): d=w-(i*(w0+3)+j*(w0+2)+k*(w0+1)) if d>=0: ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,len(x[0])-1)] ma=max(ma,ma_sub) print(ma)
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1])#reverse wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): z=wv[i][0]-w0 k=wv[i][1]+x[z][-1] l=len(x[z]) if l*wv[i][0]<=w: x[z].append(k) ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) for i in range(l3): for j in range(l2): for k in range(l1): d=w-(i*(w0+3)+j*(w0+2)+k*(w0+1)) if d>=0: ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,len(x[0])-1)] ma=max(ma,ma_sub) print(ma)
p03732
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1])#reverse wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): z=wv[i][0]-w0 k=wv[i][1]+x[z][-1] l=len(x[z]) if l*wv[i][0]<=w: x[z].append(k) ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) for i in range(l3): for j in range(l2): for k in range(l1): d=w-(i*(w0+3)+j*(w0+2)+k*(w0+1)) if d>=0: ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,len(x[0])-1)] ma=max(ma,ma_sub) print(ma)
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1])#reverse wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): z=wv[i][0]-w0 k=wv[i][1]+x[z][-1] l=len(x[z]) if l*wv[i][0]<=w: x[z].append(k) ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) for i in range(l3): d=w-i*(w0+3) for j in range(l2): d=w-i*(w0+3)-j*(w0+2) if d>=0: for k in range(l1): d=w-i*(w0+3)-j*(w0+2)-k*(w0+1) if d>=0: ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,len(x[0])-1)] ma=max(ma,ma_sub) else: break else: break print(ma)
p03732
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1])#reverse wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): z=wv[i][0]-w0 k=wv[i][1]+x[z][-1] l=len(x[z]) if l*wv[i][0]<=w: x[z].append(k) ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) l0=len(x[0]) for i in range(l3): for j in range(l2): d=w-i*(w0+3)-j*(w0+2) if d>=0: for k in range(l1): d=w-i*(w0+3)-j*(w0+2)-k*(w0+1) if d>=0: m=min(d//w0,l0-1) ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][m] ma=max(ma,ma_sub) else: break else: break print(ma)
n,w=list(map(int,input().split())) wv=[list(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1])#reverse wv.sort(key=lambda x:x[0]) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): z=wv[i][0]-w0 k=wv[i][1]+x[z][-1] l=len(x[z]) if l*wv[i][0]<=w: x[z].append(k) ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) l0=len(x[0]) for i in range(l3): for j in range(l2): d=w-i*(w0+3)-j*(w0+2) if d>=0: for k in range(l1): d=w-i*(w0+3)-j*(w0+2)-k*(w0+1) if d>=0: ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,l0-1)] ma=max(ma,ma_sub) else: break else: break print(ma)
p03732
from operator import itemgetter n,w=list(map(int,input().split())) wv=[tuple(map(int,input().split())) for i in range(n)] wv.sort(key=itemgetter(1),reverse=True)#reverse wv.sort(key=itemgetter(0)) #print(wv) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): z=wv[i][0]-w0 k=wv[i][1]+x[z][-1] l=len(x[z]) if l*wv[i][0]<=w: x[z].append(k) ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) l0=len(x[0]) for i in range(l3): for j in range(l2): d=w-i*(w0+3)-j*(w0+2) if d>=0: for k in range(l1): d=w-i*(w0+3)-j*(w0+2)-k*(w0+1) if d>=0: ma_sub=x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,l0-1)] ma=max(ma,ma_sub) else: break else: break print(ma)
n,w=list(map(int,input().split())) wv=[tuple(map(int,input().split())) for i in range(n)] wv.sort(key=lambda x:-x[1])#reverse wv.sort(key=lambda x:x[0]) w0=wv[0][0] x=[[0],[0],[0],[0]] for i in range(n): z=wv[i][0]-w0 k=wv[i][1]+x[z][-1] l=len(x[z]) if l*wv[i][0]<=w: x[z].append(k) ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) l0=len(x[0]) for i in range(l3): for j in range(l2): d=w-i*(w0+3)-j*(w0+2) if d>=0: for k in range(l1): d=w-i*(w0+3)-j*(w0+2)-k*(w0+1) if d>=0: ma=max(ma,x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,l0-1)]) else: break else: break print(ma)
p03732
n,w=list(map(int,input().split())) w_sub,v_sub=list(map(int,input().split())) w0=w_sub inf=1000000001 x=[[inf,v_sub],[inf],[inf],[inf]] for i in range(n-1): w_sub,v_sub=list(map(int,input().split())) w_sub-=w0 x[w_sub].append(v_sub) for i in range(4): x[i].sort(key=lambda x:-x) x[i][0]=0 l_sub=len(x[i]) for j in range(1,l_sub): x[i][j]+=x[i][j-1] ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) l0=len(x[0]) for i in range(l3): for j in range(l2): d=w-i*(w0+3)-j*(w0+2) if d>=0: for k in range(l1): d=w-i*(w0+3)-j*(w0+2)-k*(w0+1) if d>=0: ma=max(ma,x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,l0-1)]) else: break else: break print(ma)
import sys input = sys.stdin.readline n,w=list(map(int,input().split())) w_sub,v_sub=list(map(int,input().split())) w0=w_sub inf=1000000001 x=[[inf,v_sub],[inf],[inf],[inf]] for i in range(n-1): w_sub,v_sub=list(map(int,input().split())) z=w_sub-w0 x[z].append(v_sub) for i in range(4): x[i].sort(key=lambda x:-x) x[i][0]=0 l_sub=len(x[i]) for j in range(1,l_sub): x[i][j]+=x[i][j-1] ma=0 l3=len(x[3]) l2=len(x[2]) l1=len(x[1]) l0=len(x[0]) for i in range(l3): for j in range(l2): d=w-i*(w0+3)-j*(w0+2) if d>=0: for k in range(l1): d=w-i*(w0+3)-j*(w0+2)-k*(w0+1) if d>=0: ma=max(ma,x[3][i]+x[2][j]+x[1][k]+x[0][min(d//w0,l0-1)]) else: break else: break print(ma)
p03732
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): n,q = LI() a = [LI() for _ in range(n)] b = [LI() for _ in range(q)] rr = [] def k(a,b): return sum([(a[i]-b[i]) ** 2 for i in range(3)]) ** 0.5 def f(a,b,c,r): ab = k(a,b) ac = k(a,c) bc = k(b,c) if ac <= r or bc <= r: return True at = (ac ** 2 - r ** 2) bt = (bc ** 2 - r ** 2) t = max(at,0) ** 0.5 + max(bt,0) ** 0.5 return ab >= t - eps for x1,y1,z1,x2,y2,z2 in b: tr = 0 ta = (x1,y1,z1) tb = (x2,y2,z2) for x,y,z,r,l in a: if f(ta,tb,(x,y,z),r): tr += l rr.append(tr) return '\n'.join(map(str,rr)) print(main())
eps = 1.0 / 10**10 def LI(): return [int(x) for x in input().split()] def main(): n,q = LI() na = [LI() for _ in range(n)] qa = [LI() for _ in range(q)] rr = [] def k(a,b): return sum([(a[i]-b[i]) ** 2 for i in range(3)]) ** 0.5 def f(a,b,c,r): ab = k(a,b) ac = k(a,c) bc = k(b,c) if ac <= r or bc <= r: return True at = (ac ** 2 - r ** 2) ** 0.5 bt = (bc ** 2 - r ** 2) ** 0.5 return ab >= at + bt - eps for x1,y1,z1,x2,y2,z2 in qa: tr = 0 for x,y,z,r,l in na: if f((x1,y1,z1),(x2,y2,z2),(x,y,z),r): tr += l rr.append(tr) return '\n'.join(map(str,rr)) print((main()))
p01753
n,m=[int(i) for i in input().split()] A=[] b=[] for i in range(n): A.append([int(j) for j in input().split()]) for i in range(m): b.append(int(eval(input()))) for i in range(n): s=0 for j in range(m): s+=A[i][j]*b[j] print(s)
a,b=list(map(int,input().split())) A=[] B=[] for i in range(a): A.append([int(j) for j in input().split()]) for i in range(b): B.append(int(eval(input()))) for i in range(a): s=0 for j in range(b): s+=A[i][j]*B[j] print(s)
p02410
[n, m] = [int(x) for x in input().split()] A = [[0] * m for x in range(n)] B = [0] * m counter = 0 while counter < n: A[counter] = [int(x) for x in input().split()] counter += 1 counter = 0 while counter < m: B[counter] = int(input()) counter += 1 counter = 0 while counter < n: result = 0 for j in range(m): result += A[counter][j] * B[j] print(result) counter += 1
[n, m] = [int(x) for x in input().split()] A = [] counter = 0 while counter < n: A.append([int(x) for x in input().split()]) counter += 1 B = [int(input()) for j in range(m)] counter = 0 while counter < n: result = 0 for j in range(m): result += A[counter][j] * B[j] print(result) counter += 1
p02410
(n, m) = [int(i) for i in input().split()] A = [] b = [] for i in range(n): A.append([int(j) for j in input().split()]) for i in range(m): b.append(int(eval(input()))) for i in range(n): s = 0 for j in range(m): s += A[i][j] * b[j] print(s)
n, m = [int(i) for i in input().split()] matrix = [] for ni in range(n): matrix.append([int(a) for a in input().split()]) vector = [] for mi in range(m): vector.append(int(eval(input()))) for ni in range(n): sum = 0 for mi in range(m): sum += matrix[ni][mi] * vector[mi] print(sum)
p02410
n,m = list(map(int,input().split())) A = [[0 for q in range(m)] for w in range(n)] B = [0 for e in range(m)] for i in range(n): A[i] = list(map(int, input().split())) for j in range(m): B[j] = int(eval(input())) for i in range(n): c = 0 for j in range(m): c += A[i][j] * B[j] print(c)
listA = [] listB = [] Answer = [] n, m = list(map(int, input().split())) for i in range(n): listA.append(list(map(int, input().split()))) for j in range(m): listB.append(int(eval(input()))) for k in range(n): result = 0 for l in range(m): result += listA[k][l]*listB[l] Answer.append(result) for p in range(n): print((Answer[p]))
p02410
n,m = list(map(int,input().split())) A = [] b = [] for i in range(n): A.append([int(j) for j in input().split()]) for i in range(m): b.append(int(eval(input()))) for i in range(n): sum = 0 for j in range(m): sum += A[i][j]*b[j] print(sum)
n,m=list(map(int,input().split())) A =[[int(i) for i in input().split()] for j in range(n)] b = [] for i in range(m): b.append(int(eval(input()))) ans = [0 for i in range(n)] for i in range(n): for j in range(m): ans[i] += A[i][j]*b[j] for i in ans: print(i)
p02410
n,m = list(map(int, input().split())) # init A = [] b = [] for _ in range(n): A.append(list(map(int, input().split()))) for _ in range(m): b.append(int(eval(input()))) for row in range(n): p = 0 for i, j in zip(A[row], b): p += i * j print(p)
n, m = list(map(int, input().split())) A = [] for i in range(n): A.append(list(map(int, input().split()))) b = [] for i in range(m): b.append(int(eval(input()))) for i in range(n): sum = 0 for j in range(m): sum += A[i][j] * b[j] print(sum)
p02410
n, m = list(map(int, input().split())) a = [[int(i) for i in input().split()] for j in range(n)] b = [int(eval(input())) for i in range(m)] c = [0 for i in range(n)] for i in range(n): for j in range(m): c[i] += a[i][j] * b[j] for i in range(n): print((c[i]))
n, m = list(map(int, input().split())) A = [[int(e) for e in input().split()] for i in range(n)] b = [] for i in range(m): e = int(eval(input())) b.append(e) for i in range(n): p = 0 for j in range(m): p += A[i][j] * b[j] print(p)
p02410
def f():return list(map(int,input().split())) n,m = f() A = [f() for _ in [0]*n] B = [eval(input()) for _ in [0]*m] for i in range(n): print(sum([A[i][j]*B[j] for j in range(m)]))
def f():return list(map(int,input().split())) n,m = f() A = [f() for _ in [0]*n] B = [int(input()) for _ in [0]*m] for i in range(n): print(sum([A[i][j]*B[j] for j in range(m)]))
p02410
# -*- coding: utf-8 -*- """ Created on Tue Jun 20 20:19:33 2017 @author: syaga """ if __name__ == "__main__": n, q = list(map(int, input().split())) a = [] for i in range(n): b = input().split() b[1] = int(b[1]) a.append(b) ans = [] time = 0 flag = 0 while True: if flag == 1: break for i in range(len(a)): if a[i] == []: continue if a[i][1] <= q: time += a[i][1] ans.append([a[i][0], time]) a[i] = [] if len(ans) == len(a): flag = 1 break else: a[i][1] -= q time += q for i in ans: print((" ".join(map(str, i))))
# -*- coding: utf-8 -*- """ Created on Tue Jun 20 20:19:33 2017 @author: syaga """ if __name__ == "__main__": n, q = list(map(int, input().split())) a = [] for i in range(n): b = input().split() b[1] = int(b[1]) a.append(b) ans = [] time = 0 while len(a) != 0: x = a.pop(0) if x[1] <= q: time += x[1] ans.append([x[0], time]) else: x[1] -= q time += q a.append(x) for i in ans: print((" ".join(map(str, i))))
p02264
import sys from collections import deque s=sys.stdin.readlines() q=int(s[0].split()[1]) f=lambda x,y:(x,int(y)) d=deque(f(*e.split())for e in s[1:]) t,a=0,[] while d: k,v=d.popleft() if v>q:v-=q;t+=q;d.append([k,v]) else:t+=v;a+=[f'{k} {t}'] print(*a,sep='\n')
import sys from collections import deque s=sys.stdin.readlines() q=int(s[0].split()[1]) f=lambda x,y:(x,int(y)) d=deque(f(*e.split())for e in s[1:]) t,a=0,[] while d: k,v=d.popleft() if v>q:v-=q;t+=q;d.append([k,v]) else:t+=v;a+=[f'{k} {t}'] print(('\n'.join(a)))
p02264
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 14:42:43 2018 @author: maezawa """ def print_array(g): ans = str(g[0]) if len(g) > 1: for i in range(1,len(g)): ans += ' '+str(g[i]) print(ans) name=[] time=[] current_time = 0 n, q = list(map(int, input().split())) for i in range(n): s = input().split() name.append(s[0]) time.append(int(s[1])) # ============================================================================= # print(n,q) # print(name) # print(time) # ============================================================================= finished = [] fin_time = [] i=0 remain = n while True: if time[i] == 0: i = (i+1)%n continue if time[i] <= q: current_time += time[i] finished.append(name[i]) fin_time.append(current_time) time[i] = 0 remain -= 1 if remain == 0: break else: time[i] -= q current_time += q i = (i+1)%n for i in range(n): print(("{} {}".format(finished[i], fin_time[i])))
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 14:42:43 2018 @author: maezawa """ def print_array(g): ans = str(g[0]) if len(g) > 1: for i in range(1,len(g)): ans += ' '+str(g[i]) print(ans) name=[] time=[] current_time = 0 n, q = list(map(int, input().split())) for i in range(n): s = input().split() name.append(s[0]) time.append(int(s[1])) # ============================================================================= # print(n,q) # print(name) # print(time) # ============================================================================= finished = [] fin_time = [] i=0 remain = n while True: if time[i] <= q: current_time += time.pop(i) finished.append(name.pop(i)) fin_time.append(current_time) remain -= 1 if remain == 0: break i = i%remain else: time[i] -= q current_time += q i = (i+1)%remain for i in range(n): print(("{} {}".format(finished[i], fin_time[i])))
p02264
from collections import deque n, q = map(int, input().split()) f = lambda a, b: (a, int(b)) dq = deque(f(*input().split()) for _ in range(n)) cnt = 0 ans = [] while dq: s, t = dq.popleft() if t <= q: cnt += t ans.append(f"{s} {cnt}") else: cnt += q dq.append((s, t - q)) print(*ans, sep="\n")
import sys from collections import deque readline = sys.stdin.readline n, q = map(int, input().split()) f = lambda a, b: (a, int(b)) dq = deque(f(*readline().split()) for _ in range(n)) cnt = 0 ans = [] while dq: s, t = dq.popleft() if t <= q: cnt += t ans.append(f"{s} {cnt}") else: cnt += q dq.append((s, t - q)) print(*ans, sep="\n")
p02264
n, q = [ int( val ) for val in input( ).split( " " ) ] ps = [0]*n t = [0]*n for i in range( n ): ps[i], t[i] = input( ).split( " " ) output = [] qsum = 0 while t: psi = ps.pop( 0 ) ti = int( t.pop( 0 ) ) if ti <= q: qsum += ti output.append( psi+" "+str( qsum ) ) else: t.append( ti - q ) ps.append( psi ) qsum += q print(( "\n".join( output ) ))
n, q = [ int( val ) for val in input( ).split( " " ) ] ps = [0]*n t = [0]*n for i in range( n ): ps[i], t[i] = input( ).split( " " ) output = [] qsum = 0 while t: psi = ps.pop( 0 ) ti = int( t.pop( 0 ) ) if ti <= q: qsum += ti output.append( "".join( ( psi, " ", str( qsum ) ) ) ) else: t.append( ti - q ) ps.append( psi ) qsum += q print(( "\n".join( output ) ))
p02264
from queue import Queue n, q = [ int( val ) for val in input( ).split( " " ) ] names = Queue( ) times = Queue( ) for i in range( n ): name, time = input( ).split( " " ) names.put( name ) times.put( int( time ) ) qsum = 0 output = [] while not times.empty( ): name = names.get( ) time = times.get( ) if time <= q: qsum += time output.append( "{:s} {:d}".format( name, qsum ) ) else: times.put( time - q ) names.put( name ) qsum += q print(( "\n".join( output ) ))
from queue import Queue n, q = [ int( val ) for val in input( ).split( " " ) ] processes = Queue( ) for i in range( n ): name, time = input( ).split( " " ) processes.put( ( name, int( time ) ) ) qsum = 0 output = [] while not processes.empty( ): process = processes.get( ) if process[1] <= q: qsum += process[1] output.append( "{:s} {:d}".format( process[0], qsum ) ) else: processes.put( ( process[0], process[1]- q ) ) qsum += q print(( "\n".join( output ) ))
p02264
from queue import Queue n, q = [ int( val ) for val in input( ).split( " " ) ] processes = Queue( ) for i in range( n ): name, time = input( ).split( " " ) processes.put( ( name, int( time ) ) ) qsum = 0 output = [] while not processes.empty( ): process = processes.get( ) if process[1] <= q: qsum += process[1] output.append( "{:s} {:d}".format( process[0], qsum ) ) else: processes.put( ( process[0], process[1]- q ) ) qsum += q print(( "\n".join( output ) ))
from collections import deque n, q = [ int( val ) for val in input( ).split( " " ) ] processes = deque( ) for i in range( n ): name, time = input( ).split( " " ) processes.append( ( name, int( time ) ) ) qsum = 0 output = [] while len( processes ): process = processes.popleft( ) if process[1] <= q: qsum += process[1] output.append( "{:s} {:d}".format( process[0], qsum ) ) else: processes.append( ( process[0], process[1]- q ) ) qsum += q print(( "\n".join( output ) ))
p02264
n,q = list(map(int, input().split())) que = [list(map(str, input().split())) for i in range(n)] for i in range(n):que[i][1] = int(que[i][1]) mxt = sum([y for x,y in que]) t = 0 i = 0 while t < mxt: i %= n a = que[i] if 0 < a[1] <= q: t += a[1] que[i][1] = 0 print(a[0],t) elif q < a[1]: t += q que[i][1] = a[1] - q i += 1
n,q = list(map(int, input().split())) que = [list(map(str, input().split())) for i in range(n)] for i in range(n):que[i][1] = int(que[i][1]) mxt = sum([y for x,y in que]) t = 0 i = 0 while t < mxt: i %= n a = que[i] if 0 < a[1] <= q: t += a[1] que.pop(i) n -= 1 print(a[0],t) elif q < a[1]: t += q que[i][1] = a[1] - q i += 1
p02264
# -*- coding: utf-8 -*- dict={} kl=[] n,p=list(map(int,input().split())) for i in range(n): key,value=input().split() kl.append(key) dict.update({key:int(value)}) cnt=0 time=0 count=0 while time!=n: for key in kl: if 0<dict[key]<=p: cnt+=dict[key] dict[key]=0 #del dict[key] #kl.remove(key) time+=1 print(key,cnt) elif dict[key]>p: dict[key]-=p cnt+=p
# -*- coding: utf-8 -*- dict={} kl=[] n,p=list(map(int,input().split())) for i in range(n): key,value=input().split() kl.append(key) dict.update({key:int(value)}) cnt=0 time=0 while time!=n: for key in kl[:]: if 0<dict[key]<=p: cnt+=dict[key] dict[key]=0 del dict[key] kl.remove(key) time+=1 print(key,cnt) elif dict[key]>p: dict[key]-=p cnt+=p
p02264
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_B&lang=jp #?????\??? #??????????????¨????§?????????¨?????¨????????????????????????????????????????????????????????? def rrs(quantum, process): finished_process = [] time_queue = Queue() name_queue = Queue() current_time = 0 for name, time in process: time = int(time) time_queue.enqueue(time) name_queue.enqueue(name) while time_queue.data: time = time_queue.dequeue() name = name_queue.dequeue() if time <= quantum: current_time += time finished_process.append((name, current_time)) else: current_time += quantum time_queue.enqueue(time - quantum) name_queue.enqueue(name) return finished_process class Queue: def __init__(self): self.data = [] def enqueue(self, d): self.data.append(d) def dequeue(self): r = self.data[0] self.data = self.data[1:] return r def main(): info = input().split() n_list = int(info[0]) quantum = int(info[1]) target_list = [tuple(input().split()) for i in range(n_list)] print(("\n".join([p + " " + str(t) for p,t in rrs(quantum, target_list)]))) if __name__ == "__main__": main()
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_B&lang=jp #?????\??? #??????????????¨????§?????????¨?????¨????????????????????????????????????????????????????????? def rrs(quantum, process): finished_process = [] queue = Queue() current_time = 0 for p in process: queue.enqueue(p) while queue.data: p_info = queue.dequeue() time = int(p_info[1]) name = p_info[0] if time <= quantum: current_time += time finished_process.append((name, current_time)) else: current_time += quantum queue.enqueue((name, time - quantum)) return finished_process class Queue: def __init__(self): self.data = [] def enqueue(self, d): self.data.append(d) def dequeue(self): r = self.data[0] self.data = self.data[1:] return r def main(): info = input().split() n_list = int(info[0]) quantum = int(info[1]) target_list = [tuple(input().split()) for i in range(n_list)] print(("\n".join([p + " " + str(t) for p,t in rrs(quantum, target_list)]))) if __name__ == "__main__": main()
p02264
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_B&lang=jp #?????\??? #??????????????¨????§?????????¨?????¨????????????????????????????????????????????????????????? def rrs(quantum, process): finished_process = [] queue = Queue() current_time = 0 for p in process: queue.enqueue(p) while queue.data: p_info = queue.dequeue() time = int(p_info[1]) name = p_info[0] if time <= quantum: current_time += time finished_process.append((name, current_time)) else: current_time += quantum queue.enqueue((name, time - quantum)) return finished_process class Queue: def __init__(self): self.data = [] def enqueue(self, d): self.data.append(d) def dequeue(self): r = self.data[0] self.data = self.data[1:] return r def main(): info = input().split() n_list = int(info[0]) quantum = int(info[1]) target_list = [tuple(input().split()) for i in range(n_list)] print(("\n".join([p + " " + str(t) for p,t in rrs(quantum, target_list)]))) if __name__ == "__main__": main()
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_B&lang=jp #?????\??? #??????????????¨????§?????????¨?????¨????????????????????????????????????????????????????????? def rrs(quantum, process): finished_process = [] queue = Queue() current_time = 0 i = 0 while len(finished_process) < len(process): if i < len(process): p_info = process[i] i += 1 else: p_info = queue.dequeue() time = int(p_info[1]) name = p_info[0] if time <= quantum: current_time += time finished_process.append((name, current_time)) else: current_time += quantum queue.enqueue((name, time - quantum)) return finished_process class Queue: def __init__(self): self.data = [] def enqueue(self, d): self.data.append(d) def dequeue(self): r = self.data[0] self.data = self.data[1:] return r def main(): info = input().split() n_list = int(info[0]) quantum = int(info[1]) target_list = [tuple(input().split()) for i in range(n_list)] print(("\n".join([p + " " + str(t) for p,t in rrs(quantum, target_list)]))) if __name__ == "__main__": main()
p02264
from collections import deque n, q = list(map(int,input().split())) queue = deque([]) for i in range(n): queue.append(list(map(str,input().split()))) queue = deque([[x[0],int(x[1])] for x in queue]) end = deque([]) time = 0 while len(queue) > 0: xqt = queue.popleft() res_time = xqt[1] - q if res_time <= 0: time = time + xqt[1] end.append([xqt[0],time]) else: time = time + q xqt[1] = res_time queue.append(xqt) while len(end) > 0: out = end.popleft() print(out[0], out[1])
from collections import deque n, q = list(map(int,input().split())) queue = deque([]) for i in range(n): queue.append(list(map(str,input().split()))) queue = deque([[x[0],int(x[1])] for x in queue]) time = 0 while len(queue) > 0: xqt = queue.popleft() res_time = xqt[1] - q if res_time <= 0: time = time + xqt[1] print(xqt[0], time) else: time = time + q xqt[1] = res_time queue.append(xqt)
p02264
import sys def isEmpty(S): if len(S) == 0: return True def isFull(S): if len(S) >= 100000: return True def enqueue(x): if isFull(x_list_list): print('Error') x_list_list.append(x) def dequeue(x_list_list): if isEmpty(x_list_list): print('Error') del_list = x_list_list[0] x_list_list.pop(0) return(del_list) y = sys.stdin.readline() a, b = y.split(" ") a = int(a) b = int(b) S = [] x_list_list = [] for i in range(a): text = input() x_list = text.split() x_list[1] = int(x_list[1]) x_list.append(0) x_list_list.append(x_list) flag = a while flag != 0: if int(x_list_list[0][1]) > b: x_list_list[0][1] -= int(b) for j in range(flag): x_list_list[j][2] += b del_list = dequeue(x_list_list) enqueue(del_list) else: for j in range(flag): x_list_list[j][2] += x_list_list[0][1] x_list_list[0][1] = 0 flag -= 1 print(x_list_list[0][0],x_list_list[0][2]) dequeue(x_list_list)
import sys def isEmpty(S): if len(S) == 0: return True def isFull(S): if len(S) >= 100000: return True def enqueue(x): if isFull(x_list_list): print('Error') x_list_list.append(x) def dequeue(x_list_list): if isEmpty(x_list_list): print('Error') del_list = x_list_list[0] x_list_list.pop(0) return(del_list) y = sys.stdin.readline() a, b = y.split(" ") a = int(a) b = int(b) S = [] x_list_list = [] for i in range(a): text = input() x_list = text.split() x_list[1] = int(x_list[1]) x_list.append(0) x_list_list.append(x_list) flag = a while flag != 0: if int(x_list_list[0][1]) > b: x_list_list[0][1] -= int(b) for j in range(flag): x_list_list[j][2] += b del_list = dequeue(x_list_list) enqueue(del_list) elif int(x_list_list[0][1]) <= b: for j in range(flag): x_list_list[j][2] += x_list_list[0][1] x_list_list[0][1] = 0 flag -= 1 print(x_list_list[0][0],x_list_list[0][2]) dequeue(x_list_list)
p02264
class Queue(object): def __init__(self, _max): if type(_max) != int: raise ValueError self._array = [None for i in range(0, _max)] self._head = 0 self._tail = 0 self._cnt = 0 def enqueue(self, value): if self.is_full(): raise IndexError self._array[self._head] = value self._cnt += 1 if self._head + 1 >= len(self._array): self._head = 0 else: self._head += 1 def dequeue(self): if self.is_empty(): raise IndexError value = self._array[self._tail] self._cnt -= 1 if self._tail + 1 >= len(self._array): self._tail = 0 else: self._tail += 1 return value def is_empty(self): return self._cnt <= 0 def is_full(self): return self._cnt >= len(self._array) def round_robin(quantum, jobs): queue = Queue(100000) total = 0 for job in jobs: queue.enqueue(job) while not queue.is_empty(): name, time = queue.dequeue() if time > quantum: total += quantum queue.enqueue((name, time - quantum)) else: total += time print(("{0} {1}".format(name, total))) if __name__ == "__main__": n, quantum = input().split() jobs = [input().split() for i in range(0, int(n))] jobs = [(job[0], int(job[1])) for job in jobs] round_robin(int(quantum), jobs)
class Queue(object): def __init__(self, _max): if type(_max) != int: raise ValueError self._array = [None for i in range(0, _max)] self._head = 0 self._tail = 0 self._cnt = 0 def enqueue(self, value): if self.is_full(): raise IndexError self._array[self._head] = value self._cnt += 1 if self._head + 1 >= len(self._array): self._head = 0 else: self._head += 1 def dequeue(self): if self.is_empty(): raise IndexError value = self._array[self._tail] self._cnt -= 1 if self._tail + 1 >= len(self._array): self._tail = 0 else: self._tail += 1 return value def is_empty(self): return self._cnt <= 0 def is_full(self): return self._cnt >= len(self._array) def round_robin(quantum, jobs): queue = Queue(len(jobs)) total = 0 for job in jobs: queue.enqueue(job) while not queue.is_empty(): name, time = queue.dequeue() if time > quantum: total += quantum queue.enqueue((name, time - quantum)) else: total += time print(("{0} {1}".format(name, total))) if __name__ == "__main__": n, quantum = input().split() jobs = [input().split() for i in range(0, int(n))] jobs = [(job[0], int(job[1])) for job in jobs] round_robin(int(quantum), jobs)
p02264
class Process(object): def __init__(self, name, s): self.name = name self.s = s def exec(self, q): if self.s <= q: time = self.s self.s = 0 return time else: time = q self.s = self.s - q return time def execute(processes, q): time = 0 completed = [] while len(processes) != len(completed): for i, p in enumerate(processes): if not p.s == 0: time += p.exec(q) if p.s == 0: completed.append((p, time)) return completed def run(): n, q = list(map(int, input().split())) processes = [] for _ in range(n): name, time = input().split() processes.append(Process(name, int(time))) completed = execute(processes, q) for c in completed: print(c[0].name, c[1]) if __name__ == '__main__': run()
class Process(object): def __init__(self, name, s): self.name = name self.s = s def exec(self, q): if self.s <= q: time = self.s self.s = 0 return time else: time = q self.s = self.s - q return time def execute(processes, q): time = 0 completed = [] while processes: p = processes.pop() time += p.exec(q) if p.s == 0: completed.append((p, time)) else: processes.insert(0, p) return completed def run(): n, q = list(map(int, input().split())) processes = [] for _ in range(n): name, time = input().split() processes.append(Process(name, int(time))) processes.reverse() completed = execute(processes, q) for c in completed: print(c[0].name, c[1]) if __name__ == '__main__': run()
p02264
def search(N, M, adj): reachable = [[set() for i in range(N)] for _ in range(N)] reachable[0] = adj start = -1 for m in range(1, N): prev = reachable[m-1] cur = reachable[m] for i in range(N): cur[i] = set(prev[i]) for i in range(N): for nxt in adj[i]: if i in prev[nxt]: return (i, reachable, m+1) for p in prev[nxt]: cur[i].add(p) return None def main(): N, M = list(map(int, input().split())) adj = [set() for _ in range(N)] for _ in range(M): A, B = list(map(int, input().split())) adj[A-1].add(B-1) result = search(N, M, adj) if not result: print((-1)) return start, reachable, cnt = result ans = [-1] * cnt x = start for i in range(cnt): ans[i] = x+1 for nxt in adj[x]: if start in reachable[cnt-i-1][nxt]: x = nxt break print((len(ans))) for a in ans: print(a) if __name__ == "__main__": main()
def search(N, M, adj): reachable = [[set() for i in range(N)] for _ in range(N)] reachable[0] = adj start = -1 for m in range(1, N): prev = reachable[m-1] cur = reachable[m] # for i in range(N): # cur[i] = set(prev[i]) for i in range(N): for nxt in adj[i]: for p in prev[nxt]: cur[i].add(p) if i in prev[nxt]: return (i, reachable, m+1) return None def main(): N, M = list(map(int, input().split())) adj = [set() for _ in range(N)] for _ in range(M): A, B = list(map(int, input().split())) adj[A-1].add(B-1) result = search(N, M, adj) if not result: print((-1)) return start, reachable, cnt = result ans = [-1] * cnt x = start for i in range(cnt): ans[i] = x+1 for nxt in adj[x]: if start in reachable[cnt-i-2][nxt]: x = nxt break print((len(ans))) for a in ans: print(a) if __name__ == "__main__": main()
p02902
import sys input = sys.stdin.readline def main(): n,m = list(map(int,input().split())) edge = [[] for _ in [0]*n] for _ in range(m): a,b = list(map(int,input().split())) edge[a-1].append(b-1) new = [tuple([i]) for i in range(n)] res = [] tank = [] res2 = -1 while len(new) > 0: tank = [] for i in range(len(new)): el = new[i] for go in edge[el[-1]]: if not go in el: if el[0] in edge[go]: print((len(el)+1)) for e in el: print((e+1)) print((go+1)) exit() tank.append(el+(go,)) new = tank print((-1)) if __name__ == '__main__': main()
import sys input = sys.stdin.readline def main(): n,m = list(map(int,input().split())) edge = [[] for _ in [0]*n] for _ in range(m): a,b = list(map(int,input().split())) edge[a-1].append(b-1) new = [0]*n for i in range(n): new[i] = [i] res = [] tank = [] res2 = -1 while len(new) > 0: tank = [] for i in range(len(new)): el = new[i] for go in edge[el[-1]]: if not go in el: if el[0] in edge[go]: print((len(el)+1)) for e in el: print((e+1)) print((go+1)) exit() tank.append(el+[go]) new = tank print((-1)) if __name__ == '__main__': main()
p02902
from collections import deque def dfs(N, AB): status = [-1] * N for i in range(N): if status[i] == 1: continue stack = [i] status[i] = 0 while stack: v = stack[-1] if AB[v]: n = AB[v].popleft() if status[n] == -1: stack.append(n) status[n] = 0 else: if n in stack: idx = stack.index(n) cycle = stack[idx:] return cycle else: status[v] = 1 stack.pop() return False def find_smaller_cycle(cycle, AB): i = 0 while i < len(cycle): v = cycle[i] if AB[v]: n = AB[v].popleft() if n in cycle: r = cycle.index(n) if i < r: cycle = cycle[:i+1] + cycle[r:] else: cycle = cycle[r:i+1] i = cycle.index(v) else: i += 1 return cycle N, M = [int(i) for i in input().split()] AB = [deque() for _ in range(N)] for _ in range(M): A, B = [int(i) - 1 for i in input().split()] AB[A].append(B) cycle = dfs(N, AB) if not cycle: print((-1)) else: cycle = find_smaller_cycle(cycle, AB) print((len(cycle))) for v in cycle: print((v + 1))
def dfs(N, AB): status = [-1] * N for i in range(N): if status[i] == 1: continue stack = [i] status[i] = 0 while stack: v = stack[-1] if AB[v]: n = AB[v].pop() if status[n] == -1: stack.append(n) status[n] = 0 elif status[n] == 0: idx = stack.index(n) cycle = stack[idx:] return cycle else: status[v] = 1 stack.pop() return False def find_smaller_cycle(cycle, AB): i = 0 while i < len(cycle): v = cycle[i] if AB[v]: n = AB[v].pop() if n in cycle: r = cycle.index(n) if i < r: cycle = cycle[:i+1] + cycle[r:] else: cycle = cycle[r:i+1] i = cycle.index(v) else: i += 1 return cycle N, M = [int(i) for i in input().split()] AB = [[] for _ in range(N)] for _ in range(M): A, B = [int(i) - 1 for i in input().split()] AB[A].append(B) cycle = dfs(N, AB) if not cycle: print((-1)) else: cycle = find_smaller_cycle(cycle, AB) print((len(cycle))) for v in cycle: print((v + 1))
p02902
from collections import deque n, m = list(map(int, input().split())) edges = [[] for _ in range(n)] for _ in range(m): a, b = list(map(int, input().split())) edges[a - 1].append(b - 1) def bfs(node): seen = [0] * n todo = deque([]) for to in edges[node]: todo.append([to, 1, {to}]) while todo: now, distance, path = todo.popleft() seen[now] = distance if now == node: return distance, path for next_node in edges[now]: # type: int if seen[next_node] != 0: continue new_path = path | {next_node} todo.append([next_node, distance + 1, new_path]) return float('INF'), set() cycle_size = [float('INF')] * n cycle_nodes = [set()] * n for i in range(n): cycle_size[i], cycle_nodes[i] = bfs(i) mini_cycle = min(cycle_size) if mini_cycle == float('INF'): print((-1)) else: idx = cycle_size.index(mini_cycle) ans = cycle_nodes[idx] print(mini_cycle) for node in ans: print((node+1))
n, m = list(map(int, input().split())) edges = [[] for _ in range(n)] for _ in range(m): a, b = list(map(int, input().split())) edges[a-1].append(b-1) def get_first_cycle(n, edges): seen = [-1] * n # seen: -1: 未確認, 0: 非cycleのnode, 1: cycle候補 for start in range(n): if seen[start] == 0: continue seen[start] = 1 path = [start] while path: now = path[-1] if not edges[now]: path.pop() seen[now] = 0 continue next_node = edges[now].pop() if seen[next_node] == -1: path.append(next_node) seen[next_node] = 1 elif seen[next_node] == 1: idx = path.index(next_node) cycle = path[idx:] return cycle return False cycle = get_first_cycle(n, edges) if not cycle: print((-1)) exit() nodes = set(cycle) length = len(cycle) i = 0 while i < length: now = cycle[i] routes = edges[now] while routes: to = routes.pop() if to in nodes: update = True idx = cycle.index(to) cycle = cycle[:i+1] + cycle[idx:] nodes = set(cycle) length = len(cycle) break i += 1 print((len(cycle))) for node in cycle: print((node+1))
p02902
import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") n,m = list(map(int, input().split())) from collections import defaultdict ns = defaultdict(set) for i in range(m): a,b = list(map(int, input().split())) ns[a-1].add(b-1) seen = [False] * n done = [False] * n hist = [] def dfs(u, pos): # uからdfs seen[u] = True hist.append(u) for v in ns[u]: if done[v]: continue elif seen[v]: # サイクルを検出 pos = v return pos else: pos = dfs(v, pos) if pos>=0: return pos done[u] = True hist.pop() return pos for u in range(n): pos = dfs(u, -1) if pos>=0: while True: us = set(hist) update = False for i,u in enumerate(hist): nu = hist[(i+1)%len(hist)] if ns[u]&us-set([nu]): for v in ns[u]&us-set([nu]): break j = hist.index(v) if i<j: hist = hist[i:] + hist[:j+1] else: hist = hist[j:i+1] update = True break if not update or len(us)==len(hist): break print((len(hist))) write("\n".join([str(x+1) for x in hist])) break else: print((-1))
import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") n,m = list(map(int, input().split())) from collections import defaultdict ns = defaultdict(set) for i in range(m): a,b = list(map(int, input().split())) ns[a-1].add(b-1) seen = [False] * n done = [False] * n hist = [] def dfs(u, pos): # uからdfs seen[u] = True hist.append(u) for v in ns[u]: if done[v]: continue elif seen[v]: # サイクルを検出 pos = v return pos else: pos = dfs(v, pos) if pos>=0: return pos done[u] = True hist.pop() return pos def cycle(hist, pos): for i, u in enumerate(hist): if u==pos: break return hist[i:] for u in range(n): pos = dfs(u, -1) if pos>=0: hist = cycle(hist, pos) while True: us = set(hist) update = False for i,u in enumerate(hist): nu = hist[(i+1)%len(hist)] pu = hist[(i-1)] if (ns[u]&us)-set([nu, pu]): for v in (ns[u]&us)-set([nu, pu]): break j = hist.index(v) if i<j: hist = hist[i:] + hist[:j+1] else: hist = hist[j:i+1] update = True break if not update: break print((len(hist))) write("\n".join([str(x+1) for x in hist])) break else: print((-1))
p02902
import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") n,m = list(map(int, input().split())) from collections import defaultdict ns = defaultdict(set) for i in range(m): a,b = list(map(int, input().split())) ns[a-1].add(b-1) seen = [False] * n done = [False] * n hist = [] def dfs(u, pos): # uからdfs seen[u] = True hist.append(u) for v in ns[u]: if done[v]: continue elif seen[v]: # サイクルを検出 pos = v return pos else: pos = dfs(v, pos) if pos>=0: return pos done[u] = True hist.pop() return pos def cycle(hist, pos): for i, u in enumerate(hist): if u==pos: break return hist[i:] for u in range(n): pos = dfs(u, -1) if pos>=0: hist = cycle(hist, pos) while True: us = set(hist) update = False for i,u in enumerate(hist): nu = hist[(i+1)%len(hist)] pu = hist[(i-1)] if (ns[u]&us)-set([nu, pu]): for v in (ns[u]&us)-set([nu, pu]): break j = hist.index(v) if i<j: hist = hist[i:] + hist[:j+1] else: hist = hist[j:i+1] update = True break if not update: break print((len(hist))) write("\n".join([str(x+1) for x in hist])) break else: print((-1))
import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") from collections import defaultdict n,m = list(map(int, input().split())) ns = defaultdict(set) es = set() for _ in range(m): u,v = list(map(int, input().split())) u -= 1 v -= 1 ns[u].add(v) es.add((u,v)) ### サイクル検出 cycle detection seen = [False] * n done = [False] * n hist = [] def dfs(u, pos): # uからdfs seen[u] = True hist.append(u) for v in ns[u]: if done[v]: continue elif seen[v]: # サイクルを検出 pos = v return pos else: pos = dfs(v, pos) if pos>=0: return pos done[u] = True hist.pop() return pos # サイクル復元 def cycle(hist, pos): for i, u in enumerate(hist): if u==pos: break return hist[i:] # 極小サイクルを復元 def sub(hist): s = set(hist) ss = set((hist[i],hist[i+1]) for i in range(len(hist)-1)) ss.add((hist[len(hist)-1], hist[0])) l = None for u,v in es: if u in s and v in s and (u,v) not in ss: l = [] for i,k in enumerate(hist): if k==v: break for j in range(i,len(hist)): l.append(hist[j]) if hist[j]==u: break else: for j in range(len(hist)): l.append(hist[j]) if hist[j]==u: break # print(hist, l, i, u,v,ss) if l is None or len(l)==len(hist): return hist else: return sub(l) ans = None for u in range(n): pos = dfs(u, -1) if pos>=0: hist = cycle(hist, pos) ans = sub(hist) break if ans is None: print((-1)) else: print((len(ans))) write("\n".join([str(x+1) for x in ans]))
p02902
def dfs(N, AB): status = [-1] * N for i in range(N): if status[i] == 1: continue stack = [i] status[i] = 0 while stack: print(("stack:", stack)) v = stack[-1] if AB[v]: n = AB[v].pop() if status[n] == -1: stack.append(n) status[n] = 0 elif status[n] == 0: idx = stack.index(n) print(("stack:", stack, "n:", n, "idx:", idx)) cycle = stack[idx:] return cycle else: status[v] = 1 stack.pop() return False def dfs_2(N, AB): for c in range(N): stack = [(c, [])] while stack: # print("stack:", stack) curr, visited = stack.pop() if curr in visited: # print("cycle found:", curr) return visited else: # print("adding in visited:", curr) for i in AB[curr]: stack.append((i, visited+[curr])) return False def find_smaller_cycle(cycle, AB): i = 0 while i < len(cycle): v = cycle[i] if AB[v]: n = AB[v].pop() if n in cycle: r = cycle.index(n) if i < r: cycle = cycle[:i+1] + cycle[r:] else: cycle = cycle[r:i+1] i = cycle.index(v) else: i += 1 return cycle N, M = [int(i) for i in input().split()] AB = [[] for _ in range(N)] for _ in range(M): A, B = [int(i) - 1 for i in input().split()] AB[A].append(B) # print("AB:") # for i in AB: # print(i) cycle = dfs_2(N, AB) # print("cycle:", cycle) if not cycle: print((-1)) else: cycle = find_smaller_cycle(cycle, AB) print((len(cycle))) for v in cycle: print((v + 1))
def find_cycle(N, AB): for c in range(N): stack = [(c, [])] while stack: # print("stack:", stack) curr, visited = stack.pop() if curr in visited: # print("cycle found:", curr) return visited else: # print("adding in visited:", curr) for i in AB[curr]: stack.append((i, visited+[curr])) return False def find_smaller_cycle(cycle, AB): i = 0 while i < len(cycle): v = cycle[i] if AB[v]: n = AB[v].pop() if n in cycle: r = cycle.index(n) if i < r: cycle = cycle[:i+1] + cycle[r:] else: cycle = cycle[r:i+1] i = cycle.index(v) else: i += 1 return cycle N, M = [int(i) for i in input().split()] AB = [[] for _ in range(N)] for _ in range(M): A, B = [int(i) - 1 for i in input().split()] AB[A].append(B) cycle = find_cycle(N, AB) # print("cycle:", cycle) if not cycle: print((-1)) else: cycle = find_smaller_cycle(cycle, AB) print((len(cycle))) for v in cycle: print((v + 1))
p02902
import sys from collections import deque from collections import defaultdict import copy n, m = list(map(int, sys.stdin.readline().split())) adj = [[] for _ in range(n+1)] for _ in range(m): a, b = list(map(int, sys.stdin.readline().split())) adj[a].append(b) def searchRoute(i): global adj nexts = deque() route = [i] visited = set() result = [] for x in adj[i]: if x < i: continue nroute = copy.copy(route) nvisited = copy.copy(visited) nexts.append((x, nroute, nvisited)) while len(nexts) > 0: error = False found = False x, xroute, xvisited = nexts.popleft() xroute.append(x) xvisited.add(x) for y in adj[x]: if y < i: continue if y == i: found = True break if y in xvisited: break yroute = copy.copy(xroute) yvisited = copy.copy(xvisited) nexts.append((y, yroute, yvisited)) if found: result = xroute break return result heiro = [] for i in range(1, n+1): res = searchRoute(i) if len(res) > 0: heiro = res break if len(heiro) == 0: print((-1)) exit() while True: visited = set() bp = [-1, -1] rt = defaultdict(int) for i in range(len(heiro)): visited.add(heiro[i]) rt[heiro[i]] = i for j in adj[heiro[i]]: if j in visited and not (i == len(heiro) - 1 and j == heiro[0]): bp = [i, rt[j]] break if bp[0] != -1: break if bp[0] == -1: print((len(heiro))) for i in heiro: print(i) exit() heiro = heiro[bp[1]:bp[0]+1]
import sys from collections import deque from collections import defaultdict import copy n, m = list(map(int, sys.stdin.readline().split())) adj = [[] for _ in range(n+1)] radj = [[] for _ in range(n+1)] for _ in range(m): a, b = list(map(int, sys.stdin.readline().split())) adj[a].append(b) radj[b] def searchRoute(i): global adj nexts = deque() route = [i] visited = set() result = [] for x in adj[i]: if x < i: continue nroute = copy.copy(route) nexts.append((x, nroute)) while len(nexts) > 0: error = False found = False x, xroute = nexts.popleft() xroute.append(x) visited.add(x) for y in adj[x]: if y < i: continue if y == i: found = True break if y in visited: break yroute = copy.copy(xroute) nexts.append((y, yroute)) if found: result = xroute break return result heiro = [] for i in range(1, n+1): res = searchRoute(i) if len(res) > 0: heiro = res break if len(heiro) == 0: print((-1)) exit() while True: visited = set() bp = [-1, -1] rt = defaultdict(int) for i in range(len(heiro)): visited.add(heiro[i]) rt[heiro[i]] = i for j in adj[heiro[i]]: if j in visited and not (i == len(heiro) - 1 and j == heiro[0]): bp = [i, rt[j]] break if bp[0] != -1: break if bp[0] == -1: print((len(heiro))) for i in heiro: print(i) exit() heiro = heiro[bp[1]:bp[0]+1]
p02902
def examA(): class Dijkstra(object): """ construct: O(ElogV) """ def __init__(self, edges, start=0): """ :param list of list of list of int edges: :param int start=0: """ self.__dist = [inf] * len(edges) self.__dist[start] = 0 self.__calculate(edges, start) @property def dist(self): return self.__dist def __calculate(self, edges, start): Q = [(0, start)] # (dist,vertex) while (Q): dist, v = heapq.heappop(Q) if self.dist[v] < dist: continue # 候補として挙がったd,vだが、他に短いのがある for u, cost in edges[v]: if self.dist[u] > self.dist[v] + cost: self.__dist[u] = self.dist[v] + cost heapq.heappush(Q, (self.dist[u], u)) N, L = LI() V, D = LI() X = [LI()for _ in range(N)] X.append([0,V,D]) X.append([L,0,0]) X.sort() V = [[]for _ in range(N+2)] for i in range(N+1): x1, v1, d1 = X[i] r = x1 + d1 for j in range(i+1,N+2): x2, v2, d2 = X[j] if r<x2: break cost = (x2-x1)/v1 V[i].append((j,cost)) dij = Dijkstra(V, 0) ans = dij.dist[-1] if ans>=inf: print("impossible") return print(('{:.18f}'.format(ans))) return def examB(): N, K = LI() H = 11; W = 7 S = [[0]*(W+1) for _ in range(H+3)] for h in range(H+2): for w in range(W): S[h+1][w+1] = (S[h][w+1] + S[h+1][w] - S[h][w] + (7*h+w+1)) #print(S) base = 0 for h in range(H): for w in range(W-2): cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w] if cur%11==K: base += 1 #print(h,w) ans = base * ((N-2)//11) #print(ans) rest = (N-2)%11 for h in range(rest): for w in range(W-2): cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w] if cur%11==K: ans += 1 #print(h,w) print(ans) return def examC(): N, K = LI() A = LI() loop = 2**N ans = inf for i in range(loop): cnt = 0 need = 0 highest = 0 for j in range(N): if i&(1<<j)==0: if highest<A[j]: need = inf break continue cnt += 1 if highest>=A[j]: need += (highest+1-A[j]) highest = highest + 1 else: highest = A[j] if cnt>=K and need<ans: ans = need #print(need) print(ans) return def examD(): # 参考 https://qiita.com/maskot1977/items/e1819b7a1053eb9f7d61 def cycle(neighbor, start, ring_size, node): visited = [False]*node stack = [] stack.append([start]) visited[start] = True while (stack): curr_path = stack.pop() check = deepcopy(curr_path) check = set(check) if len(curr_path) > ring_size: continue # print curr_path last = curr_path[-1] for nei in neighbor[last]: if nei in check: if len(curr_path)==0: continue if (len(curr_path) <= ring_size) and (curr_path[0] == nei): new_path = copy(curr_path) return new_path elif (len(curr_path) <= ring_size): return cycle(neighbor,nei,ring_size-1,node) if visited[nei]: continue visited[nei] = True new_path = copy(curr_path) new_path.append(nei) stack.append(new_path) return -1 N, M = LI() V = [[]for _ in range(N)] for _ in range(M): a,b = LI() a -= 1; b -= 1 V[a].append(b) #print(V) loop = -1 for i in range(N): loop = cycle(V,i,N,N) if loop!=-1: break if loop==-1: print((-1)) return while(True): next = -1 for k in loop: next = cycle(V,k,len(loop)-1,N) if next != -1: break if next==-1: break loop = next ans = loop print((len(ans))) for v in ans: print((v+1)) return import sys,bisect,itertools,heapq,math,random from copy import copy,deepcopy from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 _ep = 10**(-12) alphabet = [chr(ord('a') + i) for i in range(26)] sys.setrecursionlimit(10**6) if __name__ == '__main__': examD()
def examA(): class Dijkstra(object): """ construct: O(ElogV) """ def __init__(self, edges, start=0): """ :param list of list of list of int edges: :param int start=0: """ self.__dist = [inf] * len(edges) self.__dist[start] = 0 self.__calculate(edges, start) @property def dist(self): return self.__dist def __calculate(self, edges, start): Q = [(0, start)] # (dist,vertex) while (Q): dist, v = heapq.heappop(Q) if self.dist[v] < dist: continue # 候補として挙がったd,vだが、他に短いのがある for u, cost in edges[v]: if self.dist[u] > self.dist[v] + cost: self.__dist[u] = self.dist[v] + cost heapq.heappush(Q, (self.dist[u], u)) N, L = LI() V, D = LI() X = [LI()for _ in range(N)] X.append([0,V,D]) X.append([L,0,0]) X.sort() V = [[]for _ in range(N+2)] for i in range(N+1): x1, v1, d1 = X[i] r = x1 + d1 for j in range(i+1,N+2): x2, v2, d2 = X[j] if r<x2: break cost = (x2-x1)/v1 V[i].append((j,cost)) dij = Dijkstra(V, 0) ans = dij.dist[-1] if ans>=inf: print("impossible") return print(('{:.18f}'.format(ans))) return def examB(): N, K = LI() H = 11; W = 7 S = [[0]*(W+1) for _ in range(H+3)] for h in range(H+2): for w in range(W): S[h+1][w+1] = (S[h][w+1] + S[h+1][w] - S[h][w] + (7*h+w+1)) #print(S) base = 0 for h in range(H): for w in range(W-2): cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w] if cur%11==K: base += 1 #print(h,w) ans = base * ((N-2)//11) #print(ans) rest = (N-2)%11 for h in range(rest): for w in range(W-2): cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w] if cur%11==K: ans += 1 #print(h,w) print(ans) return def examC(): N, K = LI() A = LI() loop = 2**N ans = inf for i in range(loop): cnt = 0 need = 0 highest = 0 for j in range(N): if i&(1<<j)==0: if highest<A[j]: need = inf break continue cnt += 1 if highest>=A[j]: need += (highest+1-A[j]) highest = highest + 1 else: highest = A[j] if cnt>=K and need<ans: ans = need #print(need) print(ans) return def examD(): # 参考 https://qiita.com/maskot1977/items/e1819b7a1053eb9f7d61 def cycle(neighbor, start, ring_size, node): visited = [False]*node stack = [] stack.append([start]) visited[start] = True while (stack): curr_path = stack.pop() #check = deepcopy(curr_path) #check = set(check) if len(curr_path) > ring_size: continue # print curr_path last = curr_path[-1] for nei in neighbor[last]: if nei in curr_path: if len(curr_path)==0: continue if (len(curr_path) <= ring_size) and (curr_path[0] == nei): new_path = copy(curr_path) return new_path elif (len(curr_path) <= ring_size): return cycle(neighbor,nei,ring_size-1,node) if visited[nei]: continue visited[nei] = True new_path = copy(curr_path) new_path.append(nei) stack.append(new_path) return -1 N, M = LI() V = [[]for _ in range(N)] for _ in range(M): a,b = LI() a -= 1; b -= 1 V[a].append(b) #print(V) loop = -1 for i in range(N): loop = cycle(V,i,N,N) if loop!=-1: break if loop==-1: print((-1)) return while(True): next = -1 for k in loop: next = cycle(V,k,len(loop)-1,N) if next != -1: break if next==-1: break loop = next ans = loop print((len(ans))) for v in ans: print((v+1)) return import sys,bisect,itertools,heapq,math,random from copy import copy,deepcopy from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 _ep = 10**(-12) alphabet = [chr(ord('a') + i) for i in range(26)] sys.setrecursionlimit(10**6) if __name__ == '__main__': examD()
p02902
# coding: utf-8 # Your code here! import sys sys.setrecursionlimit(10**6) readline = sys.stdin.readline from collections import deque def bfs(g,root,memo,backtrack): q = deque() # """初期化、キューに入れて訪問済みにする""" memo[root] = 0 q.append(root) """BFS""" while q: #キューが空になるまで v = q.popleft() #キューから情報を取り出す for c in g[v]: if memo[c] > 0: continue #訪問済みならスキップ # 訪問済みにしてキューに入れる memo[c] = memo[v] + 1 backtrack[c] = v q.append(c) ############################## n,m = [int(i) for i in readline().split()] g = [[] for _ in range(n)] for _ in range(m): a,b = [int(i)-1 for i in readline().split()] g[a].append(b) res = 1000000 v0 = -1 b0 = None for v in range(n): memo = [-1]*n backtrack = [-1]*n bfs(g,v,memo,backtrack) if 1 < memo[v] < res: v0 = v b0 = backtrack res = memo[v] #print(res,v0,b0) if res == 1000000: print(-1) else: i = b0[v0] ans = [i+1] while i != v0: i = b0[i] ans.append(i+1) ans.reverse() print(res) print(*ans,sep="\n")
# find a cycle def find_cycle(g): n = len(g) used = [0]*n #0:not yet 1: visiting 2: visited for v in range(n): #各点でDFS if used[v] == 2: continue #初期化 stack = [v] hist =[] #履歴 while stack: v = stack[-1] if used[v] == 1: used[v] = 2 #帰りがけの状態に stack.pop() hist.pop() continue hist.append(v) used[v] = 1 #行きがけの状態に for c in g[v]: if used[c] == 2: continue elif used[c] == 1: # cを始点とするサイクル発見! return hist[hist.index(c):] else: stack.append(c) return None def find_minimal_cycle(g,cycle): n = len(g) is_in_cycle = [0]*n #サイクルに使われているか nxt = [-1]*n #次の頂点 l = len(cycle) for i,c in enumerate(cycle): is_in_cycle[c] = 1 nxt[c] = cycle[i+1-l] # 極小サイクルを求める for v in cycle: if is_in_cycle[v]: for c in g[v]: if is_in_cycle[c] == 1: #もしショートカット v -> c があれば v0 = nxt[v] #以下サイクルのうち v から c までを削除 while v0 != c: is_in_cycle[v0] = 0 v0 = nxt[v0] nxt[v] = c # nxt を繋ぎ直す #極小サイクルの出力 i = is_in_cycle.index(1) v = nxt[i] hist = [i] #履歴 while v != i: hist.append(v) v = nxt[v] return hist ######################################################### ########################################################## # coding: utf-8 # Your code here! import sys sys.setrecursionlimit(10**6) readline = sys.stdin.readline n,m = [int(i) for i in readline().split()] g = [[] for _ in range(n)] for _ in range(m): a,b = [int(i)-1 for i in readline().split()] g[a].append(b) cycle = find_cycle(g) if cycle == None: print((-1)) else: res = find_minimal_cycle(g,cycle) print((len(res))) for i in res: print((i+1))
p02902
import sys from collections import deque sys.setrecursionlimit(10**9) input = lambda: sys.stdin.readline().rstrip() inpl = lambda: list(map(int,input().split())) N, M = inpl() uv = [ set() for _ in range(N)] vu = [ set() for _ in range(N)] for _ in range(M): A, B = inpl() uv[A-1].add(B-1) vu[B-1].add(A-1) for s in range(N): states_pool = deque() states_pool.append((s,set({}),set(range(N))-set({s}))) while states_pool: u, chain, remain = states_pool.pop() if s in uv[u] and len(chain): print((len(chain)+1)) for c in chain: print((c+1)) print((u+1)) exit() else: new_remain = remain.copy() if u != s: new_remain -= vu[u] candidates = new_remain & uv[u] new_remain -= uv[u] new_chain = chain.copy() new_chain.add(u) for c in candidates: states_pool.append((c, new_chain, new_remain)) for i in range(s+1,N): uv[i].discard(s) print((-1))
import sys input = lambda: sys.stdin.readline().rstrip() inpl = lambda: list(map(int,input().split())) N, M = inpl() uv = [ set() for _ in range(N)] vu = [ set() for _ in range(N)] for _ in range(M): A, B = inpl() uv[A-1].add(B-1) vu[B-1].add(A-1) EMPTY, LOOP, TREE = 0, 1, 2 ENTER, EXIT = 0, 1 status = [EMPTY] * N for s in range(N): states_pool = [(s,[],ENTER)] while states_pool: u, chain, flag = states_pool.pop() if flag == EXIT or status[u] == TREE: status[u] = TREE continue elif status[u] == LOOP: break else: # ENTER, EMPTY status[u] = LOOP states_pool.append((u,chain,EXIT)) new_chain = chain.copy() new_chain.append(u) for c in uv[u]: states_pool.append((c, new_chain, ENTER)) else: continue break else: print((-1)) exit() n = 0 while chain[n] != u: n += 1 chain = chain[n:] L = len(chain) nextnode = [None]*N for i in range(L-1): nextnode[chain[i]] = chain[i+1] nextnode[chain[L-1]] = chain[0] pos = [None]*N for p in range(len(chain)): pos[chain[p]] = p i = 0 while i < L: h = 1 c = chain[(i+1)%L] for j in uv[chain[i % L]]: p = pos[j] if p is None: continue else: if (p-i)%L > h: h = (p-i)%L c = j nextnode[chain[i % L]] = c i += 1 while chain[i % L] != c: pos[chain[i % L]] = None i += 1 loop = [c] k = c while nextnode[k] != c: k = nextnode[k] loop.append(k) print((len(loop))) for l in loop: print((l+1))
p02902
from collections import defaultdict from heapq import heappop, heappush class Graph(object): """ 隣接リストによる有向グラフ """ def __init__(self): self.graph = defaultdict(list) def __len__(self): return len(self.graph) def add_edge(self, src, dst, weight=1): self.graph[src].append((dst, weight)) def get_nodes(self): return list(self.graph.keys()) class Dijkstra(object): """ ダイクストラ法(二分ヒープ)による最短経路探索 計算量: O((E+V)logV) """ def __init__(self, graph, start): self.g = graph.graph # startノードからの最短距離 # startノードは0, それ以外は無限大で初期化 self.dist = defaultdict(lambda: float('inf')) self.dist[start] = 0 # 最短経路での1つ前のノード self.prev = defaultdict(lambda: None) # startノードをキューに入れる self.Q = [] heappush(self.Q, (self.dist[start], start)) while self.Q: # 優先度(距離)が最小であるキューを取り出す dist_u, u = heappop(self.Q) if self.dist[u] < dist_u: continue for v, weight in self.g[u]: alt = dist_u + weight if self.dist[v] > alt: self.dist[v] = alt self.prev[v] = u heappush(self.Q, (alt, v)) def shortest_distance(self, goal): """ startノードからgoalノードまでの最短距離 """ return self.dist[goal] def shortest_path(self, goal): """ startノードからgoalノードまでの最短経路 """ path = [] node = goal while node is not None: path.append(node) node = self.prev[node] return path[::-1] g = Graph() N, M = [int(i) for i in input().split()] for i in range(M): u, v = [int(i) for i in input().split()] g.add_edge(u-1, v-1, 1) g.add_edge(u-1+N, v-1, 1) g.add_edge(u-1, v-1+N, 1) d = Dijkstra(g, 0) ans_n = 10 ** 6 ans_index = -1 for i in range(N): d = Dijkstra(g, i) ans_n_ = d.dist[i+N] if ans_n_ < ans_n: ans_index = i ans_n = ans_n_ if ans_n == 10 ** 6: print((-1)) else: d = Dijkstra(g, ans_index) ans = d.shortest_path(ans_index + N) ans.sort() print(ans_n) for j in range(ans_n): print((ans[j]+1))
from collections import defaultdict from heapq import heappop, heappush class Graph(object): """ 隣接リストによる有向グラフ """ def __init__(self): self.graph = defaultdict(list) def __len__(self): return len(self.graph) def add_edge(self, src, dst, weight=1): self.graph[src].append((dst, weight)) def get_nodes(self): return list(self.graph.keys()) class Dijkstra(object): """ ダイクストラ法(二分ヒープ)による最短経路探索 計算量: O((E+V)logV) """ def __init__(self, graph, start): self.g = graph.graph # startノードからの最短距離 # startノードは0, それ以外は無限大で初期化 self.dist = defaultdict(lambda: float('inf')) self.dist[start] = 0 # 最短経路での1つ前のノード self.prev = defaultdict(lambda: None) # startノードをキューに入れる self.Q = [] heappush(self.Q, (self.dist[start], start)) while self.Q: # 優先度(距離)が最小であるキューを取り出す dist_u, u = heappop(self.Q) if self.dist[u] < dist_u: continue for v, weight in self.g[u]: alt = dist_u + weight if self.dist[v] > alt: self.dist[v] = alt self.prev[v] = u heappush(self.Q, (alt, v)) def shortest_distance(self, goal): """ startノードからgoalノードまでの最短距離 """ return self.dist[goal] def shortest_path(self, goal): """ startノードからgoalノードまでの最短経路 """ path = [] node = goal while node is not None: path.append(node) node = self.prev[node] return path[::-1] g = Graph() N, M = [int(i) for i in input().split()] for i in range(M): u, v = [int(i) for i in input().split()] g.add_edge(u-1, v-1, 1) g.add_edge(u-1, v-1+N, 1) ans_n = 10 ** 6 ans_index = -1 for i in range(N): d = Dijkstra(g, i) ans_n_ = d.dist[i+N] if ans_n_ < ans_n: ans_index = i ans_n = ans_n_ if ans_n == 10 ** 6: print((-1)) else: d = Dijkstra(g, ans_index) ans = d.shortest_path(ans_index + N) ans.sort() print(ans_n) for j in range(ans_n): print((ans[j]+1))
p02902
import collections as c n,k=list(map(int,input().split()));a=c.Counter(list(map(int,input().split()))) print(([0,sum(sorted([i for i in list(a.values())])[:len(a)-k])][len(a)>k]))
import collections as c n,k=list(map(int,input().split()));a=c.Counter(list(map(int,input().split()))) print(([0,sum(sorted([*list(a.values())])[:len(a)-k])][len(a)>k]))
p03495
n, k = (int(i) for i in input().split()) balls = list(int(i) for i in input().split()) ball_set = set(balls) freqs = list(balls.count(i) for i in ball_set) freqs.sort(reverse=True) print((sum(freqs[k:])))
n, k = (int(i) for i in input().split()) balls = (int(i) for i in input().split()) freqs = {} for ball in balls: freqs[ball] = freqs[ball] + 1 if ball in freqs else 1 freq_hist = list(freqs.values()) freq_hist.sort(reverse=True) print((sum(freq_hist[k:])))
p03495
n, k = list(map(int, input().split())) a = list(map(int, input().split())) from collections import Counter c = Counter(a) key = [] value = [] for i, j in sorted(list(c.items()), key=lambda x: x[1]): key.append(i) value.append(j) print((sum(value[:(len(key)-k)])))
n, k = list(map(int, input().split())) a = list(map(int, input().split())) from collections import Counter c = Counter(a) cnts = [] for i, j in list(c.items()): cnts.append(j) print((sum(sorted(cnts)[:-k])))
p03495
n, k = list(map(int, input().split())) a = list(map(int, input().split())) from collections import Counter c = Counter(a) cnts = [] for i, j in list(c.items()): cnts.append(j) print((sum(sorted(cnts)[:-k])))
from collections import Counter n, k = list(map(int, input().split())) a = list(map(int, input().split())) cnts = list(Counter(a).values()) print((sum(sorted(cnts)[:-k])))
p03495
from collections import Counter n, k = list(map(int, input().split())) a = list(map(int, input().split())) cnts = list(Counter(a).values()) print((sum(sorted(cnts)[:-k])))
from collections import Counter n, k = list(map(int, input().split())) a = list(map(int, input().split())) cnts = list(Counter(a).values()) print((sum(sorted(cnts, reverse=True)[k:])))
p03495
#!/usr/bin/env python3 import sys import collections def solve(N: int, K: int, A: "List[int]"): a_counter = collections.Counter(A) if len(a_counter) <= K: print((0)) return values = sorted(list(a_counter.values())) answer = 0 for i in range(len(a_counter)-K): answer += values[i] print(answer) return # Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template) def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int K = int(next(tokens)) # type: int A = [int(next(tokens)) for _ in range(N)] # type: "List[int]" solve(N, K, A) if __name__ == '__main__': main()
#!/usr/bin/env python3 import sys from collections import Counter def solve(N: int, K: int, A: "List[int]"): counter = list(Counter(A).values()) counter.sort() if len(counter) <= K: print((0)) else: need = len(counter)-K print((sum(counter[:need]))) return # Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template) def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int K = int(next(tokens)) # type: int A = [int(next(tokens)) for _ in range(N)] # type: "List[int]" solve(N, K, A) if __name__ == '__main__': main()
p03495
from collections import Counter N,K=list(map(int,input().split())) a = list(map(int,input().split())) d=Counter(a) d=sorted(list(d.items()),key=lambda x:x[1]) ans=0 for i in range(len(d)-K): ans+=d[i][1] print(ans)
from collections import Counter N,K=list(map(int,input().split())) a = list(map(int,input().split())) d=Counter(a) ans=sum(sorted(list(d.values()),reverse=1)[:K]) print((N-ans))
p03495
n,k=list(map(int,input().split())) a=list(map(int,input().split())) a.sort() kind=[] count=1 for i in range(len(a)-1): if(a[i]==a[i+1]):count+=1 else: kind.append(count) count=1 kind.append(count) kind.sort() change=0 while(len(kind)>k): change+=kind.pop(0) print(change)
n,k=list(map(int,input().split())) a=list(map(int,input().split())) a.sort() kind=[] count=1 for i in range(len(a)-1): if(a[i]==a[i+1]):count+=1 else: kind.append(count) count=1 kind.append(count) kind.sort() change=0 for i in range(k): if(len(kind)!=0):change+=kind.pop() print((n-change))
p03495
import collections n,k=list(map(int,input().split())) a=list(map(int,input().split())) ans=0 c=collections.Counter(a) if len(c)<k: print(ans) exit() for i in range(1,-k+len(c)+1): ans+=c.most_common()[-i][1] print(ans)
import collections n,k=list(map(int,input().split())) a=list(map(int,input().split())) ans=0 c=collections.Counter(a) if len(c)<k: print(ans) exit() l=c.most_common() for i in range(1,-k+len(c)+1): ans+=l[-i][1] print(ans)
p03495
nums , types = list(map(int, input().split())) array = list(map(int,input().split())) array.sort() type_count = 0 count = 0 result = 0 ary_count = [] array.append(1000000000) for i in range (nums): if array[i] == array[i +1]: count += 1 elif array[i] < array[i +1]: ary_count.append(count) type_count += 1 count = 0 if type_count > types: for i in range(type_count - types): result += min(ary_count)+1 ary_count.pop(ary_count.index(min(ary_count))) print(result)
nums , types = list(map(int, input().split())) array = list(map(int,input().split())) array.sort() type_count = 0 count = 0 result = 0 ary_count = [] array.append(1000000000) for i in range (nums): if array[i] == array[i +1]: count += 1 elif array[i] < array[i +1]: ary_count.append(count) type_count += 1 count = 0 ary_count.sort() if type_count > types: for i in range(type_count - types): result += ary_count[i]+1 print(result)
p03495
from collections import Counter N,K=list(map(int,input().split())) A=input().split() B=Counter(A) C=sorted(list(B.items()),key=lambda x: -x[1]) print((sum(C[K:][i][1] for i in range(len(C[K:])))))
from collections import Counter N,K=list(map(int,input().split())) A=input().split() B=Counter(A) C=sorted(list(B.values()),reverse=True) print((sum(C[K:])))
p03495
from collections import Counter n,k = list(map(int,input().split())) dic = Counter(list(map(int,input().split()))) x = len(dic) - k lis = sorted(list(dic.items()), key = lambda z:z[1]) ans = 0 for i in range(x): ans += lis[i][1] print(ans)
from collections import Counter from operator import itemgetter n,k = list(map(int,input().split())) dic = Counter(list(map(int,input().split()))) x = len(dic) - k lis = sorted(list(dic.items()), key = itemgetter(1)) ans = 0 for i in range(x): ans += lis[i][1] print(ans)
p03495
N,K=list(map(int,input().split())) s=list(map(int,input().split())) t=list(set(s)) ss,ans=[],0 for i in t: ss.append(s.count(i)) ss=sorted(ss) if len(ss)>K: for i in range(len(ss)-K): ans+=ss[i] print(ans) else: print("0")
N,K=list(map(int,input().split())) d,ans={},0 for i in list(map(int,input().split())): d[i]=d.get(i,0)+1 s=sorted(d.values()) for i in range(len(s)-K): ans+=s[i] print(ans)
p03495
from collections import Counter N, K = list(map(int, input().split())) A = list(map(int, input().split())) c = Counter(A).most_common() c.sort(key=lambda x: -x[1]) ans = 0 while len(c) > K: ans += c.pop()[1] print(ans)
from collections import Counter N, K = list(map(int, input().split())) A = list(map(int, input().split())) print((sum(sorted(Counter(A).values())[:-K])))
p03495
from collections import Counter N, K = list(map(int, input().split())) A = list(map(int, input().split())) cnt = Counter() for num in A: cnt[str(num)] += 1 values = sorted(cnt.values()) ans = 0 for x in range(len(values) - K): ans += values.pop(0) print(ans)
from collections import Counter N, K = list(map(int, input().split())) A = list(map(int, input().split())) cnt = Counter() for num in A: cnt[str(num)] += 1 values = sorted(cnt.values()) ans = sum(values[:max(len(values)-K, 0)]) print(ans)
p03495
from collections import Counter N,K = [int(i) for i in input().split()] A = [int(i) for i in input().split()] counter = Counter(A) ans = 0 counter_list = counter.most_common() if K < len(counter_list): while (K!=len(counter_list)): ans += counter_list[-1][1] counter_list = counter_list[:-1] print(ans)
from collections import Counter N,K = [int(i) for i in input().split()] A = [int(i) for i in input().split()] counter = Counter(A) ans = 0 counter_list = counter.most_common()[::-1] if K < len(counter_list): for a in counter_list[:len(counter_list)-K]: ans += a[1] print(ans)
p03495
N,K = list(map(int, input().split(' '))) A = input().split(' ') num = [] count = [] for a in range(len(A)): tmp = A[a] if not tmp in num: num.append(tmp) count.append(1) else: index = num.index(tmp) count[index] += 1 count = sorted(count) ans = 0 if len(count)<=K: pass else: tmp = len(count)-K count = count[:tmp] ans = sum(count) print(ans)
#辞書型でリトライ N,K = list(map(int, input().split(' '))) A = input().split(' ') dic = {} for a in range(len(A)): tmp = A[a] if not tmp in dic: dic[tmp] = 1 else: dic[tmp] += 1 values = sorted(dic.values()) ans = 0 if len(values)<=K: pass else: tmp = len(values)-K values = values[:tmp] ans = sum(values) print(ans)
p03495
# coding: utf-8 # https://atcoder.jp/contests/abc081/tasks/arc086_a # 14:07-14:14 done def main(): N, K = list(map(int, input().split())) A = list(map(int, input().split())) A = sorted(A) cnt = {} for a in A: if a in cnt: cnt[a] += 1 else: cnt[a] = 1 num_cnts = [[k, v] for k, v in list(cnt.items())] if len(num_cnts) <= K: return 0 num_cnts = sorted(num_cnts, key=lambda x: x[1], reverse=True) ans = sum([cnt for num, cnt in num_cnts[K:]]) return ans print((main()))
# coding: utf-8 # https://atcoder.jp/contests/abc081/tasks/arc086_a # 14:07-14:14 done def main(): N, K = list(map(int, input().split())) A = list(map(int, input().split())) A = sorted(A) cnt = {} for a in A: if a in cnt: cnt[a] += 1 else: cnt[a] = 1 num_cnts = [[k, v] for k, v in list(cnt.items())] # if len(num_cnts) <= K: # return 0 num_cnts = sorted(num_cnts, key=lambda x: x[1], reverse=True) ans = sum([cnt for num, cnt in num_cnts[K:]]) return ans print((main()))
p03495
from collections import Counter _, K = list(map(int, input().split())) A = list(map(int, input().split())) _, cnt = list(zip(*Counter(A).most_common()[::-1])) print((sum(cnt[:len(cnt) - K])))
from collections import Counter _, K = list(map(int, input().split())) A = sorted(list(Counter(input().split()).values())) print((sum(A[:len(A)-K])))
p03495
N, K = list(map(int, input().split())) A = list(map(int, input().split())) from collections import Counter c = Counter(A) cnt = 0 if len(c) > K: for i in range(K, len(c)): cnt += c.most_common()[i][1] print(cnt)
N, K = list(map(int, input().split())) A = list(map(int, input().split())) from collections import Counter ac = Counter(A) cnt = 0 if len(ac) > K: for a in ac.most_common()[K:]: cnt += a[1] print(cnt)
p03495
from collections import Counter n, k = list(map(int,input().split())) a = list(map(int,input().split())) c = Counter(a) l = len(c) cnt = 0 if k < l: i = -1 for _ in range(l-k): cnt += c.most_common()[i][1] i -= 1 print(cnt)
from collections import Counter import heapq n, k = list(map(int,input().split())) a = list(map(int,input().split())) c = Counter(a) heapc = list(c.values()) heapq.heapify(heapc) l = len(c) cnt = 0 if k < l: for _ in range(l-k): cnt += heapq.heappop(heapc) print(cnt)
p03495
N, K = (int(x) for x in input().split()) A = [int(x) for x in input().split()] cnt = [A.count(a) for a in set(A)] cnt.sort() vrt = len(cnt) print((sum(cnt[:vrt-K]) if vrt > K else 0))
import bisect as bs N, K = (int(x) for x in input().split()) A = sorted([int(x) for x in input().split()]) f = lambda X, x: bs.bisect_right(X,x)-bs.bisect_left(X,x) cnt = sorted([f(A,a) for a in set(A)],reverse=True) vrt = len(cnt) print((sum(cnt[K:]) if vrt > K else 0))
p03495
# ABC081C - Not so Diverse (ARC086C) from collections import Counter def main(): N, K, *A = list(map(int, open(0).read().split())) C = list(Counter(A).values()) C.sort(reverse=1) ans = sum(C[K:]) print(ans) if __name__ == "__main__": main()
# ABC081C - Not so Diverse (ARC086C) from collections import Counter def main(): N, K, *A = open(0).read().split() C, K = list(Counter(A).values()), int(K) C.sort(reverse=1) ans = sum(C[K:]) print(ans) if __name__ == "__main__": main()
p03495
from collections import defaultdict N, K = list(map(int, input().split())) A = list(map(int, input().split())) d = defaultdict(int) for i in range(N): d[A[i]] += 1 cnt = len(list(d.keys())) - K d = sorted(list(d.items()), key=lambda x:x[1]) ans = 0 for val in d: if cnt <= 0: print(ans) exit() ans += val[1] cnt -= 1
from collections import defaultdict N, K = list(map(int, input().split())) A = list(map(int, input().split())) d = defaultdict(int) for i in range(N): d[A[i]] += 1 cnt = max(len(list(d.keys())) - K, 0) d = sorted(list(d.items()), key=lambda x:x[1]) ans = 0 for i in range(cnt): ans += d[i][1] print(ans)
p03495
N, K = list(map(int, input().split())) A = list(map(int, input().split())) dict = {} for Ai in A: if Ai in dict: dict[Ai] += 1 else: dict[Ai] = 1 count = 0 while len(dict) > K: max_key = max(dict, key=dict.get) min_key = min(dict, key=dict.get) dict[max_key] += 1 dict[min_key] -= 1 count += 1 if dict[min_key] == 0: del dict[min_key] print(count)
N, K = list(map(int, input().split())) A = list(map(int, input().split())) dict = {} for Ai in A: if Ai in dict: dict[Ai] += 1 else: dict[Ai] = 1 count = 0 if len(dict) > K: count = sum(sorted(dict.values())[:len(dict) - K]) print(count)
p03495
from collections import Counter n, k = list(map(int, input().split())) a = Counter((i for i in input().split())) sort_count = sorted(list(a.items()), key=lambda x: x[1]) total = 0 while len(sort_count) > k: _, n = sort_count.pop(0) total += n print(total)
N, K = list(map(int, input().split())) B = [0]*(N+1) for i in input().split(): B[int(i)] += 1 print((sum(sorted(B)[:-K])))
p03495
from collections import Counter n,k=list(map(int,input().split())) a=input().split() x=len(list(set(a))) n=x-k if x-k>=0 else 0 counter=Counter(a) l=sorted(counter.values()) print((sum(l[:n])))
from collections import Counter n,k=list(map(int,input().split())) a=input().split() x=len(list(set(a))) n=x-k if x-k>=0 else 0 print((sum(sorted(Counter(a).values())[:n])))
p03495
import sys from collections import Counter input = sys.stdin.readline def main(): N, K = [int(x) for x in input().split()] A = [int(x) for x in input().split()] C = Counter(A) ans = 0 if len(C) <= K: print((0)) return else: for i in range(len(C) - K): ans += C.most_common()[-i - 1][1] print(ans) if __name__ == '__main__': main()
import sys from collections import Counter input = sys.stdin.readline def main(): N, K = [int(x) for x in input().split()] A = [int(x) for x in input().split()] C = Counter(A) ans = 0 if len(C) <= K: print((0)) return else: mc = C.most_common() for i in range(len(C) - K): ans += mc[-i - 1][1] print(ans) if __name__ == '__main__': main()
p03495
n,k = list(map(int,input().split())) l = list(map(int, input().split())) def counter(l): count = {} for i in l: count[i] = l.count(i) return sorted(count.values()) freq = counter(l) vf = len(freq) - k if len(freq)> k else 0 print((sum(freq[:vf])))
n,k = list(map(int,input().split())) l = list(map(int, input().split())) freq = [0]*(n+1) for i in l: freq[i]+=1 freq.sort() vf = len(freq) - k if len(freq)> k else 0 print((sum(freq[:vf])))
p03495
from collections import Counter n,k = list(map(int,input().split())) a = list(map(int,input().split())) cnt = Counter(a) mo = cnt.most_common()[::-1] #print(mo) ans = 0 for i in range(max(0,len(mo)-k)): ans += mo[i][1] print(ans)
from collections import Counter n,k = list(map(int,input().split())) a = list(map(int,input().split())) cnt = Counter(a) mo = sorted(cnt.values()) #print(mo) ans = 0 for i in range(max(0,len(mo)-k)): ans += mo[i] print(ans)
p03495
def main(): from collections import Counter n, k, *a = list(map(int, open(0).read().split())) c = Counter(a) v = len(c) l = list(c.values()) m = sorted(l) ans = sum(m[:v - k]) print(ans) if __name__ == '__main__': main()
def main(): from collections import Counter n, k, *a = list(map(int, open(0).read().split())) c = list(Counter(a).values()) v = len(c) - k l = list(c) l.sort() ans = sum(l[:v]) print(ans) if __name__ == '__main__': main()
p03495
from collections import * f=lambda:list(map(int,input().split())) _,k=f() c=Counter(f()) print((sum(sorted(c.values())[~k::-1])))
from collections import*;f=lambda:list(map(int,input().split()));_,k=f();print((sum(sorted(Counter(f()).values())[:-k])))
p03495
import collections from collections import OrderedDict num = [int(x) for x in input().split()] val = input().split() count_dict = collections.Counter(val) cant = 0 if len(count_dict) <= num[1]: print((0)) else: sort_dict = OrderedDict(sorted(list(count_dict.items()), key=lambda x:x[1], reverse= True)) value_dict = list(sort_dict.values()) print((sum(list(value_dict)[num[1]:])))
import collections n, k = list(map(int, input().split())) array = [int(x) for x in input().split()] _dict = collections.Counter(array) res = 0 tmp = len(list(_dict.values())) if len(list(_dict.values())) < k: print((0)) else: sort_dict = collections.OrderedDict(sorted(list(_dict.items()), key=lambda x: x[1], reverse=True)) value_dict = list(sort_dict.values()) print((sum(list(value_dict)[k:])))
p03495
import collections def calc(A, K): dist = {} tmp = collections.Counter(A) type_ = len(tmp) if type_ <= K: return 0 for a, count in list(tmp.items()): if count not in list(dist.keys()): dist[count] = [a] else: dist[count].append(a) rewrite = 0 i = 0 for c in sorted(dist.keys()): for _ in dist[c]: i += 1 rewrite += c if i == type_ - K: return rewrite def main(): N, K = list(map(int, input().split())) A = list(map(int, input().split())) ans = calc(A, K) print(ans) if __name__ == "__main__": main()
N, K = list(map(int, input().split())) cnt = [0 for _ in range(N)] for i in map(int, input().split()): cnt[i-1] += 1 ans = 0 for i in sorted(cnt)[:N - K]: ans += i print(ans)
p03495
N,K=list(map(int,input().split())) A=list(map(int,input().split())) As=list(set(A)) sa=max(0,len(As)-K) if sa==0: print((0)) exit else: count=[0]*len(As) for i in range(len(As)): count[i]=int(A.count(As[i])) num=sorted(count) num2=num[0:sa] ans=0 for i in num2: ans+=i print(ans)
N,K=list(map(int,input().split())) A=list(map(int,input().split())) sa=len(set(A))-K if sa>0: As={} for i in range(N): if A[i] in As: As[A[i]]+=1 else: As[A[i]]=1 Ass=sorted(As.values()) print((sum(Ass[:sa]))) else: print((0))
p03495
a, b = list(map(int, input().split())) n = list(map(int, input().split())) m = list(set(n)) c = 0 if len(m) <= b: print((0)) else: dic = {} for i in range(len(m)): dic[str(m[i])] = n.count(m[i]) dic = sorted(list(dic.items()), key = lambda x:x[1]) for i in range(len(m) - b): c += dic[i][1] print(c)
a, b = list(map(int, input().split())) n = list(map(int, input().split())) l = {} for a in n: l[a] = l.get(a, 0) + 1 print((sum(sorted(l.values())[:-b])))
p03495
from collections import Counter n, k = [int(i) for i in input().split()] a = Counter([int(i) for i in input().split()]) cost = 0 print((sum(c for (v, c) in a.most_common()[k:])))
from collections import Counter n, k = [int(i) for i in input().split()] a = Counter([int(i) for i in input().split()]) print((sum(c for (v, c) in a.most_common()[k:])))
p03495
n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = {} for i in a: if i in b: b[i] += 1 else: b[i] = 1 b = sorted(b.values()) print((sum(b[:-k])))
n, k = list(map(int, input().split())) b = {} for i in input().split(): if i in b: b[i] += 1 else: b[i] = 1 b = sorted(b.values()) print((sum(b[:-k])))
p03495