Dataset Viewer
Auto-converted to Parquet
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; }
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
0