language_1
stringclasses
10 values
code_1
stringlengths
14
618k
language_2
stringclasses
10 values
code_2
stringlengths
11
783k
label
stringclasses
2 values
prompt
stringlengths
87
784k
C++
#include <stdio.h> #include <iostream> #include <algorithm> #include <sstream> #include <complex> #include <vector> #include <list> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <cstdio> #include <string> #include <cstdlib> #include <cstring> #include <bits/stdc++.h> using namespace std; typedef long long ll; const long double EPS = 1e-9; const ll mod = 1e9 + 7; const ll INF = 1e9; #define rep(i, n) for(ll i = 0; i < n ; i++ ) #define For(i, a, b) for(ll i = (a); i < (b) ; i++ ) #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() const ll MAX_N = 100000; int main(void){ ll N, K; string s; ll answer = 0; cin >> N >> K >> s; ll r = 0; ll l = 0; ll cnt = 0; while(r < N){ while(s[r] == '1' && r < N) r++; while(s[r] == '0' && r < N) r++; while(s[r] == '1' && r < N) r++; cnt ++; if (cnt > K){ while(s[l] == '1' && l < N) l++; while(s[l] == '0' && l < N) l++; } answer = max(answer, r - l); } cout << answer << endl; return 0; }
Python
while True: a,b,c = input().split() a = int(a) c = int(c) if b == '+': print(a + c) elif b == '-': print(a - c) elif b == '*': print(a * c) elif b == '/': print(a // c) if b == '?': break
No
Do these codes solve the same problem? Code 1: #include <stdio.h> #include <iostream> #include <algorithm> #include <sstream> #include <complex> #include <vector> #include <list> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <cstdio> #include <string> #include <cstdlib> #include <cstring> #include <bits/stdc++.h> using namespace std; typedef long long ll; const long double EPS = 1e-9; const ll mod = 1e9 + 7; const ll INF = 1e9; #define rep(i, n) for(ll i = 0; i < n ; i++ ) #define For(i, a, b) for(ll i = (a); i < (b) ; i++ ) #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() const ll MAX_N = 100000; int main(void){ ll N, K; string s; ll answer = 0; cin >> N >> K >> s; ll r = 0; ll l = 0; ll cnt = 0; while(r < N){ while(s[r] == '1' && r < N) r++; while(s[r] == '0' && r < N) r++; while(s[r] == '1' && r < N) r++; cnt ++; if (cnt > K){ while(s[l] == '1' && l < N) l++; while(s[l] == '0' && l < N) l++; } answer = max(answer, r - l); } cout << answer << endl; return 0; } Code 2: while True: a,b,c = input().split() a = int(a) c = int(c) if b == '+': print(a + c) elif b == '-': print(a - c) elif b == '*': print(a * c) elif b == '/': print(a // c) if b == '?': break
C++
#include <string> #include <vector> #include <map> #include <iostream> #include <algorithm> #define MAXN 111111 #define ll long long using namespace std; int V[22]; int main() { int A,B,T; cin>>A>>B>>T; cout << (T/A)*B << endl; }
Python
s_str = input() ans = "" for s in s_str : # print(s) if len(ans) != 0 and s == "B" : ans = ans[:-1] elif s == "0" : ans += "0" elif s == "1" : ans += "1" print(ans)
No
Do these codes solve the same problem? Code 1: #include <string> #include <vector> #include <map> #include <iostream> #include <algorithm> #define MAXN 111111 #define ll long long using namespace std; int V[22]; int main() { int A,B,T; cin>>A>>B>>T; cout << (T/A)*B << endl; } Code 2: s_str = input() ans = "" for s in s_str : # print(s) if len(ans) != 0 and s == "B" : ans = ans[:-1] elif s == "0" : ans += "0" elif s == "1" : ans += "1" print(ans)
Kotlin
import java.util.* class Node { var left = -1 var right = -1 var parent = -1 var depth = -1 var degree = 0 var height = -1 } class BinaryTree(var n: Int) { var nodes = Array(n) { Node() } fun setNode(id: Int, left: Int, right: Int) { nodes[id].left = left nodes[id].right = right if (left != -1) { nodes[left].parent = id; nodes[id].degree += 1 } if (right != -1) { nodes[right].parent = id; nodes[id].degree += 1 } } fun getDepth(id: Int) : Int { if (nodes[id].depth != -1) return nodes[id].depth nodes[id].depth = when (nodes[id].parent) { -1 -> 0 else -> getDepth(nodes[id].parent) + 1 } return nodes[id].depth } fun getSibling(id: Int) : Int { if (nodes[id].parent != -1) { val parent = nodes[nodes[id].parent] return if (parent.left == id) parent.right else parent.left } return -1 } fun getHeight(id: Int) : Int { if (id == -1) return -1 if (nodes[id].height == -1) { nodes[id].height = Math.max(getHeight(nodes[id].left), getHeight(nodes[id].right)) + 1 } return nodes[id].height } fun hoge() { for (i in 0 until n) { val node = nodes[i] println("node ${i}: parent = ${node.parent}, sibling = ${getSibling(i)}, degree = ${node.degree}, depth = ${getDepth(i)}, height = ${getHeight(i)}, ${if (node.parent == -1) "root" else if (node.height == 0) "leaf" else "internal node"}") } } } fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val tree = BinaryTree(n) for (i in 1..n) { val a = Array<Int>(3) { sc.nextInt() } tree.setNode(a[0], a[1], a[2]) } tree.hoge() }
Go
package main import ( "bufio" "bytes" "fmt" "io" "os" "strconv" "strings" ) const NIL = -1 type Node struct { parent, left, right int } type Deps []int type Heights []int type Tree struct { T []Node D Deps H Heights } func answer(reader io.Reader) string { var v, l, r, root int sc := bufio.NewScanner(reader) sc.Split(bufio.ScanWords) sc.Scan() n, _ := strconv.Atoi(sc.Text()) var tree Tree tree.T = make([]Node, n) for i := 0; i < n; i++ { tree.T[i].parent = NIL } for i := 0; i < n; i++ { sc.Scan() v, _ = strconv.Atoi(sc.Text()) sc.Scan() l, _ = strconv.Atoi(sc.Text()) sc.Scan() r, _ = strconv.Atoi(sc.Text()) tree.T[v].left, tree.T[v].right = l, r if l != NIL { tree.T[l].parent = v } if r != NIL { tree.T[r].parent = v } } for i := 0; i < n; i++ { if tree.T[i].parent == NIL { root = i } } tree.D = make(Deps, n) tree.H = make(Heights, n) tree.setDepth(root, 0) tree.setHeight(root) var out bytes.Buffer for i := 0; i < n; i++ { out.WriteString(tree.String(i)) } return strings.TrimRight(out.String(), "\n") } func (t *Tree) setDepth(u, d int) { if u == NIL { return } t.D[u] = d t.setDepth(t.T[u].left, d+1) t.setDepth(t.T[u].right, d+1) } func (t *Tree) setHeight(u int) int { var h1, h2 int if t.T[u].left != NIL { h1 = t.setHeight(t.T[u].left) + 1 } if t.T[u].right != NIL { h2 = t.setHeight(t.T[u].right) + 1 } t.H[u] = h2 if h1 > h2 { t.H[u] = h1 } return t.H[u] } func (t *Tree) getSibling(u int) int { if t.T[u].parent == NIL { return NIL } if t.T[t.T[u].parent].left != u && t.T[t.T[u].parent].left != NIL { return t.T[t.T[u].parent].left } if t.T[t.T[u].parent].right != u && t.T[t.T[u].parent].right != NIL { return t.T[t.T[u].parent].right } return NIL } func (t *Tree) String(u int) string { var out bytes.Buffer out.WriteString(fmt.Sprintf("node %d: ", u)) out.WriteString(fmt.Sprintf("parent = %d, ", t.T[u].parent)) out.WriteString(fmt.Sprintf("sibling = %d, ", t.getSibling(u))) var deg int if t.T[u].left != NIL { deg++ } if t.T[u].right != NIL { deg++ } out.WriteString(fmt.Sprintf("degree = %d, ", deg)) out.WriteString(fmt.Sprintf("depth = %d, ", t.D[u])) out.WriteString(fmt.Sprintf("height = %d, ", t.H[u])) if t.T[u].parent == NIL { out.WriteString("root\n") } else if t.T[u].left == NIL && t.T[u].right == NIL { out.WriteString("leaf\n") } else { out.WriteString("internal node\n") } return out.String() } func main() { fmt.Println(answer(os.Stdin)) }
Yes
Do these codes solve the same problem? Code 1: import java.util.* class Node { var left = -1 var right = -1 var parent = -1 var depth = -1 var degree = 0 var height = -1 } class BinaryTree(var n: Int) { var nodes = Array(n) { Node() } fun setNode(id: Int, left: Int, right: Int) { nodes[id].left = left nodes[id].right = right if (left != -1) { nodes[left].parent = id; nodes[id].degree += 1 } if (right != -1) { nodes[right].parent = id; nodes[id].degree += 1 } } fun getDepth(id: Int) : Int { if (nodes[id].depth != -1) return nodes[id].depth nodes[id].depth = when (nodes[id].parent) { -1 -> 0 else -> getDepth(nodes[id].parent) + 1 } return nodes[id].depth } fun getSibling(id: Int) : Int { if (nodes[id].parent != -1) { val parent = nodes[nodes[id].parent] return if (parent.left == id) parent.right else parent.left } return -1 } fun getHeight(id: Int) : Int { if (id == -1) return -1 if (nodes[id].height == -1) { nodes[id].height = Math.max(getHeight(nodes[id].left), getHeight(nodes[id].right)) + 1 } return nodes[id].height } fun hoge() { for (i in 0 until n) { val node = nodes[i] println("node ${i}: parent = ${node.parent}, sibling = ${getSibling(i)}, degree = ${node.degree}, depth = ${getDepth(i)}, height = ${getHeight(i)}, ${if (node.parent == -1) "root" else if (node.height == 0) "leaf" else "internal node"}") } } } fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val tree = BinaryTree(n) for (i in 1..n) { val a = Array<Int>(3) { sc.nextInt() } tree.setNode(a[0], a[1], a[2]) } tree.hoge() } Code 2: package main import ( "bufio" "bytes" "fmt" "io" "os" "strconv" "strings" ) const NIL = -1 type Node struct { parent, left, right int } type Deps []int type Heights []int type Tree struct { T []Node D Deps H Heights } func answer(reader io.Reader) string { var v, l, r, root int sc := bufio.NewScanner(reader) sc.Split(bufio.ScanWords) sc.Scan() n, _ := strconv.Atoi(sc.Text()) var tree Tree tree.T = make([]Node, n) for i := 0; i < n; i++ { tree.T[i].parent = NIL } for i := 0; i < n; i++ { sc.Scan() v, _ = strconv.Atoi(sc.Text()) sc.Scan() l, _ = strconv.Atoi(sc.Text()) sc.Scan() r, _ = strconv.Atoi(sc.Text()) tree.T[v].left, tree.T[v].right = l, r if l != NIL { tree.T[l].parent = v } if r != NIL { tree.T[r].parent = v } } for i := 0; i < n; i++ { if tree.T[i].parent == NIL { root = i } } tree.D = make(Deps, n) tree.H = make(Heights, n) tree.setDepth(root, 0) tree.setHeight(root) var out bytes.Buffer for i := 0; i < n; i++ { out.WriteString(tree.String(i)) } return strings.TrimRight(out.String(), "\n") } func (t *Tree) setDepth(u, d int) { if u == NIL { return } t.D[u] = d t.setDepth(t.T[u].left, d+1) t.setDepth(t.T[u].right, d+1) } func (t *Tree) setHeight(u int) int { var h1, h2 int if t.T[u].left != NIL { h1 = t.setHeight(t.T[u].left) + 1 } if t.T[u].right != NIL { h2 = t.setHeight(t.T[u].right) + 1 } t.H[u] = h2 if h1 > h2 { t.H[u] = h1 } return t.H[u] } func (t *Tree) getSibling(u int) int { if t.T[u].parent == NIL { return NIL } if t.T[t.T[u].parent].left != u && t.T[t.T[u].parent].left != NIL { return t.T[t.T[u].parent].left } if t.T[t.T[u].parent].right != u && t.T[t.T[u].parent].right != NIL { return t.T[t.T[u].parent].right } return NIL } func (t *Tree) String(u int) string { var out bytes.Buffer out.WriteString(fmt.Sprintf("node %d: ", u)) out.WriteString(fmt.Sprintf("parent = %d, ", t.T[u].parent)) out.WriteString(fmt.Sprintf("sibling = %d, ", t.getSibling(u))) var deg int if t.T[u].left != NIL { deg++ } if t.T[u].right != NIL { deg++ } out.WriteString(fmt.Sprintf("degree = %d, ", deg)) out.WriteString(fmt.Sprintf("depth = %d, ", t.D[u])) out.WriteString(fmt.Sprintf("height = %d, ", t.H[u])) if t.T[u].parent == NIL { out.WriteString("root\n") } else if t.T[u].left == NIL && t.T[u].right == NIL { out.WriteString("leaf\n") } else { out.WriteString("internal node\n") } return out.String() } func main() { fmt.Println(answer(os.Stdin)) }
C
#include<stdio.h> int main(){ int x; scanf("%d",&x); printf("%d\n",x*x*x); return 0; }
C++
#include<bits/stdc++.h> #define ALL(c) (c).begin(),(c).end() #define EACH(i,c) for(auto i=(c).begin();i!=(c).end();++i) using namespace std; int main(){ int N; cin >> N; vector<pair<int,int>> a(N), c(N); for(int i = 0; i < N; ++i) { cin >> a[i].first >> a[i].second; } for(int i = 0; i < N; ++i){ cin >> c[i].first >> c[i].second; } sort(ALL(a)); sort(ALL(c)); c.push_back(make_pair(3 * N, 3 * N)); vector<int> used(N); int res = 0; for(int i = N -1; i >=0; --i){ int p = N; for(int j = 0; j < N; ++j) { if(used[j]) continue; if(a[i].first >= c[j].first || a[i].second >= c[j].second) continue; if(c[j].second < c[p].second) { p = j; } } if(p < N) { ++res; used[p] = true; } } cout << res << endl; return 0; }
No
Do these codes solve the same problem? Code 1: #include<stdio.h> int main(){ int x; scanf("%d",&x); printf("%d\n",x*x*x); return 0; } Code 2: #include<bits/stdc++.h> #define ALL(c) (c).begin(),(c).end() #define EACH(i,c) for(auto i=(c).begin();i!=(c).end();++i) using namespace std; int main(){ int N; cin >> N; vector<pair<int,int>> a(N), c(N); for(int i = 0; i < N; ++i) { cin >> a[i].first >> a[i].second; } for(int i = 0; i < N; ++i){ cin >> c[i].first >> c[i].second; } sort(ALL(a)); sort(ALL(c)); c.push_back(make_pair(3 * N, 3 * N)); vector<int> used(N); int res = 0; for(int i = N -1; i >=0; --i){ int p = N; for(int j = 0; j < N; ++j) { if(used[j]) continue; if(a[i].first >= c[j].first || a[i].second >= c[j].second) continue; if(c[j].second < c[p].second) { p = j; } } if(p < N) { ++res; used[p] = true; } } cout << res << endl; return 0; }
Python
import math N = int(input()) As = list(map(int, input().split())) anss = [0] * (N + 1) for a in As: anss[a] += 1 for ans in anss[1:]: print(ans)
C++
#include<bits/stdc++.h> using namespace std; int main(){ int n , x; cin >> n; int cnt = 0; for(int i = 1; i <= n; i++){ cin >> x; if(x!=i)cnt++; } if(cnt > 2){ cout << "NO\n"; } else{ cout << "YES\n"; } }
No
Do these codes solve the same problem? Code 1: import math N = int(input()) As = list(map(int, input().split())) anss = [0] * (N + 1) for a in As: anss[a] += 1 for ans in anss[1:]: print(ans) Code 2: #include<bits/stdc++.h> using namespace std; int main(){ int n , x; cin >> n; int cnt = 0; for(int i = 1; i <= n; i++){ cin >> x; if(x!=i)cnt++; } if(cnt > 2){ cout << "NO\n"; } else{ cout << "YES\n"; } }
Python
from bisect import bisect_right as br def quad_primes(n): is_prime = [True] * (n + 1) is_prime[0] = is_prime[1] = False for i in range(2, int(n ** (1 / 2)) + 1): if is_prime[i]: for j in range(i * i, n + 1, i): is_prime[j] = False return [i + 8 for i in range(n - 7) if is_prime[i] and is_prime[i + 2] and is_prime[i + 6] and is_prime[i + 8]] quad = quad_primes(10000000) while True: n = int(input()) if n == 0: break print(quad[br(quad, n) - 1])
Kotlin
import java.lang.Math.sqrt fun main(args:Array<String>?): Unit { val prime = primes(10_000_000) val yotsugo = (3 until prime.size).filter{i -> prime[i] - 8 == prime[i - 3] && prime[i - 2] - 2 == prime[i - 1] - 6 && prime[i - 3] == prime[i - 1] - 6}.map{prime[it]}.toIntArray() while(true){ val n = readLine()!!.trim().toInt() if (n == 0) return println(yotsugo[upperBound(yotsugo, n) - 1]) } } fun upperBound(array: IntArray, target: Int): Int { var left = 0 var right = array.size while(left < right){ val mid = (left + right) / 2 if (array[mid] <= target){ left = mid + 1 }else { right = mid } } return right } fun primes(upper: Int): IntArray { val isPrime = BooleanArray(upper + 1){true} for (p in 2 .. sqrt(upper.toDouble()).toInt()) if (isPrime[p]) { for (i in p * p .. upper step p) { isPrime[i] = false } } return (2 .. upper).filter(isPrime::get).toIntArray() }
Yes
Do these codes solve the same problem? Code 1: from bisect import bisect_right as br def quad_primes(n): is_prime = [True] * (n + 1) is_prime[0] = is_prime[1] = False for i in range(2, int(n ** (1 / 2)) + 1): if is_prime[i]: for j in range(i * i, n + 1, i): is_prime[j] = False return [i + 8 for i in range(n - 7) if is_prime[i] and is_prime[i + 2] and is_prime[i + 6] and is_prime[i + 8]] quad = quad_primes(10000000) while True: n = int(input()) if n == 0: break print(quad[br(quad, n) - 1]) Code 2: import java.lang.Math.sqrt fun main(args:Array<String>?): Unit { val prime = primes(10_000_000) val yotsugo = (3 until prime.size).filter{i -> prime[i] - 8 == prime[i - 3] && prime[i - 2] - 2 == prime[i - 1] - 6 && prime[i - 3] == prime[i - 1] - 6}.map{prime[it]}.toIntArray() while(true){ val n = readLine()!!.trim().toInt() if (n == 0) return println(yotsugo[upperBound(yotsugo, n) - 1]) } } fun upperBound(array: IntArray, target: Int): Int { var left = 0 var right = array.size while(left < right){ val mid = (left + right) / 2 if (array[mid] <= target){ left = mid + 1 }else { right = mid } } return right } fun primes(upper: Int): IntArray { val isPrime = BooleanArray(upper + 1){true} for (p in 2 .. sqrt(upper.toDouble()).toInt()) if (isPrime[p]) { for (i in p * p .. upper step p) { isPrime[i] = false } } return (2 .. upper).filter(isPrime::get).toIntArray() }
JavaScript
"use strict"; var input=require("fs").readFileSync("/dev/stdin","utf8"); var cin=input.split(/ |\n/),cid=0; function next(a){return a?cin[cid++]:+cin[cid++];} function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);} function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;} function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);} var myOut = main(); if(myOut !== undefined)console.log(myOut); function main(){ var n = next(); var a = nexts(n); var set = new Set(); for(var i = 0; i < n; i++){ if(set.has(a[i]))return "NO"; set.add(a[i]); } return "YES"; }
Go
package main import ( "bufio" "bytes" "fmt" "io" "os" "strconv" ) // ----------------------------------------------------------------------------- // IO helper functions // Returns next token from input. It must be initialized by SetInput() // before the first call. var nextToken func() ([]byte, error) var nextLine func() ([]byte, error) // Holds a buffer for output. It must be initialized by SetOutput(). // All IO fucntions (read*() and [e]print*()) should write to OutputWriter // instead of this. var OutputBuffer *bufio.Writer // Holds an io.Writer. It must be initialized by SetOutput() var OutputWriter io.Writer // Set IO functions for interactive input/output. func SetInteractive(w io.Writer, r io.Reader) { SetUnbefferedInput(r) OutputBuffer = nil OutputWriter = w } // Setup OutputBuffer and OutputWriter. func SetOutput(w io.Writer) { OutputBuffer = bufio.NewWriter(w) OutputWriter = OutputBuffer } // Flushes OutputBuffer func Flush() { if OutputBuffer != nil { OutputBuffer.Flush() } } // Returns true if c is a white space func IsSpace(c byte) bool { switch c { case '\t', '\n', '\v', '\f', '\r', ' ': return true } return false } func IsNewLine(c byte) bool { switch c { case '\n', '\r': return true } return false } // Setup nextToken with input buffer. func SetInput(r io.Reader) { buf := new(bytes.Buffer) var b []byte var i int rest := func() ([]byte, error) { for i < len(b) && IsSpace(b[i]) { i++ } if i == len(b) { return nil, io.ErrUnexpectedEOF } j := i for i < len(b) && !IsSpace(b[i]) { i++ } return b[j:i], nil } initial := func() ([]byte, error) { io.Copy(buf, r) b = buf.Bytes() nextToken = rest return rest() } nextToken = initial restLn := func() ([]byte, error) { for i < len(b) && IsNewLine(b[i]) { i++ } if i == len(b) { return nil, io.ErrUnexpectedEOF } j := i for i < len(b) && !IsNewLine(b[i]) { i++ } return b[j:i], nil } initialLn := func() ([]byte, error) { io.Copy(buf, r) b = buf.Bytes() nextLine = restLn return restLn() } nextLine = initialLn } // Setup nextToken without input buffer. func SetUnbefferedInput(r io.Reader) { buf := bufio.NewReader(r) var b []byte var i int nextToken = func() ([]byte, error) { var err error if i == len(b) { b, err = buf.ReadBytes('\n') if err != nil { return nil, err } i = 0 j := len(b) - 1 for 0 <= j && IsSpace(b[j]) { j-- } b = b[0 : j+1] } for i < len(b) && IsSpace(b[i]) { i++ } j := i for i < len(b) && !IsSpace(b[i]) { i++ } if i == j { return nil, io.ErrUnexpectedEOF } return b[j:i], nil } } // ----------------------------------------------------------------------------- // IO functions // Reads next token and return it as []byte func readb() []byte { b, err := nextToken() if err != nil { panic(err) } return b[:len(b):len(b)] } // Reads next token and return it as string func reads() string { return string(readb()) } // Read next line as []byte. Trailing '\n' will not be included. // See also comments on readb() func readbln() []byte { b, err := nextLine() if err != nil { panic(err) } return b[:len(b):len(b)] } // Read next line as string func readsln() string { return string(readbln()) } // Reads next token and return it as int64 func readll() int64 { i, err := strconv.ParseInt(reads(), 10, 64) if err != nil { panic(err.Error()) } return i } // Reads next token and return it as int func readi() int { return int(readll()) } // Reads next token and return it as float64 func readf() float64 { f, err := strconv.ParseFloat(reads(), 64) if err != nil { panic(err.Error()) } return f } // Write args to OutputWriter with the format f func printf(f string, args ...interface{}) (int, error) { return fmt.Fprintf(OutputWriter, f, args...) } // Write args to OutputWriter without format func println(args ...interface{}) (int, error) { return fmt.Fprintln(OutputWriter, args...) } // Write args to stderr with the format f func eprintf(f string, args ...interface{}) (int, error) { return fmt.Fprintf(os.Stderr, f, args...) } // Write args to stderr without format func eprintln(args ...interface{}) (int, error) { return fmt.Fprintln(os.Stderr, args...) } // ----------------------------------------------------------------------------- // Utilities func sumSlice(a []int) int { var res int for _, v := range a { res += v } return res } func sumSlicell(a []int64) int64 { var res int64 for _, v := range a { res += v } return res } func readInts(N int) (int, []int) { if N == 0 { N = readi() } a := make([]int, N) for i := range a { a[i] = readi() } return N, a } func readIntsll(N int) (int, []int64) { if N == 0 { N = readi() } a := make([]int64, N) for i := range a { a[i] = readll() } return N, a } // reverse slice in place func reverse(a []int) { for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] } } // areverse: allocating reverse func areverse(a []int) []int { b := make([]int, len(a)) for i := range a { b[i] = a[len(a)-i-1] } return b } // ----------------------------------------------------------------------------- // Simple math functions const ( // big prime INF = 1000000007 INF2 = 1000000009 INF3 = 998244353 ) func min(a, b int) int { if a < b { return a } return b } func minll(a, b int64) int64 { if a < b { return a } return b } func max(a, b int) int { if a < b { return b } return a } func maxll(a, b int64) int64 { if a < b { return b } return a } func abs(a int) int { if a < 0 { return -a } return a } func absll(a int64) int64 { if a < 0 { return -a } return a } // egcd(a, b) returns d, x, y: // d is gcd(a,b) // x, y are integers that satisfy ax + by = d func egcd(a, b int) (int, int, int) { if b == 0 { return a, 1, 0 } d, x, y := egcd(b, a%b) return d, y, x - a/b*y } func egcdll(a, b int64) (int64, int64, int64) { if b == 0 { return a, 1, 0 } d, x, y := egcdll(b, a%b) return d, y, x - a/b*y } func gcd(a, b int) int { d, _, _ := egcd(a, b) return d } func gcdll(a, b int64) int64 { d, _, _ := egcdll(a, b) return d } // set up IO functions func init() { // for non-interactive SetInput(os.Stdin) SetOutput(os.Stdout) // Enable below when interactive. Its ok to leave above intact. // SetInteractive(os.Stdout, os.Stdin) } func main() { defer Flush() N, A := readInts(0) _ = N m := make(map[int]bool) for _, v := range A { if m[v] { println("NO") return } m[v] = true } println("YES") }
Yes
Do these codes solve the same problem? Code 1: "use strict"; var input=require("fs").readFileSync("/dev/stdin","utf8"); var cin=input.split(/ |\n/),cid=0; function next(a){return a?cin[cid++]:+cin[cid++];} function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);} function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;} function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);} var myOut = main(); if(myOut !== undefined)console.log(myOut); function main(){ var n = next(); var a = nexts(n); var set = new Set(); for(var i = 0; i < n; i++){ if(set.has(a[i]))return "NO"; set.add(a[i]); } return "YES"; } Code 2: package main import ( "bufio" "bytes" "fmt" "io" "os" "strconv" ) // ----------------------------------------------------------------------------- // IO helper functions // Returns next token from input. It must be initialized by SetInput() // before the first call. var nextToken func() ([]byte, error) var nextLine func() ([]byte, error) // Holds a buffer for output. It must be initialized by SetOutput(). // All IO fucntions (read*() and [e]print*()) should write to OutputWriter // instead of this. var OutputBuffer *bufio.Writer // Holds an io.Writer. It must be initialized by SetOutput() var OutputWriter io.Writer // Set IO functions for interactive input/output. func SetInteractive(w io.Writer, r io.Reader) { SetUnbefferedInput(r) OutputBuffer = nil OutputWriter = w } // Setup OutputBuffer and OutputWriter. func SetOutput(w io.Writer) { OutputBuffer = bufio.NewWriter(w) OutputWriter = OutputBuffer } // Flushes OutputBuffer func Flush() { if OutputBuffer != nil { OutputBuffer.Flush() } } // Returns true if c is a white space func IsSpace(c byte) bool { switch c { case '\t', '\n', '\v', '\f', '\r', ' ': return true } return false } func IsNewLine(c byte) bool { switch c { case '\n', '\r': return true } return false } // Setup nextToken with input buffer. func SetInput(r io.Reader) { buf := new(bytes.Buffer) var b []byte var i int rest := func() ([]byte, error) { for i < len(b) && IsSpace(b[i]) { i++ } if i == len(b) { return nil, io.ErrUnexpectedEOF } j := i for i < len(b) && !IsSpace(b[i]) { i++ } return b[j:i], nil } initial := func() ([]byte, error) { io.Copy(buf, r) b = buf.Bytes() nextToken = rest return rest() } nextToken = initial restLn := func() ([]byte, error) { for i < len(b) && IsNewLine(b[i]) { i++ } if i == len(b) { return nil, io.ErrUnexpectedEOF } j := i for i < len(b) && !IsNewLine(b[i]) { i++ } return b[j:i], nil } initialLn := func() ([]byte, error) { io.Copy(buf, r) b = buf.Bytes() nextLine = restLn return restLn() } nextLine = initialLn } // Setup nextToken without input buffer. func SetUnbefferedInput(r io.Reader) { buf := bufio.NewReader(r) var b []byte var i int nextToken = func() ([]byte, error) { var err error if i == len(b) { b, err = buf.ReadBytes('\n') if err != nil { return nil, err } i = 0 j := len(b) - 1 for 0 <= j && IsSpace(b[j]) { j-- } b = b[0 : j+1] } for i < len(b) && IsSpace(b[i]) { i++ } j := i for i < len(b) && !IsSpace(b[i]) { i++ } if i == j { return nil, io.ErrUnexpectedEOF } return b[j:i], nil } } // ----------------------------------------------------------------------------- // IO functions // Reads next token and return it as []byte func readb() []byte { b, err := nextToken() if err != nil { panic(err) } return b[:len(b):len(b)] } // Reads next token and return it as string func reads() string { return string(readb()) } // Read next line as []byte. Trailing '\n' will not be included. // See also comments on readb() func readbln() []byte { b, err := nextLine() if err != nil { panic(err) } return b[:len(b):len(b)] } // Read next line as string func readsln() string { return string(readbln()) } // Reads next token and return it as int64 func readll() int64 { i, err := strconv.ParseInt(reads(), 10, 64) if err != nil { panic(err.Error()) } return i } // Reads next token and return it as int func readi() int { return int(readll()) } // Reads next token and return it as float64 func readf() float64 { f, err := strconv.ParseFloat(reads(), 64) if err != nil { panic(err.Error()) } return f } // Write args to OutputWriter with the format f func printf(f string, args ...interface{}) (int, error) { return fmt.Fprintf(OutputWriter, f, args...) } // Write args to OutputWriter without format func println(args ...interface{}) (int, error) { return fmt.Fprintln(OutputWriter, args...) } // Write args to stderr with the format f func eprintf(f string, args ...interface{}) (int, error) { return fmt.Fprintf(os.Stderr, f, args...) } // Write args to stderr without format func eprintln(args ...interface{}) (int, error) { return fmt.Fprintln(os.Stderr, args...) } // ----------------------------------------------------------------------------- // Utilities func sumSlice(a []int) int { var res int for _, v := range a { res += v } return res } func sumSlicell(a []int64) int64 { var res int64 for _, v := range a { res += v } return res } func readInts(N int) (int, []int) { if N == 0 { N = readi() } a := make([]int, N) for i := range a { a[i] = readi() } return N, a } func readIntsll(N int) (int, []int64) { if N == 0 { N = readi() } a := make([]int64, N) for i := range a { a[i] = readll() } return N, a } // reverse slice in place func reverse(a []int) { for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] } } // areverse: allocating reverse func areverse(a []int) []int { b := make([]int, len(a)) for i := range a { b[i] = a[len(a)-i-1] } return b } // ----------------------------------------------------------------------------- // Simple math functions const ( // big prime INF = 1000000007 INF2 = 1000000009 INF3 = 998244353 ) func min(a, b int) int { if a < b { return a } return b } func minll(a, b int64) int64 { if a < b { return a } return b } func max(a, b int) int { if a < b { return b } return a } func maxll(a, b int64) int64 { if a < b { return b } return a } func abs(a int) int { if a < 0 { return -a } return a } func absll(a int64) int64 { if a < 0 { return -a } return a } // egcd(a, b) returns d, x, y: // d is gcd(a,b) // x, y are integers that satisfy ax + by = d func egcd(a, b int) (int, int, int) { if b == 0 { return a, 1, 0 } d, x, y := egcd(b, a%b) return d, y, x - a/b*y } func egcdll(a, b int64) (int64, int64, int64) { if b == 0 { return a, 1, 0 } d, x, y := egcdll(b, a%b) return d, y, x - a/b*y } func gcd(a, b int) int { d, _, _ := egcd(a, b) return d } func gcdll(a, b int64) int64 { d, _, _ := egcdll(a, b) return d } // set up IO functions func init() { // for non-interactive SetInput(os.Stdin) SetOutput(os.Stdout) // Enable below when interactive. Its ok to leave above intact. // SetInteractive(os.Stdout, os.Stdin) } func main() { defer Flush() N, A := readInts(0) _ = N m := make(map[int]bool) for _, v := range A { if m[v] { println("NO") return } m[v] = true } println("YES") }
C
#include<stdio.h> int main(){ int t,n,i,ans[4]; for(i=0;i<4;i++){ scanf("%d %d",&t,&n); if(t==1)printf("%d\n",n*6000); if(t==2)printf("%d\n",n*4000); if(t==3)printf("%d\n",n*3000); if(t==4)printf("%d\n",n*2000); } return 0; }
JavaScript
var input = require('fs').readFileSync('/dev/stdin', 'utf8'); var Arr=(input.trim()).split("\n"); for(var i=0;i<4;i++){ var arr=Arr[i].split(" ").map(Number); if(arr[0]==1)console.log(arr[1]*6000); if(arr[0]==2)console.log(arr[1]*4000); if(arr[0]==3)console.log(arr[1]*3000); if(arr[0]==4)console.log(arr[1]*2000); }
Yes
Do these codes solve the same problem? Code 1: #include<stdio.h> int main(){ int t,n,i,ans[4]; for(i=0;i<4;i++){ scanf("%d %d",&t,&n); if(t==1)printf("%d\n",n*6000); if(t==2)printf("%d\n",n*4000); if(t==3)printf("%d\n",n*3000); if(t==4)printf("%d\n",n*2000); } return 0; } Code 2: var input = require('fs').readFileSync('/dev/stdin', 'utf8'); var Arr=(input.trim()).split("\n"); for(var i=0;i<4;i++){ var arr=Arr[i].split(" ").map(Number); if(arr[0]==1)console.log(arr[1]*6000); if(arr[0]==2)console.log(arr[1]*4000); if(arr[0]==3)console.log(arr[1]*3000); if(arr[0]==4)console.log(arr[1]*2000); }
Python
n = int(input()) lis = sorted(map(int, input().split())) ans = lis[0] for i in lis[1:]: ans += i ans /= 2 print(ans)
Java
import java.io.*; import java.util.*; public class Main{ public static void main(String args[]){ try{ new Main(); }catch(IOException e){ e.printStackTrace(); } } public Main() throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); List<Integer> Ans = new ArrayList<Integer>(); String line; int[] prime = Eratos(); while((line = in.readLine()) != null){ int size = Integer.parseInt(line); if(size==0) break; int pay = 0; for(int n=0; n<size; n++){ line = in.readLine(); String[] dst = line.split(" "); int center = Integer.parseInt(dst[0]); int range = Integer.parseInt(dst[1]); int min = Math.max(2, center-range); int max = Math.min(center+range, 999983); if(prime[min] != prime[min-1]){ pay += prime[max] - prime[min]; } else{ pay += prime[max] - prime[min] - 1; } } Ans.add(Math.max(0, pay)); } for(int n=0; n<Ans.size(); n++){ System.out.println(Ans.get(n)); } } public int[] Eratos(){ int[] prime = new int[1000000]; int c = 0; for(int i=2; i<1000000; i++){ if(prime[i]==0){ c++; prime[i] = c; long big = i*i; if(big > 1000000){ for(int j=i; j<1000000; j++){ if(prime[j]==0){ c++; prime[j] = c; } else{ prime[j] = c; } } break; } for(int j=i*i; j<1000000; j+=i){ prime[j] = -1; } } if(prime[i]==-1){ prime[i] = c; } } return prime; } }
No
Do these codes solve the same problem? Code 1: n = int(input()) lis = sorted(map(int, input().split())) ans = lis[0] for i in lis[1:]: ans += i ans /= 2 print(ans) Code 2: import java.io.*; import java.util.*; public class Main{ public static void main(String args[]){ try{ new Main(); }catch(IOException e){ e.printStackTrace(); } } public Main() throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); List<Integer> Ans = new ArrayList<Integer>(); String line; int[] prime = Eratos(); while((line = in.readLine()) != null){ int size = Integer.parseInt(line); if(size==0) break; int pay = 0; for(int n=0; n<size; n++){ line = in.readLine(); String[] dst = line.split(" "); int center = Integer.parseInt(dst[0]); int range = Integer.parseInt(dst[1]); int min = Math.max(2, center-range); int max = Math.min(center+range, 999983); if(prime[min] != prime[min-1]){ pay += prime[max] - prime[min]; } else{ pay += prime[max] - prime[min] - 1; } } Ans.add(Math.max(0, pay)); } for(int n=0; n<Ans.size(); n++){ System.out.println(Ans.get(n)); } } public int[] Eratos(){ int[] prime = new int[1000000]; int c = 0; for(int i=2; i<1000000; i++){ if(prime[i]==0){ c++; prime[i] = c; long big = i*i; if(big > 1000000){ for(int j=i; j<1000000; j++){ if(prime[j]==0){ c++; prime[j] = c; } else{ prime[j] = c; } } break; } for(int j=i*i; j<1000000; j+=i){ prime[j] = -1; } } if(prime[i]==-1){ prime[i] = c; } } return prime; } }
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; class Program { const int M = 1000000007; const double eps = 1e-9; static int[] dd = { 0, 1, 0, -1, 0 }; static void Main() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; var sc = new Scan(); var s = sc.Str; int n = s.Length; for (int i = 0; i < n - 1; i++) { if (s[i] == s[i + 1]) { Console.WriteLine("{0} {1}", i + 1, i + 2); return; } } for (int i = 0; i < n - 2; i++) { if (s[i] == s[i + 2]) { Console.WriteLine("{0} {1}", i + 1, i + 3); return; } } sw.WriteLine("-1 -1"); sw.Flush(); } static void swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static void swap<T>(IList<T> a, int i, int j) { var t = a[i]; a[i] = a[j]; a[j] = a[i]; } static T Max<T>(params T[] a) { return a.Max(); } static T Min<T>(params T[] a) { return a.Min(); } static T[] copy<T>(IList<T> a) { var ret = new T[a.Count]; for (int i = 0; i < a.Count; i++) ret[i] = a[i]; return ret; } } class Scan { public int Int { get { return int.Parse(Str); } } public long Long { get { return long.Parse(Str); } } public double Double { get { return double.Parse(Str); } } public string Str { get { return Console.ReadLine().Trim(); } } public int[] IntArr { get { return StrArr.Select(int.Parse).ToArray(); } } public int[] IntArrWithSep(char sep) { return Str.Split(sep).Select(int.Parse).ToArray(); } public long[] LongArr { get { return StrArr.Select(long.Parse).ToArray(); } } public double[] DoubleArr { get { return StrArr.Select(double.Parse).ToArray(); } } public string[] StrArr { get { return Str.Split(); } } public void Multi(out int a, out int b) { var arr = IntArr; a = arr[0]; b = arr[1]; } public void Multi(out int a, out int b, out int c) { var arr = IntArr; a = arr[0]; b = arr[1]; c = arr[2]; } public void Multi(out int a, out string b) { var arr = StrArr; a = int.Parse(arr[0]); b = arr[1]; } public void Multi(out string a, out int b) { var arr = StrArr; a = arr[0]; b = int.Parse(arr[1]); } public void Multi(out int a, out char b) { var arr = StrArr; a = int.Parse(arr[0]); b = arr[1][0]; } public void Multi(out char a, out int b) { var arr = StrArr; a = arr[0][0]; b = int.Parse(arr[1]); } public void Multi(out long a, out long b) { var arr = LongArr; a = arr[0]; b = arr[1]; } public void Multi(out long a, out int b) { var arr = LongArr; a = arr[0]; b = (int)arr[1]; } public void Multi(out int a, out long b) { var arr = LongArr; a = (int)arr[0]; b = arr[1]; } public void Multi(out string a, out string b) { var arr = StrArr; a = arr[0]; b = arr[1]; } } class mymath { static int Mod = 1000000007; public void setMod(int m) { Mod = m; } public bool isprime(long a) { if (a < 2) return false; for (long i = 2; i * i <= a; i++) if (a % i == 0) return false; return true; } public long[][] powmat(long[][] A, long n) { var E = new long[A.Length][]; for (int i = 0; i < A.Length; i++) { E[i] = new long[A.Length]; E[i][i] = 1; } if (n == 0) return E; var t = powmat(A, n / 2); if ((n & 1) == 0) return mulmat(t, t); return mulmat(mulmat(t, t), A); } public long[] mulmat(long[][] A, long[] x) { var ans = new long[A.Length]; for (int i = 0; i < A.Length; i++) for (int j = 0; j < x.Length; j++) ans[i] = (ans[i] + x[j] * A[i][j]) % Mod; return ans; } public long[][] mulmat(long[][] A, long[][] B) { var ans = new long[A.Length][]; for (int i = 0; i < A.Length; i++) { ans[i] = new long[B[0].Length]; for (int j = 0; j < B[0].Length; j++) for (int k = 0; k < B.Length; k++) ans[i][j] = (ans[i][j] + A[i][k] * B[k][j]) % Mod; } return ans; } public long powmod(long a, long b) { if (a >= Mod) return powmod(a % Mod, b); if (a == 0) return 0; if (b == 0) return 1; var t = powmod(a, b / 2); if ((b & 1) == 0) return t * t % Mod; return t * t % Mod * a % Mod; } public long gcd(long a, long b) { while (b > 0) { var t = a % b; a = b; b = t; } return a; } public long lcm(long a, long b) { return a * (b / gcd(a, b)); } public long Comb(int n, int r) { if (n < 0 || r < 0 || r > n) return 0; if (n - r < r) r = n - r; if (r == 0) return 1; if (r == 1) return n; var numerator = new int[r]; var denominator = new int[r]; for (int k = 0; k < r; k++) { numerator[k] = n - r + k + 1; denominator[k] = k + 1; } for (int p = 2; p <= r; p++) { int pivot = denominator[p - 1]; if (pivot > 1) { int offset = (n - r) % p; for (int k = p - 1; k < r; k += p) { numerator[k - offset] /= pivot; denominator[k] /= pivot; } } } long result = 1; for (int k = 0; k < r; k++) if (numerator[k] > 1) result = result * numerator[k] % Mod; return result; } }
Go
package main import "fmt" type Pair struct{ fst int snd int } func main() { var s string ans := Pair{-1, -1} fmt.Scan(&s) for i:=0; i<len(s)-2; i++ { if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { ans = Pair{i+1, i+3} break } } if len(s) == 2 && s[0] == s[1] { ans = Pair{1, 2} } fmt.Println(ans.fst, ans.snd) }
Yes
Do these codes solve the same problem? Code 1: using System; using System.Collections.Generic; using System.Linq; using System.IO; class Program { const int M = 1000000007; const double eps = 1e-9; static int[] dd = { 0, 1, 0, -1, 0 }; static void Main() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; var sc = new Scan(); var s = sc.Str; int n = s.Length; for (int i = 0; i < n - 1; i++) { if (s[i] == s[i + 1]) { Console.WriteLine("{0} {1}", i + 1, i + 2); return; } } for (int i = 0; i < n - 2; i++) { if (s[i] == s[i + 2]) { Console.WriteLine("{0} {1}", i + 1, i + 3); return; } } sw.WriteLine("-1 -1"); sw.Flush(); } static void swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static void swap<T>(IList<T> a, int i, int j) { var t = a[i]; a[i] = a[j]; a[j] = a[i]; } static T Max<T>(params T[] a) { return a.Max(); } static T Min<T>(params T[] a) { return a.Min(); } static T[] copy<T>(IList<T> a) { var ret = new T[a.Count]; for (int i = 0; i < a.Count; i++) ret[i] = a[i]; return ret; } } class Scan { public int Int { get { return int.Parse(Str); } } public long Long { get { return long.Parse(Str); } } public double Double { get { return double.Parse(Str); } } public string Str { get { return Console.ReadLine().Trim(); } } public int[] IntArr { get { return StrArr.Select(int.Parse).ToArray(); } } public int[] IntArrWithSep(char sep) { return Str.Split(sep).Select(int.Parse).ToArray(); } public long[] LongArr { get { return StrArr.Select(long.Parse).ToArray(); } } public double[] DoubleArr { get { return StrArr.Select(double.Parse).ToArray(); } } public string[] StrArr { get { return Str.Split(); } } public void Multi(out int a, out int b) { var arr = IntArr; a = arr[0]; b = arr[1]; } public void Multi(out int a, out int b, out int c) { var arr = IntArr; a = arr[0]; b = arr[1]; c = arr[2]; } public void Multi(out int a, out string b) { var arr = StrArr; a = int.Parse(arr[0]); b = arr[1]; } public void Multi(out string a, out int b) { var arr = StrArr; a = arr[0]; b = int.Parse(arr[1]); } public void Multi(out int a, out char b) { var arr = StrArr; a = int.Parse(arr[0]); b = arr[1][0]; } public void Multi(out char a, out int b) { var arr = StrArr; a = arr[0][0]; b = int.Parse(arr[1]); } public void Multi(out long a, out long b) { var arr = LongArr; a = arr[0]; b = arr[1]; } public void Multi(out long a, out int b) { var arr = LongArr; a = arr[0]; b = (int)arr[1]; } public void Multi(out int a, out long b) { var arr = LongArr; a = (int)arr[0]; b = arr[1]; } public void Multi(out string a, out string b) { var arr = StrArr; a = arr[0]; b = arr[1]; } } class mymath { static int Mod = 1000000007; public void setMod(int m) { Mod = m; } public bool isprime(long a) { if (a < 2) return false; for (long i = 2; i * i <= a; i++) if (a % i == 0) return false; return true; } public long[][] powmat(long[][] A, long n) { var E = new long[A.Length][]; for (int i = 0; i < A.Length; i++) { E[i] = new long[A.Length]; E[i][i] = 1; } if (n == 0) return E; var t = powmat(A, n / 2); if ((n & 1) == 0) return mulmat(t, t); return mulmat(mulmat(t, t), A); } public long[] mulmat(long[][] A, long[] x) { var ans = new long[A.Length]; for (int i = 0; i < A.Length; i++) for (int j = 0; j < x.Length; j++) ans[i] = (ans[i] + x[j] * A[i][j]) % Mod; return ans; } public long[][] mulmat(long[][] A, long[][] B) { var ans = new long[A.Length][]; for (int i = 0; i < A.Length; i++) { ans[i] = new long[B[0].Length]; for (int j = 0; j < B[0].Length; j++) for (int k = 0; k < B.Length; k++) ans[i][j] = (ans[i][j] + A[i][k] * B[k][j]) % Mod; } return ans; } public long powmod(long a, long b) { if (a >= Mod) return powmod(a % Mod, b); if (a == 0) return 0; if (b == 0) return 1; var t = powmod(a, b / 2); if ((b & 1) == 0) return t * t % Mod; return t * t % Mod * a % Mod; } public long gcd(long a, long b) { while (b > 0) { var t = a % b; a = b; b = t; } return a; } public long lcm(long a, long b) { return a * (b / gcd(a, b)); } public long Comb(int n, int r) { if (n < 0 || r < 0 || r > n) return 0; if (n - r < r) r = n - r; if (r == 0) return 1; if (r == 1) return n; var numerator = new int[r]; var denominator = new int[r]; for (int k = 0; k < r; k++) { numerator[k] = n - r + k + 1; denominator[k] = k + 1; } for (int p = 2; p <= r; p++) { int pivot = denominator[p - 1]; if (pivot > 1) { int offset = (n - r) % p; for (int k = p - 1; k < r; k += p) { numerator[k - offset] /= pivot; denominator[k] /= pivot; } } } long result = 1; for (int k = 0; k < r; k++) if (numerator[k] > 1) result = result * numerator[k] % Mod; return result; } } Code 2: package main import "fmt" type Pair struct{ fst int snd int } func main() { var s string ans := Pair{-1, -1} fmt.Scan(&s) for i:=0; i<len(s)-2; i++ { if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { ans = Pair{i+1, i+3} break } } if len(s) == 2 && s[0] == s[1] { ans = Pair{1, 2} } fmt.Println(ans.fst, ans.snd) }
Python
a,b = map(int,input().split()) c = a - b * 2 if(c < 0): print(0) else: print(c)
C++
#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; vector<int> A(3); for(int i = 0; i < 3; ++i) cin >> A[i]; vector<pair<int, int>> query; for(int i = 0; i < N; ++i) { string S; cin >> S; query.emplace_back(S[0] - 'A', S[1] - 'A'); } vector<int> ans, tmp; auto dfs = [&](auto &&dfs, int i) { if(!ans.empty() or A[0] < 0 or A[1] < 0 or A[2] < 0) return; if(i == N) { ans = tmp; return; } auto[x, y] = query[i]; for(int _ = 0; _ < 2; ++_) { A[x]++, A[y]--, tmp.push_back(x); dfs(dfs, i + 1); A[x]--, A[y]++, tmp.pop_back(); swap(x, y); } }; dfs(dfs, 0); if(ans.empty()) { cout << "No" << '\n'; } else { cout << "Yes" << '\n'; for(auto &i : ans) cout << "ABC"[i] << '\n'; } return 0; }
No
Do these codes solve the same problem? Code 1: a,b = map(int,input().split()) c = a - b * 2 if(c < 0): print(0) else: print(c) Code 2: #include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; vector<int> A(3); for(int i = 0; i < 3; ++i) cin >> A[i]; vector<pair<int, int>> query; for(int i = 0; i < N; ++i) { string S; cin >> S; query.emplace_back(S[0] - 'A', S[1] - 'A'); } vector<int> ans, tmp; auto dfs = [&](auto &&dfs, int i) { if(!ans.empty() or A[0] < 0 or A[1] < 0 or A[2] < 0) return; if(i == N) { ans = tmp; return; } auto[x, y] = query[i]; for(int _ = 0; _ < 2; ++_) { A[x]++, A[y]--, tmp.push_back(x); dfs(dfs, i + 1); A[x]--, A[y]++, tmp.pop_back(); swap(x, y); } }; dfs(dfs, 0); if(ans.empty()) { cout << "No" << '\n'; } else { cout << "Yes" << '\n'; for(auto &i : ans) cout << "ABC"[i] << '\n'; } return 0; }
Python
S = input() tmp = "" tmp2 = "" count = 0 for i in S: tmp2 += i if tmp2 != tmp: tmp = tmp2 tmp2 = "" count += 1 print(count)
PHP
<?php $s=trim(fgets(STDIN)); $n=strlen($s); $i=1; $c=$s[0]; $ans=1; while($i<$n){ if($s[$i]==$c){ ++$i; $c='ok'; }else{ $c=$s[$i]; } ++$ans; ++$i; } if($i>$n){ --$ans; } echo $ans;
Yes
Do these codes solve the same problem? Code 1: S = input() tmp = "" tmp2 = "" count = 0 for i in S: tmp2 += i if tmp2 != tmp: tmp = tmp2 tmp2 = "" count += 1 print(count) Code 2: <?php $s=trim(fgets(STDIN)); $n=strlen($s); $i=1; $c=$s[0]; $ans=1; while($i<$n){ if($s[$i]==$c){ ++$i; $c='ok'; }else{ $c=$s[$i]; } ++$ans; ++$i; } if($i>$n){ --$ans; } echo $ans;
C++
#include <bits/stdc++.h> using namespace std; int main() { long long n,d,x,sum; cin >> n >> d; x=n-d+1; sum=x*(x-1)/2+d-1; if(d>1) sum+=x-2; cout << sum << endl; return 0; }
Python
# AOJ 1591 Graph Making # Python3 2018.7.13 bal4u n, d = map(int, input().split()) if d == 1: print(n*(n-1)//2) else: print((n-1)+(n-d-1)*n-((n-d-1)*(n+d-2)//2))
Yes
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; int main() { long long n,d,x,sum; cin >> n >> d; x=n-d+1; sum=x*(x-1)/2+d-1; if(d>1) sum+=x-2; cout << sum << endl; return 0; } Code 2: # AOJ 1591 Graph Making # Python3 2018.7.13 bal4u n, d = map(int, input().split()) if d == 1: print(n*(n-1)//2) else: print((n-1)+(n-d-1)*n-((n-d-1)*(n+d-2)//2))
C++
#include <iostream> #include <cstdio> #include <algorithm> #include <sstream> #include <vector> #include <map> #include <cassert> using namespace std; int main(){ string s; while(cin >> s && s != "0000"){ if( count(s.begin(),s.end(),s[0]) == 4 ){ cout << "NA" << endl; continue; } int cnt = 0; while( s != "6174" ){ string l,g; l=g=s; sort(l.begin(),l.end()); sort(g.rbegin(),g.rend()); int a = atoi(l.c_str()); int b = atoi(g.c_str()); int r = b - a; char c[10]; sprintf(c,"%04d",r); s = string(c); cnt++; } cout << cnt << endl; } }
Python
a,b,c=map(int,input().split()) print(a if b==c else b if a==c else c)
No
Do these codes solve the same problem? Code 1: #include <iostream> #include <cstdio> #include <algorithm> #include <sstream> #include <vector> #include <map> #include <cassert> using namespace std; int main(){ string s; while(cin >> s && s != "0000"){ if( count(s.begin(),s.end(),s[0]) == 4 ){ cout << "NA" << endl; continue; } int cnt = 0; while( s != "6174" ){ string l,g; l=g=s; sort(l.begin(),l.end()); sort(g.rbegin(),g.rend()); int a = atoi(l.c_str()); int b = atoi(g.c_str()); int r = b - a; char c[10]; sprintf(c,"%04d",r); s = string(c); cnt++; } cout << cnt << endl; } } Code 2: a,b,c=map(int,input().split()) print(a if b==c else b if a==c else c)
C++
#include <bits/stdc++.h> using namespace std; typedef bool boolean; #define ll long long void exgcd(int a, int b, int& x, int& y) { if (!b) { x = 1, y = 0; } else { exgcd(b, a % b, y, x); y -= (a / b) * x; } } int inv(int a, int n) { int x, y; exgcd(a, n, x, y); return (x < 0) ? (x + n) : (x); } const int Mod = 1e9 + 7; template <const int Mod = :: Mod> class Z { public: int v; Z() : v(0) { } Z(int x) : v(x){ } Z(ll x) : v(x % Mod) { } Z operator + (Z b) { int x; return Z(((x = v + b.v) >= Mod) ? (x - Mod) : (x)); } Z operator - (Z b) { int x; return Z(((x = v - b.v) < 0) ? (x + Mod) : (x)); } Z operator * (Z b) { return Z(v * 1ll * b.v); } Z operator ~() { return inv(v, Mod); } Z operator - () { return Z(0) - *this; } Z& operator += (Z b) { return *this = *this + b; } Z& operator -= (Z b) { return *this = *this - b; } Z& operator *= (Z b) { return *this = *this * b; } }; Z<> qpow(Z<> a, int p) { Z<> rt = Z<>(1), pa = a; for ( ; p; p >>= 1, pa = pa * pa) { if (p & 1) { rt = rt * pa; } } return rt; } typedef Z<> Zi; const int N = 2005, M = N * N; int n, m; Zi f[N][N]; Zi fac[M], _fac[M]; void init_fac(int n) { fac[0] = 1; for (int i = 1; i <= n; i++) { fac[i] = fac[i - 1] * i; } _fac[n] = ~fac[n]; for (int i = n; i; i--) { _fac[i - 1] = _fac[i] * i; } } Zi comb(int n, int m) { return (n < m) ? (0) : (fac[n] * _fac[m] * _fac[n - m]); } int main() { scanf("%d%d", &n, &m); if (m == 1) { puts("1"); return 0; } init_fac(n * m); f[0][0] = 1; for (int i = 1; i <= n; i++) { for (int j = i; j; j--) { f[i][j] = f[i - 1][j - 1] * comb(i * m - j - 1, m - 2) + f[i][j + 1]; } f[i][0] += f[i][1]; } printf("%d\n", (f[n][0] * fac[n]).v); return 0; }
Python
k,n=map(int,input().split()) a = list(map(int,input().split())) m = k-a[n-1]+a[0] for i in range(n-1): m = max(m,a[i+1]-a[i]) x = k-m print(x)
No
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; typedef bool boolean; #define ll long long void exgcd(int a, int b, int& x, int& y) { if (!b) { x = 1, y = 0; } else { exgcd(b, a % b, y, x); y -= (a / b) * x; } } int inv(int a, int n) { int x, y; exgcd(a, n, x, y); return (x < 0) ? (x + n) : (x); } const int Mod = 1e9 + 7; template <const int Mod = :: Mod> class Z { public: int v; Z() : v(0) { } Z(int x) : v(x){ } Z(ll x) : v(x % Mod) { } Z operator + (Z b) { int x; return Z(((x = v + b.v) >= Mod) ? (x - Mod) : (x)); } Z operator - (Z b) { int x; return Z(((x = v - b.v) < 0) ? (x + Mod) : (x)); } Z operator * (Z b) { return Z(v * 1ll * b.v); } Z operator ~() { return inv(v, Mod); } Z operator - () { return Z(0) - *this; } Z& operator += (Z b) { return *this = *this + b; } Z& operator -= (Z b) { return *this = *this - b; } Z& operator *= (Z b) { return *this = *this * b; } }; Z<> qpow(Z<> a, int p) { Z<> rt = Z<>(1), pa = a; for ( ; p; p >>= 1, pa = pa * pa) { if (p & 1) { rt = rt * pa; } } return rt; } typedef Z<> Zi; const int N = 2005, M = N * N; int n, m; Zi f[N][N]; Zi fac[M], _fac[M]; void init_fac(int n) { fac[0] = 1; for (int i = 1; i <= n; i++) { fac[i] = fac[i - 1] * i; } _fac[n] = ~fac[n]; for (int i = n; i; i--) { _fac[i - 1] = _fac[i] * i; } } Zi comb(int n, int m) { return (n < m) ? (0) : (fac[n] * _fac[m] * _fac[n - m]); } int main() { scanf("%d%d", &n, &m); if (m == 1) { puts("1"); return 0; } init_fac(n * m); f[0][0] = 1; for (int i = 1; i <= n; i++) { for (int j = i; j; j--) { f[i][j] = f[i - 1][j - 1] * comb(i * m - j - 1, m - 2) + f[i][j + 1]; } f[i][0] += f[i][1]; } printf("%d\n", (f[n][0] * fac[n]).v); return 0; } Code 2: k,n=map(int,input().split()) a = list(map(int,input().split())) m = k-a[n-1]+a[0] for i in range(n-1): m = max(m,a[i+1]-a[i]) x = k-m print(x)
C++
#include <iostream> #include <algorithm> using namespace std; int main() { int h,w; cin >> h >> w; int c[10][10]; int a[h][w]; for(int i=0;i<10;i++){ for(int j=0;j<10;j++){ cin >> c[i][j]; } } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> a[i][j]; } } for(int l=0;l<5;l++){ for(int i=0;i<10;i++){ for(int j=0;j<10;j++){ for(int k=0;k<10;k++){ c[i][j] = min(c[i][j],c[i][k]+c[k][j]); } } } } int magic = 0; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ magic = magic + c[a[i][j]][1]; } } cout << magic << endl; return 0; }
C
#include <stdio.h> int main(void) { char s[19]; scanf("%s",s); s[5] = ' '; s[13] = ' '; printf("%s",s); return 0; }
No
Do these codes solve the same problem? Code 1: #include <iostream> #include <algorithm> using namespace std; int main() { int h,w; cin >> h >> w; int c[10][10]; int a[h][w]; for(int i=0;i<10;i++){ for(int j=0;j<10;j++){ cin >> c[i][j]; } } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ cin >> a[i][j]; } } for(int l=0;l<5;l++){ for(int i=0;i<10;i++){ for(int j=0;j<10;j++){ for(int k=0;k<10;k++){ c[i][j] = min(c[i][j],c[i][k]+c[k][j]); } } } } int magic = 0; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ magic = magic + c[a[i][j]][1]; } } cout << magic << endl; return 0; } Code 2: #include <stdio.h> int main(void) { char s[19]; scanf("%s",s); s[5] = ' '; s[13] = ' '; printf("%s",s); return 0; }
Python
import sys stdin = sys.stdin ni = lambda: int(ns()) na = lambda: list(map(int, stdin.readline().split())) ns = lambda: stdin.readline().rstrip() # ignore trailing spaces n, m, q = na() cs = [] for i in range(q): cs.append(na()) def dfs(pos, a, m, cs): if pos == len(a): sc = 0 for co in cs: if a[co[1]-1] - a[co[0]-1] == co[2]: sc += co[3] return sc ans = 0 low = 1 if pos == 0 else a[pos-1] for i in range(low, m+1): a[pos] = i ans = max(ans, dfs(pos+1, a, m, cs)) return ans print(dfs(0, [0] * n, m, cs))
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Diagnostics; using System.Numerics; using static System.Console; using static System.Convert; using static System.Math; using static Template; using Pi = Pair<int, int>; class Solver { int N, M, Q; int[] now; int[][] A; int res = 0; public void Solve(Scanner sc) { sc.Make(out N, out M, out Q); A = sc.ArrInt2D(Q); now = new int[N]; for(int k = 1; k <= M; k++) { now[0] = k; dfs(1); } Console.WriteLine(res); } void dfs(int i) { if (i == N) { var s = 0; for(int j = 0; j < Q; j++) { if (now[A[j][1] - 1] - now[A[j][0] - 1] == A[j][2]) s += A[j][3]; } chmax(ref res, s); return; } for(int j = now[i - 1]; j <= M; j++) { now[i] = j; dfs(i + 1); } } } #region Template public static class Template { static void Main(string[] args) { Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }); new Solver().Solve(new Scanner()); Console.Out.Flush(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; } public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; } public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; } public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid()); public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; } public static int MaxElement<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; } public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; } public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); } } public class Scanner { public string Str => Console.ReadLine().Trim(); public int Int => int.Parse(Str); public long Long => long.Parse(Str); public double Double => double.Parse(Str); public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray(); public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray(); public char[][] Grid(int n) => Create(n, () => Str.ToCharArray()); public int[] ArrInt1D(int n) => Create(n, () => Int); public long[] ArrLong1D(int n) => Create(n, () => Long); public int[][] ArrInt2D(int n) => Create(n, () => ArrInt); public long[][] ArrLong2D(int n) => Create(n, () => ArrLong); private Queue<string> q = new Queue<string>(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); } public void Make<T1>(out T1 v1) => v1 = Next<T1>(); public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); } public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); } public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); } public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); } public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); } //public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); } //public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); } //public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); } } public class Pair<T1, T2> : IComparable<Pair<T1, T2>> { public T1 v1; public T2 v2; public Pair() { } public Pair(T1 v1, T2 v2) { this.v1 = v1; this.v2 = v2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(Pair<T1, T2> p) { var c = Comparer<T1>.Default.Compare(v1, p.v1); if (c == 0) c = Comparer<T2>.Default.Compare(v2, p.v2); return c; } public override string ToString() => $"{v1.ToString()} {v2.ToString()}"; public void Deconstruct(out T1 a, out T2 b) { a = v1; b = v2; } } public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>> { public T3 v3; public Pair() : base() { } public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2) { this.v3 = v3; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(Pair<T1, T2, T3> p) { var c = base.CompareTo(p); if (c == 0) c = Comparer<T3>.Default.Compare(v3, p.v3); return c; } public override string ToString() => $"{base.ToString()} {v3.ToString()}"; public void Deconstruct(out T1 a, out T2 b, out T3 c) { Deconstruct(out a, out b); c = v3; } } #endregion
Yes
Do these codes solve the same problem? Code 1: import sys stdin = sys.stdin ni = lambda: int(ns()) na = lambda: list(map(int, stdin.readline().split())) ns = lambda: stdin.readline().rstrip() # ignore trailing spaces n, m, q = na() cs = [] for i in range(q): cs.append(na()) def dfs(pos, a, m, cs): if pos == len(a): sc = 0 for co in cs: if a[co[1]-1] - a[co[0]-1] == co[2]: sc += co[3] return sc ans = 0 low = 1 if pos == 0 else a[pos-1] for i in range(low, m+1): a[pos] = i ans = max(ans, dfs(pos+1, a, m, cs)) return ans print(dfs(0, [0] * n, m, cs)) Code 2: using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Diagnostics; using System.Numerics; using static System.Console; using static System.Convert; using static System.Math; using static Template; using Pi = Pair<int, int>; class Solver { int N, M, Q; int[] now; int[][] A; int res = 0; public void Solve(Scanner sc) { sc.Make(out N, out M, out Q); A = sc.ArrInt2D(Q); now = new int[N]; for(int k = 1; k <= M; k++) { now[0] = k; dfs(1); } Console.WriteLine(res); } void dfs(int i) { if (i == N) { var s = 0; for(int j = 0; j < Q; j++) { if (now[A[j][1] - 1] - now[A[j][0] - 1] == A[j][2]) s += A[j][3]; } chmax(ref res, s); return; } for(int j = now[i - 1]; j <= M; j++) { now[i] = j; dfs(i + 1); } } } #region Template public static class Template { static void Main(string[] args) { Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }); new Solver().Solve(new Scanner()); Console.Out.Flush(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; } public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; } public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; } public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid()); public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; } public static int MaxElement<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; } public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; } public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); } } public class Scanner { public string Str => Console.ReadLine().Trim(); public int Int => int.Parse(Str); public long Long => long.Parse(Str); public double Double => double.Parse(Str); public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray(); public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray(); public char[][] Grid(int n) => Create(n, () => Str.ToCharArray()); public int[] ArrInt1D(int n) => Create(n, () => Int); public long[] ArrLong1D(int n) => Create(n, () => Long); public int[][] ArrInt2D(int n) => Create(n, () => ArrInt); public long[][] ArrLong2D(int n) => Create(n, () => ArrLong); private Queue<string> q = new Queue<string>(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); } public void Make<T1>(out T1 v1) => v1 = Next<T1>(); public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); } public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); } public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); } public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); } public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); } //public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); } //public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); } //public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); } } public class Pair<T1, T2> : IComparable<Pair<T1, T2>> { public T1 v1; public T2 v2; public Pair() { } public Pair(T1 v1, T2 v2) { this.v1 = v1; this.v2 = v2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(Pair<T1, T2> p) { var c = Comparer<T1>.Default.Compare(v1, p.v1); if (c == 0) c = Comparer<T2>.Default.Compare(v2, p.v2); return c; } public override string ToString() => $"{v1.ToString()} {v2.ToString()}"; public void Deconstruct(out T1 a, out T2 b) { a = v1; b = v2; } } public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>> { public T3 v3; public Pair() : base() { } public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2) { this.v3 = v3; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(Pair<T1, T2, T3> p) { var c = base.CompareTo(p); if (c == 0) c = Comparer<T3>.Default.Compare(v3, p.v3); return c; } public override string ToString() => $"{base.ToString()} {v3.ToString()}"; public void Deconstruct(out T1 a, out T2 b, out T3 c) { Deconstruct(out a, out b); c = v3; } } #endregion
C#
using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Net.NetworkInformation; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Extensions; using DSA; using static System.Math; using static Extensions.MathExtension; using static Extensions.ConsoleInputExtension; using static Extensions.ConsoleOutputExtension; class Solver { public void Solve() { //Solve Code Here int d = Cin; var c = new int[26]; for (int i = 0; i < 26; i++) c[i] = Cin; var s = new int[d, 26]; for (int i = 0; i < d; i++) for (int j = 0; j < 26; j++) s[i, j] = Cin; var contests = new int[d]; for (int i = 0; i < d; i++) { int max = 0; for (int j = 0; j < 26; j++) { if (s[i, max] < s[i, j]) max = j; } contests[i] = max + 1; } contests.ForEach(val => Coutln(val)); } } //Other Classes Here #if !DEBUG class EntryPoint { static void Main(string[] args) { new Solver().Solve(); Flush(); } } #endif namespace DSA { public class PriorityQueue<T> { private readonly List<Tuple<int, T>> _list = new List<Tuple<int, T>>(); public int Count => _list.Count; public PriorityQueue() { } public void Push(T item, int priority) { _list.Add(Tuple.Create(priority, item)); int itemIndex = Count - 1, parentIndex; while ((parentIndex = GetParentIndex(itemIndex)) != -1 && priority > _list[parentIndex].Item1) { Swap(itemIndex, parentIndex); itemIndex = parentIndex; } } private int GetParentIndex(int index) { if (index == 0) return -1; return ((index + 1) >> 1) - 1; } private Tuple<int, int> GetChildrenIndex(int index) { var item2 = (index + 1) << 1; var item1 = item2 - 1; return Tuple.Create(item1, item2); } public T Pop() { if (Count <= 0) throw new IndexOutOfRangeException(); var item = _list[0].Item2; _list[0] = _list[Count - 1]; _list.RemoveAt(Count - 1); int index = 0; Tuple<int, int> childrenIndex = GetChildrenIndex(index); while (childrenIndex.Item1 < Count || childrenIndex.Item2 < Count) { if (childrenIndex.Item2 >= Count || _list[childrenIndex.Item1].Item1 > _list[childrenIndex.Item2].Item1) { if (_list[childrenIndex.Item1].Item1 <= _list[index].Item1) return item; Swap(index, childrenIndex.Item1); index = childrenIndex.Item1; } else { if (_list[childrenIndex.Item2].Item1 <= _list[index].Item1) return item; Swap(index, childrenIndex.Item2); index = childrenIndex.Item2; } childrenIndex = GetChildrenIndex(index); } return item; } public T Peek() { return _list[0].Item2; } private void Swap(int index1, int index2) { var tmp = _list[index1]; _list[index1] = _list[index2]; _list[index2] = tmp; } } public class UnionFind { private readonly int[] _array; public UnionFind(int size) { _array = new int[size]; for (int i = 0; i < size; i++) { _array[i] = i; } } public int GetRootNode(int n) { if (_array[n] == n) return n; return _array[n] = GetRootNode(_array[n]); } public void UnionGroup(int a, int b) { var rootA = GetRootNode(a); var rootB = GetRootNode(b); if (rootA == rootB) return; _array[rootA] = rootB; } public bool IsSameGroup(int a, int b) => GetRootNode(a) == GetRootNode(b); public bool IsRoot(int n) => _array[n] == n; } public delegate T SegTreeCombiner<T>(T item1, T item2); public class SegTree<T> { private readonly T _defaultItem; private readonly SegTreeCombiner<T> _func; private T[] List; private int size; public SegTree(T[] list, T defaultItem, SegTreeCombiner<T> func) { _defaultItem = defaultItem; _func = func; size = 1; while (size < list.Length) size <<= 1; List = new T[2 * size - 1]; for (int i = 0; i < list.Length; i++) List[i + size - 1] = list[i]; for (int i = list.Length; i < size; i++) List[i + size - 1] = defaultItem; for (int i = size - 1 - 1; i >= 0; i--) { List[i] = _func(List[2 * i + 1], List[2 * i + 2]); } } public void Update(int index, T value) { index += size - 1; List[index] = value; while (index > 0) { index = (index - 1) >> 1; List[index] = _func(List[2 * index + 1], List[2 * index + 2]); } } public T Query(int a, int b) { return Query(a, b, 0, 0, size); } private T Query(int a, int b, int k, int l, int r) { if (r <= a || b <= l) return _defaultItem; if (a <= l && r <= b) return List[k]; return _func(Query(a, b, k * 2 + 1, l, (l + r) >> 1), Query(a, b, k * 2 + 2, (l + r) >> 1, r)); } } public static class BinarySearch { public delegate bool Terms<T>(T i); public static int UpperBound(int initLeft, int initRight, Terms<int> term) { int left = initLeft - 1, right = initRight; while (right - left > 1) { int mid = (left + right) >> 1; if (mid != initLeft - 1 && term(mid)) left = mid; else right = mid; } return left; } public static long UpperBound(long initLeft, long initRight, Terms<long> term) { long left = initLeft - 1, right = initRight; while (right - left > 1) { long mid = (left + right) >> 1; if (mid != initLeft - 1 && term(mid)) left = mid; else right = mid; } return left; } public static int LowerBound(int initLeft, int initRight, Terms<int> term) { int left = initLeft - 1, right = initRight; while (right - left > 1) { int mid = (left + right) >> 1; if (mid != initRight && term(mid)) right = mid; else left = mid; } return right; } public static long LowerBound(long initLeft, long initRight, Terms<long> term) { long left = initLeft - 1, right = initRight; while (right - left > 1) { long mid = (left + right) >> 1; if (term(mid)) right = mid; else left = mid; } return right; } } } struct ModInt { public long Value { get; } public static long Mod { get; set; } = 1000000000L + 7; public ModInt(long l) { long value = l % Mod; while (value < 0) value += Mod; Value = value % Mod; } public static implicit operator long(ModInt m) { return m.Value; } public static implicit operator ModInt(long l) { return new ModInt(l); } public static ModInt operator +(ModInt a, ModInt b) { return new ModInt(a.Value + b.Value); } public static ModInt operator -(ModInt a, ModInt b) { return new ModInt(a.Value - b.Value); } public static ModInt operator *(ModInt a, ModInt b) { return new ModInt(a.Value * b.Value); } public static ModInt operator /(ModInt a, ModInt b) { return new ModInt(a * b.Inverse()); } public override string ToString() { return Value.ToString(); } } static class ModIntMath { public static ModInt Pow(this ModInt a, ModInt b) { var pow = b.Value; var m = a; ModInt ans = new ModInt(1); while (pow != 0) { if ((pow & 1) == 1) { ans *= m; } pow >>= 1; m *= m; } return ans; } public static ModInt Inverse(this ModInt m) { return m.Pow((ModInt) (ModInt.Mod - 2)); } } namespace Extensions { public class ConsoleInputExtension { private static readonly ConsoleInputExtension _cin = new ConsoleInputExtension(); public static ConsoleInputExtension Cin => _cin; private static readonly Queue<string> _inputQueue = new Queue<string>(); private ConsoleInputExtension() { } public static implicit operator string(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return _inputQueue.Dequeue(); } public static implicit operator int(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return int.Parse(_inputQueue.Dequeue()); } public static implicit operator long(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return long.Parse(_inputQueue.Dequeue()); } public static implicit operator float(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return float.Parse(_inputQueue.Dequeue()); } public static implicit operator double(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return double.Parse(_inputQueue.Dequeue()); } } public static class ConsoleOutputExtension { private static StringBuilder _builder = new StringBuilder(); public static void Cout(object o) { _builder.Append(o); } public static void CoutF(object o) { _builder.Append(o); Flush(); } public static void Coutln(object o) { _builder.Append(o); _builder.Append('\n'); } public static void Coutln() { _builder.Append('\n'); } public static void CoutlnF(object o) { _builder.Append(o); _builder.Append('\n'); Flush(); } public static void Flush() { Console.Write(_builder.ToString()); _builder.Clear(); } } public static class MathExtension { //最小公倍数 public static int LCM(int num1, int num2) { var gcd = GCD(num1, num2); return num1 * (num2 / gcd); } public static long LCM(long num1, long num2) { var gcd = GCD(num1, num2); return num1 * (num2 / gcd); } //最大公約数 public static int GCD(int num1, int num2) { int a = Math.Max(num1, num2); int b = Math.Min(num1, num2); if (b == 0) return a; int mod; while ((mod = a % b) != 0) { a = b; b = mod; } return b; } public static long GCD(long num1, long num2) { long a = Math.Max(num1, num2); long b = Math.Min(num1, num2); if (b == 0) return a; long mod; while ((mod = a % b) != 0) { a = b; b = mod; } return b; } } public static class EnumerableExtension { public delegate void Function<in T>(T val); public static void ForEach<T>(this IEnumerable<T> enumerable, Function<T> function) { foreach (var x in enumerable) { function(x); } } } }
Go
package main import ( "bufio" "fmt" "os" "strconv" ) var ( D int c [26]int s [365][26]int ) func main() { readVariables() for row := 0; row < D; row++ { fmt.Println(maxGreed(row)) } } func maxGreed(row int) int { max := 0 result := 0 for i, v := range s[row] { if v > max { result = i max = v } } return result + 1 } func readVariables() { D = nextInt() for i := 0; i < 26; i++ { c[i] = nextInt() } for i := 0; i < D; i++ { for j := 0; j < 26; j++ { s[i][j] = nextInt() } } } /* Template */ var scanner *bufio.Scanner func init() { Max := 1001001 scanner = bufio.NewScanner(os.Stdin) scanner.Buffer(make([]byte, 0, Max), Max) scanner.Split(bufio.ScanWords) } //nextInt converts next token from stdin and returns integer value. //nextInt panics when conversion into an integer fails. func nextInt() int { if !scanner.Scan() { panic("No more token.") } num, err := strconv.Atoi(scanner.Text()) if err != nil { panic("nextInt(): cannot convert to int: " + scanner.Text()) } return num } func nextStr() string { if !scanner.Scan() { panic("No more token.") } return scanner.Text() } // MinInt returns minimum argument func MinInt(x, y int) int { if x < y { return x } else { return y } } //MaxInt returns maximum argument func MaxInt(x, y int) int { if x < y { return y } else { return x } } //AbsInt returns |x| for x func AbsInt(x int) int { if x < 0 { return -x } return x } //ModPow calculates integer power with modulo operation //if modulo <= 1, it powers w/o module operation //if base < 0, return value might be negative too. func ModPow(base, exponent, modulo int) (result int) { result = 1 for exponent > 0 { if exponent%2 == 1 { result *= base if modulo > 1 { result %= modulo } } base *= base if modulo > 1 { base %= modulo } exponent /= 2 } return } //Gcd func Gcd(vals ...int) (result int) { if len(vals) == 0 { return } result = vals[0] for i := 1; i < len(vals); i++ { result = gcd(result, vals[i]) } return } func gcd(x, y int) int { x, y = AbsInt(x), AbsInt(y) for y > 0 { x, y = y, x%y } return x } //Lcm func Lcm(vals ...int) (result int) { if len(vals) == 0 { return } result = vals[0] for i := 1; i < len(vals); i++ { result = lcm(result, vals[i]) } return } func lcm(x, y int) int { return x * y / gcd(x, y) }
Yes
Do these codes solve the same problem? Code 1: using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Net.NetworkInformation; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Extensions; using DSA; using static System.Math; using static Extensions.MathExtension; using static Extensions.ConsoleInputExtension; using static Extensions.ConsoleOutputExtension; class Solver { public void Solve() { //Solve Code Here int d = Cin; var c = new int[26]; for (int i = 0; i < 26; i++) c[i] = Cin; var s = new int[d, 26]; for (int i = 0; i < d; i++) for (int j = 0; j < 26; j++) s[i, j] = Cin; var contests = new int[d]; for (int i = 0; i < d; i++) { int max = 0; for (int j = 0; j < 26; j++) { if (s[i, max] < s[i, j]) max = j; } contests[i] = max + 1; } contests.ForEach(val => Coutln(val)); } } //Other Classes Here #if !DEBUG class EntryPoint { static void Main(string[] args) { new Solver().Solve(); Flush(); } } #endif namespace DSA { public class PriorityQueue<T> { private readonly List<Tuple<int, T>> _list = new List<Tuple<int, T>>(); public int Count => _list.Count; public PriorityQueue() { } public void Push(T item, int priority) { _list.Add(Tuple.Create(priority, item)); int itemIndex = Count - 1, parentIndex; while ((parentIndex = GetParentIndex(itemIndex)) != -1 && priority > _list[parentIndex].Item1) { Swap(itemIndex, parentIndex); itemIndex = parentIndex; } } private int GetParentIndex(int index) { if (index == 0) return -1; return ((index + 1) >> 1) - 1; } private Tuple<int, int> GetChildrenIndex(int index) { var item2 = (index + 1) << 1; var item1 = item2 - 1; return Tuple.Create(item1, item2); } public T Pop() { if (Count <= 0) throw new IndexOutOfRangeException(); var item = _list[0].Item2; _list[0] = _list[Count - 1]; _list.RemoveAt(Count - 1); int index = 0; Tuple<int, int> childrenIndex = GetChildrenIndex(index); while (childrenIndex.Item1 < Count || childrenIndex.Item2 < Count) { if (childrenIndex.Item2 >= Count || _list[childrenIndex.Item1].Item1 > _list[childrenIndex.Item2].Item1) { if (_list[childrenIndex.Item1].Item1 <= _list[index].Item1) return item; Swap(index, childrenIndex.Item1); index = childrenIndex.Item1; } else { if (_list[childrenIndex.Item2].Item1 <= _list[index].Item1) return item; Swap(index, childrenIndex.Item2); index = childrenIndex.Item2; } childrenIndex = GetChildrenIndex(index); } return item; } public T Peek() { return _list[0].Item2; } private void Swap(int index1, int index2) { var tmp = _list[index1]; _list[index1] = _list[index2]; _list[index2] = tmp; } } public class UnionFind { private readonly int[] _array; public UnionFind(int size) { _array = new int[size]; for (int i = 0; i < size; i++) { _array[i] = i; } } public int GetRootNode(int n) { if (_array[n] == n) return n; return _array[n] = GetRootNode(_array[n]); } public void UnionGroup(int a, int b) { var rootA = GetRootNode(a); var rootB = GetRootNode(b); if (rootA == rootB) return; _array[rootA] = rootB; } public bool IsSameGroup(int a, int b) => GetRootNode(a) == GetRootNode(b); public bool IsRoot(int n) => _array[n] == n; } public delegate T SegTreeCombiner<T>(T item1, T item2); public class SegTree<T> { private readonly T _defaultItem; private readonly SegTreeCombiner<T> _func; private T[] List; private int size; public SegTree(T[] list, T defaultItem, SegTreeCombiner<T> func) { _defaultItem = defaultItem; _func = func; size = 1; while (size < list.Length) size <<= 1; List = new T[2 * size - 1]; for (int i = 0; i < list.Length; i++) List[i + size - 1] = list[i]; for (int i = list.Length; i < size; i++) List[i + size - 1] = defaultItem; for (int i = size - 1 - 1; i >= 0; i--) { List[i] = _func(List[2 * i + 1], List[2 * i + 2]); } } public void Update(int index, T value) { index += size - 1; List[index] = value; while (index > 0) { index = (index - 1) >> 1; List[index] = _func(List[2 * index + 1], List[2 * index + 2]); } } public T Query(int a, int b) { return Query(a, b, 0, 0, size); } private T Query(int a, int b, int k, int l, int r) { if (r <= a || b <= l) return _defaultItem; if (a <= l && r <= b) return List[k]; return _func(Query(a, b, k * 2 + 1, l, (l + r) >> 1), Query(a, b, k * 2 + 2, (l + r) >> 1, r)); } } public static class BinarySearch { public delegate bool Terms<T>(T i); public static int UpperBound(int initLeft, int initRight, Terms<int> term) { int left = initLeft - 1, right = initRight; while (right - left > 1) { int mid = (left + right) >> 1; if (mid != initLeft - 1 && term(mid)) left = mid; else right = mid; } return left; } public static long UpperBound(long initLeft, long initRight, Terms<long> term) { long left = initLeft - 1, right = initRight; while (right - left > 1) { long mid = (left + right) >> 1; if (mid != initLeft - 1 && term(mid)) left = mid; else right = mid; } return left; } public static int LowerBound(int initLeft, int initRight, Terms<int> term) { int left = initLeft - 1, right = initRight; while (right - left > 1) { int mid = (left + right) >> 1; if (mid != initRight && term(mid)) right = mid; else left = mid; } return right; } public static long LowerBound(long initLeft, long initRight, Terms<long> term) { long left = initLeft - 1, right = initRight; while (right - left > 1) { long mid = (left + right) >> 1; if (term(mid)) right = mid; else left = mid; } return right; } } } struct ModInt { public long Value { get; } public static long Mod { get; set; } = 1000000000L + 7; public ModInt(long l) { long value = l % Mod; while (value < 0) value += Mod; Value = value % Mod; } public static implicit operator long(ModInt m) { return m.Value; } public static implicit operator ModInt(long l) { return new ModInt(l); } public static ModInt operator +(ModInt a, ModInt b) { return new ModInt(a.Value + b.Value); } public static ModInt operator -(ModInt a, ModInt b) { return new ModInt(a.Value - b.Value); } public static ModInt operator *(ModInt a, ModInt b) { return new ModInt(a.Value * b.Value); } public static ModInt operator /(ModInt a, ModInt b) { return new ModInt(a * b.Inverse()); } public override string ToString() { return Value.ToString(); } } static class ModIntMath { public static ModInt Pow(this ModInt a, ModInt b) { var pow = b.Value; var m = a; ModInt ans = new ModInt(1); while (pow != 0) { if ((pow & 1) == 1) { ans *= m; } pow >>= 1; m *= m; } return ans; } public static ModInt Inverse(this ModInt m) { return m.Pow((ModInt) (ModInt.Mod - 2)); } } namespace Extensions { public class ConsoleInputExtension { private static readonly ConsoleInputExtension _cin = new ConsoleInputExtension(); public static ConsoleInputExtension Cin => _cin; private static readonly Queue<string> _inputQueue = new Queue<string>(); private ConsoleInputExtension() { } public static implicit operator string(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return _inputQueue.Dequeue(); } public static implicit operator int(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return int.Parse(_inputQueue.Dequeue()); } public static implicit operator long(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return long.Parse(_inputQueue.Dequeue()); } public static implicit operator float(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return float.Parse(_inputQueue.Dequeue()); } public static implicit operator double(ConsoleInputExtension _) { if (_inputQueue.Count == 0) Console.ReadLine().Split(' ') .ForEach(val => _inputQueue.Enqueue(val)); return double.Parse(_inputQueue.Dequeue()); } } public static class ConsoleOutputExtension { private static StringBuilder _builder = new StringBuilder(); public static void Cout(object o) { _builder.Append(o); } public static void CoutF(object o) { _builder.Append(o); Flush(); } public static void Coutln(object o) { _builder.Append(o); _builder.Append('\n'); } public static void Coutln() { _builder.Append('\n'); } public static void CoutlnF(object o) { _builder.Append(o); _builder.Append('\n'); Flush(); } public static void Flush() { Console.Write(_builder.ToString()); _builder.Clear(); } } public static class MathExtension { //最小公倍数 public static int LCM(int num1, int num2) { var gcd = GCD(num1, num2); return num1 * (num2 / gcd); } public static long LCM(long num1, long num2) { var gcd = GCD(num1, num2); return num1 * (num2 / gcd); } //最大公約数 public static int GCD(int num1, int num2) { int a = Math.Max(num1, num2); int b = Math.Min(num1, num2); if (b == 0) return a; int mod; while ((mod = a % b) != 0) { a = b; b = mod; } return b; } public static long GCD(long num1, long num2) { long a = Math.Max(num1, num2); long b = Math.Min(num1, num2); if (b == 0) return a; long mod; while ((mod = a % b) != 0) { a = b; b = mod; } return b; } } public static class EnumerableExtension { public delegate void Function<in T>(T val); public static void ForEach<T>(this IEnumerable<T> enumerable, Function<T> function) { foreach (var x in enumerable) { function(x); } } } } Code 2: package main import ( "bufio" "fmt" "os" "strconv" ) var ( D int c [26]int s [365][26]int ) func main() { readVariables() for row := 0; row < D; row++ { fmt.Println(maxGreed(row)) } } func maxGreed(row int) int { max := 0 result := 0 for i, v := range s[row] { if v > max { result = i max = v } } return result + 1 } func readVariables() { D = nextInt() for i := 0; i < 26; i++ { c[i] = nextInt() } for i := 0; i < D; i++ { for j := 0; j < 26; j++ { s[i][j] = nextInt() } } } /* Template */ var scanner *bufio.Scanner func init() { Max := 1001001 scanner = bufio.NewScanner(os.Stdin) scanner.Buffer(make([]byte, 0, Max), Max) scanner.Split(bufio.ScanWords) } //nextInt converts next token from stdin and returns integer value. //nextInt panics when conversion into an integer fails. func nextInt() int { if !scanner.Scan() { panic("No more token.") } num, err := strconv.Atoi(scanner.Text()) if err != nil { panic("nextInt(): cannot convert to int: " + scanner.Text()) } return num } func nextStr() string { if !scanner.Scan() { panic("No more token.") } return scanner.Text() } // MinInt returns minimum argument func MinInt(x, y int) int { if x < y { return x } else { return y } } //MaxInt returns maximum argument func MaxInt(x, y int) int { if x < y { return y } else { return x } } //AbsInt returns |x| for x func AbsInt(x int) int { if x < 0 { return -x } return x } //ModPow calculates integer power with modulo operation //if modulo <= 1, it powers w/o module operation //if base < 0, return value might be negative too. func ModPow(base, exponent, modulo int) (result int) { result = 1 for exponent > 0 { if exponent%2 == 1 { result *= base if modulo > 1 { result %= modulo } } base *= base if modulo > 1 { base %= modulo } exponent /= 2 } return } //Gcd func Gcd(vals ...int) (result int) { if len(vals) == 0 { return } result = vals[0] for i := 1; i < len(vals); i++ { result = gcd(result, vals[i]) } return } func gcd(x, y int) int { x, y = AbsInt(x), AbsInt(y) for y > 0 { x, y = y, x%y } return x } //Lcm func Lcm(vals ...int) (result int) { if len(vals) == 0 { return } result = vals[0] for i := 1; i < len(vals); i++ { result = lcm(result, vals[i]) } return } func lcm(x, y int) int { return x * y / gcd(x, y) }
C++
#include <bits/stdc++.h> using namespace std; using lint = long long; using pint = pair<int, int>; using plint = pair<lint, lint>; struct fast_ios { fast_ios(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_; #define ALL(x) (x).begin(), (x).end() #define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++) #define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--) #define REP(i, n) FOR(i,0,n) #define IREP(i, n) IFOR(i,0,n) template <typename T> void ndarray(vector<T> &vec, int len) { vec.resize(len); } template <typename T, typename... Args> void ndarray(vector<T> &vec, int len, Args... args) { vec.resize(len); for (auto &v : vec) ndarray(v, args...); } template <typename V, typename T> void ndfill(V &x, const T &val) { x = val; } template <typename V, typename T> void ndfill(vector<V> &vec, const T &val) { for (auto &v : vec) ndfill(v, val); } template <typename T> bool chmax(T &m, const T q) { if (m < q) {m = q; return true;} else return false; } template <typename T> bool chmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; } template <typename T1, typename T2> pair<T1, T2> operator+(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first + r.first, l.second + r.second); } template <typename T1, typename T2> pair<T1, T2> operator-(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first - r.first, l.second - r.second); } template <typename T> vector<T> srtunq(vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; } template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto &v : vec) is >> v; return is; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; } #if __cplusplus >= 201703L template <typename... T> istream &operator>>(istream &is, tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; } template <typename... T> ostream &operator<<(ostream &os, const tuple<T...> &tpl) { std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os; } #endif template <typename T> ostream &operator<<(ostream &os, const deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; } template <typename T> ostream &operator<<(ostream &os, const set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template <typename T> ostream &operator<<(ostream &os, const unordered_set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template <typename T> ostream &operator<<(ostream &os, const multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template <typename T> ostream &operator<<(ostream &os, const unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &pa) { os << '(' << pa.first << ',' << pa.second << ')'; return os; } template <typename TK, typename TV> ostream &operator<<(ostream &os, const map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; } template <typename TK, typename TV> ostream &operator<<(ostream &os, const unordered_map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; } #ifdef HITONANODE_LOCAL #define dbg(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ") " << __FILE__ << endl #else #define dbg(x) #endif // Directed graph library to find strongly connected components (強連結成分分解) // 0-indexed directed graph // Complexity: O(V + E) struct DirectedGraphSCC { int V; // # of Vertices std::vector<std::vector<int>> to, from; std::vector<int> used; // Only true/false std::vector<int> vs; std::vector<int> cmp; int scc_num = -1; DirectedGraphSCC(int V = 0) : V(V), to(V), from(V), cmp(V) {} void _dfs(int v) { used[v] = true; for (auto t : to[v]) if (!used[t]) _dfs(t); vs.push_back(v); } void _rdfs(int v, int k) { used[v] = true; cmp[v] = k; for (auto t : from[v]) if (!used[t]) _rdfs(t, k); } void add_edge(int from_, int to_) { assert(from_ >= 0 and from_ < V and to_ >= 0 and to_ < V); to[from_].push_back(to_); from[to_].push_back(from_); } // Detect strongly connected components and return # of them. // Also, assign each vertex `v` the scc id `cmp[v]` (0-indexed) int FindStronglyConnectedComponents() { used.assign(V, false); vs.clear(); for (int v = 0; v < V; v++) if (!used[v]) _dfs(v); used.assign(V, false); scc_num = 0; for (int i = (int)vs.size() - 1; i >= 0; i--) if (!used[vs[i]]) _rdfs(vs[i], scc_num++); return scc_num; } // Find and output the vertices that form a closed cycle. // output: {v_1, ..., v_C}, where C is the length of cycle, // {} if there's NO cycle (graph is DAG) std::vector<int> DetectCycle() { int ns = FindStronglyConnectedComponents(); if (ns == V) return {}; std::vector<int> cnt(ns); for (auto x : cmp) cnt[x]++; const int c = std::find_if(cnt.begin(), cnt.end(), [](int x) { return x > 1; }) - cnt.begin(); const int init = std::find(cmp.begin(), cmp.end(), c) - cmp.begin(); used.assign(V, false); std::vector<int> ret; auto dfs = [&](auto &&dfs, int now, bool b0) -> bool { if (now == init and b0) return true; for (auto nxt : to[now]) if (cmp[nxt] == c and !used[nxt]) { ret.emplace_back(nxt), used[nxt] = 1; if (dfs(dfs, nxt, true)) return true; ret.pop_back(); } return false; }; dfs(dfs, init, false); return ret; } // After calling `FindStronglyConnectedComponents()`, generate a new graph by uniting all vertices // belonging to the same component(The resultant graph is DAG). DirectedGraphSCC GenerateTopologicalGraph() { DirectedGraphSCC newgraph(scc_num); for (int s = 0; s < V; s++) for (auto t : to[s]) { if (cmp[s] != cmp[t]) newgraph.add_edge(cmp[s], cmp[t]); } return newgraph; } }; // 2-SAT solver: Find a solution for `(Ai v Aj) ^ (Ak v Al) ^ ... = true` // - `nb_sat_vars`: Number of variables // - Considering a graph with `2 * nb_sat_vars` vertices // - Vertices [0, nb_sat_vars) means `Ai` // - vertices [nb_sat_vars, 2 * nb_sat_vars) means `not Ai` struct SATSolver : DirectedGraphSCC { int nb_sat_vars; std::vector<int> solution; SATSolver(int nb_variables = 0) : DirectedGraphSCC(nb_variables * 2), nb_sat_vars(nb_variables), solution(nb_sat_vars) {} void add_x_or_y_constraint(bool is_x_true, int x, bool is_y_true, int y) { assert(x >= 0 and x < nb_sat_vars); assert(y >= 0 and y < nb_sat_vars); if (!is_x_true) x += nb_sat_vars; if (!is_y_true) y += nb_sat_vars; add_edge((x + nb_sat_vars) % (nb_sat_vars * 2), y); add_edge((y + nb_sat_vars) % (nb_sat_vars * 2), x); } // Solve the 2-SAT problem. If no solution exists, return `false`. // Otherwise, dump one solution to `solution` and return `true`. bool run() { FindStronglyConnectedComponents(); for (int i = 0; i < nb_sat_vars; i++) { if (cmp[i] == cmp[i + nb_sat_vars]) return false; solution[i] = cmp[i] > cmp[i + nb_sat_vars]; } return true; } }; int main() { int N, D; cin >> N >> D; vector<int> X(N), Y(N); REP(i, N) cin >> X[i] >> Y[i]; SATSolver solver(N); REP(i, N) REP(j, i) { int d00 = abs(X[i] - X[j]) >= D; int d01 = abs(X[i] - Y[j]) >= D; int d11 = abs(Y[i] - Y[j]) >= D; int d10 = abs(Y[i] - X[j]) >= D; if (!d00) solver.add_x_or_y_constraint(1, i, 1, j); if (!d01) solver.add_x_or_y_constraint(1, i, 0, j); if (!d11) solver.add_x_or_y_constraint(0, i, 0, j); if (!d10) solver.add_x_or_y_constraint(0, i, 1, j); } auto ret = solver.run(); if (!ret) puts("No"); else { cout << "Yes\n"; REP(i, N) cout << (solver.solution[i] ? Y[i] : X[i]) << '\n'; } }
Kotlin
@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE") //@file:OptIn(ExperimentalStdlibApi::class) import java.io.PrintWriter import kotlin.math.* import kotlin.random.Random import kotlin.collections.sort as _sort import kotlin.collections.sortDescending as _sortDescending import kotlin.io.println as iprintln /** @author Spheniscine */ fun main() { _writer.solve(); _writer.flush() } fun PrintWriter.solve() { // val startTime = System.nanoTime() val numCases = 1//readInt() case@ for(case in 1..numCases) { // print("Case #$case: ") val n = readInt() val d = readInt() val n2 = n+n val A = IntArray(n2) for(i in 0 until n) { val j = n2 + i.inv() A[i] = readInt() A[j] = readInt() } val S = TwoSat(n) for(i in 0 until n2) { for(j in i+1 until n2) { if(abs(A[i] - A[j]) < d) { S.or(i.inv(), j.inv()) } } } val ans = S.solve() if(ans == null) println("No") else { println("Yes") for(i in 0 until n) { println(if(ans[i]) A[i] else A[n2 + i.inv()]) } } } // iprintln("Time: ${(System.nanoTime() - startTime) / 1000000} ms") } class TwoSat(val n: Int) { private val n2 = n+n private val G = SCC(n2) private fun norm(i: Int) = i + (i shr 31 and n2) private fun imply(x: Int, y: Int) { G.addEdge(norm(x), norm(y)) } fun or(x: Int, y: Int) { // x or y must be true imply(x.inv(), y) imply(y.inv(), x) } fun set(x: Int) { // x must be true imply(x.inv(), x) } fun xor(x: Int, y: Int) { // exactly one of x, y is true or(x, y) or(x.inv(), y.inv()) } fun eq(x: Int, y: Int) { // both or none of x and y are true, x == y or(x, y.inv()) or(x.inv(), y) } fun solve(): BooleanArray? { val scc = G.scc() val pos = IntArray(n2) for(i in scc.indices) { for(u in scc[i]) { pos[u] = i } } return BooleanArray(n) { u -> val t = pos[u] val f = pos[n2 + u.inv()] if(t == f) return null f < t } } } class SCC(val n: Int) { val G = Array(n) { IntList() } fun addEdge(u: Int, v: Int) { G[u].add(v) } fun scc(): List<IntArray> { val res = mutableListOf<IntArray>() val S = IntList() val P = IntList() val depth = IntArray(n) val stack = IntList(n) { it } while(stack.isNotEmpty()) { val u = stack.pop() when { u < 0 -> { val d = depth[u.inv()] - 1 if(P.last() > d) { val comp = IntArray(S.size - d) { S[d+it] } res.add(comp) S.popToSize(d) P.pop() for(v in comp) depth[v] = -1 } } depth[u] > 0 -> { while(P.last() > depth[u]) P.pop() } depth[u] == 0 -> { S.add(u) P.add(S.size) depth[u] = S.size stack.add(u.inv()) for(v in G[u]) stack.add(v) } } } res.reverse() // output will have components topologically ordered relative to each other return res } } class IntList(initialCapacity: Int = 12) { private var _arr = IntArray(initialCapacity) private val capacity get() = _arr.size var size = 0 private set inline val lastIndex get() = size - 1 inline val indices get() = 0 until size constructor(copyFrom: IntArray): this(copyFrom.size) { copyFrom.copyInto(_arr); size = copyFrom.size } constructor(copyFrom: Collection<Int>): this(copyFrom.size) { _arr = copyFrom.toIntArray(); size = copyFrom.size } fun contentEquals(other: IntList): Boolean { return this === other || size == other.size && indices.all { this[it] == other[it] } } private fun grow(minCapacity: Int = 8) { val newCapacity = maxOf(minCapacity, capacity + (capacity shr 1)) _arr = _arr.copyOf(newCapacity) } fun ensureCapacity(minCapacity: Int) { if(capacity < minCapacity) grow(minCapacity) } operator fun get(index: Int): Int { require(index in 0 until size) return _arr[index] } operator fun set(index: Int, value: Int) { require(index in 0 until size) _arr[index] = value } fun add(value: Int) { if(size == capacity) grow() _arr[size++] = value } fun addAll(list: IntList) { ensureCapacity(size + list.size) list._arr.copyInto(_arr, size, 0, list.size) size += list.size } fun add(index: Int, element: Int) { if(size == capacity) grow() _arr.copyInto(_arr, index + 1, index, size) size++ set(index, element) } fun clear() { size = 0 } fun removeAt(index: Int): Int { val e = get(index) _arr.copyInto(_arr, index, index + 1, size) size-- return e } fun indexOf(e: Int): Int { for(i in 0 until size) if(this[i] == e) return i return -1 } fun remove(e: Int): Boolean { val i = indexOf(e) if(i == -1) return false removeAt(i) return true } operator fun iterator() = object: IntIterator() { private var pos = 0 override fun hasNext() = pos < size override fun nextInt() = get(pos++) } inline fun isEmpty() = size == 0 inline fun isNotEmpty() = size != 0 fun pop() = _arr[--size] fun popToSize(s: Int) { require(s >= 0) if(s < size) size = s } fun swap(i: Int, j: Int) { val t = this[i]; this[i] = this[j]; this[j] = t } fun reverse() { for(i in 0 until size / 2) swap(i, lastIndex - i) } fun shuffle(rnd: Random = random) { for(i in lastIndex downTo 1) swap(i, rnd.nextInt(i+1)) } fun sort() { shuffle(); _arr._sort(0, size) } fun sortDescending() { sort(); reverse() } fun joinToString(separator: CharSequence) = if(size == 0) "" else let { buildString { append(it[0]) for (i in 1 until size) { append(separator).append(it[i]) } } } override fun toString() = "[" + joinToString(", ") + "]" fun toIntArray() = _arr.copyOf(size) fun toList() = List(size, ::get) inline fun first() = get(0) inline fun last() = get(lastIndex) } inline fun IntList(size: Int, init: (Int) -> Int) = IntList(size).apply { for(i in 0 until size) { add(init(i)) } } inline fun IntArray.toIntList() = IntList(this) inline fun Collection<Int>.toIntList() = IntList(this) inline fun intListOf(vararg values: Int) = IntList(values) fun IntList.max() = (1 until size).fold(this[0]) { acc, i -> max(acc, this[i]) } fun IntList.min() = (1 until size).fold(this[0]) { acc, i -> min(acc, this[i]) } fun IntList.getOrNull(i: Int) = if(i in indices) get(i) else null inline fun IntList.count(predicate: (Int) -> Boolean) = indices.count { predicate(this[it]) } fun IntList.copyOf() = IntList(size, ::get) /** IO */ //@JvmField val INPUT = File("input.txt").inputStream() //@JvmField val OUTPUT = File("output.txt").outputStream() @JvmField val INPUT = System.`in` @JvmField val OUTPUT = System.out const val _BUFFER_SIZE = 1 shl 16 @JvmField val _buffer = ByteArray(_BUFFER_SIZE) @JvmField var _bufferPt = 0 @JvmField var _bytesRead = 0 tailrec fun readChar(): Char { if(_bufferPt == _bytesRead) { _bufferPt = 0 _bytesRead = INPUT.read(_buffer, 0, _BUFFER_SIZE) } return if(_bytesRead < 0) Char.MIN_VALUE else { val c = _buffer[_bufferPt++].toChar() if (c == '\r') readChar() else c } } fun readLine(): String? { var c = readChar() return if(c == Char.MIN_VALUE) null else buildString { while(c != '\n' && c != Char.MIN_VALUE) { append(c) c = readChar() } } } fun readLn() = readLine()!! fun read() = buildString { var c = readChar() while(c <= ' ') { if(c == Char.MIN_VALUE) return@buildString c = readChar() } do { append(c) c = readChar() } while(c > ' ') } fun readInt() = read().toInt() fun readDouble() = read().toDouble() fun readLong() = read().toLong() fun readStrings(n: Int) = List(n) { read() } fun readLines(n: Int) = List(n) { readLn() } fun readInts(n: Int) = List(n) { read().toInt() } fun readIntArray(n: Int) = IntArray(n) { read().toInt() } fun readDoubles(n: Int) = List(n) { read().toDouble() } fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() } fun readLongs(n: Int) = List(n) { read().toLong() } fun readLongArray(n: Int) = LongArray(n) { read().toLong() } @JvmField val _writer = PrintWriter(OUTPUT, false) /** shuffles and sort overrides to avoid quicksort attacks */ private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) { // Fisher-Yates shuffle algorithm for (i in size - 1 downTo 1) { val j = rnd.nextInt(i + 1) val temp = get(i) set(i, get(j)) set(j, temp) } } @JvmField var _random: Random? = null val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it } fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size) fun IntArray.sort() { shuffle(); _sort() } fun IntArray.sortDescending() { shuffle(); _sortDescending() } fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size) fun LongArray.sort() { shuffle(); _sort() } fun LongArray.sortDescending() { shuffle(); _sortDescending() } fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size) fun DoubleArray.sort() { shuffle(); _sort() } fun DoubleArray.sortDescending() { shuffle(); _sortDescending() } fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size) inline fun CharArray.sort() { _sort() } inline fun CharArray.sortDescending() { _sortDescending() } inline fun <T: Comparable<T>> Array<out T>.sort() = _sort() inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending() inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort() inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending() fun `please stop removing these imports IntelliJ`() { iprintln(max(1, 2)) } /** additional commons */ inline fun <T> Iterable<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) } inline fun <T> Sequence<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) } inline fun <T> Array<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) } fun IntArray.sumLong() = fold(0L, Long::plus)
Yes
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; using lint = long long; using pint = pair<int, int>; using plint = pair<lint, lint>; struct fast_ios { fast_ios(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_; #define ALL(x) (x).begin(), (x).end() #define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++) #define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--) #define REP(i, n) FOR(i,0,n) #define IREP(i, n) IFOR(i,0,n) template <typename T> void ndarray(vector<T> &vec, int len) { vec.resize(len); } template <typename T, typename... Args> void ndarray(vector<T> &vec, int len, Args... args) { vec.resize(len); for (auto &v : vec) ndarray(v, args...); } template <typename V, typename T> void ndfill(V &x, const T &val) { x = val; } template <typename V, typename T> void ndfill(vector<V> &vec, const T &val) { for (auto &v : vec) ndfill(v, val); } template <typename T> bool chmax(T &m, const T q) { if (m < q) {m = q; return true;} else return false; } template <typename T> bool chmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; } template <typename T1, typename T2> pair<T1, T2> operator+(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first + r.first, l.second + r.second); } template <typename T1, typename T2> pair<T1, T2> operator-(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first - r.first, l.second - r.second); } template <typename T> vector<T> srtunq(vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; } template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto &v : vec) is >> v; return is; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; } #if __cplusplus >= 201703L template <typename... T> istream &operator>>(istream &is, tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; } template <typename... T> ostream &operator<<(ostream &os, const tuple<T...> &tpl) { std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os; } #endif template <typename T> ostream &operator<<(ostream &os, const deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; } template <typename T> ostream &operator<<(ostream &os, const set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template <typename T> ostream &operator<<(ostream &os, const unordered_set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template <typename T> ostream &operator<<(ostream &os, const multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template <typename T> ostream &operator<<(ostream &os, const unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &pa) { os << '(' << pa.first << ',' << pa.second << ')'; return os; } template <typename TK, typename TV> ostream &operator<<(ostream &os, const map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; } template <typename TK, typename TV> ostream &operator<<(ostream &os, const unordered_map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; } #ifdef HITONANODE_LOCAL #define dbg(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ") " << __FILE__ << endl #else #define dbg(x) #endif // Directed graph library to find strongly connected components (強連結成分分解) // 0-indexed directed graph // Complexity: O(V + E) struct DirectedGraphSCC { int V; // # of Vertices std::vector<std::vector<int>> to, from; std::vector<int> used; // Only true/false std::vector<int> vs; std::vector<int> cmp; int scc_num = -1; DirectedGraphSCC(int V = 0) : V(V), to(V), from(V), cmp(V) {} void _dfs(int v) { used[v] = true; for (auto t : to[v]) if (!used[t]) _dfs(t); vs.push_back(v); } void _rdfs(int v, int k) { used[v] = true; cmp[v] = k; for (auto t : from[v]) if (!used[t]) _rdfs(t, k); } void add_edge(int from_, int to_) { assert(from_ >= 0 and from_ < V and to_ >= 0 and to_ < V); to[from_].push_back(to_); from[to_].push_back(from_); } // Detect strongly connected components and return # of them. // Also, assign each vertex `v` the scc id `cmp[v]` (0-indexed) int FindStronglyConnectedComponents() { used.assign(V, false); vs.clear(); for (int v = 0; v < V; v++) if (!used[v]) _dfs(v); used.assign(V, false); scc_num = 0; for (int i = (int)vs.size() - 1; i >= 0; i--) if (!used[vs[i]]) _rdfs(vs[i], scc_num++); return scc_num; } // Find and output the vertices that form a closed cycle. // output: {v_1, ..., v_C}, where C is the length of cycle, // {} if there's NO cycle (graph is DAG) std::vector<int> DetectCycle() { int ns = FindStronglyConnectedComponents(); if (ns == V) return {}; std::vector<int> cnt(ns); for (auto x : cmp) cnt[x]++; const int c = std::find_if(cnt.begin(), cnt.end(), [](int x) { return x > 1; }) - cnt.begin(); const int init = std::find(cmp.begin(), cmp.end(), c) - cmp.begin(); used.assign(V, false); std::vector<int> ret; auto dfs = [&](auto &&dfs, int now, bool b0) -> bool { if (now == init and b0) return true; for (auto nxt : to[now]) if (cmp[nxt] == c and !used[nxt]) { ret.emplace_back(nxt), used[nxt] = 1; if (dfs(dfs, nxt, true)) return true; ret.pop_back(); } return false; }; dfs(dfs, init, false); return ret; } // After calling `FindStronglyConnectedComponents()`, generate a new graph by uniting all vertices // belonging to the same component(The resultant graph is DAG). DirectedGraphSCC GenerateTopologicalGraph() { DirectedGraphSCC newgraph(scc_num); for (int s = 0; s < V; s++) for (auto t : to[s]) { if (cmp[s] != cmp[t]) newgraph.add_edge(cmp[s], cmp[t]); } return newgraph; } }; // 2-SAT solver: Find a solution for `(Ai v Aj) ^ (Ak v Al) ^ ... = true` // - `nb_sat_vars`: Number of variables // - Considering a graph with `2 * nb_sat_vars` vertices // - Vertices [0, nb_sat_vars) means `Ai` // - vertices [nb_sat_vars, 2 * nb_sat_vars) means `not Ai` struct SATSolver : DirectedGraphSCC { int nb_sat_vars; std::vector<int> solution; SATSolver(int nb_variables = 0) : DirectedGraphSCC(nb_variables * 2), nb_sat_vars(nb_variables), solution(nb_sat_vars) {} void add_x_or_y_constraint(bool is_x_true, int x, bool is_y_true, int y) { assert(x >= 0 and x < nb_sat_vars); assert(y >= 0 and y < nb_sat_vars); if (!is_x_true) x += nb_sat_vars; if (!is_y_true) y += nb_sat_vars; add_edge((x + nb_sat_vars) % (nb_sat_vars * 2), y); add_edge((y + nb_sat_vars) % (nb_sat_vars * 2), x); } // Solve the 2-SAT problem. If no solution exists, return `false`. // Otherwise, dump one solution to `solution` and return `true`. bool run() { FindStronglyConnectedComponents(); for (int i = 0; i < nb_sat_vars; i++) { if (cmp[i] == cmp[i + nb_sat_vars]) return false; solution[i] = cmp[i] > cmp[i + nb_sat_vars]; } return true; } }; int main() { int N, D; cin >> N >> D; vector<int> X(N), Y(N); REP(i, N) cin >> X[i] >> Y[i]; SATSolver solver(N); REP(i, N) REP(j, i) { int d00 = abs(X[i] - X[j]) >= D; int d01 = abs(X[i] - Y[j]) >= D; int d11 = abs(Y[i] - Y[j]) >= D; int d10 = abs(Y[i] - X[j]) >= D; if (!d00) solver.add_x_or_y_constraint(1, i, 1, j); if (!d01) solver.add_x_or_y_constraint(1, i, 0, j); if (!d11) solver.add_x_or_y_constraint(0, i, 0, j); if (!d10) solver.add_x_or_y_constraint(0, i, 1, j); } auto ret = solver.run(); if (!ret) puts("No"); else { cout << "Yes\n"; REP(i, N) cout << (solver.solution[i] ? Y[i] : X[i]) << '\n'; } } Code 2: @file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE") //@file:OptIn(ExperimentalStdlibApi::class) import java.io.PrintWriter import kotlin.math.* import kotlin.random.Random import kotlin.collections.sort as _sort import kotlin.collections.sortDescending as _sortDescending import kotlin.io.println as iprintln /** @author Spheniscine */ fun main() { _writer.solve(); _writer.flush() } fun PrintWriter.solve() { // val startTime = System.nanoTime() val numCases = 1//readInt() case@ for(case in 1..numCases) { // print("Case #$case: ") val n = readInt() val d = readInt() val n2 = n+n val A = IntArray(n2) for(i in 0 until n) { val j = n2 + i.inv() A[i] = readInt() A[j] = readInt() } val S = TwoSat(n) for(i in 0 until n2) { for(j in i+1 until n2) { if(abs(A[i] - A[j]) < d) { S.or(i.inv(), j.inv()) } } } val ans = S.solve() if(ans == null) println("No") else { println("Yes") for(i in 0 until n) { println(if(ans[i]) A[i] else A[n2 + i.inv()]) } } } // iprintln("Time: ${(System.nanoTime() - startTime) / 1000000} ms") } class TwoSat(val n: Int) { private val n2 = n+n private val G = SCC(n2) private fun norm(i: Int) = i + (i shr 31 and n2) private fun imply(x: Int, y: Int) { G.addEdge(norm(x), norm(y)) } fun or(x: Int, y: Int) { // x or y must be true imply(x.inv(), y) imply(y.inv(), x) } fun set(x: Int) { // x must be true imply(x.inv(), x) } fun xor(x: Int, y: Int) { // exactly one of x, y is true or(x, y) or(x.inv(), y.inv()) } fun eq(x: Int, y: Int) { // both or none of x and y are true, x == y or(x, y.inv()) or(x.inv(), y) } fun solve(): BooleanArray? { val scc = G.scc() val pos = IntArray(n2) for(i in scc.indices) { for(u in scc[i]) { pos[u] = i } } return BooleanArray(n) { u -> val t = pos[u] val f = pos[n2 + u.inv()] if(t == f) return null f < t } } } class SCC(val n: Int) { val G = Array(n) { IntList() } fun addEdge(u: Int, v: Int) { G[u].add(v) } fun scc(): List<IntArray> { val res = mutableListOf<IntArray>() val S = IntList() val P = IntList() val depth = IntArray(n) val stack = IntList(n) { it } while(stack.isNotEmpty()) { val u = stack.pop() when { u < 0 -> { val d = depth[u.inv()] - 1 if(P.last() > d) { val comp = IntArray(S.size - d) { S[d+it] } res.add(comp) S.popToSize(d) P.pop() for(v in comp) depth[v] = -1 } } depth[u] > 0 -> { while(P.last() > depth[u]) P.pop() } depth[u] == 0 -> { S.add(u) P.add(S.size) depth[u] = S.size stack.add(u.inv()) for(v in G[u]) stack.add(v) } } } res.reverse() // output will have components topologically ordered relative to each other return res } } class IntList(initialCapacity: Int = 12) { private var _arr = IntArray(initialCapacity) private val capacity get() = _arr.size var size = 0 private set inline val lastIndex get() = size - 1 inline val indices get() = 0 until size constructor(copyFrom: IntArray): this(copyFrom.size) { copyFrom.copyInto(_arr); size = copyFrom.size } constructor(copyFrom: Collection<Int>): this(copyFrom.size) { _arr = copyFrom.toIntArray(); size = copyFrom.size } fun contentEquals(other: IntList): Boolean { return this === other || size == other.size && indices.all { this[it] == other[it] } } private fun grow(minCapacity: Int = 8) { val newCapacity = maxOf(minCapacity, capacity + (capacity shr 1)) _arr = _arr.copyOf(newCapacity) } fun ensureCapacity(minCapacity: Int) { if(capacity < minCapacity) grow(minCapacity) } operator fun get(index: Int): Int { require(index in 0 until size) return _arr[index] } operator fun set(index: Int, value: Int) { require(index in 0 until size) _arr[index] = value } fun add(value: Int) { if(size == capacity) grow() _arr[size++] = value } fun addAll(list: IntList) { ensureCapacity(size + list.size) list._arr.copyInto(_arr, size, 0, list.size) size += list.size } fun add(index: Int, element: Int) { if(size == capacity) grow() _arr.copyInto(_arr, index + 1, index, size) size++ set(index, element) } fun clear() { size = 0 } fun removeAt(index: Int): Int { val e = get(index) _arr.copyInto(_arr, index, index + 1, size) size-- return e } fun indexOf(e: Int): Int { for(i in 0 until size) if(this[i] == e) return i return -1 } fun remove(e: Int): Boolean { val i = indexOf(e) if(i == -1) return false removeAt(i) return true } operator fun iterator() = object: IntIterator() { private var pos = 0 override fun hasNext() = pos < size override fun nextInt() = get(pos++) } inline fun isEmpty() = size == 0 inline fun isNotEmpty() = size != 0 fun pop() = _arr[--size] fun popToSize(s: Int) { require(s >= 0) if(s < size) size = s } fun swap(i: Int, j: Int) { val t = this[i]; this[i] = this[j]; this[j] = t } fun reverse() { for(i in 0 until size / 2) swap(i, lastIndex - i) } fun shuffle(rnd: Random = random) { for(i in lastIndex downTo 1) swap(i, rnd.nextInt(i+1)) } fun sort() { shuffle(); _arr._sort(0, size) } fun sortDescending() { sort(); reverse() } fun joinToString(separator: CharSequence) = if(size == 0) "" else let { buildString { append(it[0]) for (i in 1 until size) { append(separator).append(it[i]) } } } override fun toString() = "[" + joinToString(", ") + "]" fun toIntArray() = _arr.copyOf(size) fun toList() = List(size, ::get) inline fun first() = get(0) inline fun last() = get(lastIndex) } inline fun IntList(size: Int, init: (Int) -> Int) = IntList(size).apply { for(i in 0 until size) { add(init(i)) } } inline fun IntArray.toIntList() = IntList(this) inline fun Collection<Int>.toIntList() = IntList(this) inline fun intListOf(vararg values: Int) = IntList(values) fun IntList.max() = (1 until size).fold(this[0]) { acc, i -> max(acc, this[i]) } fun IntList.min() = (1 until size).fold(this[0]) { acc, i -> min(acc, this[i]) } fun IntList.getOrNull(i: Int) = if(i in indices) get(i) else null inline fun IntList.count(predicate: (Int) -> Boolean) = indices.count { predicate(this[it]) } fun IntList.copyOf() = IntList(size, ::get) /** IO */ //@JvmField val INPUT = File("input.txt").inputStream() //@JvmField val OUTPUT = File("output.txt").outputStream() @JvmField val INPUT = System.`in` @JvmField val OUTPUT = System.out const val _BUFFER_SIZE = 1 shl 16 @JvmField val _buffer = ByteArray(_BUFFER_SIZE) @JvmField var _bufferPt = 0 @JvmField var _bytesRead = 0 tailrec fun readChar(): Char { if(_bufferPt == _bytesRead) { _bufferPt = 0 _bytesRead = INPUT.read(_buffer, 0, _BUFFER_SIZE) } return if(_bytesRead < 0) Char.MIN_VALUE else { val c = _buffer[_bufferPt++].toChar() if (c == '\r') readChar() else c } } fun readLine(): String? { var c = readChar() return if(c == Char.MIN_VALUE) null else buildString { while(c != '\n' && c != Char.MIN_VALUE) { append(c) c = readChar() } } } fun readLn() = readLine()!! fun read() = buildString { var c = readChar() while(c <= ' ') { if(c == Char.MIN_VALUE) return@buildString c = readChar() } do { append(c) c = readChar() } while(c > ' ') } fun readInt() = read().toInt() fun readDouble() = read().toDouble() fun readLong() = read().toLong() fun readStrings(n: Int) = List(n) { read() } fun readLines(n: Int) = List(n) { readLn() } fun readInts(n: Int) = List(n) { read().toInt() } fun readIntArray(n: Int) = IntArray(n) { read().toInt() } fun readDoubles(n: Int) = List(n) { read().toDouble() } fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() } fun readLongs(n: Int) = List(n) { read().toLong() } fun readLongArray(n: Int) = LongArray(n) { read().toLong() } @JvmField val _writer = PrintWriter(OUTPUT, false) /** shuffles and sort overrides to avoid quicksort attacks */ private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) { // Fisher-Yates shuffle algorithm for (i in size - 1 downTo 1) { val j = rnd.nextInt(i + 1) val temp = get(i) set(i, get(j)) set(j, temp) } } @JvmField var _random: Random? = null val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it } fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size) fun IntArray.sort() { shuffle(); _sort() } fun IntArray.sortDescending() { shuffle(); _sortDescending() } fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size) fun LongArray.sort() { shuffle(); _sort() } fun LongArray.sortDescending() { shuffle(); _sortDescending() } fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size) fun DoubleArray.sort() { shuffle(); _sort() } fun DoubleArray.sortDescending() { shuffle(); _sortDescending() } fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size) inline fun CharArray.sort() { _sort() } inline fun CharArray.sortDescending() { _sortDescending() } inline fun <T: Comparable<T>> Array<out T>.sort() = _sort() inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending() inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort() inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending() fun `please stop removing these imports IntelliJ`() { iprintln(max(1, 2)) } /** additional commons */ inline fun <T> Iterable<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) } inline fun <T> Sequence<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) } inline fun <T> Array<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) } fun IntArray.sumLong() = fold(0L, Long::plus)
C++
#include <bits/stdc++.h> #define fi first #define se second #define rep(i,n) for(int i = 0; i < (n); ++i) #define drep(i,n) for(int i = (n)-1; i >= 0; --i) #define srep(i,s,t) for (int i = s; i < t; ++i) #define rng(a) a.begin(),a.end() #define sz(x) (int)(x).size() #define uni(x) x.erase(unique(rng(x)),x.end()) #define show(x) cout<<#x<<" = "<<x<<endl; #define PQ(T) priority_queue<T,v(T),greater<T> > #define newline puts("") #define v(T) vector<T> #define vv(T) v(v(T)) using namespace std; typedef long long int ll; typedef pair<int,int> P; typedef set<int> S; typedef queue<int> Q; typedef queue<P> QP; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vl; typedef vector<P> vp; const ll LINF = 1001002003004005006ll; const int INF = 1001001001; const int MOD = 1000000007; vector<pair<ll, int>> Pfact(ll num) { vector<pair<ll, int>> res; for (ll i = 2; i * i <= num; i++) { int cnt = 0; while (num % i == 0) { cnt++; num /= i; } if (cnt) res.emplace_back(i, cnt); } if (num != 1) res.emplace_back(make_pair(num, 1)); return res; } class Combi { private: v(ll) fac, inv, finv; void init(int N) { fac[0] = fac[1] = 1; inv[1] = 1; finv[0] = finv[1] = 1; for (int i = 2; i < N; i++) { fac[i] = fac[i - 1] * i % MOD; inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD; finv[i] = finv[i - 1] * inv[i] % MOD; } } public: Combi(int N) : fac(N + 1), inv(N + 1), finv(N + 1) { init(N + 1); } ll Cmod(int n, int k) { if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD; } ll Pmod(int n, int k) { if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * finv[n - k] % MOD; } }; int main() { int N,M; cin >> N >> M; vector<pair<ll, int>> f = Pfact(M); Combi C = Combi(1000000); ll ans = 1; rep(i,sz(f)) { int num = f[i].second; ans *= C.Cmod(N+num-1,num); ans %= MOD; } cout << ans << endl; return 0; }
C
#include<stdio.h> int main(void) { int a,b; scanf("%d %d",&a,&b); if(b%a==0){ printf("%d\n",a+b); } else{ printf("%d\n",b-a); } return 0; }
No
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> #define fi first #define se second #define rep(i,n) for(int i = 0; i < (n); ++i) #define drep(i,n) for(int i = (n)-1; i >= 0; --i) #define srep(i,s,t) for (int i = s; i < t; ++i) #define rng(a) a.begin(),a.end() #define sz(x) (int)(x).size() #define uni(x) x.erase(unique(rng(x)),x.end()) #define show(x) cout<<#x<<" = "<<x<<endl; #define PQ(T) priority_queue<T,v(T),greater<T> > #define newline puts("") #define v(T) vector<T> #define vv(T) v(v(T)) using namespace std; typedef long long int ll; typedef pair<int,int> P; typedef set<int> S; typedef queue<int> Q; typedef queue<P> QP; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vl; typedef vector<P> vp; const ll LINF = 1001002003004005006ll; const int INF = 1001001001; const int MOD = 1000000007; vector<pair<ll, int>> Pfact(ll num) { vector<pair<ll, int>> res; for (ll i = 2; i * i <= num; i++) { int cnt = 0; while (num % i == 0) { cnt++; num /= i; } if (cnt) res.emplace_back(i, cnt); } if (num != 1) res.emplace_back(make_pair(num, 1)); return res; } class Combi { private: v(ll) fac, inv, finv; void init(int N) { fac[0] = fac[1] = 1; inv[1] = 1; finv[0] = finv[1] = 1; for (int i = 2; i < N; i++) { fac[i] = fac[i - 1] * i % MOD; inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD; finv[i] = finv[i - 1] * inv[i] % MOD; } } public: Combi(int N) : fac(N + 1), inv(N + 1), finv(N + 1) { init(N + 1); } ll Cmod(int n, int k) { if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD; } ll Pmod(int n, int k) { if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * finv[n - k] % MOD; } }; int main() { int N,M; cin >> N >> M; vector<pair<ll, int>> f = Pfact(M); Combi C = Combi(1000000); ll ans = 1; rep(i,sz(f)) { int num = f[i].second; ans *= C.Cmod(N+num-1,num); ans %= MOD; } cout << ans << endl; return 0; } Code 2: #include<stdio.h> int main(void) { int a,b; scanf("%d %d",&a,&b); if(b%a==0){ printf("%d\n",a+b); } else{ printf("%d\n",b-a); } return 0; }
Java
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main implements Runnable { private void solve() throws IOException { int R = nextInt(); int C = nextInt(); for(int r = 0; r < R; ++r) { String s = reader.readLine(); writer.println(s); writer.println(s); } } public static void main(String[] args) { new Main().run(); } BufferedReader reader; // BufferedReader reader2; StringTokenizer tokenizer; PrintWriter writer; // BufferedWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); // reader = new BufferedReader(new FileReader("trees.in")); // reader2 = new BufferedReader(new FileReader("1.in")); tokenizer = null; writer = new PrintWriter(System.out); // writer = new PrintWriter("trees.out"); // writer = new BufferedWriter(System.out); // writer = new BufferedWriter(new OutputStreamWriter(System.out)); solve(); reader.close(); // reader2.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } short nextShort() throws IOException { return Short.parseShort(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Kotlin
fun main(args : Array<String> ) { val (h, w) = readLine()!!.split(" ").map { x -> x.toInt() } val strs = (1..h).map { val s = readLine()!! s } strs.zip(strs).map{ x -> x.toList() }.flatten() .map{ x -> println(x) } }
Yes
Do these codes solve the same problem? Code 1: import java.io.*; import java.math.BigInteger; import java.util.*; public class Main implements Runnable { private void solve() throws IOException { int R = nextInt(); int C = nextInt(); for(int r = 0; r < R; ++r) { String s = reader.readLine(); writer.println(s); writer.println(s); } } public static void main(String[] args) { new Main().run(); } BufferedReader reader; // BufferedReader reader2; StringTokenizer tokenizer; PrintWriter writer; // BufferedWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); // reader = new BufferedReader(new FileReader("trees.in")); // reader2 = new BufferedReader(new FileReader("1.in")); tokenizer = null; writer = new PrintWriter(System.out); // writer = new PrintWriter("trees.out"); // writer = new BufferedWriter(System.out); // writer = new BufferedWriter(new OutputStreamWriter(System.out)); solve(); reader.close(); // reader2.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } short nextShort() throws IOException { return Short.parseShort(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } } Code 2: fun main(args : Array<String> ) { val (h, w) = readLine()!!.split(" ").map { x -> x.toInt() } val strs = (1..h).map { val s = readLine()!! s } strs.zip(strs).map{ x -> x.toList() }.flatten() .map{ x -> println(x) } }
Python
a, b, x = map(int, input().split()) fb = b//x + 1 if a == 0: fam = 0 else: fam = (a-1)//x + 1 print(fb-fam)
C++
#include<iostream> using namespace std; int main(){ int n; long long int T, t[200009], ans=0; cin >> n >> T; for(int i=0;i<n;i++)cin >> t[i]; for(int i=0;i<n-1;i++){ ans+=min(T, t[i+1]-t[i]); } cout << ans+T << endl; }
No
Do these codes solve the same problem? Code 1: a, b, x = map(int, input().split()) fb = b//x + 1 if a == 0: fam = 0 else: fam = (a-1)//x + 1 print(fb-fam) Code 2: #include<iostream> using namespace std; int main(){ int n; long long int T, t[200009], ans=0; cin >> n >> T; for(int i=0;i<n;i++)cin >> t[i]; for(int i=0;i<n-1;i++){ ans+=min(T, t[i+1]-t[i]); } cout << ans+T << endl; }
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] s = sc.next().toCharArray(); int min = Integer.MAX_VALUE; int x; for(int i=0;i+2<s.length;i++){ x = 100*(s[i]-'0')+10*(s[i+1]-'0')+s[i+2]-'0'; min = Math.min(Math.abs(x-753),min); } System.out.println(min); } }
C++
/*input 141421 356237 */ // Nihesh Anderson - knandy #include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; typedef long long ll; typedef long double ld; typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set; // find_by_order, order_of_key ll MOD=1000000007; #define endl '\n' #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #define pb push_back ll INF = 2000000000000000001; long double EPS = 1e-9; ll power(ll a, ll n, ll md){if(n==0){return 1;}else{ll res=power(a,n/2,md);res=(res*res)%md;if(n%2!=0){res=(res*a)%md;}return res;}} random_device rndm; mt19937 grndm(rndm()); void mix(ll* a, ll* b){shuffle(a,b,grndm);} const ll MX = 1000005; ll ifact[MX], fact[MX]; ll choose(ll n, ll r) { return fact[n] * ifact[r] % MOD * ifact[n - r] % MOD; } int main(){ fast_cin(); // freopen("input.in","r",stdin); // freopen("output.out","w",stdout); ll n, m; cin >> n >> m; fact[0] = 1; for(ll i = 1; i < MX; i++) { fact[i] = (i * fact[i - 1]) % MOD; } for(ll i = 0; i < MX; i++) { ifact[i] = power(fact[i], MOD - 2, MOD); } ll run = 1, ans = 0; for(ll i = n; i >= 0; i--) { if(i & 1) { ans = (ans + MOD - choose(n, i) * run % MOD) % MOD; } else ans = (ans + choose(n, i) * run % MOD) % MOD; if(i > 0) run = run * (m - (i - 1)) % MOD; } cout << run * ans % MOD; return 0; }
No
Do these codes solve the same problem? Code 1: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] s = sc.next().toCharArray(); int min = Integer.MAX_VALUE; int x; for(int i=0;i+2<s.length;i++){ x = 100*(s[i]-'0')+10*(s[i+1]-'0')+s[i+2]-'0'; min = Math.min(Math.abs(x-753),min); } System.out.println(min); } } Code 2: /*input 141421 356237 */ // Nihesh Anderson - knandy #include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; typedef long long ll; typedef long double ld; typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set; // find_by_order, order_of_key ll MOD=1000000007; #define endl '\n' #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #define pb push_back ll INF = 2000000000000000001; long double EPS = 1e-9; ll power(ll a, ll n, ll md){if(n==0){return 1;}else{ll res=power(a,n/2,md);res=(res*res)%md;if(n%2!=0){res=(res*a)%md;}return res;}} random_device rndm; mt19937 grndm(rndm()); void mix(ll* a, ll* b){shuffle(a,b,grndm);} const ll MX = 1000005; ll ifact[MX], fact[MX]; ll choose(ll n, ll r) { return fact[n] * ifact[r] % MOD * ifact[n - r] % MOD; } int main(){ fast_cin(); // freopen("input.in","r",stdin); // freopen("output.out","w",stdout); ll n, m; cin >> n >> m; fact[0] = 1; for(ll i = 1; i < MX; i++) { fact[i] = (i * fact[i - 1]) % MOD; } for(ll i = 0; i < MX; i++) { ifact[i] = power(fact[i], MOD - 2, MOD); } ll run = 1, ans = 0; for(ll i = n; i >= 0; i--) { if(i & 1) { ans = (ans + MOD - choose(n, i) * run % MOD) % MOD; } else ans = (ans + choose(n, i) * run % MOD) % MOD; if(i > 0) run = run * (m - (i - 1)) % MOD; } cout << run * ans % MOD; return 0; }
Java
import java.io.*; import java.util.*; class Solver { final int h, w, k; final char[][] sm; Solver(int h, int w, int k, char[][] sm) { this.h = h; this.w = w; this.k = k; this.sm = sm; } private List<Integer> getCounts(int bitset, int j) { List<Integer> counts = new ArrayList<>(); int count = 0; for (int i = 0; i < h; i++) { if (sm[i][j] == '1') { count++; } if (((bitset >> i) & 1) == 1) { counts.add(count); count = 0; } } counts.add(count); return counts; } private int solve(int bitset) { List<Integer> counts = new ArrayList<>(); for (int i = 0; i < Integer.bitCount(bitset) + 1; i++) { counts.add(0); } int answer = Integer.bitCount(bitset); for (int j = 0; j < w; j++) { List<Integer> nextCounts = getCounts(bitset, j); for (int c : nextCounts) { if (c > k) { return Integer.MAX_VALUE; } } for (int i = 0; i < counts.size(); i++) { int nextCount = counts.get(i) + nextCounts.get(i); if (nextCount > k) { answer++; counts = nextCounts; break; } counts.set(i, nextCount); } } return answer; } public int solve() { int answer = Integer.MAX_VALUE; for (int bitset = 0; bitset < (1 << (h - 1)); bitset++) { answer = Math.min(answer, solve(bitset)); } return answer; } } public class Main { private static void execute(ContestReader reader, ContestWriter out) { int h = reader.nextInt(); int w = reader.nextInt(); int k = reader.nextInt(); char[][] sm = reader.nextCharArray(h); out.println(new Solver(h, w, k, sm).solve()); } public static void main(String[] args) { ContestReader reader = new ContestReader(System.in); ContestWriter out = new ContestWriter(System.out); execute(reader, out); out.flush(); } } class ContestWriter extends PrintWriter { ContestWriter(PrintStream printeStream) { super(printeStream); } public void print(List list) { for (Object object : list) { println(object); } } public void printOneLine(List list) { if (!list.isEmpty()) { print(list.get(0)); for (int i = 1; i < list.size(); i++) { print(" "); print(list.get(i)); } } println(); } } class ContestReader { private static final int BUFFER_SIZE = 1024; private final InputStream stream; private final byte[] buffer; private int pointer; private int bufferLength; ContestReader(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.pointer = 0; this.bufferLength = 0; } private boolean hasNextByte() { if (pointer < bufferLength) { return true; } pointer = 0; try { bufferLength = stream.read(buffer); } catch (IOException e) { throw new RuntimeException(e); } return bufferLength > 0; } private int readByte() { if (hasNextByte()) { return buffer[pointer++]; } else { return -1; } } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[pointer])) { pointer++; } return hasNextByte(); } public String next() { if (!hasNext()) { throw new NoSuchElementException(); } StringBuilder sb = new StringBuilder(); while(true) { int b = readByte(); if (!isPrintableChar(b)) { break; } sb.appendCodePoint(b); } return sb.toString(); } public String nextLine() { if (!hasNext()) { throw new NoSuchElementException(); } StringBuilder sb = new StringBuilder(); while(true) { int b = readByte(); if (!isPrintableChar(b) && b != 0x20) { break; } sb.appendCodePoint(b); } return sb.toString(); } public char nextChar() { return next().charAt(0); } public int nextInt() { if (!hasNext()) { throw new NoSuchElementException(); } int n = 0; boolean minus = false; { int b = readByte(); if (b == '-') { minus = true; } else if ('0' <= b && b <= '9') { n = b - '0'; } else { throw new NumberFormatException(); } } while(true){ int b = readByte(); if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } } } public long nextLong() { if (!hasNext()) { throw new NoSuchElementException(); } long n = 0; boolean minus = false; { int b = readByte(); if (b == '-') { minus = true; } else if ('0' <= b && b <= '9') { n = b - '0'; } else { throw new NumberFormatException(); } } while(true){ int b = readByte(); if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } } } public double nextDouble() { return Double.parseDouble(next()); } public String[] next(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = next(); } return array; } public String[] nextLine(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = nextLine(); } return array; } public char[] nextChar(int n) { char[] array = new char[n]; for (int i = 0; i < n; i++) { array[i] = nextChar(); } return array; } public int[] nextInt(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } public long[] nextLong(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } public double[] nextDouble(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } public char[] nextCharArray() { return next().toCharArray(); } public String[][] next(int n, int m) { String[][] matrix = new String[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = next(); } } return matrix; } public int[][] nextInt(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextInt(); } } return matrix; } public char[][] nextChar(int n, int m) { char[][] matrix = new char[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextChar(); } } return matrix; } public long[][] nextLong(int n, int m) { long[][] matrix = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextLong(); } } return matrix; } public double[][] nextDouble(int n, int m) { double[][] matrix = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextDouble(); } } return matrix; } public char[][] nextCharArray(int n) { char[][] matrix = new char[n][]; for (int i = 0; i < n; i++) { matrix[i] = next().toCharArray(); } return matrix; } }
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Threading; using System.Text; using System.Text.RegularExpressions; using System.Diagnostics; using static util; using P = pair<int, int>; class Program { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; var solver = new Solver(sw); // var t = new Thread(solver.solve, 1 << 26); // 64 MB // t.Start(); // t.Join(); solver.solve(); sw.Flush(); } } class Solver { StreamWriter sw; Scan sc; void Prt(string a) => sw.WriteLine(a); void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a)); void Prt(params object[] a) => Prt(string.Join(" ", a)); public Solver(StreamWriter sw) { this.sw = sw; this.sc = new Scan(); } public void solve() { int h, w, k; sc.Multi(out h, out w, out k); var s = new string[h]; for (int i = 0; i < h; i++) { s[i] = sc.Str; } int ans = M; for (int i = 0; i < (1 << h - 1); i++) { int c = 0; var lis = new List<int>(); lis.Add(0); for (int j = 0; j < h - 1; j++) { if (((i >> j) & 1) == 1) { ++c; lis.Add(j + 1); } } lis.Add(h); int n = c + 1; var cnt = new int[n]; for (int j = 0; j < w; j++) { bool ok = true; var cc = new int[n]; for (int l = 0; l < n; l++) { for (int m = lis[l]; m < lis[l + 1]; m++) { if (s[m][j] == '1') ++cc[l]; } if (cc[l] > k) { goto A; } if (cnt[l] + cc[l] > k) { ok = false; } } if (!ok) { ++c; cnt = new int[n]; } for (int l = 0; l < n; l++) { cnt[l] += cc[l]; } } ans = Math.Min(ans, c); A: continue; } Prt(ans); } } class pair<T, U> : IComparable<pair<T, U>> { public T v1; public U v2; public pair() : this(default(T), default(U)) {} public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; } public int CompareTo(pair<T, U> a) { int c = Comparer<T>.Default.Compare(v1, a.v1); return c != 0 ? c : Comparer<U>.Default.Compare(v2, a.v2); } public override string ToString() => v1 + " " + v2; public void Deconstruct(out T a, out U b) { a = v1; b = v2; } } static class util { // public static readonly int M = 1000000007; public static readonly int M = 998244353; public static readonly long LM = 1L << 60; public static readonly double eps = 1e-11; public static void DBG(string a) => Console.Error.WriteLine(a); public static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a)); public static void DBG(params object[] a) => DBG(string.Join(" ", a)); public static void Assert(params bool[] conds) { foreach (var cond in conds) if (!cond) throw new Exception(); } public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2); public static int CompareList<T>(IList<T> a, IList<T> b) where T : IComparable<T> { for (int i = 0; i < a.Count && i < b.Count; i++) if (a[i].CompareTo(b[i]) != 0) return a[i].CompareTo(b[i]); return a.Count.CompareTo(b.Count); } public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w; static readonly int[] dd = { 0, 1, 0, -1 }; // static readonly string dstring = "RDLU"; public static P[] adjacents(int i, int j) => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).ToArray(); public static P[] adjacents(int i, int j, int h, int w) => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])) .Where(p => inside(p.v1, p.v2, h, w)).ToArray(); public static P[] adjacents(this P p) => adjacents(p.v1, p.v2); public static P[] adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w); public static Dictionary<T, int> compress<T>(this IEnumerable<T> a) => a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i); public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.Aggregate(Enumerable.Union)); public static T[] inv<T>(this Dictionary<T, int> dic) { var res = new T[dic.Count]; foreach (var item in dic) res[item.Value] = item.Key; return res; } public static void swap<T>(ref T a, ref T b) where T : struct { var t = a; a = b; b = t; } public static void swap<T>(this IList<T> a, int i, int j) where T : struct { var t = a[i]; a[i] = a[j]; a[j] = t; } public static T[] copy<T>(this IList<T> a) { var ret = new T[a.Count]; for (int i = 0; i < a.Count; i++) ret[i] = a[i]; return ret; } public static void Deconstruct<T>(this IList<T> v, out T a) { a = v[0]; } public static void Deconstruct<T>(this IList<T> v, out T a, out T b) { a = v[0]; b = v[1]; } public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c) { a = v[0]; b = v[1]; c = v[2]; } public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c, out T d) { a = v[0]; b = v[1]; c = v[2]; d = v[3]; } public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c, out T d, out T e) { a = v[0]; b = v[1]; c = v[2]; d = v[3]; e = v[4]; } } class Scan { StreamReader sr; public Scan() { sr = new StreamReader(Console.OpenStandardInput()); } public Scan(string path) { sr = new StreamReader(path); } public int Int => int.Parse(Str); public long Long => long.Parse(Str); public double Double => double.Parse(Str); public string Str => sr.ReadLine().Trim(); public pair<T, U> Pair<T, U>() { T a; U b; Multi(out a, out b); return new pair<T, U>(a, b); } public P P => Pair<int, int>(); public int[] IntArr => StrArr.Select(int.Parse).ToArray(); public long[] LongArr => StrArr.Select(long.Parse).ToArray(); public double[] DoubleArr => StrArr.Select(double.Parse).ToArray(); public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries); bool eq<T, U>() => typeof(T).Equals(typeof(U)); T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T)); T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s)) : eq<T, long>() ? ct<T, long>(long.Parse(s)) : eq<T, double>() ? ct<T, double>(double.Parse(s)) : eq<T, char>() ? ct<T, char>(s[0]) : ct<T, string>(s); public void Multi<T>(out T a) => a = cv<T>(Str); public void Multi<T, U>(out T a, out U b) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); } public void Multi<T, U, V>(out T a, out U b, out V c) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); } public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); } public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); } }
Yes
Do these codes solve the same problem? Code 1: import java.io.*; import java.util.*; class Solver { final int h, w, k; final char[][] sm; Solver(int h, int w, int k, char[][] sm) { this.h = h; this.w = w; this.k = k; this.sm = sm; } private List<Integer> getCounts(int bitset, int j) { List<Integer> counts = new ArrayList<>(); int count = 0; for (int i = 0; i < h; i++) { if (sm[i][j] == '1') { count++; } if (((bitset >> i) & 1) == 1) { counts.add(count); count = 0; } } counts.add(count); return counts; } private int solve(int bitset) { List<Integer> counts = new ArrayList<>(); for (int i = 0; i < Integer.bitCount(bitset) + 1; i++) { counts.add(0); } int answer = Integer.bitCount(bitset); for (int j = 0; j < w; j++) { List<Integer> nextCounts = getCounts(bitset, j); for (int c : nextCounts) { if (c > k) { return Integer.MAX_VALUE; } } for (int i = 0; i < counts.size(); i++) { int nextCount = counts.get(i) + nextCounts.get(i); if (nextCount > k) { answer++; counts = nextCounts; break; } counts.set(i, nextCount); } } return answer; } public int solve() { int answer = Integer.MAX_VALUE; for (int bitset = 0; bitset < (1 << (h - 1)); bitset++) { answer = Math.min(answer, solve(bitset)); } return answer; } } public class Main { private static void execute(ContestReader reader, ContestWriter out) { int h = reader.nextInt(); int w = reader.nextInt(); int k = reader.nextInt(); char[][] sm = reader.nextCharArray(h); out.println(new Solver(h, w, k, sm).solve()); } public static void main(String[] args) { ContestReader reader = new ContestReader(System.in); ContestWriter out = new ContestWriter(System.out); execute(reader, out); out.flush(); } } class ContestWriter extends PrintWriter { ContestWriter(PrintStream printeStream) { super(printeStream); } public void print(List list) { for (Object object : list) { println(object); } } public void printOneLine(List list) { if (!list.isEmpty()) { print(list.get(0)); for (int i = 1; i < list.size(); i++) { print(" "); print(list.get(i)); } } println(); } } class ContestReader { private static final int BUFFER_SIZE = 1024; private final InputStream stream; private final byte[] buffer; private int pointer; private int bufferLength; ContestReader(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.pointer = 0; this.bufferLength = 0; } private boolean hasNextByte() { if (pointer < bufferLength) { return true; } pointer = 0; try { bufferLength = stream.read(buffer); } catch (IOException e) { throw new RuntimeException(e); } return bufferLength > 0; } private int readByte() { if (hasNextByte()) { return buffer[pointer++]; } else { return -1; } } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[pointer])) { pointer++; } return hasNextByte(); } public String next() { if (!hasNext()) { throw new NoSuchElementException(); } StringBuilder sb = new StringBuilder(); while(true) { int b = readByte(); if (!isPrintableChar(b)) { break; } sb.appendCodePoint(b); } return sb.toString(); } public String nextLine() { if (!hasNext()) { throw new NoSuchElementException(); } StringBuilder sb = new StringBuilder(); while(true) { int b = readByte(); if (!isPrintableChar(b) && b != 0x20) { break; } sb.appendCodePoint(b); } return sb.toString(); } public char nextChar() { return next().charAt(0); } public int nextInt() { if (!hasNext()) { throw new NoSuchElementException(); } int n = 0; boolean minus = false; { int b = readByte(); if (b == '-') { minus = true; } else if ('0' <= b && b <= '9') { n = b - '0'; } else { throw new NumberFormatException(); } } while(true){ int b = readByte(); if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } } } public long nextLong() { if (!hasNext()) { throw new NoSuchElementException(); } long n = 0; boolean minus = false; { int b = readByte(); if (b == '-') { minus = true; } else if ('0' <= b && b <= '9') { n = b - '0'; } else { throw new NumberFormatException(); } } while(true){ int b = readByte(); if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } } } public double nextDouble() { return Double.parseDouble(next()); } public String[] next(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = next(); } return array; } public String[] nextLine(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = nextLine(); } return array; } public char[] nextChar(int n) { char[] array = new char[n]; for (int i = 0; i < n; i++) { array[i] = nextChar(); } return array; } public int[] nextInt(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } public long[] nextLong(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } public double[] nextDouble(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } public char[] nextCharArray() { return next().toCharArray(); } public String[][] next(int n, int m) { String[][] matrix = new String[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = next(); } } return matrix; } public int[][] nextInt(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextInt(); } } return matrix; } public char[][] nextChar(int n, int m) { char[][] matrix = new char[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextChar(); } } return matrix; } public long[][] nextLong(int n, int m) { long[][] matrix = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextLong(); } } return matrix; } public double[][] nextDouble(int n, int m) { double[][] matrix = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = nextDouble(); } } return matrix; } public char[][] nextCharArray(int n) { char[][] matrix = new char[n][]; for (int i = 0; i < n; i++) { matrix[i] = next().toCharArray(); } return matrix; } } Code 2: using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Threading; using System.Text; using System.Text.RegularExpressions; using System.Diagnostics; using static util; using P = pair<int, int>; class Program { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; var solver = new Solver(sw); // var t = new Thread(solver.solve, 1 << 26); // 64 MB // t.Start(); // t.Join(); solver.solve(); sw.Flush(); } } class Solver { StreamWriter sw; Scan sc; void Prt(string a) => sw.WriteLine(a); void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a)); void Prt(params object[] a) => Prt(string.Join(" ", a)); public Solver(StreamWriter sw) { this.sw = sw; this.sc = new Scan(); } public void solve() { int h, w, k; sc.Multi(out h, out w, out k); var s = new string[h]; for (int i = 0; i < h; i++) { s[i] = sc.Str; } int ans = M; for (int i = 0; i < (1 << h - 1); i++) { int c = 0; var lis = new List<int>(); lis.Add(0); for (int j = 0; j < h - 1; j++) { if (((i >> j) & 1) == 1) { ++c; lis.Add(j + 1); } } lis.Add(h); int n = c + 1; var cnt = new int[n]; for (int j = 0; j < w; j++) { bool ok = true; var cc = new int[n]; for (int l = 0; l < n; l++) { for (int m = lis[l]; m < lis[l + 1]; m++) { if (s[m][j] == '1') ++cc[l]; } if (cc[l] > k) { goto A; } if (cnt[l] + cc[l] > k) { ok = false; } } if (!ok) { ++c; cnt = new int[n]; } for (int l = 0; l < n; l++) { cnt[l] += cc[l]; } } ans = Math.Min(ans, c); A: continue; } Prt(ans); } } class pair<T, U> : IComparable<pair<T, U>> { public T v1; public U v2; public pair() : this(default(T), default(U)) {} public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; } public int CompareTo(pair<T, U> a) { int c = Comparer<T>.Default.Compare(v1, a.v1); return c != 0 ? c : Comparer<U>.Default.Compare(v2, a.v2); } public override string ToString() => v1 + " " + v2; public void Deconstruct(out T a, out U b) { a = v1; b = v2; } } static class util { // public static readonly int M = 1000000007; public static readonly int M = 998244353; public static readonly long LM = 1L << 60; public static readonly double eps = 1e-11; public static void DBG(string a) => Console.Error.WriteLine(a); public static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a)); public static void DBG(params object[] a) => DBG(string.Join(" ", a)); public static void Assert(params bool[] conds) { foreach (var cond in conds) if (!cond) throw new Exception(); } public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2); public static int CompareList<T>(IList<T> a, IList<T> b) where T : IComparable<T> { for (int i = 0; i < a.Count && i < b.Count; i++) if (a[i].CompareTo(b[i]) != 0) return a[i].CompareTo(b[i]); return a.Count.CompareTo(b.Count); } public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w; static readonly int[] dd = { 0, 1, 0, -1 }; // static readonly string dstring = "RDLU"; public static P[] adjacents(int i, int j) => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).ToArray(); public static P[] adjacents(int i, int j, int h, int w) => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])) .Where(p => inside(p.v1, p.v2, h, w)).ToArray(); public static P[] adjacents(this P p) => adjacents(p.v1, p.v2); public static P[] adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w); public static Dictionary<T, int> compress<T>(this IEnumerable<T> a) => a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i); public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.Aggregate(Enumerable.Union)); public static T[] inv<T>(this Dictionary<T, int> dic) { var res = new T[dic.Count]; foreach (var item in dic) res[item.Value] = item.Key; return res; } public static void swap<T>(ref T a, ref T b) where T : struct { var t = a; a = b; b = t; } public static void swap<T>(this IList<T> a, int i, int j) where T : struct { var t = a[i]; a[i] = a[j]; a[j] = t; } public static T[] copy<T>(this IList<T> a) { var ret = new T[a.Count]; for (int i = 0; i < a.Count; i++) ret[i] = a[i]; return ret; } public static void Deconstruct<T>(this IList<T> v, out T a) { a = v[0]; } public static void Deconstruct<T>(this IList<T> v, out T a, out T b) { a = v[0]; b = v[1]; } public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c) { a = v[0]; b = v[1]; c = v[2]; } public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c, out T d) { a = v[0]; b = v[1]; c = v[2]; d = v[3]; } public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c, out T d, out T e) { a = v[0]; b = v[1]; c = v[2]; d = v[3]; e = v[4]; } } class Scan { StreamReader sr; public Scan() { sr = new StreamReader(Console.OpenStandardInput()); } public Scan(string path) { sr = new StreamReader(path); } public int Int => int.Parse(Str); public long Long => long.Parse(Str); public double Double => double.Parse(Str); public string Str => sr.ReadLine().Trim(); public pair<T, U> Pair<T, U>() { T a; U b; Multi(out a, out b); return new pair<T, U>(a, b); } public P P => Pair<int, int>(); public int[] IntArr => StrArr.Select(int.Parse).ToArray(); public long[] LongArr => StrArr.Select(long.Parse).ToArray(); public double[] DoubleArr => StrArr.Select(double.Parse).ToArray(); public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries); bool eq<T, U>() => typeof(T).Equals(typeof(U)); T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T)); T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s)) : eq<T, long>() ? ct<T, long>(long.Parse(s)) : eq<T, double>() ? ct<T, double>(double.Parse(s)) : eq<T, char>() ? ct<T, char>(s[0]) : ct<T, string>(s); public void Multi<T>(out T a) => a = cv<T>(Str); public void Multi<T, U>(out T a, out U b) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); } public void Multi<T, U, V>(out T a, out U b, out V c) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); } public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); } public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); } }
C
#include <stdio.h> #define MAX 10 void print( int val, int delim ) { if ( val != delim ) { printf( "%d ", val ); } else if ( val == delim ) { printf( "%d", val ); } } int main() { int path[MAX][MAX], s, d; int num; scanf( "%d", &num ); for ( int i = 0 ; i < num ; i++ ) { scanf( "%d %d", &s, &d ); if ( i > 102 ) { break; } // 場合分け // s:d:5 x // d:s:5 x // s:5:d // d:5:s // 5:d:s o // 5:s:d o if ( s <= 5 && d <= 5 ) { if ( s < d ) { while ( s < d ) { print( s, d ); s++; } } else if ( s > d ) { while ( s > d ) { print( s, d ); s--; } } } else if ( s >= 5 && d >= 5 ) { if ( s < d ) { while ( s < d ) { print( s, d ); s++; } } else if ( s > d ) { while ( s < MAX ) { print( s, d ); s++; } s = 5; if ( s != d ) { while ( s > 0 ) { print( s, d ); s--; } s = 0; while ( s < d ) { print( s, d ); s++; } } } } else { if ( s < d ) { while ( s < d ) { print( s, d ); s++; } } else if ( s > d ) { while ( s < MAX ) { print( s, d ); s++; } s = 5; while ( s > d ) { print( s, d ); s--; } } } print( s, d ); printf( "\n" ); } return 0; }
Java
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] stop = new int[]{0,1,2,3,4,5,6,7,8,9,5,4,3,2,1}; while(n-- > 0){ int s = sc.nextInt(); int g = sc.nextInt(); int idx; for(idx=0;stop[idx]!=s;idx++); ArrayList<Integer> r1 = getRoute(stop,idx,s,g); for(idx=stop.length-1;stop[idx]!=s;idx--); ArrayList<Integer> r2 = getRoute(stop,idx,s,g); ArrayList<Integer> ans = r1.size() < r2.size() ? r1 : r2; for(int i=0;i<ans.size()-1;i++){ System.out.print(ans.get(i) + " "); } System.out.println(ans.get(ans.size()-1)); } } private static ArrayList<Integer> getRoute(int[] stop,int idx,int s,int g){ ArrayList<Integer> res = new ArrayList<Integer>(); for(int i=idx;stop[i]!=g;i=(i+1)%stop.length){ res.add(stop[i]); } res.add(g); return res; } }
Yes
Do these codes solve the same problem? Code 1: #include <stdio.h> #define MAX 10 void print( int val, int delim ) { if ( val != delim ) { printf( "%d ", val ); } else if ( val == delim ) { printf( "%d", val ); } } int main() { int path[MAX][MAX], s, d; int num; scanf( "%d", &num ); for ( int i = 0 ; i < num ; i++ ) { scanf( "%d %d", &s, &d ); if ( i > 102 ) { break; } // 場合分け // s:d:5 x // d:s:5 x // s:5:d // d:5:s // 5:d:s o // 5:s:d o if ( s <= 5 && d <= 5 ) { if ( s < d ) { while ( s < d ) { print( s, d ); s++; } } else if ( s > d ) { while ( s > d ) { print( s, d ); s--; } } } else if ( s >= 5 && d >= 5 ) { if ( s < d ) { while ( s < d ) { print( s, d ); s++; } } else if ( s > d ) { while ( s < MAX ) { print( s, d ); s++; } s = 5; if ( s != d ) { while ( s > 0 ) { print( s, d ); s--; } s = 0; while ( s < d ) { print( s, d ); s++; } } } } else { if ( s < d ) { while ( s < d ) { print( s, d ); s++; } } else if ( s > d ) { while ( s < MAX ) { print( s, d ); s++; } s = 5; while ( s > d ) { print( s, d ); s--; } } } print( s, d ); printf( "\n" ); } return 0; } Code 2: import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] stop = new int[]{0,1,2,3,4,5,6,7,8,9,5,4,3,2,1}; while(n-- > 0){ int s = sc.nextInt(); int g = sc.nextInt(); int idx; for(idx=0;stop[idx]!=s;idx++); ArrayList<Integer> r1 = getRoute(stop,idx,s,g); for(idx=stop.length-1;stop[idx]!=s;idx--); ArrayList<Integer> r2 = getRoute(stop,idx,s,g); ArrayList<Integer> ans = r1.size() < r2.size() ? r1 : r2; for(int i=0;i<ans.size()-1;i++){ System.out.print(ans.get(i) + " "); } System.out.println(ans.get(ans.size()-1)); } } private static ArrayList<Integer> getRoute(int[] stop,int idx,int s,int g){ ArrayList<Integer> res = new ArrayList<Integer>(); for(int i=idx;stop[i]!=g;i=(i+1)%stop.length){ res.add(stop[i]); } res.add(g); return res; } }
Java
import java.util.Scanner; import java.util.Stack; class Main { public static void main(String[] args) { new Main().compute(); } void compute() { Scanner sc = new Scanner(System.in); sc.useDelimiter("[\\s]+"); while (true) { int n = sc.nextInt(); if (n == 0) { break; } long max = Long.MIN_VALUE; int[] vars = new int[n]; for (int i = 0; i < n; i++) { vars[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { long cur = 0; for (int j = i; j < n; j++) { cur+=vars[j]; max = max > cur ? max : cur; } } System.out.println(max); } } }
PHP
<?php while(1) { $d = $a = -PHP_INT_MAX; fscanf(STDIN, "%d", $n); if(!$n) break; for($i = 0; $i < $n; $i++) { fscanf(STDIN, "%d", $m); $d = max($d + $m, $m); $a = max($a, $d); } echo $a . "\n"; }
Yes
Do these codes solve the same problem? Code 1: import java.util.Scanner; import java.util.Stack; class Main { public static void main(String[] args) { new Main().compute(); } void compute() { Scanner sc = new Scanner(System.in); sc.useDelimiter("[\\s]+"); while (true) { int n = sc.nextInt(); if (n == 0) { break; } long max = Long.MIN_VALUE; int[] vars = new int[n]; for (int i = 0; i < n; i++) { vars[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { long cur = 0; for (int j = i; j < n; j++) { cur+=vars[j]; max = max > cur ? max : cur; } } System.out.println(max); } } } Code 2: <?php while(1) { $d = $a = -PHP_INT_MAX; fscanf(STDIN, "%d", $n); if(!$n) break; for($i = 0; $i < $n; $i++) { fscanf(STDIN, "%d", $m); $d = max($d + $m, $m); $a = max($a, $d); } echo $a . "\n"; }
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Program { class MainClass { //////////////////////////////////////////////////////////// string S; void Solve() { io.i(out S); io.o(S.Where(c => c == '1').Count()); } //////////////////////////////////////////////////////////// public static void Main() { new MainClass().Stream(); } IO io = new IO(); void Stream() { Solve(); io.writeFlush(); } //void Stream() { Test(); io.writeFlush(); } void Test() { } #region MockMacro //cannot use break,continue,goto void FOR(int a, int b, Action<int> act) { for (int i = a; i < b; ++i) act(i); } void FORR(int a, int b, Action<int> act) { for (int i = a - 1; i >= b; --i) act(i); } #endregion //////////////////////////////////////////////////////////// } #region default class IO { string[] nextBuffer; int BufferCnt; char[] cs = new char[] { ' ' }; StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; public IO() { nextBuffer = new string[0]; BufferCnt = 0; Console.SetOut(sw); } public string Next() { if (BufferCnt < nextBuffer.Length) return nextBuffer[BufferCnt++]; string st = Console.ReadLine(); while (st == "") st = Console.ReadLine(); nextBuffer = st.Split(cs, StringSplitOptions.RemoveEmptyEntries); BufferCnt = 0; return nextBuffer[BufferCnt++]; } public string String => Next(); public char Char => char.Parse(String); public int Int => int.Parse(String); public long Long => long.Parse(String); public double Double => double.Parse(String); public string[] arr => Console.ReadLine().Split(' '); public char[] arrChar => Array.ConvertAll(arr, char.Parse); public int[] arrInt => Array.ConvertAll(arr, int.Parse); public long[] arrLong => Array.ConvertAll(arr, long.Parse); public double[] arrDouble => Array.ConvertAll(arr, double.Parse); public T i<T>() { return suitType<T>(String); } public void i<T>(out T v) { v = suitType<T>(String); } public void i<T, U>(out T v1, out U v2) { i(out v1); i(out v2); } public void i<T, U, V>(out T v1, out U v2, out V v3) { i(out v1); i(out v2); i(out v3); } public void i<T, U, V, W>(out T v1, out U v2, out V v3, out W v4) { i(out v1); i(out v2); i(out v3); i(out v4); } public void i<T, U, V, W, X>(out T v1, out U v2, out V v3, out W v4, out X v5) { i(out v1); i(out v2); i(out v3); i(out v4); i(out v5); } public void ini<T>(out T[] a, int n) { a = new T[n]; for (int i = 0; i < n; ++i) a[i] = suitType<T>(String); } public void ini<T, U>(out T[] a, out U[] b, int n) { a = new T[n]; b = new U[n]; for (int i = 0; i < n; ++i) { a[i] = i<T>(); b[i] = i<U>(); } } public void ini<T, U, V>(out T[] a, out U[] b, out V[] c, int n) { a = new T[n]; b = new U[n]; c = new V[n]; for (int i = 0; i < n; ++i) { a[i] = i<T>(); b[i] = i<U>(); c[i] = i<V>(); } } public void ini<T>(out T[,] a, int h, int w) { a = new T[h, w]; for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) a[i, j] = i<T>(); } public void o<T>(T v) { Console.WriteLine(v); } public void o<T>(params T[] a) { Array.ForEach(a, n => o(n)); } public void o<T>(T[,] a) { int a0 = a.GetLength(0), a1 = a.GetLength(1); for (int i = 0; i < a0; ++i) { for (int j = 0; j < a1 - 1; ++j) Console.Write(a[i, j] + " "); Console.WriteLine(a[i, a1 - 1]); } } public void YN(bool f) { o(f ? "YES" : "NO"); } public void Yn(bool f) { o(f ? "Yes" : "No"); } public void yn(bool f) { o(f ? "yes" : "no"); } public void ol<T>(params T[] a) { o(connect<T>(a)); } public void or<T>(T a) { Console.Write(a); } public void br() { o(""); } public void writeFlush() { Console.Out.Flush(); } private string connect<T>(params T[] s) { return string.Join(" ", s); } private bool typeEQ<T, U>() { return typeof(T).Equals(typeof(U)); } private T convertType<T, U>(U v) { return (T)Convert.ChangeType(v, typeof(T)); } private T suitType<T>(string s) { if (typeEQ<T, int>()) return convertType<T, int>(int.Parse(s)); if (typeEQ<T, long>()) return convertType<T, long>(long.Parse(s)); if (typeEQ<T, double>()) return convertType<T, double>(double.Parse(s)); if (typeEQ<T, char>()) return convertType<T, char>(char.Parse(s)); return convertType<T, string>(s); } } class PQueue<T> where T : IComparable { public List<T> heap; private Comparison<T> comp; private IComparer<T> comparer; private int size; private int type;//type=0->min public PQueue(int type = 0) : this(Comparer<T>.Default) { this.type = type; } public PQueue(IComparer<T> comparer) : this(16, comparer.Compare) { this.comparer = comparer; } public PQueue(Comparison<T> comparison) : this(16, comparison) { } public PQueue(int capacity, Comparison<T> comparison) { this.heap = new List<T>(capacity); this.comp = comparison; } public void Enqueue(T item) { this.heap.Add(item); var i = size++; while (i > 0) { var p = (i - 1) >> 1; if (Compare(this.heap[p], item) <= 0) break; this.heap[i] = heap[p]; i = p; } this.heap[i] = item; } public T Dequeue() { var ret = this.heap[0]; var x = this.heap[--size]; var i = 0; while ((i << 1) + 1 < size) { var a = (i << 1) + 1; var b = (i << 1) + 2; if (b < size && Compare(heap[b], heap[a]) < 0) a = b; if (Compare(heap[a], x) >= 0) break; heap[i] = heap[a]; i = a; } heap[i] = x; heap.RemoveAt(size); return ret; } public T Peek() { return heap[0]; } public int Count { get { return size; } } public bool Any() { return size > 0; } public bool Empty() { return !Any(); } public bool Contains(T v) { return heap.Contains(v); } private int Compare(T x, T y) { return type == 0 ? x.CompareTo(y) : y.CompareTo(x); } } #endregion #region other class Mat { public long mod = 1000000007;//10^9+7 public long Pow(long a, long b) { if (b == 0) return 1; if (b % 2 == 1) return (a % mod * Pow(a % mod, b - 1) % mod) % mod; else return Pow(a * a % mod, b / 2) % mod; } public long Fact(long n) { long ret = 1; for (long i = 1; i <= n; i++) ret = (ret * i) % mod; return ret; } public long ModC(long n, long r) { if (r == 0 || n == r) return 1; if (n == 0) return 0; if (n < 0 || n < r) throw new ArgumentException("n,r invalid"); else return (Fact(n) % mod * Pow((Fact(n - r) % mod * Fact(r) % mod) % mod, mod - 2) % mod) % mod; } public long[,] C(int N) { long[,] Co = new long[N + 1, N + 1]; (N + 1).REP(i => (i + 1).REP(j => Co[i, j] = (j == 0 || j == i) ? 1L : Co[i - 1, j - 1] + Co[i - 1, j])); return Co; } public long DupC(long n, long r) { return ModC(n + r - 1, r); } public long P(long n, long r) { return Fact(n) / (Fact(n - r)); }//test public bool isPrime(long n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (long v = 3; v <= (long)Math.Sqrt(n); v += 2) if (n % v == 0) return false; return true; } public long LCM(long a, long b) { return a * (b / GCD(a, b)); } public long LCM(params long[] a) { return a.Aggregate((v, n) => LCM(v, n)); } public long GCD(long a, long b) { if (a < b) Swap(ref a, ref b); return b == 0 ? a : GCD(b, a % b); } public long GCD(params long[] array) { return array.Aggregate((v, n) => GCD(v, n)); } public T Max<T>(params T[] a) { return a.Max(); } public T Min<T>(params T[] a) { return a.Min(); } public void Swap<T>(ref T a, ref T b) { T tmp = a; a = b; b = tmp; } public double Dis(int x1, int y1, int x2, int y2) { return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2)); } public int mDis(int x1, int y1, int x2, int y2) { return Math.Abs(x1 - x2) + Math.Abs(y1 - y2); } public int[] DigArr(int n) { int[] ret = new int[Digit(n)]; ret.Length.REP(i => ret[i] = DigVal(n, i + 1)); return ret; } public long DigArr2Num(IEnumerable<int> enu) { return enu.Aggregate((v, n) => v * 10 + n); } public int Digit(long n) { return (n == 0) ? 1 : (int)Math.Log10(n) + 1; } public int DigVal(int n, int dig) { return (n % (int)Pow(10, dig)) / (int)Pow(10, dig - 1); } public long Tousa(long a, long d, long n) { return a + (n - 1) * d; } public long TousaSum(long a, long d, long n) { return n * (2 * a + (n - 1) * d) / 2; } public long[] EnuDivsor(long N) { var ret = new SortedSet<long>(); for (long i = 1; i * i <= N; i++) if (N % i == 0) { ret.Add(i); ret.Add(N / i); } return ret.ToArray(); } public Dictionary<long, long> PrimeFactor(long n) { var ret = new Dictionary<long, long>(); for (int i = 2; i * i <= n; ++i) { if (!ret.ContainsKey(i)) ret[i] = 0; while (n % i == 0) { ++ret[i]; n /= i; } } return ret.Where(kp => kp.Value != 0).ToDictionary(kp => kp.Key, kp => kp.Value); } public IEnumerable<int[]> enuP(int[] Arr, int Use = -1) {//列挙順列 Use = (Use != -1) ? Use : Arr.Length; if (Use == 0 || Arr.Length < Use) yield break; var s = new Stack<List<int>>(); for (int i = Arr.Length - 1; i >= 0; i--) s.Push(new List<int>() { i }); while (s.Count > 0) { var cur = s.Pop(); if (cur.Count == Use) { var ret = new List<int>(); cur.ForEach(X => ret.Add(Arr[X])); yield return ret.ToArray(); } else for (int i = Arr.Length - 1; i >= 0; i--) if (!cur.Contains(i)) s.Push(new List<int>(cur) { i }); } } public IEnumerable<int[]> enuC(int[] Arr, int Use = -1) {//列挙組み合わせ Use = (Use != -1) ? Use : Arr.Length; if (Use == 0 || Arr.Length < Use) yield break; var s = new Stack<Tuple<int, List<int>>>(); Arr.Length.REPR(i => s.Push(Tuple.Create(i, new List<int>() { Arr[i] }))); while (s.Count > 0) { var cur = s.Pop(); if (cur.Item2.Count == Use) yield return cur.Item2.ToArray(); else for (int i = Arr.GetUpperBound(0); i > cur.Item1; i--) s.Push(Tuple.Create(i, new List<int>(cur.Item2) { Arr[i] })); } } public IEnumerable<int[]> enuDupP(int[] Arr, int Use = -1) {//列挙重複順列 Use = (Use != -1) ? Use : Arr.Length; if (Use == 0) yield break; var s = new Stack<List<int>>(); Arr.Length.REPR(i => s.Push(new List<int>() { Arr[i] })); while (s.Count > 0) { var cur = s.Pop(); if (cur.Count == Use) yield return cur.ToArray(); else Arr.Length.REPR(i => s.Push(new List<int>(cur) { Arr[i] })); } } public IEnumerable<int[]> enuDupC(int[] Arr, int Use = -1) {//列挙組み合わせ Use = (Use != -1) ? Use : Arr.Length; if (Use == 0) yield break; var s = new Stack<Tuple<int, List<int>>>(); Arr.Length.REPR(i => s.Push(Tuple.Create(i, new List<int>() { Arr[i] }))); while (s.Count > 0) { var cur = s.Pop(); if (cur.Item2.Count == Use) yield return cur.Item2.ToArray(); else for (int i = Arr.GetUpperBound(0); i >= cur.Item1; i--) s.Push(Tuple.Create(i, new List<int>(cur.Item2) { Arr[i] })); } } public IEnumerable<string[]> enuPart(string str) { var s = new Stack<Tuple<string, List<string>, int>>(); s.Push(Tuple.Create(str[0].ToString(), new List<string>(), 1)); while (s.Count > 0) { var cur = s.Pop(); if (cur.Item3 >= str.Length) yield return (new List<string>(cur.Item2) { cur.Item1 }).ToArray(); else { s.Push(Tuple.Create(cur.Item1 + str[cur.Item3], new List<string>(cur.Item2), cur.Item3 + 1)); s.Push(Tuple.Create(str[cur.Item3].ToString(), new List<string>(cur.Item2) { cur.Item1 }, cur.Item3 + 1)); } } } } #endregion #region Data class AssociativeArray<T> : IEnumerable { public Dictionary<T, int> dic; public AssociativeArray() { dic = new Dictionary<T, int>(); } public AssociativeArray(params T[] a) { dic = new Dictionary<T, int>(); Add(a); } public void Add(T a) { if (!conK(a)) dic[a] = 0; dic[a]++; } public void Add(params T[] a) { a.Length.REP(i => { if (!conK(a[i])) dic[a[i]] = 0; dic[a[i]]++; }); } public void Set(T k, int v) { if (!dic.ContainsKey(k)) dic[k] = 0; dic[k] = v; } public void Remove(params T[] a) { a.Length.REP(i => { if (conK(a[i])) dic.Remove(a[i]); }); } public T[] Keys() { return dic.Keys.ToArray<T>(); } public int Val(T k) { return (dic.ContainsKey(k)) ? dic[k] : 0; } public int ValSum => dic.Values.Sum(); public int KeyNum => dic.Keys.Count; public int MaxVal => dic.Values.Max(); public int MinVal => dic.Values.Min(); public T MaxKey => MaxK(); public T MinKey => MinK(); public T MaxK() { var maxV = MaxVal; return dic.First(d => d.Value == maxV).Key; } public T MinK() { var minV = MinVal; return dic.First(d => d.Value == minV).Key; } public T[] MaxKeys() { var maxV = MaxVal; return dic.Where(kp => kp.Value == maxV).ToDictionary(kp => kp.Key, kp => kp.Value).Keys.ToArray(); } public T[] MinKeys() { var minV = MinVal; return dic.Where(kp => kp.Value == minV).ToDictionary(kp => kp.Key, kp => kp.Value).Keys.ToArray(); } public bool conK(T k) { return dic.ContainsKey(k); } public bool anyK(params T[] k) { return k.Any(key => conK(key)); } public bool allK(params T[] k) { return k.All(key => conK(key)); } public void Show() { foreach (var v in dic) { Console.WriteLine(v.Key + " : " + v.Value); } } public T[] ValueSortedKey(bool inc = true) { return (inc ? (dic.OrderBy(kp => kp.Value)) : (dic.OrderByDescending(kp => kp.Value))) .ThenBy(kp => kp.Key).ToDictionary(kp => kp.Key, kp => kp.Value).Keys.ToArray(); } public IEnumerator GetEnumerator() { foreach (var kp in dic) yield return kp; } //:sort->array } class TreeDis {//TODO:shortestPath public List<Tuple<long, long>>[] g; public long[] a2other; private int type; public TreeDis(int type = 0) { this.type = type; }//0->bfs,other->dfs public void Init(long n) { g = new List<Tuple<long, long>>[n + 1]; g.Length.REP(i => g[i] = new List<Tuple<long, long>>()); } public void Run(long[] a, long[] b) { a.Length.REP(i => { g[a[i]].Add(Tuple.Create(b[i], 1L)); g[b[i]].Add(Tuple.Create(a[i], 1L)); }); } public void Run(long[] a, long[] b, long[] w) { a.Length.REP(i => { g[a[i]].Add(Tuple.Create(b[i], w[i])); g[b[i]].Add(Tuple.Create(a[i], w[i])); }); } public long[] a2iArr(long a) { a2other = new long[g.Count()]; if (type == 0) BFS(a); else DFS(a); return a2other; } private void BFS(long a) { var q = new Queue<Tuple<long, long>>(); q.Enqueue(Tuple.Create(a, -1L)); while (q.Count > 0) { var c = q.Dequeue(); foreach (var v in g[c.Item1]) { if (v.Item1 == c.Item2) continue; a2other[v.Item1] = a2other[c.Item1] + v.Item2; q.Enqueue(Tuple.Create(v.Item1, c.Item1)); } } } private void DFS(long a) { var s = new Stack<Tuple<long, long>>(); s.Push(Tuple.Create(a, -1L)); while (s.Count > 0) { var c = s.Pop(); foreach (var v in g[c.Item1]) { if (v.Item1 == c.Item2) continue; a2other[v.Item1] = a2other[c.Item1] + v.Item2; s.Push(Tuple.Create(v.Item1, c.Item1)); } } } } class ShortestPath { protected int I = -1; //辺は1~N protected int V; //頂点数 protected int E; //辺の数 protected bool isNonDir = true; //有向? public long INF = (long)1e15; //初期化 public long[] cost; //重み public List<Tuple<int, long>>[] Adj;//Adj[from]=(to,cost) public void Init(int n) { I = n + 1; V = n; Adj = new List<Tuple<int, long>>[I]; for (int i = 0; i < I; ++i) Adj[i] = new List<Tuple<int, long>>(); } public void AddPath(int f, int t, long c = 1) { E++; Adj[f].Add(Tuple.Create(t, c)); if (isNonDir) Adj[t].Add(Tuple.Create(f, c)); } public void AddPath(int[] f, int[] t, long[] c) { for (int i = 0; i < f.Length; ++i) AddPath(f[i], t[i], c[i]); } public void AddPath(int[] f, int[] t) { for (int i = 0; i < f.Length; ++i) AddPath(f[i], t[i]); } } class Dijkstra : ShortestPath {//隣接対応後検証不足,有向とか public Dijkstra(bool isNonDir = true) { this.isNonDir = isNonDir; } public long MinCost(int f, int t) { Run(f); return cost[t]; } public long MinCost(int t) { return cost[t]; } public void Run(int f) { cost = new long[I]; for (int i = 0; i < I; ++i) cost[i] = INF; cost[f] = 0; var pq = new PQueue<Tuple<int, long>>(); pq.Enqueue(Tuple.Create(f, 0L));//(from,cost) while (!pq.Empty()) { var cur = pq.Dequeue(); //if (cost[cur.Item1] != cur.Item2) continue; if (cost[cur.Item1] < cur.Item2) continue; for (int i = 0; i < Adj[cur.Item1].Count; ++i) { var tmp = Adj[cur.Item1][i]; if (cost[tmp.Item1] > cur.Item2 + tmp.Item2) { cost[tmp.Item1] = cur.Item2 + tmp.Item2; pq.Enqueue(Tuple.Create(tmp.Item1, cost[tmp.Item1])); } } } } public bool PathExist(int t) { return cost[t] != INF; } } class BellmanFord : ShortestPath { private bool[] neg; public BellmanFord() { } public BellmanFord(bool isNonDir) { this.isNonDir = isNonDir; } public long MinCost(int f, int t) { cost = new long[I]; cost.Set(INF); cost[f] = 0; neg = new bool[I]; for (int i = 0; i < I - 1; i++) { I.REP(j => Adj[j].Count.REP(k => { var cur = Adj[j][k]; if (cost[cur.Item1] > cost[j] + cur.Item2) cost[cur.Item1] = cost[j] + cur.Item2; })); } for (int i = 0; i < I; i++) { I.REP(j => Adj[j].Count.REP(k => { var cur = Adj[j][k]; if (cost[cur.Item1] > cost[j] + cur.Item2) { cost[cur.Item1] = cost[j] + cur.Item2; neg[cur.Item1] = true; } if (neg[j]) neg[cur.Item1] = true; })); } return cost[t]; } public bool loopExist() { return neg[I - 1]; } } class WF : ShortestPath { public WF() { } public WF(bool isNonDir) { this.isNonDir = isNonDir; } public void Run() { } } class WarshallFloyd { private int E; private bool isNonDir; public long INF = (long)1e15; public long[,] BefG; public long[,] G; public WarshallFloyd(bool isNonDir = true) { this.isNonDir = isNonDir; } public void Init(int n) { E = n + 1; G = new long[E, E]; BefG = new long[E, E]; for (int i = 0; i < E; ++i) for (int j = 0; j < E; ++j) { G[i, j] = INF; BefG[i, j] = INF; } for (int i = 0; i < E; ++i) { G[i, i] = 0; BefG[i, i] = 0; } } public void AddPath(int f, int t, long c = 1) { if (isNonDir) { G[f, t] = c; G[t, f] = c; BefG[f, t] = c; BefG[t, f] = c; } else { G[f, t] = c; BefG[f, t] = c; } } public void AddPath(int[] f, int[] t) { for (int i = 0; i < f.Length; ++i) AddPath(f[i], t[i], 1); } public void AddPath(int[] f, int[] t, long[] c) { for (int i = 0; i < f.Length; ++i) AddPath(f[i], t[i], c[i]); } public void Run() { G = MinCostArr(); } public long[,] MinCostArr() { for (int i = 0; i < E; ++i) for (int j = 0; j < E; ++j) for (int k = 0; k < E; ++k) G[j, k] = Math.Min(G[j, k], G[j, i] + G[i, k]); return G; } //使う?使わない? public int[] MinPath(int from, int to) { var ret = new List<int>(); var cur = from; while (cur != to) { ret.Add(cur); for (int i = 1; i < E; ++i) { if (BefG[cur, i] + G[i, to] == G[cur, to]) { if (i == cur) continue; cur = i; break; } } } ret.Add(cur); return ret.ToArray(); } public bool isMinPath(int a, int b, long c) { for (int i = 0; i < E; ++i) if (G[i, a] + c == G[i, b]) return true; return false; } //全地点間を繋ぐ最小コスト public long MinCost() { long orig = 0; for (int i = 0; i < E; ++i) for (int j = i + 1; j < E; ++j) { bool isOrig = true; for (int k = 0; k < E; ++k) { if (k == i || k == j) continue; if (G[i, j] == G[i, k] + G[k, j]) { isOrig = false; break; } } if (isOrig) orig += G[i, j]; } return orig; } } class UnionFind { int[] dat; public void Init(int n) { dat = new int[n + 1]; for (int i = 0; i <= n; ++i) dat[i] = -1; } public void Unite(int x, int y) { x = Root(x); y = Root(y); if (x == y) return; if (dat[y] < dat[x]) swap(ref x, ref y); dat[x] += dat[y]; dat[y] = x; } public bool Find(int x, int y) { return Root(x) == Root(y); } public int Root(int x) { return dat[x] < 0 ? x : dat[x] = Root(dat[x]); } public int Size(int x) { return -dat[Root(x)]; } void swap(ref int a, ref int b) { int tmp = b; b = a; a = tmp; } } class Kruskal : ShortestPath { public Kruskal() { } public Kruskal(bool isNonDir) { this.isNonDir = isNonDir; } public long Run() { var uf = new UnionFind(); var ret = 0L; var L = new List<Tuple<int, int, long>>(); uf.Init(V); for (int i = 0; i < I; ++i) for (int j = 0; j < Adj[i].Count; ++i) L.Add(Tuple.Create(i, Adj[i][j].Item1, Adj[i][j].Item2)); L = L.OrderBy(t => t.Item3).ToList(); for (int i = 0; i < L.Count; ++i) if (!uf.Find(L[i].Item1, L[i].Item2)) { ret += L[i].Item3; uf.Unite(L[i].Item1, L[i].Item2); } return ret; } } #endregion #region Ex static class StringEX { public static string Reversed(this string s) { return string.Join("", s.Reverse()); } public static string Repeat(this string s, int n) { return string.Concat(Enumerable.Repeat(s, n).ToArray()); } public static int toInt(this string s) { int n; return (int.TryParse(s.TrimStart('0'), out n)) ? n : 0; } public static int toInt(this char c) { return toInt(c.ToString()); } public static int toInt(this char[] c) { return toInt(new string(c)); } public static long toLong(this string s) { long n; return (long.TryParse(s.TrimStart('0'), out n)) ? n : (long)0; } public static long toLong(this char c) { return toLong(c.ToString()); } public static long toLong(this char[] c) { return toLong(new string(c)); } public static string toString(this char[] c) { return new string(c); } } static class NumericEx { public static string pad0<T>(this T v, int n) { return v.ToString().PadLeft(n, '0'); } public static double RoundOff(this double v, int n) { return Math.Round(v, n - 1, MidpointRounding.AwayFromZero); } public static bool Odd(this int v) { return v % 2 != 0; } public static bool Odd(this long v) { return v % 2 != 0; } public static void REP(this int v, Action<int> act) { for (int i = 0; i < v; ++i) act(i); } public static void REPR(this int v, Action<int> act) { for (int i = v - 1; i >= 0; --i) act(i); } } static class ArrayEX { public static T[] Sort<T>(this T[] a) { Array.Sort(a); return a; } public static T[] SortR<T>(this T[] a) { Array.Sort(a); Array.Reverse(a); return a; } public static void Set<T>(this T[] a, T v) { a.Length.REP(i => a[i] = v); } public static void Set<T>(this T[,] a, T v) { a.GetLength(0).REP(i => a.GetLength(1).REP(j => a[i, j] = v)); } public static int[] toIntArr(this string[] a) { return Array.ConvertAll(a, int.Parse); } public static long[] toLongArr(this string[] a) { return Array.ConvertAll(a, long.Parse); } public static double[] toDoubleArr(this string[] a) { return Array.ConvertAll(a, double.Parse); } public static char[] toCharArr(this string[] a) { return Array.ConvertAll(a, char.Parse); } } static class BitEx { public static bool Any(this BitArray b) { foreach (bool f in b) if (f) return true; return false; } public static bool All(this BitArray b) { foreach (bool f in b) if (!f) return false; return true; } public static bool None(this BitArray b) { return !Any(b); } public static void Flip(this BitArray b, int index) { b.Set(index, !b.Get(index)); } } static class IEnumerableEx { } #endregion }
Kotlin
fun main(args:Array<String>) =readLine()?.let { println(it.filter{ it == '1'}.length) }
Yes
Do these codes solve the same problem? Code 1: using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Program { class MainClass { //////////////////////////////////////////////////////////// string S; void Solve() { io.i(out S); io.o(S.Where(c => c == '1').Count()); } //////////////////////////////////////////////////////////// public static void Main() { new MainClass().Stream(); } IO io = new IO(); void Stream() { Solve(); io.writeFlush(); } //void Stream() { Test(); io.writeFlush(); } void Test() { } #region MockMacro //cannot use break,continue,goto void FOR(int a, int b, Action<int> act) { for (int i = a; i < b; ++i) act(i); } void FORR(int a, int b, Action<int> act) { for (int i = a - 1; i >= b; --i) act(i); } #endregion //////////////////////////////////////////////////////////// } #region default class IO { string[] nextBuffer; int BufferCnt; char[] cs = new char[] { ' ' }; StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; public IO() { nextBuffer = new string[0]; BufferCnt = 0; Console.SetOut(sw); } public string Next() { if (BufferCnt < nextBuffer.Length) return nextBuffer[BufferCnt++]; string st = Console.ReadLine(); while (st == "") st = Console.ReadLine(); nextBuffer = st.Split(cs, StringSplitOptions.RemoveEmptyEntries); BufferCnt = 0; return nextBuffer[BufferCnt++]; } public string String => Next(); public char Char => char.Parse(String); public int Int => int.Parse(String); public long Long => long.Parse(String); public double Double => double.Parse(String); public string[] arr => Console.ReadLine().Split(' '); public char[] arrChar => Array.ConvertAll(arr, char.Parse); public int[] arrInt => Array.ConvertAll(arr, int.Parse); public long[] arrLong => Array.ConvertAll(arr, long.Parse); public double[] arrDouble => Array.ConvertAll(arr, double.Parse); public T i<T>() { return suitType<T>(String); } public void i<T>(out T v) { v = suitType<T>(String); } public void i<T, U>(out T v1, out U v2) { i(out v1); i(out v2); } public void i<T, U, V>(out T v1, out U v2, out V v3) { i(out v1); i(out v2); i(out v3); } public void i<T, U, V, W>(out T v1, out U v2, out V v3, out W v4) { i(out v1); i(out v2); i(out v3); i(out v4); } public void i<T, U, V, W, X>(out T v1, out U v2, out V v3, out W v4, out X v5) { i(out v1); i(out v2); i(out v3); i(out v4); i(out v5); } public void ini<T>(out T[] a, int n) { a = new T[n]; for (int i = 0; i < n; ++i) a[i] = suitType<T>(String); } public void ini<T, U>(out T[] a, out U[] b, int n) { a = new T[n]; b = new U[n]; for (int i = 0; i < n; ++i) { a[i] = i<T>(); b[i] = i<U>(); } } public void ini<T, U, V>(out T[] a, out U[] b, out V[] c, int n) { a = new T[n]; b = new U[n]; c = new V[n]; for (int i = 0; i < n; ++i) { a[i] = i<T>(); b[i] = i<U>(); c[i] = i<V>(); } } public void ini<T>(out T[,] a, int h, int w) { a = new T[h, w]; for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) a[i, j] = i<T>(); } public void o<T>(T v) { Console.WriteLine(v); } public void o<T>(params T[] a) { Array.ForEach(a, n => o(n)); } public void o<T>(T[,] a) { int a0 = a.GetLength(0), a1 = a.GetLength(1); for (int i = 0; i < a0; ++i) { for (int j = 0; j < a1 - 1; ++j) Console.Write(a[i, j] + " "); Console.WriteLine(a[i, a1 - 1]); } } public void YN(bool f) { o(f ? "YES" : "NO"); } public void Yn(bool f) { o(f ? "Yes" : "No"); } public void yn(bool f) { o(f ? "yes" : "no"); } public void ol<T>(params T[] a) { o(connect<T>(a)); } public void or<T>(T a) { Console.Write(a); } public void br() { o(""); } public void writeFlush() { Console.Out.Flush(); } private string connect<T>(params T[] s) { return string.Join(" ", s); } private bool typeEQ<T, U>() { return typeof(T).Equals(typeof(U)); } private T convertType<T, U>(U v) { return (T)Convert.ChangeType(v, typeof(T)); } private T suitType<T>(string s) { if (typeEQ<T, int>()) return convertType<T, int>(int.Parse(s)); if (typeEQ<T, long>()) return convertType<T, long>(long.Parse(s)); if (typeEQ<T, double>()) return convertType<T, double>(double.Parse(s)); if (typeEQ<T, char>()) return convertType<T, char>(char.Parse(s)); return convertType<T, string>(s); } } class PQueue<T> where T : IComparable { public List<T> heap; private Comparison<T> comp; private IComparer<T> comparer; private int size; private int type;//type=0->min public PQueue(int type = 0) : this(Comparer<T>.Default) { this.type = type; } public PQueue(IComparer<T> comparer) : this(16, comparer.Compare) { this.comparer = comparer; } public PQueue(Comparison<T> comparison) : this(16, comparison) { } public PQueue(int capacity, Comparison<T> comparison) { this.heap = new List<T>(capacity); this.comp = comparison; } public void Enqueue(T item) { this.heap.Add(item); var i = size++; while (i > 0) { var p = (i - 1) >> 1; if (Compare(this.heap[p], item) <= 0) break; this.heap[i] = heap[p]; i = p; } this.heap[i] = item; } public T Dequeue() { var ret = this.heap[0]; var x = this.heap[--size]; var i = 0; while ((i << 1) + 1 < size) { var a = (i << 1) + 1; var b = (i << 1) + 2; if (b < size && Compare(heap[b], heap[a]) < 0) a = b; if (Compare(heap[a], x) >= 0) break; heap[i] = heap[a]; i = a; } heap[i] = x; heap.RemoveAt(size); return ret; } public T Peek() { return heap[0]; } public int Count { get { return size; } } public bool Any() { return size > 0; } public bool Empty() { return !Any(); } public bool Contains(T v) { return heap.Contains(v); } private int Compare(T x, T y) { return type == 0 ? x.CompareTo(y) : y.CompareTo(x); } } #endregion #region other class Mat { public long mod = 1000000007;//10^9+7 public long Pow(long a, long b) { if (b == 0) return 1; if (b % 2 == 1) return (a % mod * Pow(a % mod, b - 1) % mod) % mod; else return Pow(a * a % mod, b / 2) % mod; } public long Fact(long n) { long ret = 1; for (long i = 1; i <= n; i++) ret = (ret * i) % mod; return ret; } public long ModC(long n, long r) { if (r == 0 || n == r) return 1; if (n == 0) return 0; if (n < 0 || n < r) throw new ArgumentException("n,r invalid"); else return (Fact(n) % mod * Pow((Fact(n - r) % mod * Fact(r) % mod) % mod, mod - 2) % mod) % mod; } public long[,] C(int N) { long[,] Co = new long[N + 1, N + 1]; (N + 1).REP(i => (i + 1).REP(j => Co[i, j] = (j == 0 || j == i) ? 1L : Co[i - 1, j - 1] + Co[i - 1, j])); return Co; } public long DupC(long n, long r) { return ModC(n + r - 1, r); } public long P(long n, long r) { return Fact(n) / (Fact(n - r)); }//test public bool isPrime(long n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (long v = 3; v <= (long)Math.Sqrt(n); v += 2) if (n % v == 0) return false; return true; } public long LCM(long a, long b) { return a * (b / GCD(a, b)); } public long LCM(params long[] a) { return a.Aggregate((v, n) => LCM(v, n)); } public long GCD(long a, long b) { if (a < b) Swap(ref a, ref b); return b == 0 ? a : GCD(b, a % b); } public long GCD(params long[] array) { return array.Aggregate((v, n) => GCD(v, n)); } public T Max<T>(params T[] a) { return a.Max(); } public T Min<T>(params T[] a) { return a.Min(); } public void Swap<T>(ref T a, ref T b) { T tmp = a; a = b; b = tmp; } public double Dis(int x1, int y1, int x2, int y2) { return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2)); } public int mDis(int x1, int y1, int x2, int y2) { return Math.Abs(x1 - x2) + Math.Abs(y1 - y2); } public int[] DigArr(int n) { int[] ret = new int[Digit(n)]; ret.Length.REP(i => ret[i] = DigVal(n, i + 1)); return ret; } public long DigArr2Num(IEnumerable<int> enu) { return enu.Aggregate((v, n) => v * 10 + n); } public int Digit(long n) { return (n == 0) ? 1 : (int)Math.Log10(n) + 1; } public int DigVal(int n, int dig) { return (n % (int)Pow(10, dig)) / (int)Pow(10, dig - 1); } public long Tousa(long a, long d, long n) { return a + (n - 1) * d; } public long TousaSum(long a, long d, long n) { return n * (2 * a + (n - 1) * d) / 2; } public long[] EnuDivsor(long N) { var ret = new SortedSet<long>(); for (long i = 1; i * i <= N; i++) if (N % i == 0) { ret.Add(i); ret.Add(N / i); } return ret.ToArray(); } public Dictionary<long, long> PrimeFactor(long n) { var ret = new Dictionary<long, long>(); for (int i = 2; i * i <= n; ++i) { if (!ret.ContainsKey(i)) ret[i] = 0; while (n % i == 0) { ++ret[i]; n /= i; } } return ret.Where(kp => kp.Value != 0).ToDictionary(kp => kp.Key, kp => kp.Value); } public IEnumerable<int[]> enuP(int[] Arr, int Use = -1) {//列挙順列 Use = (Use != -1) ? Use : Arr.Length; if (Use == 0 || Arr.Length < Use) yield break; var s = new Stack<List<int>>(); for (int i = Arr.Length - 1; i >= 0; i--) s.Push(new List<int>() { i }); while (s.Count > 0) { var cur = s.Pop(); if (cur.Count == Use) { var ret = new List<int>(); cur.ForEach(X => ret.Add(Arr[X])); yield return ret.ToArray(); } else for (int i = Arr.Length - 1; i >= 0; i--) if (!cur.Contains(i)) s.Push(new List<int>(cur) { i }); } } public IEnumerable<int[]> enuC(int[] Arr, int Use = -1) {//列挙組み合わせ Use = (Use != -1) ? Use : Arr.Length; if (Use == 0 || Arr.Length < Use) yield break; var s = new Stack<Tuple<int, List<int>>>(); Arr.Length.REPR(i => s.Push(Tuple.Create(i, new List<int>() { Arr[i] }))); while (s.Count > 0) { var cur = s.Pop(); if (cur.Item2.Count == Use) yield return cur.Item2.ToArray(); else for (int i = Arr.GetUpperBound(0); i > cur.Item1; i--) s.Push(Tuple.Create(i, new List<int>(cur.Item2) { Arr[i] })); } } public IEnumerable<int[]> enuDupP(int[] Arr, int Use = -1) {//列挙重複順列 Use = (Use != -1) ? Use : Arr.Length; if (Use == 0) yield break; var s = new Stack<List<int>>(); Arr.Length.REPR(i => s.Push(new List<int>() { Arr[i] })); while (s.Count > 0) { var cur = s.Pop(); if (cur.Count == Use) yield return cur.ToArray(); else Arr.Length.REPR(i => s.Push(new List<int>(cur) { Arr[i] })); } } public IEnumerable<int[]> enuDupC(int[] Arr, int Use = -1) {//列挙組み合わせ Use = (Use != -1) ? Use : Arr.Length; if (Use == 0) yield break; var s = new Stack<Tuple<int, List<int>>>(); Arr.Length.REPR(i => s.Push(Tuple.Create(i, new List<int>() { Arr[i] }))); while (s.Count > 0) { var cur = s.Pop(); if (cur.Item2.Count == Use) yield return cur.Item2.ToArray(); else for (int i = Arr.GetUpperBound(0); i >= cur.Item1; i--) s.Push(Tuple.Create(i, new List<int>(cur.Item2) { Arr[i] })); } } public IEnumerable<string[]> enuPart(string str) { var s = new Stack<Tuple<string, List<string>, int>>(); s.Push(Tuple.Create(str[0].ToString(), new List<string>(), 1)); while (s.Count > 0) { var cur = s.Pop(); if (cur.Item3 >= str.Length) yield return (new List<string>(cur.Item2) { cur.Item1 }).ToArray(); else { s.Push(Tuple.Create(cur.Item1 + str[cur.Item3], new List<string>(cur.Item2), cur.Item3 + 1)); s.Push(Tuple.Create(str[cur.Item3].ToString(), new List<string>(cur.Item2) { cur.Item1 }, cur.Item3 + 1)); } } } } #endregion #region Data class AssociativeArray<T> : IEnumerable { public Dictionary<T, int> dic; public AssociativeArray() { dic = new Dictionary<T, int>(); } public AssociativeArray(params T[] a) { dic = new Dictionary<T, int>(); Add(a); } public void Add(T a) { if (!conK(a)) dic[a] = 0; dic[a]++; } public void Add(params T[] a) { a.Length.REP(i => { if (!conK(a[i])) dic[a[i]] = 0; dic[a[i]]++; }); } public void Set(T k, int v) { if (!dic.ContainsKey(k)) dic[k] = 0; dic[k] = v; } public void Remove(params T[] a) { a.Length.REP(i => { if (conK(a[i])) dic.Remove(a[i]); }); } public T[] Keys() { return dic.Keys.ToArray<T>(); } public int Val(T k) { return (dic.ContainsKey(k)) ? dic[k] : 0; } public int ValSum => dic.Values.Sum(); public int KeyNum => dic.Keys.Count; public int MaxVal => dic.Values.Max(); public int MinVal => dic.Values.Min(); public T MaxKey => MaxK(); public T MinKey => MinK(); public T MaxK() { var maxV = MaxVal; return dic.First(d => d.Value == maxV).Key; } public T MinK() { var minV = MinVal; return dic.First(d => d.Value == minV).Key; } public T[] MaxKeys() { var maxV = MaxVal; return dic.Where(kp => kp.Value == maxV).ToDictionary(kp => kp.Key, kp => kp.Value).Keys.ToArray(); } public T[] MinKeys() { var minV = MinVal; return dic.Where(kp => kp.Value == minV).ToDictionary(kp => kp.Key, kp => kp.Value).Keys.ToArray(); } public bool conK(T k) { return dic.ContainsKey(k); } public bool anyK(params T[] k) { return k.Any(key => conK(key)); } public bool allK(params T[] k) { return k.All(key => conK(key)); } public void Show() { foreach (var v in dic) { Console.WriteLine(v.Key + " : " + v.Value); } } public T[] ValueSortedKey(bool inc = true) { return (inc ? (dic.OrderBy(kp => kp.Value)) : (dic.OrderByDescending(kp => kp.Value))) .ThenBy(kp => kp.Key).ToDictionary(kp => kp.Key, kp => kp.Value).Keys.ToArray(); } public IEnumerator GetEnumerator() { foreach (var kp in dic) yield return kp; } //:sort->array } class TreeDis {//TODO:shortestPath public List<Tuple<long, long>>[] g; public long[] a2other; private int type; public TreeDis(int type = 0) { this.type = type; }//0->bfs,other->dfs public void Init(long n) { g = new List<Tuple<long, long>>[n + 1]; g.Length.REP(i => g[i] = new List<Tuple<long, long>>()); } public void Run(long[] a, long[] b) { a.Length.REP(i => { g[a[i]].Add(Tuple.Create(b[i], 1L)); g[b[i]].Add(Tuple.Create(a[i], 1L)); }); } public void Run(long[] a, long[] b, long[] w) { a.Length.REP(i => { g[a[i]].Add(Tuple.Create(b[i], w[i])); g[b[i]].Add(Tuple.Create(a[i], w[i])); }); } public long[] a2iArr(long a) { a2other = new long[g.Count()]; if (type == 0) BFS(a); else DFS(a); return a2other; } private void BFS(long a) { var q = new Queue<Tuple<long, long>>(); q.Enqueue(Tuple.Create(a, -1L)); while (q.Count > 0) { var c = q.Dequeue(); foreach (var v in g[c.Item1]) { if (v.Item1 == c.Item2) continue; a2other[v.Item1] = a2other[c.Item1] + v.Item2; q.Enqueue(Tuple.Create(v.Item1, c.Item1)); } } } private void DFS(long a) { var s = new Stack<Tuple<long, long>>(); s.Push(Tuple.Create(a, -1L)); while (s.Count > 0) { var c = s.Pop(); foreach (var v in g[c.Item1]) { if (v.Item1 == c.Item2) continue; a2other[v.Item1] = a2other[c.Item1] + v.Item2; s.Push(Tuple.Create(v.Item1, c.Item1)); } } } } class ShortestPath { protected int I = -1; //辺は1~N protected int V; //頂点数 protected int E; //辺の数 protected bool isNonDir = true; //有向? public long INF = (long)1e15; //初期化 public long[] cost; //重み public List<Tuple<int, long>>[] Adj;//Adj[from]=(to,cost) public void Init(int n) { I = n + 1; V = n; Adj = new List<Tuple<int, long>>[I]; for (int i = 0; i < I; ++i) Adj[i] = new List<Tuple<int, long>>(); } public void AddPath(int f, int t, long c = 1) { E++; Adj[f].Add(Tuple.Create(t, c)); if (isNonDir) Adj[t].Add(Tuple.Create(f, c)); } public void AddPath(int[] f, int[] t, long[] c) { for (int i = 0; i < f.Length; ++i) AddPath(f[i], t[i], c[i]); } public void AddPath(int[] f, int[] t) { for (int i = 0; i < f.Length; ++i) AddPath(f[i], t[i]); } } class Dijkstra : ShortestPath {//隣接対応後検証不足,有向とか public Dijkstra(bool isNonDir = true) { this.isNonDir = isNonDir; } public long MinCost(int f, int t) { Run(f); return cost[t]; } public long MinCost(int t) { return cost[t]; } public void Run(int f) { cost = new long[I]; for (int i = 0; i < I; ++i) cost[i] = INF; cost[f] = 0; var pq = new PQueue<Tuple<int, long>>(); pq.Enqueue(Tuple.Create(f, 0L));//(from,cost) while (!pq.Empty()) { var cur = pq.Dequeue(); //if (cost[cur.Item1] != cur.Item2) continue; if (cost[cur.Item1] < cur.Item2) continue; for (int i = 0; i < Adj[cur.Item1].Count; ++i) { var tmp = Adj[cur.Item1][i]; if (cost[tmp.Item1] > cur.Item2 + tmp.Item2) { cost[tmp.Item1] = cur.Item2 + tmp.Item2; pq.Enqueue(Tuple.Create(tmp.Item1, cost[tmp.Item1])); } } } } public bool PathExist(int t) { return cost[t] != INF; } } class BellmanFord : ShortestPath { private bool[] neg; public BellmanFord() { } public BellmanFord(bool isNonDir) { this.isNonDir = isNonDir; } public long MinCost(int f, int t) { cost = new long[I]; cost.Set(INF); cost[f] = 0; neg = new bool[I]; for (int i = 0; i < I - 1; i++) { I.REP(j => Adj[j].Count.REP(k => { var cur = Adj[j][k]; if (cost[cur.Item1] > cost[j] + cur.Item2) cost[cur.Item1] = cost[j] + cur.Item2; })); } for (int i = 0; i < I; i++) { I.REP(j => Adj[j].Count.REP(k => { var cur = Adj[j][k]; if (cost[cur.Item1] > cost[j] + cur.Item2) { cost[cur.Item1] = cost[j] + cur.Item2; neg[cur.Item1] = true; } if (neg[j]) neg[cur.Item1] = true; })); } return cost[t]; } public bool loopExist() { return neg[I - 1]; } } class WF : ShortestPath { public WF() { } public WF(bool isNonDir) { this.isNonDir = isNonDir; } public void Run() { } } class WarshallFloyd { private int E; private bool isNonDir; public long INF = (long)1e15; public long[,] BefG; public long[,] G; public WarshallFloyd(bool isNonDir = true) { this.isNonDir = isNonDir; } public void Init(int n) { E = n + 1; G = new long[E, E]; BefG = new long[E, E]; for (int i = 0; i < E; ++i) for (int j = 0; j < E; ++j) { G[i, j] = INF; BefG[i, j] = INF; } for (int i = 0; i < E; ++i) { G[i, i] = 0; BefG[i, i] = 0; } } public void AddPath(int f, int t, long c = 1) { if (isNonDir) { G[f, t] = c; G[t, f] = c; BefG[f, t] = c; BefG[t, f] = c; } else { G[f, t] = c; BefG[f, t] = c; } } public void AddPath(int[] f, int[] t) { for (int i = 0; i < f.Length; ++i) AddPath(f[i], t[i], 1); } public void AddPath(int[] f, int[] t, long[] c) { for (int i = 0; i < f.Length; ++i) AddPath(f[i], t[i], c[i]); } public void Run() { G = MinCostArr(); } public long[,] MinCostArr() { for (int i = 0; i < E; ++i) for (int j = 0; j < E; ++j) for (int k = 0; k < E; ++k) G[j, k] = Math.Min(G[j, k], G[j, i] + G[i, k]); return G; } //使う?使わない? public int[] MinPath(int from, int to) { var ret = new List<int>(); var cur = from; while (cur != to) { ret.Add(cur); for (int i = 1; i < E; ++i) { if (BefG[cur, i] + G[i, to] == G[cur, to]) { if (i == cur) continue; cur = i; break; } } } ret.Add(cur); return ret.ToArray(); } public bool isMinPath(int a, int b, long c) { for (int i = 0; i < E; ++i) if (G[i, a] + c == G[i, b]) return true; return false; } //全地点間を繋ぐ最小コスト public long MinCost() { long orig = 0; for (int i = 0; i < E; ++i) for (int j = i + 1; j < E; ++j) { bool isOrig = true; for (int k = 0; k < E; ++k) { if (k == i || k == j) continue; if (G[i, j] == G[i, k] + G[k, j]) { isOrig = false; break; } } if (isOrig) orig += G[i, j]; } return orig; } } class UnionFind { int[] dat; public void Init(int n) { dat = new int[n + 1]; for (int i = 0; i <= n; ++i) dat[i] = -1; } public void Unite(int x, int y) { x = Root(x); y = Root(y); if (x == y) return; if (dat[y] < dat[x]) swap(ref x, ref y); dat[x] += dat[y]; dat[y] = x; } public bool Find(int x, int y) { return Root(x) == Root(y); } public int Root(int x) { return dat[x] < 0 ? x : dat[x] = Root(dat[x]); } public int Size(int x) { return -dat[Root(x)]; } void swap(ref int a, ref int b) { int tmp = b; b = a; a = tmp; } } class Kruskal : ShortestPath { public Kruskal() { } public Kruskal(bool isNonDir) { this.isNonDir = isNonDir; } public long Run() { var uf = new UnionFind(); var ret = 0L; var L = new List<Tuple<int, int, long>>(); uf.Init(V); for (int i = 0; i < I; ++i) for (int j = 0; j < Adj[i].Count; ++i) L.Add(Tuple.Create(i, Adj[i][j].Item1, Adj[i][j].Item2)); L = L.OrderBy(t => t.Item3).ToList(); for (int i = 0; i < L.Count; ++i) if (!uf.Find(L[i].Item1, L[i].Item2)) { ret += L[i].Item3; uf.Unite(L[i].Item1, L[i].Item2); } return ret; } } #endregion #region Ex static class StringEX { public static string Reversed(this string s) { return string.Join("", s.Reverse()); } public static string Repeat(this string s, int n) { return string.Concat(Enumerable.Repeat(s, n).ToArray()); } public static int toInt(this string s) { int n; return (int.TryParse(s.TrimStart('0'), out n)) ? n : 0; } public static int toInt(this char c) { return toInt(c.ToString()); } public static int toInt(this char[] c) { return toInt(new string(c)); } public static long toLong(this string s) { long n; return (long.TryParse(s.TrimStart('0'), out n)) ? n : (long)0; } public static long toLong(this char c) { return toLong(c.ToString()); } public static long toLong(this char[] c) { return toLong(new string(c)); } public static string toString(this char[] c) { return new string(c); } } static class NumericEx { public static string pad0<T>(this T v, int n) { return v.ToString().PadLeft(n, '0'); } public static double RoundOff(this double v, int n) { return Math.Round(v, n - 1, MidpointRounding.AwayFromZero); } public static bool Odd(this int v) { return v % 2 != 0; } public static bool Odd(this long v) { return v % 2 != 0; } public static void REP(this int v, Action<int> act) { for (int i = 0; i < v; ++i) act(i); } public static void REPR(this int v, Action<int> act) { for (int i = v - 1; i >= 0; --i) act(i); } } static class ArrayEX { public static T[] Sort<T>(this T[] a) { Array.Sort(a); return a; } public static T[] SortR<T>(this T[] a) { Array.Sort(a); Array.Reverse(a); return a; } public static void Set<T>(this T[] a, T v) { a.Length.REP(i => a[i] = v); } public static void Set<T>(this T[,] a, T v) { a.GetLength(0).REP(i => a.GetLength(1).REP(j => a[i, j] = v)); } public static int[] toIntArr(this string[] a) { return Array.ConvertAll(a, int.Parse); } public static long[] toLongArr(this string[] a) { return Array.ConvertAll(a, long.Parse); } public static double[] toDoubleArr(this string[] a) { return Array.ConvertAll(a, double.Parse); } public static char[] toCharArr(this string[] a) { return Array.ConvertAll(a, char.Parse); } } static class BitEx { public static bool Any(this BitArray b) { foreach (bool f in b) if (f) return true; return false; } public static bool All(this BitArray b) { foreach (bool f in b) if (!f) return false; return true; } public static bool None(this BitArray b) { return !Any(b); } public static void Flip(this BitArray b, int index) { b.Set(index, !b.Get(index)); } } static class IEnumerableEx { } #endregion } Code 2: fun main(args:Array<String>) =readLine()?.let { println(it.filter{ it == '1'}.length) }
Java
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int judge=0, k=sc.nextInt(), a=sc.nextInt(), b=sc.nextInt(); for(int i=a; i<=b; i++){ if(i%k==0){ judge=1; break; } } if(judge==1) System.out.print("OK"); else System.out.print("NG"); } }
C++
#include <bits/stdc++.h> using namespace std; #define CIN2(a,b) long long a,b;cin >> a >> b; #define CIN3(a,b,c) long long a,b,c;cin >> a >> b >> c; #define rep(i,n) for(int i=0,i##_len=(n); i<i##_len; ++i) int main(){ char c; char ans; scanf("%c",&c); switch(c){ case 'A':ans='T';break; case 'T':ans='A';break; case 'C':ans='G';break; case 'G':ans='C';break; } cout << ans << endl; }
No
Do these codes solve the same problem? Code 1: import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int judge=0, k=sc.nextInt(), a=sc.nextInt(), b=sc.nextInt(); for(int i=a; i<=b; i++){ if(i%k==0){ judge=1; break; } } if(judge==1) System.out.print("OK"); else System.out.print("NG"); } } Code 2: #include <bits/stdc++.h> using namespace std; #define CIN2(a,b) long long a,b;cin >> a >> b; #define CIN3(a,b,c) long long a,b,c;cin >> a >> b >> c; #define rep(i,n) for(int i=0,i##_len=(n); i<i##_len; ++i) int main(){ char c; char ans; scanf("%c",&c); switch(c){ case 'A':ans='T';break; case 'T':ans='A';break; case 'C':ans='G';break; case 'G':ans='C';break; } cout << ans << endl; }
Go
package main import "fmt" func main() { var n int fmt.Scanln(&n) if n < 1000 { fmt.Printf("ABC\n") } else { fmt.Printf("ABD\n") } }
PHP
<?php //error_reporting(0); $N = trim(fgets(STDIN)); //list($A,$B,$C,$D) = explode(" ",trim(fgets(STDIN))); //$A = explode(" ",trim(fgets(STDIN))); if ($N < 1000) { printf("ABC\n"); } else { printf("ABD\n"); }
Yes
Do these codes solve the same problem? Code 1: package main import "fmt" func main() { var n int fmt.Scanln(&n) if n < 1000 { fmt.Printf("ABC\n") } else { fmt.Printf("ABD\n") } } Code 2: <?php //error_reporting(0); $N = trim(fgets(STDIN)); //list($A,$B,$C,$D) = explode(" ",trim(fgets(STDIN))); //$A = explode(" ",trim(fgets(STDIN))); if ($N < 1000) { printf("ABC\n"); } else { printf("ABD\n"); }
Java
import java.util.Scanner; public class Main { public Main() { } private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); new Main().run(); } private void run() { int x = sc.nextInt(); if (x < 1200) { System.out.println("ABC"); } else { System.out.println("ARC"); } } }
Go
package main import "fmt" func main() { var x int fmt.Scan(&x) if x < 1200 { fmt.Println("ABC") } else { fmt.Println("ARC") } }
Yes
Do these codes solve the same problem? Code 1: import java.util.Scanner; public class Main { public Main() { } private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); new Main().run(); } private void run() { int x = sc.nextInt(); if (x < 1200) { System.out.println("ABC"); } else { System.out.println("ARC"); } } } Code 2: package main import "fmt" func main() { var x int fmt.Scan(&x) if x < 1200 { fmt.Println("ABC") } else { fmt.Println("ARC") } }
JavaScript
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})(); var o=GET(require("fs").readFileSync("/dev/stdin","utf8")); console.log(main()); function main(){ var n = o.a(); var a = o.a(); var b = o.a(); var c = Math.min(a,b); var d = Math.max(0,a+b-n) return c+" "+d; }
Go
package main import ( "bufio" "fmt" "math" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) var N, A, B int scanner.Scan() fmt.Sscanf(scanner.Text(), "%d %d %d", &N, &A, &B) ma := min(A, B) mi := max(A+B-N, 0) fmt.Println(ma, mi) } func min(ns ...int) int { ret := math.MaxInt64 for _, n := range ns { if n < ret { ret = n } } return ret } func max(ns ...int) int { ret := math.MinInt64 for _, n := range ns { if n > ret { ret = n } } return ret }
Yes
Do these codes solve the same problem? Code 1: var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})(); var o=GET(require("fs").readFileSync("/dev/stdin","utf8")); console.log(main()); function main(){ var n = o.a(); var a = o.a(); var b = o.a(); var c = Math.min(a,b); var d = Math.max(0,a+b-n) return c+" "+d; } Code 2: package main import ( "bufio" "fmt" "math" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) var N, A, B int scanner.Scan() fmt.Sscanf(scanner.Text(), "%d %d %d", &N, &A, &B) ma := min(A, B) mi := max(A+B-N, 0) fmt.Println(ma, mi) } func min(ns ...int) int { ret := math.MaxInt64 for _, n := range ns { if n < ret { ret = n } } return ret } func max(ns ...int) int { ret := math.MinInt64 for _, n := range ns { if n > ret { ret = n } } return ret }
C++
#include<bits/stdc++.h> using namespace std; const int SIZE = 2005; typedef long long ll; ll A[SIZE], dp[SIZE][SIZE]; pair<int, int> lr[SIZE][SIZE]; bool comp (const pair<ll, ll> &p1, const pair<ll, ll> &p2){ return p1 > p2; } int main(){ int N; cin >> N; lr[0][0] = make_pair(1, N); vector<pair<ll, ll> > big; for (int i = 1; i <= N; i++){ cin >> A[i]; big.push_back(make_pair(A[i], i)); } sort(big.begin(), big.end(), comp); for (int i = 0; i < N; i++){ for (int j = 0; j <= i; j++){ if (dp[i-j+1][j] < dp[i-j][j]+big[i].first*(big[i].second-lr[i-j][j].first)){ dp[i-j+1][j] = dp[i-j][j]+big[i].first*(big[i].second-lr[i-j][j].first); lr[i-j+1][j] = make_pair(lr[i-j][j].first+1, lr[i-j][j].second); } if (dp[i-j][j+1] < dp[i-j][j]+big[i].first*(lr[i-j][j].second-big[i].second)){ dp[i-j][j+1] = dp[i-j][j]+big[i].first*(lr[i-j][j].second-big[i].second); lr[i-j][j+1] = make_pair(lr[i-j][j].first, lr[i-j][j].second-1); } } } ll ans = 0; for (int i = 0; i < N; i++) ans = max(ans, dp[N-i][i]); cout << ans << endl; }
Python
#2020-03-21 import math a,b,c,d = map(float,input().split()) print(math.sqrt((c-a)**2+(d-b)**2))
No
Do these codes solve the same problem? Code 1: #include<bits/stdc++.h> using namespace std; const int SIZE = 2005; typedef long long ll; ll A[SIZE], dp[SIZE][SIZE]; pair<int, int> lr[SIZE][SIZE]; bool comp (const pair<ll, ll> &p1, const pair<ll, ll> &p2){ return p1 > p2; } int main(){ int N; cin >> N; lr[0][0] = make_pair(1, N); vector<pair<ll, ll> > big; for (int i = 1; i <= N; i++){ cin >> A[i]; big.push_back(make_pair(A[i], i)); } sort(big.begin(), big.end(), comp); for (int i = 0; i < N; i++){ for (int j = 0; j <= i; j++){ if (dp[i-j+1][j] < dp[i-j][j]+big[i].first*(big[i].second-lr[i-j][j].first)){ dp[i-j+1][j] = dp[i-j][j]+big[i].first*(big[i].second-lr[i-j][j].first); lr[i-j+1][j] = make_pair(lr[i-j][j].first+1, lr[i-j][j].second); } if (dp[i-j][j+1] < dp[i-j][j]+big[i].first*(lr[i-j][j].second-big[i].second)){ dp[i-j][j+1] = dp[i-j][j]+big[i].first*(lr[i-j][j].second-big[i].second); lr[i-j][j+1] = make_pair(lr[i-j][j].first, lr[i-j][j].second-1); } } } ll ans = 0; for (int i = 0; i < N; i++) ans = max(ans, dp[N-i][i]); cout << ans << endl; } Code 2: #2020-03-21 import math a,b,c,d = map(float,input().split()) print(math.sqrt((c-a)**2+(d-b)**2))
C
#include <stdio.h> int main(void){ int i,a,b,n,s,e; scanf("%d %d\n%d",&a,&b,&n); for(i=0;i<n;++i){ scanf("%d %d",&s,&e); if(b>s&&a<e){ printf("1\n"); return 0; } } printf("0\n"); }
Java
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); int n = scan.nextInt(); int s[] = new int[n]; int f[] = new int[n]; int g = 0; int i; for (i = 0; i < n; i++) { s[i] = scan.nextInt(); f[i] = scan.nextInt(); if (s[i] < a && b < f[i] || s[i] < b && a < f[i]) { g += 0; } else { g += 1; } } if (g == n) { System.out.println(0); } else { System.out.println(1); } } }
Yes
Do these codes solve the same problem? Code 1: #include <stdio.h> int main(void){ int i,a,b,n,s,e; scanf("%d %d\n%d",&a,&b,&n); for(i=0;i<n;++i){ scanf("%d %d",&s,&e); if(b>s&&a<e){ printf("1\n"); return 0; } } printf("0\n"); } Code 2: import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); int n = scan.nextInt(); int s[] = new int[n]; int f[] = new int[n]; int g = 0; int i; for (i = 0; i < n; i++) { s[i] = scan.nextInt(); f[i] = scan.nextInt(); if (s[i] < a && b < f[i] || s[i] < b && a < f[i]) { g += 0; } else { g += 1; } } if (g == n) { System.out.println(0); } else { System.out.println(1); } } }
Python
from collections import deque N,M = map(int,input().split()) G = [None] + [[] for i in range(N)] dist = [None]+[-1]*N ans = [None]+[10**6]*N for _ in range(M): a,b = map(int,input().split()) G[a].append(b) G[b].append(a) deq = deque() dist[1] = 0 deq.append(1) while len(deq) != 0: v = deq.popleft() for i in G[v]: if dist[i] != -1: if dist[v]-dist[i] == 1: ans[v] = i continue dist[i] = dist[v]+1 deq.append(i) print("Yes") for i in range(2,N+1): print(ans[i])
C++
#include <stdio.h> int main(){ int n,b,f,r,v,i,j,p; int A[3][10],B[3][10],C[3][10],D[3][10]; for (i=0;i<4;i++){ for (j=0;j<10;j++){ A[i][j]=0; B[i][j]=0; C[i][j]=0; D[i][j]=0; } } scanf("%d",&n); for (i=0;i<n;i++){ scanf(" %d %d %d %d",&b,&f,&r,&v); if (b==1) { A[f-1][r-1]+=v; } else if (b==2) { B[f-1][r-1]+=v; } else if (b==3) { C[f-1][r-1]+=v; } else if (b==4) { D[f-1][r-1]+=v; } } for (p=0;p<3;p++){ for (i=0;i<3;i++){ for (j=0;j<10;j++){ if (p==0){ printf(" %d",A[i][j]); } else if (p==1){ printf(" %d",B[i][j]); } else if (p==2){ printf(" %d",C[i][j]); } } printf("\n"); } printf("####################\n"); } for (i=0;i<3;i++){ for (j=0;j<10;j++){ printf(" %d",D[i][j]); } printf("\n"); } return 0; }
No
Do these codes solve the same problem? Code 1: from collections import deque N,M = map(int,input().split()) G = [None] + [[] for i in range(N)] dist = [None]+[-1]*N ans = [None]+[10**6]*N for _ in range(M): a,b = map(int,input().split()) G[a].append(b) G[b].append(a) deq = deque() dist[1] = 0 deq.append(1) while len(deq) != 0: v = deq.popleft() for i in G[v]: if dist[i] != -1: if dist[v]-dist[i] == 1: ans[v] = i continue dist[i] = dist[v]+1 deq.append(i) print("Yes") for i in range(2,N+1): print(ans[i]) Code 2: #include <stdio.h> int main(){ int n,b,f,r,v,i,j,p; int A[3][10],B[3][10],C[3][10],D[3][10]; for (i=0;i<4;i++){ for (j=0;j<10;j++){ A[i][j]=0; B[i][j]=0; C[i][j]=0; D[i][j]=0; } } scanf("%d",&n); for (i=0;i<n;i++){ scanf(" %d %d %d %d",&b,&f,&r,&v); if (b==1) { A[f-1][r-1]+=v; } else if (b==2) { B[f-1][r-1]+=v; } else if (b==3) { C[f-1][r-1]+=v; } else if (b==4) { D[f-1][r-1]+=v; } } for (p=0;p<3;p++){ for (i=0;i<3;i++){ for (j=0;j<10;j++){ if (p==0){ printf(" %d",A[i][j]); } else if (p==1){ printf(" %d",B[i][j]); } else if (p==2){ printf(" %d",C[i][j]); } } printf("\n"); } printf("####################\n"); } for (i=0;i<3;i++){ for (j=0;j<10;j++){ printf(" %d",D[i][j]); } printf("\n"); } return 0; }
C++
#include <iostream> using namespace std; struct StNode { StNode* m_poParnt; StNode* m_poLeft; StNode* m_poRigt; int m_nKey; StNode(int nNo) : m_poParnt(nullptr), m_poLeft(nullptr), m_poRigt(nullptr), m_nKey(nNo) { } }; void fnInsert(StNode*& rpoRoot, StNode* poNewNod) { StNode* poParnt = nullptr; StNode* poNode = rpoRoot; while (poNode != nullptr) { poParnt = poNode; if (poNewNod->m_nKey < poNode->m_nKey) poNode = poNode->m_poLeft; else poNode = poNode->m_poRigt; } poNewNod->m_poParnt = poParnt; if (poParnt == nullptr) rpoRoot = poNewNod; else if (poNewNod->m_nKey < poParnt->m_nKey) poParnt->m_poLeft = poNewNod; else poParnt->m_poRigt = poNewNod; } StNode* fnFind(StNode* poRoot, int nNo) { StNode* poNode = poRoot; while (poNode != nullptr) if (nNo == poNode->m_nKey) return poNode; else if (nNo < poNode->m_nKey) poNode = poNode->m_poLeft; else poNode = poNode->m_poRigt; return nullptr; } void fnInOrder(StNode* poNode) { if (poNode == nullptr) return; fnInOrder(poNode->m_poLeft); cout << " " << poNode->m_nKey; fnInOrder(poNode->m_poRigt); } void fnPreOrder(StNode* poNode) { if (poNode == nullptr) return; cout << " " << poNode->m_nKey; fnPreOrder(poNode->m_poLeft); fnPreOrder(poNode->m_poRigt); } void fnBinSchTree(StNode*& rpoRoot) { int nMaxSiz; cin >> nMaxSiz; for (int i = 0; i < nMaxSiz; ++i) { string sCmd; cin >> sCmd; if (sCmd[0] == 'i') { int nNo; cin >> nNo; StNode* poNewNod = new StNode(nNo); fnInsert(rpoRoot, poNewNod); } if (sCmd[0] == 'f') { int nNo; cin >> nNo; if (fnFind(rpoRoot, nNo)) cout << "yes" << endl; else cout << "no" << endl; } if (sCmd[0] == 'p') { fnInOrder(rpoRoot); cout << endl; fnPreOrder(rpoRoot); cout << endl; } } } void fnPstOrder(StNode* poNode) { if (poNode == nullptr) return; fnPstOrder(poNode->m_poLeft); fnPstOrder(poNode->m_poRigt); delete poNode; } int main() { cin.tie(0); ios::sync_with_stdio(false); StNode* poRoot = nullptr; fnBinSchTree(poRoot); //fnPstOrder(poRoot); return 0; }
Python
import math #import bisect #import numpy as np #import itertools #import copy import sys ipti = sys.stdin.readline MOD = 10 ** 9 + 7 INF = float('INF') sys.setrecursionlimit(10 ** 5) def main(): n, d = list(map(int,ipti().split())) x = [0] * n for i in range(n): x[i] = list(map(int,ipti().split())) ans = 0 for i in range(n-1): for j in range(i+1, n): temp = 0 for k in range(d): temp += (x[i][k] - x[j][k])**2 for k in range(401): if temp == k**2: ans += 1 print(ans) if __name__ == '__main__': main()
No
Do these codes solve the same problem? Code 1: #include <iostream> using namespace std; struct StNode { StNode* m_poParnt; StNode* m_poLeft; StNode* m_poRigt; int m_nKey; StNode(int nNo) : m_poParnt(nullptr), m_poLeft(nullptr), m_poRigt(nullptr), m_nKey(nNo) { } }; void fnInsert(StNode*& rpoRoot, StNode* poNewNod) { StNode* poParnt = nullptr; StNode* poNode = rpoRoot; while (poNode != nullptr) { poParnt = poNode; if (poNewNod->m_nKey < poNode->m_nKey) poNode = poNode->m_poLeft; else poNode = poNode->m_poRigt; } poNewNod->m_poParnt = poParnt; if (poParnt == nullptr) rpoRoot = poNewNod; else if (poNewNod->m_nKey < poParnt->m_nKey) poParnt->m_poLeft = poNewNod; else poParnt->m_poRigt = poNewNod; } StNode* fnFind(StNode* poRoot, int nNo) { StNode* poNode = poRoot; while (poNode != nullptr) if (nNo == poNode->m_nKey) return poNode; else if (nNo < poNode->m_nKey) poNode = poNode->m_poLeft; else poNode = poNode->m_poRigt; return nullptr; } void fnInOrder(StNode* poNode) { if (poNode == nullptr) return; fnInOrder(poNode->m_poLeft); cout << " " << poNode->m_nKey; fnInOrder(poNode->m_poRigt); } void fnPreOrder(StNode* poNode) { if (poNode == nullptr) return; cout << " " << poNode->m_nKey; fnPreOrder(poNode->m_poLeft); fnPreOrder(poNode->m_poRigt); } void fnBinSchTree(StNode*& rpoRoot) { int nMaxSiz; cin >> nMaxSiz; for (int i = 0; i < nMaxSiz; ++i) { string sCmd; cin >> sCmd; if (sCmd[0] == 'i') { int nNo; cin >> nNo; StNode* poNewNod = new StNode(nNo); fnInsert(rpoRoot, poNewNod); } if (sCmd[0] == 'f') { int nNo; cin >> nNo; if (fnFind(rpoRoot, nNo)) cout << "yes" << endl; else cout << "no" << endl; } if (sCmd[0] == 'p') { fnInOrder(rpoRoot); cout << endl; fnPreOrder(rpoRoot); cout << endl; } } } void fnPstOrder(StNode* poNode) { if (poNode == nullptr) return; fnPstOrder(poNode->m_poLeft); fnPstOrder(poNode->m_poRigt); delete poNode; } int main() { cin.tie(0); ios::sync_with_stdio(false); StNode* poRoot = nullptr; fnBinSchTree(poRoot); //fnPstOrder(poRoot); return 0; } Code 2: import math #import bisect #import numpy as np #import itertools #import copy import sys ipti = sys.stdin.readline MOD = 10 ** 9 + 7 INF = float('INF') sys.setrecursionlimit(10 ** 5) def main(): n, d = list(map(int,ipti().split())) x = [0] * n for i in range(n): x[i] = list(map(int,ipti().split())) ans = 0 for i in range(n-1): for j in range(i+1, n): temp = 0 for k in range(d): temp += (x[i][k] - x[j][k])**2 for k in range(401): if temp == k**2: ans += 1 print(ans) if __name__ == '__main__': main()
C++
#include<iostream> #include<string> #include<vector> #include<algorithm> #include<map> #include<set> #include<cstdio> #include<cmath> #include<numeric> #include<queue> #include<stack> #include<cstring> #include<limits> #include<functional> #include<unordered_set> #include<iomanip> #define rep(i,a) for(int i=(int)0;i<(int)a;++i) #define pb push_back #define eb emplace_back using ll=long long; constexpr ll mod = 1e9 + 7; constexpr ll INF = 1LL << 50; constexpr double pi=3.14159265358979; template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } using namespace std; void solve(){ int a,b; cin>>a>>b; int ans=a-2*b; if(ans<0)cout<<0<<endl; else cout<<ans<<endl; return; } signed main(){ ios::sync_with_stdio(false); cin.tie(0); cout<<fixed<<setprecision(20); solve(); return 0; }
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner scan = new Scanner(System.in); int a = scan.nextInt(); String S = scan.next(); int an = 0; int b = 0; for(int i=0 ;i<a;i++ ){ if('I'==S.charAt(i)){ an++; }else{ an--; } if(b<an){ b=an; } } System.out.println(b); } }
No
Do these codes solve the same problem? Code 1: #include<iostream> #include<string> #include<vector> #include<algorithm> #include<map> #include<set> #include<cstdio> #include<cmath> #include<numeric> #include<queue> #include<stack> #include<cstring> #include<limits> #include<functional> #include<unordered_set> #include<iomanip> #define rep(i,a) for(int i=(int)0;i<(int)a;++i) #define pb push_back #define eb emplace_back using ll=long long; constexpr ll mod = 1e9 + 7; constexpr ll INF = 1LL << 50; constexpr double pi=3.14159265358979; template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } using namespace std; void solve(){ int a,b; cin>>a>>b; int ans=a-2*b; if(ans<0)cout<<0<<endl; else cout<<ans<<endl; return; } signed main(){ ios::sync_with_stdio(false); cin.tie(0); cout<<fixed<<setprecision(20); solve(); return 0; } Code 2: import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner scan = new Scanner(System.in); int a = scan.nextInt(); String S = scan.next(); int an = 0; int b = 0; for(int i=0 ;i<a;i++ ){ if('I'==S.charAt(i)){ an++; }else{ an--; } if(b<an){ b=an; } } System.out.println(b); } }
Java
import java.util.*; import java.io.*; public class Main { void solve() { int r = in.nextInt(), c = in.nextInt(); int[] cnt = new int[26]; for (int i = 0; i < r; i++) { for (char ch : in.nextToken().toCharArray()){ cnt[ch - 'a']++; } } int cnt4 = (r / 2) * (c / 2); int cnt2 = (r / 2) * (c % 2) + (c / 2) * (r % 2); int cnt1 = (r % 2) * (c % 2); for (int i = 0; i < 26; i++) { while (cnt[i] >= 4 && cnt4 > 0) { cnt[i] -= 4; cnt4--; } } for (int i = 0; i < 26; i++) { while (cnt[i] >= 2 && cnt2 > 0) { cnt[i] -= 2; cnt2--; } } for (int i = 0; i < 26; i++) { while (cnt[i] >= 1 && cnt1 > 0) { cnt[i] -= 1; cnt1--; } } out.println((cnt1 == 0 && cnt2 == 0 && cnt4 == 0) ? "Yes" : "No"); } FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new Main().run(); } }
TypeScript
declare function require(x: string): any; var input = require("fs").readFileSync("/dev/stdin", "utf8"); input = input.split("\n"); const [h, w] = input[0].split(" ").map((x: string): number => +x); const a = new Array<number>(26); for (let i = 0; i < 26; i++) a[i] = 0; for (let i = 0; i < h; i++) { for (let ii = 0; ii < w; ii++) { const index = input[i + 1][ii].charCodeAt() - "a".charCodeAt(0); a[index] += 1; } } a.sort().reverse(); let c4 = Math.floor(h / 2) * Math.floor(w / 2); let c2 = 0; let c1 = 0; if (w % 2 != 0 && h % 2 != 0) { c2 = Math.floor(w / 2) + Math.floor(h / 2); c1 = 1; } else if (w % 2 != 0) { c2 = Math.floor(h / 2); } else if (h % 2 != 0) { c2 = Math.floor(w / 2); } // 貪欲 let index = 0; while (c4 > 0 && index < 26) { if (a[index] >= 4) { a[index] -= 4; c4 -= 1; } else { index += 1; } } if(c4>0){ console.log("No"); } else{ let index = 0; while (c2 > 0 && index < 26) { if (a[index] >= 2) { a[index] -= 2; c2 -= 1; } else { index += 1; } } if(c2>0){ console.log("No"); } else{ let index = 0; while (c1 > 0 && index < 26) { if (a[index] >= 1) { a[index] -= 1; c1 -= 1; } else { index += 1; } } if(c2>0){ console.log("No"); } else{ let flg_yes = true; for(let i=0; i<26; i++){ if(a[i]!=0) { flg_yes = false; break; } } if(flg_yes) console.log("Yes"); else console.log("No"); } } }
Yes
Do these codes solve the same problem? Code 1: import java.util.*; import java.io.*; public class Main { void solve() { int r = in.nextInt(), c = in.nextInt(); int[] cnt = new int[26]; for (int i = 0; i < r; i++) { for (char ch : in.nextToken().toCharArray()){ cnt[ch - 'a']++; } } int cnt4 = (r / 2) * (c / 2); int cnt2 = (r / 2) * (c % 2) + (c / 2) * (r % 2); int cnt1 = (r % 2) * (c % 2); for (int i = 0; i < 26; i++) { while (cnt[i] >= 4 && cnt4 > 0) { cnt[i] -= 4; cnt4--; } } for (int i = 0; i < 26; i++) { while (cnt[i] >= 2 && cnt2 > 0) { cnt[i] -= 2; cnt2--; } } for (int i = 0; i < 26; i++) { while (cnt[i] >= 1 && cnt1 > 0) { cnt[i] -= 1; cnt1--; } } out.println((cnt1 == 0 && cnt2 == 0 && cnt4 == 0) ? "Yes" : "No"); } FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new Main().run(); } } Code 2: declare function require(x: string): any; var input = require("fs").readFileSync("/dev/stdin", "utf8"); input = input.split("\n"); const [h, w] = input[0].split(" ").map((x: string): number => +x); const a = new Array<number>(26); for (let i = 0; i < 26; i++) a[i] = 0; for (let i = 0; i < h; i++) { for (let ii = 0; ii < w; ii++) { const index = input[i + 1][ii].charCodeAt() - "a".charCodeAt(0); a[index] += 1; } } a.sort().reverse(); let c4 = Math.floor(h / 2) * Math.floor(w / 2); let c2 = 0; let c1 = 0; if (w % 2 != 0 && h % 2 != 0) { c2 = Math.floor(w / 2) + Math.floor(h / 2); c1 = 1; } else if (w % 2 != 0) { c2 = Math.floor(h / 2); } else if (h % 2 != 0) { c2 = Math.floor(w / 2); } // 貪欲 let index = 0; while (c4 > 0 && index < 26) { if (a[index] >= 4) { a[index] -= 4; c4 -= 1; } else { index += 1; } } if(c4>0){ console.log("No"); } else{ let index = 0; while (c2 > 0 && index < 26) { if (a[index] >= 2) { a[index] -= 2; c2 -= 1; } else { index += 1; } } if(c2>0){ console.log("No"); } else{ let index = 0; while (c1 > 0 && index < 26) { if (a[index] >= 1) { a[index] -= 1; c1 -= 1; } else { index += 1; } } if(c2>0){ console.log("No"); } else{ let flg_yes = true; for(let i=0; i<26; i++){ if(a[i]!=0) { flg_yes = false; break; } } if(flg_yes) console.log("Yes"); else console.log("No"); } } }
Python
N = int(input()) A = [int(i) for i in input().split()] ret = 0 for i in range(1, N) : if A[i] <= A[i - 1] : ret += 1 print(ret + 1) print(N)
Java
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] nums=new int[n]; for(int i=0;i<n;i++)nums[i]=sc.nextInt(); int ans=1; for(int i=0;i<n-1;i++){ if(nums[i]>=nums[i+1])ans++; } System.out.println(ans); System.out.println(n); } }
Yes
Do these codes solve the same problem? Code 1: N = int(input()) A = [int(i) for i in input().split()] ret = 0 for i in range(1, N) : if A[i] <= A[i - 1] : ret += 1 print(ret + 1) print(N) Code 2: import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] nums=new int[n]; for(int i=0;i<n;i++)nums[i]=sc.nextInt(); int ans=1; for(int i=0;i<n-1;i++){ if(nums[i]>=nums[i+1])ans++; } System.out.println(ans); System.out.println(n); } }
Python
a=list(map(int,input().split())) print(max(a[0]*a[-1],a[0]*a[-2],a[1]*a[-1],a[1]*a[-2]))
C++
#include <bits/stdc++.h> using namespace std; const double pi = 3.1415926535; /********************************************************************/ #define M1 1000000007 #define M2 998244353 #define ll long long #define pll pair<ll,ll> #define REP(i,a,b) for(ll i=a;i<b;i++) #define REPR(i,a,b) for(ll i=b-1;i>=a;i--) #define forr(i,n) for(ll i=0;i<n;i++) #define F first #define S second #define pb push_back #define DB pop_back #define mp make_pair #define MT make_tuple #define V(a) vector<a> #define vi vector<ll> #define endl '\n' #define ce(ele) cout<<ele<<' ' #define cs(ele) cout<<ele<<'\n' #define CASE(t) ll t; cin>>t; while(t--) void FAST() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); } ll gcd(ll x, ll y) { if (x == 0) return y; return gcd(y % x, x); } ll powM(ll x, ll y, ll m) { ll ans = 1, r = 1; x %= m; while (r > 0 && r <= y) { if (r & y) { ans *= x; ans %= m; } r <<= 1; x *= x; x %= m; } return ans; } map<long long, long long> factorize(long long n) { map<long long, long long> ans; for (long long i = 2; i * i <= n; i++) { while (n % i == 0) { ans[i]++; n /= i; } } if (n > 1) { ans[n]++; n = 1; } return ans; } /* **********END OF TEMPLATE*********** */ const int mx = 1e5 + 5; //dfs queue<int> q; //bool visited[N]; ll ddd[mx] = {}; vector<ll> adj[mx]; bool visited[mx]; /* void bfs(int x) { visited[x] = true; distance[x] = 0; q.push(x); while (!q.empty()) { int s = q.front(); q.pop(); // process node s //CODE HERE: for (auto u : adj[s]) { if (visited[u]) continue; visited[u] = true; distance[u] = distance[s] + 1; q.push(u); } } } */ int main() { FAST(); ll n, m; cin >> n >> m; while (m--) { ll a, b; cin >> a >> b; a--; b--; adj[a].pb(b); adj[b].pb(a); } int x = 0; visited[x] = true; ddd[x] = 0; q.push(x); while (!q.empty()) { int s = q.front(); q.pop(); // process node s //CODE HERE: for (auto u : adj[s]) { if (visited[u]) continue; visited[u] = true; ddd[u] = ddd[s] + 1; q.push(u); } } bool ok = true; for (int i = 0; i < n; i++) { ok &= visited[i]; } if (!ok) { cout << "No"; } else { cout << "Yes\n"; for (int i = 1; i < n; i++) { ll rr = INT_MAX, city = -1; for (int x : adj[i]) { if (ddd[x] < rr) { rr = ddd[x]; city = x; } } cout << city + 1 << endl; } } return 0; }
No
Do these codes solve the same problem? Code 1: a=list(map(int,input().split())) print(max(a[0]*a[-1],a[0]*a[-2],a[1]*a[-1],a[1]*a[-2])) Code 2: #include <bits/stdc++.h> using namespace std; const double pi = 3.1415926535; /********************************************************************/ #define M1 1000000007 #define M2 998244353 #define ll long long #define pll pair<ll,ll> #define REP(i,a,b) for(ll i=a;i<b;i++) #define REPR(i,a,b) for(ll i=b-1;i>=a;i--) #define forr(i,n) for(ll i=0;i<n;i++) #define F first #define S second #define pb push_back #define DB pop_back #define mp make_pair #define MT make_tuple #define V(a) vector<a> #define vi vector<ll> #define endl '\n' #define ce(ele) cout<<ele<<' ' #define cs(ele) cout<<ele<<'\n' #define CASE(t) ll t; cin>>t; while(t--) void FAST() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); } ll gcd(ll x, ll y) { if (x == 0) return y; return gcd(y % x, x); } ll powM(ll x, ll y, ll m) { ll ans = 1, r = 1; x %= m; while (r > 0 && r <= y) { if (r & y) { ans *= x; ans %= m; } r <<= 1; x *= x; x %= m; } return ans; } map<long long, long long> factorize(long long n) { map<long long, long long> ans; for (long long i = 2; i * i <= n; i++) { while (n % i == 0) { ans[i]++; n /= i; } } if (n > 1) { ans[n]++; n = 1; } return ans; } /* **********END OF TEMPLATE*********** */ const int mx = 1e5 + 5; //dfs queue<int> q; //bool visited[N]; ll ddd[mx] = {}; vector<ll> adj[mx]; bool visited[mx]; /* void bfs(int x) { visited[x] = true; distance[x] = 0; q.push(x); while (!q.empty()) { int s = q.front(); q.pop(); // process node s //CODE HERE: for (auto u : adj[s]) { if (visited[u]) continue; visited[u] = true; distance[u] = distance[s] + 1; q.push(u); } } } */ int main() { FAST(); ll n, m; cin >> n >> m; while (m--) { ll a, b; cin >> a >> b; a--; b--; adj[a].pb(b); adj[b].pb(a); } int x = 0; visited[x] = true; ddd[x] = 0; q.push(x); while (!q.empty()) { int s = q.front(); q.pop(); // process node s //CODE HERE: for (auto u : adj[s]) { if (visited[u]) continue; visited[u] = true; ddd[u] = ddd[s] + 1; q.push(u); } } bool ok = true; for (int i = 0; i < n; i++) { ok &= visited[i]; } if (!ok) { cout << "No"; } else { cout << "Yes\n"; for (int i = 1; i < n; i++) { ll rr = INT_MAX, city = -1; for (int x : adj[i]) { if (ddd[x] < rr) { rr = ddd[x]; city = x; } } cout << city + 1 << endl; } } return 0; }
Python
def nbasesum(value,n): nbasevalue = 0 while value > 0: nbasevalue += value%n value //= n return nbasevalue N = int(input()) ans = nbasesum(N,9) for i in range(N+1): c6 = i c9 = N-i ans = min(ans, nbasesum(c9,9)+nbasesum(c6,6)) print(ans)
C++
#include <cstdio> #include <cstring> #include <string> #include <iostream> #include <cmath> #include <vector> #include <map> #include <set> #include <queue> #include <deque> #include <algorithm> using namespace std; typedef long long int ll; typedef pair<int, int> P; int main() { vector<int> v[1407]; int p=37; int n=p*(p+1)+1, k=p+1; for(int i=0; i<k; i++){ v[i].push_back(1); for(int j=0; j<p; j++){ v[i].push_back(2+i*p+j); } } for(int i=0; i<p; i++){ for(int j=0; j<p; j++){ v[k+i*p+j].push_back(i+2); for(int t=0; t<p; t++){ v[k+i*p+j].push_back(p+2+t*p+(i*t+j)%p); } } } cout<<n<<" "<<k<<endl; for(int i=0; i<n; i++){ for(auto x:v[i]) cout<<x<<" "; cout<<endl; } return 0; }
No
Do these codes solve the same problem? Code 1: def nbasesum(value,n): nbasevalue = 0 while value > 0: nbasevalue += value%n value //= n return nbasevalue N = int(input()) ans = nbasesum(N,9) for i in range(N+1): c6 = i c9 = N-i ans = min(ans, nbasesum(c9,9)+nbasesum(c6,6)) print(ans) Code 2: #include <cstdio> #include <cstring> #include <string> #include <iostream> #include <cmath> #include <vector> #include <map> #include <set> #include <queue> #include <deque> #include <algorithm> using namespace std; typedef long long int ll; typedef pair<int, int> P; int main() { vector<int> v[1407]; int p=37; int n=p*(p+1)+1, k=p+1; for(int i=0; i<k; i++){ v[i].push_back(1); for(int j=0; j<p; j++){ v[i].push_back(2+i*p+j); } } for(int i=0; i<p; i++){ for(int j=0; j<p; j++){ v[k+i*p+j].push_back(i+2); for(int t=0; t<p; t++){ v[k+i*p+j].push_back(p+2+t*p+(i*t+j)%p); } } } cout<<n<<" "<<k<<endl; for(int i=0; i<n; i++){ for(auto x:v[i]) cout<<x<<" "; cout<<endl; } return 0; }
JavaScript
var input = require('fs').readFileSync('/dev/stdin', 'utf8'); var arr = input.trim().split("\n").map(Number); var a = arr[0]; var b = arr[1]; var c = arr[2]; var d = arr[3]; var e = arr[4]; var t = 0; if (a < 0) { t += Math.abs(a) * c + d; a = 0; } t += (b - a) * e; console.log(t);
Go
package main import ( "bufio" "fmt" "os" "strconv" ) var scanner = bufio.NewScanner(os.Stdin) func nextInt() (int, error) { return strconv.Atoi(nextString()) } func nextString() string { scanner.Scan() return scanner.Text() } func main() { scanner.Split(bufio.ScanWords) startTemp, _ := nextInt() targetTemp, _ := nextInt() deltaFrozen, _ := nextInt() deltaZero, _ := nextInt() deltaNotFrozen, _ := nextInt() requiredTime := 0 if startTemp < 0 { requiredTime += -startTemp * deltaFrozen } if startTemp <= 0 { requiredTime += deltaZero } if startTemp <= 0 { requiredTime += targetTemp * deltaNotFrozen } else { requiredTime += (targetTemp - startTemp) * deltaNotFrozen } fmt.Println(requiredTime) }
Yes
Do these codes solve the same problem? Code 1: var input = require('fs').readFileSync('/dev/stdin', 'utf8'); var arr = input.trim().split("\n").map(Number); var a = arr[0]; var b = arr[1]; var c = arr[2]; var d = arr[3]; var e = arr[4]; var t = 0; if (a < 0) { t += Math.abs(a) * c + d; a = 0; } t += (b - a) * e; console.log(t); Code 2: package main import ( "bufio" "fmt" "os" "strconv" ) var scanner = bufio.NewScanner(os.Stdin) func nextInt() (int, error) { return strconv.Atoi(nextString()) } func nextString() string { scanner.Scan() return scanner.Text() } func main() { scanner.Split(bufio.ScanWords) startTemp, _ := nextInt() targetTemp, _ := nextInt() deltaFrozen, _ := nextInt() deltaZero, _ := nextInt() deltaNotFrozen, _ := nextInt() requiredTime := 0 if startTemp < 0 { requiredTime += -startTemp * deltaFrozen } if startTemp <= 0 { requiredTime += deltaZero } if startTemp <= 0 { requiredTime += targetTemp * deltaNotFrozen } else { requiredTime += (targetTemp - startTemp) * deltaNotFrozen } fmt.Println(requiredTime) }
C++
#pragma GCC optimize("O2,Ofast,inline,unroll-all-loops,-ffast-math") #pragma GCC target("popcnt") #include <bits/stdc++.h> #define maxn 400010 #define i128 __int128 #define ll long long #define ull unsigned long long #define ld long double #define fi first #define se second #define pb push_back #define eb emplace_back #define pob pop_back #define pf push_front #define pof pop_front #define pii pair<int, int> #define pil pair<int, ll> #define pll pair<ll, ll> #define IL inline #define ss system using namespace std; ll p, ans = 0; struct mat { ll v[3][3]; mat(int type = 0) { memset(v, 0, sizeof(v)); if (type) { for (int i = 0; i < 3; i++) { v[i][i] = 1; } } } mat operator * (const mat &rhs) const { mat ret; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { ret.v[i][j] = (ret.v[i][j] + v[i][k] * rhs.v[k][j]) % p; } } } return ret; } }; i128 n, a, b; template <class T> void read(T &x) { char ch = x = 0; bool fl = false; while (!isdigit(ch)) fl |= ch == '-', ch = getchar(); while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); x = fl ? -x : x; } mat pwm(mat a, i128 b) { mat ret(1); while (b) { if (b & 1) ret = ret * a; a = a * a, b >>= 1; } return ret; } int main() { read(n), read(a), read(b), cin >> p; i128 pw = 1; for (int i = 0; i <= 36; i++, pw *= 10) { i128 l = pw <= a ? 0 : (pw - a - 1) / b + 1, r = min((pw * 10 - 1 - a) / b, n - 1); if (pw > a + (n - 1) * b) break; if (l > r) continue; if (pw * 10 <= a) continue; i128 fst = (a % p + l % p * b) % p; mat base; base.v[0][1] = base.v[1][1] = base.v[1][2] = base.v[2][2] = 1; base.v[0][0] = pw * 10 % p; mat res = pwm(base, r - l + 1); ans = (ans * res.v[0][0] + fst * res.v[0][1] + b % p * res.v[0][2]) % p; } cout << ans << endl; return 0; }
C#
using System; using System.IO; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using E = System.Linq.Enumerable; using MatrixType = ModInt; using System.Numerics; partial class Solver { int getDigitLength(long x) { return x.ToString().Length; } public void Run() { var L = nl(); var A = nl(); var B = nl(); var M = nl(); ModInt.SetModValue((int)M); long ans = 0; var sL_1 = A + B * (L - 1); var s0 = A; var startD = getDigitLength(s0); var endD = getDigitLength(sL_1); var start = s0; var startN = 0L; for (int d = startD; d <= endD; d++) { long lower = startN, upper = L - 1; long end = -1, endN = -1; while (lower <= upper) { var mid = (lower + upper) / 2; long P = A + B * mid; if (P.ToString().Length <= d) { lower = mid + 1; end = P; endN = mid; } else { upper = mid - 1; } } if (end == -1) continue; // not exists var N = endN - startN + 1; //new { d, start, end, N }.Dump(); ans = ans * (int)BigInteger.ModPow(10, BigInteger.One * d * N, M); ans %= M; ans += Count(start, B, d, N, M); ans %= M; start = end + B; startN = endN + 1; } cout.WriteLine(ans); } long Count(long A0, long B, int digit, long N, long M) { long result = 0; { var P = (int)BigInteger.ModPow(10, digit, M); var mat = new Matrix(new ModInt[,] { { P, 0, 0 }, { 1, 1, 0 }, { 0, 1, 1 }, }); var b = new Matrix(new ModInt[,] { { B % M}, { 0 }, { 0 }, }); var R = Matrix.Pow(mat, N) * b; result += R[0, 2].ToInt(); //cout.WriteLine(" " + R[0, 2].ToInt()); } { var P = (int)BigInteger.ModPow(10, digit, M); var mat = new Matrix(new ModInt[,] { { P, 0, 0 }, { 1, 1, 0 }, { 0, 1, 1 }, }); var b = new Matrix(new ModInt[,] { { A0 % M }, { 0 }, { 0 }, }); var R = Matrix.Pow(mat, N) * b; result += R[0, 1].ToInt(); //cout.WriteLine(" " + R[0, 1].ToInt()); } return result % M; } } public struct ModInt { static private int mod = 0; private long value; public ModInt(long x) { this.value = x; Normalize(); } static private long RegularMod(long x, int mod) { if (x >= mod) { if (x < 2 * mod) return x - mod; return x % mod; } if (x >= 0) return x; x = mod - RegularMod(-x, mod); if (x == mod) return 0; return x; } static public void SetModValue(int m) { ModInt.mod = m; } private void Normalize() { this.value = RegularMod(value, mod); } public override string ToString() { return value.ToString(); } public int ToInt() { return (int)this.value; } public static bool operator ==(ModInt c1, ModInt c2) { return c1.value == c2.value; } public static bool operator !=(ModInt c1, ModInt c2) { return !(c1 == c2); } public static ModInt operator +(ModInt x, ModInt y) { return new ModInt(x.value + y.value); } public static ModInt operator -(ModInt x, ModInt y) { return new ModInt(x.value - y.value); } public static ModInt operator *(ModInt x, ModInt y) { return new ModInt(x.value * y.value); } public static ModInt operator /(ModInt x, ModInt y) { return new ModInt(x.value * Inverse(y.value, mod)); } static private long ExtendedGcd(long a, long b, ref long x, ref long y) { if (b == 0) { x = 1; y = 0; return a; } else { long d = ExtendedGcd(b, a % b, ref y, ref x); y -= a / b * x; return d; } } static private long Inverse(long a, long mod) { long x = 0, y = 0; if (ExtendedGcd(a, mod, ref x, ref y) == 1) return (x + mod) % mod; else throw new Exception("Invalid inverse " + a + " " + mod); } public static implicit operator ModInt(long x) { return new ModInt(x); } public override bool Equals(object obj) { if (obj == null) { return false; } return this.value.Equals(((ModInt)obj).value); } public override int GetHashCode() { return this.value.GetHashCode(); } } public class Matrix { public int Row { get; private set; } public int Col { get; private set; } private MatrixType[] Data; public Matrix(int row, int col) { this.Row = row; this.Col = col; this.Data = new MatrixType[Row * Col]; } public Matrix(MatrixType[,] array) : this(array.GetLength(0), array.GetLength(1)) { int index = 0; for (int i = 0; i < Row; i++) { for (int j = 0; j < Col; j++) { Data[index++] = array[i, j]; } } } public MatrixType this[int row, int col] { set { Data[row * Col + col] = value; } get { return Data[row * Col + col]; } } static public Matrix UnitMatrix(int n) { var matrix = new Matrix(n, n); for (int i = 0; i < n; i++) { matrix[i, i] = 1; } return matrix; } static public Matrix operator +(Matrix A, Matrix B) { var C = new Matrix(A.Row, A.Col); for (int i = 0; i < C.Data.Length; i++) { C.Data[i] = A.Data[i] + B.Data[i]; } return C; } static public Matrix operator -(Matrix A, Matrix B) { var C = new Matrix(A.Row, A.Col); for (int i = 0; i < C.Data.Length; i++) { C.Data[i] = A.Data[i] - B.Data[i]; } return C; } static public Matrix operator *(Matrix A, Matrix B) { var C = new Matrix(A.Row, B.Col); for (int i = 0; i < A.Row; i++) { for (int j = 0; j < B.Col; j++) { var val = C[i, j]; for (int k = 0; k < A.Col; k++) val += A[i, k] * B[k, j]; C[i, j] = val; } } return C; } public static implicit operator Matrix(MatrixType[,] array) { return new Matrix(array); } static public Matrix Pow(Matrix A, long n) { if (n == 0) return UnitMatrix(A.Row); Matrix result = A.Clone(), t = A.Clone(); n--; while (n > 0) { if ((n & 1) != 0) { result = result * t; } t = t * t; n >>= 1; } return result; } public Matrix Clone() { return new Matrix(Row, Col) { Data = Data.Clone() as MatrixType[] }; } static private void Swap<T>(ref T a, ref T b) { T t = a; a = b; b = t; } } // PREWRITEN CODE BEGINS FROM HERE partial class Solver : Scanner { public static void Main(string[] args) { #if LOCAL new Solver(Console.In, Console.Out).Run(); #else Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }); new Solver(Console.In, Console.Out).Run(); Console.Out.Flush(); #endif } #pragma warning disable IDE0052 private readonly TextReader cin; private readonly TextWriter cout; #pragma warning restore IDE0052 public Solver(TextReader reader, TextWriter writer) : base(reader) { this.cin = reader; this.cout = writer; } public Solver(string input, TextWriter writer) : this(new StringReader(input), writer) { } #pragma warning disable IDE1006 #pragma warning disable IDE0051 private int ni() { return NextInt(); } private int[] ni(int n) { return NextIntArray(n); } private long nl() { return NextLong(); } private long[] nl(int n) { return NextLongArray(n); } private double nd() { return NextDouble(); } private double[] nd(int n) { return NextDoubleArray(n); } private string ns() { return Next(); } private string[] ns(int n) { return NextArray(n); } #pragma warning restore IDE1006 #pragma warning restore IDE0051 } public static class LinqPadExtension { static public T Dump<T>(this T obj) { #if LOCAL return LINQPad.Extensions.Dump(obj); #else return obj; #endif } } public class Scanner { private readonly TextReader Reader; private readonly Queue<string> TokenQueue = new Queue<string>(); private readonly CultureInfo ci = CultureInfo.InvariantCulture; public Scanner() : this(Console.In) { } public Scanner(TextReader reader) { this.Reader = reader; } public int NextInt() { return int.Parse(Next(), ci); } public long NextLong() { return long.Parse(Next(), ci); } public double NextDouble() { return double.Parse(Next(), ci); } public string[] NextArray(int size) { var array = new string[size]; for (int i = 0; i < size; i++) array[i] = Next(); return array; } public int[] NextIntArray(int size) { var array = new int[size]; for (int i = 0; i < size; i++) array[i] = NextInt(); return array; } public long[] NextLongArray(int size) { var array = new long[size]; for (int i = 0; i < size; i++) array[i] = NextLong(); return array; } public double[] NextDoubleArray(int size) { var array = new double[size]; for (int i = 0; i < size; i++) array[i] = NextDouble(); return array; } public string Next() { if (TokenQueue.Count == 0) { if (!StockTokens()) throw new InvalidOperationException(); } return TokenQueue.Dequeue(); } public bool HasNext() { if (TokenQueue.Count > 0) return true; return StockTokens(); } static readonly char[] _separator = new[] { ' ' }; private bool StockTokens() { while (true) { var line = Reader.ReadLine(); if (line == null) return false; var tokens = line.Split(_separator, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length == 0) continue; foreach (var token in tokens) TokenQueue.Enqueue(token); return true; } } }
Yes
Do these codes solve the same problem? Code 1: #pragma GCC optimize("O2,Ofast,inline,unroll-all-loops,-ffast-math") #pragma GCC target("popcnt") #include <bits/stdc++.h> #define maxn 400010 #define i128 __int128 #define ll long long #define ull unsigned long long #define ld long double #define fi first #define se second #define pb push_back #define eb emplace_back #define pob pop_back #define pf push_front #define pof pop_front #define pii pair<int, int> #define pil pair<int, ll> #define pll pair<ll, ll> #define IL inline #define ss system using namespace std; ll p, ans = 0; struct mat { ll v[3][3]; mat(int type = 0) { memset(v, 0, sizeof(v)); if (type) { for (int i = 0; i < 3; i++) { v[i][i] = 1; } } } mat operator * (const mat &rhs) const { mat ret; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { ret.v[i][j] = (ret.v[i][j] + v[i][k] * rhs.v[k][j]) % p; } } } return ret; } }; i128 n, a, b; template <class T> void read(T &x) { char ch = x = 0; bool fl = false; while (!isdigit(ch)) fl |= ch == '-', ch = getchar(); while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); x = fl ? -x : x; } mat pwm(mat a, i128 b) { mat ret(1); while (b) { if (b & 1) ret = ret * a; a = a * a, b >>= 1; } return ret; } int main() { read(n), read(a), read(b), cin >> p; i128 pw = 1; for (int i = 0; i <= 36; i++, pw *= 10) { i128 l = pw <= a ? 0 : (pw - a - 1) / b + 1, r = min((pw * 10 - 1 - a) / b, n - 1); if (pw > a + (n - 1) * b) break; if (l > r) continue; if (pw * 10 <= a) continue; i128 fst = (a % p + l % p * b) % p; mat base; base.v[0][1] = base.v[1][1] = base.v[1][2] = base.v[2][2] = 1; base.v[0][0] = pw * 10 % p; mat res = pwm(base, r - l + 1); ans = (ans * res.v[0][0] + fst * res.v[0][1] + b % p * res.v[0][2]) % p; } cout << ans << endl; return 0; } Code 2: using System; using System.IO; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using E = System.Linq.Enumerable; using MatrixType = ModInt; using System.Numerics; partial class Solver { int getDigitLength(long x) { return x.ToString().Length; } public void Run() { var L = nl(); var A = nl(); var B = nl(); var M = nl(); ModInt.SetModValue((int)M); long ans = 0; var sL_1 = A + B * (L - 1); var s0 = A; var startD = getDigitLength(s0); var endD = getDigitLength(sL_1); var start = s0; var startN = 0L; for (int d = startD; d <= endD; d++) { long lower = startN, upper = L - 1; long end = -1, endN = -1; while (lower <= upper) { var mid = (lower + upper) / 2; long P = A + B * mid; if (P.ToString().Length <= d) { lower = mid + 1; end = P; endN = mid; } else { upper = mid - 1; } } if (end == -1) continue; // not exists var N = endN - startN + 1; //new { d, start, end, N }.Dump(); ans = ans * (int)BigInteger.ModPow(10, BigInteger.One * d * N, M); ans %= M; ans += Count(start, B, d, N, M); ans %= M; start = end + B; startN = endN + 1; } cout.WriteLine(ans); } long Count(long A0, long B, int digit, long N, long M) { long result = 0; { var P = (int)BigInteger.ModPow(10, digit, M); var mat = new Matrix(new ModInt[,] { { P, 0, 0 }, { 1, 1, 0 }, { 0, 1, 1 }, }); var b = new Matrix(new ModInt[,] { { B % M}, { 0 }, { 0 }, }); var R = Matrix.Pow(mat, N) * b; result += R[0, 2].ToInt(); //cout.WriteLine(" " + R[0, 2].ToInt()); } { var P = (int)BigInteger.ModPow(10, digit, M); var mat = new Matrix(new ModInt[,] { { P, 0, 0 }, { 1, 1, 0 }, { 0, 1, 1 }, }); var b = new Matrix(new ModInt[,] { { A0 % M }, { 0 }, { 0 }, }); var R = Matrix.Pow(mat, N) * b; result += R[0, 1].ToInt(); //cout.WriteLine(" " + R[0, 1].ToInt()); } return result % M; } } public struct ModInt { static private int mod = 0; private long value; public ModInt(long x) { this.value = x; Normalize(); } static private long RegularMod(long x, int mod) { if (x >= mod) { if (x < 2 * mod) return x - mod; return x % mod; } if (x >= 0) return x; x = mod - RegularMod(-x, mod); if (x == mod) return 0; return x; } static public void SetModValue(int m) { ModInt.mod = m; } private void Normalize() { this.value = RegularMod(value, mod); } public override string ToString() { return value.ToString(); } public int ToInt() { return (int)this.value; } public static bool operator ==(ModInt c1, ModInt c2) { return c1.value == c2.value; } public static bool operator !=(ModInt c1, ModInt c2) { return !(c1 == c2); } public static ModInt operator +(ModInt x, ModInt y) { return new ModInt(x.value + y.value); } public static ModInt operator -(ModInt x, ModInt y) { return new ModInt(x.value - y.value); } public static ModInt operator *(ModInt x, ModInt y) { return new ModInt(x.value * y.value); } public static ModInt operator /(ModInt x, ModInt y) { return new ModInt(x.value * Inverse(y.value, mod)); } static private long ExtendedGcd(long a, long b, ref long x, ref long y) { if (b == 0) { x = 1; y = 0; return a; } else { long d = ExtendedGcd(b, a % b, ref y, ref x); y -= a / b * x; return d; } } static private long Inverse(long a, long mod) { long x = 0, y = 0; if (ExtendedGcd(a, mod, ref x, ref y) == 1) return (x + mod) % mod; else throw new Exception("Invalid inverse " + a + " " + mod); } public static implicit operator ModInt(long x) { return new ModInt(x); } public override bool Equals(object obj) { if (obj == null) { return false; } return this.value.Equals(((ModInt)obj).value); } public override int GetHashCode() { return this.value.GetHashCode(); } } public class Matrix { public int Row { get; private set; } public int Col { get; private set; } private MatrixType[] Data; public Matrix(int row, int col) { this.Row = row; this.Col = col; this.Data = new MatrixType[Row * Col]; } public Matrix(MatrixType[,] array) : this(array.GetLength(0), array.GetLength(1)) { int index = 0; for (int i = 0; i < Row; i++) { for (int j = 0; j < Col; j++) { Data[index++] = array[i, j]; } } } public MatrixType this[int row, int col] { set { Data[row * Col + col] = value; } get { return Data[row * Col + col]; } } static public Matrix UnitMatrix(int n) { var matrix = new Matrix(n, n); for (int i = 0; i < n; i++) { matrix[i, i] = 1; } return matrix; } static public Matrix operator +(Matrix A, Matrix B) { var C = new Matrix(A.Row, A.Col); for (int i = 0; i < C.Data.Length; i++) { C.Data[i] = A.Data[i] + B.Data[i]; } return C; } static public Matrix operator -(Matrix A, Matrix B) { var C = new Matrix(A.Row, A.Col); for (int i = 0; i < C.Data.Length; i++) { C.Data[i] = A.Data[i] - B.Data[i]; } return C; } static public Matrix operator *(Matrix A, Matrix B) { var C = new Matrix(A.Row, B.Col); for (int i = 0; i < A.Row; i++) { for (int j = 0; j < B.Col; j++) { var val = C[i, j]; for (int k = 0; k < A.Col; k++) val += A[i, k] * B[k, j]; C[i, j] = val; } } return C; } public static implicit operator Matrix(MatrixType[,] array) { return new Matrix(array); } static public Matrix Pow(Matrix A, long n) { if (n == 0) return UnitMatrix(A.Row); Matrix result = A.Clone(), t = A.Clone(); n--; while (n > 0) { if ((n & 1) != 0) { result = result * t; } t = t * t; n >>= 1; } return result; } public Matrix Clone() { return new Matrix(Row, Col) { Data = Data.Clone() as MatrixType[] }; } static private void Swap<T>(ref T a, ref T b) { T t = a; a = b; b = t; } } // PREWRITEN CODE BEGINS FROM HERE partial class Solver : Scanner { public static void Main(string[] args) { #if LOCAL new Solver(Console.In, Console.Out).Run(); #else Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }); new Solver(Console.In, Console.Out).Run(); Console.Out.Flush(); #endif } #pragma warning disable IDE0052 private readonly TextReader cin; private readonly TextWriter cout; #pragma warning restore IDE0052 public Solver(TextReader reader, TextWriter writer) : base(reader) { this.cin = reader; this.cout = writer; } public Solver(string input, TextWriter writer) : this(new StringReader(input), writer) { } #pragma warning disable IDE1006 #pragma warning disable IDE0051 private int ni() { return NextInt(); } private int[] ni(int n) { return NextIntArray(n); } private long nl() { return NextLong(); } private long[] nl(int n) { return NextLongArray(n); } private double nd() { return NextDouble(); } private double[] nd(int n) { return NextDoubleArray(n); } private string ns() { return Next(); } private string[] ns(int n) { return NextArray(n); } #pragma warning restore IDE1006 #pragma warning restore IDE0051 } public static class LinqPadExtension { static public T Dump<T>(this T obj) { #if LOCAL return LINQPad.Extensions.Dump(obj); #else return obj; #endif } } public class Scanner { private readonly TextReader Reader; private readonly Queue<string> TokenQueue = new Queue<string>(); private readonly CultureInfo ci = CultureInfo.InvariantCulture; public Scanner() : this(Console.In) { } public Scanner(TextReader reader) { this.Reader = reader; } public int NextInt() { return int.Parse(Next(), ci); } public long NextLong() { return long.Parse(Next(), ci); } public double NextDouble() { return double.Parse(Next(), ci); } public string[] NextArray(int size) { var array = new string[size]; for (int i = 0; i < size; i++) array[i] = Next(); return array; } public int[] NextIntArray(int size) { var array = new int[size]; for (int i = 0; i < size; i++) array[i] = NextInt(); return array; } public long[] NextLongArray(int size) { var array = new long[size]; for (int i = 0; i < size; i++) array[i] = NextLong(); return array; } public double[] NextDoubleArray(int size) { var array = new double[size]; for (int i = 0; i < size; i++) array[i] = NextDouble(); return array; } public string Next() { if (TokenQueue.Count == 0) { if (!StockTokens()) throw new InvalidOperationException(); } return TokenQueue.Dequeue(); } public bool HasNext() { if (TokenQueue.Count > 0) return true; return StockTokens(); } static readonly char[] _separator = new[] { ' ' }; private bool StockTokens() { while (true) { var line = Reader.ReadLine(); if (line == null) return false; var tokens = line.Split(_separator, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length == 0) continue; foreach (var token in tokens) TokenQueue.Enqueue(token); return true; } } }
C++
#include<bits/stdc++.h> using namespace std; #define endl "\n" #define lln long long int #define IOS ios::sync_with_stdio(0);cin.tie(0); int main(){ IOS; int n,c=0; cin >> n; for(int i=1;i<=n;i++){ int val = (n/i) - (n%i == 0); c += val; } cout << c; return 0; }
Python
n,k = [int(j) for j in input().split()] l = [int(j) for j in input().split()] l.sort() l = l[::-1] for i in range(min(k, n)): l[i] = 0 print(sum(l))
No
Do these codes solve the same problem? Code 1: #include<bits/stdc++.h> using namespace std; #define endl "\n" #define lln long long int #define IOS ios::sync_with_stdio(0);cin.tie(0); int main(){ IOS; int n,c=0; cin >> n; for(int i=1;i<=n;i++){ int val = (n/i) - (n%i == 0); c += val; } cout << c; return 0; } Code 2: n,k = [int(j) for j in input().split()] l = [int(j) for j in input().split()] l.sort() l = l[::-1] for i in range(min(k, n)): l[i] = 0 print(sum(l))
C
int main() { int num1; int num2; int ans1; int ans2=0; int count=10; int judge=0; scanf("%d ", &num1); for(int i=0;i<=2;i++){ num2 = num1%count; ans1=num2/(count/10); num1=num1-num2; count=count*10; if (i!=0){ if(ans1==ans2){ judge=1; } } ans2=ans1; } ans1=num1/1000; if(ans1==ans2){ judge=1; } if(judge==1){ printf("Bad"); }else{ printf("Good"); } return 0; }
C++
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; while(n!=0){ int i; double s[1000]={},sum=0,a=0; for(i=0;i<n;i++){ cin>>s[i]; sum+=s[i]; } for(i=0;i<n;i++){ a+=(pow((sum/n)-s[i],2)/n); } printf("%.5f\n",sqrt(a)); cin>>n; } }
No
Do these codes solve the same problem? Code 1: int main() { int num1; int num2; int ans1; int ans2=0; int count=10; int judge=0; scanf("%d ", &num1); for(int i=0;i<=2;i++){ num2 = num1%count; ans1=num2/(count/10); num1=num1-num2; count=count*10; if (i!=0){ if(ans1==ans2){ judge=1; } } ans2=ans1; } ans1=num1/1000; if(ans1==ans2){ judge=1; } if(judge==1){ printf("Bad"); }else{ printf("Good"); } return 0; } Code 2: #include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; while(n!=0){ int i; double s[1000]={},sum=0,a=0; for(i=0;i<n;i++){ cin>>s[i]; sum+=s[i]; } for(i=0;i<n;i++){ a+=(pow((sum/n)-s[i],2)/n); } printf("%.5f\n",sqrt(a)); cin>>n; } }
C++
#include <bits/stdc++.h> using namespace std; #define int long long #define all(v) (v).begin(), (v).end() #define resz(v, ...) (v).clear(), (v).resize(__VA_ARGS__) #define reps(i, m, n) for(int i = (int)(m); i < (int)(n); i++) #define rep(i, n) reps(i, 0, n) template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;} template<class T1, class T2> void chmax(T1 &a, T2 b){if(a<b)a=b;} using Pi = pair<int, int>; using Tapris = tuple<int, int, int>; using vint = vector<int>; const int inf = 1LL << 55; const int mod = 1e9 + 7; signed main() { cin.tie(0); ios_base::sync_with_stdio(0); cout << fixed << setprecision(12); int n; cin >> n; vint a(n); rep(i, n) cin >> a[i]; int m; cin >> m; vint b(m); rep(i, m) cin >> b[i]; vint res; set_intersection(all(a), all(b), inserter(res, res.end())); for(int x : res) cout << x << endl; return 0; }
PHP
<?php $numbers = fgets(STDIN); $n = intval($numbers); // print $n; $numbers1 = preg_split("/[\s,]+/", rtrim(fgets(STDIN))); // print_r($numbers); $numbers2 = fgets(STDIN); $n = intval($numbers); // print $n; $numbers2 = preg_split("/[\s,]+/", rtrim(fgets(STDIN))); // print_r($numbers); // print_r($numbers2); $numbers_merge = array_intersect($numbers1, $numbers2); sort($numbers_merge); foreach ($numbers_merge as $nm){ echo $nm; echo PHP_EOL; } // print_r($numbers_merge);
Yes
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; #define int long long #define all(v) (v).begin(), (v).end() #define resz(v, ...) (v).clear(), (v).resize(__VA_ARGS__) #define reps(i, m, n) for(int i = (int)(m); i < (int)(n); i++) #define rep(i, n) reps(i, 0, n) template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;} template<class T1, class T2> void chmax(T1 &a, T2 b){if(a<b)a=b;} using Pi = pair<int, int>; using Tapris = tuple<int, int, int>; using vint = vector<int>; const int inf = 1LL << 55; const int mod = 1e9 + 7; signed main() { cin.tie(0); ios_base::sync_with_stdio(0); cout << fixed << setprecision(12); int n; cin >> n; vint a(n); rep(i, n) cin >> a[i]; int m; cin >> m; vint b(m); rep(i, m) cin >> b[i]; vint res; set_intersection(all(a), all(b), inserter(res, res.end())); for(int x : res) cout << x << endl; return 0; } Code 2: <?php $numbers = fgets(STDIN); $n = intval($numbers); // print $n; $numbers1 = preg_split("/[\s,]+/", rtrim(fgets(STDIN))); // print_r($numbers); $numbers2 = fgets(STDIN); $n = intval($numbers); // print $n; $numbers2 = preg_split("/[\s,]+/", rtrim(fgets(STDIN))); // print_r($numbers); // print_r($numbers2); $numbers_merge = array_intersect($numbers1, $numbers2); sort($numbers_merge); foreach ($numbers_merge as $nm){ echo $nm; echo PHP_EOL; } // print_r($numbers_merge);
C++
#include<bits/stdc++.h> using namespace std; #ifdef LOCAL #include "../../dump.hpp" #else #define dump(...) #endif #define rep(i,n) for(int i=0,i##_cond=(n);i<i##_cond;i++) #define FOR(i,a,b) for(int i=(a),i##_cond=(b);i<i##_cond;i++) #define ROF(i,a,b) for(int i=(a)-1,i##_cond=(b);i>=i##_cond;i--) #define all(a) (a).begin(),(a).end() #define rall(a) (a).rbegin(),(a).rend() //sortで大きい順 #define UNIQUE(v) v.erase(unique(all(v)),v.end()) #define SUM(a) accumulate(all(a),0) #define sz(x) ((int)(x).size()) #define pb push_back #define fst first #define snd second #define mp make_pair typedef long long ll; typedef vector<ll> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef pair<ll,ll> pii; #define int ll const int inf = 1ll<<62; const int mod = 1e9+7; main() { int n; cin >> n; vi p(n); rep(i,n) cin >> p[i]; vi a(n),b(n); rep(i,n){ int pos; rep(j,n) if(p[j] == i + 1) pos = j; a[i] = 30000 * i + pos + 1; b[i] = 30000 * (n - i); } rep(i,n-1) cout << a[i] << " "; cout << a[n-1] << endl; rep(i,n-1) cout << b[i] << " "; cout << b[n-1] << endl; }
Go
package main import ( "bufio" "flag" "fmt" "io" "math" "math/big" "os" ) var reader *bufio.Reader var writer *bufio.Writer var inputFile = flag.String("input", "", "") func init() { flag.Parse() var i io.Reader if *inputFile != "" { i, _ = os.Open(*inputFile) } else { i = os.Stdin } reader = bufio.NewReaderSize(i, 1<<20) writer = bufio.NewWriterSize(os.Stdout, 1<<20) } func println(a ...interface{}) { _, _ = fmt.Fprintln(writer, a...) } func printf(format string, a ...interface{}) { _, _ = fmt.Fprintf(writer, format, a...) } func scanf(format string, a ...interface{}) { _, _ = fmt.Fscanf(reader, format, a...) } func scan(a interface{}) { _, _ = fmt.Fscan(reader, a) } func NextInt64() int64 { var res int64 scan(&res) return res } func NextInt() int { var res int scan(&res) return res } func NextIntArray(n int) []int { res := make([]int, n) for i := range res { scan(&res[i]) } return res } func NextInt64Array(n int) []int64 { res := make([]int64, n) for i := range res { scan(&res[i]) } return res } func NextString() string { var res string scan(&res) return res } func NextBigInt() *big.Int { n := new(big.Int) n, _ = n.SetString(NextString(), 10) return n } func AbsInt64(x int64) int64 { if x < 0 { return -x } return x } func MinInt64(x, y int64) int64 { if x < y { return x } return y } func main() { defer writer.Flush() n := NextInt() data := NextInt64Array(3 * n) cost := make([][]int64, n) for i := range cost { cost[i] = data[3*i : 3*i+3] } dp := make([][]int64, n+1) dp[0] = []int64{0, 0, 0} for i := 0; i < n; i++ { dp[i + 1] = []int64{math.MaxInt64, math.MaxInt64, math.MaxInt64} for prev, value := range dp[i] { for step, c := range cost[i] { if step == prev { continue } dp[i + 1][step] = MinInt64(dp[i + 1][step], value - c) } } } println(-MinInt64(dp[n][0], MinInt64(dp[n][1], dp[n][2]))) }
No
Do these codes solve the same problem? Code 1: #include<bits/stdc++.h> using namespace std; #ifdef LOCAL #include "../../dump.hpp" #else #define dump(...) #endif #define rep(i,n) for(int i=0,i##_cond=(n);i<i##_cond;i++) #define FOR(i,a,b) for(int i=(a),i##_cond=(b);i<i##_cond;i++) #define ROF(i,a,b) for(int i=(a)-1,i##_cond=(b);i>=i##_cond;i--) #define all(a) (a).begin(),(a).end() #define rall(a) (a).rbegin(),(a).rend() //sortで大きい順 #define UNIQUE(v) v.erase(unique(all(v)),v.end()) #define SUM(a) accumulate(all(a),0) #define sz(x) ((int)(x).size()) #define pb push_back #define fst first #define snd second #define mp make_pair typedef long long ll; typedef vector<ll> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef pair<ll,ll> pii; #define int ll const int inf = 1ll<<62; const int mod = 1e9+7; main() { int n; cin >> n; vi p(n); rep(i,n) cin >> p[i]; vi a(n),b(n); rep(i,n){ int pos; rep(j,n) if(p[j] == i + 1) pos = j; a[i] = 30000 * i + pos + 1; b[i] = 30000 * (n - i); } rep(i,n-1) cout << a[i] << " "; cout << a[n-1] << endl; rep(i,n-1) cout << b[i] << " "; cout << b[n-1] << endl; } Code 2: package main import ( "bufio" "flag" "fmt" "io" "math" "math/big" "os" ) var reader *bufio.Reader var writer *bufio.Writer var inputFile = flag.String("input", "", "") func init() { flag.Parse() var i io.Reader if *inputFile != "" { i, _ = os.Open(*inputFile) } else { i = os.Stdin } reader = bufio.NewReaderSize(i, 1<<20) writer = bufio.NewWriterSize(os.Stdout, 1<<20) } func println(a ...interface{}) { _, _ = fmt.Fprintln(writer, a...) } func printf(format string, a ...interface{}) { _, _ = fmt.Fprintf(writer, format, a...) } func scanf(format string, a ...interface{}) { _, _ = fmt.Fscanf(reader, format, a...) } func scan(a interface{}) { _, _ = fmt.Fscan(reader, a) } func NextInt64() int64 { var res int64 scan(&res) return res } func NextInt() int { var res int scan(&res) return res } func NextIntArray(n int) []int { res := make([]int, n) for i := range res { scan(&res[i]) } return res } func NextInt64Array(n int) []int64 { res := make([]int64, n) for i := range res { scan(&res[i]) } return res } func NextString() string { var res string scan(&res) return res } func NextBigInt() *big.Int { n := new(big.Int) n, _ = n.SetString(NextString(), 10) return n } func AbsInt64(x int64) int64 { if x < 0 { return -x } return x } func MinInt64(x, y int64) int64 { if x < y { return x } return y } func main() { defer writer.Flush() n := NextInt() data := NextInt64Array(3 * n) cost := make([][]int64, n) for i := range cost { cost[i] = data[3*i : 3*i+3] } dp := make([][]int64, n+1) dp[0] = []int64{0, 0, 0} for i := 0; i < n; i++ { dp[i + 1] = []int64{math.MaxInt64, math.MaxInt64, math.MaxInt64} for prev, value := range dp[i] { for step, c := range cost[i] { if step == prev { continue } dp[i + 1][step] = MinInt64(dp[i + 1][step], value - c) } } } println(-MinInt64(dp[n][0], MinInt64(dp[n][1], dp[n][2]))) }
Go
package main import ( "bufio" "fmt" "os" "sort" "strconv" ) var sc, wr = bufio.NewScanner(os.Stdin), bufio.NewWriter(os.Stdout) func scanString() string { sc.Scan(); return sc.Text() } func scanRunes() []rune { return []rune(scanString()) } func scanInt() int { a, _ := strconv.Atoi(scanString()); return a } func scanInt64() int64 { a, _ := strconv.ParseInt(scanString(), 10, 64); return a } func scanFloat64() float64 { a, _ := strconv.ParseFloat(scanString(), 64); return a } func scanInts(n int) []int { a := make([]int, n) for i := 0; i < n; i++ { a[i] = scanInt() } return a } func debug(a ...interface{}) { if os.Getenv("ONLINE_JUDGE") == "false" { fmt.Fprintln(os.Stderr, a...) } } func abs(a int) int { if a < 0 { return -a } return a } func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } //•*¨*•.¸¸♪main•*¨*•.¸¸♪( -ω-)ノ ( ・ω・) func main() { defer wr.Flush() sc.Split(bufio.ScanWords) sc.Buffer(make([]byte, 10000), 1001001) n := scanInt() p := make([]pair, n) t := make([]int, n) for i := 0; i < n; i++ { p[i] = pair{scanInt() - 1, scanInt() - 1, i} t[p[i].b] = p[i].k } sort.Slice(p, func(i, j int) bool { return p[i].a < p[j].a }) b1 := newBinaryIndexedTree(n) b2 := newBinaryIndexedTree(n) uf := newUnionFind(n) for i := 0; i < n; i++ { _, y, k := p[i].a, p[i].b, p[i].k a := b1.sum(y) if a != 0 { id := b1.lowerBound(a) uf.unite(k, t[id]) } b1.add(y, 1) } for i := 0; i < n; i++ { _, y, k := p[n-1-i].a, p[n-1-i].b, p[n-1-i].k a := b2.sum(y) + 1 id := b2.lowerBound(a) if id != n { uf.unite(k, t[id]) } b := b2.sum(n - 1) if b != b2.sum(y) { id2 := b2.lowerBound(b) uf.unite(k, t[id2]) } b2.add(y, 1) } for i := 0; i < n; i++ { fmt.Fprintln(wr, uf.size(i)) } } type pair struct{ a, b, k int } type binaryIndexedTree []int func newBinaryIndexedTree(n int) *binaryIndexedTree { bit := make(binaryIndexedTree, n+1) return &bit } func (t binaryIndexedTree) sum(i int) (s int) { for i++; i > 0; i -= i & -i { s += t[i] } return } func (t binaryIndexedTree) add(i, x int) { for i++; i < len(t) && i > 0; i += i & -i { t[i] += x } } func (t binaryIndexedTree) lowerBound(x int) int { idx, k := 0, 1 for k < len(t) { k <<= 1 } for k >>= 1; k > 0; k >>= 1 { if idx+k < len(t) && t[idx+k] < x { x -= t[idx+k] idx += k } } return idx } type unionFind []int func newUnionFind(n int) *unionFind { uf := make(unionFind, n) for i := 0; i < n; i++ { uf[i] = -1 } return &uf } func (uf unionFind) find(x int) int { if uf[x] < 0 { return x } uf[x] = uf.find(uf[x]) return uf[x] } func (uf unionFind) unite(x, y int) { x, y = uf.find(x), uf.find(y) if x != y { if uf[x] > uf[y] { x, y = y, x } uf[x] += uf[y] uf[y] = x } } func (uf unionFind) size(x int) int { return -uf[uf.find(x)] }
PHP
<?php $N = (int)trim(fgets(STDIN)); //$S = trim(fgets(STDIN)); //list($a,$b,$c,$d) = array_map('intval',explode(" ",trim(fgets(STDIN)))); //$A = array_map('intval',explode(" ",trim(fgets(STDIN)))); for($i=0;$i<$N;$i++) { list($x,$y) = array_map('intval',explode(" ",trim(fgets(STDIN)))); $c = new StdClass(); $c->x = $x; $c->y = $y; $c->idx = $i; $d[]=$c; $s[$i]=$x; } array_multisort($s,SORT_ASC,$d); $uft = new UF($N); $dm=array(); foreach($d as $v) { $miny = $v->y; while(count($dm)) { $l = count($dm)-1; if ($dm[$l]->miny>$v->y) break; $uft->unite($dm[$l]->idx,$v->idx); $miny = min($dm[$l]->miny,$miny); array_pop($dm); } $c = new StdClass(); $c->miny = $miny; $c->idx = $v->idx; $dm[]=$c; } for ($i=0;$i<$N;$i++) { printf("%d\n",$uft->size($i)); } //https://atcoder.jp/contests/acl1/submissions/16913401 class UF { private $pnode; private $sz; public function __construct($n) { $this->pnode = range(0,$n); $this->sz = array_fill(0,$n,1); } public function find($x) { return $x==$this->pnode[$x]?$x:$this->pnode[$x]=$this->find($this->pnode[$x]); } public function unite($x,$y) { $x = $this->find($x); $y = $this->find($y); if ($x==$y) return; $this->sz[$x]+=$this->sz[$y]; $this->pnode[$y]=$x; } public function same($x,$y) { return $this->find($x) == $this->find($y); } public function size($x) { return $this->sz[$this->find($x)]; } }
Yes
Do these codes solve the same problem? Code 1: package main import ( "bufio" "fmt" "os" "sort" "strconv" ) var sc, wr = bufio.NewScanner(os.Stdin), bufio.NewWriter(os.Stdout) func scanString() string { sc.Scan(); return sc.Text() } func scanRunes() []rune { return []rune(scanString()) } func scanInt() int { a, _ := strconv.Atoi(scanString()); return a } func scanInt64() int64 { a, _ := strconv.ParseInt(scanString(), 10, 64); return a } func scanFloat64() float64 { a, _ := strconv.ParseFloat(scanString(), 64); return a } func scanInts(n int) []int { a := make([]int, n) for i := 0; i < n; i++ { a[i] = scanInt() } return a } func debug(a ...interface{}) { if os.Getenv("ONLINE_JUDGE") == "false" { fmt.Fprintln(os.Stderr, a...) } } func abs(a int) int { if a < 0 { return -a } return a } func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } //•*¨*•.¸¸♪main•*¨*•.¸¸♪( -ω-)ノ ( ・ω・) func main() { defer wr.Flush() sc.Split(bufio.ScanWords) sc.Buffer(make([]byte, 10000), 1001001) n := scanInt() p := make([]pair, n) t := make([]int, n) for i := 0; i < n; i++ { p[i] = pair{scanInt() - 1, scanInt() - 1, i} t[p[i].b] = p[i].k } sort.Slice(p, func(i, j int) bool { return p[i].a < p[j].a }) b1 := newBinaryIndexedTree(n) b2 := newBinaryIndexedTree(n) uf := newUnionFind(n) for i := 0; i < n; i++ { _, y, k := p[i].a, p[i].b, p[i].k a := b1.sum(y) if a != 0 { id := b1.lowerBound(a) uf.unite(k, t[id]) } b1.add(y, 1) } for i := 0; i < n; i++ { _, y, k := p[n-1-i].a, p[n-1-i].b, p[n-1-i].k a := b2.sum(y) + 1 id := b2.lowerBound(a) if id != n { uf.unite(k, t[id]) } b := b2.sum(n - 1) if b != b2.sum(y) { id2 := b2.lowerBound(b) uf.unite(k, t[id2]) } b2.add(y, 1) } for i := 0; i < n; i++ { fmt.Fprintln(wr, uf.size(i)) } } type pair struct{ a, b, k int } type binaryIndexedTree []int func newBinaryIndexedTree(n int) *binaryIndexedTree { bit := make(binaryIndexedTree, n+1) return &bit } func (t binaryIndexedTree) sum(i int) (s int) { for i++; i > 0; i -= i & -i { s += t[i] } return } func (t binaryIndexedTree) add(i, x int) { for i++; i < len(t) && i > 0; i += i & -i { t[i] += x } } func (t binaryIndexedTree) lowerBound(x int) int { idx, k := 0, 1 for k < len(t) { k <<= 1 } for k >>= 1; k > 0; k >>= 1 { if idx+k < len(t) && t[idx+k] < x { x -= t[idx+k] idx += k } } return idx } type unionFind []int func newUnionFind(n int) *unionFind { uf := make(unionFind, n) for i := 0; i < n; i++ { uf[i] = -1 } return &uf } func (uf unionFind) find(x int) int { if uf[x] < 0 { return x } uf[x] = uf.find(uf[x]) return uf[x] } func (uf unionFind) unite(x, y int) { x, y = uf.find(x), uf.find(y) if x != y { if uf[x] > uf[y] { x, y = y, x } uf[x] += uf[y] uf[y] = x } } func (uf unionFind) size(x int) int { return -uf[uf.find(x)] } Code 2: <?php $N = (int)trim(fgets(STDIN)); //$S = trim(fgets(STDIN)); //list($a,$b,$c,$d) = array_map('intval',explode(" ",trim(fgets(STDIN)))); //$A = array_map('intval',explode(" ",trim(fgets(STDIN)))); for($i=0;$i<$N;$i++) { list($x,$y) = array_map('intval',explode(" ",trim(fgets(STDIN)))); $c = new StdClass(); $c->x = $x; $c->y = $y; $c->idx = $i; $d[]=$c; $s[$i]=$x; } array_multisort($s,SORT_ASC,$d); $uft = new UF($N); $dm=array(); foreach($d as $v) { $miny = $v->y; while(count($dm)) { $l = count($dm)-1; if ($dm[$l]->miny>$v->y) break; $uft->unite($dm[$l]->idx,$v->idx); $miny = min($dm[$l]->miny,$miny); array_pop($dm); } $c = new StdClass(); $c->miny = $miny; $c->idx = $v->idx; $dm[]=$c; } for ($i=0;$i<$N;$i++) { printf("%d\n",$uft->size($i)); } //https://atcoder.jp/contests/acl1/submissions/16913401 class UF { private $pnode; private $sz; public function __construct($n) { $this->pnode = range(0,$n); $this->sz = array_fill(0,$n,1); } public function find($x) { return $x==$this->pnode[$x]?$x:$this->pnode[$x]=$this->find($this->pnode[$x]); } public function unite($x,$y) { $x = $this->find($x); $y = $this->find($y); if ($x==$y) return; $this->sz[$x]+=$this->sz[$y]; $this->pnode[$y]=$x; } public function same($x,$y) { return $this->find($x) == $this->find($y); } public function size($x) { return $this->sz[$this->find($x)]; } }
Python
n,a,b=int(input()),list(map(int,input().split()))+[0],list(map(int,input().split()))+[0] for i in range(n): a[n]^=a[i] b[n]^=b[i] na,nb=sorted(a),sorted(b) if na!=nb: print("-1") exit() f=dict() def find(x): if f[x]==x: return x else: f[x]=find(f[x]) return f[x] ans=0 for i in range(n): if a[i]!=b[i]: f[a[i]]=a[i] f[a[n]]=a[n] for i in range(n): if a[i]!=b[i]: ans+=1 f[find(b[i])]=find(a[i]) for i in f: if i==f[i]: ans+=1 print(ans-1)
Java
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n + 1]; int[] b = new int[n + 1]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); a[n] ^= a[i]; } for (int i = 0; i < n; ++i) { b[i] = in.nextInt(); b[n] ^= b[i]; } int[] as = a.clone(); Arrays.sort(as); int[] bs = b.clone(); Arrays.sort(bs); if (!Arrays.equals(as, bs)) { out.println(-1); return; } Map<Integer, TaskD.Vertex> vs = new HashMap<>(); for (int i = 0; i <= n; ++i) { TaskD.Vertex va = vs.computeIfAbsent(a[i], k -> new TaskD.Vertex()); TaskD.Vertex vb = vs.computeIfAbsent(b[i], k -> new TaskD.Vertex()); ++va.count; ++vb.count; if (i < n && a[i] == b[i]) ++va.countIdentity; va.adj.add(vb); vb.adj.add(va); } int res = 0; for (int i = n; i >= 0; --i) { TaskD.Vertex v = vs.get(a[i]); if (!v.mark) { TaskD.Pair p = new TaskD.Pair(); v.dfs(p); if (p.total % 2 != 0) throw new RuntimeException(); p.total /= 2; p.total -= p.totalIdentity; if (i == n) res += p.total - 1; else if (p.total > 0) res += p.total + 1; } } out.println(res); } static class Pair { int total; int totalIdentity; } static class Vertex { boolean mark = false; int count = 0; int countIdentity = 0; List<TaskD.Vertex> adj = new ArrayList<>(); public void dfs(TaskD.Pair res) { mark = true; res.total += count; res.totalIdentity += countIdentity; for (TaskD.Vertex v : adj) if (!v.mark) v.dfs(res); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Yes
Do these codes solve the same problem? Code 1: n,a,b=int(input()),list(map(int,input().split()))+[0],list(map(int,input().split()))+[0] for i in range(n): a[n]^=a[i] b[n]^=b[i] na,nb=sorted(a),sorted(b) if na!=nb: print("-1") exit() f=dict() def find(x): if f[x]==x: return x else: f[x]=find(f[x]) return f[x] ans=0 for i in range(n): if a[i]!=b[i]: f[a[i]]=a[i] f[a[n]]=a[n] for i in range(n): if a[i]!=b[i]: ans+=1 f[find(b[i])]=find(a[i]) for i in f: if i==f[i]: ans+=1 print(ans-1) Code 2: import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n + 1]; int[] b = new int[n + 1]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); a[n] ^= a[i]; } for (int i = 0; i < n; ++i) { b[i] = in.nextInt(); b[n] ^= b[i]; } int[] as = a.clone(); Arrays.sort(as); int[] bs = b.clone(); Arrays.sort(bs); if (!Arrays.equals(as, bs)) { out.println(-1); return; } Map<Integer, TaskD.Vertex> vs = new HashMap<>(); for (int i = 0; i <= n; ++i) { TaskD.Vertex va = vs.computeIfAbsent(a[i], k -> new TaskD.Vertex()); TaskD.Vertex vb = vs.computeIfAbsent(b[i], k -> new TaskD.Vertex()); ++va.count; ++vb.count; if (i < n && a[i] == b[i]) ++va.countIdentity; va.adj.add(vb); vb.adj.add(va); } int res = 0; for (int i = n; i >= 0; --i) { TaskD.Vertex v = vs.get(a[i]); if (!v.mark) { TaskD.Pair p = new TaskD.Pair(); v.dfs(p); if (p.total % 2 != 0) throw new RuntimeException(); p.total /= 2; p.total -= p.totalIdentity; if (i == n) res += p.total - 1; else if (p.total > 0) res += p.total + 1; } } out.println(res); } static class Pair { int total; int totalIdentity; } static class Vertex { boolean mark = false; int count = 0; int countIdentity = 0; List<TaskD.Vertex> adj = new ArrayList<>(); public void dfs(TaskD.Pair res) { mark = true; res.total += count; res.totalIdentity += countIdentity; for (TaskD.Vertex v : adj) if (!v.mark) v.dfs(res); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Python
N = int(input()) for h in range(1, 3501): for n in range(1, 3501): b = 4*h*n - N*(n+h) a = N*h*n #print(a, b) if b > 0 and a % b == 0: w = a // b print(h, n, w) exit(0)
Kotlin
fun main(args: Array<String>) { fun calc(h: Int, n: Int, w: Int, N: Int): Double { var ans: Double = 1.0 ans *= N ans *= n * w + h * w + h * n ans /= h.toDouble() * n * w return ans } val N = readLine()!!.toInt() for (h in 1..3500) { for (n in 1..3500) { var l = 1 var r = 3500 while (l + 1 < r) { val w = (l + r) / 2 val ans = calc(h, n, w, N) if (4.0 == ans) { print("$h $n $w") return } if (4.0 < ans) { l = w } else { r = w } } } } }
Yes
Do these codes solve the same problem? Code 1: N = int(input()) for h in range(1, 3501): for n in range(1, 3501): b = 4*h*n - N*(n+h) a = N*h*n #print(a, b) if b > 0 and a % b == 0: w = a // b print(h, n, w) exit(0) Code 2: fun main(args: Array<String>) { fun calc(h: Int, n: Int, w: Int, N: Int): Double { var ans: Double = 1.0 ans *= N ans *= n * w + h * w + h * n ans /= h.toDouble() * n * w return ans } val N = readLine()!!.toInt() for (h in 1..3500) { for (n in 1..3500) { var l = 1 var r = 3500 while (l + 1 < r) { val w = (l + r) / 2 val ans = calc(h, n, w, N) if (4.0 == ans) { print("$h $n $w") return } if (4.0 < ans) { l = w } else { r = w } } } } }
Python
a=str(input()) ans="No" for i in a: if i=="7": ans="Yes" break print(ans)
C++
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <set> #include <string> #include <vector> using namespace std; typedef long long i64; typedef long double ld; #define rep(i, s, e) for (int i = (s); i <= (e); i++) int H, N, P, M, K; vector<int> stick(505, -1); vector<vector<ld>> dp(505, vector<ld>(101, 0)); int main() { cin >> H >> N >> P >> M >> K; for (int i = 0; i < M; i++) { int a, b; cin >> a >> b; stick[a] = b; } dp[K][P] = 1; for (int i = H; i >= 1; i--) { if (stick[i] != -1) { vector<vector<ld>> next(505,vector<ld>(101,0)); rep(j, 1, N) rep(k, 0, K) { int st = stick[i]; if (st == j) next[k][j + 1] += dp[k][j]; else if (st + 1 == j) next[k][j - 1] += dp[k][j]; else next[k][j] += dp[k][j]; } swap(dp,next); } else { vector<vector<ld>> next(505,vector<ld>(101,0)); rep(j,1,N) rep(k,0,K){ next[k][j] += dp[k][j]; } rep(j, 1, N) rep(k, 0, K) rep(st, 1, N - 1) { if (st == j) next[k][j + 1] += dp[k + 1][j]; else if (st + 1 == j) next[k][j - 1] += dp[k + 1][j]; else next[k][j] += dp[k + 1][j]; } swap(dp,next); } } ld result = 0; ld sum = 0; for (int i = 1; i <= N; i++) { sum += dp[0][i]; result = max(result, dp[0][i]); } cout << fixed << setprecision(10) << result / sum << endl; return 0; }
No
Do these codes solve the same problem? Code 1: a=str(input()) ans="No" for i in a: if i=="7": ans="Yes" break print(ans) Code 2: #include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <set> #include <string> #include <vector> using namespace std; typedef long long i64; typedef long double ld; #define rep(i, s, e) for (int i = (s); i <= (e); i++) int H, N, P, M, K; vector<int> stick(505, -1); vector<vector<ld>> dp(505, vector<ld>(101, 0)); int main() { cin >> H >> N >> P >> M >> K; for (int i = 0; i < M; i++) { int a, b; cin >> a >> b; stick[a] = b; } dp[K][P] = 1; for (int i = H; i >= 1; i--) { if (stick[i] != -1) { vector<vector<ld>> next(505,vector<ld>(101,0)); rep(j, 1, N) rep(k, 0, K) { int st = stick[i]; if (st == j) next[k][j + 1] += dp[k][j]; else if (st + 1 == j) next[k][j - 1] += dp[k][j]; else next[k][j] += dp[k][j]; } swap(dp,next); } else { vector<vector<ld>> next(505,vector<ld>(101,0)); rep(j,1,N) rep(k,0,K){ next[k][j] += dp[k][j]; } rep(j, 1, N) rep(k, 0, K) rep(st, 1, N - 1) { if (st == j) next[k][j + 1] += dp[k + 1][j]; else if (st + 1 == j) next[k][j - 1] += dp[k + 1][j]; else next[k][j] += dp[k + 1][j]; } swap(dp,next); } } ld result = 0; ld sum = 0; for (int i = 1; i <= N; i++) { sum += dp[0][i]; result = max(result, dp[0][i]); } cout << fixed << setprecision(10) << result / sum << endl; return 0; }
Python
a, b = [int(i) for i in input().split()] ans = 0 ans += a - 1 if b >= a: ans += 1 print(ans)
C++
#include <bits/stdc++.h> using namespace std; typedef unsigned long ul; typedef unsigned long long ull; typedef long long ll; typedef vector<ll> vint; typedef vector< vector<ll> > vvint; typedef vector< vector< vector<ll> > > vvvint; typedef vector<string> vstring; typedef vector< vector<string> > vvstring; typedef vector<char> vchar; typedef vector< vector<char> > vvchar; typedef vector<long double> vdouble; typedef vector< vector<long double> > vvdouble; typedef vector< vector< vector<long double> > > vvvdouble; typedef pair<ll,ll> pint; typedef vector<pint> vpint; typedef vector<bool> vbool; #define rep(i,n) for(ll i=0;i<n;i++) #define repf(i,f,n) for(ll i=f;i<n;i++) #define repr(i,n) for(ll i=n-1;i>=0;i--) #define mp make_pair #define mt make_tuple #define pb push_back #define pf push_front #define fi first #define se second #define ALL(obj) (obj).begin(), (obj).end() // #define LLONG_MAX 9223372036854775806 #define vmax(vec) *max_element(vec.begin(), vec.end()) #define vmin(vec) *min_element(vec.begin(), vec.end()) #define vsort(vec) sort(vec.begin(), vec.end()) #define vsortgr(vec) sort(vec.begin(), vec.end(), greater<ll>()) #define MOD 1000000007 // #define MOD 998244353 // #define MOD LLONG_MAX const double PI=3.14159265358979323846; template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; } int dy[]={0, 0, 1, -1}; int dx[]={1, -1, 0, 0,}; void printv(vint &v){ for(auto e:v) cout<<e<<" "; cout<<endl; } int main() { cout<<fixed<<setprecision(10); ll a,b,c; cin>>a>>b>>c; cout<<min(b/a, c)<<endl; } //
No
Do these codes solve the same problem? Code 1: a, b = [int(i) for i in input().split()] ans = 0 ans += a - 1 if b >= a: ans += 1 print(ans) Code 2: #include <bits/stdc++.h> using namespace std; typedef unsigned long ul; typedef unsigned long long ull; typedef long long ll; typedef vector<ll> vint; typedef vector< vector<ll> > vvint; typedef vector< vector< vector<ll> > > vvvint; typedef vector<string> vstring; typedef vector< vector<string> > vvstring; typedef vector<char> vchar; typedef vector< vector<char> > vvchar; typedef vector<long double> vdouble; typedef vector< vector<long double> > vvdouble; typedef vector< vector< vector<long double> > > vvvdouble; typedef pair<ll,ll> pint; typedef vector<pint> vpint; typedef vector<bool> vbool; #define rep(i,n) for(ll i=0;i<n;i++) #define repf(i,f,n) for(ll i=f;i<n;i++) #define repr(i,n) for(ll i=n-1;i>=0;i--) #define mp make_pair #define mt make_tuple #define pb push_back #define pf push_front #define fi first #define se second #define ALL(obj) (obj).begin(), (obj).end() // #define LLONG_MAX 9223372036854775806 #define vmax(vec) *max_element(vec.begin(), vec.end()) #define vmin(vec) *min_element(vec.begin(), vec.end()) #define vsort(vec) sort(vec.begin(), vec.end()) #define vsortgr(vec) sort(vec.begin(), vec.end(), greater<ll>()) #define MOD 1000000007 // #define MOD 998244353 // #define MOD LLONG_MAX const double PI=3.14159265358979323846; template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; } int dy[]={0, 0, 1, -1}; int dx[]={1, -1, 0, 0,}; void printv(vint &v){ for(auto e:v) cout<<e<<" "; cout<<endl; } int main() { cout<<fixed<<setprecision(10); ll a,b,c; cin>>a>>b>>c; cout<<min(b/a, c)<<endl; } //
C++
#include <bits/stdc++.h> using namespace std; typedef long long int lld; int main(void){ lld a,b,c,k; cin >> a >> b >> c >> k; if(a>=k){ printf("%lld",k); }else if(a+b>=k){ printf("%lld",a); }else{ lld dd = k - a - b; lld sol = a - dd; printf("%lld",sol); } return 0; }
Java
import java.util.*; import java.lang.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int d = sc.nextInt(); int x = sc.nextInt(); int[] a = new int[n]; for(int i = 0;i<n;i++){ a[i] = sc.nextInt(); } int tabe = 0; for(int i = 0;i<d;i++){ for(int j = 0;j<n;j++){ if(i%a[j] == 0){ tabe++; } } } tabe += x; System.out.println(tabe); sc.close(); } }
No
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; typedef long long int lld; int main(void){ lld a,b,c,k; cin >> a >> b >> c >> k; if(a>=k){ printf("%lld",k); }else if(a+b>=k){ printf("%lld",a); }else{ lld dd = k - a - b; lld sol = a - dd; printf("%lld",sol); } return 0; } Code 2: import java.util.*; import java.lang.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int d = sc.nextInt(); int x = sc.nextInt(); int[] a = new int[n]; for(int i = 0;i<n;i++){ a[i] = sc.nextInt(); } int tabe = 0; for(int i = 0;i<d;i++){ for(int j = 0;j<n;j++){ if(i%a[j] == 0){ tabe++; } } } tabe += x; System.out.println(tabe); sc.close(); } }
C#
using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Text; public class Program { public void Proc() { int rate = int.Parse(Reader.ReadLine()); string ans = "AGC"; if(rate <1200) { ans = "ABC"; } else if(rate < 2800) { ans = "ARC"; } Console.WriteLine(ans); } public class Reader { static StringReader sr; public static bool IsDebug = false; public static string ReadLine() { if (IsDebug) { if (sr == null) { sr = new StringReader(InputText.Trim()); } return sr.ReadLine(); } else { return Console.ReadLine(); } } private static string InputText = @" 1200 "; } public static void Main(string[] args) { #if DEBUG Reader.IsDebug = true; #endif Program prg = new Program(); prg.Proc(); } }
Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); Integer ans[] = {1,1,1,1,1} ; int count = 0; while (sc.hasNext()) { int num = sc.nextInt(); ans[count] = num; count++; if(count==5){ System.out.println(strkn(ans)); break; } } } public static String strkn(Integer[] ans){ Arrays.sort(ans, Comparator.reverseOrder()); // ??????????????? String result = ans[0].toString() +" "+ ans[1].toString() +" "+ ans[2].toString() +" "+ ans[3].toString() +" "+ ans[4].toString(); return result; } }
No
Do these codes solve the same problem? Code 1: using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Text; public class Program { public void Proc() { int rate = int.Parse(Reader.ReadLine()); string ans = "AGC"; if(rate <1200) { ans = "ABC"; } else if(rate < 2800) { ans = "ARC"; } Console.WriteLine(ans); } public class Reader { static StringReader sr; public static bool IsDebug = false; public static string ReadLine() { if (IsDebug) { if (sr == null) { sr = new StringReader(InputText.Trim()); } return sr.ReadLine(); } else { return Console.ReadLine(); } } private static string InputText = @" 1200 "; } public static void Main(string[] args) { #if DEBUG Reader.IsDebug = true; #endif Program prg = new Program(); prg.Proc(); } } Code 2: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); Integer ans[] = {1,1,1,1,1} ; int count = 0; while (sc.hasNext()) { int num = sc.nextInt(); ans[count] = num; count++; if(count==5){ System.out.println(strkn(ans)); break; } } } public static String strkn(Integer[] ans){ Arrays.sort(ans, Comparator.reverseOrder()); // ??????????????? String result = ans[0].toString() +" "+ ans[1].toString() +" "+ ans[2].toString() +" "+ ans[3].toString() +" "+ ans[4].toString(); return result; } }
Python
import heapq from collections import deque N = int(input()) A = [[int(a) for a in input().split()] for _ in range(N)] def dijkstra_heap(s, edge, n): #始点sから各頂点への最短距離 d = [10**9+1] * n used = [True] * n #True:未確定 d[s] = 0 used[s] = False edgelist = [] for a,b in edge[s]: heapq.heappush(edgelist,a*(10**6)+b) while len(edgelist): minedge = heapq.heappop(edgelist) #まだ使われてない頂点の中から最小の距離のものを探す if not used[minedge%(10**6)]: continue v = minedge%(10**6) d[v] = minedge//(10**6) used[v] = False for e in edge[v]: if used[e[1]]: heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1]) return d Road = [[] for _ in range(N)] h = [] for i in range(N): for j in range(i+1, N): heapq.heappush(h, (A[i][j], i, j)) m = h[0][0] D = [[10**9+1]*N for _ in range(N)] ans = 0 while h: t = heapq.heappop(h) cost = t[0] i = t[1] j = t[2] if cost < 2*m: Road[i].append((cost, j)) Road[j].append((cost, i)) D[i][j] = cost D[j][i] = cost elif D[i][j] > cost: D[i] = dijkstra_heap(i, Road, N) if D[i][j] > cost: Road[i].append((cost, j)) Road[j].append((cost, i)) D[i][j] = cost D[j][i] = cost if D[i][j] < cost: ans = -1 break if ans == 0: for i in range(N): for t in Road[i]: ans += t[0] ans //= 2 print(ans)
C++
#include <string> #include <vector> #include <algorithm> #include <numeric> #include <set> #include <map> #include <queue> #include<stack> #include<bitset> #include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <cctype> #include <cassert> #include <limits> #include <functional> #include<unordered_map> #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i)) #define aut(r,v) for(auto r:v) #define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it) #define all(o) (o).begin(), (o).end() #define pb(x) push_back(x) #define pc() pop_back() #define ull unsigned long long #define mp(x,y) make_pair((x),(y)) #define mset(m,v) memset(m,v,sizeof(m)) #define INF 0x3f3f3f3f #define INFL 0x3f3f3f3f3f3f3f3fLL using namespace std; #define endl '\n' #define st stack<int> #define vl vector<long long> #define vi vector<int> #define vb vector<bool> #define vc vector<char> #define pii pair<int,int> #define vpii vector<pii> #define vvi vector<vi> #define vs vector<string> #define mod 1000000007 #define un unordered_map<int,int> #define mii map<int,int> #define Sort(a) sort(all(a)) #define ED(a) Sort(a), a.erase(unique(all(a)), a.end())//removing all duplicates #define max3(a, b, c) max(a, max(b, c)) #define min3(a, b, c) min(a, min(b, c)) #define Max(a) *max_element(all(a)) #define Min(a) *min_element(all(a)) #define MaxP(a) max_element(all(a)) - a.begin() #define MinP(a) min_element(all(a)) - a.begin() #define allUpper(a) transform(all(a), a.begin(), :: toupper) #define allLower(a) transform(all(a), a.begin(), :: tolower) #define rev(a) reverse(all(a)) #define ub(v,k) upper_bound(all(v), k) - v.begin() #define lb(v,k) lower_bound(all(v), k) - v.begin() #define adv(a,n) advance(auto it:a,n) #define RSort(a) sort(a.rbegin(),a.rend()) //decending order #define cnt(v,a) count(all(v),a) #define bs(v,a) binary_search(all(v),a) #define mmax(v) *max_element(all(v)) #define mmin(v) *min_element(all(v)) #define popcount(mask) __builtin_popcount(mask) // count set bit #define popcountLL(mask) __builtin_popcountll(mask) // for long long #define X real() // useful for working with #include <complex> for computational geometry #define Y imag() #define ll long long #define ss second #define ff first #define trace1(x) cerr << #x << ": " << x << endl; #define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl; #define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl; #define trace4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl; #define trace5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl; #define trace6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl; template <typename T> T gcd(T a, T b) { while (b) b ^= a ^= b ^= a %= b; return a; } template <typename T> T setbit(T mask, T pos) { return mask |= (1 << pos); } template <typename T> T resetbit(T mask, T pos) { return mask &= ~(1 << pos); } template <typename T> T togglebit(T mask, T pos) { return mask ^= (1 << pos); } template <typename T> T checkbit(T mask, T pos) { return (bool)(mask & (1 << pos)); } template <typename T> T lcm(T a, T b) { return (a / gcd(a, b)) * b; } template <typename T> T modu(T a, T b) { return (a < b ? a : a % b); } template<typename T> T mod_neg(T a, T b) { a = mod(a, b); if (a < 0) { a += b; } return a; } template <typename T>T expo(T e, T n) { T x = 1, p = e; while (n) { if (n & 1)x = x * p; p = p * p; n >>= 1; } return x; } template<typename T> T mod_inverse(T a, T n) { T x, y; T d = extended_euclid(a, n, x, y); return (d > 1 ? -1 : mod_neg(x, n)); } template <typename T>T power(T e, T n, T m) { T x = 1, p = e; while (n) { if (n & 1)x = mod(x * p, m); p = mod(p * p, m); n >>= 1; } return x; } template <typename T>T powerL(T e, T n, T m) { T x = 1, p = e; while (n) { if (n & 1)x = mulmod(x, p, m); p = mulmod(p, p, m); n >>= 1; } return x; } bool Pow2(int n) { return n && (!(n & (n - 1))); } void printc(vc& result) { aut(r, result) cout << r << " "; cout << endl; } void printl(vl& result) { aut(r, result) cout << r << " "; cout << endl; } void print(vi& result) { aut(r, result) cout << r << " "; cout << endl; } // Recursively computes the power int binpow(int a, int b) { if (b == 0) return a; int res = binpow(a, b / 2); if (b % 2) return res * res * a; else return res * res; } // iteratively computes the power int pow(int a, int b) { int res = 1; while (b) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } int modpow(int a, int b, int m) { int ans = 1; while (b) { if (b & 1) ans = (ans * a) % m; b /= 2; a = (a * a) % m; } return ans; } const int MOD = 1000000000 + 7; const int MXX = 100000 + 69; int fact[MXX], invfact[MXX]; int modinv(int k) { return modpow(k, MOD - 2, MOD); } void combinatorics() { fact[0] = fact[1] = 1; for (int i = 2; i < MXX; i++) { fact[i] = fact[i - 1] * i; fact[i] %= MOD; } invfact[MXX - 1] = modinv(fact[MXX - 1]); for (int i = MXX - 2; i >= 0; i--) { invfact[i] = invfact[i + 1] * (i + 1); invfact[i] %= MOD; } } int nCr(int x, int y) { if (y > x) return 0; int num = fact[x]; num *= invfact[y]; num %= MOD; num *= invfact[x - y]; num %= MOD; return num; } //ifstream cin("b_read_on.txt"); ofstream cout("output3.txt"); //Use (<<) for multiplication //Use (>>) for division //ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);cout<<fixed;cerr.tie(NULL); // find_by_order -> value at index // order_of_key -> index of value // while using (1<<i) use ((ll)1<<(ll)i) // in Floyd-Warshall Algo, k is outer loop // If an element was not initially in map and if asked mp[a],the element gets inserted // a%=mod take a lot of time... try to use it minimum and use memset as it reduces a lot of time usage...use if(a>=mod) a%=mod //cout<<(double) can be harmful , always use printf(%.9llf)...take scanf("%lf",&p[i][j]) as input , not llf; //use s.erase(it++) for erasing iterator and then moving to the next one //never use adj.resize(n) as value is persistent, always erase //use __builtin_popcountll() for ll // no of prime numbers in range : (70,19) , (1000,168) , (100000,1229) , (sqrt(10^9),3409) ; //always check the use of segment tree using bottom-up dp /* int dx[] = {1,-1,0,0} , dy[] = {0,0,1,-1}; */ // 4 Direction /* int dx[] = {1,-1,0,0,1,1,-1,-1} , dy[] = {0,0,1,-1,1,-1,1,-1}; */ // 8 Direction /* int dx[] = {1,-1,1,-1,2,2,-2,-2} , dy[] = {2,2,-2,-2,1,-1,1,-1}; */ // Knight Direction /* int dx[] = {2,-2,1,1,-1,-1} , dy[] = {0,0,1,-1,1,-1}; */ // Hexagonal Direction int power(int a, int b) { int ans = 1; while (b) { if (b & 1) ans *= a; a *= a; b >>= 1; }return ans; } bool isPrime(int n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } bool ok(vi& v) { int cnt = 0; for (int i = 0; i < v.size(); i++) { if (isPrime(v[i])) cnt++; } if (cnt == 2) return true; return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int test; test = 1; //cin >> test; while (test--) { int n; cin >> n; vvi v(n, vi(3)); for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) cin >> v[i][j]; } vvi ans(n, vi(3)); for (int i = 0; i < 3; i++) ans[0][i] = v[0][i]; for (int i = 1; i < n; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (k == j) continue; ans[i][j] = max(ans[i][j], v[i][j] + ans[i - 1][k]); } } } int maxi = 0; for (int i = 0; i < 3; i++) maxi = max(maxi, ans[n - 1][i]); cout << maxi << endl; } }
No
Do these codes solve the same problem? Code 1: import heapq from collections import deque N = int(input()) A = [[int(a) for a in input().split()] for _ in range(N)] def dijkstra_heap(s, edge, n): #始点sから各頂点への最短距離 d = [10**9+1] * n used = [True] * n #True:未確定 d[s] = 0 used[s] = False edgelist = [] for a,b in edge[s]: heapq.heappush(edgelist,a*(10**6)+b) while len(edgelist): minedge = heapq.heappop(edgelist) #まだ使われてない頂点の中から最小の距離のものを探す if not used[minedge%(10**6)]: continue v = minedge%(10**6) d[v] = minedge//(10**6) used[v] = False for e in edge[v]: if used[e[1]]: heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1]) return d Road = [[] for _ in range(N)] h = [] for i in range(N): for j in range(i+1, N): heapq.heappush(h, (A[i][j], i, j)) m = h[0][0] D = [[10**9+1]*N for _ in range(N)] ans = 0 while h: t = heapq.heappop(h) cost = t[0] i = t[1] j = t[2] if cost < 2*m: Road[i].append((cost, j)) Road[j].append((cost, i)) D[i][j] = cost D[j][i] = cost elif D[i][j] > cost: D[i] = dijkstra_heap(i, Road, N) if D[i][j] > cost: Road[i].append((cost, j)) Road[j].append((cost, i)) D[i][j] = cost D[j][i] = cost if D[i][j] < cost: ans = -1 break if ans == 0: for i in range(N): for t in Road[i]: ans += t[0] ans //= 2 print(ans) Code 2: #include <string> #include <vector> #include <algorithm> #include <numeric> #include <set> #include <map> #include <queue> #include<stack> #include<bitset> #include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <cctype> #include <cassert> #include <limits> #include <functional> #include<unordered_map> #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i)) #define aut(r,v) for(auto r:v) #define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it) #define all(o) (o).begin(), (o).end() #define pb(x) push_back(x) #define pc() pop_back() #define ull unsigned long long #define mp(x,y) make_pair((x),(y)) #define mset(m,v) memset(m,v,sizeof(m)) #define INF 0x3f3f3f3f #define INFL 0x3f3f3f3f3f3f3f3fLL using namespace std; #define endl '\n' #define st stack<int> #define vl vector<long long> #define vi vector<int> #define vb vector<bool> #define vc vector<char> #define pii pair<int,int> #define vpii vector<pii> #define vvi vector<vi> #define vs vector<string> #define mod 1000000007 #define un unordered_map<int,int> #define mii map<int,int> #define Sort(a) sort(all(a)) #define ED(a) Sort(a), a.erase(unique(all(a)), a.end())//removing all duplicates #define max3(a, b, c) max(a, max(b, c)) #define min3(a, b, c) min(a, min(b, c)) #define Max(a) *max_element(all(a)) #define Min(a) *min_element(all(a)) #define MaxP(a) max_element(all(a)) - a.begin() #define MinP(a) min_element(all(a)) - a.begin() #define allUpper(a) transform(all(a), a.begin(), :: toupper) #define allLower(a) transform(all(a), a.begin(), :: tolower) #define rev(a) reverse(all(a)) #define ub(v,k) upper_bound(all(v), k) - v.begin() #define lb(v,k) lower_bound(all(v), k) - v.begin() #define adv(a,n) advance(auto it:a,n) #define RSort(a) sort(a.rbegin(),a.rend()) //decending order #define cnt(v,a) count(all(v),a) #define bs(v,a) binary_search(all(v),a) #define mmax(v) *max_element(all(v)) #define mmin(v) *min_element(all(v)) #define popcount(mask) __builtin_popcount(mask) // count set bit #define popcountLL(mask) __builtin_popcountll(mask) // for long long #define X real() // useful for working with #include <complex> for computational geometry #define Y imag() #define ll long long #define ss second #define ff first #define trace1(x) cerr << #x << ": " << x << endl; #define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl; #define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl; #define trace4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl; #define trace5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl; #define trace6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl; template <typename T> T gcd(T a, T b) { while (b) b ^= a ^= b ^= a %= b; return a; } template <typename T> T setbit(T mask, T pos) { return mask |= (1 << pos); } template <typename T> T resetbit(T mask, T pos) { return mask &= ~(1 << pos); } template <typename T> T togglebit(T mask, T pos) { return mask ^= (1 << pos); } template <typename T> T checkbit(T mask, T pos) { return (bool)(mask & (1 << pos)); } template <typename T> T lcm(T a, T b) { return (a / gcd(a, b)) * b; } template <typename T> T modu(T a, T b) { return (a < b ? a : a % b); } template<typename T> T mod_neg(T a, T b) { a = mod(a, b); if (a < 0) { a += b; } return a; } template <typename T>T expo(T e, T n) { T x = 1, p = e; while (n) { if (n & 1)x = x * p; p = p * p; n >>= 1; } return x; } template<typename T> T mod_inverse(T a, T n) { T x, y; T d = extended_euclid(a, n, x, y); return (d > 1 ? -1 : mod_neg(x, n)); } template <typename T>T power(T e, T n, T m) { T x = 1, p = e; while (n) { if (n & 1)x = mod(x * p, m); p = mod(p * p, m); n >>= 1; } return x; } template <typename T>T powerL(T e, T n, T m) { T x = 1, p = e; while (n) { if (n & 1)x = mulmod(x, p, m); p = mulmod(p, p, m); n >>= 1; } return x; } bool Pow2(int n) { return n && (!(n & (n - 1))); } void printc(vc& result) { aut(r, result) cout << r << " "; cout << endl; } void printl(vl& result) { aut(r, result) cout << r << " "; cout << endl; } void print(vi& result) { aut(r, result) cout << r << " "; cout << endl; } // Recursively computes the power int binpow(int a, int b) { if (b == 0) return a; int res = binpow(a, b / 2); if (b % 2) return res * res * a; else return res * res; } // iteratively computes the power int pow(int a, int b) { int res = 1; while (b) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } int modpow(int a, int b, int m) { int ans = 1; while (b) { if (b & 1) ans = (ans * a) % m; b /= 2; a = (a * a) % m; } return ans; } const int MOD = 1000000000 + 7; const int MXX = 100000 + 69; int fact[MXX], invfact[MXX]; int modinv(int k) { return modpow(k, MOD - 2, MOD); } void combinatorics() { fact[0] = fact[1] = 1; for (int i = 2; i < MXX; i++) { fact[i] = fact[i - 1] * i; fact[i] %= MOD; } invfact[MXX - 1] = modinv(fact[MXX - 1]); for (int i = MXX - 2; i >= 0; i--) { invfact[i] = invfact[i + 1] * (i + 1); invfact[i] %= MOD; } } int nCr(int x, int y) { if (y > x) return 0; int num = fact[x]; num *= invfact[y]; num %= MOD; num *= invfact[x - y]; num %= MOD; return num; } //ifstream cin("b_read_on.txt"); ofstream cout("output3.txt"); //Use (<<) for multiplication //Use (>>) for division //ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);cout<<fixed;cerr.tie(NULL); // find_by_order -> value at index // order_of_key -> index of value // while using (1<<i) use ((ll)1<<(ll)i) // in Floyd-Warshall Algo, k is outer loop // If an element was not initially in map and if asked mp[a],the element gets inserted // a%=mod take a lot of time... try to use it minimum and use memset as it reduces a lot of time usage...use if(a>=mod) a%=mod //cout<<(double) can be harmful , always use printf(%.9llf)...take scanf("%lf",&p[i][j]) as input , not llf; //use s.erase(it++) for erasing iterator and then moving to the next one //never use adj.resize(n) as value is persistent, always erase //use __builtin_popcountll() for ll // no of prime numbers in range : (70,19) , (1000,168) , (100000,1229) , (sqrt(10^9),3409) ; //always check the use of segment tree using bottom-up dp /* int dx[] = {1,-1,0,0} , dy[] = {0,0,1,-1}; */ // 4 Direction /* int dx[] = {1,-1,0,0,1,1,-1,-1} , dy[] = {0,0,1,-1,1,-1,1,-1}; */ // 8 Direction /* int dx[] = {1,-1,1,-1,2,2,-2,-2} , dy[] = {2,2,-2,-2,1,-1,1,-1}; */ // Knight Direction /* int dx[] = {2,-2,1,1,-1,-1} , dy[] = {0,0,1,-1,1,-1}; */ // Hexagonal Direction int power(int a, int b) { int ans = 1; while (b) { if (b & 1) ans *= a; a *= a; b >>= 1; }return ans; } bool isPrime(int n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } bool ok(vi& v) { int cnt = 0; for (int i = 0; i < v.size(); i++) { if (isPrime(v[i])) cnt++; } if (cnt == 2) return true; return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int test; test = 1; //cin >> test; while (test--) { int n; cin >> n; vvi v(n, vi(3)); for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) cin >> v[i][j]; } vvi ans(n, vi(3)); for (int i = 0; i < 3; i++) ans[0][i] = v[0][i]; for (int i = 1; i < n; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (k == j) continue; ans[i][j] = max(ans[i][j], v[i][j] + ans[i - 1][k]); } } } int maxi = 0; for (int i = 0; i < 3; i++) maxi = max(maxi, ans[n - 1][i]); cout << maxi << endl; } }
Python
#!usr/bin/env python3 from collections import defaultdict from collections import deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS():return list(map(list, sys.stdin.readline().split())) def S(): return list(sys.stdin.readline())[:-1] def IR(n): l = [None for i in range(n)] for i in range(n):l[i] = I() return l def LIR(n): l = [None for i in range(n)] for i in range(n):l[i] = LI() return l def SR(n): l = [None for i in range(n)] for i in range(n):l[i] = S() return l def LSR(n): l = [None for i in range(n)] for i in range(n):l[i] = LS() return l sys.setrecursionlimit(1000000) mod = 1000000007 #A def A(): n = I() a,b = LI() c,d = LI() a -= 1 b -= 1 c -= 1 d -= 1 ans = float("inf") for w in range(1,1000): ans = min(ans, abs(a%w-b%w)+abs(a//w-b//w)+abs(c%w-d%w)+abs(c//w-d//w)) print(ans) return #B def B(): n = I() dp = [-1]*394 dp[0] = 0 for i in range(n): l,r,p = LI() for j in range(l,394): for k in range(l,r+1): if j-k >= 0: if dp[j-k] >= 0: if dp[j-k]+p > dp[j]: dp[j] = dp[j-k]+p m = I() ans = [None for i in range(m)] for i in range(m): k = I() if dp[k] == -1: print(-1) quit() ans[i] = dp[k] for i in ans: print(i) return #C def C(): def dfs(x): if f[x] != None: return f[x] res = 0 for y,c in v[x]: res = max(res,dfs(y)+c) f[x] = res return f[x] n,m = LI() v = [[] for i in range(n)] f = defaultdict(lambda : None) f[0] = 0 for i in range(m): a,b,c = LI() v[b].append((a,c)) print(dfs(n-1)) return #D def D(): return #E def E(): return #F def F(): return #G def G(): return #H def H(): return #I def I_(): return #J def J(): return #Solve if __name__ == "__main__": C()
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; // G問題の類題: // AOJ2503: C: Project Management / プロジェクト管理 // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2503 // https://qiita.com/drken/items/03c7db44ccd27820ea0d // https://atcoder.jp/contests/dp/tasks namespace EducationalDPContest.G_AOJ2503 { using static Util; struct Dest { public int Y; public int Len; public Dest(int y, int len) { Y = y; Len = len; } } // メモ化再帰による解法 // https://qiita.com/drken/items/03c7db44ccd27820ea0d // 『DP の更新順序が非自明』な場合にはメモ化再帰が大きなメリットを生むという一例 // ※明示的なトポロジカルソートが不要になる public class Solver : SolverBase { int[] DP; List<Dest>[] Edges; public void Run() { var ary = ReadIntArray(); var N = ary[0]; var M = ary[1]; // Listの配列 に x -> [y, len] を格納していく Edges = new List<Dest>[N]; for (int i = 0; i < N; i++) { Edges[i] = new List<Dest>(); } for (int i = 0; i < M; i++) { var xyl = ReadIntArray(); var x = xyl[0]; var y = xyl[1]; var l = xyl[2]; Edges[x].Add(new Dest(y, l)); } DP = new int[N + 1]; InitArray(DP, -1); // 全ノードをメモ化再帰で回して、最長を更新していく int maxLen = 0; for (int x = 0; x < N; x++) { var len = Recurse(x); if (maxLen < len) maxLen = len; } WriteLine(maxLen); } // xからの最長経路長を返す int Recurse(int x) { if (DP[x] != -1) return DP[x]; // x->y の y でループ再帰 int maxLen = 0; foreach (var dest in Edges[x]) { var len = Recurse(dest.Y) + dest.Len; if (maxLen < len) maxLen = len; } // メモしながら返す return DP[x] = maxLen; } #if !MYHOME public static void Main(string[] args) { new Solver().Run(); } #endif } public static class Util { public readonly static long MOD = 1000000007; public static string DumpToString<T>(IEnumerable<T> array) where T : IFormattable { var sb = new StringBuilder(); foreach (var item in array) { sb.Append(item); sb.Append(", "); } return sb.ToString(); } public static void InitArray<T>(T[] ary, T value) { for (int i = 0; i < ary.Length; i++) { ary[i] = value; } } public static void InitDP<T>(T[,] dp, T value) { for (int i = 0; i < dp.GetLength(0); i++) { for (int j = 0; j < dp.GetLength(1); j++) { dp[i, j] = value; } } } public static T Max<T>(params T[] nums) where T : IComparable { if (nums.Length == 0) return default(T); T max = nums[0]; for (int i = 1; i < nums.Length; i++) { max = max.CompareTo(nums[i]) > 0 ? max : nums[i]; } return max; } public static T Min<T>(params T[] nums) where T : IComparable { if (nums.Length == 0) return default(T); T min = nums[0]; for (int i = 1; i < nums.Length; i++) { min = min.CompareTo(nums[i]) < 0 ? min : nums[i]; } return min; } /// <summary> /// ソート済み配列 ary に同じ値の要素が含まれている? /// ※ソート順は昇順/降順どちらでもよい /// </summary> public static bool HasDuplicateInSortedArray<T>(T[] ary) where T : IComparable, IComparable<T> { if (ary.Length <= 1) return false; var lastNum = ary[ary.Length - 1]; foreach (var n in ary) { if (lastNum.CompareTo(n) == 0) { return true; } else { lastNum = n; } } return false; } /// <summary> /// 二分探索 /// ※条件を満たす最小のidxを返す /// ※満たすものがない場合は ary.Length を返す /// ※『aryの先頭側が条件を満たさない、末尾側が条件を満たす』という前提 /// ただし、IsOK(...)の戻り値を逆転させれば、逆でも同じことが可能。 /// </summary> /// <param name="ary">探索対象配列 ★ソート済みであること</param> /// <param name="key">探索値 ※これ以上の値を持つ(IsOKがtrueを返す)最小のindexを返す</param> public static int BinarySearch<T>(T[] ary, T key) where T : IComparable, IComparable<T> { int left = -1; int right = ary.Length; while (1 < right - left) { var mid = left + (right - left) / 2; if (IsOK(ary, mid, key)) { right = mid; } else { left = mid; } } // left は条件を満たさない最大の値、right は条件を満たす最小の値になっている return right; } public static bool IsOK<T>(T[] ary, int idx, T key) where T : IComparable, IComparable<T> { // key <= ary[idx] と同じ意味 return key.CompareTo(ary[idx]) <= 0; } } public class SolverBase { virtual protected string ReadLine() => Console.ReadLine(); virtual protected int ReadInt() => int.Parse(ReadLine()); virtual protected long ReadLong() => long.Parse(ReadLine()); virtual protected string[] ReadStringArray() => ReadLine().Split(' '); virtual protected int[] ReadIntArray() => ReadLine().Split(' ').Select<string, int>(s => int.Parse(s)).ToArray(); virtual protected long[] ReadLongArray() => ReadLine().Split(' ').Select<string, long>(s => long.Parse(s)).ToArray(); virtual protected double[] ReadDoubleArray() => ReadLine().Split(' ').Select<string, double>(s => double.Parse(s)).ToArray(); virtual protected void WriteLine(string line) => Console.WriteLine(line); virtual protected void WriteLine(double d) => Console.WriteLine($"{d:F9}"); virtual protected void WriteLine<T>(T value) where T : IFormattable => Console.WriteLine(value); [Conditional("DEBUG")] protected void Dump(string s) => Console.WriteLine(s); [Conditional("DEBUG")] protected void Dump(char c) => Console.WriteLine(c); [Conditional("DEBUG")] protected void Dump(double d) => Console.WriteLine($"{d:F9}"); [Conditional("DEBUG")] protected void Dump<T>(IEnumerable<T> array) where T : IFormattable { string s = Util.DumpToString(array); // Consoleに出力すると、UnitTestの邪魔をしないというメリットあり。 Console.WriteLine(s); //_writer.WriteLine(s); } [Conditional("DEBUG")] protected void DumpGrid<T>(IEnumerable<IEnumerable<T>> arrayOfArray) where T : IFormattable { var sb = new StringBuilder(); foreach (var a in arrayOfArray) { sb.AppendLine(Util.DumpToString(a)); } // Consoleに出力すると、UnitTestの邪魔をしないというメリットあり。 Console.WriteLine(sb.ToString()); //_writer.WriteLine(sb.ToString()); } [Conditional("DEBUG")] protected void DumpDP<T>(T[,] dp) where T : IFormattable { var sb = new StringBuilder(); for (int i = 0; i < dp.GetLength(0); i++) { for (int j = 0; j < dp.GetLength(1); j++) { sb.Append(dp[i, j]); sb.Append(", "); } sb.AppendLine(); } Console.WriteLine(sb.ToString()); } } }
Yes
Do these codes solve the same problem? Code 1: #!usr/bin/env python3 from collections import defaultdict from collections import deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS():return list(map(list, sys.stdin.readline().split())) def S(): return list(sys.stdin.readline())[:-1] def IR(n): l = [None for i in range(n)] for i in range(n):l[i] = I() return l def LIR(n): l = [None for i in range(n)] for i in range(n):l[i] = LI() return l def SR(n): l = [None for i in range(n)] for i in range(n):l[i] = S() return l def LSR(n): l = [None for i in range(n)] for i in range(n):l[i] = LS() return l sys.setrecursionlimit(1000000) mod = 1000000007 #A def A(): n = I() a,b = LI() c,d = LI() a -= 1 b -= 1 c -= 1 d -= 1 ans = float("inf") for w in range(1,1000): ans = min(ans, abs(a%w-b%w)+abs(a//w-b//w)+abs(c%w-d%w)+abs(c//w-d//w)) print(ans) return #B def B(): n = I() dp = [-1]*394 dp[0] = 0 for i in range(n): l,r,p = LI() for j in range(l,394): for k in range(l,r+1): if j-k >= 0: if dp[j-k] >= 0: if dp[j-k]+p > dp[j]: dp[j] = dp[j-k]+p m = I() ans = [None for i in range(m)] for i in range(m): k = I() if dp[k] == -1: print(-1) quit() ans[i] = dp[k] for i in ans: print(i) return #C def C(): def dfs(x): if f[x] != None: return f[x] res = 0 for y,c in v[x]: res = max(res,dfs(y)+c) f[x] = res return f[x] n,m = LI() v = [[] for i in range(n)] f = defaultdict(lambda : None) f[0] = 0 for i in range(m): a,b,c = LI() v[b].append((a,c)) print(dfs(n-1)) return #D def D(): return #E def E(): return #F def F(): return #G def G(): return #H def H(): return #I def I_(): return #J def J(): return #Solve if __name__ == "__main__": C() Code 2: using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; // G問題の類題: // AOJ2503: C: Project Management / プロジェクト管理 // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2503 // https://qiita.com/drken/items/03c7db44ccd27820ea0d // https://atcoder.jp/contests/dp/tasks namespace EducationalDPContest.G_AOJ2503 { using static Util; struct Dest { public int Y; public int Len; public Dest(int y, int len) { Y = y; Len = len; } } // メモ化再帰による解法 // https://qiita.com/drken/items/03c7db44ccd27820ea0d // 『DP の更新順序が非自明』な場合にはメモ化再帰が大きなメリットを生むという一例 // ※明示的なトポロジカルソートが不要になる public class Solver : SolverBase { int[] DP; List<Dest>[] Edges; public void Run() { var ary = ReadIntArray(); var N = ary[0]; var M = ary[1]; // Listの配列 に x -> [y, len] を格納していく Edges = new List<Dest>[N]; for (int i = 0; i < N; i++) { Edges[i] = new List<Dest>(); } for (int i = 0; i < M; i++) { var xyl = ReadIntArray(); var x = xyl[0]; var y = xyl[1]; var l = xyl[2]; Edges[x].Add(new Dest(y, l)); } DP = new int[N + 1]; InitArray(DP, -1); // 全ノードをメモ化再帰で回して、最長を更新していく int maxLen = 0; for (int x = 0; x < N; x++) { var len = Recurse(x); if (maxLen < len) maxLen = len; } WriteLine(maxLen); } // xからの最長経路長を返す int Recurse(int x) { if (DP[x] != -1) return DP[x]; // x->y の y でループ再帰 int maxLen = 0; foreach (var dest in Edges[x]) { var len = Recurse(dest.Y) + dest.Len; if (maxLen < len) maxLen = len; } // メモしながら返す return DP[x] = maxLen; } #if !MYHOME public static void Main(string[] args) { new Solver().Run(); } #endif } public static class Util { public readonly static long MOD = 1000000007; public static string DumpToString<T>(IEnumerable<T> array) where T : IFormattable { var sb = new StringBuilder(); foreach (var item in array) { sb.Append(item); sb.Append(", "); } return sb.ToString(); } public static void InitArray<T>(T[] ary, T value) { for (int i = 0; i < ary.Length; i++) { ary[i] = value; } } public static void InitDP<T>(T[,] dp, T value) { for (int i = 0; i < dp.GetLength(0); i++) { for (int j = 0; j < dp.GetLength(1); j++) { dp[i, j] = value; } } } public static T Max<T>(params T[] nums) where T : IComparable { if (nums.Length == 0) return default(T); T max = nums[0]; for (int i = 1; i < nums.Length; i++) { max = max.CompareTo(nums[i]) > 0 ? max : nums[i]; } return max; } public static T Min<T>(params T[] nums) where T : IComparable { if (nums.Length == 0) return default(T); T min = nums[0]; for (int i = 1; i < nums.Length; i++) { min = min.CompareTo(nums[i]) < 0 ? min : nums[i]; } return min; } /// <summary> /// ソート済み配列 ary に同じ値の要素が含まれている? /// ※ソート順は昇順/降順どちらでもよい /// </summary> public static bool HasDuplicateInSortedArray<T>(T[] ary) where T : IComparable, IComparable<T> { if (ary.Length <= 1) return false; var lastNum = ary[ary.Length - 1]; foreach (var n in ary) { if (lastNum.CompareTo(n) == 0) { return true; } else { lastNum = n; } } return false; } /// <summary> /// 二分探索 /// ※条件を満たす最小のidxを返す /// ※満たすものがない場合は ary.Length を返す /// ※『aryの先頭側が条件を満たさない、末尾側が条件を満たす』という前提 /// ただし、IsOK(...)の戻り値を逆転させれば、逆でも同じことが可能。 /// </summary> /// <param name="ary">探索対象配列 ★ソート済みであること</param> /// <param name="key">探索値 ※これ以上の値を持つ(IsOKがtrueを返す)最小のindexを返す</param> public static int BinarySearch<T>(T[] ary, T key) where T : IComparable, IComparable<T> { int left = -1; int right = ary.Length; while (1 < right - left) { var mid = left + (right - left) / 2; if (IsOK(ary, mid, key)) { right = mid; } else { left = mid; } } // left は条件を満たさない最大の値、right は条件を満たす最小の値になっている return right; } public static bool IsOK<T>(T[] ary, int idx, T key) where T : IComparable, IComparable<T> { // key <= ary[idx] と同じ意味 return key.CompareTo(ary[idx]) <= 0; } } public class SolverBase { virtual protected string ReadLine() => Console.ReadLine(); virtual protected int ReadInt() => int.Parse(ReadLine()); virtual protected long ReadLong() => long.Parse(ReadLine()); virtual protected string[] ReadStringArray() => ReadLine().Split(' '); virtual protected int[] ReadIntArray() => ReadLine().Split(' ').Select<string, int>(s => int.Parse(s)).ToArray(); virtual protected long[] ReadLongArray() => ReadLine().Split(' ').Select<string, long>(s => long.Parse(s)).ToArray(); virtual protected double[] ReadDoubleArray() => ReadLine().Split(' ').Select<string, double>(s => double.Parse(s)).ToArray(); virtual protected void WriteLine(string line) => Console.WriteLine(line); virtual protected void WriteLine(double d) => Console.WriteLine($"{d:F9}"); virtual protected void WriteLine<T>(T value) where T : IFormattable => Console.WriteLine(value); [Conditional("DEBUG")] protected void Dump(string s) => Console.WriteLine(s); [Conditional("DEBUG")] protected void Dump(char c) => Console.WriteLine(c); [Conditional("DEBUG")] protected void Dump(double d) => Console.WriteLine($"{d:F9}"); [Conditional("DEBUG")] protected void Dump<T>(IEnumerable<T> array) where T : IFormattable { string s = Util.DumpToString(array); // Consoleに出力すると、UnitTestの邪魔をしないというメリットあり。 Console.WriteLine(s); //_writer.WriteLine(s); } [Conditional("DEBUG")] protected void DumpGrid<T>(IEnumerable<IEnumerable<T>> arrayOfArray) where T : IFormattable { var sb = new StringBuilder(); foreach (var a in arrayOfArray) { sb.AppendLine(Util.DumpToString(a)); } // Consoleに出力すると、UnitTestの邪魔をしないというメリットあり。 Console.WriteLine(sb.ToString()); //_writer.WriteLine(sb.ToString()); } [Conditional("DEBUG")] protected void DumpDP<T>(T[,] dp) where T : IFormattable { var sb = new StringBuilder(); for (int i = 0; i < dp.GetLength(0); i++) { for (int j = 0; j < dp.GetLength(1); j++) { sb.Append(dp[i, j]); sb.Append(", "); } sb.AppendLine(); } Console.WriteLine(sb.ToString()); } } }
Java
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); EBinaryProgramming solver = new EBinaryProgramming(); solver.solve(1, in, out); out.close(); } } static class EBinaryProgramming { public void solve(int testNumber, FastInput in, FastOutput out) { int[] s = new int[(int) 2e5]; int n = in.readString(s, 0); for (int i = 0; i < n; i++) { s[i] -= '0'; } IntegerPreSum[] ips = new IntegerPreSum[2]; ips[0] = new IntegerPreSum(i -> i % 2 == 0 && s[i] == 1 ? 1 : 0, n); ips[1] = new IntegerPreSum(i -> i % 2 == 1 && s[i] == 1 ? 1 : 0, n); long ans = 0; boolean[] used = new boolean[n]; boolean[] star = new boolean[n]; int cnt = 0; for (int i = 0; i < n; i++) { if (s[i] == 1) { used[i] = true; star[i] = true; cnt++; ans += cnt; if (i + 1 < n) { used[i + 1] = true; ans += cnt; i++; } } } IntegerPreSum occur = new IntegerPreSum(i -> used[i] ? 1 : 0, n); for (int i = n - 1; i >= 0; i--) { if (used[i]) { if (star[i]) { cnt--; } continue; } ans += cnt; if (occur.prefix(i - 1) % 2 == 0) { ans += ips[i % 2].post(i); } else { ans += ips[1 - i % 2].post(i); } } out.println(ans); } } static interface IntToIntegerFunction { int apply(int x); } static class IntegerPreSum { private int[] pre; private int n; public IntegerPreSum(int n) { pre = new int[n]; } public void populate(IntToIntegerFunction a, int n) { this.n = n; if (n == 0) { return; } pre[0] = a.apply(0); for (int i = 1; i < n; i++) { pre[i] = pre[i - 1] + a.apply(i); } } public IntegerPreSum(IntToIntegerFunction a, int n) { this(n); populate(a, n); } public int prefix(int i) { if (i < 0) { return 0; } return pre[Math.min(i, n - 1)]; } public int post(int i) { return pre[n - 1] - prefix(i - 1); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(long c) { cache.append(c); return this; } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readString(int[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } } }
PHP
<?php fscanf(STDIN, "%s", $N); $array = str_split($N); $length = count($array); $list = []; $copy = $array; $k=1; $ans = 0; $last = -1; $t=0; for($i=0;$i<$length-1;$i++){ if($array[$i] === "1"){ if($array[$i+1] === "0"){ $list[] = $i; $list[] = $i+1; unset($copy[$i]); unset($copy[$i+1]); $i++; $ans += $k*2; $k++; $last = -1; }else{ if(isset($array[$i+2])){ if(!isset($array[$i+4]) && $array[$i+1] ==="1" && $array[$i+2]==="1" && $array[$i+3]==="1"){ $list[] = $i; $list[] = $i+1; $list[] = $i+2; $list[] = $i+3; unset($copy[$i]); unset($copy[$i+1]); unset($copy[$i+2]); unset($copy[$i+3]); $i+=3; $ans += $k*2; $k++; $ans += $k*2; $k++; $t = 1; $last = -1; }elseif($array[$i+2] === "1"){ $list[] = $i; $list[] = $i+1; unset($copy[$i]); unset($copy[$i+1]); $i++; $ans += $k*2; $k++; $last = -1; }else{ $list[] = $i; $list[] = $i+2; unset($copy[$i]); unset($copy[$i+2]); $i+=2; $ans += $k*2; $k++; $last = -1; } }elseif($array[$i+1]==="1"){ $list[] = $i; $list[] = $i+1; unset($copy[$i]); unset($copy[$i+1]); $i++; $ans += $k*2; $k++; $last = -1; $t = 1; }else{ $last = $i; } } } } if(count($copy)===0){ echo$ans; exit; } if($last >= 0 ){ $ans += $k; $list[] = $last; unset($copy[$i]); }elseif($array[$length-1] === "1" && $t === 0) { $ans += $k; $list[] = $length-1; unset($copy[$i]); }else{ if(count($list) === 0){ echo 0; exit; } $k--; } krsort($copy); $reverse = 0; $truth = 0; $next = count($list)-1; //$next = $list[$list_count]; foreach($copy as $key=>$value){ if( $next >= 0 && $key < $list[$next]){ while ($key < $list[$next]) { if($array[$list[$next]] === "1"){ if($next % 2 === 0){ $truth++; $k--; }else{ $reverse++; } } // if ($next === 0) { // break; // } $next--; if($next < 0){ break; } } } if( $next === -1 || $key > $list[$next]){ if($value === "1"){ if($next % 2 === 0){ $truth++; }else{ $reverse++; } } $tmp = $truth ; $truth = $reverse; $reverse = $tmp; $ans += $k + $truth; } } echo $ans;
Yes
Do these codes solve the same problem? Code 1: import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); EBinaryProgramming solver = new EBinaryProgramming(); solver.solve(1, in, out); out.close(); } } static class EBinaryProgramming { public void solve(int testNumber, FastInput in, FastOutput out) { int[] s = new int[(int) 2e5]; int n = in.readString(s, 0); for (int i = 0; i < n; i++) { s[i] -= '0'; } IntegerPreSum[] ips = new IntegerPreSum[2]; ips[0] = new IntegerPreSum(i -> i % 2 == 0 && s[i] == 1 ? 1 : 0, n); ips[1] = new IntegerPreSum(i -> i % 2 == 1 && s[i] == 1 ? 1 : 0, n); long ans = 0; boolean[] used = new boolean[n]; boolean[] star = new boolean[n]; int cnt = 0; for (int i = 0; i < n; i++) { if (s[i] == 1) { used[i] = true; star[i] = true; cnt++; ans += cnt; if (i + 1 < n) { used[i + 1] = true; ans += cnt; i++; } } } IntegerPreSum occur = new IntegerPreSum(i -> used[i] ? 1 : 0, n); for (int i = n - 1; i >= 0; i--) { if (used[i]) { if (star[i]) { cnt--; } continue; } ans += cnt; if (occur.prefix(i - 1) % 2 == 0) { ans += ips[i % 2].post(i); } else { ans += ips[1 - i % 2].post(i); } } out.println(ans); } } static interface IntToIntegerFunction { int apply(int x); } static class IntegerPreSum { private int[] pre; private int n; public IntegerPreSum(int n) { pre = new int[n]; } public void populate(IntToIntegerFunction a, int n) { this.n = n; if (n == 0) { return; } pre[0] = a.apply(0); for (int i = 1; i < n; i++) { pre[i] = pre[i - 1] + a.apply(i); } } public IntegerPreSum(IntToIntegerFunction a, int n) { this(n); populate(a, n); } public int prefix(int i) { if (i < 0) { return 0; } return pre[Math.min(i, n - 1)]; } public int post(int i) { return pre[n - 1] - prefix(i - 1); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(long c) { cache.append(c); return this; } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readString(int[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } } } Code 2: <?php fscanf(STDIN, "%s", $N); $array = str_split($N); $length = count($array); $list = []; $copy = $array; $k=1; $ans = 0; $last = -1; $t=0; for($i=0;$i<$length-1;$i++){ if($array[$i] === "1"){ if($array[$i+1] === "0"){ $list[] = $i; $list[] = $i+1; unset($copy[$i]); unset($copy[$i+1]); $i++; $ans += $k*2; $k++; $last = -1; }else{ if(isset($array[$i+2])){ if(!isset($array[$i+4]) && $array[$i+1] ==="1" && $array[$i+2]==="1" && $array[$i+3]==="1"){ $list[] = $i; $list[] = $i+1; $list[] = $i+2; $list[] = $i+3; unset($copy[$i]); unset($copy[$i+1]); unset($copy[$i+2]); unset($copy[$i+3]); $i+=3; $ans += $k*2; $k++; $ans += $k*2; $k++; $t = 1; $last = -1; }elseif($array[$i+2] === "1"){ $list[] = $i; $list[] = $i+1; unset($copy[$i]); unset($copy[$i+1]); $i++; $ans += $k*2; $k++; $last = -1; }else{ $list[] = $i; $list[] = $i+2; unset($copy[$i]); unset($copy[$i+2]); $i+=2; $ans += $k*2; $k++; $last = -1; } }elseif($array[$i+1]==="1"){ $list[] = $i; $list[] = $i+1; unset($copy[$i]); unset($copy[$i+1]); $i++; $ans += $k*2; $k++; $last = -1; $t = 1; }else{ $last = $i; } } } } if(count($copy)===0){ echo$ans; exit; } if($last >= 0 ){ $ans += $k; $list[] = $last; unset($copy[$i]); }elseif($array[$length-1] === "1" && $t === 0) { $ans += $k; $list[] = $length-1; unset($copy[$i]); }else{ if(count($list) === 0){ echo 0; exit; } $k--; } krsort($copy); $reverse = 0; $truth = 0; $next = count($list)-1; //$next = $list[$list_count]; foreach($copy as $key=>$value){ if( $next >= 0 && $key < $list[$next]){ while ($key < $list[$next]) { if($array[$list[$next]] === "1"){ if($next % 2 === 0){ $truth++; $k--; }else{ $reverse++; } } // if ($next === 0) { // break; // } $next--; if($next < 0){ break; } } } if( $next === -1 || $key > $list[$next]){ if($value === "1"){ if($next % 2 === 0){ $truth++; }else{ $reverse++; } } $tmp = $truth ; $truth = $reverse; $reverse = $tmp; $ans += $k + $truth; } } echo $ans;
Python
L = int(input()) bL = bin(L)[2:] N = len(bL) L = 2 * (N-1) + bL[1:].count('1') print(N, L) for i, b in enumerate(bL[1:]): if b == '1': print(1, i+2, 0) M, m = 0, 0 for i, b in enumerate(bL[:0:-1]): add = M - m + 1 if b == '1': print(N-i-1, N-i, add) print(N-i-1, N-i, 2*add) m += add M += 2 * add else: print(N-i-1, N-i, 0) print(N-i-1, N-i, add) M += add
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using static System.Console; using static System.Math; class Z { static void Main() => new K(); } class K { int F => int.Parse(Str); long FL => long.Parse(Str); int[] G => Strs.Select(int.Parse).ToArray(); long[] GL => Strs.Select(long.Parse).ToArray(); string Str => ReadLine(); string[] Strs => Str.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); const int MOD = 1000000007; public K() { // SetOut(new StreamWriter(OpenStandardOutput()) { AutoFlush = false }); Solve(); Out.Flush(); } void Solve() { var L = F; var V = 1; while ((1 << V) <= L) V++; var es = new List<Edge>[V]; for (var i = 0; i < V; i++) es[i] = new List<Edge>(); for (var i = 0; i < V - 1; i++) { es[i].Add(new Edge(i + 1, 0)); es[i].Add(new Edge(i + 1, 1 << i)); } for (var i = 0; i < V - 1; i++) { if ((L & (1 << i)) != 0) { var tmp = (1 << 30) - 1; tmp ^= (1 << (i + 1)) - 1; es[i].Add(new Edge(V - 1, L & tmp)); } } var E = 0; foreach (var e in es) E += e.Count; WriteLine($"{V} {E}"); for (var i = 0; i < V; i++) foreach (var e in es[i]) WriteLine($"{i + 1} {e.To + 1} {e.Cost}"); var res = new List<Edge>[V]; for (var i = 0; i < V; i++) res[i] = new List<Edge>(); for (var i = 0; i < V; i++) foreach (var e in es[i]) res[e.To].Add(new Edge(i, e.Cost)); } } struct Edge { public readonly int To, Cost; public Edge(int t, int c) { To = t; Cost = c; } }
Yes
Do these codes solve the same problem? Code 1: L = int(input()) bL = bin(L)[2:] N = len(bL) L = 2 * (N-1) + bL[1:].count('1') print(N, L) for i, b in enumerate(bL[1:]): if b == '1': print(1, i+2, 0) M, m = 0, 0 for i, b in enumerate(bL[:0:-1]): add = M - m + 1 if b == '1': print(N-i-1, N-i, add) print(N-i-1, N-i, 2*add) m += add M += 2 * add else: print(N-i-1, N-i, 0) print(N-i-1, N-i, add) M += add Code 2: using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using static System.Console; using static System.Math; class Z { static void Main() => new K(); } class K { int F => int.Parse(Str); long FL => long.Parse(Str); int[] G => Strs.Select(int.Parse).ToArray(); long[] GL => Strs.Select(long.Parse).ToArray(); string Str => ReadLine(); string[] Strs => Str.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); const int MOD = 1000000007; public K() { // SetOut(new StreamWriter(OpenStandardOutput()) { AutoFlush = false }); Solve(); Out.Flush(); } void Solve() { var L = F; var V = 1; while ((1 << V) <= L) V++; var es = new List<Edge>[V]; for (var i = 0; i < V; i++) es[i] = new List<Edge>(); for (var i = 0; i < V - 1; i++) { es[i].Add(new Edge(i + 1, 0)); es[i].Add(new Edge(i + 1, 1 << i)); } for (var i = 0; i < V - 1; i++) { if ((L & (1 << i)) != 0) { var tmp = (1 << 30) - 1; tmp ^= (1 << (i + 1)) - 1; es[i].Add(new Edge(V - 1, L & tmp)); } } var E = 0; foreach (var e in es) E += e.Count; WriteLine($"{V} {E}"); for (var i = 0; i < V; i++) foreach (var e in es[i]) WriteLine($"{i + 1} {e.To + 1} {e.Cost}"); var res = new List<Edge>[V]; for (var i = 0; i < V; i++) res[i] = new List<Edge>(); for (var i = 0; i < V; i++) foreach (var e in es[i]) res[e.To].Add(new Edge(i, e.Cost)); } } struct Edge { public readonly int To, Cost; public Edge(int t, int c) { To = t; Cost = c; } }
Python
N, K = map(int, input().split()) R, S, P = map(int, input().split()) T = input() flag = [0]*N ans = 0 for i in range(N): if i-K>=0 and T[i-K] == T[i] and flag[i-K]: continue if T[i] == 'r': ans+=P elif T[i] == 's': ans+=R else: ans+=S flag[i] = True print(ans)
Java
import java.awt.Point; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.Set; import java.util.function.BinaryOperator; import java.util.function.UnaryOperator; public class Main implements Runnable{ private void solve(FastIO io, String[] args) { /* * author: 31536000 * ABC149 D問題 * 考察メモ * 基本的には貪欲に勝つ * ただし、K回前と今が同じ手なら、今を負けたことにする * それだけ * */ int N = io.nextInt(), K = io.nextInt(), R = io.nextInt(), S = io.nextInt(), P = io.nextInt(); char[] T = io.next().toCharArray(); long score = 0; for (int i = 0;i < K;++ i) { for (int j = i;j < N;j += K) { if (j + K < N && T[j + K] == T[j]) T[j + K] = 'o'; switch(T[j]) { case 'r': score += P; break; case 's': score += R; break; case 'p': score += S; break; } } } io.println(score); } /** デバッグ用コードのお供に */ private static boolean DEBUG = false; /** 確保するメモリの大きさ(単位: MB)*/ private static final long MEMORY = 64; private final FastIO io; private final String[] args; public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler((t, e) -> e.printStackTrace()); new Thread(null, new Main(args), "", MEMORY * 1048576).start(); } public Main(String[] args) { this(new FastIO(), args); } public Main(FastIO io, String... args) { this.io = io; this.args = args; if (DEBUG) io.setAutoFlush(true); } @Override public void run() { solve(io, args); io.flush(); } // 以下、ライブラリ /** * 高速な入出力を提供します。 * @author 31536000 * */ public static class FastIO { private InputStream in; private final byte[] buffer = new byte[1024]; private int read = 0; private int length = 0; private PrintWriter out; private PrintWriter err; private boolean autoFlush = false; public FastIO() { this(System.in, System.out, System.err); } public FastIO(InputStream in, PrintStream out, PrintStream err) { this.in = in; this.out = new PrintWriter(out, false); this.err = new PrintWriter(err, false); } public final void setInputStream(InputStream in) { this.in = in; } public final void setInputStream(File in) { try { this.in = new FileInputStream(in); } catch (FileNotFoundException e) { e.printStackTrace(); } } public final void setOutputStream(PrintStream out) { this.out = new PrintWriter(out, false); } public final void setOutputStream(File out) { try { this.out = new PrintWriter(new FileOutputStream(out), false); } catch (FileNotFoundException e) { e.printStackTrace(); } } public final void setErrorStream(PrintStream err) { this.err = new PrintWriter(err, false); } public final void setErrorStream(File err) { try { this.err = new PrintWriter(new FileOutputStream(err), false); } catch (FileNotFoundException e) { e.printStackTrace(); } } public final void setAutoFlush(boolean flush) { autoFlush = flush; } private boolean hasNextByte() { if (read < length) return true; read = 0; try { length = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } return length > 0; } private int readByte() { return hasNextByte() ? buffer[read++] : -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private static boolean isNumber(int c) { return '0' <= c && c <= '9'; } public final boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[read])) read++; return hasNextByte(); } public final char nextChar() { if (!hasNextByte()) throw new NoSuchElementException(); return (char)readByte(); } public final char[][] nextChar(int height) { char[][] ret = new char[height][]; for (int i = 0;i < ret.length;++ i) ret[i] = next().toCharArray(); return ret; } public final String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b; while (isPrintableChar(b = readByte())) sb.appendCodePoint(b); return sb.toString(); } public final String nextLine() { StringBuilder sb = new StringBuilder(); int b; while(!isPrintableChar(b = readByte())); do sb.appendCodePoint(b); while(isPrintableChar(b = readByte()) || b == ' '); return sb.toString(); } public final long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (!isNumber(b)) throw new NumberFormatException(); while (true) { if (isNumber(b)) { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) return minus ? -n : n; else throw new NumberFormatException(); b = readByte(); } } public final int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public final double nextDouble() { return Double.parseDouble(next()); } public final int[] nextInt(int width) { int[] ret = new int[width]; for (int i = 0;i < width;++ i) ret[i] = nextInt(); return ret; } public final int[] nextInts() { return nextInts(" "); } public final int[] nextInts(String parse) { String[] get = nextLine().split(parse); int[] ret = new int[get.length]; for (int i = 0;i < ret.length;++ i) ret[i] = Integer.valueOf(get[i]); return ret; } public final long[] nextLong(int width) { long[] ret = new long[width]; for (int i = 0;i < width;++ i) ret[i] = nextLong(); return ret; } public final long[] nextLongs() { return nextLongs(" "); } public final long[] nextLongs(String parse) { String[] get = nextLine().split(parse); long[] ret = new long[get.length]; for (int i = 0;i < ret.length;++ i) ret[i] = Long.valueOf(get[i]); return ret; } public final int[][] nextInt(int width, int height) { int[][] ret = new int[height][width]; for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[i][j] = nextInt(); return ret; } public final long[][] nextLong(int width, int height) { long[][] ret = new long[height][width]; for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[j][i] = nextLong(); return ret; } public final boolean[] nextBoolean(char T) { char[] s = next().toCharArray(); boolean[] ret = new boolean[s.length]; for (int i = 0;i < ret.length;++ i) ret[i] = s[i] == T; return ret; } public final boolean[][] nextBoolean(char T, int height) { boolean[][] ret = new boolean[height][]; for (int i = 0;i < ret.length;++ i) { char[] s = next().toCharArray(); ret[i] = new boolean[s.length]; for (int j = 0;j < ret[i].length;++ j) ret[i][j] = s[j] == T; } return ret; } public final Point nextPoint() { return new Point(nextInt(), nextInt()); } public final Point[] nextPoint(int width) { Point[] ret = new Point[width]; for (int i = 0;i < width;++ i) ret[i] = nextPoint(); return ret; } @Override protected void finalize() throws Throwable { try { super.finalize(); } finally { in.close(); out.close(); err.close(); } } public final boolean print(boolean b) { out.print(b); if (autoFlush) flush(); return b; } public final Object print(boolean b, Object t, Object f) { return b ? print(t) : print(f); } public final char print(char c) { out.print(c); if (autoFlush) flush(); return c; } public final char[] print(char[] s) { out.print(s); return s; } public final double print(double d) { out.print(d); if (autoFlush) flush(); return d; } public final double print(double d, int length) { if (d < 0) { out.print('-'); d = -d; } d += Math.pow(10, -length) / 2; out.print((long)d); out.print('.'); d -= (long)d; for (int i = 0;i < length;++ i) { d *= 10; out.print((int)d); d -= (int)d; } if (autoFlush) flush(); return d; } public final float print(float f) { out.print(f); if (autoFlush) flush(); return f; } public final int print(int i) { out.print(i); if (autoFlush) flush(); return i; } public final long print(long l) { out.print(l); if (autoFlush) flush(); return l; } public final Object print(Object obj) { if (obj.getClass().isArray()) { if (obj instanceof boolean[][]) print(obj, "\n", " "); else if (obj instanceof byte[][]) print(obj, "\n", " "); else if (obj instanceof short[][]) print(obj, "\n", " "); else if (obj instanceof int[][]) print(obj, "\n", " "); else if (obj instanceof long[][]) print(obj, "\n", " "); else if (obj instanceof float[][]) print(obj, "\n", " "); else if (obj instanceof double[][]) print(obj, "\n", " "); else if (obj instanceof char[][]) print(obj, "\n", " "); else if (obj instanceof Object[][]) print(obj, "\n", " "); else print(obj, " "); } else { out.print(obj); if (autoFlush) flush(); } return obj; } public final String print(String s) { out.print(s); if (autoFlush) flush(); return s; } public final Object print(Object array, String... parse) { print(array, 0, parse); if (autoFlush) flush(); return array; } private final Object print(Object array, int check, String... parse) { if (check >= parse.length) { if (array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension"); print(array); return array; } String str = parse[check]; if (array instanceof Object[]) { Object[] obj = (Object[]) array; if (obj.length == 0) return array; print(obj[0], check + 1, parse); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i], check + 1, parse); } return array; } if (array instanceof Collection) { Iterator<?> iter = ((Collection<?>)array).iterator(); if (!iter.hasNext()) return array; print(iter.next(), check + 1, parse); while(iter.hasNext()) { print(str); print(iter.next(), check + 1, parse); } return array; } if (!array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension"); if (check != parse.length - 1) throw new IllegalArgumentException("not equal dimension"); if (array instanceof boolean[]) { boolean[] obj = (boolean[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof byte[]) { byte[] obj = (byte[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } return array; } else if (array instanceof short[]) { short[] obj = (short[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof int[]) { int[] obj = (int[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof long[]) { long[] obj = (long[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof float[]) { float[] obj = (float[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof double[]) { double[] obj = (double[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof char[]) { char[] obj = (char[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else throw new AssertionError(); return array; } public final Object[] print(String parse, Object... args) { print(args[0]); for (int i = 1;i < args.length;++ i) { print(parse); print(args[i]); } return args; } public final Object[] printf(String format, Object... args) { out.printf(format, args); if (autoFlush) flush(); return args; } public final Object printf(Locale l, String format, Object... args) { out.printf(l, format, args); if (autoFlush) flush(); return args; } public final void println() { out.println(); if (autoFlush) flush(); } public final boolean println(boolean b) { out.println(b); if (autoFlush) flush(); return b; } public final Object println(boolean b, Object t, Object f) { return b ? println(t) : println(f); } public final char println(char c) { out.println(c); if (autoFlush) flush(); return c; } public final char[] println(char[] s) { out.println(s); if (autoFlush) flush(); return s; } public final double println(double d) { out.println(d); if (autoFlush) flush(); return d; } public final double println(double d, int length) { print(d, length); println(); return d; } public final float println(float f) { out.println(f); if (autoFlush) flush(); return f; } public final int println(int i) { out.println(i); if (autoFlush) flush(); return i; } public final long println(long l) { out.println(l); if (autoFlush) flush(); return l; } public final Object println(Object obj) { print(obj); println(); return obj; } public final String println(String s) { out.println(s); if (autoFlush) flush(); return s; } public final Object println(Object array, String... parse) { print(array, parse); println(); return array; } public final boolean debug(boolean b) { err.print(b); if (autoFlush) flush(); return b; } public final Object debug(boolean b, Object t, Object f) { return b ? debug(t) : debug(f); } public final char debug(char c) { err.print(c); if (autoFlush) flush(); return c; } public final char[] debug(char[] s) { err.print(s); return s; } public final double debug(double d) { err.print(d); if (autoFlush) flush(); return d; } public final double debug(double d, int length) { if (d < 0) { err.print('-'); d = -d; } d += Math.pow(10, -length) / 2; err.print((long)d); err.print('.'); d -= (long)d; for (int i = 0;i < length;++ i) { d *= 10; err.print((int)d); d -= (int)d; } if (autoFlush) flush(); return d; } public final float debug(float f) { err.print(f); if (autoFlush) flush(); return f; } public final int debug(int i) { err.print(i); if (autoFlush) flush(); return i; } public final long debug(long l) { err.print(l); if (autoFlush) flush(); return l; } public final Object debug(Object obj) { if (obj.getClass().isArray()) { if (obj instanceof boolean[][]) debug(obj, "\n", " "); else if (obj instanceof byte[][]) debug(obj, "\n", " "); else if (obj instanceof short[][]) debug(obj, "\n", " "); else if (obj instanceof int[][]) debug(obj, "\n", " "); else if (obj instanceof long[][]) debug(obj, "\n", " "); else if (obj instanceof float[][]) debug(obj, "\n", " "); else if (obj instanceof double[][]) debug(obj, "\n", " "); else if (obj instanceof char[][]) debug(obj, "\n", " "); else if (obj instanceof Object[][]) debug(obj, "\n", " "); else debug(obj, " "); } else { err.print(obj); if (autoFlush) flush(); } return obj; } public final String debug(String s) { err.print(s); if (autoFlush) flush(); return s; } public final Object debug(Object array, String... parse) { debug(array, 0, parse); if (autoFlush) flush(); return array; } private final Object debug(Object array, int check, String... parse) { if (check >= parse.length) { if (array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension"); debug(array); return array; } String str = parse[check]; if (array instanceof Object[]) { Object[] obj = (Object[]) array; if (obj.length == 0) return array; debug(obj[0], check + 1, parse); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i], check + 1, parse); } return array; } if (array instanceof Collection) { Iterator<?> iter = ((Collection<?>)array).iterator(); if (!iter.hasNext()) return array; debug(iter.next(), check + 1, parse); while(iter.hasNext()) { debug(str); debug(iter.next(), check + 1, parse); } return array; } if (!array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension"); if (check != parse.length - 1) throw new IllegalArgumentException("not equal dimension"); if (array instanceof boolean[]) { boolean[] obj = (boolean[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof byte[]) { byte[] obj = (byte[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } return array; } else if (array instanceof short[]) { short[] obj = (short[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof int[]) { int[] obj = (int[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof long[]) { long[] obj = (long[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof float[]) { float[] obj = (float[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof double[]) { double[] obj = (double[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof char[]) { char[] obj = (char[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else throw new AssertionError(); return array; } public final Object[] debug(String parse, Object... args) { debug(args[0]); for (int i = 1;i < args.length;++ i) { debug(parse); debug(args[i]); } return args; } public final Object[] debugf(String format, Object... args) { err.printf(format, args); if (autoFlush) flush(); return args; } public final Object debugf(Locale l, String format, Object... args) { err.printf(l, format, args); if (autoFlush) flush(); return args; } public final void debugln() { err.println(); if (autoFlush) flush(); } public final boolean debugln(boolean b) { err.println(b); if (autoFlush) flush(); return b; } public final Object debugln(boolean b, Object t, Object f) { return b ? debugln(t) : debugln(f); } public final char debugln(char c) { err.println(c); if (autoFlush) flush(); return c; } public final char[] debugln(char[] s) { err.println(s); if (autoFlush) flush(); return s; } public final double debugln(double d) { err.println(d); if (autoFlush) flush(); return d; } public final double debugln(double d, int length) { debug(d, length); debugln(); return d; } public final float debugln(float f) { err.println(f); if (autoFlush) flush(); return f; } public final int debugln(int i) { err.println(i); if (autoFlush) flush(); return i; } public final long debugln(long l) { err.println(l); if (autoFlush) flush(); return l; } public final Object debugln(Object obj) { debug(obj); debugln(); return obj; } public final String debugln(String s) { err.println(s); if (autoFlush) flush(); return s; } public final Object debugln(Object array, String... parse) { debug(array, parse); debugln(); return array; } public final void flush() { out.flush(); err.flush(); } } public enum BoundType { CLOSED, OPEN; } public static class Range<C> implements Serializable{ private static final long serialVersionUID = -4702828934863023392L; protected C lower; protected C upper; protected BoundType lowerType; protected BoundType upperType; private Comparator<? super C> comparator; protected Range(C lower, BoundType lowerType, C upper, BoundType upperType) { this(lower, lowerType, upper, upperType, null); } protected Range(C lower, BoundType lowerType, C upper, BoundType upperType, Comparator<? super C> comparator) { this.lower = lower; this.upper = upper; this.lowerType = lowerType; this.upperType = upperType; this.comparator = comparator; } public static <C extends Comparable<? super C>> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType) { if (lower != null && upper != null) { int comp = lower.compareTo(upper); if (comp > 0) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED); else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN))return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED); } return new Range<C>(lower, lowerType, upper, upperType); } public static <C> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType, Comparator<? super C> comparator) { if (lower != null && upper != null) { int comp = comparator.compare(lower, upper); if (comp > 0) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, comparator); else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN)) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, comparator); } return new Range<C>(lower, lowerType, upper, upperType, comparator); } public static <C extends Comparable<? super C>> Range<C> all() { return range((C)null, BoundType.OPEN, null, BoundType.OPEN); } public static <C> Range<C> all(Comparator<? super C> comparator) { return range((C)null, BoundType.OPEN, null, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> atMost(C upper) { return range(null, BoundType.OPEN, upper, BoundType.CLOSED); } public static <C> Range<C> atMost(C upper, Comparator<? super C> comparator) { return range(null, BoundType.OPEN, upper, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> lessThan(C upper) { return range(null, BoundType.OPEN, upper, BoundType.OPEN); } public static <C> Range<C> lessThan(C upper, Comparator<? super C> comparator) { return range(null, BoundType.OPEN, upper, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> downTo(C upper, BoundType boundType) { return range(null, BoundType.OPEN, upper, boundType); } public static <C> Range<C> downTo(C upper, BoundType boundType, Comparator<? super C> comparator) { return range(null, BoundType.OPEN, upper, boundType, comparator); } public static <C extends Comparable<? super C>> Range<C> atLeast(C lower) { return range(lower, BoundType.CLOSED, null, BoundType.OPEN); } public static <C> Range<C> atLeast(C lower, Comparator<? super C> comparator) { return range(lower, BoundType.CLOSED, null, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> greaterThan(C lower) { return range(lower, BoundType.OPEN, null, BoundType.OPEN); } public static <C> Range<C> greaterThan(C lower, Comparator<? super C> comparator) { return range(lower, BoundType.OPEN, null, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> upTo(C lower, BoundType boundType) { return range(lower, boundType, null, BoundType.OPEN); } public static <C> Range<C> upTo(C lower, BoundType boundType, Comparator<? super C> comparator) { return range(lower, boundType, null, BoundType.OPEN, comparator ); } public static <C extends Comparable<? super C>> Range<C> open(C lower, C upper) { return range(lower, BoundType.OPEN, upper, BoundType.OPEN); } public static <C> Range<C> open(C lower, C upper, Comparator<? super C> comparator) { return range(lower, BoundType.OPEN, upper, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> openClosed(C lower, C upper) { return range(lower, BoundType.OPEN, upper, BoundType.CLOSED); } public static <C> Range<C> openClosed(C lower, C upper, Comparator<? super C> comparator) { return range(lower, BoundType.OPEN, upper, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> closedOpen(C lower, C upper) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN); } public static <C> Range<C> closedOpen(C lower, C upper, Comparator<? super C> comparator) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> closed(C lower, C upper) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED); } public static <C> Range<C> closed(C lower, C upper, Comparator<? super C> comparator) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> singleton(C value) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED); } public static <C> Range<C> singleton(C value, Comparator<? super C> comparator) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> empty() { return range((C)null, BoundType.CLOSED, null, BoundType.CLOSED); } public static <C> Range<C> empty(Comparator<? super C> comparator) { return range((C)null, BoundType.CLOSED, null, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> encloseAll(Iterable<C> values) { C lower = values.iterator().next(); C upper = lower; for (C i : values) { if (lower.compareTo(i) > 0) lower = i; if (upper.compareTo(i) < 0) upper = i; } return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED); } public static <C> Range<C> encloseAll(Iterable<C> values, Comparator<? super C> comparator) { C lower = values.iterator().next(); C upper = lower; for (C i : values) { if (comparator.compare(lower, i) > 0) lower = i; if (comparator.compare(upper, i) < 0) upper = i; } return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, comparator); } protected int compareLower(C value) { return compareLower(value, BoundType.CLOSED); } protected int compareLower(C value, BoundType boundType) { return compareLower(lower, lowerType, value, boundType); } protected int compareLower(C lower, BoundType lowerType, C value) { return compareLower(lower, lowerType, value, BoundType.CLOSED); } protected int compareLower(C lower, BoundType lowerType, C value, BoundType boundType) { if (lower == null) return value == null ? 0 : -1; else if (value == null) return 1; int compare; if (comparator == null) { @SuppressWarnings("unchecked") Comparable<C> comp = (Comparable<C>)lower; compare = comp.compareTo(value); } else compare = comparator.compare(lower, value); if (compare == 0) { if (lowerType == BoundType.CLOSED) -- compare; if (boundType == BoundType.CLOSED) ++ compare; } return compare; } protected int compareUpper(C value) { return compareUpper(value, BoundType.CLOSED); } protected int compareUpper(C value, BoundType boundType) { return compareUpper(upper, upperType, value, boundType); } protected int compareUpper(C upper, BoundType upperType, C value) { return compareUpper(upper, upperType, value, BoundType.CLOSED); } protected int compareUpper(C upper, BoundType upperType, C value, BoundType boundType) { if (upper == null) return value == null ? 0 : 1; if (value == null) return -1; int compare; if (comparator == null) { @SuppressWarnings("unchecked") Comparable<C> comp = (Comparable<C>)upper; compare = comp.compareTo(value); } else compare = comparator.compare(upper, value); if (compare == 0) { if (upperType == BoundType.CLOSED) ++ compare; if (boundType == BoundType.CLOSED) -- compare; } return compare; } public boolean hasLowerBound() { return lower != null; } public C lowerEndpoint() { if (hasLowerBound()) return lower; throw new IllegalStateException(); } public BoundType lowerBoundType() { if (hasLowerBound()) return lowerType; throw new IllegalStateException(); } public boolean hasUpperBound() { return upper != null; } public C upperEndpoint() { if (hasUpperBound()) return upper; throw new IllegalStateException(); } public BoundType upperBoundType() { if (hasUpperBound()) return upperType; throw new IllegalStateException(); } /** * この区間が空集合か判定します。 * @return 空集合ならばtrue */ public boolean isEmpty() { return lower == null && upper == null && lowerType == BoundType.CLOSED; } /** * 与えられた引数が区間の左側に位置するか判定します。<br> * 接する場合は区間の左側ではないと判定します。 * @param value 調べる引数 * @return 区間の左側に位置するならtrue */ public boolean isLess(C value) { return isLess(value, BoundType.CLOSED); } protected boolean isLess(C value, BoundType boundType) { return compareLower(value, boundType) > 0; } /** * 与えられた引数が区間の右側に位置するか判定します。<br> * 接する場合は区間の右側ではないと判定します。 * @param value 調べる引数 * @return 区間の右側に位置するならtrue */ public boolean isGreater(C value) { return isGreater(value, BoundType.CLOSED); } private boolean isGreater(C value, BoundType boundType) { return compareUpper(value, boundType) < 0; } /** * 与えられた引数が区間内に位置するか判定します。<br> * 接する場合も区間内に位置すると判定します。 * @param value 調べる引数 * @return 区間内に位置するならtrue */ public boolean contains(C value) { return !isLess(value) && !isGreater(value) && !isEmpty(); } /** * 与えられた引数すべてが区間内に位置するか判定します。<br> * 接する場合も区間内に位置すると判定します。 * @param value 調べる要素 * @return 全ての要素が区間内に位置するならtrue */ public boolean containsAll(Iterable<? extends C> values) { for (C i : values) if (!contains(i)) return false; return true; } /** * 与えられた区間がこの区間に内包されるか判定します。<br> * * @param other * @return 与えられた区間がこの区間に内包されるならtrue */ public boolean encloses(Range<C> other) { return !isLess(other.lower, other.lowerType) && !isGreater(other.upper, other.upperType); } /** * 与えられた区間がこの区間と公差するか判定します。<br> * 接する場合は公差するものとします。 * @param value 調べる引数 * @return 区間が交差するならtrue */ public boolean isConnected(Range<C> other) { if (this.isEmpty() || other.isEmpty()) return false; C lower, upper; BoundType lowerType, upperType; if (isLess(other.lower, other.lowerType)) { lower = other.lower; lowerType = other.lowerType; } else { lower = this.lower; lowerType = this.lowerType; } if (isGreater(other.upper, other.upperType)) { upper = other.upper; upperType = other.upperType; } else { upper = this.upper; upperType = this.upperType; } if (lower == null || upper == null) return true; int comp = compareLower(lower, lowerType, upper, upperType); return comp <= 0; } /** * この区間との積集合を返します。 * @param connectedRange 積集合を求める区間 * @return 積集合 */ public Range<C> intersection(Range<C> connectedRange) { if (this.isEmpty() || connectedRange.isEmpty()) { if (comparator == null) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED); return empty(comparator); } C lower, upper; BoundType lowerType, upperType; if (isLess(connectedRange.lower, connectedRange.lowerType)) { lower = connectedRange.lower; lowerType = connectedRange.lowerType; } else { lower = this.lower; lowerType = this.lowerType; } if (isGreater(connectedRange.upper, connectedRange.upperType)) { upper = connectedRange.upper; upperType = connectedRange.upperType; } else { upper = this.upper; upperType = this.upperType; } if (comparator == null) { return new Range<C>(lower, lowerType, upper, upperType); } return range(lower, lowerType, upper, upperType, comparator); } /** * この区間との和集合を返します。 * @param other 和集合を求める区間 * @return 和集合 */ public Range<C> span(Range<C> other) { if (other.isEmpty()) return new Range<C>(lower, lowerType, upper, upperType); C lower, upper; BoundType lowerType, upperType; if (isLess(other.lower, other.lowerType)) { lower = this.lower; lowerType = this.lowerType; } else { lower = other.lower; lowerType = other.lowerType; } if (isGreater(other.upper, other.upperType)) { upper = this.upper; upperType = this.upperType; } else { upper = other.upper; upperType = other.upperType; } return new Range<C>(lower, lowerType, upper, upperType, comparator); } @Override public boolean equals(Object object) { if (this == object) return true; if (object instanceof Range) { @SuppressWarnings("unchecked") Range<C> comp = (Range<C>) object; return compareLower(comp.lower, comp.lowerType) == 0 && compareUpper(comp.upper, comp.upperType) == 0 && lowerType == comp.lowerType && upperType == comp.upperType; } return false; } @Override public int hashCode() { if (lower == null && upper == null) return 0; else if (lower == null) return upper.hashCode(); else if (upper == null) return lower.hashCode(); return lower.hashCode() ^ upper.hashCode(); } @Override public String toString() { if (isEmpty()) return "()"; return (lowerType == BoundType.OPEN ? "(" : "[") + (lower == null ? "" : lower.toString()) + ".." + (upper == null ? "" : upper.toString()) + (upperType == BoundType.OPEN ? ")" : "]"); } } public static class IterableRange<C> extends Range<C> implements Iterable<C>{ private static final long serialVersionUID = 9065915259748260688L; protected UnaryOperator<C> func; protected IterableRange(C lower, BoundType lowerType, C upper, BoundType upperType, UnaryOperator<C> func) { super(lower, lowerType, upper, upperType); this.func = func; } public static <C extends Comparable<? super C>> IterableRange<C> range(C lower, BoundType lowerType, C upper, BoundType upperType, UnaryOperator<C> func) { if (lower == null || upper == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); int comp = lower.compareTo(upper); if (comp > 0) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN)) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); return new IterableRange<C>(lower, lowerType, upper, upperType, func); } public static <C extends Comparable<? super C>> IterableRange<C> open(C lower, C upper, UnaryOperator<C> func) { if (lower == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); return range(func.apply(lower), BoundType.CLOSED, upper, BoundType.OPEN, func); } public static <C extends Comparable<? super C>> IterableRange<C> openClosed(C lower, C upper, UnaryOperator<C> func) { if (lower == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); return range(func.apply(lower), BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static <C extends Comparable<? super C>> IterableRange<C> closedOpen(C lower, C upper, UnaryOperator<C> func) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN, func); } public static <C extends Comparable<? super C>> IterableRange<C> closed(C lower, C upper, UnaryOperator<C> func) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static <C extends Comparable<? super C>> IterableRange<C> singleton(C value, UnaryOperator<C> func) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED, func); } protected class Iter implements Iterator<C> { C now; Iter() { now = lower; } @Override public final boolean hasNext() { return !isGreater(now); } @Override public final C next() { C ret = now; now = func.apply(now); return ret; } @Override public final void remove() { throw new UnsupportedOperationException(); } } protected class EmptyIter implements Iterator<C> { @Override public boolean hasNext() { return false; } @Override public C next() { return null; } @Override public final void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<C> iterator() { return lower == null || upper == null ? new EmptyIter() : new Iter(); } public int getDistance() { C check = upper; int ret = 0; while (lower != check) { check = func.apply(check); ++ ret; } return ret; } } public static class IntRange extends IterableRange<Integer>{ private static final long serialVersionUID = 5623995336491967216L; private final boolean useFastIter; private static class Next implements UnaryOperator<Integer> { @Override public Integer apply(Integer value) { return value + 1; } } protected IntRange() { super(null, BoundType.CLOSED, null, BoundType.CLOSED, new Next()); useFastIter = true; } protected IntRange(UnaryOperator<Integer> func) { super(null, BoundType.CLOSED, null, BoundType.CLOSED, func); useFastIter = false; } protected IntRange(int lower, BoundType lowerType, int upper, BoundType upperType) { super(lower, lowerType, upper, upperType, new Next()); useFastIter = true; } protected IntRange(int lower, BoundType lowerType, int upper, BoundType upperType, UnaryOperator<Integer> func) { super(lower, lowerType, upper, upperType, func); useFastIter = false; } public static IntRange range(int lower, BoundType lowerType, int upper, BoundType upperType) { if (lower > upper) return new IntRange(); if (lowerType == BoundType.OPEN) ++ lower; if (upperType == BoundType.OPEN) -- upper; return new IntRange(lower, BoundType.CLOSED, upper, BoundType.CLOSED); } public static IntRange range(int lower, BoundType lowerType, int upper, BoundType upperType, UnaryOperator<Integer> func) { if (lower > upper) return new IntRange(func); if (lowerType == BoundType.OPEN) ++ lower; if (upperType == BoundType.OPEN) -- upper; return new IntRange(lower, BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static IntRange open(int lower, int upper) { return range(lower, BoundType.OPEN, upper, BoundType.OPEN); } public static IntRange open(int lower, int upper, UnaryOperator<Integer> func) { return range(lower, BoundType.OPEN, upper, BoundType.OPEN, func); } public static IntRange open(int upper) { return range(0, BoundType.CLOSED, upper, BoundType.OPEN); } public static IntRange open(int upper, UnaryOperator<Integer> func) { return range(0, BoundType.CLOSED, upper, BoundType.OPEN, func); } public static IntRange openClosed(int lower, int upper) { return range(lower, BoundType.OPEN, upper, BoundType.CLOSED); } public static IntRange openClosed(int lower, int upper, UnaryOperator<Integer> func) { return range(lower, BoundType.OPEN, upper, BoundType.CLOSED, func); } public static IntRange closedOpen(int lower, int upper) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN); } public static IntRange closedOpen(int lower, int upper, UnaryOperator<Integer> func) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN, func); } public static IntRange closed(int lower, int upper) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED); } public static IntRange closed(int lower, int upper, UnaryOperator<Integer> func) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static IntRange closed(int upper) { return range(0, BoundType.CLOSED, upper, BoundType.CLOSED); } public static IntRange closed(int upper, UnaryOperator<Integer> func) { return range(0, BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static IntRange singleton(int value) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED); } public static IntRange singleton(int value, UnaryOperator<Integer> func) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED, func); } private class FastIter implements Iterator<Integer> { int now; public FastIter() { now = lower; } @Override public final boolean hasNext() { return now <= upper; } @Override public final Integer next() { return now++; } @Override public final void remove() { throw new UnsupportedOperationException(); } } private class Iter implements Iterator<Integer> { int now; public Iter() { now = lower; } @Override public final boolean hasNext() { return now <= upper; } @Override public final Integer next() { int ret = now; now = func.apply(now); return ret; } @Override public final void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<Integer> iterator() { return lower == null || upper == null ? new EmptyIter() : useFastIter ? new FastIter() : new Iter(); } @Override public int getDistance() { int ret = upper - lower; if (upperType == BoundType.CLOSED) ++ ret; return ret; } public int getClosedLower() { return lower; } public int getOpenLower() { return lower - 1; } public int getClosedUpper() { return upperType == BoundType.CLOSED ? upper : upper - 1; } public int getOpenUpper() { return upperType == BoundType.CLOSED ? upper + 1 : upper; } } /** * 演算が結合法則を満たすことを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Associative<T> extends BinaryOperator<T>{ /** * repeat個のelementを順次演算した値を返します。 * @param element 演算する値 * @param repeat 繰り返す回数、1以上であること * @return 演算を+として、element + element + ... + elementと演算をrepeat-1回行った値 */ public default T hyper(T element, int repeat) { if (repeat < 1) throw new IllegalArgumentException("undefined operation"); T ret = element; -- repeat; for (T mul = element;repeat > 0;repeat >>= 1, mul = apply(mul, mul)) if ((repeat & 1) != 0) ret = apply(ret, mul); return ret; } } /** * この演算が逆元を持つことを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Inverse<T> extends BinaryOperator<T>{ public T inverse(T element); } /** * 演算が交換法則を満たすことを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Commutative<T> extends BinaryOperator<T>{ } /** * 演算が単位元を持つことを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Identity<T> extends BinaryOperator<T>{ /** * 単位元を返します。 * @return 単位元 */ public T identity(); } /** * 演算が群であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Group<T> extends Monoid<T>, Inverse<T>{ /** * repeat個のelementを順次演算した値を返します。 * @param element 演算する値 * @param repeat 繰り返す回数 * @return 演算を+として、element + element + ... + elementと演算をrepeat-1回行った値 */ @Override public default T hyper(T element, int repeat) { T ret = identity(); if (repeat < 0) { repeat = -repeat; for (T mul = element;repeat > 0;repeat >>= 1, mul = apply(mul, mul)) if ((repeat & 1) != 0) ret = apply(ret, mul); return inverse(ret); } for (T mul = element;repeat > 0;repeat >>= 1, mul = apply(mul, mul)) if ((repeat & 1) != 0) ret = apply(ret, mul); return ret; } } /** * 演算がモノイドであることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Monoid<T> extends Associative<T>, Identity<T> { /** * repeat個のelementを順次演算した値を返します。 * @param element 演算する値 * @param repeat 繰り返す回数、0以上であること * @return 演算を+として、element + element + ... + elementと演算をrepeat-1回行った値 */ @Override public default T hyper(T element, int repeat) { if (repeat < 0) throw new IllegalArgumentException("undefined operation"); T ret = identity(); for (T mul = element;repeat > 0;repeat >>= 1, mul = apply(mul, mul)) if ((repeat & 1) != 0) ret = apply(ret, mul); return ret; } } /** * 演算が可換モノイドであることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface CommutativeMonoid<T> extends Monoid<T>, Commutative<T> { } /** * 演算がアーベル群(可換群)であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Abelian<T> extends Group<T>, CommutativeMonoid<T> { } /** * 演算が半環であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface Semiring<T, A extends CommutativeMonoid<T>, M extends Monoid<T>> { public A getAddition(); public M getMultiplication(); public default T add(T left, T right) { return getAddition().apply(left, right); } public default T multiply(T left, T right) { return getMultiplication().apply(left, right); } public default T additiveIdentity() { return getAddition().identity(); } public default T multipleIdentity() { return getMultiplication().identity(); } public default int characteristic() { return 0; } } /** * 演算が環であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface Ring<T, A extends Abelian<T>, M extends Monoid<T>> extends Semiring<T, A, M>{ } /** * 演算が可換環に属することを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface CommutativeRing<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends Ring<T, A, M>{ } /** * 演算が整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface IntegralDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends CommutativeRing<T, A, M>{ public boolean isDivisible(T left, T right); public T divide(T left, T right); } /** * 演算が整閉整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface IntegrallyClosedDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends IntegralDomain<T, A, M>{ } /** * 演算がGCD整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface GCDDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends IntegrallyClosedDomain<T, A, M>{ public T gcd(T left, T right); public T lcm(T left, T right); } /** * 素元を提供します。 * @author 31536000 * * @param <T> 演算の型 */ public static class PrimeElement<T> { public final T element; public PrimeElement(T element) { this.element = element; } } public interface MultiSet<E> extends Collection<E>{ public int add(E element, int occurrences); public int count(Object element); public Set<E> elementSet(); public boolean remove(Object element, int occurrences); public int setCount(E element, int count); public boolean setCount(E element, int oldCount, int newCount); } /** * 演算が一意分解整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface UniqueFactorizationDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends GCDDomain<T, A, M>{ public MultiSet<PrimeElement<T>> PrimeFactorization(T x); } /** * 演算が主イデアル整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface PrincipalIdealDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends UniqueFactorizationDomain<T, A, M> { } /** * 演算がユークリッド整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface EuclideanDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends PrincipalIdealDomain<T, A, M>{ public T reminder(T left, T right); } /** * 演算が体であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface Field<T, A extends Abelian<T>, M extends Abelian<T>> extends EuclideanDomain<T, A, M>{ @Override public default boolean isDivisible(T left, T right) { return !right.equals(additiveIdentity()); } @Override public default T divide(T left, T right) { if (isDivisible(left, right)) throw new ArithmeticException("divide by Additive Identify"); return multiply(left, getMultiplication().inverse(right)); } @Override public default T reminder(T left, T right) { if (isDivisible(left, right)) throw new ArithmeticException("divide by Additive Identify"); return additiveIdentity(); } @Override public default T gcd(T left, T right) { return multipleIdentity(); } @Override public default T lcm(T left, T right) { return multipleIdentity(); } @Override public default MultiSet<PrimeElement<T>> PrimeFactorization(T x) { HashMultiSet<PrimeElement<T>> ret = HashMultiSet.create(1); ret.add(new PrimeElement<T>(x)); return ret; } } public static class HashMultiSet<E> implements MultiSet<E>, Serializable{ private static final long serialVersionUID = -8378919645386251159L; private final transient HashMap<E, Integer> map; private transient int size; private HashMultiSet() { map = new HashMap<>(); size = 0; } private HashMultiSet(int distinctElements) { map = new HashMap<>(distinctElements); size = 0; } public static <E> HashMultiSet<E> create() { return new HashMultiSet<>(); } public static <E> HashMultiSet<E> create(int distinctElements) { return new HashMultiSet<>(distinctElements); } public static <E> HashMultiSet<E> create(Iterable<? extends E> elements) { HashMultiSet<E> ret = new HashMultiSet<>(); for (E i : elements) ret.map.compute(i, (v, e) -> e == null ? 1 : ++e); return ret; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public boolean contains(Object o) { return map.containsKey(o); } private class Iter implements Iterator<E> { private final Iterator<Entry<E, Integer>> iter = map.entrySet().iterator(); private E value; private int count = 0; @Override public boolean hasNext() { if (count > 0) return true; if (iter.hasNext()) { Entry<E, Integer> entry = iter.next(); value = entry.getKey(); count = entry.getValue(); return true; } return false; } @Override public E next() { -- count; return value; } } @Override public Iterator<E> iterator() { return new Iter(); } @Override public Object[] toArray() { Object[] ret = new Object[size]; int read = 0; for (Entry<E, Integer> i : map.entrySet()) Arrays.fill(ret, read, read += i.getValue(), i.getKey()); return ret; } @Override public <T> T[] toArray(T[] a) { Object[] src = toArray(); if (a.length < src.length) { @SuppressWarnings("unchecked") T[] ret = (T[])Arrays.copyOfRange(src, 0, src.length, a.getClass()); return ret; } System.arraycopy(src, 0, a, 0, src.length); return a; } @Override public boolean add(E e) { add(e, 1); return true; } @Override public boolean remove(Object o) { return remove(o, 1); } @Override public boolean containsAll(Collection<?> c) { boolean ret = true; for (Object i : c) ret |= contains(i); return ret; } @Override public boolean addAll(Collection<? extends E> c) { boolean ret = false; for (E i : c) ret |= add(i); return ret; } @Override public boolean removeAll(Collection<?> c) { boolean ret = false; for (Object i : c) ret |= remove(i); return ret; } @Override public boolean retainAll(Collection<?> c) { return removeAll(c); } @Override public void clear() { map.clear(); size = 0; } @Override public int add(E element, int occurrences) { size += occurrences; return map.compute(element, (k, v) -> v == null ? occurrences : v + occurrences) - occurrences; } @Override public int count(Object element) { return map.getOrDefault(element, 0); } @Override public Set<E> elementSet() { return map.keySet(); } public Set<Entry<E, Integer>> entrySet() { return map.entrySet(); } @Override public boolean remove(Object element, int occurrences) { try { @SuppressWarnings("unchecked") E put = (E) element; return map.compute(put, (k, v) -> { if (v == null) return null; if (v < occurrences) { size -= v; return null; } size -= occurrences; return v - occurrences; }) != null; } catch (ClassCastException E) { return false; } } @Override public int setCount(E element, int count) { Integer ret = map.put(element, count); int ret2 = ret == null ? 0 : ret; size += count - ret2; return ret2; } @Override public boolean setCount(E element, int oldCount, int newCount) { boolean ret = map.replace(element, oldCount, newCount); if (ret) size += newCount - oldCount; return ret; } } public static class ModInteger extends Number implements Field<ModInteger, Abelian<ModInteger>, Abelian<ModInteger>>{ private static final long serialVersionUID = -8595710127161317579L; private final int mod; private int num; private final Addition add; private final Multiplication mul; private class Addition implements Abelian<ModInteger> { @Override public ModInteger identity() { return new ModInteger(mod, 0); } @Override public ModInteger inverse(ModInteger element) { return new ModInteger(element, element.mod - element.num); } @Override public ModInteger apply(ModInteger left, ModInteger right) { return new ModInteger(left).addEqual(right); } } private class Multiplication implements Abelian<ModInteger> { @Override public ModInteger identity() { return new ModInteger(mod, 1); } @Override public ModInteger apply(ModInteger left, ModInteger right) { return new ModInteger(left).multiplyEqual(right); } @Override public ModInteger inverse(ModInteger element) { return new ModInteger(element, element.inverse(element.num)); } } @Override public int characteristic() { return mod; } public ModInteger(int mod) { this.mod = mod; num = 0; add = new Addition(); mul = new Multiplication(); } public ModInteger(int mod, int num) { this.mod = mod; this.num = validNum(num); add = new Addition(); mul = new Multiplication(); } public ModInteger(ModInteger n) { mod = n.mod; num = n.num; add = n.add; mul = n.mul; } private ModInteger(ModInteger n, int num) { mod = n.mod; this.num = num; add = n.add; mul = n.mul; } private int validNum(int n) { n %= mod; if (n < 0) n += mod; return n; } private int validNum(long n) { n %= mod; if (n < 0) n += mod; return (int)n; } protected int inverse(int n) { int m = mod, u = 0, v = 1, t; while(n != 0) { t = m / n; m -= t * n; u -= t * v; if (m != 0) { t = n / m; n -= t * m; v -= t * u; } else { v %= mod; if (v < 0) v += mod; return v; } } u %= mod; if (u < 0) u += mod; return u; } public boolean isPrime(int n) { if ((n & 1) == 0) return false; // 偶数 for (int i = 3, j = 8, k = 9;k <= n;i += 2, k += j += 8) if (n % i == 0) return false; return true; } @Override public int intValue() { return num; } @Override public long longValue() { return num; } @Override public float floatValue() { return num; } @Override public double doubleValue() { return num; } protected ModInteger getNewInstance(ModInteger mod) { return new ModInteger(mod); } public ModInteger add(int n) { return getNewInstance(this).addEqual(n); } public ModInteger add(long n) { return getNewInstance(this).addEqual(n); } public ModInteger add(ModInteger n) { return getNewInstance(this).addEqual(n); } public ModInteger addEqual(int n) { num = validNum(num + n); return this; } public ModInteger addEqual(long n) { num = validNum(num + n); return this; } public ModInteger addEqual(ModInteger n) { if ((num += n.num) >= mod) num -= mod; return this; } public ModInteger subtract(int n) { return getNewInstance(this).subtractEqual(n); } public ModInteger subtract(long n) { return getNewInstance(this).subtractEqual(n); } public ModInteger subtract(ModInteger n) { return getNewInstance(this).subtractEqual(n); } public ModInteger subtractEqual(int n) { num = validNum(num - n); return this; } public ModInteger subtractEqual(long n) { num = validNum(num - n); return this; } public ModInteger subtractEqual(ModInteger n) { if ((num -= n.num) < 0) num += mod; return this; } public ModInteger multiply(int n) { return getNewInstance(this).multiplyEqual(n); } public ModInteger multiply(long n) { return getNewInstance(this).multiplyEqual(n); } public ModInteger multiply(ModInteger n) { return getNewInstance(this).multiplyEqual(n); } public ModInteger multiplyEqual(int n) { num = (int)((long)num * n % mod); if (num < 0) num += mod; return this; } public ModInteger multiplyEqual(long n) { return multiplyEqual((int) (n % mod)); } public ModInteger multiplyEqual(ModInteger n) { num = (int)((long)num * n.num % mod); return this; } public ModInteger divide(int n) { return getNewInstance(this).divideEqual(n); } public ModInteger divide(long n) { return getNewInstance(this).divideEqual(n); } public ModInteger divide(ModInteger n) { return getNewInstance(this).divideEqual(n); } public ModInteger divideEqual(int n) { num = (int)((long)num * inverse(validNum(n)) % mod); return this; } public ModInteger divideEqual(long n) { return divideEqual((int)(n % mod)); } public ModInteger divideEqual(ModInteger n) { num = (int)((long)num * n.inverse(n.num) % mod); return this; } public ModInteger pow(int n) { return getNewInstance(this).powEqual(n); } public ModInteger pow(long n) { return getNewInstance(this).powEqual(n); } public ModInteger pow(ModInteger n) { return getNewInstance(this).powEqual(n); } public ModInteger powEqual(int n) { long ans = 1, num = this.num; if (n < 0) { n = -n; while (n != 0) { if ((n & 1) != 0) ans = ans * num % mod; n >>>= 1; num = num * num % mod; } this.num = inverse((int)ans); return this; } while (n != 0) { if ((n & 1) != 0) ans = ans * num % mod; n >>>= 1; num = num * num % mod; } this.num = (int)ans; return this; } public ModInteger powEqual(long n) { return powEqual((int)(n % (mod - 1))); } public ModInteger powEqual(ModInteger n) { long num = this.num; this.num = 1; int mul = n.num; while (mul != 0) { if ((mul & 1) != 0) this.num *= num; mul >>>= 1; num *= num; num %= mod; } return this; } public ModInteger equal(int n) { num = validNum(n); return this; } public ModInteger equal(long n) { num = validNum(n); return this; } public ModInteger equal(ModInteger n) { num = n.num; return this; } public int toInt() { return num; } public int getMod() { return mod; } @Override public boolean equals(Object x) { if (x instanceof ModInteger) return ((ModInteger)x).num == num && ((ModInteger)x).mod == mod; return false; } @Override public int hashCode() { return num ^ mod; } @Override public String toString() { return String.valueOf(num); } @Deprecated public String debug() { int min = num, ans = 1; for (int i = 2;i < min;++ i) { int tmp = multiply(i).num; if (min > tmp) { min = tmp; ans = i; } } return min + "/" + ans; } @Override public Addition getAddition() { return add; } @Override public Multiplication getMultiplication() { return mul; } } /** * 素数を法とする演算上で、組み合わせの計算を高速に行います。 * @author 31536000 * */ public static class ModUtility { private final int mod; private int[] fact, inv, invfact; /** * modを法として、演算を行います。 * @param mod 法とする素数 */ public ModUtility(Prime mod) { this(mod, 2); } /** * modを法として、演算を行います。 * @param mod 法とする素数 * @param calc 予め前計算しておく大きさ */ public ModUtility(Prime mod, int calc) { this.mod = mod.prime; precalc(calc); } /** * calcの大きさだけ、前計算を行います。 * @param calc 前計算をする大きさ */ public void precalc(int calc) { ++ calc; if (calc < 2) calc = 2; fact = new int[calc]; inv = new int[calc]; invfact = new int[calc]; fact[0] = invfact[0] = fact[1] = invfact[1] = inv[1] = 1; for (int i = 2;i < calc;++ i) { fact[i] = (int)((long)fact[i - 1] * i % mod); inv[i] = (int)(mod - (long)inv[mod % i] * (mod / i) % mod); invfact[i] = (int)((long)invfact[i - 1] * inv[i] % mod); } } /** * modを法とする剰余環上で振舞う整数を返します。 * @return modを法とする整数、初期値は0 */ public ModInteger create() { return new ModInt(); } /** * modを法とする剰余環上で振舞う整数を返します。 * @param n 初期値 * @return modを法とする整数 */ public ModInteger create(int n) { return new ModInt(n); } private class ModInt extends ModInteger { private static final long serialVersionUID = -2435281861935422575L; public ModInt() { super(mod); } public ModInt(int n) { super(mod, n); } public ModInt(ModInteger mod) { super(mod); } @Override protected ModInteger getNewInstance(ModInteger mod) { return new ModInt(mod); } @Override protected int inverse(int n) { return ModUtility.this.inverse(n); } } /** * modを法として、nの逆元を返します。<br> * 計算量はO(log n)です。 * @param n 逆元を求めたい値 * @return 逆元 */ public int inverse(int n) { try { if (inv.length > n) return inv[n]; int m = mod, u = 0, v = 1, t; while(n != 0) { t = m / n; m -= t * n; u -= t * v; if (m != 0) { t = n / m; n -= t * m; v -= t * u; } else { v %= mod; if (v < 0) v += mod; return v; } } u %= mod; if (u < 0) u += mod; return u; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } } /** * n!を、modを法として求めた値を返します。<br> * 計算量はO(n)です。 * @param n 階乗を求めたい値 * @return nの階乗をmodで割った余り */ public int factorial(int n) { try { if (fact.length > n) return fact[n]; long ret = fact[fact.length - 1]; for (int i = fact.length;i <= n;++ i) ret = ret * i % mod; return (int)ret; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } } /** * nPkをmodで割った余りを求めます。<br> * 計算量はO(n-k)です。 * @param n 左辺 * @param k 右辺 * @return nPkをmodで割った余り */ public int permutation(int n, int k) { if (k < 0) throw new IllegalArgumentException(); if (n < k) return 0; if (fact.length > n) return (int)((long)fact[n] * invfact[n - k] % mod); long ret = 1; for (int i = n - k + 1;i <= n;++ i) ret = ret * i % mod; return (int)ret; } /** * nCkをmodで割った余りを求めます。<br> * 計算量はO(n-k)です。 * @param n 左辺 * @param k 右辺 * @return nCkをmodで割った余り */ public int combination(int n, int k) { if (k < 0) throw new IllegalArgumentException(); if (n < k) return 0; if (fact.length > n) return (int)((long)fact[n] * invfact[k] % mod * invfact[n - k] % mod); long ret = 1; if (n < 2 * k) k = n - k; if (invfact.length > k) ret = invfact[k]; else ret = inverse(factorial(k)); for (int i = n - k + 1;i <= n;++ i) ret = ret * i % mod; return (int)ret; } /** * 他項係数をmodで割った余りを求めます。<br>] * 計算量はO(n)です。 * @param n 左辺 * @param k 右辺、合計がn以下である必要がある * @return 他項係数 */ public int multinomial(int n, int... k) { int sum = 0; for (int i : k) sum += i; long ret = factorial(n); if (fact.length > n) { for (int i : k) { if (i < 0) throw new IllegalArgumentException(); ret = ret * invfact[i] % mod; sum += i; } if (sum > n) return 0; ret = ret * invfact[n - sum] % mod; } else { for (int i : k) { if (i < 0) throw new IllegalArgumentException(); if (invfact.length > i) ret = ret * invfact[i] % mod; else ret = ret * inverse(factorial(i)) % mod; sum += i; } if (sum > n) return 0; if (invfact.length > n - sum) ret = ret * invfact[n - sum] % mod; else ret = ret * inverse(factorial(n - sum)) % mod; } return (int)ret; } /** * n個からk個を選ぶ重複組み合わせnHkをmodで割った余りを求めます。<br> * 計算量はO(min(n, k))です。 * @param n 左辺 * @param k 右辺 * @return nHkをmodで割った余り */ public int multichoose(int n, int k) { return combination(mod(n + k - 1), k); } /** * カタラン数C(n)をmodで割った余りを求めます。<br> * 計算量はO(n)です。 * @param n 求めたいカタラン数の番号 * @return カタラン数 */ public int catalan(int n) { return divide(combination(mod(2 * n), n), mod(n + 1)); } /** * nのm乗をmodで割った余りを求めます。<br> * 計算量はO(log m)です。 * @param n 床 * @param m 冪指数 * @return n^mをmodで割った余り */ public int pow(int n, int m) { long ans = 1, num = n; if (m < 0) { m = -m; while (m != 0) { if ((m & 1) != 0) ans = ans * num % mod; m >>>= 1; num = num * num % mod; } return inverse((int)ans); } while (m != 0) { if ((m & 1) != 0) ans = ans * num % mod; m >>>= 1; num = num * num % mod; } return (int)ans; } /** * nのm乗をmodで割った余りを求めます。<br> * 計算量はO(log m)です。 * @param n 床 * @param m 冪指数 * @return n^mをmodで割った余り */ public int pow(long n, long m) { return pow((int)(n % mod), (int)(n % (mod - 1))); } /** * 現在のmod値のトーシェント数を返します。<br> * なお、これはmod-1に等しいです。 * @return トーシェント数 */ public int totient() { return mod - 1; } /** * nのトーシェント数を返します。<br> * 計算量はO(sqrt n)です。 * @param n トーシェント数を求めたい値 * @return nのトーシェント数 */ public static int totient(int n) { int totient = n; for (int i = 2;i * i <= n;++ i) { if (n % i == 0) { totient = totient / i * (i - 1); while ((n %= i) % i == 0); } } if (n != 1) totient = totient / n * (n - 1); return totient; } /** * nをmodで割った余りを返します。 * @param n 演算する値 * @return nをmodで割った余り */ public int mod(int n) { return (n %= mod) < 0 ? n + mod : n; } /** * nをmodで割った余りを返します。 * @param n 演算する値 * @return nをmodで割った余り */ public int mod(long n) { return (int)((n %= mod) < 0 ? n + mod : n); } /** * n+mをmodで割った余りを返します。 * @param n 足される値 * @param m 足す値 * @return n+mをmodで割った余り */ public int add(int n, int m) { return mod(n + m); } /** * n-mをmodで割った余りを返します。 * @param n 引かれる値 * @param m 引く値 * @return n-mをmodで割った余り */ public int subtract(int n, int m) { return mod(n - m); } /** * n*mをmodで割った余りを返します。 * @param n 掛けられる値 * @param m 掛ける値 * @return n*mをmodで割った余り */ public int multiply(int n, int m) { int ans = (int)((long)n * m % mod); return ans < 0 ? ans + mod : ans; } /** * n/mをmodで割った余りを返します。 * @param n 割られる値 * @param m 割る値 * @return n/mをmodで割った余り */ public int divide(int n, int m) { return multiply(n, inverse(m)); } /** * fを通ることが分かっているfの要素数-1次の関数について、xの位置における値をmodで割った余りを返します。<br> * 計算量はO(f)です。 * @param f 関数の形 * @param x 求める位置 * @return 求めたい値をmodで割った余り */ public ModInteger lagrangePolynomial(ModInteger[] f, int x) { if (f.length > x) return f[x]; if (x > fact.length) precalc(x); ModInteger ret = create(0); ModInteger[] dp = new ModInteger[f.length], dp2 = new ModInteger[f.length]; dp[0] = create(1); dp2[f.length - 1] = create(1); for (int i = 1;i < f.length;++ i) { dp[i] = dp[i - 1].multiply(x - i - 1); dp2[f.length - i - 1] = dp2[f.length - i].multiply(x - f.length + i); } for (int i = 0;i < f.length;++ i) { ModInteger tmp = f[i].multiply(dp[i]).multiplyEqual(dp2[i]).multiplyEqual(inv[i]).multiplyEqual(inv[f.length - 1 - i]); if ((f.length - i & 1) == 0) ret.addEqual(tmp); else ret.subtractEqual(tmp); } return ret; } } /** * 素数を渡すためのクラスです。<br> * 中身が確実に素数であることを保証するときに使ってください。 * * @author 31536000 * */ public static class Prime extends Number{ private static final long serialVersionUID = 8216169308184181643L; public final int prime; /** * 素数を設定します。 * * @param prime 素数 * @throws IllegalArgumentException 素数以外を渡した時 */ public Prime(int prime) { if (!isPrime(prime)) throw new IllegalArgumentException(prime + " is not prime"); this.prime = prime; } private static final int bases[] = {15591, 2018, 166, 7429, 8064, 16045, 10503, 4399, 1949, 1295, 2776, 3620, 560, 3128, 5212, 2657, 2300, 2021, 4652, 1471, 9336, 4018, 2398, 20462, 10277, 8028, 2213, 6219, 620, 3763, 4852, 5012, 3185, 1333, 6227, 5298, 1074, 2391, 5113, 7061, 803, 1269, 3875, 422, 751, 580, 4729, 10239, 746, 2951, 556, 2206, 3778, 481, 1522, 3476, 481, 2487, 3266, 5633, 488, 3373, 6441, 3344, 17, 15105, 1490, 4154, 2036, 1882, 1813, 467, 3307, 14042, 6371, 658, 1005, 903, 737, 1887, 7447, 1888, 2848, 1784, 7559, 3400, 951, 13969, 4304, 177, 41, 19875, 3110, 13221, 8726, 571, 7043, 6943, 1199, 352, 6435, 165, 1169, 3315, 978, 233, 3003, 2562, 2994, 10587, 10030, 2377, 1902, 5354, 4447, 1555, 263, 27027, 2283, 305, 669, 1912, 601, 6186, 429, 1930, 14873, 1784, 1661, 524, 3577, 236, 2360, 6146, 2850, 55637, 1753, 4178, 8466, 222, 2579, 2743, 2031, 2226, 2276, 374, 2132, 813, 23788, 1610, 4422, 5159, 1725, 3597, 3366, 14336, 579, 165, 1375, 10018, 12616, 9816, 1371, 536, 1867, 10864, 857, 2206, 5788, 434, 8085, 17618, 727, 3639, 1595, 4944, 2129, 2029, 8195, 8344, 6232, 9183, 8126, 1870, 3296, 7455, 8947, 25017, 541, 19115, 368, 566, 5674, 411, 522, 1027, 8215, 2050, 6544, 10049, 614, 774, 2333, 3007, 35201, 4706, 1152, 1785, 1028, 1540, 3743, 493, 4474, 2521, 26845, 8354, 864, 18915, 5465, 2447, 42, 4511, 1660, 166, 1249, 6259, 2553, 304, 272, 7286, 73, 6554, 899, 2816, 5197, 13330, 7054, 2818, 3199, 811, 922, 350, 7514, 4452, 3449, 2663, 4708, 418, 1621, 1171, 3471, 88, 11345, 412, 1559, 194}; private static boolean isSPRP(int n, int a) { int d = n - 1, s = 0; while ((d & 1) == 0) { ++s; d >>= 1; } long cur = 1, pw = d; while (pw != 0) { if ((pw & 1) != 0) cur = (cur * a) % n; a = (int)(((long)a * a) % n); pw >>= 1; } if (cur == 1) return true; for (int r = 0; r < s; r++ ) { if (cur == n - 1) return true; cur = (cur * cur) % n; } return false; } /** * 与えられた値が素数か否かを判定します。<br> * この実装はhttp://ceur-ws.org/Vol-1326/020-Forisek.pdfに基づきます。 * @param x 判定したい値 * @return xが素数ならtrue */ public static boolean isPrime(int x) { if (x == 2 || x == 3 || x == 5 || x == 7) return true; if ((x & 1) == 0 || x % 3 == 0 || x % 5 == 0 || x % 7 == 0) return false; if (x < 121) return x > 1; long h = x; h = ((h >> 16) ^ h) * 0x45d9f3b; h = ((h >> 16) ^ h) * 0x45d9f3b; h = ((h >> 16) ^ h) & 0xFF; return isSPRP(x, bases[(int)h]); } @Override public int intValue() { return prime; } @Override public long longValue() { return prime; } @Override public float floatValue() { return prime; } @Override public double doubleValue() { return prime; } @Override public String toString() { return String.valueOf(prime); } } public static class AbstractArray<T> extends AbstractList<T> implements RandomAccess{ private final Object[] array; public AbstractArray(int size) { array = new Object[size]; } public AbstractArray(T[] array) { this(array.length); System.arraycopy(array, 0, this.array, 0, array.length); } @Override public T set(int index, T element) { T ret = get(index); array[index] = element; return ret; } @Override public T get(int index) { @SuppressWarnings("unchecked") T ret = (T)array[index]; return ret; } public Object[] get() { return array; } public T[] get(T[] array) { if (array.length < this.array.length) { @SuppressWarnings("unchecked") T[] ret = (T[])Arrays.copyOfRange(this.array, 0, this.array.length, array.getClass()); return ret; } System.arraycopy(this.array, 0, array, 0, this.array.length); return array; } @Override public int size() { return array.length; } public int length() { return size(); } @Override public int hashCode() { return Arrays.hashCode(array); } private class Iter implements Iterator<T> { private int index; private Iter() { index = 0; } @Override public boolean hasNext() { return index < array.length; } @Override public T next() { return get(index++); } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<T> iterator() { return new Iter(); } } public static class Array<T> extends AbstractArray<T> implements Serializable{ private static final long serialVersionUID = 2749604433067098063L; public Array(int size) { super(size); } public Array(T[] array) { super(array); } public T front() { return get(0); } public T back() { return get(size() - 1); } } }
Yes
Do these codes solve the same problem? Code 1: N, K = map(int, input().split()) R, S, P = map(int, input().split()) T = input() flag = [0]*N ans = 0 for i in range(N): if i-K>=0 and T[i-K] == T[i] and flag[i-K]: continue if T[i] == 'r': ans+=P elif T[i] == 's': ans+=R else: ans+=S flag[i] = True print(ans) Code 2: import java.awt.Point; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.Set; import java.util.function.BinaryOperator; import java.util.function.UnaryOperator; public class Main implements Runnable{ private void solve(FastIO io, String[] args) { /* * author: 31536000 * ABC149 D問題 * 考察メモ * 基本的には貪欲に勝つ * ただし、K回前と今が同じ手なら、今を負けたことにする * それだけ * */ int N = io.nextInt(), K = io.nextInt(), R = io.nextInt(), S = io.nextInt(), P = io.nextInt(); char[] T = io.next().toCharArray(); long score = 0; for (int i = 0;i < K;++ i) { for (int j = i;j < N;j += K) { if (j + K < N && T[j + K] == T[j]) T[j + K] = 'o'; switch(T[j]) { case 'r': score += P; break; case 's': score += R; break; case 'p': score += S; break; } } } io.println(score); } /** デバッグ用コードのお供に */ private static boolean DEBUG = false; /** 確保するメモリの大きさ(単位: MB)*/ private static final long MEMORY = 64; private final FastIO io; private final String[] args; public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler((t, e) -> e.printStackTrace()); new Thread(null, new Main(args), "", MEMORY * 1048576).start(); } public Main(String[] args) { this(new FastIO(), args); } public Main(FastIO io, String... args) { this.io = io; this.args = args; if (DEBUG) io.setAutoFlush(true); } @Override public void run() { solve(io, args); io.flush(); } // 以下、ライブラリ /** * 高速な入出力を提供します。 * @author 31536000 * */ public static class FastIO { private InputStream in; private final byte[] buffer = new byte[1024]; private int read = 0; private int length = 0; private PrintWriter out; private PrintWriter err; private boolean autoFlush = false; public FastIO() { this(System.in, System.out, System.err); } public FastIO(InputStream in, PrintStream out, PrintStream err) { this.in = in; this.out = new PrintWriter(out, false); this.err = new PrintWriter(err, false); } public final void setInputStream(InputStream in) { this.in = in; } public final void setInputStream(File in) { try { this.in = new FileInputStream(in); } catch (FileNotFoundException e) { e.printStackTrace(); } } public final void setOutputStream(PrintStream out) { this.out = new PrintWriter(out, false); } public final void setOutputStream(File out) { try { this.out = new PrintWriter(new FileOutputStream(out), false); } catch (FileNotFoundException e) { e.printStackTrace(); } } public final void setErrorStream(PrintStream err) { this.err = new PrintWriter(err, false); } public final void setErrorStream(File err) { try { this.err = new PrintWriter(new FileOutputStream(err), false); } catch (FileNotFoundException e) { e.printStackTrace(); } } public final void setAutoFlush(boolean flush) { autoFlush = flush; } private boolean hasNextByte() { if (read < length) return true; read = 0; try { length = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } return length > 0; } private int readByte() { return hasNextByte() ? buffer[read++] : -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private static boolean isNumber(int c) { return '0' <= c && c <= '9'; } public final boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[read])) read++; return hasNextByte(); } public final char nextChar() { if (!hasNextByte()) throw new NoSuchElementException(); return (char)readByte(); } public final char[][] nextChar(int height) { char[][] ret = new char[height][]; for (int i = 0;i < ret.length;++ i) ret[i] = next().toCharArray(); return ret; } public final String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b; while (isPrintableChar(b = readByte())) sb.appendCodePoint(b); return sb.toString(); } public final String nextLine() { StringBuilder sb = new StringBuilder(); int b; while(!isPrintableChar(b = readByte())); do sb.appendCodePoint(b); while(isPrintableChar(b = readByte()) || b == ' '); return sb.toString(); } public final long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (!isNumber(b)) throw new NumberFormatException(); while (true) { if (isNumber(b)) { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) return minus ? -n : n; else throw new NumberFormatException(); b = readByte(); } } public final int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public final double nextDouble() { return Double.parseDouble(next()); } public final int[] nextInt(int width) { int[] ret = new int[width]; for (int i = 0;i < width;++ i) ret[i] = nextInt(); return ret; } public final int[] nextInts() { return nextInts(" "); } public final int[] nextInts(String parse) { String[] get = nextLine().split(parse); int[] ret = new int[get.length]; for (int i = 0;i < ret.length;++ i) ret[i] = Integer.valueOf(get[i]); return ret; } public final long[] nextLong(int width) { long[] ret = new long[width]; for (int i = 0;i < width;++ i) ret[i] = nextLong(); return ret; } public final long[] nextLongs() { return nextLongs(" "); } public final long[] nextLongs(String parse) { String[] get = nextLine().split(parse); long[] ret = new long[get.length]; for (int i = 0;i < ret.length;++ i) ret[i] = Long.valueOf(get[i]); return ret; } public final int[][] nextInt(int width, int height) { int[][] ret = new int[height][width]; for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[i][j] = nextInt(); return ret; } public final long[][] nextLong(int width, int height) { long[][] ret = new long[height][width]; for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[j][i] = nextLong(); return ret; } public final boolean[] nextBoolean(char T) { char[] s = next().toCharArray(); boolean[] ret = new boolean[s.length]; for (int i = 0;i < ret.length;++ i) ret[i] = s[i] == T; return ret; } public final boolean[][] nextBoolean(char T, int height) { boolean[][] ret = new boolean[height][]; for (int i = 0;i < ret.length;++ i) { char[] s = next().toCharArray(); ret[i] = new boolean[s.length]; for (int j = 0;j < ret[i].length;++ j) ret[i][j] = s[j] == T; } return ret; } public final Point nextPoint() { return new Point(nextInt(), nextInt()); } public final Point[] nextPoint(int width) { Point[] ret = new Point[width]; for (int i = 0;i < width;++ i) ret[i] = nextPoint(); return ret; } @Override protected void finalize() throws Throwable { try { super.finalize(); } finally { in.close(); out.close(); err.close(); } } public final boolean print(boolean b) { out.print(b); if (autoFlush) flush(); return b; } public final Object print(boolean b, Object t, Object f) { return b ? print(t) : print(f); } public final char print(char c) { out.print(c); if (autoFlush) flush(); return c; } public final char[] print(char[] s) { out.print(s); return s; } public final double print(double d) { out.print(d); if (autoFlush) flush(); return d; } public final double print(double d, int length) { if (d < 0) { out.print('-'); d = -d; } d += Math.pow(10, -length) / 2; out.print((long)d); out.print('.'); d -= (long)d; for (int i = 0;i < length;++ i) { d *= 10; out.print((int)d); d -= (int)d; } if (autoFlush) flush(); return d; } public final float print(float f) { out.print(f); if (autoFlush) flush(); return f; } public final int print(int i) { out.print(i); if (autoFlush) flush(); return i; } public final long print(long l) { out.print(l); if (autoFlush) flush(); return l; } public final Object print(Object obj) { if (obj.getClass().isArray()) { if (obj instanceof boolean[][]) print(obj, "\n", " "); else if (obj instanceof byte[][]) print(obj, "\n", " "); else if (obj instanceof short[][]) print(obj, "\n", " "); else if (obj instanceof int[][]) print(obj, "\n", " "); else if (obj instanceof long[][]) print(obj, "\n", " "); else if (obj instanceof float[][]) print(obj, "\n", " "); else if (obj instanceof double[][]) print(obj, "\n", " "); else if (obj instanceof char[][]) print(obj, "\n", " "); else if (obj instanceof Object[][]) print(obj, "\n", " "); else print(obj, " "); } else { out.print(obj); if (autoFlush) flush(); } return obj; } public final String print(String s) { out.print(s); if (autoFlush) flush(); return s; } public final Object print(Object array, String... parse) { print(array, 0, parse); if (autoFlush) flush(); return array; } private final Object print(Object array, int check, String... parse) { if (check >= parse.length) { if (array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension"); print(array); return array; } String str = parse[check]; if (array instanceof Object[]) { Object[] obj = (Object[]) array; if (obj.length == 0) return array; print(obj[0], check + 1, parse); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i], check + 1, parse); } return array; } if (array instanceof Collection) { Iterator<?> iter = ((Collection<?>)array).iterator(); if (!iter.hasNext()) return array; print(iter.next(), check + 1, parse); while(iter.hasNext()) { print(str); print(iter.next(), check + 1, parse); } return array; } if (!array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension"); if (check != parse.length - 1) throw new IllegalArgumentException("not equal dimension"); if (array instanceof boolean[]) { boolean[] obj = (boolean[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof byte[]) { byte[] obj = (byte[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } return array; } else if (array instanceof short[]) { short[] obj = (short[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof int[]) { int[] obj = (int[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof long[]) { long[] obj = (long[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof float[]) { float[] obj = (float[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof double[]) { double[] obj = (double[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else if (array instanceof char[]) { char[] obj = (char[]) array; if (obj.length == 0) return array; print(obj[0]); for (int i = 1;i < obj.length;++ i) { print(str); print(obj[i]); } } else throw new AssertionError(); return array; } public final Object[] print(String parse, Object... args) { print(args[0]); for (int i = 1;i < args.length;++ i) { print(parse); print(args[i]); } return args; } public final Object[] printf(String format, Object... args) { out.printf(format, args); if (autoFlush) flush(); return args; } public final Object printf(Locale l, String format, Object... args) { out.printf(l, format, args); if (autoFlush) flush(); return args; } public final void println() { out.println(); if (autoFlush) flush(); } public final boolean println(boolean b) { out.println(b); if (autoFlush) flush(); return b; } public final Object println(boolean b, Object t, Object f) { return b ? println(t) : println(f); } public final char println(char c) { out.println(c); if (autoFlush) flush(); return c; } public final char[] println(char[] s) { out.println(s); if (autoFlush) flush(); return s; } public final double println(double d) { out.println(d); if (autoFlush) flush(); return d; } public final double println(double d, int length) { print(d, length); println(); return d; } public final float println(float f) { out.println(f); if (autoFlush) flush(); return f; } public final int println(int i) { out.println(i); if (autoFlush) flush(); return i; } public final long println(long l) { out.println(l); if (autoFlush) flush(); return l; } public final Object println(Object obj) { print(obj); println(); return obj; } public final String println(String s) { out.println(s); if (autoFlush) flush(); return s; } public final Object println(Object array, String... parse) { print(array, parse); println(); return array; } public final boolean debug(boolean b) { err.print(b); if (autoFlush) flush(); return b; } public final Object debug(boolean b, Object t, Object f) { return b ? debug(t) : debug(f); } public final char debug(char c) { err.print(c); if (autoFlush) flush(); return c; } public final char[] debug(char[] s) { err.print(s); return s; } public final double debug(double d) { err.print(d); if (autoFlush) flush(); return d; } public final double debug(double d, int length) { if (d < 0) { err.print('-'); d = -d; } d += Math.pow(10, -length) / 2; err.print((long)d); err.print('.'); d -= (long)d; for (int i = 0;i < length;++ i) { d *= 10; err.print((int)d); d -= (int)d; } if (autoFlush) flush(); return d; } public final float debug(float f) { err.print(f); if (autoFlush) flush(); return f; } public final int debug(int i) { err.print(i); if (autoFlush) flush(); return i; } public final long debug(long l) { err.print(l); if (autoFlush) flush(); return l; } public final Object debug(Object obj) { if (obj.getClass().isArray()) { if (obj instanceof boolean[][]) debug(obj, "\n", " "); else if (obj instanceof byte[][]) debug(obj, "\n", " "); else if (obj instanceof short[][]) debug(obj, "\n", " "); else if (obj instanceof int[][]) debug(obj, "\n", " "); else if (obj instanceof long[][]) debug(obj, "\n", " "); else if (obj instanceof float[][]) debug(obj, "\n", " "); else if (obj instanceof double[][]) debug(obj, "\n", " "); else if (obj instanceof char[][]) debug(obj, "\n", " "); else if (obj instanceof Object[][]) debug(obj, "\n", " "); else debug(obj, " "); } else { err.print(obj); if (autoFlush) flush(); } return obj; } public final String debug(String s) { err.print(s); if (autoFlush) flush(); return s; } public final Object debug(Object array, String... parse) { debug(array, 0, parse); if (autoFlush) flush(); return array; } private final Object debug(Object array, int check, String... parse) { if (check >= parse.length) { if (array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension"); debug(array); return array; } String str = parse[check]; if (array instanceof Object[]) { Object[] obj = (Object[]) array; if (obj.length == 0) return array; debug(obj[0], check + 1, parse); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i], check + 1, parse); } return array; } if (array instanceof Collection) { Iterator<?> iter = ((Collection<?>)array).iterator(); if (!iter.hasNext()) return array; debug(iter.next(), check + 1, parse); while(iter.hasNext()) { debug(str); debug(iter.next(), check + 1, parse); } return array; } if (!array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension"); if (check != parse.length - 1) throw new IllegalArgumentException("not equal dimension"); if (array instanceof boolean[]) { boolean[] obj = (boolean[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof byte[]) { byte[] obj = (byte[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } return array; } else if (array instanceof short[]) { short[] obj = (short[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof int[]) { int[] obj = (int[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof long[]) { long[] obj = (long[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof float[]) { float[] obj = (float[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof double[]) { double[] obj = (double[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else if (array instanceof char[]) { char[] obj = (char[]) array; if (obj.length == 0) return array; debug(obj[0]); for (int i = 1;i < obj.length;++ i) { debug(str); debug(obj[i]); } } else throw new AssertionError(); return array; } public final Object[] debug(String parse, Object... args) { debug(args[0]); for (int i = 1;i < args.length;++ i) { debug(parse); debug(args[i]); } return args; } public final Object[] debugf(String format, Object... args) { err.printf(format, args); if (autoFlush) flush(); return args; } public final Object debugf(Locale l, String format, Object... args) { err.printf(l, format, args); if (autoFlush) flush(); return args; } public final void debugln() { err.println(); if (autoFlush) flush(); } public final boolean debugln(boolean b) { err.println(b); if (autoFlush) flush(); return b; } public final Object debugln(boolean b, Object t, Object f) { return b ? debugln(t) : debugln(f); } public final char debugln(char c) { err.println(c); if (autoFlush) flush(); return c; } public final char[] debugln(char[] s) { err.println(s); if (autoFlush) flush(); return s; } public final double debugln(double d) { err.println(d); if (autoFlush) flush(); return d; } public final double debugln(double d, int length) { debug(d, length); debugln(); return d; } public final float debugln(float f) { err.println(f); if (autoFlush) flush(); return f; } public final int debugln(int i) { err.println(i); if (autoFlush) flush(); return i; } public final long debugln(long l) { err.println(l); if (autoFlush) flush(); return l; } public final Object debugln(Object obj) { debug(obj); debugln(); return obj; } public final String debugln(String s) { err.println(s); if (autoFlush) flush(); return s; } public final Object debugln(Object array, String... parse) { debug(array, parse); debugln(); return array; } public final void flush() { out.flush(); err.flush(); } } public enum BoundType { CLOSED, OPEN; } public static class Range<C> implements Serializable{ private static final long serialVersionUID = -4702828934863023392L; protected C lower; protected C upper; protected BoundType lowerType; protected BoundType upperType; private Comparator<? super C> comparator; protected Range(C lower, BoundType lowerType, C upper, BoundType upperType) { this(lower, lowerType, upper, upperType, null); } protected Range(C lower, BoundType lowerType, C upper, BoundType upperType, Comparator<? super C> comparator) { this.lower = lower; this.upper = upper; this.lowerType = lowerType; this.upperType = upperType; this.comparator = comparator; } public static <C extends Comparable<? super C>> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType) { if (lower != null && upper != null) { int comp = lower.compareTo(upper); if (comp > 0) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED); else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN))return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED); } return new Range<C>(lower, lowerType, upper, upperType); } public static <C> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType, Comparator<? super C> comparator) { if (lower != null && upper != null) { int comp = comparator.compare(lower, upper); if (comp > 0) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, comparator); else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN)) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, comparator); } return new Range<C>(lower, lowerType, upper, upperType, comparator); } public static <C extends Comparable<? super C>> Range<C> all() { return range((C)null, BoundType.OPEN, null, BoundType.OPEN); } public static <C> Range<C> all(Comparator<? super C> comparator) { return range((C)null, BoundType.OPEN, null, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> atMost(C upper) { return range(null, BoundType.OPEN, upper, BoundType.CLOSED); } public static <C> Range<C> atMost(C upper, Comparator<? super C> comparator) { return range(null, BoundType.OPEN, upper, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> lessThan(C upper) { return range(null, BoundType.OPEN, upper, BoundType.OPEN); } public static <C> Range<C> lessThan(C upper, Comparator<? super C> comparator) { return range(null, BoundType.OPEN, upper, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> downTo(C upper, BoundType boundType) { return range(null, BoundType.OPEN, upper, boundType); } public static <C> Range<C> downTo(C upper, BoundType boundType, Comparator<? super C> comparator) { return range(null, BoundType.OPEN, upper, boundType, comparator); } public static <C extends Comparable<? super C>> Range<C> atLeast(C lower) { return range(lower, BoundType.CLOSED, null, BoundType.OPEN); } public static <C> Range<C> atLeast(C lower, Comparator<? super C> comparator) { return range(lower, BoundType.CLOSED, null, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> greaterThan(C lower) { return range(lower, BoundType.OPEN, null, BoundType.OPEN); } public static <C> Range<C> greaterThan(C lower, Comparator<? super C> comparator) { return range(lower, BoundType.OPEN, null, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> upTo(C lower, BoundType boundType) { return range(lower, boundType, null, BoundType.OPEN); } public static <C> Range<C> upTo(C lower, BoundType boundType, Comparator<? super C> comparator) { return range(lower, boundType, null, BoundType.OPEN, comparator ); } public static <C extends Comparable<? super C>> Range<C> open(C lower, C upper) { return range(lower, BoundType.OPEN, upper, BoundType.OPEN); } public static <C> Range<C> open(C lower, C upper, Comparator<? super C> comparator) { return range(lower, BoundType.OPEN, upper, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> openClosed(C lower, C upper) { return range(lower, BoundType.OPEN, upper, BoundType.CLOSED); } public static <C> Range<C> openClosed(C lower, C upper, Comparator<? super C> comparator) { return range(lower, BoundType.OPEN, upper, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> closedOpen(C lower, C upper) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN); } public static <C> Range<C> closedOpen(C lower, C upper, Comparator<? super C> comparator) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN, comparator); } public static <C extends Comparable<? super C>> Range<C> closed(C lower, C upper) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED); } public static <C> Range<C> closed(C lower, C upper, Comparator<? super C> comparator) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> singleton(C value) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED); } public static <C> Range<C> singleton(C value, Comparator<? super C> comparator) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> empty() { return range((C)null, BoundType.CLOSED, null, BoundType.CLOSED); } public static <C> Range<C> empty(Comparator<? super C> comparator) { return range((C)null, BoundType.CLOSED, null, BoundType.CLOSED, comparator); } public static <C extends Comparable<? super C>> Range<C> encloseAll(Iterable<C> values) { C lower = values.iterator().next(); C upper = lower; for (C i : values) { if (lower.compareTo(i) > 0) lower = i; if (upper.compareTo(i) < 0) upper = i; } return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED); } public static <C> Range<C> encloseAll(Iterable<C> values, Comparator<? super C> comparator) { C lower = values.iterator().next(); C upper = lower; for (C i : values) { if (comparator.compare(lower, i) > 0) lower = i; if (comparator.compare(upper, i) < 0) upper = i; } return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, comparator); } protected int compareLower(C value) { return compareLower(value, BoundType.CLOSED); } protected int compareLower(C value, BoundType boundType) { return compareLower(lower, lowerType, value, boundType); } protected int compareLower(C lower, BoundType lowerType, C value) { return compareLower(lower, lowerType, value, BoundType.CLOSED); } protected int compareLower(C lower, BoundType lowerType, C value, BoundType boundType) { if (lower == null) return value == null ? 0 : -1; else if (value == null) return 1; int compare; if (comparator == null) { @SuppressWarnings("unchecked") Comparable<C> comp = (Comparable<C>)lower; compare = comp.compareTo(value); } else compare = comparator.compare(lower, value); if (compare == 0) { if (lowerType == BoundType.CLOSED) -- compare; if (boundType == BoundType.CLOSED) ++ compare; } return compare; } protected int compareUpper(C value) { return compareUpper(value, BoundType.CLOSED); } protected int compareUpper(C value, BoundType boundType) { return compareUpper(upper, upperType, value, boundType); } protected int compareUpper(C upper, BoundType upperType, C value) { return compareUpper(upper, upperType, value, BoundType.CLOSED); } protected int compareUpper(C upper, BoundType upperType, C value, BoundType boundType) { if (upper == null) return value == null ? 0 : 1; if (value == null) return -1; int compare; if (comparator == null) { @SuppressWarnings("unchecked") Comparable<C> comp = (Comparable<C>)upper; compare = comp.compareTo(value); } else compare = comparator.compare(upper, value); if (compare == 0) { if (upperType == BoundType.CLOSED) ++ compare; if (boundType == BoundType.CLOSED) -- compare; } return compare; } public boolean hasLowerBound() { return lower != null; } public C lowerEndpoint() { if (hasLowerBound()) return lower; throw new IllegalStateException(); } public BoundType lowerBoundType() { if (hasLowerBound()) return lowerType; throw new IllegalStateException(); } public boolean hasUpperBound() { return upper != null; } public C upperEndpoint() { if (hasUpperBound()) return upper; throw new IllegalStateException(); } public BoundType upperBoundType() { if (hasUpperBound()) return upperType; throw new IllegalStateException(); } /** * この区間が空集合か判定します。 * @return 空集合ならばtrue */ public boolean isEmpty() { return lower == null && upper == null && lowerType == BoundType.CLOSED; } /** * 与えられた引数が区間の左側に位置するか判定します。<br> * 接する場合は区間の左側ではないと判定します。 * @param value 調べる引数 * @return 区間の左側に位置するならtrue */ public boolean isLess(C value) { return isLess(value, BoundType.CLOSED); } protected boolean isLess(C value, BoundType boundType) { return compareLower(value, boundType) > 0; } /** * 与えられた引数が区間の右側に位置するか判定します。<br> * 接する場合は区間の右側ではないと判定します。 * @param value 調べる引数 * @return 区間の右側に位置するならtrue */ public boolean isGreater(C value) { return isGreater(value, BoundType.CLOSED); } private boolean isGreater(C value, BoundType boundType) { return compareUpper(value, boundType) < 0; } /** * 与えられた引数が区間内に位置するか判定します。<br> * 接する場合も区間内に位置すると判定します。 * @param value 調べる引数 * @return 区間内に位置するならtrue */ public boolean contains(C value) { return !isLess(value) && !isGreater(value) && !isEmpty(); } /** * 与えられた引数すべてが区間内に位置するか判定します。<br> * 接する場合も区間内に位置すると判定します。 * @param value 調べる要素 * @return 全ての要素が区間内に位置するならtrue */ public boolean containsAll(Iterable<? extends C> values) { for (C i : values) if (!contains(i)) return false; return true; } /** * 与えられた区間がこの区間に内包されるか判定します。<br> * * @param other * @return 与えられた区間がこの区間に内包されるならtrue */ public boolean encloses(Range<C> other) { return !isLess(other.lower, other.lowerType) && !isGreater(other.upper, other.upperType); } /** * 与えられた区間がこの区間と公差するか判定します。<br> * 接する場合は公差するものとします。 * @param value 調べる引数 * @return 区間が交差するならtrue */ public boolean isConnected(Range<C> other) { if (this.isEmpty() || other.isEmpty()) return false; C lower, upper; BoundType lowerType, upperType; if (isLess(other.lower, other.lowerType)) { lower = other.lower; lowerType = other.lowerType; } else { lower = this.lower; lowerType = this.lowerType; } if (isGreater(other.upper, other.upperType)) { upper = other.upper; upperType = other.upperType; } else { upper = this.upper; upperType = this.upperType; } if (lower == null || upper == null) return true; int comp = compareLower(lower, lowerType, upper, upperType); return comp <= 0; } /** * この区間との積集合を返します。 * @param connectedRange 積集合を求める区間 * @return 積集合 */ public Range<C> intersection(Range<C> connectedRange) { if (this.isEmpty() || connectedRange.isEmpty()) { if (comparator == null) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED); return empty(comparator); } C lower, upper; BoundType lowerType, upperType; if (isLess(connectedRange.lower, connectedRange.lowerType)) { lower = connectedRange.lower; lowerType = connectedRange.lowerType; } else { lower = this.lower; lowerType = this.lowerType; } if (isGreater(connectedRange.upper, connectedRange.upperType)) { upper = connectedRange.upper; upperType = connectedRange.upperType; } else { upper = this.upper; upperType = this.upperType; } if (comparator == null) { return new Range<C>(lower, lowerType, upper, upperType); } return range(lower, lowerType, upper, upperType, comparator); } /** * この区間との和集合を返します。 * @param other 和集合を求める区間 * @return 和集合 */ public Range<C> span(Range<C> other) { if (other.isEmpty()) return new Range<C>(lower, lowerType, upper, upperType); C lower, upper; BoundType lowerType, upperType; if (isLess(other.lower, other.lowerType)) { lower = this.lower; lowerType = this.lowerType; } else { lower = other.lower; lowerType = other.lowerType; } if (isGreater(other.upper, other.upperType)) { upper = this.upper; upperType = this.upperType; } else { upper = other.upper; upperType = other.upperType; } return new Range<C>(lower, lowerType, upper, upperType, comparator); } @Override public boolean equals(Object object) { if (this == object) return true; if (object instanceof Range) { @SuppressWarnings("unchecked") Range<C> comp = (Range<C>) object; return compareLower(comp.lower, comp.lowerType) == 0 && compareUpper(comp.upper, comp.upperType) == 0 && lowerType == comp.lowerType && upperType == comp.upperType; } return false; } @Override public int hashCode() { if (lower == null && upper == null) return 0; else if (lower == null) return upper.hashCode(); else if (upper == null) return lower.hashCode(); return lower.hashCode() ^ upper.hashCode(); } @Override public String toString() { if (isEmpty()) return "()"; return (lowerType == BoundType.OPEN ? "(" : "[") + (lower == null ? "" : lower.toString()) + ".." + (upper == null ? "" : upper.toString()) + (upperType == BoundType.OPEN ? ")" : "]"); } } public static class IterableRange<C> extends Range<C> implements Iterable<C>{ private static final long serialVersionUID = 9065915259748260688L; protected UnaryOperator<C> func; protected IterableRange(C lower, BoundType lowerType, C upper, BoundType upperType, UnaryOperator<C> func) { super(lower, lowerType, upper, upperType); this.func = func; } public static <C extends Comparable<? super C>> IterableRange<C> range(C lower, BoundType lowerType, C upper, BoundType upperType, UnaryOperator<C> func) { if (lower == null || upper == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); int comp = lower.compareTo(upper); if (comp > 0) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN)) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); return new IterableRange<C>(lower, lowerType, upper, upperType, func); } public static <C extends Comparable<? super C>> IterableRange<C> open(C lower, C upper, UnaryOperator<C> func) { if (lower == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); return range(func.apply(lower), BoundType.CLOSED, upper, BoundType.OPEN, func); } public static <C extends Comparable<? super C>> IterableRange<C> openClosed(C lower, C upper, UnaryOperator<C> func) { if (lower == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func); return range(func.apply(lower), BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static <C extends Comparable<? super C>> IterableRange<C> closedOpen(C lower, C upper, UnaryOperator<C> func) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN, func); } public static <C extends Comparable<? super C>> IterableRange<C> closed(C lower, C upper, UnaryOperator<C> func) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static <C extends Comparable<? super C>> IterableRange<C> singleton(C value, UnaryOperator<C> func) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED, func); } protected class Iter implements Iterator<C> { C now; Iter() { now = lower; } @Override public final boolean hasNext() { return !isGreater(now); } @Override public final C next() { C ret = now; now = func.apply(now); return ret; } @Override public final void remove() { throw new UnsupportedOperationException(); } } protected class EmptyIter implements Iterator<C> { @Override public boolean hasNext() { return false; } @Override public C next() { return null; } @Override public final void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<C> iterator() { return lower == null || upper == null ? new EmptyIter() : new Iter(); } public int getDistance() { C check = upper; int ret = 0; while (lower != check) { check = func.apply(check); ++ ret; } return ret; } } public static class IntRange extends IterableRange<Integer>{ private static final long serialVersionUID = 5623995336491967216L; private final boolean useFastIter; private static class Next implements UnaryOperator<Integer> { @Override public Integer apply(Integer value) { return value + 1; } } protected IntRange() { super(null, BoundType.CLOSED, null, BoundType.CLOSED, new Next()); useFastIter = true; } protected IntRange(UnaryOperator<Integer> func) { super(null, BoundType.CLOSED, null, BoundType.CLOSED, func); useFastIter = false; } protected IntRange(int lower, BoundType lowerType, int upper, BoundType upperType) { super(lower, lowerType, upper, upperType, new Next()); useFastIter = true; } protected IntRange(int lower, BoundType lowerType, int upper, BoundType upperType, UnaryOperator<Integer> func) { super(lower, lowerType, upper, upperType, func); useFastIter = false; } public static IntRange range(int lower, BoundType lowerType, int upper, BoundType upperType) { if (lower > upper) return new IntRange(); if (lowerType == BoundType.OPEN) ++ lower; if (upperType == BoundType.OPEN) -- upper; return new IntRange(lower, BoundType.CLOSED, upper, BoundType.CLOSED); } public static IntRange range(int lower, BoundType lowerType, int upper, BoundType upperType, UnaryOperator<Integer> func) { if (lower > upper) return new IntRange(func); if (lowerType == BoundType.OPEN) ++ lower; if (upperType == BoundType.OPEN) -- upper; return new IntRange(lower, BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static IntRange open(int lower, int upper) { return range(lower, BoundType.OPEN, upper, BoundType.OPEN); } public static IntRange open(int lower, int upper, UnaryOperator<Integer> func) { return range(lower, BoundType.OPEN, upper, BoundType.OPEN, func); } public static IntRange open(int upper) { return range(0, BoundType.CLOSED, upper, BoundType.OPEN); } public static IntRange open(int upper, UnaryOperator<Integer> func) { return range(0, BoundType.CLOSED, upper, BoundType.OPEN, func); } public static IntRange openClosed(int lower, int upper) { return range(lower, BoundType.OPEN, upper, BoundType.CLOSED); } public static IntRange openClosed(int lower, int upper, UnaryOperator<Integer> func) { return range(lower, BoundType.OPEN, upper, BoundType.CLOSED, func); } public static IntRange closedOpen(int lower, int upper) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN); } public static IntRange closedOpen(int lower, int upper, UnaryOperator<Integer> func) { return range(lower, BoundType.CLOSED, upper, BoundType.OPEN, func); } public static IntRange closed(int lower, int upper) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED); } public static IntRange closed(int lower, int upper, UnaryOperator<Integer> func) { return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static IntRange closed(int upper) { return range(0, BoundType.CLOSED, upper, BoundType.CLOSED); } public static IntRange closed(int upper, UnaryOperator<Integer> func) { return range(0, BoundType.CLOSED, upper, BoundType.CLOSED, func); } public static IntRange singleton(int value) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED); } public static IntRange singleton(int value, UnaryOperator<Integer> func) { return range(value, BoundType.CLOSED, value, BoundType.CLOSED, func); } private class FastIter implements Iterator<Integer> { int now; public FastIter() { now = lower; } @Override public final boolean hasNext() { return now <= upper; } @Override public final Integer next() { return now++; } @Override public final void remove() { throw new UnsupportedOperationException(); } } private class Iter implements Iterator<Integer> { int now; public Iter() { now = lower; } @Override public final boolean hasNext() { return now <= upper; } @Override public final Integer next() { int ret = now; now = func.apply(now); return ret; } @Override public final void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<Integer> iterator() { return lower == null || upper == null ? new EmptyIter() : useFastIter ? new FastIter() : new Iter(); } @Override public int getDistance() { int ret = upper - lower; if (upperType == BoundType.CLOSED) ++ ret; return ret; } public int getClosedLower() { return lower; } public int getOpenLower() { return lower - 1; } public int getClosedUpper() { return upperType == BoundType.CLOSED ? upper : upper - 1; } public int getOpenUpper() { return upperType == BoundType.CLOSED ? upper + 1 : upper; } } /** * 演算が結合法則を満たすことを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Associative<T> extends BinaryOperator<T>{ /** * repeat個のelementを順次演算した値を返します。 * @param element 演算する値 * @param repeat 繰り返す回数、1以上であること * @return 演算を+として、element + element + ... + elementと演算をrepeat-1回行った値 */ public default T hyper(T element, int repeat) { if (repeat < 1) throw new IllegalArgumentException("undefined operation"); T ret = element; -- repeat; for (T mul = element;repeat > 0;repeat >>= 1, mul = apply(mul, mul)) if ((repeat & 1) != 0) ret = apply(ret, mul); return ret; } } /** * この演算が逆元を持つことを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Inverse<T> extends BinaryOperator<T>{ public T inverse(T element); } /** * 演算が交換法則を満たすことを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Commutative<T> extends BinaryOperator<T>{ } /** * 演算が単位元を持つことを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Identity<T> extends BinaryOperator<T>{ /** * 単位元を返します。 * @return 単位元 */ public T identity(); } /** * 演算が群であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Group<T> extends Monoid<T>, Inverse<T>{ /** * repeat個のelementを順次演算した値を返します。 * @param element 演算する値 * @param repeat 繰り返す回数 * @return 演算を+として、element + element + ... + elementと演算をrepeat-1回行った値 */ @Override public default T hyper(T element, int repeat) { T ret = identity(); if (repeat < 0) { repeat = -repeat; for (T mul = element;repeat > 0;repeat >>= 1, mul = apply(mul, mul)) if ((repeat & 1) != 0) ret = apply(ret, mul); return inverse(ret); } for (T mul = element;repeat > 0;repeat >>= 1, mul = apply(mul, mul)) if ((repeat & 1) != 0) ret = apply(ret, mul); return ret; } } /** * 演算がモノイドであることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Monoid<T> extends Associative<T>, Identity<T> { /** * repeat個のelementを順次演算した値を返します。 * @param element 演算する値 * @param repeat 繰り返す回数、0以上であること * @return 演算を+として、element + element + ... + elementと演算をrepeat-1回行った値 */ @Override public default T hyper(T element, int repeat) { if (repeat < 0) throw new IllegalArgumentException("undefined operation"); T ret = identity(); for (T mul = element;repeat > 0;repeat >>= 1, mul = apply(mul, mul)) if ((repeat & 1) != 0) ret = apply(ret, mul); return ret; } } /** * 演算が可換モノイドであることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface CommutativeMonoid<T> extends Monoid<T>, Commutative<T> { } /** * 演算がアーベル群(可換群)であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 */ public interface Abelian<T> extends Group<T>, CommutativeMonoid<T> { } /** * 演算が半環であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface Semiring<T, A extends CommutativeMonoid<T>, M extends Monoid<T>> { public A getAddition(); public M getMultiplication(); public default T add(T left, T right) { return getAddition().apply(left, right); } public default T multiply(T left, T right) { return getMultiplication().apply(left, right); } public default T additiveIdentity() { return getAddition().identity(); } public default T multipleIdentity() { return getMultiplication().identity(); } public default int characteristic() { return 0; } } /** * 演算が環であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface Ring<T, A extends Abelian<T>, M extends Monoid<T>> extends Semiring<T, A, M>{ } /** * 演算が可換環に属することを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface CommutativeRing<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends Ring<T, A, M>{ } /** * 演算が整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface IntegralDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends CommutativeRing<T, A, M>{ public boolean isDivisible(T left, T right); public T divide(T left, T right); } /** * 演算が整閉整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface IntegrallyClosedDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends IntegralDomain<T, A, M>{ } /** * 演算がGCD整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface GCDDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends IntegrallyClosedDomain<T, A, M>{ public T gcd(T left, T right); public T lcm(T left, T right); } /** * 素元を提供します。 * @author 31536000 * * @param <T> 演算の型 */ public static class PrimeElement<T> { public final T element; public PrimeElement(T element) { this.element = element; } } public interface MultiSet<E> extends Collection<E>{ public int add(E element, int occurrences); public int count(Object element); public Set<E> elementSet(); public boolean remove(Object element, int occurrences); public int setCount(E element, int count); public boolean setCount(E element, int oldCount, int newCount); } /** * 演算が一意分解整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface UniqueFactorizationDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends GCDDomain<T, A, M>{ public MultiSet<PrimeElement<T>> PrimeFactorization(T x); } /** * 演算が主イデアル整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface PrincipalIdealDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends UniqueFactorizationDomain<T, A, M> { } /** * 演算がユークリッド整域であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface EuclideanDomain<T, A extends Abelian<T>, M extends CommutativeMonoid<T>> extends PrincipalIdealDomain<T, A, M>{ public T reminder(T left, T right); } /** * 演算が体であることを示すために使用するマーカー・インターフェースです。 * @author 31536000 * * @param <T> 二項演算の型 * @param <A> 和に関する演算 * @param <M> 積に関する演算 */ public interface Field<T, A extends Abelian<T>, M extends Abelian<T>> extends EuclideanDomain<T, A, M>{ @Override public default boolean isDivisible(T left, T right) { return !right.equals(additiveIdentity()); } @Override public default T divide(T left, T right) { if (isDivisible(left, right)) throw new ArithmeticException("divide by Additive Identify"); return multiply(left, getMultiplication().inverse(right)); } @Override public default T reminder(T left, T right) { if (isDivisible(left, right)) throw new ArithmeticException("divide by Additive Identify"); return additiveIdentity(); } @Override public default T gcd(T left, T right) { return multipleIdentity(); } @Override public default T lcm(T left, T right) { return multipleIdentity(); } @Override public default MultiSet<PrimeElement<T>> PrimeFactorization(T x) { HashMultiSet<PrimeElement<T>> ret = HashMultiSet.create(1); ret.add(new PrimeElement<T>(x)); return ret; } } public static class HashMultiSet<E> implements MultiSet<E>, Serializable{ private static final long serialVersionUID = -8378919645386251159L; private final transient HashMap<E, Integer> map; private transient int size; private HashMultiSet() { map = new HashMap<>(); size = 0; } private HashMultiSet(int distinctElements) { map = new HashMap<>(distinctElements); size = 0; } public static <E> HashMultiSet<E> create() { return new HashMultiSet<>(); } public static <E> HashMultiSet<E> create(int distinctElements) { return new HashMultiSet<>(distinctElements); } public static <E> HashMultiSet<E> create(Iterable<? extends E> elements) { HashMultiSet<E> ret = new HashMultiSet<>(); for (E i : elements) ret.map.compute(i, (v, e) -> e == null ? 1 : ++e); return ret; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public boolean contains(Object o) { return map.containsKey(o); } private class Iter implements Iterator<E> { private final Iterator<Entry<E, Integer>> iter = map.entrySet().iterator(); private E value; private int count = 0; @Override public boolean hasNext() { if (count > 0) return true; if (iter.hasNext()) { Entry<E, Integer> entry = iter.next(); value = entry.getKey(); count = entry.getValue(); return true; } return false; } @Override public E next() { -- count; return value; } } @Override public Iterator<E> iterator() { return new Iter(); } @Override public Object[] toArray() { Object[] ret = new Object[size]; int read = 0; for (Entry<E, Integer> i : map.entrySet()) Arrays.fill(ret, read, read += i.getValue(), i.getKey()); return ret; } @Override public <T> T[] toArray(T[] a) { Object[] src = toArray(); if (a.length < src.length) { @SuppressWarnings("unchecked") T[] ret = (T[])Arrays.copyOfRange(src, 0, src.length, a.getClass()); return ret; } System.arraycopy(src, 0, a, 0, src.length); return a; } @Override public boolean add(E e) { add(e, 1); return true; } @Override public boolean remove(Object o) { return remove(o, 1); } @Override public boolean containsAll(Collection<?> c) { boolean ret = true; for (Object i : c) ret |= contains(i); return ret; } @Override public boolean addAll(Collection<? extends E> c) { boolean ret = false; for (E i : c) ret |= add(i); return ret; } @Override public boolean removeAll(Collection<?> c) { boolean ret = false; for (Object i : c) ret |= remove(i); return ret; } @Override public boolean retainAll(Collection<?> c) { return removeAll(c); } @Override public void clear() { map.clear(); size = 0; } @Override public int add(E element, int occurrences) { size += occurrences; return map.compute(element, (k, v) -> v == null ? occurrences : v + occurrences) - occurrences; } @Override public int count(Object element) { return map.getOrDefault(element, 0); } @Override public Set<E> elementSet() { return map.keySet(); } public Set<Entry<E, Integer>> entrySet() { return map.entrySet(); } @Override public boolean remove(Object element, int occurrences) { try { @SuppressWarnings("unchecked") E put = (E) element; return map.compute(put, (k, v) -> { if (v == null) return null; if (v < occurrences) { size -= v; return null; } size -= occurrences; return v - occurrences; }) != null; } catch (ClassCastException E) { return false; } } @Override public int setCount(E element, int count) { Integer ret = map.put(element, count); int ret2 = ret == null ? 0 : ret; size += count - ret2; return ret2; } @Override public boolean setCount(E element, int oldCount, int newCount) { boolean ret = map.replace(element, oldCount, newCount); if (ret) size += newCount - oldCount; return ret; } } public static class ModInteger extends Number implements Field<ModInteger, Abelian<ModInteger>, Abelian<ModInteger>>{ private static final long serialVersionUID = -8595710127161317579L; private final int mod; private int num; private final Addition add; private final Multiplication mul; private class Addition implements Abelian<ModInteger> { @Override public ModInteger identity() { return new ModInteger(mod, 0); } @Override public ModInteger inverse(ModInteger element) { return new ModInteger(element, element.mod - element.num); } @Override public ModInteger apply(ModInteger left, ModInteger right) { return new ModInteger(left).addEqual(right); } } private class Multiplication implements Abelian<ModInteger> { @Override public ModInteger identity() { return new ModInteger(mod, 1); } @Override public ModInteger apply(ModInteger left, ModInteger right) { return new ModInteger(left).multiplyEqual(right); } @Override public ModInteger inverse(ModInteger element) { return new ModInteger(element, element.inverse(element.num)); } } @Override public int characteristic() { return mod; } public ModInteger(int mod) { this.mod = mod; num = 0; add = new Addition(); mul = new Multiplication(); } public ModInteger(int mod, int num) { this.mod = mod; this.num = validNum(num); add = new Addition(); mul = new Multiplication(); } public ModInteger(ModInteger n) { mod = n.mod; num = n.num; add = n.add; mul = n.mul; } private ModInteger(ModInteger n, int num) { mod = n.mod; this.num = num; add = n.add; mul = n.mul; } private int validNum(int n) { n %= mod; if (n < 0) n += mod; return n; } private int validNum(long n) { n %= mod; if (n < 0) n += mod; return (int)n; } protected int inverse(int n) { int m = mod, u = 0, v = 1, t; while(n != 0) { t = m / n; m -= t * n; u -= t * v; if (m != 0) { t = n / m; n -= t * m; v -= t * u; } else { v %= mod; if (v < 0) v += mod; return v; } } u %= mod; if (u < 0) u += mod; return u; } public boolean isPrime(int n) { if ((n & 1) == 0) return false; // 偶数 for (int i = 3, j = 8, k = 9;k <= n;i += 2, k += j += 8) if (n % i == 0) return false; return true; } @Override public int intValue() { return num; } @Override public long longValue() { return num; } @Override public float floatValue() { return num; } @Override public double doubleValue() { return num; } protected ModInteger getNewInstance(ModInteger mod) { return new ModInteger(mod); } public ModInteger add(int n) { return getNewInstance(this).addEqual(n); } public ModInteger add(long n) { return getNewInstance(this).addEqual(n); } public ModInteger add(ModInteger n) { return getNewInstance(this).addEqual(n); } public ModInteger addEqual(int n) { num = validNum(num + n); return this; } public ModInteger addEqual(long n) { num = validNum(num + n); return this; } public ModInteger addEqual(ModInteger n) { if ((num += n.num) >= mod) num -= mod; return this; } public ModInteger subtract(int n) { return getNewInstance(this).subtractEqual(n); } public ModInteger subtract(long n) { return getNewInstance(this).subtractEqual(n); } public ModInteger subtract(ModInteger n) { return getNewInstance(this).subtractEqual(n); } public ModInteger subtractEqual(int n) { num = validNum(num - n); return this; } public ModInteger subtractEqual(long n) { num = validNum(num - n); return this; } public ModInteger subtractEqual(ModInteger n) { if ((num -= n.num) < 0) num += mod; return this; } public ModInteger multiply(int n) { return getNewInstance(this).multiplyEqual(n); } public ModInteger multiply(long n) { return getNewInstance(this).multiplyEqual(n); } public ModInteger multiply(ModInteger n) { return getNewInstance(this).multiplyEqual(n); } public ModInteger multiplyEqual(int n) { num = (int)((long)num * n % mod); if (num < 0) num += mod; return this; } public ModInteger multiplyEqual(long n) { return multiplyEqual((int) (n % mod)); } public ModInteger multiplyEqual(ModInteger n) { num = (int)((long)num * n.num % mod); return this; } public ModInteger divide(int n) { return getNewInstance(this).divideEqual(n); } public ModInteger divide(long n) { return getNewInstance(this).divideEqual(n); } public ModInteger divide(ModInteger n) { return getNewInstance(this).divideEqual(n); } public ModInteger divideEqual(int n) { num = (int)((long)num * inverse(validNum(n)) % mod); return this; } public ModInteger divideEqual(long n) { return divideEqual((int)(n % mod)); } public ModInteger divideEqual(ModInteger n) { num = (int)((long)num * n.inverse(n.num) % mod); return this; } public ModInteger pow(int n) { return getNewInstance(this).powEqual(n); } public ModInteger pow(long n) { return getNewInstance(this).powEqual(n); } public ModInteger pow(ModInteger n) { return getNewInstance(this).powEqual(n); } public ModInteger powEqual(int n) { long ans = 1, num = this.num; if (n < 0) { n = -n; while (n != 0) { if ((n & 1) != 0) ans = ans * num % mod; n >>>= 1; num = num * num % mod; } this.num = inverse((int)ans); return this; } while (n != 0) { if ((n & 1) != 0) ans = ans * num % mod; n >>>= 1; num = num * num % mod; } this.num = (int)ans; return this; } public ModInteger powEqual(long n) { return powEqual((int)(n % (mod - 1))); } public ModInteger powEqual(ModInteger n) { long num = this.num; this.num = 1; int mul = n.num; while (mul != 0) { if ((mul & 1) != 0) this.num *= num; mul >>>= 1; num *= num; num %= mod; } return this; } public ModInteger equal(int n) { num = validNum(n); return this; } public ModInteger equal(long n) { num = validNum(n); return this; } public ModInteger equal(ModInteger n) { num = n.num; return this; } public int toInt() { return num; } public int getMod() { return mod; } @Override public boolean equals(Object x) { if (x instanceof ModInteger) return ((ModInteger)x).num == num && ((ModInteger)x).mod == mod; return false; } @Override public int hashCode() { return num ^ mod; } @Override public String toString() { return String.valueOf(num); } @Deprecated public String debug() { int min = num, ans = 1; for (int i = 2;i < min;++ i) { int tmp = multiply(i).num; if (min > tmp) { min = tmp; ans = i; } } return min + "/" + ans; } @Override public Addition getAddition() { return add; } @Override public Multiplication getMultiplication() { return mul; } } /** * 素数を法とする演算上で、組み合わせの計算を高速に行います。 * @author 31536000 * */ public static class ModUtility { private final int mod; private int[] fact, inv, invfact; /** * modを法として、演算を行います。 * @param mod 法とする素数 */ public ModUtility(Prime mod) { this(mod, 2); } /** * modを法として、演算を行います。 * @param mod 法とする素数 * @param calc 予め前計算しておく大きさ */ public ModUtility(Prime mod, int calc) { this.mod = mod.prime; precalc(calc); } /** * calcの大きさだけ、前計算を行います。 * @param calc 前計算をする大きさ */ public void precalc(int calc) { ++ calc; if (calc < 2) calc = 2; fact = new int[calc]; inv = new int[calc]; invfact = new int[calc]; fact[0] = invfact[0] = fact[1] = invfact[1] = inv[1] = 1; for (int i = 2;i < calc;++ i) { fact[i] = (int)((long)fact[i - 1] * i % mod); inv[i] = (int)(mod - (long)inv[mod % i] * (mod / i) % mod); invfact[i] = (int)((long)invfact[i - 1] * inv[i] % mod); } } /** * modを法とする剰余環上で振舞う整数を返します。 * @return modを法とする整数、初期値は0 */ public ModInteger create() { return new ModInt(); } /** * modを法とする剰余環上で振舞う整数を返します。 * @param n 初期値 * @return modを法とする整数 */ public ModInteger create(int n) { return new ModInt(n); } private class ModInt extends ModInteger { private static final long serialVersionUID = -2435281861935422575L; public ModInt() { super(mod); } public ModInt(int n) { super(mod, n); } public ModInt(ModInteger mod) { super(mod); } @Override protected ModInteger getNewInstance(ModInteger mod) { return new ModInt(mod); } @Override protected int inverse(int n) { return ModUtility.this.inverse(n); } } /** * modを法として、nの逆元を返します。<br> * 計算量はO(log n)です。 * @param n 逆元を求めたい値 * @return 逆元 */ public int inverse(int n) { try { if (inv.length > n) return inv[n]; int m = mod, u = 0, v = 1, t; while(n != 0) { t = m / n; m -= t * n; u -= t * v; if (m != 0) { t = n / m; n -= t * m; v -= t * u; } else { v %= mod; if (v < 0) v += mod; return v; } } u %= mod; if (u < 0) u += mod; return u; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } } /** * n!を、modを法として求めた値を返します。<br> * 計算量はO(n)です。 * @param n 階乗を求めたい値 * @return nの階乗をmodで割った余り */ public int factorial(int n) { try { if (fact.length > n) return fact[n]; long ret = fact[fact.length - 1]; for (int i = fact.length;i <= n;++ i) ret = ret * i % mod; return (int)ret; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } } /** * nPkをmodで割った余りを求めます。<br> * 計算量はO(n-k)です。 * @param n 左辺 * @param k 右辺 * @return nPkをmodで割った余り */ public int permutation(int n, int k) { if (k < 0) throw new IllegalArgumentException(); if (n < k) return 0; if (fact.length > n) return (int)((long)fact[n] * invfact[n - k] % mod); long ret = 1; for (int i = n - k + 1;i <= n;++ i) ret = ret * i % mod; return (int)ret; } /** * nCkをmodで割った余りを求めます。<br> * 計算量はO(n-k)です。 * @param n 左辺 * @param k 右辺 * @return nCkをmodで割った余り */ public int combination(int n, int k) { if (k < 0) throw new IllegalArgumentException(); if (n < k) return 0; if (fact.length > n) return (int)((long)fact[n] * invfact[k] % mod * invfact[n - k] % mod); long ret = 1; if (n < 2 * k) k = n - k; if (invfact.length > k) ret = invfact[k]; else ret = inverse(factorial(k)); for (int i = n - k + 1;i <= n;++ i) ret = ret * i % mod; return (int)ret; } /** * 他項係数をmodで割った余りを求めます。<br>] * 計算量はO(n)です。 * @param n 左辺 * @param k 右辺、合計がn以下である必要がある * @return 他項係数 */ public int multinomial(int n, int... k) { int sum = 0; for (int i : k) sum += i; long ret = factorial(n); if (fact.length > n) { for (int i : k) { if (i < 0) throw new IllegalArgumentException(); ret = ret * invfact[i] % mod; sum += i; } if (sum > n) return 0; ret = ret * invfact[n - sum] % mod; } else { for (int i : k) { if (i < 0) throw new IllegalArgumentException(); if (invfact.length > i) ret = ret * invfact[i] % mod; else ret = ret * inverse(factorial(i)) % mod; sum += i; } if (sum > n) return 0; if (invfact.length > n - sum) ret = ret * invfact[n - sum] % mod; else ret = ret * inverse(factorial(n - sum)) % mod; } return (int)ret; } /** * n個からk個を選ぶ重複組み合わせnHkをmodで割った余りを求めます。<br> * 計算量はO(min(n, k))です。 * @param n 左辺 * @param k 右辺 * @return nHkをmodで割った余り */ public int multichoose(int n, int k) { return combination(mod(n + k - 1), k); } /** * カタラン数C(n)をmodで割った余りを求めます。<br> * 計算量はO(n)です。 * @param n 求めたいカタラン数の番号 * @return カタラン数 */ public int catalan(int n) { return divide(combination(mod(2 * n), n), mod(n + 1)); } /** * nのm乗をmodで割った余りを求めます。<br> * 計算量はO(log m)です。 * @param n 床 * @param m 冪指数 * @return n^mをmodで割った余り */ public int pow(int n, int m) { long ans = 1, num = n; if (m < 0) { m = -m; while (m != 0) { if ((m & 1) != 0) ans = ans * num % mod; m >>>= 1; num = num * num % mod; } return inverse((int)ans); } while (m != 0) { if ((m & 1) != 0) ans = ans * num % mod; m >>>= 1; num = num * num % mod; } return (int)ans; } /** * nのm乗をmodで割った余りを求めます。<br> * 計算量はO(log m)です。 * @param n 床 * @param m 冪指数 * @return n^mをmodで割った余り */ public int pow(long n, long m) { return pow((int)(n % mod), (int)(n % (mod - 1))); } /** * 現在のmod値のトーシェント数を返します。<br> * なお、これはmod-1に等しいです。 * @return トーシェント数 */ public int totient() { return mod - 1; } /** * nのトーシェント数を返します。<br> * 計算量はO(sqrt n)です。 * @param n トーシェント数を求めたい値 * @return nのトーシェント数 */ public static int totient(int n) { int totient = n; for (int i = 2;i * i <= n;++ i) { if (n % i == 0) { totient = totient / i * (i - 1); while ((n %= i) % i == 0); } } if (n != 1) totient = totient / n * (n - 1); return totient; } /** * nをmodで割った余りを返します。 * @param n 演算する値 * @return nをmodで割った余り */ public int mod(int n) { return (n %= mod) < 0 ? n + mod : n; } /** * nをmodで割った余りを返します。 * @param n 演算する値 * @return nをmodで割った余り */ public int mod(long n) { return (int)((n %= mod) < 0 ? n + mod : n); } /** * n+mをmodで割った余りを返します。 * @param n 足される値 * @param m 足す値 * @return n+mをmodで割った余り */ public int add(int n, int m) { return mod(n + m); } /** * n-mをmodで割った余りを返します。 * @param n 引かれる値 * @param m 引く値 * @return n-mをmodで割った余り */ public int subtract(int n, int m) { return mod(n - m); } /** * n*mをmodで割った余りを返します。 * @param n 掛けられる値 * @param m 掛ける値 * @return n*mをmodで割った余り */ public int multiply(int n, int m) { int ans = (int)((long)n * m % mod); return ans < 0 ? ans + mod : ans; } /** * n/mをmodで割った余りを返します。 * @param n 割られる値 * @param m 割る値 * @return n/mをmodで割った余り */ public int divide(int n, int m) { return multiply(n, inverse(m)); } /** * fを通ることが分かっているfの要素数-1次の関数について、xの位置における値をmodで割った余りを返します。<br> * 計算量はO(f)です。 * @param f 関数の形 * @param x 求める位置 * @return 求めたい値をmodで割った余り */ public ModInteger lagrangePolynomial(ModInteger[] f, int x) { if (f.length > x) return f[x]; if (x > fact.length) precalc(x); ModInteger ret = create(0); ModInteger[] dp = new ModInteger[f.length], dp2 = new ModInteger[f.length]; dp[0] = create(1); dp2[f.length - 1] = create(1); for (int i = 1;i < f.length;++ i) { dp[i] = dp[i - 1].multiply(x - i - 1); dp2[f.length - i - 1] = dp2[f.length - i].multiply(x - f.length + i); } for (int i = 0;i < f.length;++ i) { ModInteger tmp = f[i].multiply(dp[i]).multiplyEqual(dp2[i]).multiplyEqual(inv[i]).multiplyEqual(inv[f.length - 1 - i]); if ((f.length - i & 1) == 0) ret.addEqual(tmp); else ret.subtractEqual(tmp); } return ret; } } /** * 素数を渡すためのクラスです。<br> * 中身が確実に素数であることを保証するときに使ってください。 * * @author 31536000 * */ public static class Prime extends Number{ private static final long serialVersionUID = 8216169308184181643L; public final int prime; /** * 素数を設定します。 * * @param prime 素数 * @throws IllegalArgumentException 素数以外を渡した時 */ public Prime(int prime) { if (!isPrime(prime)) throw new IllegalArgumentException(prime + " is not prime"); this.prime = prime; } private static final int bases[] = {15591, 2018, 166, 7429, 8064, 16045, 10503, 4399, 1949, 1295, 2776, 3620, 560, 3128, 5212, 2657, 2300, 2021, 4652, 1471, 9336, 4018, 2398, 20462, 10277, 8028, 2213, 6219, 620, 3763, 4852, 5012, 3185, 1333, 6227, 5298, 1074, 2391, 5113, 7061, 803, 1269, 3875, 422, 751, 580, 4729, 10239, 746, 2951, 556, 2206, 3778, 481, 1522, 3476, 481, 2487, 3266, 5633, 488, 3373, 6441, 3344, 17, 15105, 1490, 4154, 2036, 1882, 1813, 467, 3307, 14042, 6371, 658, 1005, 903, 737, 1887, 7447, 1888, 2848, 1784, 7559, 3400, 951, 13969, 4304, 177, 41, 19875, 3110, 13221, 8726, 571, 7043, 6943, 1199, 352, 6435, 165, 1169, 3315, 978, 233, 3003, 2562, 2994, 10587, 10030, 2377, 1902, 5354, 4447, 1555, 263, 27027, 2283, 305, 669, 1912, 601, 6186, 429, 1930, 14873, 1784, 1661, 524, 3577, 236, 2360, 6146, 2850, 55637, 1753, 4178, 8466, 222, 2579, 2743, 2031, 2226, 2276, 374, 2132, 813, 23788, 1610, 4422, 5159, 1725, 3597, 3366, 14336, 579, 165, 1375, 10018, 12616, 9816, 1371, 536, 1867, 10864, 857, 2206, 5788, 434, 8085, 17618, 727, 3639, 1595, 4944, 2129, 2029, 8195, 8344, 6232, 9183, 8126, 1870, 3296, 7455, 8947, 25017, 541, 19115, 368, 566, 5674, 411, 522, 1027, 8215, 2050, 6544, 10049, 614, 774, 2333, 3007, 35201, 4706, 1152, 1785, 1028, 1540, 3743, 493, 4474, 2521, 26845, 8354, 864, 18915, 5465, 2447, 42, 4511, 1660, 166, 1249, 6259, 2553, 304, 272, 7286, 73, 6554, 899, 2816, 5197, 13330, 7054, 2818, 3199, 811, 922, 350, 7514, 4452, 3449, 2663, 4708, 418, 1621, 1171, 3471, 88, 11345, 412, 1559, 194}; private static boolean isSPRP(int n, int a) { int d = n - 1, s = 0; while ((d & 1) == 0) { ++s; d >>= 1; } long cur = 1, pw = d; while (pw != 0) { if ((pw & 1) != 0) cur = (cur * a) % n; a = (int)(((long)a * a) % n); pw >>= 1; } if (cur == 1) return true; for (int r = 0; r < s; r++ ) { if (cur == n - 1) return true; cur = (cur * cur) % n; } return false; } /** * 与えられた値が素数か否かを判定します。<br> * この実装はhttp://ceur-ws.org/Vol-1326/020-Forisek.pdfに基づきます。 * @param x 判定したい値 * @return xが素数ならtrue */ public static boolean isPrime(int x) { if (x == 2 || x == 3 || x == 5 || x == 7) return true; if ((x & 1) == 0 || x % 3 == 0 || x % 5 == 0 || x % 7 == 0) return false; if (x < 121) return x > 1; long h = x; h = ((h >> 16) ^ h) * 0x45d9f3b; h = ((h >> 16) ^ h) * 0x45d9f3b; h = ((h >> 16) ^ h) & 0xFF; return isSPRP(x, bases[(int)h]); } @Override public int intValue() { return prime; } @Override public long longValue() { return prime; } @Override public float floatValue() { return prime; } @Override public double doubleValue() { return prime; } @Override public String toString() { return String.valueOf(prime); } } public static class AbstractArray<T> extends AbstractList<T> implements RandomAccess{ private final Object[] array; public AbstractArray(int size) { array = new Object[size]; } public AbstractArray(T[] array) { this(array.length); System.arraycopy(array, 0, this.array, 0, array.length); } @Override public T set(int index, T element) { T ret = get(index); array[index] = element; return ret; } @Override public T get(int index) { @SuppressWarnings("unchecked") T ret = (T)array[index]; return ret; } public Object[] get() { return array; } public T[] get(T[] array) { if (array.length < this.array.length) { @SuppressWarnings("unchecked") T[] ret = (T[])Arrays.copyOfRange(this.array, 0, this.array.length, array.getClass()); return ret; } System.arraycopy(this.array, 0, array, 0, this.array.length); return array; } @Override public int size() { return array.length; } public int length() { return size(); } @Override public int hashCode() { return Arrays.hashCode(array); } private class Iter implements Iterator<T> { private int index; private Iter() { index = 0; } @Override public boolean hasNext() { return index < array.length; } @Override public T next() { return get(index++); } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<T> iterator() { return new Iter(); } } public static class Array<T> extends AbstractArray<T> implements Serializable{ private static final long serialVersionUID = 2749604433067098063L; public Array(int size) { super(size); } public Array(T[] array) { super(array); } public T front() { return get(0); } public T back() { return get(size() - 1); } } }
C#
using System; using System.Linq; using System.Collections.Generic; using Debug = System.Diagnostics.Debug; using StringBuilder = System.Text.StringBuilder; using Number = System.Int64; namespace Program { public class Solver { public void Solve() { var n = sc.Long(); for (long i = 1; i <= n; i++) { var x = i * (i + 1) / 2; if (x >= n) { IO.Printer.Out.WriteLine(i); return; } } } public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput()); static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; } static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; } } } #region main static class Ex { static public string AsString(this IEnumerable<char> ie) { return new string(System.Linq.Enumerable.ToArray(ie)); } static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); } static public void Main() { var solver = new Program.Solver(); solver.Solve(); Program.IO.Printer.Out.Flush(); } } #endregion #region Ex namespace Program.IO { using System.IO; using System.Text; using System.Globalization; public class Printer: StreamWriter { static Printer() { Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false }; } public static Printer Out { get; set; } public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } } public Printer(System.IO.Stream stream) : base(stream, new UTF8Encoding(false, true)) { } public Printer(System.IO.Stream stream, Encoding encoding) : base(stream, encoding) { } public void Write<T>(string format, T[] source) { base.Write(format, source.OfType<object>().ToArray()); } public void WriteLine<T>(string format, T[] source) { base.WriteLine(format, source.OfType<object>().ToArray()); } } public class StreamScanner { public StreamScanner(Stream stream) { str = stream; } public readonly Stream str; private readonly byte[] buf = new byte[1024]; private int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } private byte read() { if (isEof) return 0; if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } public char Char() { byte b = 0; do b = read(); while ((b < 33 || 126 < b) && !isEof); return (char)b; } public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } public string ScanLine() { var sb = new StringBuilder(); for (var b = Char(); b != '\n'; b = (char)read()) if (b == 0) break; else if (b != '\r') sb.Append(b); return sb.ToString(); } public long Long() { if (isEof) return long.MinValue; long ret = 0; byte b = 0; var ng = false; do b = read(); while (b != 0 && b != '-' && (b < '0' || '9' < b)); if (b == 0) return long.MinValue; if (b == '-') { ng = true; b = read(); } for (; true; b = read()) { if (b < '0' || '9' < b) return ng ? -ret : ret; else ret = ret * 10 + b - '0'; } } public int Integer() { return (isEof) ? int.MinValue : (int)Long(); } public double Double() { var s = Scan(); return s != "" ? double.Parse(s, CultureInfo.InvariantCulture) : double.NaN; } private T[] enumerate<T>(int n, Func<T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(); return a; } public char[] Char(int n) { return enumerate(n, Char); } public string[] Scan(int n) { return enumerate(n, Scan); } public double[] Double(int n) { return enumerate(n, Double); } public int[] Integer(int n) { return enumerate(n, Integer); } public long[] Long(int n) { return enumerate(n, Long); } } } #endregion
PHP
<?php /* Problem URL : http://arc070.contest.atcoder.jp/tasks/arc070_a Score : Result : Time : ms Memory : KB */ ini_set('error_reporting', E_ALL & ~E_NOTICE); define('DEBUG', false); fscanf(STDIN, "%d\n", $X); for ($i = 1; $i < PHP_INT_MAX; $i++) { $a += $i; if ($a >= $X) { echo $i . PHP_EOL; exit; } }
Yes
Do these codes solve the same problem? Code 1: using System; using System.Linq; using System.Collections.Generic; using Debug = System.Diagnostics.Debug; using StringBuilder = System.Text.StringBuilder; using Number = System.Int64; namespace Program { public class Solver { public void Solve() { var n = sc.Long(); for (long i = 1; i <= n; i++) { var x = i * (i + 1) / 2; if (x >= n) { IO.Printer.Out.WriteLine(i); return; } } } public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput()); static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; } static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; } } } #region main static class Ex { static public string AsString(this IEnumerable<char> ie) { return new string(System.Linq.Enumerable.ToArray(ie)); } static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); } static public void Main() { var solver = new Program.Solver(); solver.Solve(); Program.IO.Printer.Out.Flush(); } } #endregion #region Ex namespace Program.IO { using System.IO; using System.Text; using System.Globalization; public class Printer: StreamWriter { static Printer() { Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false }; } public static Printer Out { get; set; } public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } } public Printer(System.IO.Stream stream) : base(stream, new UTF8Encoding(false, true)) { } public Printer(System.IO.Stream stream, Encoding encoding) : base(stream, encoding) { } public void Write<T>(string format, T[] source) { base.Write(format, source.OfType<object>().ToArray()); } public void WriteLine<T>(string format, T[] source) { base.WriteLine(format, source.OfType<object>().ToArray()); } } public class StreamScanner { public StreamScanner(Stream stream) { str = stream; } public readonly Stream str; private readonly byte[] buf = new byte[1024]; private int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } private byte read() { if (isEof) return 0; if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } public char Char() { byte b = 0; do b = read(); while ((b < 33 || 126 < b) && !isEof); return (char)b; } public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } public string ScanLine() { var sb = new StringBuilder(); for (var b = Char(); b != '\n'; b = (char)read()) if (b == 0) break; else if (b != '\r') sb.Append(b); return sb.ToString(); } public long Long() { if (isEof) return long.MinValue; long ret = 0; byte b = 0; var ng = false; do b = read(); while (b != 0 && b != '-' && (b < '0' || '9' < b)); if (b == 0) return long.MinValue; if (b == '-') { ng = true; b = read(); } for (; true; b = read()) { if (b < '0' || '9' < b) return ng ? -ret : ret; else ret = ret * 10 + b - '0'; } } public int Integer() { return (isEof) ? int.MinValue : (int)Long(); } public double Double() { var s = Scan(); return s != "" ? double.Parse(s, CultureInfo.InvariantCulture) : double.NaN; } private T[] enumerate<T>(int n, Func<T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(); return a; } public char[] Char(int n) { return enumerate(n, Char); } public string[] Scan(int n) { return enumerate(n, Scan); } public double[] Double(int n) { return enumerate(n, Double); } public int[] Integer(int n) { return enumerate(n, Integer); } public long[] Long(int n) { return enumerate(n, Long); } } } #endregion Code 2: <?php /* Problem URL : http://arc070.contest.atcoder.jp/tasks/arc070_a Score : Result : Time : ms Memory : KB */ ini_set('error_reporting', E_ALL & ~E_NOTICE); define('DEBUG', false); fscanf(STDIN, "%d\n", $X); for ($i = 1; $i < PHP_INT_MAX; $i++) { $a += $i; if ($a >= $X) { echo $i . PHP_EOL; exit; } }
Python
a, b = map(int, input().split()) if a <= 8 and b <= 8: print("Yay!") else: print(":(")
C++
#include <stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> int main(){ int t,i,j,m,k=0,s[16]={0},n[20],a[20][20],b[20][20]; scanf("%d",&t); for(i=0;i<t;i++){ scanf("%d",&n[i]); for(j=0;j<n[i];j++) scanf("%d%d",&a[i][j],&b[i][j]); } m=0; while(s[t]!=1){ s[0]++; for(i=0;i<t;i++){ if(s[i]==2){ s[i]=0; s[i+1]++; } else break; } k=0; for(i=0;i<t;i++){ if(s[i]==1) k++; } for(i=0;i<t;i++){ if(s[i]==1){ for(j=0;j<n[i];j++){ if(b[i][j]!=s[a[i][j]-1]){ k=0; break; } } if(k==0) break; } } if(k>m) m=k; } printf("%d",m); return 0; }
No
Do these codes solve the same problem? Code 1: a, b = map(int, input().split()) if a <= 8 and b <= 8: print("Yay!") else: print(":(") Code 2: #include <stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> int main(){ int t,i,j,m,k=0,s[16]={0},n[20],a[20][20],b[20][20]; scanf("%d",&t); for(i=0;i<t;i++){ scanf("%d",&n[i]); for(j=0;j<n[i];j++) scanf("%d%d",&a[i][j],&b[i][j]); } m=0; while(s[t]!=1){ s[0]++; for(i=0;i<t;i++){ if(s[i]==2){ s[i]=0; s[i+1]++; } else break; } k=0; for(i=0;i<t;i++){ if(s[i]==1) k++; } for(i=0;i<t;i++){ if(s[i]==1){ for(j=0;j<n[i];j++){ if(b[i][j]!=s[a[i][j]-1]){ k=0; break; } } if(k==0) break; } } if(k>m) m=k; } printf("%d",m); return 0; }
Java
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.TreeSet; public class Main { public static void main(String[] args) { InputReader sc = new InputReader(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int ans = 0; for(int i = 0; i < n; i++){ int a2 = sc.nextInt(); int b2 = sc.nextInt(); if(a <= a2 && b <= b2){ ans++; } } System.out.println(ans); } //ここからテンプレ static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int next() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextStr() { int c = next(); while(isSpaceChar(c)){c = next();} StringBuffer str = new StringBuffer(); do{ str.append((char)c); c = next(); }while(!isSpaceChar(c)); return str.toString(); } public char nextChar() { int c = next(); while(isSpaceChar(c)){c = next();} char ret; do{ ret = (char)c; c = next(); }while(!isSpaceChar(c)); return ret; } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
PHP
<?php //error_reporting(0); //$N = trim(fgets(STDIN)); list($N,$H,$W) = explode(" ",trim(fgets(STDIN))); //$a = explode(" ",trim(fgets(STDIN))); //$H = explode(" ",trim(fgets(STDIN))); $res=0; for($i=0;$i<$N;$i++) { list($A,$B) = explode(" ",trim(fgets(STDIN))); if ($A >= $H && $B >= $W) { $res++; } } printf("%d\n",$res);
Yes
Do these codes solve the same problem? Code 1: import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.TreeSet; public class Main { public static void main(String[] args) { InputReader sc = new InputReader(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int ans = 0; for(int i = 0; i < n; i++){ int a2 = sc.nextInt(); int b2 = sc.nextInt(); if(a <= a2 && b <= b2){ ans++; } } System.out.println(ans); } //ここからテンプレ static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int next() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextStr() { int c = next(); while(isSpaceChar(c)){c = next();} StringBuffer str = new StringBuffer(); do{ str.append((char)c); c = next(); }while(!isSpaceChar(c)); return str.toString(); } public char nextChar() { int c = next(); while(isSpaceChar(c)){c = next();} char ret; do{ ret = (char)c; c = next(); }while(!isSpaceChar(c)); return ret; } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } } Code 2: <?php //error_reporting(0); //$N = trim(fgets(STDIN)); list($N,$H,$W) = explode(" ",trim(fgets(STDIN))); //$a = explode(" ",trim(fgets(STDIN))); //$H = explode(" ",trim(fgets(STDIN))); $res=0; for($i=0;$i<$N;$i++) { list($A,$B) = explode(" ",trim(fgets(STDIN))); if ($A >= $H && $B >= $W) { $res++; } } printf("%d\n",$res);
JavaScript
(function (input) { var inputs = input.replace(/\r/g, '').split("\n"), str, joi, ioi; while(true) { joi = 0; ioi = 0; str = inputs.shift(); if(str === '') { break; } for(var i = 0, len = str.length; i < len - 2; i++) { var tmp = str[i] + str[i + 1] + str[i + 2]; if(tmp == 'JOI') { joi++; } if(tmp == 'IOI') { ioi++; } } console.log(joi + "\n" + ioi); } })(require("fs").readFileSync("/dev/stdin", "utf8"));
C#
using System; class MyClass { static void Main(string[] args) { string str = ""; while ((str = Console.ReadLine()) != null) { int length = str.Length; int count1 = 0; int count2 = 0; for (int i = 0; i < length - 2; i++) { string sub = str.Substring(i, 3); if (sub == "JOI") { count1++; } else if (sub == "IOI") { count2++; } } Console.WriteLine(count1); Console.WriteLine(count2); } } }
Yes
Do these codes solve the same problem? Code 1: (function (input) { var inputs = input.replace(/\r/g, '').split("\n"), str, joi, ioi; while(true) { joi = 0; ioi = 0; str = inputs.shift(); if(str === '') { break; } for(var i = 0, len = str.length; i < len - 2; i++) { var tmp = str[i] + str[i + 1] + str[i + 2]; if(tmp == 'JOI') { joi++; } if(tmp == 'IOI') { ioi++; } } console.log(joi + "\n" + ioi); } })(require("fs").readFileSync("/dev/stdin", "utf8")); Code 2: using System; class MyClass { static void Main(string[] args) { string str = ""; while ((str = Console.ReadLine()) != null) { int length = str.Length; int count1 = 0; int count2 = 0; for (int i = 0; i < length - 2; i++) { string sub = str.Substring(i, 3); if (sub == "JOI") { count1++; } else if (sub == "IOI") { count2++; } } Console.WriteLine(count1); Console.WriteLine(count2); } } }
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { int[] ABCD = Console.ReadLine().Split().Select(int.Parse).ToArray(); int ans; if (ABCD[0] * ABCD[1] >= ABCD[2] * ABCD[3]) { ans = ABCD[0] * ABCD[1]; } else { ans = ABCD[2] * ABCD[3]; } Console.WriteLine(ans.ToString()); } }
C++
#include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cassert> #include <cstdint> #include <iostream> #include <iomanip> #include <string> #include <stack> #include <queue> #include <vector> #include <map> #include <set> #include <algorithm> #include <numeric> #include <bitset> using namespace std; using ll = long long; using Pll = pair<ll, ll>; using Pii = pair<int, int>; constexpr ll MOD = 1000000007; constexpr long double EPS = 1e-10; constexpr int dyx[4][2] = { { 0, 1}, {-1, 0}, {0,-1}, {1, 0} }; int main() { std::ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n), b(n), c(n-1); for(int i=0;i<n;++i){ cin >> a[i]; --a[i]; } int ans = 0; for(int i=0;i<n;++i) { cin >> b[i]; ans += b[i]; } for(int i=0;i<n-1;++i) { cin >> c[i]; } for(int i=1;i<n;++i) { if(a[i-1] + 1 == a[i]) { ans += c[a[i-1]]; } } cout << ans << endl; }
No
Do these codes solve the same problem? Code 1: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { int[] ABCD = Console.ReadLine().Split().Select(int.Parse).ToArray(); int ans; if (ABCD[0] * ABCD[1] >= ABCD[2] * ABCD[3]) { ans = ABCD[0] * ABCD[1]; } else { ans = ABCD[2] * ABCD[3]; } Console.WriteLine(ans.ToString()); } } Code 2: #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cassert> #include <cstdint> #include <iostream> #include <iomanip> #include <string> #include <stack> #include <queue> #include <vector> #include <map> #include <set> #include <algorithm> #include <numeric> #include <bitset> using namespace std; using ll = long long; using Pll = pair<ll, ll>; using Pii = pair<int, int>; constexpr ll MOD = 1000000007; constexpr long double EPS = 1e-10; constexpr int dyx[4][2] = { { 0, 1}, {-1, 0}, {0,-1}, {1, 0} }; int main() { std::ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n), b(n), c(n-1); for(int i=0;i<n;++i){ cin >> a[i]; --a[i]; } int ans = 0; for(int i=0;i<n;++i) { cin >> b[i]; ans += b[i]; } for(int i=0;i<n-1;++i) { cin >> c[i]; } for(int i=1;i<n;++i) { if(a[i-1] + 1 == a[i]) { ans += c[a[i-1]]; } } cout << ans << endl; }
C
#include <stdio.h> #include <stdlib.h> #define MAX 2000001 #define VMAX 10000 int A[MAX], B[MAX], C[MAX]; int main(){ int n, i, j, k = 0; scanf("%d",&n); for(i = 0; i < n; i++){ scanf("%d",&A[i + 1]); if(A[i + 1] > k)k = A[i + 1]; } for(i = 0; i <= k; i++)C[i] = 0; for(j = 1; j <= n; j++)C[A[j]]++; for(i = 1; i <= k; i++)C[i] = C[i] + C[i-1]; for(j = n; j >= 1; j--){ B[C[A[j]]] = A[j]; C[A[j]]--; } for(i = 1; i <= n; i++){ if(i > 1)printf(" "); printf("%d",B[i]); } printf("\n"); return 0; }
Python
n, a, b = list(map(int, input().split())) res = 0 for i in range(1, n+1): sum = int(i/10000) + int(i%10000/1000) + int(i%1000/100) + int(i%100/10) + int(i%10) if a <= sum and sum <= b: res += i print(res)
No
Do these codes solve the same problem? Code 1: #include <stdio.h> #include <stdlib.h> #define MAX 2000001 #define VMAX 10000 int A[MAX], B[MAX], C[MAX]; int main(){ int n, i, j, k = 0; scanf("%d",&n); for(i = 0; i < n; i++){ scanf("%d",&A[i + 1]); if(A[i + 1] > k)k = A[i + 1]; } for(i = 0; i <= k; i++)C[i] = 0; for(j = 1; j <= n; j++)C[A[j]]++; for(i = 1; i <= k; i++)C[i] = C[i] + C[i-1]; for(j = n; j >= 1; j--){ B[C[A[j]]] = A[j]; C[A[j]]--; } for(i = 1; i <= n; i++){ if(i > 1)printf(" "); printf("%d",B[i]); } printf("\n"); return 0; } Code 2: n, a, b = list(map(int, input().split())) res = 0 for i in range(1, n+1): sum = int(i/10000) + int(i%10000/1000) + int(i%1000/100) + int(i%100/10) + int(i%10) if a <= sum and sum <= b: res += i print(res)
Java
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Main main = new Main(); main.solve(); } private void solve() { Scanner sc = new Scanner(System.in); String N = sc.next(); long[][] dp = new long[N.length() + 1][2]; dp[0][0] = 0L; dp[0][1] = 1L; for (int i = 0; i < N.length(); i++) { dp[i + 1][0] = Math.min(dp[i][0] + (N.charAt(i) - '0'), dp[i][1] + 10 - (N.charAt(i) - '0')); dp[i + 1][1] = Math.min(dp[i][0] + (N.charAt(i) - '0') + 1, dp[i][1] + 9 - (N.charAt(i) - '0')); } System.out.println(Math.min(dp[N.length()][0], dp[N.length()][1] + 1)); } class Scanner { private InputStream in; private byte[] buffer = new byte[1024]; private int index; private int length; public Scanner(InputStream in) { this.in = in; } private boolean isPrintableChar(int c) { return '!' <= c && c <= '~'; } private boolean isDigit(int c) { return '0' <= c && c <= '9'; } private boolean hasNextByte() { if (index < length) { return true; } else { try { length = in.read(buffer); index = 0; } catch (IOException e) { e.printStackTrace(); } return length > 0; } } private boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[index])) { index++; } return hasNextByte(); } private int readByte() { return hasNextByte() ? buffer[index++] : -1; } public String next() { if (!hasNext()) { throw new RuntimeException("no input"); } StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) { throw new RuntimeException("no input"); } long value = 0L; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } while (isPrintableChar(b)) { if (isDigit(b)) { value = value * 10 + (b - '0'); } b = readByte(); } return minus ? -value : value; } public int nextInt() { return (int)nextLong(); } public double nextDouble() { return Double.parseDouble(next()); } } interface CombCalculator { long comb(int n, int m); } interface MobiusFunction { int get(int n); } /** * メビウス関数をエラトステネスの篩っぽく前計算するクラスです。 * 計算量はO(1)で、前計算でO(N logN)です。 */ class SieveMobiusFunction implements MobiusFunction { int size; int[] mobiusFunctionValues; public SieveMobiusFunction(int size) { this.size = size; mobiusFunctionValues = new int[size]; mobiusFunctionValues[0] = 0; mobiusFunctionValues[1] = 1; for (int i = 2; i < size; i++) { mobiusFunctionValues[i] = 1; } for (int i = 2; i * i < size; i++) { for (int k = 1; i * i * k < size; k++) { mobiusFunctionValues[i * i * k] *= 0; } } for (int i = 2; i < size; i++) { if (mobiusFunctionValues[i] == 1) { for (int k = 1; i * k < size; k++) { mobiusFunctionValues[i * k] *= -2; } } if (mobiusFunctionValues[i] > 1) { mobiusFunctionValues[i] = 1; } if (mobiusFunctionValues[i] < -1) { mobiusFunctionValues[i] = -1; } } } @Override public int get(int n) { if (n > size) { throw new RuntimeException("n is greater than size."); } if (n < 0) { return 0; } return mobiusFunctionValues[n]; } } /** * メビウス関数を定義通り計算するクラスです。 * 計算量はO(logN)です。 */ class PrimeFactorizationMobiusFunction implements MobiusFunction { @Override public int get(int n) { if (n <= 0) { return 0; } if (n == 1) { return 1; } int num = 0; for (int i = 2; i < n; i++) { if (n % i == 0) { n /= i; num++; if (n % i == 0) { return 0; } } } return num % 2 == 0 ? -1 : 1; } } /** * 組み合わせ計算を階乗の値で行うクラスです(MOD対応) * 階乗とその逆元は前計算してテーブルに格納します。 * C(N, N) % M の計算量は O(1)、 前計算でO(max(N, logM))です。 * sizeを1e8より大きい値で実行するとMLEの危険性があります。 * また素数以外のMODには対応していません(逆元の計算に素数の剰余環の性質を利用しているため)。 */ class FactorialTableCombCalculator implements CombCalculator { int size; long[] factorialTable; long[] inverseFactorialTable; long mod; public FactorialTableCombCalculator(int size, long mod) { this.size = size; factorialTable = new long[size + 1]; inverseFactorialTable = new long[size + 1]; this.mod = mod; factorialTable[0] = 1L; for (int i = 1; i <= size; i++) { factorialTable[i] = (factorialTable[i - 1] * i) % mod; } inverseFactorialTable[size] = inverse(factorialTable[size], mod); for (int i = size - 1; i >= 0; i--) { inverseFactorialTable[i] = (inverseFactorialTable[i + 1] * (i + 1)) % mod; } } private long inverse(long n, long mod) { return pow(n, mod - 2, mod); } private long pow(long n, long p, long mod) { if (p == 0) { return 1L; } long half = pow(n, p / 2, mod); long ret = (half * half) % mod; if (p % 2 == 1) { ret = (ret * n) % mod; } return ret; } @Override public long comb(int n, int m) { if (n > size) { throw new RuntimeException("n is greater than size."); } if (n < 0 || m < 0 || n < m) { return 0L; } return (((factorialTable[n] * inverseFactorialTable[m]) % mod) * inverseFactorialTable[n - m]) % mod; } } /** * 組み合わせ計算をテーブルで実装したクラスです(MOD対応) * 前計算でO(N^2), combはO(1)で実行できます * sizeを2 * 1e4より大きい値で実行するとMLEの危険性があります */ class TableCombCalculator implements CombCalculator { long[][] table; int size; public TableCombCalculator(int size, long mod) { this.size = size; table = new long[size + 1][]; table[0] = new long[1]; table[0][0] = 1L; for (int n = 1; n <= size; n++) { table[n] = new long[n + 1]; table[n][0] = 1L; for (int m = 1; m < n; m++) { table[n][m] = (table[n - 1][m - 1] + table[n - 1][m]) % mod; } table[n][n] = 1L; } } @Override public long comb(int n, int m) { if (n > size) { throw new RuntimeException("n is greater than size."); } if (n < 0 || m < 0 || n < m) { return 0L; } return table[n][m]; } } interface Graph { void link(int from, int to, long cost); Optional<Long> getCost(int from, int to); int getVertexNum(); } interface FlowResolver { long maxFlow(int from, int to); } /** * グラフの行列による実装 * 接点数の大きいグラフで使うとMLEで死にそう */ class ArrayGraph implements Graph { private Long[][] costArray; private int vertexNum; public ArrayGraph(int n) { costArray = new Long[n][]; for (int i = 0; i < n; i++) { costArray[i] = new Long[n]; } vertexNum = n; } @Override public void link(int from, int to, long cost) { costArray[from][to] = new Long(cost); } @Override public Optional<Long> getCost(int from, int to) { return Optional.ofNullable(costArray[from][to]); } @Override public int getVertexNum() { return vertexNum; } } /** * DFS(深さ優先探索)による実装 * 計算量はO(E*MaxFlow)のはず (E:辺の数, MaxFlow:最大フロー) */ class DfsFlowResolver implements FlowResolver { private Graph graph; public DfsFlowResolver(Graph graph) { this.graph = graph; } /** * 最大フロー(最小カット)を求める * @param from 始点(source)のID * @param to 終点(target)のID * @return 最大フロー(最小カット) */ public long maxFlow(int from, int to) { long sum = 0L; long currentFlow; do { currentFlow = flow(from, to, Long.MAX_VALUE / 3, new boolean[graph.getVertexNum()]); sum += currentFlow; } while (currentFlow > 0); return sum; } /** * フローの実行 グラフの更新も行う * @param from 現在いる節点のID * @param to 終点(target)のID * @param current_flow ここまでの流量 * @param passed 既に通った節点か否かを格納した配列 * @return 終点(target)に流した流量/戻りのグラフの流量 */ private long flow(int from, int to, long current_flow, boolean[] passed) { passed[from] = true; if (from == to) { return current_flow; } for (int id = 0; id < graph.getVertexNum(); id++) { if (passed[id]) { continue; } Optional<Long> cost = graph.getCost(from, id); if (cost.orElse(0L) > 0) { long nextFlow = current_flow < cost.get() ? current_flow : cost.get(); long returnFlow = flow(id, to, nextFlow, passed); if (returnFlow > 0) { graph.link(from, id, cost.get() - returnFlow); graph.link(id, from, graph.getCost(id, from).orElse(0L) + returnFlow); return returnFlow; } } } return 0L; } } /** * 1-indexedのBIT配列 */ class BinaryIndexedTree { private long[] array; public BinaryIndexedTree(int size) { this.array = new long[size + 1]; } /** * 指定した要素に値を加算する * 計算量はO(logN) * @param index 加算する要素の添字 * @param value 加算する量 */ public void add(int index, long value) { for (int i = index; i < array.length; i += (i & -i)) { array[i] += value; } } /** * 1〜指定した要素までの和を取得する * 計算量はO(logN) * @param index 和の終端となる要素の添字 * @return 1〜indexまでの和 */ public long getSum(int index) { long sum = 0L; for (int i = index; i > 0; i -= (i & -i)) { sum += array[i]; } return sum; } } /** * 1-indexedの2次元BIT配列 */ class BinaryIndexedTree2D { private long[][] array; public BinaryIndexedTree2D(int size1, int size2) { this.array = new long[size1 + 1][]; for (int i = 1; i <= size1; i++) { this.array[i] = new long[size2 + 1]; } } /** * 指定した要素に値を加算する * 計算量はO(logN * logN) * @param index1 加算する要素の1次元目の添字 * @param index2 加算する要素の2次元目の添字 * @param value 加算する量 */ public void add(int index1, int index2, long value) { for (int i1 = index1; i1 < array.length; i1 += (i1 & -i1)) { for (int i2 = index2; i2 < array.length; i2 += (i2 & -i2)) { array[i1][i2] += value; } } } /** * (1,1)〜指定した要素までの矩形和を取得する * 計算量はO(logN * logN) * @param index1 和の終端となる要素の1次元目の添字 * @param index2 和の終端となる要素の2次元目の添字 * @return (1,1)〜(index1,index2)までの矩形和 */ public long getSum(int index1, int index2) { long sum = 0L; for (int i1 = index1; i1 > 0; i1 -= (i1 & -i1)) { for (int i2 = index2; i2 > 0; i2 -= (i2 & -i2)) { sum += array[i1][i2]; } } return sum; } } interface UnionFind { void union(int A, int B); boolean judge(int A, int B); Set<Integer> getSet(int id); } /** * ArrayUnionFindの拡張 * MapSetで根の添字から根にぶら下がる頂点の集合が取得できるようにした * getSetメソッドをO(logN * logN)に落とせているはず * ただしunionメソッドは2倍の計算量になっているので注意(オーダーは変わらないはず) */ class SetUnionFind extends ArrayUnionFind { Map<Integer, Set<Integer>> map; public SetUnionFind(int size) { super(size); map = new HashMap<>(); for (int i = 0; i < size; i++) { map.put(i, new HashSet<>()); map.get(i).add(i); } } @Override protected void unionTo(int source, int dest) { super.unionTo(source, dest); map.get(dest).addAll(map.get(source)); } @Override public Set<Integer> getSet(int id) { return map.get(root(id)); } } /** * 配列によるUnionFindの実装 * getSetメソッドはO(NlogN)なのでTLEに注意 */ class ArrayUnionFind implements UnionFind { int[] parent; int[] rank; int size; public ArrayUnionFind(int size) { parent = new int[size]; for (int i = 0; i < size; i++) { parent[i] = i; } rank = new int[size]; this.size = size; } @Override public void union(int A, int B) { int rootA = root(A); int rootB = root(B); if (rootA != rootB) { if (rank[rootA] < rank[rootB]) { unionTo(rootA, rootB); } else { unionTo(rootB, rootA); if (rank[rootA] == rank[rootB]) { rank[rootA]++; } } } } protected void unionTo(int source, int dest) { parent[source] = dest; } @Override public boolean judge(int A, int B) { return root(A) == root(B); } @Override public Set<Integer> getSet(int id) { Set<Integer> set = new HashSet<>(); IntStream.range(0, size).filter(i -> judge(i, id)).forEach(set::add); return set; } protected int root(int id) { if (parent[id] == id) { return id; } parent[id] = root(parent[id]); return parent[id]; } } /** * 素数のユーティリティ */ class PrimeNumberUtils { boolean[] isPrimeArray; List<Integer> primes; /** * 素数判定の上限となる値を指定してユーティリティを初期化 * @param limit 素数判定の上限(この値以上が素数であるか判定しない) */ public PrimeNumberUtils(int limit) { if (limit > 10000000) { System.err.println("上限の値が高すぎるため素数ユーティリティの初期化でTLEする可能性が大変高いです"); } primes = new ArrayList<>(); isPrimeArray = new boolean[limit]; if (limit > 2) { primes.add(2); isPrimeArray[2] = true; } for (int i = 3; i < limit; i += 2) { if (isPrime(i, primes)) { primes.add(i); isPrimeArray[i] = true; } } } public List<Integer> getPrimeNumberList() { return primes; } public boolean isPrime(int n) { return isPrimeArray[n]; } private boolean isPrime(int n, List<Integer> primes) { for (int prime : primes) { if (n % prime == 0) { return false; } if (prime > Math.sqrt(n)) { break; } } return true; } } interface BitSet { void set(int index, boolean bit); boolean get(int index); void shiftRight(int num); void shiftLeft(int num); void or(BitSet bitset); void and(BitSet bitset); } /** * Longの配列によるBitSetの実装 * get/setはO(1) * shift/or/andはO(size / 64) */ class LongBit implements BitSet { long[] bitArray; public LongBit(int size) { bitArray = new long[((size + 63) / 64)]; } @Override public void set(int index, boolean bit) { int segment = index / 64; int inIndex = index % 64; if (bit) { bitArray[segment] |= 1L << inIndex; } else { bitArray[segment] &= ~(1L << inIndex); } } @Override public boolean get(int index) { int segment = index / 64; int inIndex = index % 64; return (bitArray[segment] & (1L << inIndex)) != 0L; } @Override public void shiftRight(int num) { int shiftSeg = num / 64; int shiftInI = num % 64; for (int segment = 0; segment < bitArray.length; segment++) { int sourceSeg = segment + shiftSeg; if (sourceSeg < bitArray.length) { bitArray[segment] = bitArray[sourceSeg] >>> shiftInI; if (shiftInI > 0 && sourceSeg + 1 < bitArray.length) { bitArray[segment] |= bitArray[sourceSeg + 1] << (64 - shiftInI); } } else { bitArray[segment] = 0L; } } } @Override public void shiftLeft(int num) { int shiftSeg = num / 64; int shiftInI = num % 64; for (int segment = bitArray.length - 1; segment >= 0; segment--) { int sourceSeg = segment - shiftSeg; if (sourceSeg >= 0) { bitArray[segment] = bitArray[sourceSeg] << shiftInI; if (shiftInI > 0 && sourceSeg > 0) { bitArray[segment] |= bitArray[sourceSeg - 1] >>> (64 - shiftInI); } } else { bitArray[segment] = 0L; } } } public long getLong(int segment) { return bitArray[segment]; } @Override public void or(BitSet bitset) { if (!(bitset instanceof LongBit)) { return; } for (int segment = 0; segment < bitArray.length; segment++) { bitArray[segment] |= ((LongBit)bitset).getLong(segment); } } @Override public void and(BitSet bitset) { if (!(bitset instanceof LongBit)) { return; } for (int segment = 0; segment < bitArray.length; segment++) { bitArray[segment] &= ((LongBit)bitset).getLong(segment); } } } }
PHP
<?php $str = "0".str(); $l = strlen($str); $dp0 = array_fill(0, $l+1, 0);//超えてないやつ $dp1 = array_fill(0, $l+1, 0);//超えたやつ for($i = 0; $i < $l; $i++){ $dp0[$i+1] = min($dp0[$i]+$str[$i], $dp1[$i]+10-$str[$i]); $dp1[$i+1] = min($dp0[$i]+$str[$i]+1, $dp1[$i] + 9 - $str[$i]); } echo min($dp0[$i],$dp1[$l]+1),"\n"; //o($str); //o($dp0); //o($dp1); function str(){ return trim(fgets(STDIN)); } function ints(){ return array_map("intval", explode(" ", trim(fgets(STDIN)))); } function int(){ return intval(trim(fgets(STDIN))); } function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;} function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;} function o(...$val){ if(count($val)==1)$val = array_shift($val); $trace = debug_backtrace(); echo $trace[0]['line'].")"; if(is_array($val)){ if(count($val) == 0){ echo "empty array"; }elseif(!is_array(current($val))){ echo "array: "; echo implode(" ", addIndex($val))."\n"; }else{ echo "array:array\n"; if(isCleanArray($val)){ foreach($val as $row)echo implode(" ", addIndex($row))."\n"; }else{ foreach($val as $i => $row)echo "[".$i."] ".implode(" ", addIndex($row))."\n"; } } }else{ echo $val."\n"; } } function addIndex($val){ if(!isCleanArray($val)){ $val = array_map(function($k, $v){return $k.":".$v;}, array_keys($val), $val); } return $val; } function isCleanArray($array){ $clean = true; $i = 0; foreach($array as $k => $v){ if($k != $i++)$clean = false; } return $clean; } /** * 座圧対象の配列を渡すと以下の値を返す * ・圧縮された配列 * ・復元用のMap * ・圧縮用のMap **/ function atsu($array){ $a = array_flip($array); $fuku = array_flip($a); sort($fuku); $atsu = array_flip($fuku); foreach($array as $i => $val)$array[$i] = $atsu[$val]; return [$array, $fuku, $atsu]; } //配列の最大公約数 function gcdAll($array){ $gcd = $array[0]; for($i = 1; $i < count($array); $i++){ $gcd = gcd($gcd, $array[$i]); } return $gcd; } //最大公約数 function gcd($m, $n){ if(!$n)return $m; return gcd($n, $m % $n); } //配列の最小公倍数 function lcmAll($array){ $lcm = $array[0]; for($i = 1; $i < count($array); $i++){ $lcm = lcm($lcm, $array[$i]); } return $lcm; } //最小公倍数 function lcm($a, $b) { return $a / gcd($a, $b) * $b; } //ビットカウント-1の数を数える function popcount($x){ $con = 0; while ($x) { $x &= $x-1; ++$con; } return $con; }
Yes
Do these codes solve the same problem? Code 1: import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Main main = new Main(); main.solve(); } private void solve() { Scanner sc = new Scanner(System.in); String N = sc.next(); long[][] dp = new long[N.length() + 1][2]; dp[0][0] = 0L; dp[0][1] = 1L; for (int i = 0; i < N.length(); i++) { dp[i + 1][0] = Math.min(dp[i][0] + (N.charAt(i) - '0'), dp[i][1] + 10 - (N.charAt(i) - '0')); dp[i + 1][1] = Math.min(dp[i][0] + (N.charAt(i) - '0') + 1, dp[i][1] + 9 - (N.charAt(i) - '0')); } System.out.println(Math.min(dp[N.length()][0], dp[N.length()][1] + 1)); } class Scanner { private InputStream in; private byte[] buffer = new byte[1024]; private int index; private int length; public Scanner(InputStream in) { this.in = in; } private boolean isPrintableChar(int c) { return '!' <= c && c <= '~'; } private boolean isDigit(int c) { return '0' <= c && c <= '9'; } private boolean hasNextByte() { if (index < length) { return true; } else { try { length = in.read(buffer); index = 0; } catch (IOException e) { e.printStackTrace(); } return length > 0; } } private boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[index])) { index++; } return hasNextByte(); } private int readByte() { return hasNextByte() ? buffer[index++] : -1; } public String next() { if (!hasNext()) { throw new RuntimeException("no input"); } StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) { throw new RuntimeException("no input"); } long value = 0L; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } while (isPrintableChar(b)) { if (isDigit(b)) { value = value * 10 + (b - '0'); } b = readByte(); } return minus ? -value : value; } public int nextInt() { return (int)nextLong(); } public double nextDouble() { return Double.parseDouble(next()); } } interface CombCalculator { long comb(int n, int m); } interface MobiusFunction { int get(int n); } /** * メビウス関数をエラトステネスの篩っぽく前計算するクラスです。 * 計算量はO(1)で、前計算でO(N logN)です。 */ class SieveMobiusFunction implements MobiusFunction { int size; int[] mobiusFunctionValues; public SieveMobiusFunction(int size) { this.size = size; mobiusFunctionValues = new int[size]; mobiusFunctionValues[0] = 0; mobiusFunctionValues[1] = 1; for (int i = 2; i < size; i++) { mobiusFunctionValues[i] = 1; } for (int i = 2; i * i < size; i++) { for (int k = 1; i * i * k < size; k++) { mobiusFunctionValues[i * i * k] *= 0; } } for (int i = 2; i < size; i++) { if (mobiusFunctionValues[i] == 1) { for (int k = 1; i * k < size; k++) { mobiusFunctionValues[i * k] *= -2; } } if (mobiusFunctionValues[i] > 1) { mobiusFunctionValues[i] = 1; } if (mobiusFunctionValues[i] < -1) { mobiusFunctionValues[i] = -1; } } } @Override public int get(int n) { if (n > size) { throw new RuntimeException("n is greater than size."); } if (n < 0) { return 0; } return mobiusFunctionValues[n]; } } /** * メビウス関数を定義通り計算するクラスです。 * 計算量はO(logN)です。 */ class PrimeFactorizationMobiusFunction implements MobiusFunction { @Override public int get(int n) { if (n <= 0) { return 0; } if (n == 1) { return 1; } int num = 0; for (int i = 2; i < n; i++) { if (n % i == 0) { n /= i; num++; if (n % i == 0) { return 0; } } } return num % 2 == 0 ? -1 : 1; } } /** * 組み合わせ計算を階乗の値で行うクラスです(MOD対応) * 階乗とその逆元は前計算してテーブルに格納します。 * C(N, N) % M の計算量は O(1)、 前計算でO(max(N, logM))です。 * sizeを1e8より大きい値で実行するとMLEの危険性があります。 * また素数以外のMODには対応していません(逆元の計算に素数の剰余環の性質を利用しているため)。 */ class FactorialTableCombCalculator implements CombCalculator { int size; long[] factorialTable; long[] inverseFactorialTable; long mod; public FactorialTableCombCalculator(int size, long mod) { this.size = size; factorialTable = new long[size + 1]; inverseFactorialTable = new long[size + 1]; this.mod = mod; factorialTable[0] = 1L; for (int i = 1; i <= size; i++) { factorialTable[i] = (factorialTable[i - 1] * i) % mod; } inverseFactorialTable[size] = inverse(factorialTable[size], mod); for (int i = size - 1; i >= 0; i--) { inverseFactorialTable[i] = (inverseFactorialTable[i + 1] * (i + 1)) % mod; } } private long inverse(long n, long mod) { return pow(n, mod - 2, mod); } private long pow(long n, long p, long mod) { if (p == 0) { return 1L; } long half = pow(n, p / 2, mod); long ret = (half * half) % mod; if (p % 2 == 1) { ret = (ret * n) % mod; } return ret; } @Override public long comb(int n, int m) { if (n > size) { throw new RuntimeException("n is greater than size."); } if (n < 0 || m < 0 || n < m) { return 0L; } return (((factorialTable[n] * inverseFactorialTable[m]) % mod) * inverseFactorialTable[n - m]) % mod; } } /** * 組み合わせ計算をテーブルで実装したクラスです(MOD対応) * 前計算でO(N^2), combはO(1)で実行できます * sizeを2 * 1e4より大きい値で実行するとMLEの危険性があります */ class TableCombCalculator implements CombCalculator { long[][] table; int size; public TableCombCalculator(int size, long mod) { this.size = size; table = new long[size + 1][]; table[0] = new long[1]; table[0][0] = 1L; for (int n = 1; n <= size; n++) { table[n] = new long[n + 1]; table[n][0] = 1L; for (int m = 1; m < n; m++) { table[n][m] = (table[n - 1][m - 1] + table[n - 1][m]) % mod; } table[n][n] = 1L; } } @Override public long comb(int n, int m) { if (n > size) { throw new RuntimeException("n is greater than size."); } if (n < 0 || m < 0 || n < m) { return 0L; } return table[n][m]; } } interface Graph { void link(int from, int to, long cost); Optional<Long> getCost(int from, int to); int getVertexNum(); } interface FlowResolver { long maxFlow(int from, int to); } /** * グラフの行列による実装 * 接点数の大きいグラフで使うとMLEで死にそう */ class ArrayGraph implements Graph { private Long[][] costArray; private int vertexNum; public ArrayGraph(int n) { costArray = new Long[n][]; for (int i = 0; i < n; i++) { costArray[i] = new Long[n]; } vertexNum = n; } @Override public void link(int from, int to, long cost) { costArray[from][to] = new Long(cost); } @Override public Optional<Long> getCost(int from, int to) { return Optional.ofNullable(costArray[from][to]); } @Override public int getVertexNum() { return vertexNum; } } /** * DFS(深さ優先探索)による実装 * 計算量はO(E*MaxFlow)のはず (E:辺の数, MaxFlow:最大フロー) */ class DfsFlowResolver implements FlowResolver { private Graph graph; public DfsFlowResolver(Graph graph) { this.graph = graph; } /** * 最大フロー(最小カット)を求める * @param from 始点(source)のID * @param to 終点(target)のID * @return 最大フロー(最小カット) */ public long maxFlow(int from, int to) { long sum = 0L; long currentFlow; do { currentFlow = flow(from, to, Long.MAX_VALUE / 3, new boolean[graph.getVertexNum()]); sum += currentFlow; } while (currentFlow > 0); return sum; } /** * フローの実行 グラフの更新も行う * @param from 現在いる節点のID * @param to 終点(target)のID * @param current_flow ここまでの流量 * @param passed 既に通った節点か否かを格納した配列 * @return 終点(target)に流した流量/戻りのグラフの流量 */ private long flow(int from, int to, long current_flow, boolean[] passed) { passed[from] = true; if (from == to) { return current_flow; } for (int id = 0; id < graph.getVertexNum(); id++) { if (passed[id]) { continue; } Optional<Long> cost = graph.getCost(from, id); if (cost.orElse(0L) > 0) { long nextFlow = current_flow < cost.get() ? current_flow : cost.get(); long returnFlow = flow(id, to, nextFlow, passed); if (returnFlow > 0) { graph.link(from, id, cost.get() - returnFlow); graph.link(id, from, graph.getCost(id, from).orElse(0L) + returnFlow); return returnFlow; } } } return 0L; } } /** * 1-indexedのBIT配列 */ class BinaryIndexedTree { private long[] array; public BinaryIndexedTree(int size) { this.array = new long[size + 1]; } /** * 指定した要素に値を加算する * 計算量はO(logN) * @param index 加算する要素の添字 * @param value 加算する量 */ public void add(int index, long value) { for (int i = index; i < array.length; i += (i & -i)) { array[i] += value; } } /** * 1〜指定した要素までの和を取得する * 計算量はO(logN) * @param index 和の終端となる要素の添字 * @return 1〜indexまでの和 */ public long getSum(int index) { long sum = 0L; for (int i = index; i > 0; i -= (i & -i)) { sum += array[i]; } return sum; } } /** * 1-indexedの2次元BIT配列 */ class BinaryIndexedTree2D { private long[][] array; public BinaryIndexedTree2D(int size1, int size2) { this.array = new long[size1 + 1][]; for (int i = 1; i <= size1; i++) { this.array[i] = new long[size2 + 1]; } } /** * 指定した要素に値を加算する * 計算量はO(logN * logN) * @param index1 加算する要素の1次元目の添字 * @param index2 加算する要素の2次元目の添字 * @param value 加算する量 */ public void add(int index1, int index2, long value) { for (int i1 = index1; i1 < array.length; i1 += (i1 & -i1)) { for (int i2 = index2; i2 < array.length; i2 += (i2 & -i2)) { array[i1][i2] += value; } } } /** * (1,1)〜指定した要素までの矩形和を取得する * 計算量はO(logN * logN) * @param index1 和の終端となる要素の1次元目の添字 * @param index2 和の終端となる要素の2次元目の添字 * @return (1,1)〜(index1,index2)までの矩形和 */ public long getSum(int index1, int index2) { long sum = 0L; for (int i1 = index1; i1 > 0; i1 -= (i1 & -i1)) { for (int i2 = index2; i2 > 0; i2 -= (i2 & -i2)) { sum += array[i1][i2]; } } return sum; } } interface UnionFind { void union(int A, int B); boolean judge(int A, int B); Set<Integer> getSet(int id); } /** * ArrayUnionFindの拡張 * MapSetで根の添字から根にぶら下がる頂点の集合が取得できるようにした * getSetメソッドをO(logN * logN)に落とせているはず * ただしunionメソッドは2倍の計算量になっているので注意(オーダーは変わらないはず) */ class SetUnionFind extends ArrayUnionFind { Map<Integer, Set<Integer>> map; public SetUnionFind(int size) { super(size); map = new HashMap<>(); for (int i = 0; i < size; i++) { map.put(i, new HashSet<>()); map.get(i).add(i); } } @Override protected void unionTo(int source, int dest) { super.unionTo(source, dest); map.get(dest).addAll(map.get(source)); } @Override public Set<Integer> getSet(int id) { return map.get(root(id)); } } /** * 配列によるUnionFindの実装 * getSetメソッドはO(NlogN)なのでTLEに注意 */ class ArrayUnionFind implements UnionFind { int[] parent; int[] rank; int size; public ArrayUnionFind(int size) { parent = new int[size]; for (int i = 0; i < size; i++) { parent[i] = i; } rank = new int[size]; this.size = size; } @Override public void union(int A, int B) { int rootA = root(A); int rootB = root(B); if (rootA != rootB) { if (rank[rootA] < rank[rootB]) { unionTo(rootA, rootB); } else { unionTo(rootB, rootA); if (rank[rootA] == rank[rootB]) { rank[rootA]++; } } } } protected void unionTo(int source, int dest) { parent[source] = dest; } @Override public boolean judge(int A, int B) { return root(A) == root(B); } @Override public Set<Integer> getSet(int id) { Set<Integer> set = new HashSet<>(); IntStream.range(0, size).filter(i -> judge(i, id)).forEach(set::add); return set; } protected int root(int id) { if (parent[id] == id) { return id; } parent[id] = root(parent[id]); return parent[id]; } } /** * 素数のユーティリティ */ class PrimeNumberUtils { boolean[] isPrimeArray; List<Integer> primes; /** * 素数判定の上限となる値を指定してユーティリティを初期化 * @param limit 素数判定の上限(この値以上が素数であるか判定しない) */ public PrimeNumberUtils(int limit) { if (limit > 10000000) { System.err.println("上限の値が高すぎるため素数ユーティリティの初期化でTLEする可能性が大変高いです"); } primes = new ArrayList<>(); isPrimeArray = new boolean[limit]; if (limit > 2) { primes.add(2); isPrimeArray[2] = true; } for (int i = 3; i < limit; i += 2) { if (isPrime(i, primes)) { primes.add(i); isPrimeArray[i] = true; } } } public List<Integer> getPrimeNumberList() { return primes; } public boolean isPrime(int n) { return isPrimeArray[n]; } private boolean isPrime(int n, List<Integer> primes) { for (int prime : primes) { if (n % prime == 0) { return false; } if (prime > Math.sqrt(n)) { break; } } return true; } } interface BitSet { void set(int index, boolean bit); boolean get(int index); void shiftRight(int num); void shiftLeft(int num); void or(BitSet bitset); void and(BitSet bitset); } /** * Longの配列によるBitSetの実装 * get/setはO(1) * shift/or/andはO(size / 64) */ class LongBit implements BitSet { long[] bitArray; public LongBit(int size) { bitArray = new long[((size + 63) / 64)]; } @Override public void set(int index, boolean bit) { int segment = index / 64; int inIndex = index % 64; if (bit) { bitArray[segment] |= 1L << inIndex; } else { bitArray[segment] &= ~(1L << inIndex); } } @Override public boolean get(int index) { int segment = index / 64; int inIndex = index % 64; return (bitArray[segment] & (1L << inIndex)) != 0L; } @Override public void shiftRight(int num) { int shiftSeg = num / 64; int shiftInI = num % 64; for (int segment = 0; segment < bitArray.length; segment++) { int sourceSeg = segment + shiftSeg; if (sourceSeg < bitArray.length) { bitArray[segment] = bitArray[sourceSeg] >>> shiftInI; if (shiftInI > 0 && sourceSeg + 1 < bitArray.length) { bitArray[segment] |= bitArray[sourceSeg + 1] << (64 - shiftInI); } } else { bitArray[segment] = 0L; } } } @Override public void shiftLeft(int num) { int shiftSeg = num / 64; int shiftInI = num % 64; for (int segment = bitArray.length - 1; segment >= 0; segment--) { int sourceSeg = segment - shiftSeg; if (sourceSeg >= 0) { bitArray[segment] = bitArray[sourceSeg] << shiftInI; if (shiftInI > 0 && sourceSeg > 0) { bitArray[segment] |= bitArray[sourceSeg - 1] >>> (64 - shiftInI); } } else { bitArray[segment] = 0L; } } } public long getLong(int segment) { return bitArray[segment]; } @Override public void or(BitSet bitset) { if (!(bitset instanceof LongBit)) { return; } for (int segment = 0; segment < bitArray.length; segment++) { bitArray[segment] |= ((LongBit)bitset).getLong(segment); } } @Override public void and(BitSet bitset) { if (!(bitset instanceof LongBit)) { return; } for (int segment = 0; segment < bitArray.length; segment++) { bitArray[segment] &= ((LongBit)bitset).getLong(segment); } } } } Code 2: <?php $str = "0".str(); $l = strlen($str); $dp0 = array_fill(0, $l+1, 0);//超えてないやつ $dp1 = array_fill(0, $l+1, 0);//超えたやつ for($i = 0; $i < $l; $i++){ $dp0[$i+1] = min($dp0[$i]+$str[$i], $dp1[$i]+10-$str[$i]); $dp1[$i+1] = min($dp0[$i]+$str[$i]+1, $dp1[$i] + 9 - $str[$i]); } echo min($dp0[$i],$dp1[$l]+1),"\n"; //o($str); //o($dp0); //o($dp1); function str(){ return trim(fgets(STDIN)); } function ints(){ return array_map("intval", explode(" ", trim(fgets(STDIN)))); } function int(){ return intval(trim(fgets(STDIN))); } function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;} function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;} function o(...$val){ if(count($val)==1)$val = array_shift($val); $trace = debug_backtrace(); echo $trace[0]['line'].")"; if(is_array($val)){ if(count($val) == 0){ echo "empty array"; }elseif(!is_array(current($val))){ echo "array: "; echo implode(" ", addIndex($val))."\n"; }else{ echo "array:array\n"; if(isCleanArray($val)){ foreach($val as $row)echo implode(" ", addIndex($row))."\n"; }else{ foreach($val as $i => $row)echo "[".$i."] ".implode(" ", addIndex($row))."\n"; } } }else{ echo $val."\n"; } } function addIndex($val){ if(!isCleanArray($val)){ $val = array_map(function($k, $v){return $k.":".$v;}, array_keys($val), $val); } return $val; } function isCleanArray($array){ $clean = true; $i = 0; foreach($array as $k => $v){ if($k != $i++)$clean = false; } return $clean; } /** * 座圧対象の配列を渡すと以下の値を返す * ・圧縮された配列 * ・復元用のMap * ・圧縮用のMap **/ function atsu($array){ $a = array_flip($array); $fuku = array_flip($a); sort($fuku); $atsu = array_flip($fuku); foreach($array as $i => $val)$array[$i] = $atsu[$val]; return [$array, $fuku, $atsu]; } //配列の最大公約数 function gcdAll($array){ $gcd = $array[0]; for($i = 1; $i < count($array); $i++){ $gcd = gcd($gcd, $array[$i]); } return $gcd; } //最大公約数 function gcd($m, $n){ if(!$n)return $m; return gcd($n, $m % $n); } //配列の最小公倍数 function lcmAll($array){ $lcm = $array[0]; for($i = 1; $i < count($array); $i++){ $lcm = lcm($lcm, $array[$i]); } return $lcm; } //最小公倍数 function lcm($a, $b) { return $a / gcd($a, $b) * $b; } //ビットカウント-1の数を数える function popcount($x){ $con = 0; while ($x) { $x &= $x-1; ++$con; } return $con; }
Python
n = int(input()) a = list(map(int, input().split())) a = sorted(a)[::-1] ans = a[0] pos = 1 for i in range(1, n-1): ans += a[pos] if i%2 == 0: pos += 1 print(ans)
C++
#include<bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define rep1(i, n) for (int i = 1; i < (int)(n); i++) #define rep0c(i, n) for (int i = 1; i <= (int)(n); i++) #define rep1c(i, n) for (int i = 1; i <= (int)(n); i++) #define repc0(n, i) for (int i = (int)(n); i >= 0; i--) using namespace std; typedef long long ll; int N, K; string S; void solve() { char past = '1'; int past_count = 0; vector<int> zeros, ones; rep(i, N) { char current = S[i]; if(past != current) { if(past == '1') ones.push_back(past_count); else zeros.push_back(past_count); past = current; past_count = 0; } past_count++; } if(past == '1') ones.push_back(past_count); else { zeros.push_back(past_count); ones.push_back(0); } K = min((int)zeros.size(), K); if(K==0) { cout << ones[0] << endl; return; } int pastv = ones[K]; for(int j=0; j<K; j++) pastv += ones[j] + zeros[j]; int maxv = pastv; int ends = ((int)zeros.size())-K+1; rep1(i, ends) { pastv += ones[i+K] + zeros[i+K-1] - ones[i-1] - zeros[i-1]; maxv = max(maxv, pastv); } cout << maxv << endl; } int main() { cin >> N >> K >> S; solve(); return 0; }
No
Do these codes solve the same problem? Code 1: n = int(input()) a = list(map(int, input().split())) a = sorted(a)[::-1] ans = a[0] pos = 1 for i in range(1, n-1): ans += a[pos] if i%2 == 0: pos += 1 print(ans) Code 2: #include<bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define rep1(i, n) for (int i = 1; i < (int)(n); i++) #define rep0c(i, n) for (int i = 1; i <= (int)(n); i++) #define rep1c(i, n) for (int i = 1; i <= (int)(n); i++) #define repc0(n, i) for (int i = (int)(n); i >= 0; i--) using namespace std; typedef long long ll; int N, K; string S; void solve() { char past = '1'; int past_count = 0; vector<int> zeros, ones; rep(i, N) { char current = S[i]; if(past != current) { if(past == '1') ones.push_back(past_count); else zeros.push_back(past_count); past = current; past_count = 0; } past_count++; } if(past == '1') ones.push_back(past_count); else { zeros.push_back(past_count); ones.push_back(0); } K = min((int)zeros.size(), K); if(K==0) { cout << ones[0] << endl; return; } int pastv = ones[K]; for(int j=0; j<K; j++) pastv += ones[j] + zeros[j]; int maxv = pastv; int ends = ((int)zeros.size())-K+1; rep1(i, ends) { pastv += ones[i+K] + zeros[i+K-1] - ones[i-1] - zeros[i-1]; maxv = max(maxv, pastv); } cout << maxv << endl; } int main() { cin >> N >> K >> S; solve(); return 0; }
Python
import sys sys.setrecursionlimit(10 ** 7) read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines N, M = map(int, input().split()) if N < 2 and M < 2: print(0) exit() ans = 0 ans += N * (N - 1) // 2 ans += M * (M - 1) // 2 print(ans)
Java
import java.util.*; public class Main { public static void main(String[] args) { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); int A = sc.nextInt(); int B = sc.nextInt(); int C = sc.nextInt(); int X = sc.nextInt(); int cnt = 0; for (int i = 0; i <= A; i++) { for (int j = 0; j <= B; j++) { for (int k = 0; k <= C; k++) { int total = 500 * i + 100 * j + 50 * k; cnt = (X == total) ? cnt + 1 : cnt; } } } System.out.println(cnt); } }
No
Do these codes solve the same problem? Code 1: import sys sys.setrecursionlimit(10 ** 7) read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines N, M = map(int, input().split()) if N < 2 and M < 2: print(0) exit() ans = 0 ans += N * (N - 1) // 2 ans += M * (M - 1) // 2 print(ans) Code 2: import java.util.*; public class Main { public static void main(String[] args) { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); int A = sc.nextInt(); int B = sc.nextInt(); int C = sc.nextInt(); int X = sc.nextInt(); int cnt = 0; for (int i = 0; i <= A; i++) { for (int j = 0; j <= B; j++) { for (int k = 0; k <= C; k++) { int total = 500 * i + 100 * j + 50 * k; cnt = (X == total) ? cnt + 1 : cnt; } } } System.out.println(cnt); } }
C++
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> P; vector<int> v[100001],a; int u[100001]; int dfs(int x,int p) { if(u[x])return 1; u[x]=1; int f=0; for(int i=0;i<v[x].size();i++)if(p!=v[x][i])f|=dfs(v[x][i],x); if(f)a.push_back(x); return f; } int main() { int n,m; cin>>n>>m; int w[n]; for(int i=0;i<n;i++)cin>>w[i]; for(int i=0,x,y;i<m;i++){ cin>>x>>y; x--,y--; v[x].push_back(y); v[y].push_back(x); } dfs(0,-1); int d[n],ans=0,M=0; fill(d,d+n,-1); priority_queue<P,vector<P>,greater<P> >q; for(int i=0;i<a.size();i++){ q.push(P(0,a[i])); d[a[i]]=0; ans+=w[a[i]]; } if(q.empty())q.push(P(w[0],0)),d[0]=w[0]; while(!q.empty()) { P p=q.top();q.pop(); int x=p.second,c=p.first; if(d[x]>c)continue; for(int i=0;i<v[x].size();i++) { int y=v[x][i]; if(d[y]==-1)d[y]=d[x]+w[y],q.push(P(d[y],y)); } } for(int i=0;i<n;i++)M=max(M,d[i]); cout<<ans+M<<endl; return 0; }
C#
using System; using System.Linq; using System.Collections.Generic; using Debug = System.Diagnostics.Debug; using SB = System.Text.StringBuilder; using System.Numerics; using static System.Math; using Point = System.Numerics.Complex; using Number = System.Int64; namespace Program { public class Solver { Random rnd = new Random(0); public void Solve() { var n = ri; var m = ri; var a = Enumerate(n, x => ri); var ma = new int[n]; var G = Enumerate(n, x => new List<int>()); var deg = new int[n]; deg[0] += 1000000000; for (int i = 0; i < m; i++) { var u = ri - 1; var v = ri - 1; G[u].Add(v); G[v].Add(u); deg[u]++; deg[v]++; } var q = new Queue<int>(); for (int i = 0; i < n; i++) if (deg[i] == 1) q.Enqueue(i); while (q.Any()) { var u = q.Dequeue(); foreach (var t in G[u]) { if (deg[t] <= 1) continue; deg[t]--; ma[t] = Max(ma[t], a[u] + ma[u]); if (deg[t] == 1) q.Enqueue(t); } ma[u] = a[u] = 0; } Console.WriteLine(a.Sum() + ma.Max()); } const long INF = 1L << 60; int ri { get { return sc.Integer(); } } long rl { get { return sc.Long(); } } double rd { get { return sc.Double(); } } string rs { get { return sc.Scan(); } } public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput()); static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; } static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; } } } #region main static class Ex { static public string AsString(this IEnumerable<char> ie) { return new string(ie.ToArray()); } static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); } static public void Main() { Console.SetOut(new Program.IO.Printer(Console.OpenStandardOutput()) { AutoFlush = false }); var solver = new Program.Solver(); solver.Solve(); Console.Out.Flush(); } } #endregion #region Ex namespace Program.IO { using System.IO; using System.Text; using System.Globalization; public class Printer: StreamWriter { public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } } public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { } } public class StreamScanner { public StreamScanner(Stream stream) { str = stream; } public readonly Stream str; private readonly byte[] buf = new byte[1024]; private int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } private byte read() { if (isEof) return 0; if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } public char Char() { byte b = 0; do b = read(); while ((b < 33 || 126 < b) && !isEof); return (char)b; } public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } public string ScanLine() { var sb = new StringBuilder(); for (var b = Char(); b != '\n' && b != 0; b = (char)read()) if (b != '\r') sb.Append(b); return sb.ToString(); } public long Long() { return isEof ? long.MinValue : long.Parse(Scan()); } public int Integer() { return isEof ? int.MinValue : int.Parse(Scan()); } public double Double() { return isEof ? double.NaN : double.Parse(Scan(), CultureInfo.InvariantCulture); } } } #endregion
Yes
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; typedef pair<int,int> P; vector<int> v[100001],a; int u[100001]; int dfs(int x,int p) { if(u[x])return 1; u[x]=1; int f=0; for(int i=0;i<v[x].size();i++)if(p!=v[x][i])f|=dfs(v[x][i],x); if(f)a.push_back(x); return f; } int main() { int n,m; cin>>n>>m; int w[n]; for(int i=0;i<n;i++)cin>>w[i]; for(int i=0,x,y;i<m;i++){ cin>>x>>y; x--,y--; v[x].push_back(y); v[y].push_back(x); } dfs(0,-1); int d[n],ans=0,M=0; fill(d,d+n,-1); priority_queue<P,vector<P>,greater<P> >q; for(int i=0;i<a.size();i++){ q.push(P(0,a[i])); d[a[i]]=0; ans+=w[a[i]]; } if(q.empty())q.push(P(w[0],0)),d[0]=w[0]; while(!q.empty()) { P p=q.top();q.pop(); int x=p.second,c=p.first; if(d[x]>c)continue; for(int i=0;i<v[x].size();i++) { int y=v[x][i]; if(d[y]==-1)d[y]=d[x]+w[y],q.push(P(d[y],y)); } } for(int i=0;i<n;i++)M=max(M,d[i]); cout<<ans+M<<endl; return 0; } Code 2: using System; using System.Linq; using System.Collections.Generic; using Debug = System.Diagnostics.Debug; using SB = System.Text.StringBuilder; using System.Numerics; using static System.Math; using Point = System.Numerics.Complex; using Number = System.Int64; namespace Program { public class Solver { Random rnd = new Random(0); public void Solve() { var n = ri; var m = ri; var a = Enumerate(n, x => ri); var ma = new int[n]; var G = Enumerate(n, x => new List<int>()); var deg = new int[n]; deg[0] += 1000000000; for (int i = 0; i < m; i++) { var u = ri - 1; var v = ri - 1; G[u].Add(v); G[v].Add(u); deg[u]++; deg[v]++; } var q = new Queue<int>(); for (int i = 0; i < n; i++) if (deg[i] == 1) q.Enqueue(i); while (q.Any()) { var u = q.Dequeue(); foreach (var t in G[u]) { if (deg[t] <= 1) continue; deg[t]--; ma[t] = Max(ma[t], a[u] + ma[u]); if (deg[t] == 1) q.Enqueue(t); } ma[u] = a[u] = 0; } Console.WriteLine(a.Sum() + ma.Max()); } const long INF = 1L << 60; int ri { get { return sc.Integer(); } } long rl { get { return sc.Long(); } } double rd { get { return sc.Double(); } } string rs { get { return sc.Scan(); } } public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput()); static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; } static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; } } } #region main static class Ex { static public string AsString(this IEnumerable<char> ie) { return new string(ie.ToArray()); } static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); } static public void Main() { Console.SetOut(new Program.IO.Printer(Console.OpenStandardOutput()) { AutoFlush = false }); var solver = new Program.Solver(); solver.Solve(); Console.Out.Flush(); } } #endregion #region Ex namespace Program.IO { using System.IO; using System.Text; using System.Globalization; public class Printer: StreamWriter { public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } } public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { } } public class StreamScanner { public StreamScanner(Stream stream) { str = stream; } public readonly Stream str; private readonly byte[] buf = new byte[1024]; private int len, ptr; public bool isEof = false; public bool IsEndOfStream { get { return isEof; } } private byte read() { if (isEof) return 0; if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } } return buf[ptr++]; } public char Char() { byte b = 0; do b = read(); while ((b < 33 || 126 < b) && !isEof); return (char)b; } public string Scan() { var sb = new StringBuilder(); for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b); return sb.ToString(); } public string ScanLine() { var sb = new StringBuilder(); for (var b = Char(); b != '\n' && b != 0; b = (char)read()) if (b != '\r') sb.Append(b); return sb.ToString(); } public long Long() { return isEof ? long.MinValue : long.Parse(Scan()); } public int Integer() { return isEof ? int.MinValue : int.Parse(Scan()); } public double Double() { return isEof ? double.NaN : double.Parse(Scan(), CultureInfo.InvariantCulture); } } } #endregion
Python
a, b, c = map(int, input().split()) print("NYoe s"[a<=c<=b::2])
C++
#include<iostream> using namespace std; int main() { int n,i;cin>>n; string s;cin>>s; if(s.size()<=n){ cout<<s; } else { for(i=0;i<n;i++) { cout<<s[i]; } cout<<"..."; } }
No
Do these codes solve the same problem? Code 1: a, b, c = map(int, input().split()) print("NYoe s"[a<=c<=b::2]) Code 2: #include<iostream> using namespace std; int main() { int n,i;cin>>n; string s;cin>>s; if(s.size()<=n){ cout<<s; } else { for(i=0;i<n;i++) { cout<<s[i]; } cout<<"..."; } }
C++
#include <bits/stdc++.h> using namespace std; int main(void){ int a,b; char c; cin>>a>>b; for(int i=0;i<a+b+1;i++){ cin>>c; if(((i<a)||(i>a))&&!isdigit(c)){ cout<<"No"; return 0; } if(i==a&&c!='-'){ cout<<"No"; return 0; } } cout<<"Yes"; }
Python
from operator import itemgetter def main(): N,M = map(int, input().split()) A = [[1,int(x)] for x in input().split()] for _ in range(M): b,c = map(int, input().split()) A.append([b,c]) A.sort(key=itemgetter(1)) A.reverse() n=0 s=0 for a in A: n+=a[0] if n<=N: s+=a[1]*a[0] elif n>N: d=a[0] e=a[1] break s+=(N-n+d)*e print(s) main()
No
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; int main(void){ int a,b; char c; cin>>a>>b; for(int i=0;i<a+b+1;i++){ cin>>c; if(((i<a)||(i>a))&&!isdigit(c)){ cout<<"No"; return 0; } if(i==a&&c!='-'){ cout<<"No"; return 0; } } cout<<"Yes"; } Code 2: from operator import itemgetter def main(): N,M = map(int, input().split()) A = [[1,int(x)] for x in input().split()] for _ in range(M): b,c = map(int, input().split()) A.append([b,c]) A.sort(key=itemgetter(1)) A.reverse() n=0 s=0 for a in A: n+=a[0] if n<=N: s+=a[1]*a[0] elif n>N: d=a[0] e=a[1] break s+=(N-n+d)*e print(s) main()
C++
#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; while(cin >> a >> b >> c && (a||b||c)) { if(c==0) { if(a!=1)cout << a << " " << b << " " << 1 << " " << 0 << endl; else cout << a << " " << max(b,0) << " " << 1 << " " << min(b,0) << endl; continue; } for(int r=1; r<=a; r++) { if(a%r) continue; int p=a/r; for(int s=-10000; s<=10000; s++) { if(s==0) continue; if(c%s) continue; int q=c/s; if(p>0 && r>0 && (p>r || (p==r && q>=s))) { if(p*s+q*r==b) { cout << p << " " << q << " " << r << " " << s << endl; goto end; } } } } cout << "Impossible" << endl; end:; } return 0; }
C#
using System.Linq; using System.Collections.Generic; using System; public class P { public int x1 { get; set; } public int x2 { get; set; } } public class hello { public static void Main() { while (true) { string[] line = Console.ReadLine().Trim().Split(' '); var a = int.Parse(line[0]); var b = int.Parse(line[1]); var c = int.Parse(line[2]); if (a == 0 && b == 0 && c == 0) break; getAns(a, b, c); } } static void getAns(int a, int b, int c) { var ok = false; var ps = new P[2]; if (c == 0) { ps[0] = new P { x1 = 1, x2 = 0 }; ps[1] = new P { x1 = a, x2 = b }; ok = true; goto exit; } var ta = getDiv(a); var tc = getDiv2(c); foreach (var x in ta) foreach (var y in tc) { var p = x.x1; var r = x.x2; var q = y.x1; var s = y.x2; if (p * s + q * r == b) { ps[0] = new P { x1 = p, x2 = q }; ps[1] = new P { x1 = r, x2 = s }; ok = true; goto exit; } if (p * q + s * r == b) { ps[0] = new P { x1 = p, x2 = s }; ps[1] = new P { x1 = r, x2 = q }; ok = true; goto exit; } } exit:; if (!ok) Console.WriteLine("Impossible"); else { var prt = ps.OrderByDescending(x => x.x1).ThenByDescending(x => x.x2).ToArray(); Console.WriteLine("{0} {1} {2} {3}",prt[0].x1,prt[0].x2,prt[1].x1,prt[1].x2); } } static List<P> getDiv2(int a) { var ap = a < 0 ? -a : a; var t = new List<P>(); for (int i = 1; i * i <= ap; i++) if (ap % i == 0) { var w = ap / i; if (i <= w) if (a > 0) { t.Add(new P { x1 = i, x2 = w }); t.Add(new P { x1 = -w, x2 = -i }); } else { t.Add(new P { x1 = -i, x2 = w }); t.Add(new P { x1 = -w, x2 = i }); } } return t; } static List<P> getDiv(int a) { var t = new List<P>(); for (int i = 1; i * i <= a; i++) if (a % i == 0) { var w = a / i; if (i <= w) t.Add(new P { x1 = i, x2 = w }); } return t; } }
Yes
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; int main() { int a,b,c; while(cin >> a >> b >> c && (a||b||c)) { if(c==0) { if(a!=1)cout << a << " " << b << " " << 1 << " " << 0 << endl; else cout << a << " " << max(b,0) << " " << 1 << " " << min(b,0) << endl; continue; } for(int r=1; r<=a; r++) { if(a%r) continue; int p=a/r; for(int s=-10000; s<=10000; s++) { if(s==0) continue; if(c%s) continue; int q=c/s; if(p>0 && r>0 && (p>r || (p==r && q>=s))) { if(p*s+q*r==b) { cout << p << " " << q << " " << r << " " << s << endl; goto end; } } } } cout << "Impossible" << endl; end:; } return 0; } Code 2: using System.Linq; using System.Collections.Generic; using System; public class P { public int x1 { get; set; } public int x2 { get; set; } } public class hello { public static void Main() { while (true) { string[] line = Console.ReadLine().Trim().Split(' '); var a = int.Parse(line[0]); var b = int.Parse(line[1]); var c = int.Parse(line[2]); if (a == 0 && b == 0 && c == 0) break; getAns(a, b, c); } } static void getAns(int a, int b, int c) { var ok = false; var ps = new P[2]; if (c == 0) { ps[0] = new P { x1 = 1, x2 = 0 }; ps[1] = new P { x1 = a, x2 = b }; ok = true; goto exit; } var ta = getDiv(a); var tc = getDiv2(c); foreach (var x in ta) foreach (var y in tc) { var p = x.x1; var r = x.x2; var q = y.x1; var s = y.x2; if (p * s + q * r == b) { ps[0] = new P { x1 = p, x2 = q }; ps[1] = new P { x1 = r, x2 = s }; ok = true; goto exit; } if (p * q + s * r == b) { ps[0] = new P { x1 = p, x2 = s }; ps[1] = new P { x1 = r, x2 = q }; ok = true; goto exit; } } exit:; if (!ok) Console.WriteLine("Impossible"); else { var prt = ps.OrderByDescending(x => x.x1).ThenByDescending(x => x.x2).ToArray(); Console.WriteLine("{0} {1} {2} {3}",prt[0].x1,prt[0].x2,prt[1].x1,prt[1].x2); } } static List<P> getDiv2(int a) { var ap = a < 0 ? -a : a; var t = new List<P>(); for (int i = 1; i * i <= ap; i++) if (ap % i == 0) { var w = ap / i; if (i <= w) if (a > 0) { t.Add(new P { x1 = i, x2 = w }); t.Add(new P { x1 = -w, x2 = -i }); } else { t.Add(new P { x1 = -i, x2 = w }); t.Add(new P { x1 = -w, x2 = i }); } } return t; } static List<P> getDiv(int a) { var t = new List<P>(); for (int i = 1; i * i <= a; i++) if (a % i == 0) { var w = a / i; if (i <= w) t.Add(new P { x1 = i, x2 = w }); } return t; } }
Java
import java.io.IOException; import java.util.Scanner; public class Main { /** * Main method. */ public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); final int A = s.nextInt(); final int B = s.nextInt(); final int K = s.nextInt(); for (int i = A; i <= B; i++) { if (i < A+K || i > B-K) { System.out.println(i); } } } }
PHP
<?php $stdins = []; while($line=fgets(STDIN)){ $stdins[] = trim($line); } foreach($stdins as $stdin){ $S = $stdin; $values = explode(" ", $S); $A = $values[0]; $B = $values[1]; $K = $values[2]; for($i=$A;$i<min($A+$K, $B);$i++){ print($i."\n"); } for($i=max($B-$K+1, $i);$i<=$B;$i++){ print($i."\n"); } }
Yes
Do these codes solve the same problem? Code 1: import java.io.IOException; import java.util.Scanner; public class Main { /** * Main method. */ public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); final int A = s.nextInt(); final int B = s.nextInt(); final int K = s.nextInt(); for (int i = A; i <= B; i++) { if (i < A+K || i > B-K) { System.out.println(i); } } } } Code 2: <?php $stdins = []; while($line=fgets(STDIN)){ $stdins[] = trim($line); } foreach($stdins as $stdin){ $S = $stdin; $values = explode(" ", $S); $A = $values[0]; $B = $values[1]; $K = $values[2]; for($i=$A;$i<min($A+$K, $B);$i++){ print($i."\n"); } for($i=max($B-$K+1, $i);$i<=$B;$i++){ print($i."\n"); } }
Python
import math a, b, x = [int(x) for x in input().split()] L = x/a if(2*L/a < b): print(math.atan(b**2/(2*L))*180/math.pi) else: t = 2*L/a - b print(math.atan((b-t)/a)*180/math.pi)
C++
#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <string> #include <cstdio> #include <climits> #include <set> using namespace std; int main() { long long a, b, x; cin >> a >> b >> x; long long ans = b / x - a / x; if((a % x) == 0) ans++; cout << ans << endl; return 0; }
No
Do these codes solve the same problem? Code 1: import math a, b, x = [int(x) for x in input().split()] L = x/a if(2*L/a < b): print(math.atan(b**2/(2*L))*180/math.pi) else: t = 2*L/a - b print(math.atan((b-t)/a)*180/math.pi) Code 2: #include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <string> #include <cstdio> #include <climits> #include <set> using namespace std; int main() { long long a, b, x; cin >> a >> b >> x; long long ans = b / x - a / x; if((a % x) == 0) ans++; cout << ans << endl; return 0; }
C++
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; if(n%2 == 0) { cout << n << endl; }else{ cout << 2*n << endl; } }
Python
S = input() ans = 700 for i in S: if i == 'o': ans += 100 print(ans)
No
Do these codes solve the same problem? Code 1: #include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; if(n%2 == 0) { cout << n << endl; }else{ cout << 2*n << endl; } } Code 2: S = input() ans = 700 for i in S: if i == 'o': ans += 100 print(ans)
Java
import java.util.Scanner; public class Main{ static final double EPS = 0.00000000001; static final int COUNTER_CLOCKWISE = 1; static final int CLOCKWISE = -1; static final int ONLINE_BACK = 2; static final int ONLINE_FRONT = -2; static final int ON_SEGMENT = 0; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int q = scan.nextInt(); for(int i = 0; i < q; i++) { int[]p0 = new int[2]; int[]p1 = new int[2]; int[]p2 = new int[2]; int[]p3 = new int[2]; p0[0] = scan.nextInt(); p0[1] = scan.nextInt(); p1[0] = scan.nextInt(); p1[1] = scan.nextInt(); p2[0] = scan.nextInt(); p2[1] = scan.nextInt(); p3[0] = scan.nextInt(); p3[1] = scan.nextInt(); if(intersect(p0, p1, p2, p3)) { System.out.println(1); }else { System.out.println(0); } } scan.close(); } static boolean intersect(int[]p1, int[]p2, int[]p3, int[]p4) { if(ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 && ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0) { return true; }else { return false; } } static int ccw(int[]p0, int[]p1, int[]p2) { int[]a = {p1[0] - p0[0], p1[1] - p0[1]}; int[]b = {p2[0] - p0[0], p2[1] - p0[1]}; if(cross(a, b) > EPS) return COUNTER_CLOCKWISE; if(cross(a, b) < -EPS) return CLOCKWISE; if(dot(a, b) < -EPS) return ONLINE_BACK; if(norm(a) < norm(b)) return ONLINE_FRONT; return ON_SEGMENT; } static int norm(int[]p) { return p[0] * p[0] + p[1] * p[1]; } static int[] vec(int[]p1, int[]p2) { int[]u = {p2[0] - p1[0], p2[1] - p1[1]}; return u; } static int dot(int[]u, int[]v) { return u[0] * v[0] + u[1] * v[1]; } static int cross(int[]u, int[]v) { return u[0] * v[1] - u[1] * v[0]; } }
Go
package main import ( "bufio" "fmt" "os" "strconv" ) var scanner = bufio.NewScanner(os.Stdin) func nextString() string { scanner.Scan() return scanner.Text() } func nextInt() int { n, err := strconv.Atoi(nextString()) if err != nil { fmt.Printf("strconv.Atoi failed: %v\n", err) } return n } func nextFloat64() (float64, error) { return strconv.ParseFloat(nextString(), 64) } func min(x, y float64) float64 { if x < y { return x } return y } func max(x, y float64) float64 { if x > y { return x } return y } type Point struct { x float64 y float64 } func sub(l, r *Point) *Point { s := Point{ x: l.x - r.x, y: l.y - r.y, } return &s } func crossProd(l, r *Point) float64 { return l.x*r.y - r.x*l.y } func direction(pi, pj, pk *Point) float64 { return crossProd(sub(pk, pi), sub(pj, pi)) } func readPoint() *Point { x, _ := nextFloat64() y, _ := nextFloat64() point := Point{ x: x, y: y, } return &point } func onSegment(pi, pj, pk *Point) bool { return min(pi.x, pj.x) <= pk.x && pk.x <= max(pi.x, pj.x) && min(pi.y, pj.y) <= pk.y && pk.y <= max(pi.y, pj.y) } func segmentsIntersect(p1, p2, p3, p4 *Point) bool { d1 := direction(p3, p4, p1) d2 := direction(p3, p4, p2) d3 := direction(p1, p2, p3) d4 := direction(p1, p2, p4) // fmt.Println(d1, d2, d3, d4) if ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || d3 < 0 && d4 > 0) { return true } else if d1 == 0 && onSegment(p3, p4, p1) { return true } else if d2 == 0 && onSegment(p3, p4, p2) { return true } else if d3 == 0 && onSegment(p1, p2, p3) { return true } else if d4 == 0 && onSegment(p1, p2, p4) { return true } return false } func main() { scanner.Split(bufio.ScanWords) nQueries := nextInt() for iQuery := 0; iQuery < nQueries; iQuery++ { p0 := readPoint() p1 := readPoint() p2 := readPoint() p3 := readPoint() if segmentsIntersect(p0, p1, p2, p3) { fmt.Println(1) } else { fmt.Println(0) } } }
Yes
Do these codes solve the same problem? Code 1: import java.util.Scanner; public class Main{ static final double EPS = 0.00000000001; static final int COUNTER_CLOCKWISE = 1; static final int CLOCKWISE = -1; static final int ONLINE_BACK = 2; static final int ONLINE_FRONT = -2; static final int ON_SEGMENT = 0; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int q = scan.nextInt(); for(int i = 0; i < q; i++) { int[]p0 = new int[2]; int[]p1 = new int[2]; int[]p2 = new int[2]; int[]p3 = new int[2]; p0[0] = scan.nextInt(); p0[1] = scan.nextInt(); p1[0] = scan.nextInt(); p1[1] = scan.nextInt(); p2[0] = scan.nextInt(); p2[1] = scan.nextInt(); p3[0] = scan.nextInt(); p3[1] = scan.nextInt(); if(intersect(p0, p1, p2, p3)) { System.out.println(1); }else { System.out.println(0); } } scan.close(); } static boolean intersect(int[]p1, int[]p2, int[]p3, int[]p4) { if(ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 && ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0) { return true; }else { return false; } } static int ccw(int[]p0, int[]p1, int[]p2) { int[]a = {p1[0] - p0[0], p1[1] - p0[1]}; int[]b = {p2[0] - p0[0], p2[1] - p0[1]}; if(cross(a, b) > EPS) return COUNTER_CLOCKWISE; if(cross(a, b) < -EPS) return CLOCKWISE; if(dot(a, b) < -EPS) return ONLINE_BACK; if(norm(a) < norm(b)) return ONLINE_FRONT; return ON_SEGMENT; } static int norm(int[]p) { return p[0] * p[0] + p[1] * p[1]; } static int[] vec(int[]p1, int[]p2) { int[]u = {p2[0] - p1[0], p2[1] - p1[1]}; return u; } static int dot(int[]u, int[]v) { return u[0] * v[0] + u[1] * v[1]; } static int cross(int[]u, int[]v) { return u[0] * v[1] - u[1] * v[0]; } } Code 2: package main import ( "bufio" "fmt" "os" "strconv" ) var scanner = bufio.NewScanner(os.Stdin) func nextString() string { scanner.Scan() return scanner.Text() } func nextInt() int { n, err := strconv.Atoi(nextString()) if err != nil { fmt.Printf("strconv.Atoi failed: %v\n", err) } return n } func nextFloat64() (float64, error) { return strconv.ParseFloat(nextString(), 64) } func min(x, y float64) float64 { if x < y { return x } return y } func max(x, y float64) float64 { if x > y { return x } return y } type Point struct { x float64 y float64 } func sub(l, r *Point) *Point { s := Point{ x: l.x - r.x, y: l.y - r.y, } return &s } func crossProd(l, r *Point) float64 { return l.x*r.y - r.x*l.y } func direction(pi, pj, pk *Point) float64 { return crossProd(sub(pk, pi), sub(pj, pi)) } func readPoint() *Point { x, _ := nextFloat64() y, _ := nextFloat64() point := Point{ x: x, y: y, } return &point } func onSegment(pi, pj, pk *Point) bool { return min(pi.x, pj.x) <= pk.x && pk.x <= max(pi.x, pj.x) && min(pi.y, pj.y) <= pk.y && pk.y <= max(pi.y, pj.y) } func segmentsIntersect(p1, p2, p3, p4 *Point) bool { d1 := direction(p3, p4, p1) d2 := direction(p3, p4, p2) d3 := direction(p1, p2, p3) d4 := direction(p1, p2, p4) // fmt.Println(d1, d2, d3, d4) if ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || d3 < 0 && d4 > 0) { return true } else if d1 == 0 && onSegment(p3, p4, p1) { return true } else if d2 == 0 && onSegment(p3, p4, p2) { return true } else if d3 == 0 && onSegment(p1, p2, p3) { return true } else if d4 == 0 && onSegment(p1, p2, p4) { return true } return false } func main() { scanner.Split(bufio.ScanWords) nQueries := nextInt() for iQuery := 0; iQuery < nQueries; iQuery++ { p0 := readPoint() p1 := readPoint() p2 := readPoint() p3 := readPoint() if segmentsIntersect(p0, p1, p2, p3) { fmt.Println(1) } else { fmt.Println(0) } } }
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.IO; using System.Text; using System.Diagnostics; using static util; using P = pair<int, int>; using Binary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.BinaryExpression>; using Unary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.UnaryExpression>; class Program { static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; static Scan sc = new Scan(); const int M = 1000000007; // const int M = 998244353; const long LM = (long)1e18; const double eps = 1e-11; static readonly int[] dd = { 0, 1, 0, -1, 0 }; static void Main() { var s = sc.Str; int n = s.Length; var ind = new List<int>[26]; for (int i = 0; i < 26; i++) { ind[i] = new List<int>(); } var bit = new BIT(n); for (int i = 0; i < n; i++) { ind[s[i] - 'a'].Add(i); bit.add(i, 1); } int oc = 0; var l = new int[26]; var r = new int[26]; for (int i = 0; i < 26; i++) { r[i] = ind[i].Count - 1; if (ind[i].Count % 2 == 1) ++oc; } if (oc > 1) { DBG(-1); return; } long sum = 0; while (true) { int min = M, minid = -1; for (int i = 0; i < 26; i++) { if (l[i] >= r[i]) continue; int cos = (int)(bit.sum(ind[i][l[i]]) + bit.sum(ind[i][r[i]] + 1, n)); if (cos < min) { min = cos; minid = i; } } if (min == M) break; sum += min; bit.add(ind[minid][l[minid]], -1); bit.add(ind[minid][r[minid]], -1); ++l[minid]; --r[minid]; } Prt(sum); sw.Flush(); } static void DBG(string a) => Console.WriteLine(a); static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a)); static void DBG(params object[] a) => DBG(string.Join(" ", a)); static void Prt(string a) => sw.WriteLine(a); static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a)); static void Prt(params object[] a) => Prt(string.Join(" ", a)); } class pair<T, U> : IComparable<pair<T, U>> where T : IComparable<T> where U : IComparable<U> { public T v1; public U v2; public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; } public int CompareTo(pair<T, U> a) => v1.CompareTo(a.v1) != 0 ? v1.CompareTo(a.v1) : v2.CompareTo(a.v2); public override string ToString() => v1 + " " + v2; } static class util { public static pair<T, T> make_pair<T>(this IList<T> l) where T : IComparable<T> => make_pair(l[0], l[1]); public static pair<T, U> make_pair<T, U>(T v1, U v2) where T : IComparable<T> where U : IComparable<U> => new pair<T, U>(v1, v2); public static T sqr<T>(T a) => Operator<T>.Multiply(a, a); public static T Max<T>(params T[] a) => a.Max(); public static T Min<T>(params T[] a) => a.Min(); public static void swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } public static void swap<T>(this IList<T> a, int i, int j) { var t = a[i]; a[i] = a[j]; a[j] = t; } public static T[] copy<T>(this IList<T> a) { var ret = new T[a.Count]; for (int i = 0; i < a.Count; i++) ret[i] = a[i]; return ret; } } static class Operator<T> { static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x"); static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y"); public static readonly Func<T, T, T> Add = Lambda(Expression.Add); public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract); public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply); public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide); public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus); public static readonly Func<T, T> Negate = Lambda(Expression.Negate); public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile(); public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile(); } class Scan { public int Int => int.Parse(Str); public long Long => long.Parse(Str); public double Double => double.Parse(Str); public string Str => Console.ReadLine().Trim(); public pair<T, U> Pair<T, U>() where T : IComparable<T> where U : IComparable<U> { T a; U b; Multi(out a, out b); return make_pair(a, b); } public int[] IntArr => StrArr.Select(int.Parse).ToArray(); public long[] LongArr => StrArr.Select(long.Parse).ToArray(); public double[] DoubleArr => StrArr.Select(double.Parse).ToArray(); public string[] StrArr => Str.Split(new []{' '}, System.StringSplitOptions.RemoveEmptyEntries); bool eq<T, U>() => typeof(T).Equals(typeof(U)); T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T)); T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s)) : eq<T, long>() ? ct<T, long>(long.Parse(s)) : eq<T, double>() ? ct<T, double>(double.Parse(s)) : eq<T, char>() ? ct<T, char>(s[0]) : ct<T, string>(s); public void Multi<T>(out T a) => a = cv<T>(Str); public void Multi<T, U>(out T a, out U b) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); } public void Multi<T, U, V>(out T a, out U b, out V c) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); } public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); } public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); } public void Multi<T, U, V, W, X, Y>(out T a, out U b, out V c, out W d, out X e, out Y f) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); f = cv<Y>(ar[5]); } } static class mymath { public static long Mod = 1000000007; public static bool isprime(long a) { if (a < 2) return false; for (long i = 2; i * i <= a; i++) if (a % i == 0) return false; return true; } public static bool[] sieve(int n) { var p = new bool[n + 1]; for (int i = 2; i <= n; i++) p[i] = true; for (int i = 2; i * i <= n; i++) if (p[i]) for (int j = i * i; j <= n; j += i) p[j] = false; return p; } public static List<int> getprimes(int n) { var prs = new List<int>(); var p = sieve(n); for (int i = 2; i <= n; i++) if (p[i]) prs.Add(i); return prs; } public static long[][] E(int n) { var ret = new long[n][]; for (int i = 0; i < n; i++) { ret[i] = new long[n]; ret[i][i] = 1; } return ret; } public static double[][] dE(int n) { var ret = new double[n][]; for (int i = 0; i < n; i++) { ret[i] = new double[n]; ret[i][i] = 1; } return ret; } public static long[][] pow(long[][] A, long n) { if (n == 0) return E(A.Length); var t = pow(A, n / 2); if ((n & 1) == 0) return mul(t, t); return mul(mul(t, t), A); } public static double[][] pow(double[][] A, long n) { if (n == 0) return dE(A.Length); var t = pow(A, n / 2); if ((n & 1) == 0) return mul(t, t); return mul(mul(t, t), A); } public static double dot(double[] x, double[] y) { int n = x.Length; double ret = 0; for (int i = 0; i < n; i++) ret += x[i] * y[i]; return ret; } public static double _dot(double[] x, double[] y) { int n = x.Length; double ret = 0, r = 0; for (int i = 0; i < n; i++) { double s = ret + (x[i] * y[i] + r); r = (x[i] * y[i] + r) - (s - ret); ret = s; } return ret; } public static long dot(long[] x, long[] y) { int n = x.Length; long ret = 0; for (int i = 0; i < n; i++) ret = (ret + x[i] * y[i]) % Mod; return ret; } public static T[][] trans<T>(T[][] A) { int n = A[0].Length, m = A.Length; var ret = new T[n][]; for (int i = 0; i < n; i++) { ret[i] = new T[m]; for (int j = 0; j < m; j++) ret[i][j] = A[j][i]; } return ret; } public static double[] mul(double a, double[] x) { int n = x.Length; var ret = new double[n]; for (int i = 0; i < n; i++) ret[i] = a * x[i]; return ret; } public static long[] mul(long a, long[] x) { int n = x.Length; var ret = new long[n]; for (int i = 0; i < n; i++) ret[i] = a * x[i] % Mod; return ret; } public static double[] mul(double[][] A, double[] x) { int n = A.Length; var ret = new double[n]; for (int i = 0; i < n; i++) ret[i] = dot(x, A[i]); return ret; } public static long[] mul(long[][] A, long[] x) { int n = A.Length; var ret = new long[n]; for (int i = 0; i < n; i++) ret[i] = dot(x, A[i]); return ret; } public static double[][] mul(double a, double[][] A) { int n = A.Length; var ret = new double[n][]; for (int i = 0; i < n; i++) ret[i] = mul(a, A[i]); return ret; } public static long[][] mul(long a, long[][] A) { int n = A.Length; var ret = new long[n][]; for (int i = 0; i < n; i++) ret[i] = mul(a, A[i]); return ret; } public static double[][] mul(double[][] A, double[][] B) { int n = A.Length; var Bt = trans(B); var ret = new double[n][]; for (int i = 0; i < n; i++) ret[i] = mul(Bt, A[i]); return ret; } public static long[][] mul(long[][] A, long[][] B) { int n = A.Length; var Bt = trans(B); var ret = new long[n][]; for (int i = 0; i < n; i++) ret[i] = mul(Bt, A[i]); return ret; } public static long[] add(long[] x, long[] y) { int n = x.Length; var ret = new long[n]; for (int i = 0; i < n; i++) ret[i] = (x[i] + y[i]) % Mod; return ret; } public static long[][] add(long[][] A, long[][] B) { int n = A.Length; var ret = new long[n][]; for (int i = 0; i < n; i++) ret[i] = add(A[i], B[i]); return ret; } public static long pow(long a, long b) { if (a >= Mod) return pow(a % Mod, b); if (a == 0) return 0; if (b == 0) return 1; var t = pow(a, b / 2); if ((b & 1) == 0) return t * t % Mod; return t * t % Mod * a % Mod; } public static long inv(long a) => pow(a, Mod - 2); public static long gcd(long a, long b) { while (b > 0) { var t = a % b; a = b; b = t; } return a; } // a x + b y = gcd(a, b) public static long extgcd(long a, long b, out long x, out long y) { long g = a; x = 1; y = 0; if (b > 0) { g = extgcd(b, a % b, out y, out x); y -= a / b * x; } return g; } public static long lcm(long a, long b) => a / gcd(a, b) * b; static long[] facts; public static long[] setfacts(int n) { facts = new long[n + 1]; facts[0] = 1; for (int i = 0; i < n; i++) facts[i + 1] = facts[i] * (i + 1) % Mod; return facts; } public static long comb(int n, int r) { if (n < 0 || r < 0 || r > n) return 0; if (n - r < r) r = n - r; if (r == 0) return 1; if (r == 1) return n; if (facts != null && facts.Length > n) return facts[n] * inv(facts[r]) % Mod * inv(facts[n - r]) % Mod; int[] numer = new int[r], denom = new int[r]; for (int k = 0; k < r; k++) { numer[k] = n - r + k + 1; denom[k] = k + 1; } for (int p = 2; p <= r; p++) { int piv = denom[p - 1]; if (piv > 1) { int ofst = (n - r) % p; for (int k = p - 1; k < r; k += p) { numer[k - ofst] /= piv; denom[k] /= piv; } } } long ret = 1; for (int k = 0; k < r; k++) if (numer[k] > 1) ret = ret * numer[k] % Mod; return ret; } public static long[][] getcombs(int n) { var ret = new long[n + 1][]; for (int i = 0; i <= n; i++) { ret[i] = new long[i + 1]; ret[i][0] = ret[i][i] = 1; for (int j = 1; j < i; j++) ret[i][j] = (ret[i - 1][j - 1] + ret[i - 1][j]) % Mod; } return ret; } // nC0, nC2, ..., nCn public static long[] getcomb(int n) { var ret = new long[n + 1]; ret[0] = 1; for (int i = 0; i < n; i++) ret[i + 1] = ret[i] * (n - i) % Mod * inv(i + 1) % Mod; return ret; } } class BIT { int n; long[] bit; public BIT(int n) { this.n = n; bit = new long[n]; } public void add(int j, long w) { for (int i = j; i < n; i |= i + 1) bit[i] += w; } public long at(int j) => sum(j, j + 1); // [0, j) public long sum(int j) { long ret = 0; for (int i = j - 1; i >= 0; i = (i & i + 1) - 1) ret += bit[i]; return ret; } // [j, k) public long sum(int j, int k) => sum(k) - sum(j); }
Go
package main import "fmt" func main() { var s string fmt.Scan(&s) n := len(s) y := map[string]int{} for i:=0;i<n;i++ { y[s[i:i+1]]++ } x := "" for k,v := range y { if v%2 == 1 { if x == "" { x = k;continue } fmt.Println(-1);return } } t := "" z := map[string]int{} w := make(map[string][]int) for i:=0;i<n;i++ { z[s[i:i+1]]++ if s[i:i+1] == x && z[s[i:i+1]] < (y[s[i:i+1]]+1)/2 || s[i:i+1] != x && z[s[i:i+1]] <= y[s[i:i+1]]/2 { t += s[i:i+1] } w[s[i:i+1]] = append(w[s[i:i+1]],i) } t = t+x+reverse(t) bit := NewFenwickTree(n) a := make([]int,n) z = map[string]int{} for i:=0;i<n;i++ { a[i] = w[t[i:i+1]][z[t[i:i+1]]]+1 z[t[i:i+1]]++ } m := int64(0) for i:=0;i<n;i++ { m += int64(i)-bit.Sum(a[i]) bit.Add(a[i],1) } fmt.Println(m) } func reverse(s string) string { n,r := len(s),[]rune(s) for i:=0;i<n-i;i++ { r[i],r[n-i-1] = r[n-i-1],r[i] } return string(r) } type FenwickTree struct { bit []int64 } func NewFenwickTree(n int) FenwickTree { return FenwickTree{make([]int64,n)} } func(b FenwickTree) Add(i int,v int64) { for x:=i;x<=len(b.bit);x+=x&-x { b.bit[x-1] += v } } func(b FenwickTree) Sum(i int) int64 { r := int64(0) for x:=i;x>0;x-=x&-x { r += b.bit[x-1] } return r } func(b FenwickTree) Update(i int,v int64) { for x:=i;x<=len(b.bit);x+=x&-x { if b.bit[x-1] < v { b.bit[x-1] = v } } } func(b FenwickTree) Max(i int) int64 { r := int64(0) for x:=i;x>0;x-=x&-x { if r < b.bit[x-1] { r = b.bit[x-1] } } return r }
Yes
Do these codes solve the same problem? Code 1: using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.IO; using System.Text; using System.Diagnostics; using static util; using P = pair<int, int>; using Binary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.BinaryExpression>; using Unary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.UnaryExpression>; class Program { static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; static Scan sc = new Scan(); const int M = 1000000007; // const int M = 998244353; const long LM = (long)1e18; const double eps = 1e-11; static readonly int[] dd = { 0, 1, 0, -1, 0 }; static void Main() { var s = sc.Str; int n = s.Length; var ind = new List<int>[26]; for (int i = 0; i < 26; i++) { ind[i] = new List<int>(); } var bit = new BIT(n); for (int i = 0; i < n; i++) { ind[s[i] - 'a'].Add(i); bit.add(i, 1); } int oc = 0; var l = new int[26]; var r = new int[26]; for (int i = 0; i < 26; i++) { r[i] = ind[i].Count - 1; if (ind[i].Count % 2 == 1) ++oc; } if (oc > 1) { DBG(-1); return; } long sum = 0; while (true) { int min = M, minid = -1; for (int i = 0; i < 26; i++) { if (l[i] >= r[i]) continue; int cos = (int)(bit.sum(ind[i][l[i]]) + bit.sum(ind[i][r[i]] + 1, n)); if (cos < min) { min = cos; minid = i; } } if (min == M) break; sum += min; bit.add(ind[minid][l[minid]], -1); bit.add(ind[minid][r[minid]], -1); ++l[minid]; --r[minid]; } Prt(sum); sw.Flush(); } static void DBG(string a) => Console.WriteLine(a); static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a)); static void DBG(params object[] a) => DBG(string.Join(" ", a)); static void Prt(string a) => sw.WriteLine(a); static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a)); static void Prt(params object[] a) => Prt(string.Join(" ", a)); } class pair<T, U> : IComparable<pair<T, U>> where T : IComparable<T> where U : IComparable<U> { public T v1; public U v2; public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; } public int CompareTo(pair<T, U> a) => v1.CompareTo(a.v1) != 0 ? v1.CompareTo(a.v1) : v2.CompareTo(a.v2); public override string ToString() => v1 + " " + v2; } static class util { public static pair<T, T> make_pair<T>(this IList<T> l) where T : IComparable<T> => make_pair(l[0], l[1]); public static pair<T, U> make_pair<T, U>(T v1, U v2) where T : IComparable<T> where U : IComparable<U> => new pair<T, U>(v1, v2); public static T sqr<T>(T a) => Operator<T>.Multiply(a, a); public static T Max<T>(params T[] a) => a.Max(); public static T Min<T>(params T[] a) => a.Min(); public static void swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } public static void swap<T>(this IList<T> a, int i, int j) { var t = a[i]; a[i] = a[j]; a[j] = t; } public static T[] copy<T>(this IList<T> a) { var ret = new T[a.Count]; for (int i = 0; i < a.Count; i++) ret[i] = a[i]; return ret; } } static class Operator<T> { static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x"); static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y"); public static readonly Func<T, T, T> Add = Lambda(Expression.Add); public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract); public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply); public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide); public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus); public static readonly Func<T, T> Negate = Lambda(Expression.Negate); public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile(); public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile(); } class Scan { public int Int => int.Parse(Str); public long Long => long.Parse(Str); public double Double => double.Parse(Str); public string Str => Console.ReadLine().Trim(); public pair<T, U> Pair<T, U>() where T : IComparable<T> where U : IComparable<U> { T a; U b; Multi(out a, out b); return make_pair(a, b); } public int[] IntArr => StrArr.Select(int.Parse).ToArray(); public long[] LongArr => StrArr.Select(long.Parse).ToArray(); public double[] DoubleArr => StrArr.Select(double.Parse).ToArray(); public string[] StrArr => Str.Split(new []{' '}, System.StringSplitOptions.RemoveEmptyEntries); bool eq<T, U>() => typeof(T).Equals(typeof(U)); T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T)); T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s)) : eq<T, long>() ? ct<T, long>(long.Parse(s)) : eq<T, double>() ? ct<T, double>(double.Parse(s)) : eq<T, char>() ? ct<T, char>(s[0]) : ct<T, string>(s); public void Multi<T>(out T a) => a = cv<T>(Str); public void Multi<T, U>(out T a, out U b) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); } public void Multi<T, U, V>(out T a, out U b, out V c) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); } public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); } public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); } public void Multi<T, U, V, W, X, Y>(out T a, out U b, out V c, out W d, out X e, out Y f) { var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); f = cv<Y>(ar[5]); } } static class mymath { public static long Mod = 1000000007; public static bool isprime(long a) { if (a < 2) return false; for (long i = 2; i * i <= a; i++) if (a % i == 0) return false; return true; } public static bool[] sieve(int n) { var p = new bool[n + 1]; for (int i = 2; i <= n; i++) p[i] = true; for (int i = 2; i * i <= n; i++) if (p[i]) for (int j = i * i; j <= n; j += i) p[j] = false; return p; } public static List<int> getprimes(int n) { var prs = new List<int>(); var p = sieve(n); for (int i = 2; i <= n; i++) if (p[i]) prs.Add(i); return prs; } public static long[][] E(int n) { var ret = new long[n][]; for (int i = 0; i < n; i++) { ret[i] = new long[n]; ret[i][i] = 1; } return ret; } public static double[][] dE(int n) { var ret = new double[n][]; for (int i = 0; i < n; i++) { ret[i] = new double[n]; ret[i][i] = 1; } return ret; } public static long[][] pow(long[][] A, long n) { if (n == 0) return E(A.Length); var t = pow(A, n / 2); if ((n & 1) == 0) return mul(t, t); return mul(mul(t, t), A); } public static double[][] pow(double[][] A, long n) { if (n == 0) return dE(A.Length); var t = pow(A, n / 2); if ((n & 1) == 0) return mul(t, t); return mul(mul(t, t), A); } public static double dot(double[] x, double[] y) { int n = x.Length; double ret = 0; for (int i = 0; i < n; i++) ret += x[i] * y[i]; return ret; } public static double _dot(double[] x, double[] y) { int n = x.Length; double ret = 0, r = 0; for (int i = 0; i < n; i++) { double s = ret + (x[i] * y[i] + r); r = (x[i] * y[i] + r) - (s - ret); ret = s; } return ret; } public static long dot(long[] x, long[] y) { int n = x.Length; long ret = 0; for (int i = 0; i < n; i++) ret = (ret + x[i] * y[i]) % Mod; return ret; } public static T[][] trans<T>(T[][] A) { int n = A[0].Length, m = A.Length; var ret = new T[n][]; for (int i = 0; i < n; i++) { ret[i] = new T[m]; for (int j = 0; j < m; j++) ret[i][j] = A[j][i]; } return ret; } public static double[] mul(double a, double[] x) { int n = x.Length; var ret = new double[n]; for (int i = 0; i < n; i++) ret[i] = a * x[i]; return ret; } public static long[] mul(long a, long[] x) { int n = x.Length; var ret = new long[n]; for (int i = 0; i < n; i++) ret[i] = a * x[i] % Mod; return ret; } public static double[] mul(double[][] A, double[] x) { int n = A.Length; var ret = new double[n]; for (int i = 0; i < n; i++) ret[i] = dot(x, A[i]); return ret; } public static long[] mul(long[][] A, long[] x) { int n = A.Length; var ret = new long[n]; for (int i = 0; i < n; i++) ret[i] = dot(x, A[i]); return ret; } public static double[][] mul(double a, double[][] A) { int n = A.Length; var ret = new double[n][]; for (int i = 0; i < n; i++) ret[i] = mul(a, A[i]); return ret; } public static long[][] mul(long a, long[][] A) { int n = A.Length; var ret = new long[n][]; for (int i = 0; i < n; i++) ret[i] = mul(a, A[i]); return ret; } public static double[][] mul(double[][] A, double[][] B) { int n = A.Length; var Bt = trans(B); var ret = new double[n][]; for (int i = 0; i < n; i++) ret[i] = mul(Bt, A[i]); return ret; } public static long[][] mul(long[][] A, long[][] B) { int n = A.Length; var Bt = trans(B); var ret = new long[n][]; for (int i = 0; i < n; i++) ret[i] = mul(Bt, A[i]); return ret; } public static long[] add(long[] x, long[] y) { int n = x.Length; var ret = new long[n]; for (int i = 0; i < n; i++) ret[i] = (x[i] + y[i]) % Mod; return ret; } public static long[][] add(long[][] A, long[][] B) { int n = A.Length; var ret = new long[n][]; for (int i = 0; i < n; i++) ret[i] = add(A[i], B[i]); return ret; } public static long pow(long a, long b) { if (a >= Mod) return pow(a % Mod, b); if (a == 0) return 0; if (b == 0) return 1; var t = pow(a, b / 2); if ((b & 1) == 0) return t * t % Mod; return t * t % Mod * a % Mod; } public static long inv(long a) => pow(a, Mod - 2); public static long gcd(long a, long b) { while (b > 0) { var t = a % b; a = b; b = t; } return a; } // a x + b y = gcd(a, b) public static long extgcd(long a, long b, out long x, out long y) { long g = a; x = 1; y = 0; if (b > 0) { g = extgcd(b, a % b, out y, out x); y -= a / b * x; } return g; } public static long lcm(long a, long b) => a / gcd(a, b) * b; static long[] facts; public static long[] setfacts(int n) { facts = new long[n + 1]; facts[0] = 1; for (int i = 0; i < n; i++) facts[i + 1] = facts[i] * (i + 1) % Mod; return facts; } public static long comb(int n, int r) { if (n < 0 || r < 0 || r > n) return 0; if (n - r < r) r = n - r; if (r == 0) return 1; if (r == 1) return n; if (facts != null && facts.Length > n) return facts[n] * inv(facts[r]) % Mod * inv(facts[n - r]) % Mod; int[] numer = new int[r], denom = new int[r]; for (int k = 0; k < r; k++) { numer[k] = n - r + k + 1; denom[k] = k + 1; } for (int p = 2; p <= r; p++) { int piv = denom[p - 1]; if (piv > 1) { int ofst = (n - r) % p; for (int k = p - 1; k < r; k += p) { numer[k - ofst] /= piv; denom[k] /= piv; } } } long ret = 1; for (int k = 0; k < r; k++) if (numer[k] > 1) ret = ret * numer[k] % Mod; return ret; } public static long[][] getcombs(int n) { var ret = new long[n + 1][]; for (int i = 0; i <= n; i++) { ret[i] = new long[i + 1]; ret[i][0] = ret[i][i] = 1; for (int j = 1; j < i; j++) ret[i][j] = (ret[i - 1][j - 1] + ret[i - 1][j]) % Mod; } return ret; } // nC0, nC2, ..., nCn public static long[] getcomb(int n) { var ret = new long[n + 1]; ret[0] = 1; for (int i = 0; i < n; i++) ret[i + 1] = ret[i] * (n - i) % Mod * inv(i + 1) % Mod; return ret; } } class BIT { int n; long[] bit; public BIT(int n) { this.n = n; bit = new long[n]; } public void add(int j, long w) { for (int i = j; i < n; i |= i + 1) bit[i] += w; } public long at(int j) => sum(j, j + 1); // [0, j) public long sum(int j) { long ret = 0; for (int i = j - 1; i >= 0; i = (i & i + 1) - 1) ret += bit[i]; return ret; } // [j, k) public long sum(int j, int k) => sum(k) - sum(j); } Code 2: package main import "fmt" func main() { var s string fmt.Scan(&s) n := len(s) y := map[string]int{} for i:=0;i<n;i++ { y[s[i:i+1]]++ } x := "" for k,v := range y { if v%2 == 1 { if x == "" { x = k;continue } fmt.Println(-1);return } } t := "" z := map[string]int{} w := make(map[string][]int) for i:=0;i<n;i++ { z[s[i:i+1]]++ if s[i:i+1] == x && z[s[i:i+1]] < (y[s[i:i+1]]+1)/2 || s[i:i+1] != x && z[s[i:i+1]] <= y[s[i:i+1]]/2 { t += s[i:i+1] } w[s[i:i+1]] = append(w[s[i:i+1]],i) } t = t+x+reverse(t) bit := NewFenwickTree(n) a := make([]int,n) z = map[string]int{} for i:=0;i<n;i++ { a[i] = w[t[i:i+1]][z[t[i:i+1]]]+1 z[t[i:i+1]]++ } m := int64(0) for i:=0;i<n;i++ { m += int64(i)-bit.Sum(a[i]) bit.Add(a[i],1) } fmt.Println(m) } func reverse(s string) string { n,r := len(s),[]rune(s) for i:=0;i<n-i;i++ { r[i],r[n-i-1] = r[n-i-1],r[i] } return string(r) } type FenwickTree struct { bit []int64 } func NewFenwickTree(n int) FenwickTree { return FenwickTree{make([]int64,n)} } func(b FenwickTree) Add(i int,v int64) { for x:=i;x<=len(b.bit);x+=x&-x { b.bit[x-1] += v } } func(b FenwickTree) Sum(i int) int64 { r := int64(0) for x:=i;x>0;x-=x&-x { r += b.bit[x-1] } return r } func(b FenwickTree) Update(i int,v int64) { for x:=i;x<=len(b.bit);x+=x&-x { if b.bit[x-1] < v { b.bit[x-1] = v } } } func(b FenwickTree) Max(i int) int64 { r := int64(0) for x:=i;x>0;x-=x&-x { if r < b.bit[x-1] { r = b.bit[x-1] } } return r }
Java
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int e = sc.nextInt(); int ans = 0; if(a < 0) { ans += -a * c; ans += d; ans += e * b; }else { ans += e * (b - a); } System.out.println(ans); } }
Go
package main import ( "bufio" "fmt" "os" "strconv" ) var scanner = bufio.NewScanner(os.Stdin) func nextInt() (int, error) { return strconv.Atoi(nextString()) } func nextString() string { scanner.Scan() return scanner.Text() } func main() { scanner.Split(bufio.ScanWords) startTemp, _ := nextInt() targetTemp, _ := nextInt() deltaFrozen, _ := nextInt() deltaZero, _ := nextInt() deltaNotFrozen, _ := nextInt() requiredTime := 0 if startTemp < 0 { requiredTime += -startTemp * deltaFrozen } if startTemp <= 0 { requiredTime += deltaZero } if startTemp <= 0 { requiredTime += targetTemp * deltaNotFrozen } else { requiredTime += (targetTemp - startTemp) * deltaNotFrozen } fmt.Println(requiredTime) }
Yes
Do these codes solve the same problem? Code 1: import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int e = sc.nextInt(); int ans = 0; if(a < 0) { ans += -a * c; ans += d; ans += e * b; }else { ans += e * (b - a); } System.out.println(ans); } } Code 2: package main import ( "bufio" "fmt" "os" "strconv" ) var scanner = bufio.NewScanner(os.Stdin) func nextInt() (int, error) { return strconv.Atoi(nextString()) } func nextString() string { scanner.Scan() return scanner.Text() } func main() { scanner.Split(bufio.ScanWords) startTemp, _ := nextInt() targetTemp, _ := nextInt() deltaFrozen, _ := nextInt() deltaZero, _ := nextInt() deltaNotFrozen, _ := nextInt() requiredTime := 0 if startTemp < 0 { requiredTime += -startTemp * deltaFrozen } if startTemp <= 0 { requiredTime += deltaZero } if startTemp <= 0 { requiredTime += targetTemp * deltaNotFrozen } else { requiredTime += (targetTemp - startTemp) * deltaNotFrozen } fmt.Println(requiredTime) }
Python
# coding: utf-8 def get_ln_inputs(): return input().split() def get_ln_int_inputs(): return list(map(int, get_ln_inputs())) def main(): p = get_ln_int_inputs() print(sum(p) - max(p)) main()
Java
import java.util.Arrays; import java.util.Scanner; // Java8 public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) throws Exception { new Main().run(); } void run() { int[] a = new int[3]; for(int i = 0; i < 3; i++) a[i] = sc.nextInt(); Arrays.sort(a); System.out.println(a[0] + a[1]); } }
Yes
Do these codes solve the same problem? Code 1: # coding: utf-8 def get_ln_inputs(): return input().split() def get_ln_int_inputs(): return list(map(int, get_ln_inputs())) def main(): p = get_ln_int_inputs() print(sum(p) - max(p)) main() Code 2: import java.util.Arrays; import java.util.Scanner; // Java8 public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) throws Exception { new Main().run(); } void run() { int[] a = new int[3]; for(int i = 0; i < 3; i++) a[i] = sc.nextInt(); Arrays.sort(a); System.out.println(a[0] + a[1]); } }
C++
#include<bits/stdc++.h> using namespace std; using Int = long long; //INSERT ABOVE HERE template<typename T1,typename T2> void chmin(T1 &a,T2 b){if(a>b) a=b;}; template<typename T1,typename T2> void chmax(T1 &a,T2 b){if(a<b) a=b;}; const Int MAX = 1010; Int dp[MAX][MAX]; signed main(){ Int LIM; string s; cin>>LIM>>s; s='+'+s; Int n=s.size(); const Int INF = 1e15; for(Int i=0;i<MAX;i++) for(Int j=0;j<MAX;j++) dp[i][j]=INF; dp[0][0]=0; for(Int i=0;i<n;i++){ for(Int j=0;j<MAX;j++){ if(dp[i][j]>=INF) continue; for(Int k=2;k<=12&&i+k<=n;k++){ for(Int x=0;x<=k;x++){ Int d=s[i]!='+'; for(Int l=1;l<k;l++) d+=s[i+l]=='+'; Int res=0; for(Int l=1;l<k;l++){ res*=10; if(s[i+l]=='+'){ if(l==1&&k>2) res++; continue; } if(l==1&&k>2&&s[i+l]=='0'){ res++; d++; continue; } if(x+1<=l){ res+=s[i+l]-'0'; continue; } if(l==1&&k>2){ res++; d+=s[i+l]!='1'; }else{ d+=s[i+l]!='0'; } } //cout<<i<<" "<<j<<" "<<k<<" "<<x<<":"<<dp[i][j]<<" "<<res<<endl; chmin(dp[i+k][j+d],dp[i][j]+res); } } } } Int ans=INF; for(Int j=0;j<MAX;j++) if(dp[n][j]<=LIM) chmin(ans,j); if(ans>=INF) ans=-1; cout<<ans<<endl; return 0; }
Python
from heapq import heappush, heappop, heapify import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) S = readline().strip() L = len(S) S += "+" if L % 2 == 0 and N < 10: write("-1\n") return pw10 = [1]*11 for i in range(10): pw10[i+1] = pw10[i] * 10 INF = N+1 dist = [[INF]*(L+2) for i in range(L+1)] ques = [[] for i in range(L+1)] ques[0] = [(0, 0)] dist[0][0] = 0 for k in range(L+1): que = ques[k] dist0 = dist[k] heapify(que) while que: cost, i = heappop(que) if dist0[i] < cost or i > L: continue p = S[i] if i+1 != L-1: if p != "+": v = int(p) if S[i+1] != '+': if cost + v < dist[k+1][i+2]: dist[k+1][i+2] = cost + v ques[k+1].append((cost + v, i+2)) else: if cost + v < dist0[i+2]: dist0[i+2] = cost + v heappush(que, (cost + v, i+2)) if p != "0": nk = k+1 + (S[i+1] != "+") if cost < dist[nk][i+2]: dist[nk][i+2] = cost ques[nk].append((cost, i+2)) def calc(c0, p): for j in range(i+2, min(i+10, L+1)): if j == L-1: continue p1 = p + S[i+1:j]; l = j-i c = c0 + p1.count("+") v = int(p1.replace(*"+0")) if v <= N: nk = k+c + (S[j] != '+') if cost + v < dist[nk][j+1]: dist[nk][j+1] = cost + v ques[nk].append((cost + v, j+1)) b = pw10[l-2] for e in range(l-2, -1, -1): a = (v // b) % 10 if a: v -= a * b c += 1 if v <= N: nk = k+c + (S[j] != '+') if cost + v < dist[nk][j+1]: dist[nk][j+1] = cost + v ques[nk].append((cost + v, j+1)) b //= 10 if p not in "0+": calc(0, p) if p != "1": calc(1, "1") if dist0[L+1] <= N: write("%d\n" % k) break solve()
Yes
Do these codes solve the same problem? Code 1: #include<bits/stdc++.h> using namespace std; using Int = long long; //INSERT ABOVE HERE template<typename T1,typename T2> void chmin(T1 &a,T2 b){if(a>b) a=b;}; template<typename T1,typename T2> void chmax(T1 &a,T2 b){if(a<b) a=b;}; const Int MAX = 1010; Int dp[MAX][MAX]; signed main(){ Int LIM; string s; cin>>LIM>>s; s='+'+s; Int n=s.size(); const Int INF = 1e15; for(Int i=0;i<MAX;i++) for(Int j=0;j<MAX;j++) dp[i][j]=INF; dp[0][0]=0; for(Int i=0;i<n;i++){ for(Int j=0;j<MAX;j++){ if(dp[i][j]>=INF) continue; for(Int k=2;k<=12&&i+k<=n;k++){ for(Int x=0;x<=k;x++){ Int d=s[i]!='+'; for(Int l=1;l<k;l++) d+=s[i+l]=='+'; Int res=0; for(Int l=1;l<k;l++){ res*=10; if(s[i+l]=='+'){ if(l==1&&k>2) res++; continue; } if(l==1&&k>2&&s[i+l]=='0'){ res++; d++; continue; } if(x+1<=l){ res+=s[i+l]-'0'; continue; } if(l==1&&k>2){ res++; d+=s[i+l]!='1'; }else{ d+=s[i+l]!='0'; } } //cout<<i<<" "<<j<<" "<<k<<" "<<x<<":"<<dp[i][j]<<" "<<res<<endl; chmin(dp[i+k][j+d],dp[i][j]+res); } } } } Int ans=INF; for(Int j=0;j<MAX;j++) if(dp[n][j]<=LIM) chmin(ans,j); if(ans>=INF) ans=-1; cout<<ans<<endl; return 0; } Code 2: from heapq import heappush, heappop, heapify import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) S = readline().strip() L = len(S) S += "+" if L % 2 == 0 and N < 10: write("-1\n") return pw10 = [1]*11 for i in range(10): pw10[i+1] = pw10[i] * 10 INF = N+1 dist = [[INF]*(L+2) for i in range(L+1)] ques = [[] for i in range(L+1)] ques[0] = [(0, 0)] dist[0][0] = 0 for k in range(L+1): que = ques[k] dist0 = dist[k] heapify(que) while que: cost, i = heappop(que) if dist0[i] < cost or i > L: continue p = S[i] if i+1 != L-1: if p != "+": v = int(p) if S[i+1] != '+': if cost + v < dist[k+1][i+2]: dist[k+1][i+2] = cost + v ques[k+1].append((cost + v, i+2)) else: if cost + v < dist0[i+2]: dist0[i+2] = cost + v heappush(que, (cost + v, i+2)) if p != "0": nk = k+1 + (S[i+1] != "+") if cost < dist[nk][i+2]: dist[nk][i+2] = cost ques[nk].append((cost, i+2)) def calc(c0, p): for j in range(i+2, min(i+10, L+1)): if j == L-1: continue p1 = p + S[i+1:j]; l = j-i c = c0 + p1.count("+") v = int(p1.replace(*"+0")) if v <= N: nk = k+c + (S[j] != '+') if cost + v < dist[nk][j+1]: dist[nk][j+1] = cost + v ques[nk].append((cost + v, j+1)) b = pw10[l-2] for e in range(l-2, -1, -1): a = (v // b) % 10 if a: v -= a * b c += 1 if v <= N: nk = k+c + (S[j] != '+') if cost + v < dist[nk][j+1]: dist[nk][j+1] = cost + v ques[nk].append((cost + v, j+1)) b //= 10 if p not in "0+": calc(0, p) if p != "1": calc(1, "1") if dist0[L+1] <= N: write("%d\n" % k) break solve()
C++
#include <iostream> #include <vector> #include <array> #include <unordered_map> #include <unordered_set> #include <queue> #include <algorithm> #include <iomanip> #include <cmath> #include <limits> using namespace std; typedef long long ll; void add_mod(ll& val, ll add_val) { val = (val + add_val) % 100000007; } int main (int argc, char* argv[]) { string s; cin >> s; for (int i = 0; i < s.size(); i++) { if (i & 1) { if (s[i] == 'L' || s[i] == 'U' || s[i] == 'D') { continue; } } else { if (s[i] == 'R' || s[i] == 'U' || s[i] == 'D') { continue; } } cout << "No" << endl; return 0; } cout << "Yes" << endl; }
Python
A, B, C, D, E, F = map(int, input().split()) best = -1.0 a = ws = sg = 0 while 100 * a * A <= F: b = 0 while True: w = 100 * (a * A + b * B) if w > F: break c = 0 while w + c * C <= F and 100 * c * C <= w * E: d = 0 while True: s = c * C + d * D if w + s > F or 100 * s > w * E: break elif w + s != 0 and best < s / (w + s): best = s / (w + s) ws = w + s sg = s d += 1 c += 1 b += 1 a += 1 print(ws, sg)
No
Do these codes solve the same problem? Code 1: #include <iostream> #include <vector> #include <array> #include <unordered_map> #include <unordered_set> #include <queue> #include <algorithm> #include <iomanip> #include <cmath> #include <limits> using namespace std; typedef long long ll; void add_mod(ll& val, ll add_val) { val = (val + add_val) % 100000007; } int main (int argc, char* argv[]) { string s; cin >> s; for (int i = 0; i < s.size(); i++) { if (i & 1) { if (s[i] == 'L' || s[i] == 'U' || s[i] == 'D') { continue; } } else { if (s[i] == 'R' || s[i] == 'U' || s[i] == 'D') { continue; } } cout << "No" << endl; return 0; } cout << "Yes" << endl; } Code 2: A, B, C, D, E, F = map(int, input().split()) best = -1.0 a = ws = sg = 0 while 100 * a * A <= F: b = 0 while True: w = 100 * (a * A + b * B) if w > F: break c = 0 while w + c * C <= F and 100 * c * C <= w * E: d = 0 while True: s = c * C + d * D if w + s > F or 100 * s > w * E: break elif w + s != 0 and best < s / (w + s): best = s / (w + s) ws = w + s sg = s d += 1 c += 1 b += 1 a += 1 print(ws, sg)
Python
a, b, c, d = [int(input()) for i in range(4)] e = min(a, b) f = min(c, d) print(e + f)
C++
#include<iostream> #include<vector> #include<math.h> using namespace std; int main(){ int N, K, min = 0, t=0; bool answer = true; cin >> N >> K; vector<char> D(K); for(int i = 0; i < K; i++){ cin >> D[i]; } for(int i = N; i < 10*N; i++){ answer = true; for(int j = 0; j < to_string(i).size(); j++){ for(int l = 0; l < K;l++){ if(to_string(i).at(j) == D[l]){answer = false;} } } if(answer == true){ min = i; break; } } cout << min << endl; }
No
Do these codes solve the same problem? Code 1: a, b, c, d = [int(input()) for i in range(4)] e = min(a, b) f = min(c, d) print(e + f) Code 2: #include<iostream> #include<vector> #include<math.h> using namespace std; int main(){ int N, K, min = 0, t=0; bool answer = true; cin >> N >> K; vector<char> D(K); for(int i = 0; i < K; i++){ cin >> D[i]; } for(int i = N; i < 10*N; i++){ answer = true; for(int j = 0; j < to_string(i).size(); j++){ for(int l = 0; l < K;l++){ if(to_string(i).at(j) == D[l]){answer = false;} } } if(answer == true){ min = i; break; } } cout << min << endl; }
Java
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO ????????????????????????????????????????????? //System.out.println("??\???>>"); Scanner scan = new Scanner(System.in); ArrayList<Integer[]> list = new ArrayList<Integer[]>(); while(scan.hasNext()){ Integer ary[]; ary = new Integer[2]; ary[0] = scan.nextInt(); ary[1] = scan.nextInt(); if(ary[0] == 0 && ary[1] == 0 ){ scan.close(); break; }else{ list.add(ary); } } for(int i = 0; i < list.size(); i++){ Integer[] ary = list.get(i); if(ary[0] < ary[1]){ System.out.println( ary[0] + " " + ary[1]); }else{ System.out.println( ary[1] + " " + ary[0]); } //System.out.println("ary[0]:" + ary[0] + "ary[1]:" + ary[1]); } } }
Python
N=int(input()) a=input().split() numbers=[] for n in a: b=int(n) numbers.append(b) a=round(sum(numbers)/N) answers=[] for z in numbers: y=(z-a)*(z-a) answers.append(y) print(sum(answers))
No
Do these codes solve the same problem? Code 1: import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO ????????????????????????????????????????????? //System.out.println("??\???>>"); Scanner scan = new Scanner(System.in); ArrayList<Integer[]> list = new ArrayList<Integer[]>(); while(scan.hasNext()){ Integer ary[]; ary = new Integer[2]; ary[0] = scan.nextInt(); ary[1] = scan.nextInt(); if(ary[0] == 0 && ary[1] == 0 ){ scan.close(); break; }else{ list.add(ary); } } for(int i = 0; i < list.size(); i++){ Integer[] ary = list.get(i); if(ary[0] < ary[1]){ System.out.println( ary[0] + " " + ary[1]); }else{ System.out.println( ary[1] + " " + ary[0]); } //System.out.println("ary[0]:" + ary[0] + "ary[1]:" + ary[1]); } } } Code 2: N=int(input()) a=input().split() numbers=[] for n in a: b=int(n) numbers.append(b) a=round(sum(numbers)/N) answers=[] for z in numbers: y=(z-a)*(z-a) answers.append(y) print(sum(answers))
TypeScript
class AtCoder { // 入力系 input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/); input_i=-1; n(){ this.input_i++; return Number(this.input[this.input_i]); } nn(n):number[]{ const a=[]; for(let i=0;i<n;i++){ a.push(this.n()); } return a; } s(){ this.input_i++; return String(this.input[this.input_i]); } ss(n):string[]{ const a=[]; for(let i=0;i<n;i++){ a.push(this.s()); } return a; } // コンソール o(...a:any){ console.log(...a); } // Math abs(a:number){ return Math.abs(a); } min(...a:number[]){ return Math.min(...a); } max(...a:number[]){ return Math.max(...a); } floor(a:number){ return Math.floor(a); } ceil(a:number){ return Math.ceil(a); } round(a:number){ return Math.round(a); } // ソート asc(ar:number[]){ const t=[...ar]; ar.sort((a,b)=>{return a-b}); } desc(ar:number[]){ const t=[...ar]; ar.sort((a,b)=>{return b-a}); } // 自作 gcd(...arr):number{ for(let i=0;i<arr.length-1;i++){ let [x,y]=[arr[i],arr[i+1]]; while(y){ [x,y]=[y,x%y]; } arr[i+1]=x; } return arr[arr.length-1]; }; lcm(...arr):number{ for(let i=0;i<arr.length-1;i++){ let [x,y]=[arr[i],arr[i+1]]; while(y){ [x,y]=[y,x%y]; } arr[i+1]=arr[i]*arr[i+1]/x; } return arr[arr.length-1]; }; isPrime(n:number):boolean{ if(n < 2) return false; const suq=Math.sqrt(n); for(let i=2;i<=suq;i++){ if(n%i==0){ return false; } }return true; }; deduplicate(a:any[]):any[]{ return Array.from(new Set(a)); }; } const main = () => { const o = new AtCoder() let obj ={} let n=o.n() for(let i=0;i<n;i++){ let s=o.s() if(obj[s]){ o.o('NO') return } obj[s]=1; } o.o('YES') } main();
Go
package main import ( "bufio" "bytes" "fmt" "io" "os" "strconv" ) // ----------------------------------------------------------------------------- // IO helper functions // Returns next token from input. It must be initialized by SetInput() // before the first call. var nextToken func() ([]byte, error) var nextLine func() ([]byte, error) // Holds a buffer for output. It must be initialized by SetOutput(). // All IO fucntions (read*() and [e]print*()) should write to OutputWriter // instead of this. var OutputBuffer *bufio.Writer // Holds an io.Writer. It must be initialized by SetOutput() var OutputWriter io.Writer // Set IO functions for interactive input/output. func SetInteractive(w io.Writer, r io.Reader) { SetUnbefferedInput(r) OutputBuffer = nil OutputWriter = w } // Setup OutputBuffer and OutputWriter. func SetOutput(w io.Writer) { OutputBuffer = bufio.NewWriter(w) OutputWriter = OutputBuffer } // Flushes OutputBuffer func Flush() { if OutputBuffer != nil { OutputBuffer.Flush() } } // Returns true if c is a white space func IsSpace(c byte) bool { switch c { case '\t', '\n', '\v', '\f', '\r', ' ': return true } return false } func IsNewLine(c byte) bool { switch c { case '\n', '\r': return true } return false } // Setup nextToken with input buffer. func SetInput(r io.Reader) { buf := new(bytes.Buffer) var b []byte var i int rest := func() ([]byte, error) { for i < len(b) && IsSpace(b[i]) { i++ } if i == len(b) { return nil, io.ErrUnexpectedEOF } j := i for i < len(b) && !IsSpace(b[i]) { i++ } return b[j:i], nil } initial := func() ([]byte, error) { io.Copy(buf, r) b = buf.Bytes() nextToken = rest return rest() } nextToken = initial restLn := func() ([]byte, error) { for i < len(b) && IsNewLine(b[i]) { i++ } if i == len(b) { return nil, io.ErrUnexpectedEOF } j := i for i < len(b) && !IsNewLine(b[i]) { i++ } return b[j:i], nil } initialLn := func() ([]byte, error) { io.Copy(buf, r) b = buf.Bytes() nextLine = restLn return restLn() } nextLine = initialLn } // Setup nextToken without input buffer. func SetUnbefferedInput(r io.Reader) { buf := bufio.NewReader(r) var b []byte var i int nextToken = func() ([]byte, error) { var err error if i == len(b) { b, err = buf.ReadBytes('\n') if err != nil { return nil, err } i = 0 j := len(b) - 1 for 0 <= j && IsSpace(b[j]) { j-- } b = b[0 : j+1] } for i < len(b) && IsSpace(b[i]) { i++ } j := i for i < len(b) && !IsSpace(b[i]) { i++ } if i == j { return nil, io.ErrUnexpectedEOF } return b[j:i], nil } } // ----------------------------------------------------------------------------- // IO functions // Reads next token and return it as []byte func readb() []byte { b, err := nextToken() if err != nil { panic(err) } return b[:len(b):len(b)] } // Reads next token and return it as string func reads() string { return string(readb()) } // Read next line as []byte. Trailing '\n' will not be included. // See also comments on readb() func readbln() []byte { b, err := nextLine() if err != nil { panic(err) } return b[:len(b):len(b)] } // Read next line as string func readsln() string { return string(readbln()) } // Reads next token and return it as int64 func readll() int64 { i, err := strconv.ParseInt(reads(), 10, 64) if err != nil { panic(err.Error()) } return i } // Reads next token and return it as int func readi() int { return int(readll()) } // Reads next token and return it as float64 func readf() float64 { f, err := strconv.ParseFloat(reads(), 64) if err != nil { panic(err.Error()) } return f } // Write args to OutputWriter with the format f func printf(f string, args ...interface{}) (int, error) { return fmt.Fprintf(OutputWriter, f, args...) } // Write args to OutputWriter without format func println(args ...interface{}) (int, error) { return fmt.Fprintln(OutputWriter, args...) } // Write args to stderr with the format f func eprintf(f string, args ...interface{}) (int, error) { return fmt.Fprintf(os.Stderr, f, args...) } // Write args to stderr without format func eprintln(args ...interface{}) (int, error) { return fmt.Fprintln(os.Stderr, args...) } // ----------------------------------------------------------------------------- // Utilities func sumSlice(a []int) int { var res int for _, v := range a { res += v } return res } func sumSlicell(a []int64) int64 { var res int64 for _, v := range a { res += v } return res } func readInts(N int) (int, []int) { if N == 0 { N = readi() } a := make([]int, N) for i := range a { a[i] = readi() } return N, a } func readIntsll(N int) (int, []int64) { if N == 0 { N = readi() } a := make([]int64, N) for i := range a { a[i] = readll() } return N, a } // reverse slice in place func reverse(a []int) { for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] } } // areverse: allocating reverse func areverse(a []int) []int { b := make([]int, len(a)) for i := range a { b[i] = a[len(a)-i-1] } return b } // ----------------------------------------------------------------------------- // Simple math functions const ( // big prime INF = 1000000007 INF2 = 1000000009 INF3 = 998244353 ) func min(a, b int) int { if a < b { return a } return b } func minll(a, b int64) int64 { if a < b { return a } return b } func max(a, b int) int { if a < b { return b } return a } func maxll(a, b int64) int64 { if a < b { return b } return a } func abs(a int) int { if a < 0 { return -a } return a } func absll(a int64) int64 { if a < 0 { return -a } return a } // egcd(a, b) returns d, x, y: // d is gcd(a,b) // x, y are integers that satisfy ax + by = d func egcd(a, b int) (int, int, int) { if b == 0 { return a, 1, 0 } d, x, y := egcd(b, a%b) return d, y, x - a/b*y } func egcdll(a, b int64) (int64, int64, int64) { if b == 0 { return a, 1, 0 } d, x, y := egcdll(b, a%b) return d, y, x - a/b*y } func gcd(a, b int) int { d, _, _ := egcd(a, b) return d } func gcdll(a, b int64) int64 { d, _, _ := egcdll(a, b) return d } // set up IO functions func init() { // for non-interactive SetInput(os.Stdin) SetOutput(os.Stdout) // Enable below when interactive. Its ok to leave above intact. // SetInteractive(os.Stdout, os.Stdin) } func main() { defer Flush() N, A := readInts(0) _ = N m := make(map[int]bool) for _, v := range A { if m[v] { println("NO") return } m[v] = true } println("YES") }
Yes
Do these codes solve the same problem? Code 1: class AtCoder { // 入力系 input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/); input_i=-1; n(){ this.input_i++; return Number(this.input[this.input_i]); } nn(n):number[]{ const a=[]; for(let i=0;i<n;i++){ a.push(this.n()); } return a; } s(){ this.input_i++; return String(this.input[this.input_i]); } ss(n):string[]{ const a=[]; for(let i=0;i<n;i++){ a.push(this.s()); } return a; } // コンソール o(...a:any){ console.log(...a); } // Math abs(a:number){ return Math.abs(a); } min(...a:number[]){ return Math.min(...a); } max(...a:number[]){ return Math.max(...a); } floor(a:number){ return Math.floor(a); } ceil(a:number){ return Math.ceil(a); } round(a:number){ return Math.round(a); } // ソート asc(ar:number[]){ const t=[...ar]; ar.sort((a,b)=>{return a-b}); } desc(ar:number[]){ const t=[...ar]; ar.sort((a,b)=>{return b-a}); } // 自作 gcd(...arr):number{ for(let i=0;i<arr.length-1;i++){ let [x,y]=[arr[i],arr[i+1]]; while(y){ [x,y]=[y,x%y]; } arr[i+1]=x; } return arr[arr.length-1]; }; lcm(...arr):number{ for(let i=0;i<arr.length-1;i++){ let [x,y]=[arr[i],arr[i+1]]; while(y){ [x,y]=[y,x%y]; } arr[i+1]=arr[i]*arr[i+1]/x; } return arr[arr.length-1]; }; isPrime(n:number):boolean{ if(n < 2) return false; const suq=Math.sqrt(n); for(let i=2;i<=suq;i++){ if(n%i==0){ return false; } }return true; }; deduplicate(a:any[]):any[]{ return Array.from(new Set(a)); }; } const main = () => { const o = new AtCoder() let obj ={} let n=o.n() for(let i=0;i<n;i++){ let s=o.s() if(obj[s]){ o.o('NO') return } obj[s]=1; } o.o('YES') } main(); Code 2: package main import ( "bufio" "bytes" "fmt" "io" "os" "strconv" ) // ----------------------------------------------------------------------------- // IO helper functions // Returns next token from input. It must be initialized by SetInput() // before the first call. var nextToken func() ([]byte, error) var nextLine func() ([]byte, error) // Holds a buffer for output. It must be initialized by SetOutput(). // All IO fucntions (read*() and [e]print*()) should write to OutputWriter // instead of this. var OutputBuffer *bufio.Writer // Holds an io.Writer. It must be initialized by SetOutput() var OutputWriter io.Writer // Set IO functions for interactive input/output. func SetInteractive(w io.Writer, r io.Reader) { SetUnbefferedInput(r) OutputBuffer = nil OutputWriter = w } // Setup OutputBuffer and OutputWriter. func SetOutput(w io.Writer) { OutputBuffer = bufio.NewWriter(w) OutputWriter = OutputBuffer } // Flushes OutputBuffer func Flush() { if OutputBuffer != nil { OutputBuffer.Flush() } } // Returns true if c is a white space func IsSpace(c byte) bool { switch c { case '\t', '\n', '\v', '\f', '\r', ' ': return true } return false } func IsNewLine(c byte) bool { switch c { case '\n', '\r': return true } return false } // Setup nextToken with input buffer. func SetInput(r io.Reader) { buf := new(bytes.Buffer) var b []byte var i int rest := func() ([]byte, error) { for i < len(b) && IsSpace(b[i]) { i++ } if i == len(b) { return nil, io.ErrUnexpectedEOF } j := i for i < len(b) && !IsSpace(b[i]) { i++ } return b[j:i], nil } initial := func() ([]byte, error) { io.Copy(buf, r) b = buf.Bytes() nextToken = rest return rest() } nextToken = initial restLn := func() ([]byte, error) { for i < len(b) && IsNewLine(b[i]) { i++ } if i == len(b) { return nil, io.ErrUnexpectedEOF } j := i for i < len(b) && !IsNewLine(b[i]) { i++ } return b[j:i], nil } initialLn := func() ([]byte, error) { io.Copy(buf, r) b = buf.Bytes() nextLine = restLn return restLn() } nextLine = initialLn } // Setup nextToken without input buffer. func SetUnbefferedInput(r io.Reader) { buf := bufio.NewReader(r) var b []byte var i int nextToken = func() ([]byte, error) { var err error if i == len(b) { b, err = buf.ReadBytes('\n') if err != nil { return nil, err } i = 0 j := len(b) - 1 for 0 <= j && IsSpace(b[j]) { j-- } b = b[0 : j+1] } for i < len(b) && IsSpace(b[i]) { i++ } j := i for i < len(b) && !IsSpace(b[i]) { i++ } if i == j { return nil, io.ErrUnexpectedEOF } return b[j:i], nil } } // ----------------------------------------------------------------------------- // IO functions // Reads next token and return it as []byte func readb() []byte { b, err := nextToken() if err != nil { panic(err) } return b[:len(b):len(b)] } // Reads next token and return it as string func reads() string { return string(readb()) } // Read next line as []byte. Trailing '\n' will not be included. // See also comments on readb() func readbln() []byte { b, err := nextLine() if err != nil { panic(err) } return b[:len(b):len(b)] } // Read next line as string func readsln() string { return string(readbln()) } // Reads next token and return it as int64 func readll() int64 { i, err := strconv.ParseInt(reads(), 10, 64) if err != nil { panic(err.Error()) } return i } // Reads next token and return it as int func readi() int { return int(readll()) } // Reads next token and return it as float64 func readf() float64 { f, err := strconv.ParseFloat(reads(), 64) if err != nil { panic(err.Error()) } return f } // Write args to OutputWriter with the format f func printf(f string, args ...interface{}) (int, error) { return fmt.Fprintf(OutputWriter, f, args...) } // Write args to OutputWriter without format func println(args ...interface{}) (int, error) { return fmt.Fprintln(OutputWriter, args...) } // Write args to stderr with the format f func eprintf(f string, args ...interface{}) (int, error) { return fmt.Fprintf(os.Stderr, f, args...) } // Write args to stderr without format func eprintln(args ...interface{}) (int, error) { return fmt.Fprintln(os.Stderr, args...) } // ----------------------------------------------------------------------------- // Utilities func sumSlice(a []int) int { var res int for _, v := range a { res += v } return res } func sumSlicell(a []int64) int64 { var res int64 for _, v := range a { res += v } return res } func readInts(N int) (int, []int) { if N == 0 { N = readi() } a := make([]int, N) for i := range a { a[i] = readi() } return N, a } func readIntsll(N int) (int, []int64) { if N == 0 { N = readi() } a := make([]int64, N) for i := range a { a[i] = readll() } return N, a } // reverse slice in place func reverse(a []int) { for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] } } // areverse: allocating reverse func areverse(a []int) []int { b := make([]int, len(a)) for i := range a { b[i] = a[len(a)-i-1] } return b } // ----------------------------------------------------------------------------- // Simple math functions const ( // big prime INF = 1000000007 INF2 = 1000000009 INF3 = 998244353 ) func min(a, b int) int { if a < b { return a } return b } func minll(a, b int64) int64 { if a < b { return a } return b } func max(a, b int) int { if a < b { return b } return a } func maxll(a, b int64) int64 { if a < b { return b } return a } func abs(a int) int { if a < 0 { return -a } return a } func absll(a int64) int64 { if a < 0 { return -a } return a } // egcd(a, b) returns d, x, y: // d is gcd(a,b) // x, y are integers that satisfy ax + by = d func egcd(a, b int) (int, int, int) { if b == 0 { return a, 1, 0 } d, x, y := egcd(b, a%b) return d, y, x - a/b*y } func egcdll(a, b int64) (int64, int64, int64) { if b == 0 { return a, 1, 0 } d, x, y := egcdll(b, a%b) return d, y, x - a/b*y } func gcd(a, b int) int { d, _, _ := egcd(a, b) return d } func gcdll(a, b int64) int64 { d, _, _ := egcdll(a, b) return d } // set up IO functions func init() { // for non-interactive SetInput(os.Stdin) SetOutput(os.Stdout) // Enable below when interactive. Its ok to leave above intact. // SetInteractive(os.Stdout, os.Stdin) } func main() { defer Flush() N, A := readInts(0) _ = N m := make(map[int]bool) for _, v := range A { if m[v] { println("NO") return } m[v] = true } println("YES") }
Python
import math S = int(input()) h = math.floor(S/3600) m = math.floor((S - h*3600)/60) s = (S - (h*3600 + m*60))%60 print(str(h)+":"+str(m)+":"+str(s))
C++
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> lpair; const ll MOD = 1e9 + 7; const ll INF = 1e18; #define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i ) #define rep(i,n) REP(i,0,n) #define rREP(i,m,n) for(ll i = (m); i >= (n); i--) #define ALL(c) (c).begin(), (c).end() #define print(x) cout << (x) << endl; #define printa(x,n) for(ll i = 0; i < n; i++){ cout << (x[i]) << " ";} cout<<endl; int main(){ cin.tie(0); ios::sync_with_stdio(false); int ary[4]; rep(i,4) ary[i] = 0; rep(i,3) { int a,b; cin >> a >> b; a--;b--; ary[a]++; ary[b]++; } int odd = 0; rep(i,4) { if (ary[i]%2==1) odd++; } if (odd == 0 || odd == 2) { cout << "YES" << endl; } else { cout << "NO" << endl; } }
No
Do these codes solve the same problem? Code 1: import math S = int(input()) h = math.floor(S/3600) m = math.floor((S - h*3600)/60) s = (S - (h*3600 + m*60))%60 print(str(h)+":"+str(m)+":"+str(s)) Code 2: #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> lpair; const ll MOD = 1e9 + 7; const ll INF = 1e18; #define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i ) #define rep(i,n) REP(i,0,n) #define rREP(i,m,n) for(ll i = (m); i >= (n); i--) #define ALL(c) (c).begin(), (c).end() #define print(x) cout << (x) << endl; #define printa(x,n) for(ll i = 0; i < n; i++){ cout << (x[i]) << " ";} cout<<endl; int main(){ cin.tie(0); ios::sync_with_stdio(false); int ary[4]; rep(i,4) ary[i] = 0; rep(i,3) { int a,b; cin >> a >> b; a--;b--; ary[a]++; ary[b]++; } int odd = 0; rep(i,4) { if (ary[i]%2==1) odd++; } if (odd == 0 || odd == 2) { cout << "YES" << endl; } else { cout << "NO" << endl; } }
Python
s = input() a = [s.count("a"), s.count("b"), s.count("c")] a.sort(reverse=True) if a[0] <= a[2] + 1: print("YES") else: print("NO")
C#
using System; using System.Text; using System.Collections.Generic; using System.Linq; class Solve{ public Solve(){} StringBuilder sb; ReadData re; public static int Main(){ new Solve().Run(); return 0; } void Run(){ sb = new StringBuilder(); re = new ReadData(); Calc(); Console.Write(sb.ToString()); } void Calc(){ string S = re.s(); int[] A = new int[3]; for(int i=0;i<S.Length;i++){ A[S[i]-'a']++; } Array.Sort(A); if(A[2]-A[0] <= 1){ sb.Append("YES\n"); } else{ sb.Append("NO\n"); } } } class ReadData{ string[] str; int counter; public ReadData(){ counter = 0; } public string s(){ if(counter == 0){ str = Console.ReadLine().Split(' '); counter = str.Length; } counter--; return str[str.Length-counter-1]; } public int i(){ return int.Parse(s()); } public long l(){ return long.Parse(s()); } public double d(){ return double.Parse(s()); } public int[] ia(int N){ int[] ans = new int[N]; for(int j=0;j<N;j++){ ans[j] = i(); } return ans; } public int[] ia(){ str = Console.ReadLine().Split(' '); counter = 0; int[] ans = new int[str.Length]; for(int j=0;j<str.Length;j++){ ans[j] = int.Parse(str[j]); } return ans; } public long[] la(int N){ long[] ans = new long[N]; for(int j=0;j<N;j++){ ans[j] = l(); } return ans; } public long[] la(){ str = Console.ReadLine().Split(' '); counter = 0; long[] ans = new long[str.Length]; for(int j=0;j<str.Length;j++){ ans[j] = long.Parse(str[j]); } return ans; } public double[] da(int N){ double[] ans = new double[N]; for(int j=0;j<N;j++){ ans[j] = d(); } return ans; } public double[] da(){ str = Console.ReadLine().Split(' '); counter = 0; double[] ans = new double[str.Length]; for(int j=0;j<str.Length;j++){ ans[j] = double.Parse(str[j]); } return ans; } public List<int>[] g(int N,int[] f,int[] t){ List<int>[] ans = new List<int>[N]; for(int j=0;j<N;j++){ ans[j] = new List<int>(); } for(int j=0;j<f.Length;j++){ ans[f[j]].Add(t[j]); ans[t[j]].Add(f[j]); } return ans; } public List<int>[] g(int N,int M){ List<int>[] ans = new List<int>[N]; for(int j=0;j<N;j++){ ans[j] = new List<int>(); } for(int j=0;j<M;j++){ int f = i()-1; int t = i()-1; ans[f].Add(t); ans[t].Add(f); } return ans; } public List<int>[] g(){ int N = i(); int M = i(); List<int>[] ans = new List<int>[N]; for(int j=0;j<N;j++){ ans[j] = new List<int>(); } for(int j=0;j<M;j++){ int f = i()-1; int t = i()-1; ans[f].Add(t); ans[t].Add(f); } return ans; } } public static class Define{ public const long mod = 1000000007; } public static class Debug{ public static void Print(double[,,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ for(int l=0;l<k.GetLength(2);l++){ Console.Write(k[i,j,l]+" "); } Console.WriteLine(); } Console.WriteLine(); } } public static void Print(double[,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ Console.Write(k[i,j]+" "); } Console.WriteLine(); } } public static void Print(double[] k){ for(int i=0;i<k.Length;i++){ Console.WriteLine(k[i]); } } public static void Print(long[,,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ for(int l=0;l<k.GetLength(2);l++){ Console.Write(k[i,j,l]+" "); } Console.WriteLine(); } Console.WriteLine(); } } public static void Print(long[,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ Console.Write(k[i,j]+" "); } Console.WriteLine(); } } public static void Print(long[] k){ for(int i=0;i<k.Length;i++){ Console.WriteLine(k[i]); } } public static void Print(int[,,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ for(int l=0;l<k.GetLength(2);l++){ Console.Write(k[i,j,l]+" "); } Console.WriteLine(); } Console.WriteLine(); } } public static void Print(int[,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ Console.Write(k[i,j]+" "); } Console.WriteLine(); } } public static void Print(int[] k){ for(int i=0;i<k.Length;i++){ Console.WriteLine(k[i]); } } }
Yes
Do these codes solve the same problem? Code 1: s = input() a = [s.count("a"), s.count("b"), s.count("c")] a.sort(reverse=True) if a[0] <= a[2] + 1: print("YES") else: print("NO") Code 2: using System; using System.Text; using System.Collections.Generic; using System.Linq; class Solve{ public Solve(){} StringBuilder sb; ReadData re; public static int Main(){ new Solve().Run(); return 0; } void Run(){ sb = new StringBuilder(); re = new ReadData(); Calc(); Console.Write(sb.ToString()); } void Calc(){ string S = re.s(); int[] A = new int[3]; for(int i=0;i<S.Length;i++){ A[S[i]-'a']++; } Array.Sort(A); if(A[2]-A[0] <= 1){ sb.Append("YES\n"); } else{ sb.Append("NO\n"); } } } class ReadData{ string[] str; int counter; public ReadData(){ counter = 0; } public string s(){ if(counter == 0){ str = Console.ReadLine().Split(' '); counter = str.Length; } counter--; return str[str.Length-counter-1]; } public int i(){ return int.Parse(s()); } public long l(){ return long.Parse(s()); } public double d(){ return double.Parse(s()); } public int[] ia(int N){ int[] ans = new int[N]; for(int j=0;j<N;j++){ ans[j] = i(); } return ans; } public int[] ia(){ str = Console.ReadLine().Split(' '); counter = 0; int[] ans = new int[str.Length]; for(int j=0;j<str.Length;j++){ ans[j] = int.Parse(str[j]); } return ans; } public long[] la(int N){ long[] ans = new long[N]; for(int j=0;j<N;j++){ ans[j] = l(); } return ans; } public long[] la(){ str = Console.ReadLine().Split(' '); counter = 0; long[] ans = new long[str.Length]; for(int j=0;j<str.Length;j++){ ans[j] = long.Parse(str[j]); } return ans; } public double[] da(int N){ double[] ans = new double[N]; for(int j=0;j<N;j++){ ans[j] = d(); } return ans; } public double[] da(){ str = Console.ReadLine().Split(' '); counter = 0; double[] ans = new double[str.Length]; for(int j=0;j<str.Length;j++){ ans[j] = double.Parse(str[j]); } return ans; } public List<int>[] g(int N,int[] f,int[] t){ List<int>[] ans = new List<int>[N]; for(int j=0;j<N;j++){ ans[j] = new List<int>(); } for(int j=0;j<f.Length;j++){ ans[f[j]].Add(t[j]); ans[t[j]].Add(f[j]); } return ans; } public List<int>[] g(int N,int M){ List<int>[] ans = new List<int>[N]; for(int j=0;j<N;j++){ ans[j] = new List<int>(); } for(int j=0;j<M;j++){ int f = i()-1; int t = i()-1; ans[f].Add(t); ans[t].Add(f); } return ans; } public List<int>[] g(){ int N = i(); int M = i(); List<int>[] ans = new List<int>[N]; for(int j=0;j<N;j++){ ans[j] = new List<int>(); } for(int j=0;j<M;j++){ int f = i()-1; int t = i()-1; ans[f].Add(t); ans[t].Add(f); } return ans; } } public static class Define{ public const long mod = 1000000007; } public static class Debug{ public static void Print(double[,,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ for(int l=0;l<k.GetLength(2);l++){ Console.Write(k[i,j,l]+" "); } Console.WriteLine(); } Console.WriteLine(); } } public static void Print(double[,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ Console.Write(k[i,j]+" "); } Console.WriteLine(); } } public static void Print(double[] k){ for(int i=0;i<k.Length;i++){ Console.WriteLine(k[i]); } } public static void Print(long[,,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ for(int l=0;l<k.GetLength(2);l++){ Console.Write(k[i,j,l]+" "); } Console.WriteLine(); } Console.WriteLine(); } } public static void Print(long[,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ Console.Write(k[i,j]+" "); } Console.WriteLine(); } } public static void Print(long[] k){ for(int i=0;i<k.Length;i++){ Console.WriteLine(k[i]); } } public static void Print(int[,,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ for(int l=0;l<k.GetLength(2);l++){ Console.Write(k[i,j,l]+" "); } Console.WriteLine(); } Console.WriteLine(); } } public static void Print(int[,] k){ for(int i=0;i<k.GetLength(0);i++){ for(int j=0;j<k.GetLength(1);j++){ Console.Write(k[i,j]+" "); } Console.WriteLine(); } } public static void Print(int[] k){ for(int i=0;i<k.Length;i++){ Console.WriteLine(k[i]); } } }
Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] tmpArray = br.readLine().split(" "); int n = Integer.parseInt(tmpArray[0]); Activity[] acts = new Activity[n]; for(int i = 0; i < n; i++){ tmpArray = br.readLine().split(" "); int start = Integer.parseInt(tmpArray[0]); int end = Integer.parseInt(tmpArray[1]); acts[i] = new Activity(start, end); } Arrays.sort(acts); int count = 1; int currentTime = acts[0].end; for(int i = 1; i < n ; i++){ if(currentTime < acts[i].start){ count++; currentTime = acts[i].end; } } System.out.println(count); } } class Activity implements Comparable<Activity>{ int start; int end; public Activity(int s, int e){ this.start = s; this.end = e; } @Override public int compareTo(Activity a1) { return this.end - a1.end; } }
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CompProgLib; namespace ALDS1_15_C { public class Program { public struct Node : IComparable<Node> { public int Start { get; private set; } public int End { get; private set; } public Node(int s, int e) { Start = s; End = e; } public int CompareTo(Node other) { if (End - other.End > 0) return -1; else if (End - other.End < 0) return 1; else { if (Start - other.Start > 0) return -1; else if (End - other.End < 0) return 1; else { return 0; } } } } public static void Main(string[] args) { int n = ReadInt(); PriorityQueue<Node> pq = new PriorityQueue<Node>(); for (int i = 0 ; i < n ; i++) { int[] item = ReadIntAr(); pq.Enqueue(new Node(item[0], item[1])); } int res = 0; int currentTime = 0; while (pq.Count > 0) { Node tmp = pq.Dequeue(); if (currentTime < tmp.Start) { res++; currentTime = tmp.End; } } Console.WriteLine(res.ToString()); } static string ReadSt() { return Console.ReadLine(); } static int ReadInt() { return int.Parse(Console.ReadLine()); } static long ReadLong() { return long.Parse(Console.ReadLine()); } static double ReadDouble() { return double.Parse(Console.ReadLine()); } static string[] ReadStAr(char sep = ' ') { return Console.ReadLine().Split(sep); } static int[] ReadIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); } static long[] ReadLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); } static double[] ReadDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); } } } namespace CompProgLib { public class PriorityQueue<T> where T : IComparable<T> { private List<T> Buffer { get; set; } public int Count { get { return Buffer.Count; } } public PriorityQueue() { Buffer = new List<T>(); } public PriorityQueue(int capacity) { Buffer = new List<T>(capacity); } /// <summary> /// ヒープ化されている配列リストに新しい要素を追加する。 /// </summary> public void Enqueue(T item) { int n = Buffer.Count; Buffer.Add(item); while (n != 0) { int i = (n - 1) / 2; if (Buffer[n].CompareTo(Buffer[i]) > 0) { T tmp = Buffer[n]; Buffer[n] = Buffer[i]; Buffer[i] = tmp; } n = i; } } /// <summary> /// ヒープから最大値を取り出し、削除する。 /// </summary> public T Dequeue() { T ret = Buffer[0]; int n = Buffer.Count - 1; Buffer[0] = Buffer[n]; Buffer.RemoveAt(n); for (int i = 0, j ; (j = 2 * i + 1) < n ;) { if ((j != n - 1) && (Buffer[j].CompareTo(Buffer[j + 1]) < 0)) j++; if (Buffer[i].CompareTo(Buffer[j]) < 0) { T tmp = Buffer[j]; Buffer[j] = Buffer[i]; Buffer[i] = tmp; } i = j; } return ret; } /// <summary> /// ヒープから最大値を参照する。 /// </summary> public T Peek() { if (Count == 0) throw new InvalidOperationException(); return this.Buffer[0]; } } }
Yes
Do these codes solve the same problem? Code 1: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] tmpArray = br.readLine().split(" "); int n = Integer.parseInt(tmpArray[0]); Activity[] acts = new Activity[n]; for(int i = 0; i < n; i++){ tmpArray = br.readLine().split(" "); int start = Integer.parseInt(tmpArray[0]); int end = Integer.parseInt(tmpArray[1]); acts[i] = new Activity(start, end); } Arrays.sort(acts); int count = 1; int currentTime = acts[0].end; for(int i = 1; i < n ; i++){ if(currentTime < acts[i].start){ count++; currentTime = acts[i].end; } } System.out.println(count); } } class Activity implements Comparable<Activity>{ int start; int end; public Activity(int s, int e){ this.start = s; this.end = e; } @Override public int compareTo(Activity a1) { return this.end - a1.end; } } Code 2: using System; using System.Collections.Generic; using System.Linq; using System.Text; using CompProgLib; namespace ALDS1_15_C { public class Program { public struct Node : IComparable<Node> { public int Start { get; private set; } public int End { get; private set; } public Node(int s, int e) { Start = s; End = e; } public int CompareTo(Node other) { if (End - other.End > 0) return -1; else if (End - other.End < 0) return 1; else { if (Start - other.Start > 0) return -1; else if (End - other.End < 0) return 1; else { return 0; } } } } public static void Main(string[] args) { int n = ReadInt(); PriorityQueue<Node> pq = new PriorityQueue<Node>(); for (int i = 0 ; i < n ; i++) { int[] item = ReadIntAr(); pq.Enqueue(new Node(item[0], item[1])); } int res = 0; int currentTime = 0; while (pq.Count > 0) { Node tmp = pq.Dequeue(); if (currentTime < tmp.Start) { res++; currentTime = tmp.End; } } Console.WriteLine(res.ToString()); } static string ReadSt() { return Console.ReadLine(); } static int ReadInt() { return int.Parse(Console.ReadLine()); } static long ReadLong() { return long.Parse(Console.ReadLine()); } static double ReadDouble() { return double.Parse(Console.ReadLine()); } static string[] ReadStAr(char sep = ' ') { return Console.ReadLine().Split(sep); } static int[] ReadIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); } static long[] ReadLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); } static double[] ReadDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); } } } namespace CompProgLib { public class PriorityQueue<T> where T : IComparable<T> { private List<T> Buffer { get; set; } public int Count { get { return Buffer.Count; } } public PriorityQueue() { Buffer = new List<T>(); } public PriorityQueue(int capacity) { Buffer = new List<T>(capacity); } /// <summary> /// ヒープ化されている配列リストに新しい要素を追加する。 /// </summary> public void Enqueue(T item) { int n = Buffer.Count; Buffer.Add(item); while (n != 0) { int i = (n - 1) / 2; if (Buffer[n].CompareTo(Buffer[i]) > 0) { T tmp = Buffer[n]; Buffer[n] = Buffer[i]; Buffer[i] = tmp; } n = i; } } /// <summary> /// ヒープから最大値を取り出し、削除する。 /// </summary> public T Dequeue() { T ret = Buffer[0]; int n = Buffer.Count - 1; Buffer[0] = Buffer[n]; Buffer.RemoveAt(n); for (int i = 0, j ; (j = 2 * i + 1) < n ;) { if ((j != n - 1) && (Buffer[j].CompareTo(Buffer[j + 1]) < 0)) j++; if (Buffer[i].CompareTo(Buffer[j]) < 0) { T tmp = Buffer[j]; Buffer[j] = Buffer[i]; Buffer[i] = tmp; } i = j; } return ret; } /// <summary> /// ヒープから最大値を参照する。 /// </summary> public T Peek() { if (Count == 0) throw new InvalidOperationException(); return this.Buffer[0]; } } }
C++
#include <bits/stdc++.h> #include <algorithm> #define rep(i, n) for (int i=0; i<n; ++i) #define all(obj) (obj).begin(),(obj).end() using namespace std; typedef long long ll; ll lcm(ll a, ll b){ return a*b/__gcd(a, b); } int main(){ ll A, B; cin >> A >> B; cout << lcm(A, B) << endl; }
Python
def main(): n=int(input()) s=input() ans=s[1:].count('E') tmp=ans for i in range(n-1): if s[i]=='W': tmp+=1 if s[i+1]=='E': tmp-=1 ans=min(ans,tmp) tmp=s[:-1].count('W') ans=min(ans,tmp) print(ans) if __name__=='__main__': main()
No
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> #include <algorithm> #define rep(i, n) for (int i=0; i<n; ++i) #define all(obj) (obj).begin(),(obj).end() using namespace std; typedef long long ll; ll lcm(ll a, ll b){ return a*b/__gcd(a, b); } int main(){ ll A, B; cin >> A >> B; cout << lcm(A, B) << endl; } Code 2: def main(): n=int(input()) s=input() ans=s[1:].count('E') tmp=ans for i in range(n-1): if s[i]=='W': tmp+=1 if s[i+1]=='E': tmp-=1 ans=min(ans,tmp) tmp=s[:-1].count('W') ans=min(ans,tmp) print(ans) if __name__=='__main__': main()
Python
a,b,c = map(int,input().split()) d = int(c/a) print(d*b)
C++
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <iomanip> #include <vector> #include <string.h> #include <string> #include <map> #include <stack> #include <queue> #include <deque> #include <set> #include <math.h> #include <algorithm> #include <numeric> using namespace std; // マクロ&定数&関数 ================================================ typedef unsigned int uint; typedef long long ll; typedef pair<ll, ll> pll; typedef vector<int> vint; typedef vector<ll> vll; typedef vector<double> vdouble; typedef vector<bool> vbool; typedef vector<string> vstring; typedef vector<pair<int, int>> vpint; typedef vector<pair<ll, ll>> vpll; typedef vector<pair<double, double>> vpdouble; typedef vector<vector<int>> vvint; typedef vector<vector<ll>> vvll; typedef vector<vpint> vvpint; typedef vector<vpll> vvpll; typedef vector<vector<double>> vvdouble; typedef vector<vector<string>> vvstring; typedef vector<vector<bool>> vvbool; typedef vector<vector<vector<ll>>> vvvll; const int INF = 1e9 + 1; const ll LLINF = 1e17 + 1; const int DX[9] = { 0, 0, 1, -1, 1, 1, -1, -1, 0 }; // 4;4近傍 const int DY[9] = { 1, -1, 0, 0, 1, -1, 1, -1, 0 }; // 8:8近傍 9:(0,0)を含む const ll MOD = 1000000007; //10^9 + 7 const ll MAX = 1e9; const double PI = 3.14159265358979323846264338327950288; //--------------------------------------------------------------- // オーバーフローチェック //--------------------------------------------------------------- bool is_overflow(ll a, ll b) { return ((a * b) / b != a); } //--------------------------------------------------------------- // 約数列挙 //--------------------------------------------------------------- vll divisor(ll n) { vll ret; for (ll i = 1; i * i <= n; i++) { if (n % i == 0) { ret.push_back(i); if (i * i != n) ret.push_back(n / i); } } sort(begin(ret), end(ret)); return (ret); } //--------------------------------------------------------------- // N以下のすべての素数を列挙する(エラトステネスの篩) //--------------------------------------------------------------- vbool searchSosuu(ll N) { vbool sosuu; for (ll i = 0; i < N; i++) { sosuu.emplace_back(true); } sosuu[0] = false; sosuu[1] = false; for (ll i = 2; i < N; i++) { if (sosuu[i]) { for (ll j = 2; i * j < N; j++) { sosuu[i * j] = false; } } } return sosuu; } //--------------------------------------------------------------- // 素因数分解 O(√N) //--------------------------------------------------------------- vpll div_prime(ll n) { vpll prime_factor; for (ll i = 2; i * i <= n; i++) { ll count = 0; while (n % i == 0) { count++; n /= i; } if (count) { pair<ll, ll> temp = { i, count }; prime_factor.emplace_back(temp); } } if (n != 1) { pair<ll, ll> temp = { n, 1 }; prime_factor.emplace_back(temp); } return prime_factor; } //--------------------------------------------------------------- // 素数判定 //--------------------------------------------------------------- bool is_sosuu(ll N) { if (N < 2) return false; else if (N == 2) return true; else if (N % 2 == 0) return false; for (ll i = 3; i <= sqrt(N); i += 2) { if (N % i == 0) return false; } return true; } //--------------------------------------------------------------- // 最大公約数(ユークリッドの互除法) //--------------------------------------------------------------- ll gcd(ll a, ll b) { if (a < b) { ll tmp = a; a = b; b = tmp; } ll r = a % b; while (r != 0) { a = b; b = r; r = a % b; } return b; } //--------------------------------------------------------------- // 最小公倍数 //--------------------------------------------------------------- ll lcm(ll a, ll b) { ll temp = gcd(a, b); return temp * (a / temp) * (b / temp); } //--------------------------------------------------------------- // 階乗 //--------------------------------------------------------------- ll factorial(ll n) { if (n <= 1) return 1; return (n * (factorial(n - 1))) % MOD; } //--------------------------------------------------------------- // 高速コンビネーション計算(前処理:O(N) 計算:O(1)) //--------------------------------------------------------------- // テーブルを作る前処理 ll comb_const = 200005; vll fac(comb_const), finv(comb_const), inv(comb_const); bool COMineted = false; void COMinit() { fac[0] = fac[1] = 1; finv[0] = finv[1] = 1; inv[1] = 1; for (ll i = 2; i < comb_const; i++) { fac[i] = fac[i - 1] * i % MOD; inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD; finv[i] = finv[i - 1] * inv[i] % MOD; } COMineted = true; } // 二項係数計算 ll COM(ll n, ll k) { if (COMineted == false) COMinit(); if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD; } //--------------------------------------------------------------- // 繰り返し2乗法 base^sisuu //--------------------------------------------------------------- ll RepeatSquaring(ll base, ll sisuu) { if (sisuu < 0) { cout << "RepeatSquaring: 指数が負です!" << endl; return 0; } if (sisuu == 0) return 1; if (sisuu % 2 == 0) { ll t = RepeatSquaring(base, sisuu / 2) % MOD; return (t * t) % MOD; } return base * RepeatSquaring(base, sisuu - 1) % MOD; } //--------------------------------------------------------------- // 高速単発コンビネーション計算(O(logN)) //--------------------------------------------------------------- ll fast_com(ll a, ll b) { ll bunshi = 1; ll bunbo = 1; for (ll i = 1; i <= b; i++) { bunbo *= i; bunbo %= MOD; bunshi *= (a - i + 1); bunshi %= MOD; } ll ret = bunshi * RepeatSquaring(bunbo, MOD - 2); ret %= MOD; while (ret < 0) { ret += MOD; } return ret; } //--------------------------------------------------------------- // 2直線の交差判定(直線(x1, y1)->(x2, y2) と 直線(X1, Y1)->(X2, Y2)) //--------------------------------------------------------------- bool is_cross(ll x1, ll y1, ll x2, ll y2, ll X1, ll Y1, ll X2, ll Y2) { ll dx_ai = X1 - x1; ll dy_ai = Y1 - y1; ll dx_bi = X1 - x2; ll dy_bi = Y1 - y2; ll dx_ai2 = X2 - x1; ll dy_ai2 = Y2 - y1; ll dx_bi2 = X2 - x2; ll dy_bi2 = Y2 - y2; ll si = dx_ai * dy_bi - dy_ai * dx_bi; ll si2 = dx_ai2 * dy_bi2 - dy_ai2 * dx_bi2; ll si3 = dx_ai * dy_ai2 - dy_ai * dx_ai2; ll si4 = dx_bi * dy_bi2 - dy_bi * dx_bi2; return (si * si2 < 0 && si3 * si4 < 0); } //--------------------------------------------------------------- // 最長増加部分列の長さ(O(NlogN)) //--------------------------------------------------------------- ll LSI(vll vec) { ll size = vec.size(); vll lsi(size + 1); // 長さjを作った時の右端の最小値 for (ll i = 0; i <= size; i++) { lsi[i] = LLINF; } lsi[0] = 0; lsi[1] = vec[0]; for (ll i = 1; i < size; i++) { // 初めてvec[i]の方が小さくなるところを探す auto Iter = lower_bound(lsi.begin(), lsi.end(), vec[i]); ll idx = Iter - lsi.begin(); if (idx > 0 && lsi[idx - 1] < vec[i]) { lsi[idx] = vec[i]; } } for (ll i = size; i >= 0; i--) { if (lsi[i] < LLINF) { return i; } } } //--------------------------------------------------------------- // 木の根からの深さ //--------------------------------------------------------------- vll tree_depth(vvll edge, ll start_node, ll n_node) { vll dist(n_node, LLINF); dist[start_node] = 0; stack<pll> S; S.push({ start_node, 0 }); while (!S.empty()) { ll node = S.top().first; ll d = S.top().second; dist[node] = d; S.pop(); for (int i = 0; i < edge[node].size(); i++) { if (dist[edge[node][i]] == LLINF) { S.push({ edge[node][i], d + 1 }); } } } return dist; } //--------------------------------------------------------------- // ワーシャルフロイド法(O(N^3)) 任意の2点間の最短距離 //--------------------------------------------------------------- vvll warshall_floyd(vvll d) { ll n = d.size(); for (int k = 0; k < n; k++) { // 経由する頂点 for (int i = 0; i < n; i++) { // 始点 for (int j = 0; j < n; j++) { // 終点 d[i][j] = min(d[i][j], d[i][k] + d[k][j]); } } } return d; } //--------------------------------------------------------------- // Union Find //--------------------------------------------------------------- class UnionFind { public: /* UnionFind uf(要素の個数); for(int i = 0;i < 関係の個数; i++) { uf.merge(A[i], B[i]); } nを含む集合の大きさ = uf.size(n) nを含む集合の代表者 = uf.root(n) 集合の個数 = uf.n_group */ vector <ll> par; // 各元の親を表す配列 vector <ll> siz; // 素集合のサイズを表す配列(1 で初期化) ll n_group; //集合の数 // Constructor UnionFind(ll sz_) : par(sz_), siz(sz_, 1LL) { for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身 n_group = sz_; } void init(ll sz_) { par.resize(sz_); siz.assign(sz_, 1LL); // resize だとなぜか初期化されなかった for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身 } // Member Function // Find ll root(ll x) { // 根の検索 while (par[x] != x) { x = par[x] = par[par[x]]; // x の親の親を x の親とする } return x; } // Union(Unite, Merge) bool merge(ll x, ll y) { x = root(x); y = root(y); if (x == y) return false; // merge technique(データ構造をマージするテク.小を大にくっつける) if (siz[x] < siz[y]) swap(x, y); siz[x] += siz[y]; par[y] = x; n_group--; return true; } bool issame(ll x, ll y) { // 連結判定 return root(x) == root(y); } ll size(ll x) { // 素集合のサイズ return siz[root(x)]; } }; //======================================================================== int main() { ////================================== cin.tie(nullptr); ios_base::sync_with_stdio(false); cout << fixed << setprecision(30); ////================================== /* ~思いついたことはとりあえず絶対メモする!!~ */ ll N, M; cin >> N >> M; vvll d(N, vll(N, LLINF)); vvll edge; for (int i = 0; i < M; i++) { ll a, b, c; cin >> a >> b >> c; a--; b--; d[a][b] = c; d[b][a] = c; vll t = { a, b, c }; edge.push_back(t); } for (int i = 0; i < N; i++) { d[i][i] = 0; } d = warshall_floyd(d); vbool used(M, false); for (int i = 0; i < M; i++) { ll a = edge[i][0]; ll b = edge[i][1]; ll c = edge[i][2]; for (int from = 0; from < N; from++) { for (int to = from + 1; to < N; to++) { if (d[from][to] == d[from][a] + d[b][to] + c || d[from][to] == d[from][b] + d[a][to] + c) { used[i] = true; } } } } ll ans = 0; for (bool u : used) { ans += !u; } cout << ans << endl; return 0; }
No
Do these codes solve the same problem? Code 1: a,b,c = map(int,input().split()) d = int(c/a) print(d*b) Code 2: #include <stdio.h> #include <stdlib.h> #include <iostream> #include <iomanip> #include <vector> #include <string.h> #include <string> #include <map> #include <stack> #include <queue> #include <deque> #include <set> #include <math.h> #include <algorithm> #include <numeric> using namespace std; // マクロ&定数&関数 ================================================ typedef unsigned int uint; typedef long long ll; typedef pair<ll, ll> pll; typedef vector<int> vint; typedef vector<ll> vll; typedef vector<double> vdouble; typedef vector<bool> vbool; typedef vector<string> vstring; typedef vector<pair<int, int>> vpint; typedef vector<pair<ll, ll>> vpll; typedef vector<pair<double, double>> vpdouble; typedef vector<vector<int>> vvint; typedef vector<vector<ll>> vvll; typedef vector<vpint> vvpint; typedef vector<vpll> vvpll; typedef vector<vector<double>> vvdouble; typedef vector<vector<string>> vvstring; typedef vector<vector<bool>> vvbool; typedef vector<vector<vector<ll>>> vvvll; const int INF = 1e9 + 1; const ll LLINF = 1e17 + 1; const int DX[9] = { 0, 0, 1, -1, 1, 1, -1, -1, 0 }; // 4;4近傍 const int DY[9] = { 1, -1, 0, 0, 1, -1, 1, -1, 0 }; // 8:8近傍 9:(0,0)を含む const ll MOD = 1000000007; //10^9 + 7 const ll MAX = 1e9; const double PI = 3.14159265358979323846264338327950288; //--------------------------------------------------------------- // オーバーフローチェック //--------------------------------------------------------------- bool is_overflow(ll a, ll b) { return ((a * b) / b != a); } //--------------------------------------------------------------- // 約数列挙 //--------------------------------------------------------------- vll divisor(ll n) { vll ret; for (ll i = 1; i * i <= n; i++) { if (n % i == 0) { ret.push_back(i); if (i * i != n) ret.push_back(n / i); } } sort(begin(ret), end(ret)); return (ret); } //--------------------------------------------------------------- // N以下のすべての素数を列挙する(エラトステネスの篩) //--------------------------------------------------------------- vbool searchSosuu(ll N) { vbool sosuu; for (ll i = 0; i < N; i++) { sosuu.emplace_back(true); } sosuu[0] = false; sosuu[1] = false; for (ll i = 2; i < N; i++) { if (sosuu[i]) { for (ll j = 2; i * j < N; j++) { sosuu[i * j] = false; } } } return sosuu; } //--------------------------------------------------------------- // 素因数分解 O(√N) //--------------------------------------------------------------- vpll div_prime(ll n) { vpll prime_factor; for (ll i = 2; i * i <= n; i++) { ll count = 0; while (n % i == 0) { count++; n /= i; } if (count) { pair<ll, ll> temp = { i, count }; prime_factor.emplace_back(temp); } } if (n != 1) { pair<ll, ll> temp = { n, 1 }; prime_factor.emplace_back(temp); } return prime_factor; } //--------------------------------------------------------------- // 素数判定 //--------------------------------------------------------------- bool is_sosuu(ll N) { if (N < 2) return false; else if (N == 2) return true; else if (N % 2 == 0) return false; for (ll i = 3; i <= sqrt(N); i += 2) { if (N % i == 0) return false; } return true; } //--------------------------------------------------------------- // 最大公約数(ユークリッドの互除法) //--------------------------------------------------------------- ll gcd(ll a, ll b) { if (a < b) { ll tmp = a; a = b; b = tmp; } ll r = a % b; while (r != 0) { a = b; b = r; r = a % b; } return b; } //--------------------------------------------------------------- // 最小公倍数 //--------------------------------------------------------------- ll lcm(ll a, ll b) { ll temp = gcd(a, b); return temp * (a / temp) * (b / temp); } //--------------------------------------------------------------- // 階乗 //--------------------------------------------------------------- ll factorial(ll n) { if (n <= 1) return 1; return (n * (factorial(n - 1))) % MOD; } //--------------------------------------------------------------- // 高速コンビネーション計算(前処理:O(N) 計算:O(1)) //--------------------------------------------------------------- // テーブルを作る前処理 ll comb_const = 200005; vll fac(comb_const), finv(comb_const), inv(comb_const); bool COMineted = false; void COMinit() { fac[0] = fac[1] = 1; finv[0] = finv[1] = 1; inv[1] = 1; for (ll i = 2; i < comb_const; i++) { fac[i] = fac[i - 1] * i % MOD; inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD; finv[i] = finv[i - 1] * inv[i] % MOD; } COMineted = true; } // 二項係数計算 ll COM(ll n, ll k) { if (COMineted == false) COMinit(); if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD; } //--------------------------------------------------------------- // 繰り返し2乗法 base^sisuu //--------------------------------------------------------------- ll RepeatSquaring(ll base, ll sisuu) { if (sisuu < 0) { cout << "RepeatSquaring: 指数が負です!" << endl; return 0; } if (sisuu == 0) return 1; if (sisuu % 2 == 0) { ll t = RepeatSquaring(base, sisuu / 2) % MOD; return (t * t) % MOD; } return base * RepeatSquaring(base, sisuu - 1) % MOD; } //--------------------------------------------------------------- // 高速単発コンビネーション計算(O(logN)) //--------------------------------------------------------------- ll fast_com(ll a, ll b) { ll bunshi = 1; ll bunbo = 1; for (ll i = 1; i <= b; i++) { bunbo *= i; bunbo %= MOD; bunshi *= (a - i + 1); bunshi %= MOD; } ll ret = bunshi * RepeatSquaring(bunbo, MOD - 2); ret %= MOD; while (ret < 0) { ret += MOD; } return ret; } //--------------------------------------------------------------- // 2直線の交差判定(直線(x1, y1)->(x2, y2) と 直線(X1, Y1)->(X2, Y2)) //--------------------------------------------------------------- bool is_cross(ll x1, ll y1, ll x2, ll y2, ll X1, ll Y1, ll X2, ll Y2) { ll dx_ai = X1 - x1; ll dy_ai = Y1 - y1; ll dx_bi = X1 - x2; ll dy_bi = Y1 - y2; ll dx_ai2 = X2 - x1; ll dy_ai2 = Y2 - y1; ll dx_bi2 = X2 - x2; ll dy_bi2 = Y2 - y2; ll si = dx_ai * dy_bi - dy_ai * dx_bi; ll si2 = dx_ai2 * dy_bi2 - dy_ai2 * dx_bi2; ll si3 = dx_ai * dy_ai2 - dy_ai * dx_ai2; ll si4 = dx_bi * dy_bi2 - dy_bi * dx_bi2; return (si * si2 < 0 && si3 * si4 < 0); } //--------------------------------------------------------------- // 最長増加部分列の長さ(O(NlogN)) //--------------------------------------------------------------- ll LSI(vll vec) { ll size = vec.size(); vll lsi(size + 1); // 長さjを作った時の右端の最小値 for (ll i = 0; i <= size; i++) { lsi[i] = LLINF; } lsi[0] = 0; lsi[1] = vec[0]; for (ll i = 1; i < size; i++) { // 初めてvec[i]の方が小さくなるところを探す auto Iter = lower_bound(lsi.begin(), lsi.end(), vec[i]); ll idx = Iter - lsi.begin(); if (idx > 0 && lsi[idx - 1] < vec[i]) { lsi[idx] = vec[i]; } } for (ll i = size; i >= 0; i--) { if (lsi[i] < LLINF) { return i; } } } //--------------------------------------------------------------- // 木の根からの深さ //--------------------------------------------------------------- vll tree_depth(vvll edge, ll start_node, ll n_node) { vll dist(n_node, LLINF); dist[start_node] = 0; stack<pll> S; S.push({ start_node, 0 }); while (!S.empty()) { ll node = S.top().first; ll d = S.top().second; dist[node] = d; S.pop(); for (int i = 0; i < edge[node].size(); i++) { if (dist[edge[node][i]] == LLINF) { S.push({ edge[node][i], d + 1 }); } } } return dist; } //--------------------------------------------------------------- // ワーシャルフロイド法(O(N^3)) 任意の2点間の最短距離 //--------------------------------------------------------------- vvll warshall_floyd(vvll d) { ll n = d.size(); for (int k = 0; k < n; k++) { // 経由する頂点 for (int i = 0; i < n; i++) { // 始点 for (int j = 0; j < n; j++) { // 終点 d[i][j] = min(d[i][j], d[i][k] + d[k][j]); } } } return d; } //--------------------------------------------------------------- // Union Find //--------------------------------------------------------------- class UnionFind { public: /* UnionFind uf(要素の個数); for(int i = 0;i < 関係の個数; i++) { uf.merge(A[i], B[i]); } nを含む集合の大きさ = uf.size(n) nを含む集合の代表者 = uf.root(n) 集合の個数 = uf.n_group */ vector <ll> par; // 各元の親を表す配列 vector <ll> siz; // 素集合のサイズを表す配列(1 で初期化) ll n_group; //集合の数 // Constructor UnionFind(ll sz_) : par(sz_), siz(sz_, 1LL) { for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身 n_group = sz_; } void init(ll sz_) { par.resize(sz_); siz.assign(sz_, 1LL); // resize だとなぜか初期化されなかった for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身 } // Member Function // Find ll root(ll x) { // 根の検索 while (par[x] != x) { x = par[x] = par[par[x]]; // x の親の親を x の親とする } return x; } // Union(Unite, Merge) bool merge(ll x, ll y) { x = root(x); y = root(y); if (x == y) return false; // merge technique(データ構造をマージするテク.小を大にくっつける) if (siz[x] < siz[y]) swap(x, y); siz[x] += siz[y]; par[y] = x; n_group--; return true; } bool issame(ll x, ll y) { // 連結判定 return root(x) == root(y); } ll size(ll x) { // 素集合のサイズ return siz[root(x)]; } }; //======================================================================== int main() { ////================================== cin.tie(nullptr); ios_base::sync_with_stdio(false); cout << fixed << setprecision(30); ////================================== /* ~思いついたことはとりあえず絶対メモする!!~ */ ll N, M; cin >> N >> M; vvll d(N, vll(N, LLINF)); vvll edge; for (int i = 0; i < M; i++) { ll a, b, c; cin >> a >> b >> c; a--; b--; d[a][b] = c; d[b][a] = c; vll t = { a, b, c }; edge.push_back(t); } for (int i = 0; i < N; i++) { d[i][i] = 0; } d = warshall_floyd(d); vbool used(M, false); for (int i = 0; i < M; i++) { ll a = edge[i][0]; ll b = edge[i][1]; ll c = edge[i][2]; for (int from = 0; from < N; from++) { for (int to = from + 1; to < N; to++) { if (d[from][to] == d[from][a] + d[b][to] + c || d[from][to] == d[from][b] + d[a][to] + c) { used[i] = true; } } } } ll ans = 0; for (bool u : used) { ans += !u; } cout << ans << endl; return 0; }
Python
import numpy as np from numpy.fft import rfft, irfft N, M = map(int, input().split()) A = np.array(list(map(int, input().split())), np.int64) fft_len = 1<<20 PA = np.bincount(A) P = (irfft(rfft(PA, fft_len) * rfft(PA, fft_len)) + .5).astype(int) ans = 0 for i in range(len(P)-1, -1, -1): if P[i] > 0: if M <= P[i]: ans += i * M print(ans) exit() else: M -= P[i] ans += i * P[i]
C++
/*Ph@n^0m Dec0d3r*/ /*----------------*/ /* ^_HAR HAR MAHADEV_^ |Om namah shivaya| */ #include<bits/stdc++.h> //#include<boost/multiprecision/cpp_int.hpp> #define f(i,a,b) for(int i=a;i<b;i++) #define ll long long int #define fast std::ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0) #define pb(temp) push_back(temp) #define mp make_pair #define mod (ll)1000000007 //using namespace boost::multiprecision; using namespace std ; typedef unsigned long long int ulli; ulli gcd(ulli x,ulli y) { if(x==0) return y; return gcd(y%x,x); } ulli factorial(ulli n) { if (n == 0) return 1; return n * factorial(n - 1); } ll findS(ll s) { return (sqrtl(8*s + 1) - 1)/2; } ll prime(ll a) { if(a==1)return 0; if(a==2 || a==3)return true; if(a%2==0 ||a%3==0)return 0; for(ll i=5; i<=sqrt(a); i+=6) if(a%i==0 || a%(i+2)==0) return 0; return 1; } ll power(ll x,ll y) { if (y == 0) return 1; ll p = power(x, y/2) % mod; p = (p * p) % mod; return (y%2 == 0)? p : (x * p) % mod; } ll powermod(ll x,ll y) { ll res = 1; x = x % mod; while (y > 0) { if (y & 1) res = (res*x) % mod; y = y>>1; x = (x*x) % mod; } return res; } ll nCr(ll n,ll k) { ll C[k+1]; //memset(C, 0, sizeof(C)); C[0] = 1; for (ll i = 1; i <= n; i++) { for (ll j = min(i, k); j > 0; j--) C[j] = (C[j] + C[j-1])%(ll)(1e9 + 7); } return C[k]; } ll LOGN(ll n , ll r) { return (n > r-1) ? (1 + LOGN(n / r , r)) : 0 ; } void dfs(vector<ll> v[], bool visited[], ll current_node) { visited[current_node]=true; for(ll nxt_node : v[current_node]) { if(visited[nxt_node]==false) { dfs(v , visited, nxt_node); } } return; } void bfs(vector<ll> v[], bool visited[], ll root) { int current_node; queue<int> q; q.push(root); while(!q.empty()) { current_node=q.front(); visited[current_node]=true; for(int x:v[current_node]) if(!visited[x]) q.push(x); } } ll computeXOR(ll n) { switch(n & 3) { case 0: return n; case 1: return 1; case 2: return n + 1; case 3: return 0; } } int maxSubArraySum(int a[], int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = max(a[i], curr_max+a[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far; } int main() { fast; ll a , b , k ; cin >> a >> b >> k ; if(k >= a+b) { cout << "0" << " 0" ; } else if(k >= a && k < (a+b)) { cout << "0 " << b-k+a ; } else { cout << a-k << " " << b ; } }
No
Do these codes solve the same problem? Code 1: import numpy as np from numpy.fft import rfft, irfft N, M = map(int, input().split()) A = np.array(list(map(int, input().split())), np.int64) fft_len = 1<<20 PA = np.bincount(A) P = (irfft(rfft(PA, fft_len) * rfft(PA, fft_len)) + .5).astype(int) ans = 0 for i in range(len(P)-1, -1, -1): if P[i] > 0: if M <= P[i]: ans += i * M print(ans) exit() else: M -= P[i] ans += i * P[i] Code 2: /*Ph@n^0m Dec0d3r*/ /*----------------*/ /* ^_HAR HAR MAHADEV_^ |Om namah shivaya| */ #include<bits/stdc++.h> //#include<boost/multiprecision/cpp_int.hpp> #define f(i,a,b) for(int i=a;i<b;i++) #define ll long long int #define fast std::ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0) #define pb(temp) push_back(temp) #define mp make_pair #define mod (ll)1000000007 //using namespace boost::multiprecision; using namespace std ; typedef unsigned long long int ulli; ulli gcd(ulli x,ulli y) { if(x==0) return y; return gcd(y%x,x); } ulli factorial(ulli n) { if (n == 0) return 1; return n * factorial(n - 1); } ll findS(ll s) { return (sqrtl(8*s + 1) - 1)/2; } ll prime(ll a) { if(a==1)return 0; if(a==2 || a==3)return true; if(a%2==0 ||a%3==0)return 0; for(ll i=5; i<=sqrt(a); i+=6) if(a%i==0 || a%(i+2)==0) return 0; return 1; } ll power(ll x,ll y) { if (y == 0) return 1; ll p = power(x, y/2) % mod; p = (p * p) % mod; return (y%2 == 0)? p : (x * p) % mod; } ll powermod(ll x,ll y) { ll res = 1; x = x % mod; while (y > 0) { if (y & 1) res = (res*x) % mod; y = y>>1; x = (x*x) % mod; } return res; } ll nCr(ll n,ll k) { ll C[k+1]; //memset(C, 0, sizeof(C)); C[0] = 1; for (ll i = 1; i <= n; i++) { for (ll j = min(i, k); j > 0; j--) C[j] = (C[j] + C[j-1])%(ll)(1e9 + 7); } return C[k]; } ll LOGN(ll n , ll r) { return (n > r-1) ? (1 + LOGN(n / r , r)) : 0 ; } void dfs(vector<ll> v[], bool visited[], ll current_node) { visited[current_node]=true; for(ll nxt_node : v[current_node]) { if(visited[nxt_node]==false) { dfs(v , visited, nxt_node); } } return; } void bfs(vector<ll> v[], bool visited[], ll root) { int current_node; queue<int> q; q.push(root); while(!q.empty()) { current_node=q.front(); visited[current_node]=true; for(int x:v[current_node]) if(!visited[x]) q.push(x); } } ll computeXOR(ll n) { switch(n & 3) { case 0: return n; case 1: return 1; case 2: return n + 1; case 3: return 0; } } int maxSubArraySum(int a[], int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = max(a[i], curr_max+a[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far; } int main() { fast; ll a , b , k ; cin >> a >> b >> k ; if(k >= a+b) { cout << "0" << " 0" ; } else if(k >= a && k < (a+b)) { cout << "0 " << b-k+a ; } else { cout << a-k << " " << b ; } }
Java
import java.util.Scanner; class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int A = sc.nextInt(), B = sc.nextInt(), C = sc.nextInt(), D = sc.nextInt(), E = sc.nextInt(); System.out.println(A - Math.max((B - 1) / D + 1, (C - 1) / E + 1)); } }
JavaScript
process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { let n = chunk.toString() // 文字列化する .split("\n") // \nで分割 .map(x => Number(x)) .filter(x => x !== 0); let roop1 = true; let kokugoday = 0; let roop2 = true; let sansuday = 0; let kekka1 = n[1] - n[3]; let kekka2 = n[2] - n[4];; while (roop1) { kekka1 = kekka1 - n[3]; kokugoday += 1; if (kekka1 <= 0) { roop1 = false; kokugoday += 1; } } while (roop2) { kekka2 = kekka2 - n[4]; sansuday += 1; if (kekka2 <= 0) { roop2 = false; sansuday += 1; } } if (kokugoday <= sansuday) { const ans = n[0]-sansuday; console.log(ans); }else if(kokugoday >= sansuday){ const ans = n[0]-kokugoday; console.log(ans); } });
Yes
Do these codes solve the same problem? Code 1: import java.util.Scanner; class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int A = sc.nextInt(), B = sc.nextInt(), C = sc.nextInt(), D = sc.nextInt(), E = sc.nextInt(); System.out.println(A - Math.max((B - 1) / D + 1, (C - 1) / E + 1)); } } Code 2: process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { let n = chunk.toString() // 文字列化する .split("\n") // \nで分割 .map(x => Number(x)) .filter(x => x !== 0); let roop1 = true; let kokugoday = 0; let roop2 = true; let sansuday = 0; let kekka1 = n[1] - n[3]; let kekka2 = n[2] - n[4];; while (roop1) { kekka1 = kekka1 - n[3]; kokugoday += 1; if (kekka1 <= 0) { roop1 = false; kokugoday += 1; } } while (roop2) { kekka2 = kekka2 - n[4]; sansuday += 1; if (kekka2 <= 0) { roop2 = false; sansuday += 1; } } if (kokugoday <= sansuday) { const ans = n[0]-sansuday; console.log(ans); }else if(kokugoday >= sansuday){ const ans = n[0]-kokugoday; console.log(ans); } });
C++
#include <bits/stdc++.h> using namespace std; // macros #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define MIN(a,b) (a>b?b:a) #define MAX(a,b) (a>b?a:b) #define INT_IN(a) int a; cin >> a #define STR_IN(s) string s; cin >> s #define PRINTLN(s) cout << s << endl #define PRINTDOUBLELN(s) cout << fixed << setprecision(12) << (s) << endl; // util functions template<class T> inline T sqr(T x) {return x*x;} inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;} template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();} template <typename T>inline T max(vector<T> v){T max=v[0]; FOR(i, 1, v.size())max=MAX(v[i], max); return max;} template <typename T>inline T min(vector<T> v){T min=v[0]; FOR(i, 1, v.size())min=MIN(v[i], min); return min;} template <typename T>inline vector<T> concat(vector<T> a, vector<T> b){vector<T> ab; ab.reserve(a.size()+b.size());ab.insert(ab.end(),a.begin(),a.end());ab.insert(ab.end(),b.begin(),b.end());return ab;} // types typedef long long LL; // consts const double EPS = 1e-10; const double PI = acos(-1.0); //debug #define dump(x) #x << " = " << (x) << endl #define debug(x) #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl int main(){ INT_IN(a); INT_IN(b); PRINTLN(a / b << " " << a % b << " " << fixed << setprecision(12) << 1. * a / b); return 0; }
Java
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] str = new String[n]; boolean count = true; for(int i = 0;i < n;i++){ str[i] = sc.next(); } for(int i = 1;i < n;i++){ for(int j = 0;j < i;j++){ if( str[i].equals(str[j]) ) count = false; } } for(int i = 1;i < n;i++){ if(!(str[i-1].substring(str[i-1].length()-1,str[i-1].length()).equals(str[i].substring(0,1)) )) count = false; } if(count)System.out.println("Yes"); else System.out.println("No"); } }
No
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; // macros #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define MIN(a,b) (a>b?b:a) #define MAX(a,b) (a>b?a:b) #define INT_IN(a) int a; cin >> a #define STR_IN(s) string s; cin >> s #define PRINTLN(s) cout << s << endl #define PRINTDOUBLELN(s) cout << fixed << setprecision(12) << (s) << endl; // util functions template<class T> inline T sqr(T x) {return x*x;} inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;} template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();} template <typename T>inline T max(vector<T> v){T max=v[0]; FOR(i, 1, v.size())max=MAX(v[i], max); return max;} template <typename T>inline T min(vector<T> v){T min=v[0]; FOR(i, 1, v.size())min=MIN(v[i], min); return min;} template <typename T>inline vector<T> concat(vector<T> a, vector<T> b){vector<T> ab; ab.reserve(a.size()+b.size());ab.insert(ab.end(),a.begin(),a.end());ab.insert(ab.end(),b.begin(),b.end());return ab;} // types typedef long long LL; // consts const double EPS = 1e-10; const double PI = acos(-1.0); //debug #define dump(x) #x << " = " << (x) << endl #define debug(x) #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl int main(){ INT_IN(a); INT_IN(b); PRINTLN(a / b << " " << a % b << " " << fixed << setprecision(12) << 1. * a / b); return 0; } Code 2: import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] str = new String[n]; boolean count = true; for(int i = 0;i < n;i++){ str[i] = sc.next(); } for(int i = 1;i < n;i++){ for(int j = 0;j < i;j++){ if( str[i].equals(str[j]) ) count = false; } } for(int i = 1;i < n;i++){ if(!(str[i-1].substring(str[i-1].length()-1,str[i-1].length()).equals(str[i].substring(0,1)) )) count = false; } if(count)System.out.println("Yes"); else System.out.println("No"); } }
C#
using System; using System.Collections.Generic; using System.Globalization; namespace AOJ0501DataConversion { public class Program { static readonly IFormatProvider formatProvider = CultureInfo.InvariantCulture.NumberFormat; private static void Main() { var outputs = new List<string>(); while (true) { var numberOfTableRows = int.Parse(Console.ReadLine(), formatProvider); if (numberOfTableRows == 0 || outputs.Count >= 5) { break; } var table = new Dictionary<char, char>(); CreateTable(table, numberOfTableRows); var numberOfData = int.Parse(Console.ReadLine(), formatProvider); outputs.Add(CreateConvertedString(table, numberOfData)); } foreach (var output in outputs) { Console.WriteLine(output); } } private static void CreateTable(Dictionary<char, char> table, int numberOfTableRows) { for (var i = 0; i < numberOfTableRows; ++i) { var readLine = Console.ReadLine(); if (readLine != null) { table.Add(readLine[0], readLine[2]); } } } private static string CreateConvertedString(Dictionary<char, char> table, int numberOfData) { var result = new List<char>(); for (var i = 0; i < numberOfData; i++) { var readLine = Console.ReadLine(); if (readLine == null) { continue; } var data = readLine[0]; char convertedCharacter; result.Add(table.TryGetValue(data, out convertedCharacter) ? convertedCharacter : data); } return new string(result.ToArray()); } } }
PHP
<?php while (true) { $stdin = trim(fgets(STDIN)); if ($stdin == 0) { break; } $words_list = array(); for ($i = 0;$i < $stdin;$i++) { $words = trim(fgets(STDIN)); list($a,$b) = explode(" ",$words); $words_list[$a] = $b; } $stdin = trim(fgets(STDIN)); $result = ""; for ($i = 0;$i < $stdin;$i++) { $str = trim(fgets(STDIN)); if (array_key_exists($str,$words_list)) { $str = $words_list[$str]; } $result .= $str; } echo $result."\n"; } ?>
Yes
Do these codes solve the same problem? Code 1: using System; using System.Collections.Generic; using System.Globalization; namespace AOJ0501DataConversion { public class Program { static readonly IFormatProvider formatProvider = CultureInfo.InvariantCulture.NumberFormat; private static void Main() { var outputs = new List<string>(); while (true) { var numberOfTableRows = int.Parse(Console.ReadLine(), formatProvider); if (numberOfTableRows == 0 || outputs.Count >= 5) { break; } var table = new Dictionary<char, char>(); CreateTable(table, numberOfTableRows); var numberOfData = int.Parse(Console.ReadLine(), formatProvider); outputs.Add(CreateConvertedString(table, numberOfData)); } foreach (var output in outputs) { Console.WriteLine(output); } } private static void CreateTable(Dictionary<char, char> table, int numberOfTableRows) { for (var i = 0; i < numberOfTableRows; ++i) { var readLine = Console.ReadLine(); if (readLine != null) { table.Add(readLine[0], readLine[2]); } } } private static string CreateConvertedString(Dictionary<char, char> table, int numberOfData) { var result = new List<char>(); for (var i = 0; i < numberOfData; i++) { var readLine = Console.ReadLine(); if (readLine == null) { continue; } var data = readLine[0]; char convertedCharacter; result.Add(table.TryGetValue(data, out convertedCharacter) ? convertedCharacter : data); } return new string(result.ToArray()); } } } Code 2: <?php while (true) { $stdin = trim(fgets(STDIN)); if ($stdin == 0) { break; } $words_list = array(); for ($i = 0;$i < $stdin;$i++) { $words = trim(fgets(STDIN)); list($a,$b) = explode(" ",$words); $words_list[$a] = $b; } $stdin = trim(fgets(STDIN)); $result = ""; for ($i = 0;$i < $stdin;$i++) { $str = trim(fgets(STDIN)); if (array_key_exists($str,$words_list)) { $str = $words_list[$str]; } $result .= $str; } echo $result."\n"; } ?>
C++
#include <bits/stdc++.h> using namespace std; #define all(c) (c).begin(),(c).end() #define rep(i,n) for(int i=0; i<(int)(n); i++) #define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++) #define iter(c) __typeof((c).begin()) #define tr(it,c) for(iter(c) it=(c).begin(); it!=(c).end(); it++) #define pb(a) push_back(a) #define mp(a,b) make_pair(a,b) #define pr(a) cout << (a) << endl #define PR(a,b) cout << (a) << " " << (b) << endl; #define F first #define S second typedef long long ll; typedef pair<int,int> P; const int MAX=1000000001; const ll MAXL=1000000000000000001LL; int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1}; int main() { ll n,d=1000000; while(cin >> n && n) { map<ll,ll> m,m2,m3; set<ll> se; m.clear(); m2.clear(); m3.clear(); se.clear(); rep(i,n) { ll x,y,z; cin >> x >> y >> z; if(se.count(x)) { m2[m[x]]+=y*z; } else { m[x]=m.size()+1; m3[m[x]]=x; se.insert(x); m2[m[x]]=y*z; } } bool ck=true; tr(it,m2) { iter(m3) it2=m3.find(it->F); if(it->S>=d) { cout <<it2->S << endl; ck=false; } } if(ck) pr("NA"); } return 0; }
Go
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { stdin := bufio.NewScanner(os.Stdin) for stdin.Scan() { n, _ := strconv.Atoi(stdin.Text()) if n == 0 { break } sales := make(map[string]int) existed := make(map[string]bool) order := make([]string, 4000) flg := false for i := 0; i < n; i++ { stdin.Scan() l := strings.Split(stdin.Text(), " ") e := l[0] p, _ := strconv.Atoi(l[1]) q, _ := strconv.Atoi(l[2]) sales[e] += p * q if !existed[e] { order = append(order, e) existed[e] = true } } for _, v := range order { if sales[v] >= 1000000 { fmt.Println(v) flg = true } } if flg == false { fmt.Println("NA") } } }
Yes
Do these codes solve the same problem? Code 1: #include <bits/stdc++.h> using namespace std; #define all(c) (c).begin(),(c).end() #define rep(i,n) for(int i=0; i<(int)(n); i++) #define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++) #define iter(c) __typeof((c).begin()) #define tr(it,c) for(iter(c) it=(c).begin(); it!=(c).end(); it++) #define pb(a) push_back(a) #define mp(a,b) make_pair(a,b) #define pr(a) cout << (a) << endl #define PR(a,b) cout << (a) << " " << (b) << endl; #define F first #define S second typedef long long ll; typedef pair<int,int> P; const int MAX=1000000001; const ll MAXL=1000000000000000001LL; int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1}; int main() { ll n,d=1000000; while(cin >> n && n) { map<ll,ll> m,m2,m3; set<ll> se; m.clear(); m2.clear(); m3.clear(); se.clear(); rep(i,n) { ll x,y,z; cin >> x >> y >> z; if(se.count(x)) { m2[m[x]]+=y*z; } else { m[x]=m.size()+1; m3[m[x]]=x; se.insert(x); m2[m[x]]=y*z; } } bool ck=true; tr(it,m2) { iter(m3) it2=m3.find(it->F); if(it->S>=d) { cout <<it2->S << endl; ck=false; } } if(ck) pr("NA"); } return 0; } Code 2: package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { stdin := bufio.NewScanner(os.Stdin) for stdin.Scan() { n, _ := strconv.Atoi(stdin.Text()) if n == 0 { break } sales := make(map[string]int) existed := make(map[string]bool) order := make([]string, 4000) flg := false for i := 0; i < n; i++ { stdin.Scan() l := strings.Split(stdin.Text(), " ") e := l[0] p, _ := strconv.Atoi(l[1]) q, _ := strconv.Atoi(l[2]) sales[e] += p * q if !existed[e] { order = append(order, e) existed[e] = true } } for _, v := range order { if sales[v] >= 1000000 { fmt.Println(v) flg = true } } if flg == false { fmt.Println("NA") } } }
C#
using System; class MyClass { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int Out = 0; bool first = false; bool second = false; bool third = false; int point = 0; while (Out != n * 3) { switch (Console.ReadLine()) { case ("HIT"): if (third) { point++; third = false; } if (second) { third = true; second = false; } if (first) { second = true; } first = true; break; case ("HOMERUN"): if (first) { first = false; point++; } if (second) { second = false; point++; } if (third) { third = false; point++; } point++; break; case ("OUT"): Out++; if (Out % 3 == 0) { Console.WriteLine(point); point = 0; first = false; second = false; third = false; } break; default: break; } } } }
Go
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { stdin := bufio.NewScanner(os.Stdin) stdin.Scan() n, _ := strconv.Atoi(stdin.Text()) for i := 0; i < n; i++ { base := [3]bool{} score, out := 0, 0 for stdin.Scan() { switch stdin.Text() { case "HIT": if base[2] { // 3塁 score++ } if base[1] { // 2塁 base[2] = true base[1] = false } if base[0] { // 1塁 base[1] = true } base[0] = true case "HOMERUN": for i := 0; i < 3; i++ { if base[i] { score++ base[i] = false } } score++ case "OUT": out++ } if out >= 3 { fmt.Println(score) break } } } }
Yes
Do these codes solve the same problem? Code 1: using System; class MyClass { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int Out = 0; bool first = false; bool second = false; bool third = false; int point = 0; while (Out != n * 3) { switch (Console.ReadLine()) { case ("HIT"): if (third) { point++; third = false; } if (second) { third = true; second = false; } if (first) { second = true; } first = true; break; case ("HOMERUN"): if (first) { first = false; point++; } if (second) { second = false; point++; } if (third) { third = false; point++; } point++; break; case ("OUT"): Out++; if (Out % 3 == 0) { Console.WriteLine(point); point = 0; first = false; second = false; third = false; } break; default: break; } } } } Code 2: package main import ( "bufio" "fmt" "os" "strconv" ) func main() { stdin := bufio.NewScanner(os.Stdin) stdin.Scan() n, _ := strconv.Atoi(stdin.Text()) for i := 0; i < n; i++ { base := [3]bool{} score, out := 0, 0 for stdin.Scan() { switch stdin.Text() { case "HIT": if base[2] { // 3塁 score++ } if base[1] { // 2塁 base[2] = true base[1] = false } if base[0] { // 1塁 base[1] = true } base[0] = true case "HOMERUN": for i := 0; i < 3; i++ { if base[i] { score++ base[i] = false } } score++ case "OUT": out++ } if out >= 3 { fmt.Println(score) break } } } }
C++
#include <iostream> int main() { int r, g; std::cin >> r >> g; std::cout << 2 * g - r; }
Java
import java.awt.Point; import java.util.*; import java.io.*; import java.util.function.*; class Main { static Scanner scanner = new Scanner(); static int mod = 10007; static long inf = 0x7ffffffffffffffL; void solve() { int n = scanner.nextInt(); int m = scanner.nextInt(); SegmentTree segTree = new SegmentTree(n); segTree.setValue(1, n, inf); Map<Integer, List<Point>> map = new TreeMap<>(); for (int i = 0; i < m; i++) { int l = scanner.nextInt() - 1; int r = scanner.nextInt(); int c = scanner.nextInt(); map.computeIfAbsent(r, key -> new ArrayList<>()).add(new Point(l, c)); } for (Map.Entry<Integer, List<Point>> entry : map.entrySet()) { for (Point point : entry.getValue()) { segTree.changeMin(point.x, entry.getKey(), segTree.getMin(point.x, entry.getKey()) + point.y); } } System.out.println(segTree.get(n - 1) == inf ? -1 : segTree.get(n - 1)); } public static void main(String[]$) throws Exception { new Main().solve(); } } class SegmentTree { private int n; long[] min; long[] secondMin; long[] minCount; long[] max; long[] secondMax; long[] maxCount; long[] sum; long[] len; long[] ladd; long[] lvalue; SegmentTree(int n) { this(n, null); } SegmentTree(long[] a) { this(a.length, a); } private SegmentTree(int m, long[] a) { this.n = Integer.highestOneBit(m - 1) << 1; this.min = new long[n * 2]; this.secondMin = new long[n * 2]; this.minCount = new long[n * 2]; this.max = new long[n * 2]; this.secondMax = new long[n * 2]; this.maxCount = new long[n * 2]; this.sum = new long[n * 2]; this.len = new long[n * 2]; this.ladd = new long[n * 2]; this.lvalue = new long[n * 2]; for (int i = 0; i < n * 2; i++) { ladd[i] = 0; lvalue[i] = Main.inf; } len[0] = n; for (int i = 0; i < n - 1; i++) { len[i * 2 + 1] = len[i * 2 + 2] = len[i] >> 1; } for (int i = 0; i < n; i++) { if (i < m) { max[n - 1 + i] = min[n - 1 + i] = sum[n - 1 + i] = a == null ? 0 : a[i]; secondMax[n - 1 + i] = -Main.inf; secondMin[n - 1 + i] = Main.inf; maxCount[n - 1 + i] = minCount[n - 1 + i] = 1; } else { max[n - 1 + i] = secondMax[n - 1 + i] = -Main.inf; min[n - 1 + i] = secondMin[n - 1 + i] = Main.inf; maxCount[n - 1 + i] = minCount[n - 1 + i] = 0; } } for (int i = n - 2; i >= 0; i--) { update(i); } } void changeMin(int i, long x) { updateMin(x, i, i + 1, 0, 0, n); } void changeMax(int i, long x) { updateMax(x, i, i + 1, 0, 0, n); } void addValue(int i, long x) { addValue(x, i, i + 1, 0, 0, n); } void setValue(int i, long x) { updateValue(x, i, i + 1, 0, 0, n); } long getMin(int i) { return getMin(i, i + 1, 0, 0, n); } long getMax(int i) { return getMax(i, i + 1, 0, 0, n); } long get(int i) { return getSum(i, i + 1, 0, 0, n); } void changeMin(int l, int r, long x) { updateMin(x, l, r, 0, 0, n); } void changeMax(int l, int r, long x) { updateMax(x, l, r, 0, 0, n); } void addValue(int l, int r, long x) { addValue(x, l, r, 0, 0, n); } void setValue(int l, int r, long x) { updateValue(x, l, r, 0, 0, n); } long getMin(int l, int r) { return getMin(l, r, 0, 0, n); } long getMax(int l, int r) { return getMax(l, r, 0, 0, n); } long getSum(int l, int r) { return getSum(l, r, 0, 0, n); } private void updateNodeMin(int k, long x) { sum[k] += (x - min[k]) * minCount[k]; if (min[k] == max[k]) { min[k] = max[k] = x; } else if (min[k] == secondMax[k]) { min[k] = secondMax[k] = x; } else { min[k] = x; } if (lvalue[k] != Main.inf && lvalue[k] < x) { lvalue[k] = x; } } private void updateNodeMax(int k, long x) { sum[k] += (x - max[k]) * maxCount[k]; if (max[k] == min[k]) { max[k] = min[k] = x; } else if (max[k] == secondMin[k]) { max[k] = secondMin[k] = x; } else { max[k] = x; } if (lvalue[k] != Main.inf && x < lvalue[k]) { lvalue[k] = x; } } private void push(int k) { if (k < n - 1) { if (lvalue[k] != Main.inf) { updateAll(k * 2 + 1, lvalue[k]); updateAll(k * 2 + 2, lvalue[k]); lvalue[k] = Main.inf; } else { if (ladd[k] != 0) { addAll(k * 2 + 1, ladd[k]); addAll(k * 2 + 2, ladd[k]); ladd[k] = 0; } if (max[k] < max[k * 2 + 1]) { updateNodeMax(k * 2 + 1, max[k]); } if (min[k * 2 + 1] < min[k]) { updateNodeMin(k * 2 + 1, min[k]); } if (max[k] < max[k * 2 + 2]) { updateNodeMax(k * 2 + 2, max[k]); } if (min[k * 2 + 2] < min[k]) { updateNodeMin(k * 2 + 2, min[k]); } } } } private void update(int k) { sum[k] = sum[k * 2 + 1] + sum[k * 2 + 2]; if (max[k * 2 + 1] < max[k * 2 + 2]) { max[k] = max[k * 2 + 2]; maxCount[k] = maxCount[k * 2 + 2]; secondMax[k] = Math.max(max[k * 2 + 1], secondMax[k * 2 + 2]); } else if (max[k * 2 + 2] < max[k * 2 + 1]) { max[k] = max[k * 2 + 1]; maxCount[k] = maxCount[k * 2 + 1]; secondMax[k] = Math.max(secondMax[k * 2 + 1], max[k * 2 + 2]); } else { max[k] = max[k * 2 + 1]; maxCount[k] = maxCount[k * 2 + 1] + maxCount[k * 2 + 2]; secondMax[k] = Math.max(secondMax[k * 2 + 1], secondMax[k * 2 + 2]); } if (min[k * 2 + 1] < min[k * 2 + 2]) { min[k] = min[k * 2 + 1]; minCount[k] = minCount[k * 2 + 1]; secondMin[k] = Math.min(secondMax[k * 2 + 1], min[k * 2 + 2]); } else if (min[k * 2 + 2] < min[k * 2 + 1]) { min[k] = min[k * 2 + 2]; minCount[k] = minCount[k * 2 + 2]; secondMax[k] = Math.min(min[k * 2 + 1], secondMin[k * 2 + 2]); } else { min[k] = min[k * 2 + 1]; minCount[k] = minCount[k * 2 + 1] + minCount[k * 2 + 2]; secondMin[k] = Math.min(secondMin[k * 2 + 1], secondMin[k * 2 + 2]); } } private void updateMin(long x, int a, int b, int k, int l, int r) { if (l < b && a < r && x < max[k]) { if (a <= l && r <= b && secondMax[k] < x) { updateNodeMax(k, x); } else { push(k); updateMin(x, a, b, k * 2 + 1, l, (l + r) / 2); updateMin(x, a, b, k * 2 + 2, (l + r) / 2, r); update(k); } } } private void updateMax(long x, int a, int b, int k, int l, int r) { if (l < b && a < r && min[k] < x) { if (a <= l && r <= b && x < secondMin[k]) { updateNodeMin(k, x); } else { push(k); updateMax(x, a, b, k * 2 + 1, l, (l + r) / 2); updateMax(x, a, b, k * 2 + 2, (l + r) / 2, r); update(k); } } } private void addAll(int k, long x) { max[k] += x; if (secondMax[k] != -Main.inf) { secondMax[k] += x; } min[k] += x; if (secondMin[k] != Main.inf) { secondMin[k] += x; } sum[k] += len[k] * x; if (lvalue[k] != Main.inf) { lvalue[k] += x; } else { ladd[k] += x; } } private void updateAll(int k, long x) { max[k] = x; secondMax[k] = -Main.inf; min[k] = x; secondMin[k] = Main.inf; maxCount[k] = minCount[k] = len[k]; sum[k] = x * len[k]; lvalue[k] = x; ladd[k] = 0; } private void addValue(long x, int a, int b, int k, int l, int r) { if (l < b && a < r) { if (a <= l && r <= b) { addAll(k, x); } else { push(k); addValue(x, a, b, k * 2 + 1, l, (l + r) / 2); addValue(x, a, b, k * 2 + 2, (l + r) / 2, r); update(k); } } } private void updateValue(long x, int a, int b, int k, int l, int r) { if (l < b && a < r) { if (a <= l && r <= b) { updateAll(k, x); } else { push(k); updateValue(x, a, b, k * 2 + 1, l, (l + r) / 2); updateValue(x, a, b, k * 2 + 2, (l + r) / 2, r); update(k); } } } private long getMin(int a, int b, int k, int l, int r) { if (b <= l || r <= a) { return Main.inf; } if (a <= l && r <= b) { return min[k]; } push(k); long lv = getMin(a, b, k * 2 + 1, l, (l + r) / 2); long rv = getMin(a, b, k * 2 + 2, (l + r) / 2, r); return Math.min(lv, rv); } private long getMax(int a, int b, int k, int l, int r) { if (b <= l || r <= a) { return -Main.inf; } if (a <= l && r <= b) { return max[k]; } push(k); long lv = getMax(a, b, k * 2 + 1, l, (l + r) / 2); long rv = getMax(a, b, k * 2 + 2, (l + r) / 2, r); return Math.max(lv, rv); } private long getSum(int a, int b, int k, int l, int r) { if (b <= l || r <= a) { return 0; } if (a <= l && r <= b) { return sum[k]; } push(k); long lv = getSum(a, b, k * 2 + 1, l, (l + r) / 2); long rv = getSum(a, b, k * 2 + 2, (l + r) / 2, r); return lv + rv; } } class System { static PrintWriter out = new PrintWriter(java.lang.System.out); static { Runtime.getRuntime().addShutdownHook(new Thread(System.out::flush)); } static void exit() { java.lang.System.exit(0); } } class Scanner { private BufferedReader reader = new BufferedReader(new InputStreamReader(java.lang.System.in), 0x10000); private StringTokenizer tokenizer; String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException ignored) { } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } char[][] nextCharArray(int n, int m) { char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { a[i] = next().toCharArray(); } return a; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArray(int n, IntUnaryOperator op) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsInt(nextInt()); } return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArray(int n, LongUnaryOperator op) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsLong(nextLong()); } return a; } }
No
Do these codes solve the same problem? Code 1: #include <iostream> int main() { int r, g; std::cin >> r >> g; std::cout << 2 * g - r; } Code 2: import java.awt.Point; import java.util.*; import java.io.*; import java.util.function.*; class Main { static Scanner scanner = new Scanner(); static int mod = 10007; static long inf = 0x7ffffffffffffffL; void solve() { int n = scanner.nextInt(); int m = scanner.nextInt(); SegmentTree segTree = new SegmentTree(n); segTree.setValue(1, n, inf); Map<Integer, List<Point>> map = new TreeMap<>(); for (int i = 0; i < m; i++) { int l = scanner.nextInt() - 1; int r = scanner.nextInt(); int c = scanner.nextInt(); map.computeIfAbsent(r, key -> new ArrayList<>()).add(new Point(l, c)); } for (Map.Entry<Integer, List<Point>> entry : map.entrySet()) { for (Point point : entry.getValue()) { segTree.changeMin(point.x, entry.getKey(), segTree.getMin(point.x, entry.getKey()) + point.y); } } System.out.println(segTree.get(n - 1) == inf ? -1 : segTree.get(n - 1)); } public static void main(String[]$) throws Exception { new Main().solve(); } } class SegmentTree { private int n; long[] min; long[] secondMin; long[] minCount; long[] max; long[] secondMax; long[] maxCount; long[] sum; long[] len; long[] ladd; long[] lvalue; SegmentTree(int n) { this(n, null); } SegmentTree(long[] a) { this(a.length, a); } private SegmentTree(int m, long[] a) { this.n = Integer.highestOneBit(m - 1) << 1; this.min = new long[n * 2]; this.secondMin = new long[n * 2]; this.minCount = new long[n * 2]; this.max = new long[n * 2]; this.secondMax = new long[n * 2]; this.maxCount = new long[n * 2]; this.sum = new long[n * 2]; this.len = new long[n * 2]; this.ladd = new long[n * 2]; this.lvalue = new long[n * 2]; for (int i = 0; i < n * 2; i++) { ladd[i] = 0; lvalue[i] = Main.inf; } len[0] = n; for (int i = 0; i < n - 1; i++) { len[i * 2 + 1] = len[i * 2 + 2] = len[i] >> 1; } for (int i = 0; i < n; i++) { if (i < m) { max[n - 1 + i] = min[n - 1 + i] = sum[n - 1 + i] = a == null ? 0 : a[i]; secondMax[n - 1 + i] = -Main.inf; secondMin[n - 1 + i] = Main.inf; maxCount[n - 1 + i] = minCount[n - 1 + i] = 1; } else { max[n - 1 + i] = secondMax[n - 1 + i] = -Main.inf; min[n - 1 + i] = secondMin[n - 1 + i] = Main.inf; maxCount[n - 1 + i] = minCount[n - 1 + i] = 0; } } for (int i = n - 2; i >= 0; i--) { update(i); } } void changeMin(int i, long x) { updateMin(x, i, i + 1, 0, 0, n); } void changeMax(int i, long x) { updateMax(x, i, i + 1, 0, 0, n); } void addValue(int i, long x) { addValue(x, i, i + 1, 0, 0, n); } void setValue(int i, long x) { updateValue(x, i, i + 1, 0, 0, n); } long getMin(int i) { return getMin(i, i + 1, 0, 0, n); } long getMax(int i) { return getMax(i, i + 1, 0, 0, n); } long get(int i) { return getSum(i, i + 1, 0, 0, n); } void changeMin(int l, int r, long x) { updateMin(x, l, r, 0, 0, n); } void changeMax(int l, int r, long x) { updateMax(x, l, r, 0, 0, n); } void addValue(int l, int r, long x) { addValue(x, l, r, 0, 0, n); } void setValue(int l, int r, long x) { updateValue(x, l, r, 0, 0, n); } long getMin(int l, int r) { return getMin(l, r, 0, 0, n); } long getMax(int l, int r) { return getMax(l, r, 0, 0, n); } long getSum(int l, int r) { return getSum(l, r, 0, 0, n); } private void updateNodeMin(int k, long x) { sum[k] += (x - min[k]) * minCount[k]; if (min[k] == max[k]) { min[k] = max[k] = x; } else if (min[k] == secondMax[k]) { min[k] = secondMax[k] = x; } else { min[k] = x; } if (lvalue[k] != Main.inf && lvalue[k] < x) { lvalue[k] = x; } } private void updateNodeMax(int k, long x) { sum[k] += (x - max[k]) * maxCount[k]; if (max[k] == min[k]) { max[k] = min[k] = x; } else if (max[k] == secondMin[k]) { max[k] = secondMin[k] = x; } else { max[k] = x; } if (lvalue[k] != Main.inf && x < lvalue[k]) { lvalue[k] = x; } } private void push(int k) { if (k < n - 1) { if (lvalue[k] != Main.inf) { updateAll(k * 2 + 1, lvalue[k]); updateAll(k * 2 + 2, lvalue[k]); lvalue[k] = Main.inf; } else { if (ladd[k] != 0) { addAll(k * 2 + 1, ladd[k]); addAll(k * 2 + 2, ladd[k]); ladd[k] = 0; } if (max[k] < max[k * 2 + 1]) { updateNodeMax(k * 2 + 1, max[k]); } if (min[k * 2 + 1] < min[k]) { updateNodeMin(k * 2 + 1, min[k]); } if (max[k] < max[k * 2 + 2]) { updateNodeMax(k * 2 + 2, max[k]); } if (min[k * 2 + 2] < min[k]) { updateNodeMin(k * 2 + 2, min[k]); } } } } private void update(int k) { sum[k] = sum[k * 2 + 1] + sum[k * 2 + 2]; if (max[k * 2 + 1] < max[k * 2 + 2]) { max[k] = max[k * 2 + 2]; maxCount[k] = maxCount[k * 2 + 2]; secondMax[k] = Math.max(max[k * 2 + 1], secondMax[k * 2 + 2]); } else if (max[k * 2 + 2] < max[k * 2 + 1]) { max[k] = max[k * 2 + 1]; maxCount[k] = maxCount[k * 2 + 1]; secondMax[k] = Math.max(secondMax[k * 2 + 1], max[k * 2 + 2]); } else { max[k] = max[k * 2 + 1]; maxCount[k] = maxCount[k * 2 + 1] + maxCount[k * 2 + 2]; secondMax[k] = Math.max(secondMax[k * 2 + 1], secondMax[k * 2 + 2]); } if (min[k * 2 + 1] < min[k * 2 + 2]) { min[k] = min[k * 2 + 1]; minCount[k] = minCount[k * 2 + 1]; secondMin[k] = Math.min(secondMax[k * 2 + 1], min[k * 2 + 2]); } else if (min[k * 2 + 2] < min[k * 2 + 1]) { min[k] = min[k * 2 + 2]; minCount[k] = minCount[k * 2 + 2]; secondMax[k] = Math.min(min[k * 2 + 1], secondMin[k * 2 + 2]); } else { min[k] = min[k * 2 + 1]; minCount[k] = minCount[k * 2 + 1] + minCount[k * 2 + 2]; secondMin[k] = Math.min(secondMin[k * 2 + 1], secondMin[k * 2 + 2]); } } private void updateMin(long x, int a, int b, int k, int l, int r) { if (l < b && a < r && x < max[k]) { if (a <= l && r <= b && secondMax[k] < x) { updateNodeMax(k, x); } else { push(k); updateMin(x, a, b, k * 2 + 1, l, (l + r) / 2); updateMin(x, a, b, k * 2 + 2, (l + r) / 2, r); update(k); } } } private void updateMax(long x, int a, int b, int k, int l, int r) { if (l < b && a < r && min[k] < x) { if (a <= l && r <= b && x < secondMin[k]) { updateNodeMin(k, x); } else { push(k); updateMax(x, a, b, k * 2 + 1, l, (l + r) / 2); updateMax(x, a, b, k * 2 + 2, (l + r) / 2, r); update(k); } } } private void addAll(int k, long x) { max[k] += x; if (secondMax[k] != -Main.inf) { secondMax[k] += x; } min[k] += x; if (secondMin[k] != Main.inf) { secondMin[k] += x; } sum[k] += len[k] * x; if (lvalue[k] != Main.inf) { lvalue[k] += x; } else { ladd[k] += x; } } private void updateAll(int k, long x) { max[k] = x; secondMax[k] = -Main.inf; min[k] = x; secondMin[k] = Main.inf; maxCount[k] = minCount[k] = len[k]; sum[k] = x * len[k]; lvalue[k] = x; ladd[k] = 0; } private void addValue(long x, int a, int b, int k, int l, int r) { if (l < b && a < r) { if (a <= l && r <= b) { addAll(k, x); } else { push(k); addValue(x, a, b, k * 2 + 1, l, (l + r) / 2); addValue(x, a, b, k * 2 + 2, (l + r) / 2, r); update(k); } } } private void updateValue(long x, int a, int b, int k, int l, int r) { if (l < b && a < r) { if (a <= l && r <= b) { updateAll(k, x); } else { push(k); updateValue(x, a, b, k * 2 + 1, l, (l + r) / 2); updateValue(x, a, b, k * 2 + 2, (l + r) / 2, r); update(k); } } } private long getMin(int a, int b, int k, int l, int r) { if (b <= l || r <= a) { return Main.inf; } if (a <= l && r <= b) { return min[k]; } push(k); long lv = getMin(a, b, k * 2 + 1, l, (l + r) / 2); long rv = getMin(a, b, k * 2 + 2, (l + r) / 2, r); return Math.min(lv, rv); } private long getMax(int a, int b, int k, int l, int r) { if (b <= l || r <= a) { return -Main.inf; } if (a <= l && r <= b) { return max[k]; } push(k); long lv = getMax(a, b, k * 2 + 1, l, (l + r) / 2); long rv = getMax(a, b, k * 2 + 2, (l + r) / 2, r); return Math.max(lv, rv); } private long getSum(int a, int b, int k, int l, int r) { if (b <= l || r <= a) { return 0; } if (a <= l && r <= b) { return sum[k]; } push(k); long lv = getSum(a, b, k * 2 + 1, l, (l + r) / 2); long rv = getSum(a, b, k * 2 + 2, (l + r) / 2, r); return lv + rv; } } class System { static PrintWriter out = new PrintWriter(java.lang.System.out); static { Runtime.getRuntime().addShutdownHook(new Thread(System.out::flush)); } static void exit() { java.lang.System.exit(0); } } class Scanner { private BufferedReader reader = new BufferedReader(new InputStreamReader(java.lang.System.in), 0x10000); private StringTokenizer tokenizer; String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException ignored) { } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } char[][] nextCharArray(int n, int m) { char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { a[i] = next().toCharArray(); } return a; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArray(int n, IntUnaryOperator op) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsInt(nextInt()); } return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArray(int n, LongUnaryOperator op) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsLong(nextLong()); } return a; } }
TypeScript
import * as fs from "fs"; let input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n"); const n = +input[0]; const f = []; for (let i = 0; i < n; i++) { f.push(Number.parseInt(input[i + 1].replace(/\s/g, ""), 2)); } const p = []; for (let i = 0; i < n; i++) { p.push(input[i + n + 1].split(" ").map((x: string): number => +x)); } const bitCount = (i: number) => { i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }; let result = -Infinity; for (let time = 1; time < 0b10000000000; time++) { let profit = 0; for (let i = 0; i < n; i++) { const ci = bitCount(f[i] & time); profit += p[i][ci]; } if (profit > result) { result = profit; } } console.log(result);
Go
package main import ( "bufio" "fmt" "os" "strconv" ) const ( maxN = 110 ) var F [maxN][5][2]int var P [maxN][11]int func main() { fsc := NewFastScanner() N := fsc.NextInt() for i := 0; i < N; i++ { for j := 0; j < 5; j++ { for k := 0; k < 2; k++ { F[i][j][k] = fsc.NextInt() } } } for i := 0; i < N; i++ { for j := 0; j < 11; j++ { P[i][j] = fsc.NextInt() } } result := -10000000000 for bit := 1; bit < (1 << 10); bit++ { open := make([]int, 0) for i := 0; i < 10; i++ { if ((bit >> uint(i)) & 1) == 1 { open = append(open, 1) } else { open = append(open, 0) } } sum := 0 for i := 0; i < N; i++ { cnt := 0 for j := 0; j < 5; j++ { for k := 0; k < 2; k++ { if F[i][j][k] == 1 && open[2*j+k] == 1 { cnt++ } } } sum += P[i][cnt] } result = IntMax(result, sum) } fmt.Println(result) } //template type FastScanner struct { r *bufio.Reader buf []byte p int } func NewFastScanner() *FastScanner { rdr := bufio.NewReaderSize(os.Stdin, 1024) return &FastScanner{r: rdr} } func (s *FastScanner) Next() string { s.pre() start := s.p for ; s.p < len(s.buf); s.p++ { if s.buf[s.p] == ' ' { break } } result := string(s.buf[start:s.p]) s.p++ return result } func (s *FastScanner) NextLine() string { s.pre() start := s.p s.p = len(s.buf) return string(s.buf[start:]) } func (s *FastScanner) NextInt() int { v, _ := strconv.Atoi(s.Next()) return v } func (s *FastScanner) NextInt64() int64 { v, _ := strconv.ParseInt(s.Next(), 10, 64) return v } func (s *FastScanner) pre() { if s.p >= len(s.buf) { s.readLine() s.p = 0 } } func (s *FastScanner) readLine() { s.buf = make([]byte, 0) for { l, p, e := s.r.ReadLine() if e != nil { panic(e) } s.buf = append(s.buf, l...) if !p { break } } } //Max,Min func IntMax(a, b int) int { if a < b { return b } return a } func Int64Max(a, b int64) int64 { if a < b { return b } return a } func Float64Max(a, b float64) float64 { if a < b { return b } return a } func IntMin(a, b int) int { if a > b { return b } return a } func Int64Min(a, b int64) int64 { if a > b { return b } return a } func Float64Min(a, b float64) float64 { if a > b { return b } return a } //Gcd func IntGcd(a, b int) int { if a < b { b, a = a, b } if b == 0 { return a } return IntGcd(b, a%b) } func Int64Gcd(a, b int64) int64 { if a < b { b, a = a, b } if b == 0 { return a } return Int64Gcd(b, a%b) } func IntAbs(a int) int { if a < 0 { a *= -1 } return a } func Int64Abs(a int64) int64 { if a < 0 { a *= -1 } return a }
Yes
Do these codes solve the same problem? Code 1: import * as fs from "fs"; let input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n"); const n = +input[0]; const f = []; for (let i = 0; i < n; i++) { f.push(Number.parseInt(input[i + 1].replace(/\s/g, ""), 2)); } const p = []; for (let i = 0; i < n; i++) { p.push(input[i + n + 1].split(" ").map((x: string): number => +x)); } const bitCount = (i: number) => { i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }; let result = -Infinity; for (let time = 1; time < 0b10000000000; time++) { let profit = 0; for (let i = 0; i < n; i++) { const ci = bitCount(f[i] & time); profit += p[i][ci]; } if (profit > result) { result = profit; } } console.log(result); Code 2: package main import ( "bufio" "fmt" "os" "strconv" ) const ( maxN = 110 ) var F [maxN][5][2]int var P [maxN][11]int func main() { fsc := NewFastScanner() N := fsc.NextInt() for i := 0; i < N; i++ { for j := 0; j < 5; j++ { for k := 0; k < 2; k++ { F[i][j][k] = fsc.NextInt() } } } for i := 0; i < N; i++ { for j := 0; j < 11; j++ { P[i][j] = fsc.NextInt() } } result := -10000000000 for bit := 1; bit < (1 << 10); bit++ { open := make([]int, 0) for i := 0; i < 10; i++ { if ((bit >> uint(i)) & 1) == 1 { open = append(open, 1) } else { open = append(open, 0) } } sum := 0 for i := 0; i < N; i++ { cnt := 0 for j := 0; j < 5; j++ { for k := 0; k < 2; k++ { if F[i][j][k] == 1 && open[2*j+k] == 1 { cnt++ } } } sum += P[i][cnt] } result = IntMax(result, sum) } fmt.Println(result) } //template type FastScanner struct { r *bufio.Reader buf []byte p int } func NewFastScanner() *FastScanner { rdr := bufio.NewReaderSize(os.Stdin, 1024) return &FastScanner{r: rdr} } func (s *FastScanner) Next() string { s.pre() start := s.p for ; s.p < len(s.buf); s.p++ { if s.buf[s.p] == ' ' { break } } result := string(s.buf[start:s.p]) s.p++ return result } func (s *FastScanner) NextLine() string { s.pre() start := s.p s.p = len(s.buf) return string(s.buf[start:]) } func (s *FastScanner) NextInt() int { v, _ := strconv.Atoi(s.Next()) return v } func (s *FastScanner) NextInt64() int64 { v, _ := strconv.ParseInt(s.Next(), 10, 64) return v } func (s *FastScanner) pre() { if s.p >= len(s.buf) { s.readLine() s.p = 0 } } func (s *FastScanner) readLine() { s.buf = make([]byte, 0) for { l, p, e := s.r.ReadLine() if e != nil { panic(e) } s.buf = append(s.buf, l...) if !p { break } } } //Max,Min func IntMax(a, b int) int { if a < b { return b } return a } func Int64Max(a, b int64) int64 { if a < b { return b } return a } func Float64Max(a, b float64) float64 { if a < b { return b } return a } func IntMin(a, b int) int { if a > b { return b } return a } func Int64Min(a, b int64) int64 { if a > b { return b } return a } func Float64Min(a, b float64) float64 { if a > b { return b } return a } //Gcd func IntGcd(a, b int) int { if a < b { b, a = a, b } if b == 0 { return a } return IntGcd(b, a%b) } func Int64Gcd(a, b int64) int64 { if a < b { b, a = a, b } if b == 0 { return a } return Int64Gcd(b, a%b) } func IntAbs(a int) int { if a < 0 { a *= -1 } return a } func Int64Abs(a int64) int64 { if a < 0 { a *= -1 } return a }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int i,j,c,g,tim,head,last; int wait[101],seat[17]; int main(){ last=-1; while(head<100){ if(tim%5==0 && last<100)last++; for(i=0;i<17;i++)if(seat[i]>0)seat[i]--; for(g=head;g<=last;g++){ c=0; for(i=0;i<17;i++){ if(seat[i]>0)c=0; else c++; if(c == (g%5==1?5:2) ) break; } if(i<17){ for(c--;c>=0;c--)seat[i-c]=17*(g%2)+3*(g%3)+19; head++; } else break; } for(g=head;g<=last;g++)wait[g]++; tim++; } while(scanf("%d",&g)!=EOF)printf("%d\n",wait[g]); return 0; }
JavaScript
// 標準入力 var fs = require('fs'), length = fs.fstatSync(process.stdin.fd).size, buffer = new Buffer(length), bytesRead = fs.readSync(process.stdin.fd, buffer, 0, length, 0), input = buffer.toString('utf8', 0, bytesRead).split('\n'); main(); function main(){ var waitTime = calc(); for(var i = 0, len = input.length - 1; i < len;i++){ console.log(waitTime[parseInt(input[i], 10)]); } } function calc(){ var seats = new Int32Array(17); var groupMembers = new Int32Array([2,5,2,2,2]); var eatTimes = new Int32Array([19,39,25,36,22,42]); var headGroup = -1; var pastMinutes = 0; var waitTime = new Int32Array(100); var lastMembers = 100; while(true){ // たべおわる var i; for(i = 17; i--;){ seats[i] = max(--seats[i], 0); } // 来店 if(headGroup == -1 && pastMinutes % 5 == 0){ headGroup = pastMinutes / 5; } // ちゃくせき while(headGroup != -1 && i != 17){ var needsSequencialSeats = groupMembers[headGroup % 5]; var sequencialSeats = 0; var startIndex = -1; for(i = 0; i < 17; i++){ sequencialSeats = seats[i] == 0 ? sequencialSeats + 1 : 0; if(sequencialSeats == needsSequencialSeats){ var eatTime = eatTimes[headGroup % 6]; startIndex = i - (needsSequencialSeats - 1); // すわれるみたい waitTime[headGroup] = pastMinutes - (headGroup * 5); for(var j = startIndex, len = (needsSequencialSeats + startIndex); j < len; j++){ seats[j] = eatTime; } headGroup = (((headGroup + 1) * 5) <= pastMinutes) ? headGroup + 1 : -1; if(!(--lastMembers)){ // 100グループ着席 return waitTime; } break; } } } pastMinutes++; } } function max(a, b){ var t = (a - b); return a - (t & (t >> 31)); }
Yes
Do these codes solve the same problem? Code 1: #include <stdio.h> #include <string.h> #include <stdlib.h> int i,j,c,g,tim,head,last; int wait[101],seat[17]; int main(){ last=-1; while(head<100){ if(tim%5==0 && last<100)last++; for(i=0;i<17;i++)if(seat[i]>0)seat[i]--; for(g=head;g<=last;g++){ c=0; for(i=0;i<17;i++){ if(seat[i]>0)c=0; else c++; if(c == (g%5==1?5:2) ) break; } if(i<17){ for(c--;c>=0;c--)seat[i-c]=17*(g%2)+3*(g%3)+19; head++; } else break; } for(g=head;g<=last;g++)wait[g]++; tim++; } while(scanf("%d",&g)!=EOF)printf("%d\n",wait[g]); return 0; } Code 2: // 標準入力 var fs = require('fs'), length = fs.fstatSync(process.stdin.fd).size, buffer = new Buffer(length), bytesRead = fs.readSync(process.stdin.fd, buffer, 0, length, 0), input = buffer.toString('utf8', 0, bytesRead).split('\n'); main(); function main(){ var waitTime = calc(); for(var i = 0, len = input.length - 1; i < len;i++){ console.log(waitTime[parseInt(input[i], 10)]); } } function calc(){ var seats = new Int32Array(17); var groupMembers = new Int32Array([2,5,2,2,2]); var eatTimes = new Int32Array([19,39,25,36,22,42]); var headGroup = -1; var pastMinutes = 0; var waitTime = new Int32Array(100); var lastMembers = 100; while(true){ // たべおわる var i; for(i = 17; i--;){ seats[i] = max(--seats[i], 0); } // 来店 if(headGroup == -1 && pastMinutes % 5 == 0){ headGroup = pastMinutes / 5; } // ちゃくせき while(headGroup != -1 && i != 17){ var needsSequencialSeats = groupMembers[headGroup % 5]; var sequencialSeats = 0; var startIndex = -1; for(i = 0; i < 17; i++){ sequencialSeats = seats[i] == 0 ? sequencialSeats + 1 : 0; if(sequencialSeats == needsSequencialSeats){ var eatTime = eatTimes[headGroup % 6]; startIndex = i - (needsSequencialSeats - 1); // すわれるみたい waitTime[headGroup] = pastMinutes - (headGroup * 5); for(var j = startIndex, len = (needsSequencialSeats + startIndex); j < len; j++){ seats[j] = eatTime; } headGroup = (((headGroup + 1) * 5) <= pastMinutes) ? headGroup + 1 : -1; if(!(--lastMembers)){ // 100グループ着席 return waitTime; } break; } } } pastMinutes++; } } function max(a, b){ var t = (a - b); return a - (t & (t >> 31)); }
C++
// ABC067_A.cpp : Defines the entry point for the console application. // #include <iostream> #include <algorithm> using namespace std; int main() { int r, g, b; cin >> r >> g >> b; if ((r * 100 + g * 10 + b) % 4 == 0) { cout << "YES" << endl; return 0; } cout << "NO" << endl; return 0; }
Python
import math def inputIntList(): return [int(s) for s in input().split()] def inputInt(): return int(input()) def main(): N, capacity = inputIntList() w = [0 for _ in range(N)] v = [0 for _ in range(N)] for i in range(N): w[i], v[i] = inputIntList() dp = [[0 for _ in range(capacity + 1)] for _ in range(N + 1)] for i in range(N): for j in range(capacity + 1): if j < w[i]: dp[i + 1][j] = dp[i][j] else: dp[i + 1][j] = max(dp[i][j - w[i]] + v[i], dp[i][j]) # print(dp) return dp[N][capacity] if __name__ == "__main__": print(main())
No
Do these codes solve the same problem? Code 1: // ABC067_A.cpp : Defines the entry point for the console application. // #include <iostream> #include <algorithm> using namespace std; int main() { int r, g, b; cin >> r >> g >> b; if ((r * 100 + g * 10 + b) % 4 == 0) { cout << "YES" << endl; return 0; } cout << "NO" << endl; return 0; } Code 2: import math def inputIntList(): return [int(s) for s in input().split()] def inputInt(): return int(input()) def main(): N, capacity = inputIntList() w = [0 for _ in range(N)] v = [0 for _ in range(N)] for i in range(N): w[i], v[i] = inputIntList() dp = [[0 for _ in range(capacity + 1)] for _ in range(N + 1)] for i in range(N): for j in range(capacity + 1): if j < w[i]: dp[i + 1][j] = dp[i][j] else: dp[i + 1][j] = max(dp[i][j - w[i]] + v[i], dp[i][j]) # print(dp) return dp[N][capacity] if __name__ == "__main__": print(main())
C++
#include <iostream> using namespace std; int main() { int N; int count = 0, res = 0; cin >> N; for (int i = 1; i <= N; i = i + 2) { for (int j = 1; j <= i; j++) { if (i%j == 0) count++; } if (count == 8) res ++; count = 0; } cout << res << endl; return 0; }
C
#include <stdio.h> int main(){ int n, a[100], i; scanf("%d",&n); for (i=0;i<n;i++) scanf("%d",&a[i]); for(i=n-1;i>=0;i--) { if(i==0) printf("%d\n",a[i]); else printf("%d ",a[i]); } return 0; }
No
Do these codes solve the same problem? Code 1: #include <iostream> using namespace std; int main() { int N; int count = 0, res = 0; cin >> N; for (int i = 1; i <= N; i = i + 2) { for (int j = 1; j <= i; j++) { if (i%j == 0) count++; } if (count == 8) res ++; count = 0; } cout << res << endl; return 0; } Code 2: #include <stdio.h> int main(){ int n, a[100], i; scanf("%d",&n); for (i=0;i<n;i++) scanf("%d",&a[i]); for(i=n-1;i>=0;i--) { if(i==0) printf("%d\n",a[i]); else printf("%d ",a[i]); } return 0; }
JavaScript
'use strict' function main(input) { input = Number(input) let ans = (input < 1000) ? 'C' : 'D' console.log('AB' + ans) } main(require("fs").readFileSync("/dev/stdin", "utf8"));
Python
n, x = [int(i) for i in input().split()] b = [1] for _ in range(n + 1): b.append(b[-1] * 2 + 3) c = [1] for _ in range(n + 1): c.append(c[-1] * 2 + 1) def a(x, n): if x == 0: return 0 if n == 0: return c[0] x-=1 ans = 0 if x >= b[n - 1]: ans += c[n - 1] x -= b[n - 1] else: return a(x, n - 1) if x == 0: return ans elif x == 1: return ans + 1 else: ans += 1 x -= 1 ans += a(x, n - 1) return ans print(a(x,n))
No
Do these codes solve the same problem? Code 1: 'use strict' function main(input) { input = Number(input) let ans = (input < 1000) ? 'C' : 'D' console.log('AB' + ans) } main(require("fs").readFileSync("/dev/stdin", "utf8")); Code 2: n, x = [int(i) for i in input().split()] b = [1] for _ in range(n + 1): b.append(b[-1] * 2 + 3) c = [1] for _ in range(n + 1): c.append(c[-1] * 2 + 1) def a(x, n): if x == 0: return 0 if n == 0: return c[0] x-=1 ans = 0 if x >= b[n - 1]: ans += c[n - 1] x -= b[n - 1] else: return a(x, n - 1) if x == 0: return ans elif x == 1: return ans + 1 else: ans += 1 x -= 1 ans += a(x, n - 1) return ans print(a(x,n))