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 <iostream>
using namespace std;
int main(){
int x;
for(int i=1;i>=1;i++){
cin >> x;
if(x==0){
break;
}
cout << "Case " << i <<": "<< x <<endl;
}
return 0;
}
| Python | import sys
#a = open("test.txt", "r")
a = sys.stdin
count = 1
for line in a:
if int(line) == 0:
break
print("Case {0}: {1}".format(count, line), end="")
count = count + 1 | Yes | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int main(){
int x;
for(int i=1;i>=1;i++){
cin >> x;
if(x==0){
break;
}
cout << "Case " << i <<": "<< x <<endl;
}
return 0;
}
Code 2: import sys
#a = open("test.txt", "r")
a = sys.stdin
count = 1
for line in a:
if int(line) == 0:
break
print("Case {0}: {1}".format(count, line), end="")
count = count + 1 |
Python | import sys
from collections import deque
import copy
import math
def get_read_func(fileobject):
if fileobject == None :
return raw_input
else:
return fileobject.readline
def prime_decomposition(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n /= i
table.append(i)
i += 1
if n > 1:
table.append(n)
return table
def power_func(a,b,p):
if b==0: return 1
if b%2==0:
d=power_func(a,b//2,p)
return d*d %p
if b%2==1:
return (a*power_func(a,b-1,p ))%p
class comb_calclator():
def __init__(self, N, p):
self.N = N
self.p = p
self.frac_N = [0 for i in range(N + 1)]
self.frac_N[0] = 1L
self.comb_N = {}
for i in range(1, N + 1):
self.frac_N[i] = (self.frac_N[i - 1] * i ) % p
def comb(self, n, r):
if n<0 or r<0 or n<r: return 0
if n==0 or r==0: return 1
if (n, r) in self.comb_N:
return self.comb_N[(n, r)]
a = self.frac_N[n]
b = self.frac_N[r]
c = self.frac_N[n - r]
self.comb_N[(n, r)] = (a*power_func(b,self.p-2,self.p)*power_func(c,self.p-2, self.p))% self.p
self.comb_N[(n, n - r)] = self.comb_N[(n, r)]
return self.comb_N[(n, r)]
def main():
if len(sys.argv) > 1:
f = open(sys.argv[1])
else:
f = None
read_func = get_read_func(f);
input_raw = read_func().strip().split()
[N, M] = [int(input_raw[0]), long(input_raw[1])]
prime = prime_decomposition(M)
prime_num = {}
for p in prime:
if p not in prime_num:
prime_num[p] = 1
else:
prime_num[p] += 1
cmb = comb_calclator(N * 10, 1000000007)
count = 1L
for p in prime_num:
count = (count * cmb.comb(N + prime_num[p]- 1, prime_num[p])) % 1000000007
print count
if __name__ == '__main__':
main()
| C++ | #include<bits/stdc++.h>
using namespace std;
#define N (200010)
#define ll long long
int n,mx,a[N],now[N];
vector<int>G[N],ans;
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
for (int i=1;i<=n;i++){
for (int j=2;i*j<=n;j++) G[i*j].push_back(i);
}
for (int i=n;i>=1;i--){
if (now[i]!=a[i]){
for (int j=0;j<G[i].size();j++)
now[G[i][j]]=!now[G[i][j]];
ans.push_back(i);
}
}
printf("%d\n",ans.size());
for (int i=ans.size()-1;i>=0;i--) printf("%d ",ans[i]);
}
| No | Do these codes solve the same problem?
Code 1: import sys
from collections import deque
import copy
import math
def get_read_func(fileobject):
if fileobject == None :
return raw_input
else:
return fileobject.readline
def prime_decomposition(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n /= i
table.append(i)
i += 1
if n > 1:
table.append(n)
return table
def power_func(a,b,p):
if b==0: return 1
if b%2==0:
d=power_func(a,b//2,p)
return d*d %p
if b%2==1:
return (a*power_func(a,b-1,p ))%p
class comb_calclator():
def __init__(self, N, p):
self.N = N
self.p = p
self.frac_N = [0 for i in range(N + 1)]
self.frac_N[0] = 1L
self.comb_N = {}
for i in range(1, N + 1):
self.frac_N[i] = (self.frac_N[i - 1] * i ) % p
def comb(self, n, r):
if n<0 or r<0 or n<r: return 0
if n==0 or r==0: return 1
if (n, r) in self.comb_N:
return self.comb_N[(n, r)]
a = self.frac_N[n]
b = self.frac_N[r]
c = self.frac_N[n - r]
self.comb_N[(n, r)] = (a*power_func(b,self.p-2,self.p)*power_func(c,self.p-2, self.p))% self.p
self.comb_N[(n, n - r)] = self.comb_N[(n, r)]
return self.comb_N[(n, r)]
def main():
if len(sys.argv) > 1:
f = open(sys.argv[1])
else:
f = None
read_func = get_read_func(f);
input_raw = read_func().strip().split()
[N, M] = [int(input_raw[0]), long(input_raw[1])]
prime = prime_decomposition(M)
prime_num = {}
for p in prime:
if p not in prime_num:
prime_num[p] = 1
else:
prime_num[p] += 1
cmb = comb_calclator(N * 10, 1000000007)
count = 1L
for p in prime_num:
count = (count * cmb.comb(N + prime_num[p]- 1, prime_num[p])) % 1000000007
print count
if __name__ == '__main__':
main()
Code 2: #include<bits/stdc++.h>
using namespace std;
#define N (200010)
#define ll long long
int n,mx,a[N],now[N];
vector<int>G[N],ans;
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
for (int i=1;i<=n;i++){
for (int j=2;i*j<=n;j++) G[i*j].push_back(i);
}
for (int i=n;i>=1;i--){
if (now[i]!=a[i]){
for (int j=0;j<G[i].size();j++)
now[G[i][j]]=!now[G[i][j]];
ans.push_back(i);
}
}
printf("%d\n",ans.size());
for (int i=ans.size()-1;i>=0;i--) printf("%d ",ans[i]);
}
|
Python | from bisect import bisect_left, bisect_right
n = int(input())
a = list(map(int, input().split()))
q = int(input())
for i in range(q):
k = int(input())
print(bisect_left(a, k), bisect_right(a, k))
| Java | import java.util.*;
import java.io.*;
public class Main {
void solve (FastScanner in, PrintWriter out, Methods ms) {
int n = in.nextInt();
Integer[] a = new Integer[n];
for (int i=0; i<n; i++) a[i] = in.nextInt();
int m = in.nextInt();
for (int i=0; i<m; i++) {
int target = in.nextInt();
int lower = ~Arrays.binarySearch(a, target, (x,y)->x.compareTo(y)>=0?1:-1);
int upper = ~Arrays.binarySearch(a, target, (x,y)->x.compareTo(y)>0?1:-1);
out.println(lower+" "+upper);
}
}
public static void main(String[] args) {
Main main = new Main();
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Methods ms = new Methods();
main.solve(in, out, ms);
in.close();
out.close();
}
static class Point{
int y, x;
Point(int a, int b) {y = a; x = b;}
int getY() {return y;}
int getX() {return x;}
}
static class Methods {
public void print (Object... ar) {System.out.println(Arrays.deepToString(ar));}
public void yesno (PrintWriter out, boolean b) {out.println(b?"Yes":"No");}
public void YESNO (PrintWriter out, boolean b) {out.println(b?"YES":"NO");}
public int max (int... ar) {Arrays.sort(ar); return ar[ar.length-1];}
public int min (int... ar) {Arrays.sort(ar); return ar[0];}
public int manhat (Point p1, Point p2) {
return Math.abs(p1.x-p2.x) + Math.abs(p1.y-p2.y);
}
public double euclid (Point p1, Point p2) {
return Math.sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
}
public boolean isPrime (int n) {
if (n==2) return true;
if (n<2 || n%2==0) return false;
double d = Math.sqrt(n);
for (int i=3; i<=d; i+=2) if(n%i==0){return false;}
return true;
}
}
static class FastScanner {
private InputStream in;
private byte[] buffer = new byte[1024];
private int length = 0, p = 0;
public FastScanner (InputStream stream) {
in = stream;
}
public boolean hasNextByte () {
if (p < length) return true;
else {
p = 0;
try {length = in.read(buffer);}
catch (Exception e) {e.printStackTrace();}
if (length <= 0) return false;
}
return true;
}
public int readByte () {
if (hasNextByte() == true) return buffer[p++];
return -1;
}
public boolean isPrintable (int n) {return 33<=n&&n<=126;}
public void skip () {
while (hasNextByte() && !isPrintable(buffer[p])) p++;
}
public boolean hasNext () {skip(); return hasNextByte();}
public String next () {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int t = readByte();
while (isPrintable(t)) {
sb.appendCodePoint(t);
t = readByte();
}
return sb.toString();
}
public String[] nextArray (int n) {
String[] ar = new String[n];
for (int i=0; i<n; i++) ar[i] = next();
return ar;
}
public int nextInt () {return Math.toIntExact(nextLong());}
public int[] nextIntArray (int n) {
int[] ar = new int[n];
for (int i=0; i<n; i++) ar[i] = nextInt();
return ar;
}
public long nextLong () {
if (!hasNext()) throw new NoSuchElementException();
boolean minus = false;
int temp = readByte();
if (temp == '-') {
minus = true;
temp = readByte();
}
if (temp<'0' || '9'<temp) throw new NumberFormatException();
long n = 0;
while (isPrintable(temp)) {
if ('0'<=temp && temp<='9') {
n *= 10;
n += temp - '0';
}
else throw new NumberFormatException();
temp = readByte();
}
return minus? -n : n;
}
public long[] nextLongArray (int n) {
long[] ar = new long[n];
for (int i=0; i<n; i++) ar[i] = nextLong();
return ar;
}
public double nextDouble () {
return Double.parseDouble(next());
}
public double[] nextDoubleArray (int n) {
double[] ar = new double[n];
for (int i=0; i<n; i++) ar[i] = nextDouble();
return ar;
}
public void close () {
try {in.close();}
catch(Exception e){}
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: from bisect import bisect_left, bisect_right
n = int(input())
a = list(map(int, input().split()))
q = int(input())
for i in range(q):
k = int(input())
print(bisect_left(a, k), bisect_right(a, k))
Code 2: import java.util.*;
import java.io.*;
public class Main {
void solve (FastScanner in, PrintWriter out, Methods ms) {
int n = in.nextInt();
Integer[] a = new Integer[n];
for (int i=0; i<n; i++) a[i] = in.nextInt();
int m = in.nextInt();
for (int i=0; i<m; i++) {
int target = in.nextInt();
int lower = ~Arrays.binarySearch(a, target, (x,y)->x.compareTo(y)>=0?1:-1);
int upper = ~Arrays.binarySearch(a, target, (x,y)->x.compareTo(y)>0?1:-1);
out.println(lower+" "+upper);
}
}
public static void main(String[] args) {
Main main = new Main();
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Methods ms = new Methods();
main.solve(in, out, ms);
in.close();
out.close();
}
static class Point{
int y, x;
Point(int a, int b) {y = a; x = b;}
int getY() {return y;}
int getX() {return x;}
}
static class Methods {
public void print (Object... ar) {System.out.println(Arrays.deepToString(ar));}
public void yesno (PrintWriter out, boolean b) {out.println(b?"Yes":"No");}
public void YESNO (PrintWriter out, boolean b) {out.println(b?"YES":"NO");}
public int max (int... ar) {Arrays.sort(ar); return ar[ar.length-1];}
public int min (int... ar) {Arrays.sort(ar); return ar[0];}
public int manhat (Point p1, Point p2) {
return Math.abs(p1.x-p2.x) + Math.abs(p1.y-p2.y);
}
public double euclid (Point p1, Point p2) {
return Math.sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
}
public boolean isPrime (int n) {
if (n==2) return true;
if (n<2 || n%2==0) return false;
double d = Math.sqrt(n);
for (int i=3; i<=d; i+=2) if(n%i==0){return false;}
return true;
}
}
static class FastScanner {
private InputStream in;
private byte[] buffer = new byte[1024];
private int length = 0, p = 0;
public FastScanner (InputStream stream) {
in = stream;
}
public boolean hasNextByte () {
if (p < length) return true;
else {
p = 0;
try {length = in.read(buffer);}
catch (Exception e) {e.printStackTrace();}
if (length <= 0) return false;
}
return true;
}
public int readByte () {
if (hasNextByte() == true) return buffer[p++];
return -1;
}
public boolean isPrintable (int n) {return 33<=n&&n<=126;}
public void skip () {
while (hasNextByte() && !isPrintable(buffer[p])) p++;
}
public boolean hasNext () {skip(); return hasNextByte();}
public String next () {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int t = readByte();
while (isPrintable(t)) {
sb.appendCodePoint(t);
t = readByte();
}
return sb.toString();
}
public String[] nextArray (int n) {
String[] ar = new String[n];
for (int i=0; i<n; i++) ar[i] = next();
return ar;
}
public int nextInt () {return Math.toIntExact(nextLong());}
public int[] nextIntArray (int n) {
int[] ar = new int[n];
for (int i=0; i<n; i++) ar[i] = nextInt();
return ar;
}
public long nextLong () {
if (!hasNext()) throw new NoSuchElementException();
boolean minus = false;
int temp = readByte();
if (temp == '-') {
minus = true;
temp = readByte();
}
if (temp<'0' || '9'<temp) throw new NumberFormatException();
long n = 0;
while (isPrintable(temp)) {
if ('0'<=temp && temp<='9') {
n *= 10;
n += temp - '0';
}
else throw new NumberFormatException();
temp = readByte();
}
return minus? -n : n;
}
public long[] nextLongArray (int n) {
long[] ar = new long[n];
for (int i=0; i<n; i++) ar[i] = nextLong();
return ar;
}
public double nextDouble () {
return Double.parseDouble(next());
}
public double[] nextDoubleArray (int n) {
double[] ar = new double[n];
for (int i=0; i<n; i++) ar[i] = nextDouble();
return ar;
}
public void close () {
try {in.close();}
catch(Exception e){}
}
}
}
|
Kotlin |
fun main(args:Array<String>):Unit {
val vector = Vector()
repeat(readLine()!!.toInt()){
val arg = readLine()!!.split(' ').map(String::toInt)
when(arg.first()){
0 -> when(arg[1]){
0 -> vector.pushFront(arg.last())
else -> vector.pushBack(arg.last())
}
1 -> println(vector[arg.last()])
else -> when(arg[1]){
0 -> vector.popFront()
else -> vector.popBack()
}
}
}
}
class Vector {
var capacity:Int = 10000
private set
private var mHead:Int = 0//[mHead, mEnd)
private var mEnd:Int = 0
private var size:Int = 0
private var mArray:Array<Int> = Array(10000){0}
private fun resize():Unit {
val newArray = Array(capacity * 2){0}
for (i in 0 until size){
newArray[i] = mArray[(i + mHead) % capacity]
}
capacity *= 2
mHead = 0
mEnd = size
mArray = newArray
}
fun pushBack(value:Int):Unit {
if (size == capacity) resize()
mArray[mEnd] = value
mEnd = (mEnd + 1) % capacity
++size
}
fun pushFront(value:Int):Unit {
if (size == capacity) resize()
mHead = (mHead + capacity - 1) % capacity
mArray[mHead] = value
++size
}
fun popBack():Unit {
mEnd = (mEnd + capacity - 1) % capacity
--size
}
fun popFront():Unit {
mHead = (mHead + 1) % capacity
--size
}
operator fun get(index:Int):Int = mArray[(mHead + index) % capacity]
}
| PHP | <?php
$n = intval(fgets(STDIN));
$a = [];
array_fill(20002, 20002, 0);
// for($i = 0; $i <= 2000002 ; $i++){
// $a[] = '';
// }
$head = 10000;
$tail = 10000;
for($i=0; $i<$n; $i++) {
$g = preg_split("/[\s,]+/", fgets(STDIN));
$q = intval($g[0]);
if ($q === 0) {
if(intval($g[1])===0){
$head--;
$a[$head] = $g[2];
// var_dump($a);
} else {
$a[$tail] = $g[2];
$tail++;
}
} else if ($q === 1){
echo $a[$head+intval($g[1])] . "\n";
} else {
if(intval($g[1])===0){
$head++;
} else {
$tail--;
}
}
}
| Yes | Do these codes solve the same problem?
Code 1:
fun main(args:Array<String>):Unit {
val vector = Vector()
repeat(readLine()!!.toInt()){
val arg = readLine()!!.split(' ').map(String::toInt)
when(arg.first()){
0 -> when(arg[1]){
0 -> vector.pushFront(arg.last())
else -> vector.pushBack(arg.last())
}
1 -> println(vector[arg.last()])
else -> when(arg[1]){
0 -> vector.popFront()
else -> vector.popBack()
}
}
}
}
class Vector {
var capacity:Int = 10000
private set
private var mHead:Int = 0//[mHead, mEnd)
private var mEnd:Int = 0
private var size:Int = 0
private var mArray:Array<Int> = Array(10000){0}
private fun resize():Unit {
val newArray = Array(capacity * 2){0}
for (i in 0 until size){
newArray[i] = mArray[(i + mHead) % capacity]
}
capacity *= 2
mHead = 0
mEnd = size
mArray = newArray
}
fun pushBack(value:Int):Unit {
if (size == capacity) resize()
mArray[mEnd] = value
mEnd = (mEnd + 1) % capacity
++size
}
fun pushFront(value:Int):Unit {
if (size == capacity) resize()
mHead = (mHead + capacity - 1) % capacity
mArray[mHead] = value
++size
}
fun popBack():Unit {
mEnd = (mEnd + capacity - 1) % capacity
--size
}
fun popFront():Unit {
mHead = (mHead + 1) % capacity
--size
}
operator fun get(index:Int):Int = mArray[(mHead + index) % capacity]
}
Code 2: <?php
$n = intval(fgets(STDIN));
$a = [];
array_fill(20002, 20002, 0);
// for($i = 0; $i <= 2000002 ; $i++){
// $a[] = '';
// }
$head = 10000;
$tail = 10000;
for($i=0; $i<$n; $i++) {
$g = preg_split("/[\s,]+/", fgets(STDIN));
$q = intval($g[0]);
if ($q === 0) {
if(intval($g[1])===0){
$head--;
$a[$head] = $g[2];
// var_dump($a);
} else {
$a[$tail] = $g[2];
$tail++;
}
} else if ($q === 1){
echo $a[$head+intval($g[1])] . "\n";
} else {
if(intval($g[1])===0){
$head++;
} else {
$tail--;
}
}
}
|
Python | N, M = map(int, input().split())
st = 1
en = N
for _ in range(M):
L, R = map(int, input().split())
st = max(st, L)
en = min(en, R)
ans = en - st
if ans < 0:
print(0)
else:
print(ans + 1)
| C++ | #include <iostream>
#include <string>
using namespace std;
int main()
{
int a, b;
string op;
while (cin >> a >> op >> b) {
if (op == "?") break;
if (op == "+") cout << a + b;
else if (op == "-") cout << a - b;
else if (op == "*") cout << a * b;
else cout << a / b;
cout << endl;
}
return 0;
} | No | Do these codes solve the same problem?
Code 1: N, M = map(int, input().split())
st = 1
en = N
for _ in range(M):
L, R = map(int, input().split())
st = max(st, L)
en = min(en, R)
ans = en - st
if ans < 0:
print(0)
else:
print(ans + 1)
Code 2: #include <iostream>
#include <string>
using namespace std;
int main()
{
int a, b;
string op;
while (cin >> a >> op >> b) {
if (op == "?") break;
if (op == "+") cout << a + b;
else if (op == "-") cout << a - b;
else if (op == "*") cout << a * b;
else cout << a / b;
cout << endl;
}
return 0;
} |
C++ | #include<bits/stdc++.h>
#define LL long long
#define REP(i,n) for(int i=0;i<(n);++i)
#define PER(i,n) for(int i=n-1;i>=0;--i)
#define REPA(i,n) for(int i=1;i<(n);++i)
#define foreach(i, n) for(auto &i:(n))
#define PII pair<int,int>
#define PLI pair<long long, int>
#define PLL pair<long long, long long>
#define MOD ((LL)998244353)
#define INF ((int)1e9+7)
#define INFLL ((LL)1e18)
#define ALL(x) (x).begin(),(x).end()
#define BIT(x) (1LL << (x))
using namespace std;
class Tree{
public:
int n;
vector<int> p;
vector<int> l;
vector<int> r;
vector<int> d;
vector<int> h;
Tree(int N){
n=N;
p.resize(N, -1);
l.resize(N, -1);
r.resize(N, -1);
d.resize(N, -1);
h.resize(N, -1);
}
void add(int pa, int left, int right){
if(left>=0){
l[pa]=left;
p[left]=pa;
}
if(right>=0){
r[pa]=right;
p[right]=pa;
}
}
int get_brother(int id){
if(p[id]==-1)return -1;
int ll = l[p[id]];
if(ll>=0&&ll!=id)return ll;
int rr = r[p[id]];
if(rr>=0&&rr!=id)return rr;
return -1;
}
int get_depth(int id){
if(p[id] == -1)return 0;
if(d[id] >= 0)return d[id];
return d[id] = get_depth(p[id]) + 1;
}
int get_height(int id){
if(h[id]>=0)return h[id];
int res = 0;
if(r[id]>=0)res=max(res, get_height(r[id])+1);
if(l[id]>=0)res=max(res, get_height(l[id])+1);
return h[id]=res;
}
int get_degree(int id){
int res = 0;
if(r[id]>=0)++res;
if(l[id]>=0)++res;
return res;
}
int get_parent(int id){
return p[id];
}
int get_root(int id){
if(p[id]==-1)return id;
return get_root(p[id]);
}
vector<int> get_preorder(int id){
if(id==-1)return vector<int>(0);
vector<int> res;
res.push_back(id);
vector<int> d;
d = get_preorder(l[id]);
res.insert(res.end(), ALL(d));
d = get_preorder(r[id]);
res.insert(res.end(), ALL(d));
return res;
}
vector<int> get_inorder(int id){
if(id==-1)return vector<int>(0);
vector<int> res;
vector<int> d;
d = get_inorder(l[id]);
res.insert(res.end(), ALL(d));
res.push_back(id);
d = get_inorder(r[id]);
res.insert(res.end(), ALL(d));
return res;
}
vector<int> get_postorder(int id){
if(id==-1)return vector<int>(0);
vector<int> res;
vector<int> d;
d = get_postorder(l[id]);
res.insert(res.end(), ALL(d));
d = get_postorder(r[id]);
res.insert(res.end(), ALL(d));
res.push_back(id);
return res;
}
};
void output(int d){
static bool used = false;
if(used)cout << " ";
cout << d;
used=true;
}
vector<int> pr;
vector<int> in;
int p = -1;
void func(int l, int r){
if(l==r)return;
int j;
++p;
int tmp = pr[p];
for(j=l;j<r;++j){
if(pr[p]==in[j]){
func(l, j);
func(j+1, r);
break;
}
}
output(tmp);
}
int main(){
int N;
cin >> N;
pr.resize(N);
in.resize(N);
foreach(i, pr)cin>>i;
foreach(i, in)cin>>i;
func(0, N);
cout << endl;
return 0;
}
| Java | import java.util.*;
class Main{
static public void main(String[] args){
Scanner sc=new Scanner(System.in);
int a=sc.nextInt(),b=sc.nextInt();
System.out.println(a+b<10 ? a+b:"error");
sc.close();
}
}
| No | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
#define LL long long
#define REP(i,n) for(int i=0;i<(n);++i)
#define PER(i,n) for(int i=n-1;i>=0;--i)
#define REPA(i,n) for(int i=1;i<(n);++i)
#define foreach(i, n) for(auto &i:(n))
#define PII pair<int,int>
#define PLI pair<long long, int>
#define PLL pair<long long, long long>
#define MOD ((LL)998244353)
#define INF ((int)1e9+7)
#define INFLL ((LL)1e18)
#define ALL(x) (x).begin(),(x).end()
#define BIT(x) (1LL << (x))
using namespace std;
class Tree{
public:
int n;
vector<int> p;
vector<int> l;
vector<int> r;
vector<int> d;
vector<int> h;
Tree(int N){
n=N;
p.resize(N, -1);
l.resize(N, -1);
r.resize(N, -1);
d.resize(N, -1);
h.resize(N, -1);
}
void add(int pa, int left, int right){
if(left>=0){
l[pa]=left;
p[left]=pa;
}
if(right>=0){
r[pa]=right;
p[right]=pa;
}
}
int get_brother(int id){
if(p[id]==-1)return -1;
int ll = l[p[id]];
if(ll>=0&&ll!=id)return ll;
int rr = r[p[id]];
if(rr>=0&&rr!=id)return rr;
return -1;
}
int get_depth(int id){
if(p[id] == -1)return 0;
if(d[id] >= 0)return d[id];
return d[id] = get_depth(p[id]) + 1;
}
int get_height(int id){
if(h[id]>=0)return h[id];
int res = 0;
if(r[id]>=0)res=max(res, get_height(r[id])+1);
if(l[id]>=0)res=max(res, get_height(l[id])+1);
return h[id]=res;
}
int get_degree(int id){
int res = 0;
if(r[id]>=0)++res;
if(l[id]>=0)++res;
return res;
}
int get_parent(int id){
return p[id];
}
int get_root(int id){
if(p[id]==-1)return id;
return get_root(p[id]);
}
vector<int> get_preorder(int id){
if(id==-1)return vector<int>(0);
vector<int> res;
res.push_back(id);
vector<int> d;
d = get_preorder(l[id]);
res.insert(res.end(), ALL(d));
d = get_preorder(r[id]);
res.insert(res.end(), ALL(d));
return res;
}
vector<int> get_inorder(int id){
if(id==-1)return vector<int>(0);
vector<int> res;
vector<int> d;
d = get_inorder(l[id]);
res.insert(res.end(), ALL(d));
res.push_back(id);
d = get_inorder(r[id]);
res.insert(res.end(), ALL(d));
return res;
}
vector<int> get_postorder(int id){
if(id==-1)return vector<int>(0);
vector<int> res;
vector<int> d;
d = get_postorder(l[id]);
res.insert(res.end(), ALL(d));
d = get_postorder(r[id]);
res.insert(res.end(), ALL(d));
res.push_back(id);
return res;
}
};
void output(int d){
static bool used = false;
if(used)cout << " ";
cout << d;
used=true;
}
vector<int> pr;
vector<int> in;
int p = -1;
void func(int l, int r){
if(l==r)return;
int j;
++p;
int tmp = pr[p];
for(j=l;j<r;++j){
if(pr[p]==in[j]){
func(l, j);
func(j+1, r);
break;
}
}
output(tmp);
}
int main(){
int N;
cin >> N;
pr.resize(N);
in.resize(N);
foreach(i, pr)cin>>i;
foreach(i, in)cin>>i;
func(0, N);
cout << endl;
return 0;
}
Code 2: import java.util.*;
class Main{
static public void main(String[] args){
Scanner sc=new Scanner(System.in);
int a=sc.nextInt(),b=sc.nextInt();
System.out.println(a+b<10 ? a+b:"error");
sc.close();
}
}
|
JavaScript | var gets = (function(){
function f(s){return new g(s);}
function g(s){this._s=s.trim().split("\n");this._y=0;}
g.prototype.a = function(f){
var s = this._s, y = this._y, r;
if(typeof s[y] === "string")s[y]=s[y].split(" ").reverse();
r = s[y].pop();
if(!s[y].length)this._y++;
return f?r:+r;
}
g.prototype.l = function(f){
var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);
}
g.prototype.m = function(n,f){
var r=this._s.slice(this._y,this._y+n).map(a=>a.split(" "));
this._y += n;
return f?r:r.map(a=>+a);
}
g.prototype.r = function(n,f){
var r = this._s.slice(this._y,this._y+n);
this._y += n;
return f?r:r.map(a=>+a);
}
return f;
})();
var o=gets(require("fs").readFileSync("/dev/stdin","utf8"));
console.log(main());
function main(){
var Y = "Yes", N = "No";
var n = o.a();
var a = o.l();
var b = [0,0,0];
for(var i = 0; i < n; i++){
var t = a[i] % 4;
if(t === 0)b[2]++;
else if(t === 2)b[1]++;
else b[0]++;
}
if(n === b[1])return Y;
if(b[1])b[0]++;
if(b[2] && b[0] <= b[2]+1)return Y;
return N;
} | Kotlin | import java.io.InputStream
private val input = FastScanner()
fun main(args: Array<String>) = input.run {
val n = nextInt()
val a = nextInts(n)
var count0 = 0
var count4 = 0
a.forEach {
if (it % 2 == 1) {
count0++
} else if (it % 4 == 0) {
count4++
}
}
if (count0 <= count4 || count0 - 1 == count4 && count0 + count4 == n) {
println("Yes")
} else {
println("No")
}
}
class FastScanner(private val input: InputStream = System.`in`) {
private val sb = StringBuilder()
private val buffer = ByteArray(4096)
private var pos = 0
private var size = 0
fun nextLong(): Long {
var c = skipWhitespace()
val sign = if (c == '-'.toInt()) {
c = read()
-1
} else 1
var ans = 0L
while (c > ' '.toInt()) {
ans = ans * 10 + c - '0'.toInt()
c = read()
}
return sign * ans
}
fun nextInt() = nextLong().toInt()
fun nextInts(n: Int) = IntArray(n) { nextInt() }
private fun skipWhitespace(): Int {
while (true) {
val c = read()
if (c > ' '.toInt() || c < 0) return c
}
}
private fun read(): Int {
while (pos >= size) {
if (size < 0) return -1
size = input.read(buffer, 0, buffer.size)
pos = 0
}
return buffer[pos++].toInt()
}
} | Yes | Do these codes solve the same problem?
Code 1: var gets = (function(){
function f(s){return new g(s);}
function g(s){this._s=s.trim().split("\n");this._y=0;}
g.prototype.a = function(f){
var s = this._s, y = this._y, r;
if(typeof s[y] === "string")s[y]=s[y].split(" ").reverse();
r = s[y].pop();
if(!s[y].length)this._y++;
return f?r:+r;
}
g.prototype.l = function(f){
var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);
}
g.prototype.m = function(n,f){
var r=this._s.slice(this._y,this._y+n).map(a=>a.split(" "));
this._y += n;
return f?r:r.map(a=>+a);
}
g.prototype.r = function(n,f){
var r = this._s.slice(this._y,this._y+n);
this._y += n;
return f?r:r.map(a=>+a);
}
return f;
})();
var o=gets(require("fs").readFileSync("/dev/stdin","utf8"));
console.log(main());
function main(){
var Y = "Yes", N = "No";
var n = o.a();
var a = o.l();
var b = [0,0,0];
for(var i = 0; i < n; i++){
var t = a[i] % 4;
if(t === 0)b[2]++;
else if(t === 2)b[1]++;
else b[0]++;
}
if(n === b[1])return Y;
if(b[1])b[0]++;
if(b[2] && b[0] <= b[2]+1)return Y;
return N;
}
Code 2: import java.io.InputStream
private val input = FastScanner()
fun main(args: Array<String>) = input.run {
val n = nextInt()
val a = nextInts(n)
var count0 = 0
var count4 = 0
a.forEach {
if (it % 2 == 1) {
count0++
} else if (it % 4 == 0) {
count4++
}
}
if (count0 <= count4 || count0 - 1 == count4 && count0 + count4 == n) {
println("Yes")
} else {
println("No")
}
}
class FastScanner(private val input: InputStream = System.`in`) {
private val sb = StringBuilder()
private val buffer = ByteArray(4096)
private var pos = 0
private var size = 0
fun nextLong(): Long {
var c = skipWhitespace()
val sign = if (c == '-'.toInt()) {
c = read()
-1
} else 1
var ans = 0L
while (c > ' '.toInt()) {
ans = ans * 10 + c - '0'.toInt()
c = read()
}
return sign * ans
}
fun nextInt() = nextLong().toInt()
fun nextInts(n: Int) = IntArray(n) { nextInt() }
private fun skipWhitespace(): Int {
while (true) {
val c = read()
if (c > ' '.toInt() || c < 0) return c
}
}
private fun read(): Int {
while (pos >= size) {
if (size < 0) return -1
size = input.read(buffer, 0, buffer.size)
pos = 0
}
return buffer[pos++].toInt()
}
} |
Java | import java.io.*;
import java.util.*;
class Main {
void solve(){
Scanner sc = new Scanner( System.in );
while ( true ) {
int n = sc.nextInt();
if ( n == 0 ) break;
int less1Cnt = 0;
int zeroCnt = 0;
for ( int i=0; i<n; ++i ) {
int k = sc.nextInt();
if (k <= 1) ++less1Cnt;
if (k == 0) ++zeroCnt;
}
if (n == less1Cnt) System.out.println("NA");
else System.out.println(n - zeroCnt + 1);
}
}
public static void main( String[] a ) {new Main().solve(); }
}
| C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0279
{
class Program
{
static void Main(string[] args)
{
while (true)
{
int n = RInt();
if (n == 0) break;
int[] items = RArInt();
if (items.Max() < 2)
{
Console.WriteLine("NA");
}
else
{
Console.WriteLine(items.Count(x => x > 0) + 1);
}
}
}
static string RSt() { return Console.ReadLine(); }
static int RInt() { return int.Parse(Console.ReadLine().Trim()); }
static long RLong() { return long.Parse(Console.ReadLine().Trim()); }
static double RDouble() { return double.Parse(Console.ReadLine()); }
static string[] RArSt(char sep = ' ') { return Console.ReadLine().Trim().Split(sep); }
static int[] RArInt(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => int.Parse(e)); }
static long[] RArLong(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => long.Parse(e)); }
static double[] RArDouble(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => double.Parse(e)); }
static string WAr<T>(IEnumerable<T> array, string sep = " ") { return string.Join(sep, array.Select(x => x.ToString()).ToArray()); }
}
}
| Yes | Do these codes solve the same problem?
Code 1: import java.io.*;
import java.util.*;
class Main {
void solve(){
Scanner sc = new Scanner( System.in );
while ( true ) {
int n = sc.nextInt();
if ( n == 0 ) break;
int less1Cnt = 0;
int zeroCnt = 0;
for ( int i=0; i<n; ++i ) {
int k = sc.nextInt();
if (k <= 1) ++less1Cnt;
if (k == 0) ++zeroCnt;
}
if (n == less1Cnt) System.out.println("NA");
else System.out.println(n - zeroCnt + 1);
}
}
public static void main( String[] a ) {new Main().solve(); }
}
Code 2: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0279
{
class Program
{
static void Main(string[] args)
{
while (true)
{
int n = RInt();
if (n == 0) break;
int[] items = RArInt();
if (items.Max() < 2)
{
Console.WriteLine("NA");
}
else
{
Console.WriteLine(items.Count(x => x > 0) + 1);
}
}
}
static string RSt() { return Console.ReadLine(); }
static int RInt() { return int.Parse(Console.ReadLine().Trim()); }
static long RLong() { return long.Parse(Console.ReadLine().Trim()); }
static double RDouble() { return double.Parse(Console.ReadLine()); }
static string[] RArSt(char sep = ' ') { return Console.ReadLine().Trim().Split(sep); }
static int[] RArInt(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => int.Parse(e)); }
static long[] RArLong(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => long.Parse(e)); }
static double[] RArDouble(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => double.Parse(e)); }
static string WAr<T>(IEnumerable<T> array, string sep = " ") { return string.Join(sep, array.Select(x => x.ToString()).ToArray()); }
}
}
|
C | /* ex5_4
masaaki52 */
#include <stdio.h>
#include <string.h>
int main(void){
char string[11];
int i,count=0,max=0;
scanf("%s",string);
//文字列stringの頭からnull文字まで、以下の操作を行う
for(i=0;i<strlen(string)+1;i++){
switch(string[i]){//stringのi番目が
case 'A': case 'C': case 'G': case 'T'://A,C,G,Tのどれかなら
count++;//countに1を加える
break;
default://A,C,G,T以外の場合
if(count > max){//もしcountがmaxより大きいなら
max = count;//そのcountをmaxとする
}
count = 0;//countの初期化
}
}
printf("%d",max);
return 0;
} | Python | N = int(input())
B = int(pow(N, 0.5) + 1)
tmp = pow(10, 12)
for b in range(1, B):
if N % b == 0:
a = N // b
if tmp > a + b - 2:
tmp = a + b - 2
print(tmp)
| No | Do these codes solve the same problem?
Code 1: /* ex5_4
masaaki52 */
#include <stdio.h>
#include <string.h>
int main(void){
char string[11];
int i,count=0,max=0;
scanf("%s",string);
//文字列stringの頭からnull文字まで、以下の操作を行う
for(i=0;i<strlen(string)+1;i++){
switch(string[i]){//stringのi番目が
case 'A': case 'C': case 'G': case 'T'://A,C,G,Tのどれかなら
count++;//countに1を加える
break;
default://A,C,G,T以外の場合
if(count > max){//もしcountがmaxより大きいなら
max = count;//そのcountをmaxとする
}
count = 0;//countの初期化
}
}
printf("%d",max);
return 0;
}
Code 2: N = int(input())
B = int(pow(N, 0.5) + 1)
tmp = pow(10, 12)
for b in range(1, B):
if N % b == 0:
a = N // b
if tmp > a + b - 2:
tmp = a + b - 2
print(tmp)
|
Java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import static java.lang.Integer.parseInt;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
String[] words;
int n = parseInt(br.readLine());
Map<Integer, Integer> P = new HashMap<>();
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int s, l, p;
s = parseInt(st.nextToken());
l = parseInt(st.nextToken());
p = parseInt(st.nextToken());
for (int j = s; j <= l; j++) {
P.putIfAbsent(j, 0);
P.put(j, Math.max(P.get(j), p));
}
}
int m = parseInt(br.readLine());
StringBuilder ans = new StringBuilder();
boolean notfound = false;
for (int i = 0; i < m; i++) {
int w = parseInt(br.readLine());
int[] dp = new int[w + 1];
for (Map.Entry<Integer, Integer> p : P.entrySet()) {
for (int j = p.getKey(); j <= w; j++) {
dp[j] = Math.max(dp[j], dp[j - p.getKey()] + p.getValue());
}
}
if (dp[w] == 0) {
notfound = true;
break;
}
ans.append(dp[w]).append('\n');
}
if (notfound) {
System.out.println(-1);
} else {
System.out.print(ans.toString());
}
}
}
| C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
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;
class Solver
{
public Scanner sc;
public void Solve()
{
var N = sc.Int;
var dp = Create(400, () => int.MinValue / 2);dp[0] = 0;
for (int i = 0; i < N; i++)
{
int s,l,p;
sc.ArrInt.Out(out s, out l, out p);
for(int j = s; j <= l; j++)
{
for (int k = 0; k < 400; k++)
{
if (k - j >= 0&&dp[k-j]!= int.MinValue / 2) chmax(ref dp[k], dp[k - j] + p);
}
}
}
var M = sc.Int;
var res = new List<int>();
while (M-- > 0)
{
var w = sc.Int;
if (dp[w] == int.MinValue / 2) Fail(-1);
res.Add(dp[w]);
}
Console.WriteLine(string.Join("\n", res));
}
}
#region Template
public static class Template
{
static void Main(string[] args)
{
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
var sol = new Solver() { sc = new Scanner() };
//var th = new Thread(sol.Solve, 1 << 26);th.Start();th.Join();
sol.Solve();
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 void Out<T>(this IList<T> A, out T a) => a = A[0];
public static void Out<T>(this IList<T> A, out T a, out T b) { a = A[0]; b = A[1]; }
public static void Out<T>(this IList<T> A, out T a, out T b, out T c) { A.Out(out a, out b); c = A[2]; }
public static void Out<T>(this IList<T> A, out T a, out T b, out T c, out T d) { A.Out(out a, out b, out c); d = A[3]; }
public static string Concat<T>(this IEnumerable<T> A, string sp) => string.Join(sp, A);
public static char ToChar(this int s, char begin = '0') => (char)(s + begin);
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 ArgMax<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 void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
//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); }
}
#endregion
| Yes | Do these codes solve the same problem?
Code 1: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import static java.lang.Integer.parseInt;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
String[] words;
int n = parseInt(br.readLine());
Map<Integer, Integer> P = new HashMap<>();
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int s, l, p;
s = parseInt(st.nextToken());
l = parseInt(st.nextToken());
p = parseInt(st.nextToken());
for (int j = s; j <= l; j++) {
P.putIfAbsent(j, 0);
P.put(j, Math.max(P.get(j), p));
}
}
int m = parseInt(br.readLine());
StringBuilder ans = new StringBuilder();
boolean notfound = false;
for (int i = 0; i < m; i++) {
int w = parseInt(br.readLine());
int[] dp = new int[w + 1];
for (Map.Entry<Integer, Integer> p : P.entrySet()) {
for (int j = p.getKey(); j <= w; j++) {
dp[j] = Math.max(dp[j], dp[j - p.getKey()] + p.getValue());
}
}
if (dp[w] == 0) {
notfound = true;
break;
}
ans.append(dp[w]).append('\n');
}
if (notfound) {
System.out.println(-1);
} else {
System.out.print(ans.toString());
}
}
}
Code 2: using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
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;
class Solver
{
public Scanner sc;
public void Solve()
{
var N = sc.Int;
var dp = Create(400, () => int.MinValue / 2);dp[0] = 0;
for (int i = 0; i < N; i++)
{
int s,l,p;
sc.ArrInt.Out(out s, out l, out p);
for(int j = s; j <= l; j++)
{
for (int k = 0; k < 400; k++)
{
if (k - j >= 0&&dp[k-j]!= int.MinValue / 2) chmax(ref dp[k], dp[k - j] + p);
}
}
}
var M = sc.Int;
var res = new List<int>();
while (M-- > 0)
{
var w = sc.Int;
if (dp[w] == int.MinValue / 2) Fail(-1);
res.Add(dp[w]);
}
Console.WriteLine(string.Join("\n", res));
}
}
#region Template
public static class Template
{
static void Main(string[] args)
{
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
var sol = new Solver() { sc = new Scanner() };
//var th = new Thread(sol.Solve, 1 << 26);th.Start();th.Join();
sol.Solve();
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 void Out<T>(this IList<T> A, out T a) => a = A[0];
public static void Out<T>(this IList<T> A, out T a, out T b) { a = A[0]; b = A[1]; }
public static void Out<T>(this IList<T> A, out T a, out T b, out T c) { A.Out(out a, out b); c = A[2]; }
public static void Out<T>(this IList<T> A, out T a, out T b, out T c, out T d) { A.Out(out a, out b, out c); d = A[3]; }
public static string Concat<T>(this IEnumerable<T> A, string sp) => string.Join(sp, A);
public static char ToChar(this int s, char begin = '0') => (char)(s + begin);
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 ArgMax<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 void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
//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); }
}
#endregion
|
Python | n = input()
x = input().split()
x_int = [int(i) for i in x]
print('{} {} {}'.format(min(x_int),max(x_int),sum(x_int))) | C++ | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
typedef tree<ii,null_type,less<ii>,rb_tree_tag,tree_order_statistics_node_update> indexed_set;
int main() {
cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);
int D,G; cin>>D>>G;
vector<int> p(D), c(D);
for (int i=0; i<D; i++)
cin>>p[i]>>c[i];
int ret=INT_MAX;
for (int bt=0; bt<(1<<D); bt++) {
int cur=0, val=0;
for (int i=0; i<D; i++)
if(bt&(1<<i))
cur+=p[i], val+=p[i]*(i+1)*100+c[i];
int diff=max(0,G-val);
for (int i=D-1; i>=0; i--) {
if(bt&(1<<i))
continue;
int pt=(i+1)*100;
int tmp=min((diff+pt-1)/pt,p[i]-1);
cur+=tmp; diff=max(0,diff-pt*tmp);
}
if(diff>0)
continue;
ret=min(ret,cur);
}
cout<<ret<<"\n";
return 0;
} | No | Do these codes solve the same problem?
Code 1: n = input()
x = input().split()
x_int = [int(i) for i in x]
print('{} {} {}'.format(min(x_int),max(x_int),sum(x_int)))
Code 2: #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
typedef tree<ii,null_type,less<ii>,rb_tree_tag,tree_order_statistics_node_update> indexed_set;
int main() {
cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);
int D,G; cin>>D>>G;
vector<int> p(D), c(D);
for (int i=0; i<D; i++)
cin>>p[i]>>c[i];
int ret=INT_MAX;
for (int bt=0; bt<(1<<D); bt++) {
int cur=0, val=0;
for (int i=0; i<D; i++)
if(bt&(1<<i))
cur+=p[i], val+=p[i]*(i+1)*100+c[i];
int diff=max(0,G-val);
for (int i=D-1; i>=0; i--) {
if(bt&(1<<i))
continue;
int pt=(i+1)*100;
int tmp=min((diff+pt-1)/pt,p[i]-1);
cur+=tmp; diff=max(0,diff-pt*tmp);
}
if(diff>0)
continue;
ret=min(ret,cur);
}
cout<<ret<<"\n";
return 0;
} |
Java |
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int migi = sc.nextInt();
int hidari = sc.nextInt();
int a = 0;
if (migi < hidari) {
a = hidari - migi;
} else if (hidari<migi)
a=migi-hidari;{
System.out.println(a);
}
}
}
| Go | package main
import (
"fmt"
"math"
)
func main() {
var a, b float64
fmt.Scanf("%v %v", &a, &b)
fmt.Println(math.Abs(a - b))
}
| Yes | Do these codes solve the same problem?
Code 1:
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int migi = sc.nextInt();
int hidari = sc.nextInt();
int a = 0;
if (migi < hidari) {
a = hidari - migi;
} else if (hidari<migi)
a=migi-hidari;{
System.out.println(a);
}
}
}
Code 2: package main
import (
"fmt"
"math"
)
func main() {
var a, b float64
fmt.Scanf("%v %v", &a, &b)
fmt.Println(math.Abs(a - b))
}
|
Python | X,Y = map(str,input().split())
L = ["A","B","C","D","E","F"]
for i in range(6) :
if L[i] == X :
lx = i
if L[i] == Y :
ly = i
if lx < ly :
print("<")
elif lx > ly :
print(">")
else :
print("=")
| PHP | <?php
$rooms = array_fill(1,10,0);
$floors = array_fill(1, 3, $rooms);
$buildings = array_fill(1, 4, $floors);
$num = (int)fgets(STDIN);
while (--$num >= 0) {
fscanf(STDIN, "%d%d%d%d", $b,$f,$r,$v);
$buildings[$b][$f][$r] += $v;
}
$res = array_fill(1,4,'');
for ($i = 1; $i <= 4; $i++) {
for ($j = 1; $j <= 3; $j++) {
$res[$i] .= ' ' . implode(' ', $buildings[$i][$j]) . PHP_EOL;
}
}
echo implode('####################'.PHP_EOL, $res); | No | Do these codes solve the same problem?
Code 1: X,Y = map(str,input().split())
L = ["A","B","C","D","E","F"]
for i in range(6) :
if L[i] == X :
lx = i
if L[i] == Y :
ly = i
if lx < ly :
print("<")
elif lx > ly :
print(">")
else :
print("=")
Code 2: <?php
$rooms = array_fill(1,10,0);
$floors = array_fill(1, 3, $rooms);
$buildings = array_fill(1, 4, $floors);
$num = (int)fgets(STDIN);
while (--$num >= 0) {
fscanf(STDIN, "%d%d%d%d", $b,$f,$r,$v);
$buildings[$b][$f][$r] += $v;
}
$res = array_fill(1,4,'');
for ($i = 1; $i <= 4; $i++) {
for ($j = 1; $j <= 3; $j++) {
$res[$i] .= ' ' . implode(' ', $buildings[$i][$j]) . PHP_EOL;
}
}
echo implode('####################'.PHP_EOL, $res); |
C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0521
{
public class Program
{
public static void Main(string[] args)
{
while (true)
{
int n = ReadInt();
if (n == 0) break;
int change = 1000 - n;
int res = 0;
int[] coins = new int[] { 500, 100, 50, 10, 5, 1 };
for (int i = 0 ; i < coins.Length ; i++)
{
res += change / coins[i];
change %= coins[i];
}
Console.WriteLine(res);
}
}
static string ReadSt() { return Console.ReadLine(); }
static int ReadInt() { return int.Parse(Console.ReadLine()); }
static long ReadLong() { return long.Parse(Console.ReadLine()); }
static double ReadDouble() { return double.Parse(Console.ReadLine()); }
static string[] ReadStAr(char sep = ' ') { return Console.ReadLine().Split(sep); }
static int[] ReadIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); }
static long[] ReadLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); }
static double[] ReadDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); }
static string WriteAr(int[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
static string WriteAr(double[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
static string WriteAr(long[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
}
}
| Go | package main
import (
"fmt"
"os"
"strconv"
"strings"
"bufio"
)
var (
sc = bufio.NewScanner(os.Stdin)
buf = make([]byte, 1000)
)
func scanText() string{
sc.Scan()
return sc.Text()
}
func scanTextArray(n int) []string {
out := make([]string, n)
for i, v := range(strings.Split(scanText(), "")) {
out[i] = v
}
return out
}
func scanInt() int {
out, e := strconv.Atoi(scanText())
if e != nil {
panic(e)
}
return out
}
func scanIntArray(n int) []int {
out := make([]int, n)
for i, v := range(strings.Split(scanText(), " ")) {
num, e := strconv.Atoi(v)
if e != nil {
panic(e)
}
out[i] = num
}
return out
}
// template end
var (
coins = [6]int{500, 100, 50, 10, 5, 1}
)
func f(data int) {
ans := 0
change := 1000 - data
for _, v := range coins {
for ;v <= change; {
change -= v
ans++
}
}
fmt.Println(ans)
}
func main() {
sc.Buffer(buf, 10000)
for{
data := scanInt()
if data == 0 {
break
}
f(data)
}
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0521
{
public class Program
{
public static void Main(string[] args)
{
while (true)
{
int n = ReadInt();
if (n == 0) break;
int change = 1000 - n;
int res = 0;
int[] coins = new int[] { 500, 100, 50, 10, 5, 1 };
for (int i = 0 ; i < coins.Length ; i++)
{
res += change / coins[i];
change %= coins[i];
}
Console.WriteLine(res);
}
}
static string ReadSt() { return Console.ReadLine(); }
static int ReadInt() { return int.Parse(Console.ReadLine()); }
static long ReadLong() { return long.Parse(Console.ReadLine()); }
static double ReadDouble() { return double.Parse(Console.ReadLine()); }
static string[] ReadStAr(char sep = ' ') { return Console.ReadLine().Split(sep); }
static int[] ReadIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); }
static long[] ReadLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); }
static double[] ReadDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); }
static string WriteAr(int[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
static string WriteAr(double[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
static string WriteAr(long[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
}
}
Code 2: package main
import (
"fmt"
"os"
"strconv"
"strings"
"bufio"
)
var (
sc = bufio.NewScanner(os.Stdin)
buf = make([]byte, 1000)
)
func scanText() string{
sc.Scan()
return sc.Text()
}
func scanTextArray(n int) []string {
out := make([]string, n)
for i, v := range(strings.Split(scanText(), "")) {
out[i] = v
}
return out
}
func scanInt() int {
out, e := strconv.Atoi(scanText())
if e != nil {
panic(e)
}
return out
}
func scanIntArray(n int) []int {
out := make([]int, n)
for i, v := range(strings.Split(scanText(), " ")) {
num, e := strconv.Atoi(v)
if e != nil {
panic(e)
}
out[i] = num
}
return out
}
// template end
var (
coins = [6]int{500, 100, 50, 10, 5, 1}
)
func f(data int) {
ans := 0
change := 1000 - data
for _, v := range coins {
for ;v <= change; {
change -= v
ans++
}
}
fmt.Println(ans)
}
func main() {
sc.Buffer(buf, 10000)
for{
data := scanInt()
if data == 0 {
break
}
f(data)
}
}
|
Java | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni();
int[][] ai = new int[n][];
for(int i = 0;i < n;i++)ai[i] = new int[]{ni(), ni()};
Arrays.sort(ai, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return -((a[0]+a[1])-(b[0]+b[1]));
}
});
long v = 0;
for(int i = 0;i < n;i++){
if(i % 2 == 0){
v += ai[i][0];
}else{
v -= ai[i][1];
}
}
out.println(v);
// a1 b1
// a2 b2
// (a1-b2)-(a2-b1)
//
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
long G = System.currentTimeMillis();
tr(G-S+"ms");
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double nd() { return Double.parseDouble(ns()); }
private static char nc() { return (char)skip(); }
private static String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private static int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private static int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
| Kotlin | fun main(args: Array<String>) {
val n = readLine()!!.toInt()
val ab = (1..n).map {
val (a, b) = readLine()!!.split(" ").map(String::toInt)
Pair(a, b)
}.sortedByDescending { e -> e.first + e.second }
var ap = 0L
var bp = 0L
for (i in 0 until n) {
if (i % 2 == 0) {
ap += ab[i].first
} else {
bp += ab[i].second
}
}
println(ap - bp)
}
| Yes | Do these codes solve the same problem?
Code 1: import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni();
int[][] ai = new int[n][];
for(int i = 0;i < n;i++)ai[i] = new int[]{ni(), ni()};
Arrays.sort(ai, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return -((a[0]+a[1])-(b[0]+b[1]));
}
});
long v = 0;
for(int i = 0;i < n;i++){
if(i % 2 == 0){
v += ai[i][0];
}else{
v -= ai[i][1];
}
}
out.println(v);
// a1 b1
// a2 b2
// (a1-b2)-(a2-b1)
//
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
long G = System.currentTimeMillis();
tr(G-S+"ms");
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double nd() { return Double.parseDouble(ns()); }
private static char nc() { return (char)skip(); }
private static String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private static int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private static int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
Code 2: fun main(args: Array<String>) {
val n = readLine()!!.toInt()
val ab = (1..n).map {
val (a, b) = readLine()!!.split(" ").map(String::toInt)
Pair(a, b)
}.sortedByDescending { e -> e.first + e.second }
var ap = 0L
var bp = 0L
for (i in 0 until n) {
if (i % 2 == 0) {
ap += ab[i].first
} else {
bp += ab[i].second
}
}
println(ap - bp)
}
|
C++ | #include <vector>
#include <list>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <queue>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <fstream>
#include <cstdio>
#include <climits>
#include <complex>
#include <cstdint>
#include <tuple>
#define M_PI 3.14159265358979323846
using namespace std;
//conversion
//------------------------------------------
inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v; }
template<class T> inline string toString(T x) { ostringstream sout; sout << x; return sout.str(); }
inline int readInt() { int x; scanf("%d", &x); return x; }
//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<int, PII> TIII;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;
//container util
//------------------------------------------
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SQ(a) ((a)*(a))
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
//repetition
//------------------------------------------
#define FOR(i,s,n) for(int i=s;i<(int)n;++i)
#define REP(i,n) FOR(i,0,n)
#define MOD 1000000007
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
int N, K;
bool cmp(const pii &a, const pii &b){
if(a.first == b.first) return a.second < b.second;
return a.first < b.first;
}
struct Edge {
int to, cost;
Edge(int to, int cost): to(to), cost(cost) {}
};
typedef vector<vector<Edge>> AdjList;
AdjList graph;
const int INF = 100000000;
vi dist;
int d[110][110];
bool bellman_ford(int n, int s) { // nは頂点数、sは開始頂点
dist = vector<int>(n, INF);
dist[s] = 0; // 開始点の距離は0
for (int i = 0; i < n; i++) {
for (int v = 0; v < n; v++) {
for (int u = 0; u < n; u++) {
if (dist[v] != INF && dist[u] > dist[v] + d[v][u]) {
dist[u] = dist[v] + d[v][u];
if (i == n - 1) return true; // n回目にも更新があるなら負の閉路が存在
}
}
}
}
return false;
}
vector<string> field;
bool f = false;
int R, C;
bool state[25][25][20][4];
map<char, int> mp;
void dfs(int y, int x, int mem, char dir, int cnt){
if(f) return;
if(state[y][x][mem][mp[dir]] == true) return;
state[y][x][mem][mp[dir]] = true;
if(field[y][x] == '@'){
f = true;
return;
}
if(field[y][x] >= '0' && field[y][x] <= '9'){
if(dir == 'N') {
dfs((y-1+R)%R, x, field[y][x] - '0', 'N', cnt+1);
}else if(dir == 'S'){
dfs((y+1+R)%R, x, field[y][x] - '0', 'S', cnt+1);
}else if(dir == 'E'){
dfs(y, (x+1+C)%C, field[y][x] - '0', 'E', cnt+1);
}else {
dfs(y, (x-1+C)%C, field[y][x] -'0', 'W', cnt+1);
}
}
if(field[y][x] == '<'){
dfs(y, (x-1+C)%C, mem, 'W', cnt+1);
}
if(field[y][x] == '>'){
dfs(y, (x+1+C)%C, mem, 'E', cnt+1);
}
if(field[y][x]== '^'){
dfs((y-1+R)%R, x, mem, 'N', cnt+1);
}
if(field[y][x] == 'v'){
dfs((y+1+R)%R, x, mem, 'S', cnt+1);
}
if(field[y][x] == '_'){
if(mem == 0){
dfs(y, (x+1+C)%C, mem, 'E', cnt+1);
}else{
dfs(y, (x-1+C)%C, mem, 'W', cnt+1);
}
}
if(field[y][x] == '|'){
if(mem == 0){
dfs((y+1+R)%R, x, mem, 'S', cnt+1);
}else{
dfs((y-1+R)%R, x, mem, 'N', cnt+1);
}
}
if(field[y][x] == '?'){
dfs(y, (x-1+C)%C, mem, 'W', cnt+1);
dfs(y, (x+1+C)%C, mem, 'E', cnt+1);
dfs((y+1+R)%R, x, mem, 'S', cnt+1);
dfs((y-1+R)%R, x, mem, 'N', cnt+1);
}
if(field[y][x] == '.'){
if(dir == 'N') {
dfs((y-1+R)%R, x, mem, 'N', cnt+1);
}else if(dir == 'S'){
dfs((y+1+R)%R, x, mem, 'S', cnt+1);
}else if(dir == 'E'){
dfs(y, (x+1+C)%C, mem, 'E', cnt+1);
}else {
dfs(y, (x-1+C)%C, mem, 'W', cnt+1);
}
}
if(field[y][x] == '+'){
if(dir == 'N') {
dfs((y-1+R)%R, x, (mem+1+16)%16, 'N', cnt+1);
}else if(dir == 'S'){
dfs((y+1+R)%R, x, (mem+1+16)%16, 'S', cnt+1);
}else if(dir == 'E'){
dfs(y, (x+1+C)%C, (mem+1+16)%16, 'E', cnt+1);
}else {
dfs(y, (x-1+C)%C, (mem+1+16)%16, 'W', cnt+1);
}
}
if(field[y][x] == '-'){
if(dir == 'N') {
dfs((y-1+R)%R, x, (mem-1+16)%16, 'N', cnt+1);
}else if(dir == 'S'){
dfs((y+1+R)%R, x, (mem-1+16)%16, 'S', cnt+1);
}else if(dir == 'E'){
dfs(y, (x+1+C)%C, (mem-1+16)%16, 'E', cnt+1);
}else {
dfs(y, (x-1+C)%C, (mem-1+16)%16, 'W', cnt+1);
}
}
}
int main() {
//cout << fixed << setprecision(15);
cin >> R >> C;
REP(i, R){
string str; cin >> str;
field.push_back(str);
}
bool state[25][25][20][4];
mp['N'] = 0;
mp['S'] = 1;
mp['W'] = 2;
mp['E'] = 3;
REP(i, 25) REP(j, 25) REP(k, 20) REP(l, 4) state[i][j][k][l]=false;
dfs(0, 0, 0, 'E', 0);
if(f) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
| Python | from collections import deque
r, c = map(int, input().split())
mp = [input() for _ in range(r)]
R, U, L, D = 0, 1, 2, 3
vec = ((1, 0), (0, -1), (-1, 0), (0, 1))
dic = {}
dic[(0, 0, R, 0)] = True
que = deque()
que.append((0, 0, R, 0))
while que:
x, y, direct, mem = que.popleft()
com = mp[y][x]
if com == "?":
for d in (R, U, L, D):
dx, dy = vec[d]
nx, ny = (x + dx) % c, (y + dy) % r
if (nx, ny, d, mem) not in dic:
dic[(nx, ny, d, mem)] = True
que.append((nx, ny, d, mem))
continue
elif com == "@":
print("YES")
break
elif com == "<":
direct = L
elif com == ">":
direct = R
elif com == "^":
direct = U
elif com == "v":
direct = D
elif com == "_":
direct = R if mem == 0 else L
elif com == "|":
direct = D if mem == 0 else U
elif com == ".":
pass
elif "0" <= com <= "9":
mem = int(com)
elif com == "+":
mem = (mem + 1) % 16
elif com == "-":
mem = (mem - 1) % 16
dx, dy = vec[direct]
nx, ny = (x + dx) % c, (y + dy) % r
if (nx, ny, direct, mem) not in dic:
dic[(nx, ny, direct, mem)] = True
que.append((nx, ny, direct, mem))
else:
print("NO")
| Yes | Do these codes solve the same problem?
Code 1: #include <vector>
#include <list>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <queue>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <fstream>
#include <cstdio>
#include <climits>
#include <complex>
#include <cstdint>
#include <tuple>
#define M_PI 3.14159265358979323846
using namespace std;
//conversion
//------------------------------------------
inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v; }
template<class T> inline string toString(T x) { ostringstream sout; sout << x; return sout.str(); }
inline int readInt() { int x; scanf("%d", &x); return x; }
//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<int, PII> TIII;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;
//container util
//------------------------------------------
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SQ(a) ((a)*(a))
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
//repetition
//------------------------------------------
#define FOR(i,s,n) for(int i=s;i<(int)n;++i)
#define REP(i,n) FOR(i,0,n)
#define MOD 1000000007
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
int N, K;
bool cmp(const pii &a, const pii &b){
if(a.first == b.first) return a.second < b.second;
return a.first < b.first;
}
struct Edge {
int to, cost;
Edge(int to, int cost): to(to), cost(cost) {}
};
typedef vector<vector<Edge>> AdjList;
AdjList graph;
const int INF = 100000000;
vi dist;
int d[110][110];
bool bellman_ford(int n, int s) { // nは頂点数、sは開始頂点
dist = vector<int>(n, INF);
dist[s] = 0; // 開始点の距離は0
for (int i = 0; i < n; i++) {
for (int v = 0; v < n; v++) {
for (int u = 0; u < n; u++) {
if (dist[v] != INF && dist[u] > dist[v] + d[v][u]) {
dist[u] = dist[v] + d[v][u];
if (i == n - 1) return true; // n回目にも更新があるなら負の閉路が存在
}
}
}
}
return false;
}
vector<string> field;
bool f = false;
int R, C;
bool state[25][25][20][4];
map<char, int> mp;
void dfs(int y, int x, int mem, char dir, int cnt){
if(f) return;
if(state[y][x][mem][mp[dir]] == true) return;
state[y][x][mem][mp[dir]] = true;
if(field[y][x] == '@'){
f = true;
return;
}
if(field[y][x] >= '0' && field[y][x] <= '9'){
if(dir == 'N') {
dfs((y-1+R)%R, x, field[y][x] - '0', 'N', cnt+1);
}else if(dir == 'S'){
dfs((y+1+R)%R, x, field[y][x] - '0', 'S', cnt+1);
}else if(dir == 'E'){
dfs(y, (x+1+C)%C, field[y][x] - '0', 'E', cnt+1);
}else {
dfs(y, (x-1+C)%C, field[y][x] -'0', 'W', cnt+1);
}
}
if(field[y][x] == '<'){
dfs(y, (x-1+C)%C, mem, 'W', cnt+1);
}
if(field[y][x] == '>'){
dfs(y, (x+1+C)%C, mem, 'E', cnt+1);
}
if(field[y][x]== '^'){
dfs((y-1+R)%R, x, mem, 'N', cnt+1);
}
if(field[y][x] == 'v'){
dfs((y+1+R)%R, x, mem, 'S', cnt+1);
}
if(field[y][x] == '_'){
if(mem == 0){
dfs(y, (x+1+C)%C, mem, 'E', cnt+1);
}else{
dfs(y, (x-1+C)%C, mem, 'W', cnt+1);
}
}
if(field[y][x] == '|'){
if(mem == 0){
dfs((y+1+R)%R, x, mem, 'S', cnt+1);
}else{
dfs((y-1+R)%R, x, mem, 'N', cnt+1);
}
}
if(field[y][x] == '?'){
dfs(y, (x-1+C)%C, mem, 'W', cnt+1);
dfs(y, (x+1+C)%C, mem, 'E', cnt+1);
dfs((y+1+R)%R, x, mem, 'S', cnt+1);
dfs((y-1+R)%R, x, mem, 'N', cnt+1);
}
if(field[y][x] == '.'){
if(dir == 'N') {
dfs((y-1+R)%R, x, mem, 'N', cnt+1);
}else if(dir == 'S'){
dfs((y+1+R)%R, x, mem, 'S', cnt+1);
}else if(dir == 'E'){
dfs(y, (x+1+C)%C, mem, 'E', cnt+1);
}else {
dfs(y, (x-1+C)%C, mem, 'W', cnt+1);
}
}
if(field[y][x] == '+'){
if(dir == 'N') {
dfs((y-1+R)%R, x, (mem+1+16)%16, 'N', cnt+1);
}else if(dir == 'S'){
dfs((y+1+R)%R, x, (mem+1+16)%16, 'S', cnt+1);
}else if(dir == 'E'){
dfs(y, (x+1+C)%C, (mem+1+16)%16, 'E', cnt+1);
}else {
dfs(y, (x-1+C)%C, (mem+1+16)%16, 'W', cnt+1);
}
}
if(field[y][x] == '-'){
if(dir == 'N') {
dfs((y-1+R)%R, x, (mem-1+16)%16, 'N', cnt+1);
}else if(dir == 'S'){
dfs((y+1+R)%R, x, (mem-1+16)%16, 'S', cnt+1);
}else if(dir == 'E'){
dfs(y, (x+1+C)%C, (mem-1+16)%16, 'E', cnt+1);
}else {
dfs(y, (x-1+C)%C, (mem-1+16)%16, 'W', cnt+1);
}
}
}
int main() {
//cout << fixed << setprecision(15);
cin >> R >> C;
REP(i, R){
string str; cin >> str;
field.push_back(str);
}
bool state[25][25][20][4];
mp['N'] = 0;
mp['S'] = 1;
mp['W'] = 2;
mp['E'] = 3;
REP(i, 25) REP(j, 25) REP(k, 20) REP(l, 4) state[i][j][k][l]=false;
dfs(0, 0, 0, 'E', 0);
if(f) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
Code 2: from collections import deque
r, c = map(int, input().split())
mp = [input() for _ in range(r)]
R, U, L, D = 0, 1, 2, 3
vec = ((1, 0), (0, -1), (-1, 0), (0, 1))
dic = {}
dic[(0, 0, R, 0)] = True
que = deque()
que.append((0, 0, R, 0))
while que:
x, y, direct, mem = que.popleft()
com = mp[y][x]
if com == "?":
for d in (R, U, L, D):
dx, dy = vec[d]
nx, ny = (x + dx) % c, (y + dy) % r
if (nx, ny, d, mem) not in dic:
dic[(nx, ny, d, mem)] = True
que.append((nx, ny, d, mem))
continue
elif com == "@":
print("YES")
break
elif com == "<":
direct = L
elif com == ">":
direct = R
elif com == "^":
direct = U
elif com == "v":
direct = D
elif com == "_":
direct = R if mem == 0 else L
elif com == "|":
direct = D if mem == 0 else U
elif com == ".":
pass
elif "0" <= com <= "9":
mem = int(com)
elif com == "+":
mem = (mem + 1) % 16
elif com == "-":
mem = (mem - 1) % 16
dx, dy = vec[direct]
nx, ny = (x + dx) % c, (y + dy) % r
if (nx, ny, direct, mem) not in dic:
dic[(nx, ny, direct, mem)] = True
que.append((nx, ny, direct, mem))
else:
print("NO")
|
C++ | #include <bits/stdc++.h>
#define REP(i, n) for(int i=0; i<(int)(n); i++)
#define REP1(i,a,b) for(int i=a; i<=(int)(b); i++)
#define ALL(x) begin(x),end(x)
#define PB push_back
using namespace std;
typedef int64_t LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
template<class T> inline bool chmax( T &a, const T &b ) { return b>a ? a=b,true : false; }
template<class T> inline bool chmin( T &a, const T &b ) { return b<a ? a=b,true : false; }
template<class T> using MaxHeap = priority_queue<T>;
template<class T> using MinHeap = priority_queue<T, vector<T>, greater<T>>;
template<class T, class F=less<T>> void sort_uniq( vector<T> &v, F f=F() ) {
sort(begin(v),end(v),f);
v.resize(unique(begin(v),end(v))-begin(v));
}
struct UnionFind
{
int n, num;
vector<int> sz, par;
UnionFind() {}
UnionFind(int n_) : n(n_), num(n_), sz(n_, 1), par(n_, 0) { iota(par.begin(), par.end(), 0); }
int find(int x)
{
return (x == par[x] ? x : par[x] = find(par[x]));
}
bool same(int x, int y)
{
return find(x) == find(y);
}
void unite(int x, int y)
{
x = find(x);
y = find(y);
if (x == y)
return;
if (sz[x] < sz[y])
swap(x, y);
sz[x] += sz[y];
par[y] = x;
num--;
}
int size(int x)
{
return sz[find(x)];
}
int count() const
{
return num;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m, k;
cin >> n >> m >> k;
UnionFind uf(n);
vector<int> fr[n];
vector<int> bl[n];
REP(i, m) {
int a, b;
cin >> a >> b;
--a; --b;
uf.unite(a, b);
fr[a].PB(b);
fr[b].PB(a);
}
REP(i, k) {
int a, b;
cin >> a >> b;
--a; --b;
bl[a].PB(b);
bl[b].PB(a);
}
REP(i, n) {
int sz = uf.size(i);
for(int j:bl[i]) {
if(uf.same(i, j)) sz--;
}
cout << sz - (int)fr[i].size() - 1 << " \n"[i==n-1];
}
return 0;
} | Python | n,a,b = map(int,input().split())
print(min(a * n , b))
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#define REP(i, n) for(int i=0; i<(int)(n); i++)
#define REP1(i,a,b) for(int i=a; i<=(int)(b); i++)
#define ALL(x) begin(x),end(x)
#define PB push_back
using namespace std;
typedef int64_t LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
template<class T> inline bool chmax( T &a, const T &b ) { return b>a ? a=b,true : false; }
template<class T> inline bool chmin( T &a, const T &b ) { return b<a ? a=b,true : false; }
template<class T> using MaxHeap = priority_queue<T>;
template<class T> using MinHeap = priority_queue<T, vector<T>, greater<T>>;
template<class T, class F=less<T>> void sort_uniq( vector<T> &v, F f=F() ) {
sort(begin(v),end(v),f);
v.resize(unique(begin(v),end(v))-begin(v));
}
struct UnionFind
{
int n, num;
vector<int> sz, par;
UnionFind() {}
UnionFind(int n_) : n(n_), num(n_), sz(n_, 1), par(n_, 0) { iota(par.begin(), par.end(), 0); }
int find(int x)
{
return (x == par[x] ? x : par[x] = find(par[x]));
}
bool same(int x, int y)
{
return find(x) == find(y);
}
void unite(int x, int y)
{
x = find(x);
y = find(y);
if (x == y)
return;
if (sz[x] < sz[y])
swap(x, y);
sz[x] += sz[y];
par[y] = x;
num--;
}
int size(int x)
{
return sz[find(x)];
}
int count() const
{
return num;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m, k;
cin >> n >> m >> k;
UnionFind uf(n);
vector<int> fr[n];
vector<int> bl[n];
REP(i, m) {
int a, b;
cin >> a >> b;
--a; --b;
uf.unite(a, b);
fr[a].PB(b);
fr[b].PB(a);
}
REP(i, k) {
int a, b;
cin >> a >> b;
--a; --b;
bl[a].PB(b);
bl[b].PB(a);
}
REP(i, n) {
int sz = uf.size(i);
for(int j:bl[i]) {
if(uf.same(i, j)) sz--;
}
cout << sz - (int)fr[i].size() - 1 << " \n"[i==n-1];
}
return 0;
}
Code 2: n,a,b = map(int,input().split())
print(min(a * n , b))
|
C++ | #include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int dp[1000000];
string S;
int main() {
cin >> S; dp[0] = 1;
for (int i = 0; i < S.size(); i++) {
if (dp[i] == 0)continue;
if (i + 5 <= S.size() && S.substr(i, 5) == "dream")dp[i + 5] = 1;
if (i + 7 <= S.size() && S.substr(i, 7) == "dreamer")dp[i + 7] = 1;
if (i + 5 <= S.size() && S.substr(i, 5) == "erase")dp[i + 5] = 1;
if (i + 6 <= S.size() && S.substr(i, 6) == "eraser")dp[i + 6] = 1;
}
if (dp[S.size()] == 1)cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
} | Python | import sys
S = input()
S = S[::-1]
temp = ''
for a in S:
temp += a
# dream,dreamer
if temp == "maerd" or temp == "remaerd" or temp == "esare" or temp == "resare":
temp = ""
if len(temp)>7:
print("NO")
sys.exit()
print("YES")
| Yes | Do these codes solve the same problem?
Code 1: #include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int dp[1000000];
string S;
int main() {
cin >> S; dp[0] = 1;
for (int i = 0; i < S.size(); i++) {
if (dp[i] == 0)continue;
if (i + 5 <= S.size() && S.substr(i, 5) == "dream")dp[i + 5] = 1;
if (i + 7 <= S.size() && S.substr(i, 7) == "dreamer")dp[i + 7] = 1;
if (i + 5 <= S.size() && S.substr(i, 5) == "erase")dp[i + 5] = 1;
if (i + 6 <= S.size() && S.substr(i, 6) == "eraser")dp[i + 6] = 1;
}
if (dp[S.size()] == 1)cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
Code 2: import sys
S = input()
S = S[::-1]
temp = ''
for a in S:
temp += a
# dream,dreamer
if temp == "maerd" or temp == "remaerd" or temp == "esare" or temp == "resare":
temp = ""
if len(temp)>7:
print("NO")
sys.exit()
print("YES")
|
C++ | #include <bits/stdc++.h>
#define _overload3(_1,_2,_3,name,...)name
#define _rep(i,n)repi(i,0,n)
#define repi(i,a,b)for(int i=int(a),i##_len=(b);i<i##_len;++i)
#define MSVC_UNKO(x)x
#define rep(...)MSVC_UNKO(_overload3(__VA_ARGS__,repi,_rep,_rep)(__VA_ARGS__))
#define all(c)c.begin(),c.end()
#define write(x)cout<<(x)<<'\n'
using namespace std; using ll = long long; template<class T>using vv = vector<vector<T>>;
template<class T>auto vvec(int n, int m, T v) { return vv<T>(n, vector<T>(m, v)); }
constexpr int INF = 1 << 29, MOD = int(1e9) + 7; constexpr ll LINF = 1LL << 60;
struct aaa { aaa() { cin.tie(0); ios::sync_with_stdio(0); cout << fixed << setprecision(10); }; }aaaa;
struct PrimeFactorization {
vector<pair<int, int>> factors;
void factor(ll n) {
int sqrt_n = (int)(sqrt(n) + 0.5);
primes.clear();
isPrime.assign(sqrt_n + 1, true);
for (int k = 2; k <= sqrt_n; ++k) {
if (!isPrime[k]) continue;
primes.push_back(k);
for (int m = k * 2; m <= sqrt_n; m += k) isPrime[m] = false;
}
factors.clear();
for (int i = 0; i < (int)primes.size() && n > 1; ++i) {
if (n % primes[i] != 0) continue;
factors.emplace_back(primes[i], 0);
for (; n % primes[i] == 0; n /= primes[i]) factors.back().second++;
}
if (n > 1) factors.emplace_back(n, 1);
sort(factors.begin(), factors.end());
}
pair<int, int> operator [](int i) const { return factors[i]; }
int size() const { return factors.size(); }
private:
vector<int> primes;
vector<bool> isPrime;
};
int main() {
ll N;
cin >> N;
if (N == 1) {
write(0);
return 0;
}
PrimeFactorization pf;
pf.factor(N);
int ans = 0;
rep(i, pf.size()) {
int exp = pf[i].second;
rep(e, 1, pf[i].second + 1) {
if (e <= exp) {
ans++;
exp -= e;
}
else break;
}
}
write(ans);
}
| Python | h,w = map(int, input().split())
a = list(map(int, input().split())) + [0]
b = list(map(int, input().split())) + [0]
mod = 10**9 + 7
a.sort(reverse=True)
b.sort(reverse=True)
if len(set(a)) <= h or len(set(b)) <= w:
print(0); exit(0)
cnt = 1
ai,bi = 0,0
for i in range(h*w,0,-1):
while a[ai] > i: ai += 1
while b[bi] > i: bi += 1
if a[ai] == b[bi] == i: pass
elif a[ai] == i: cnt *= bi
elif b[bi] == i: cnt *= ai
else: cnt *= ai*bi - h*w + i
cnt %= mod
print(cnt) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#define _overload3(_1,_2,_3,name,...)name
#define _rep(i,n)repi(i,0,n)
#define repi(i,a,b)for(int i=int(a),i##_len=(b);i<i##_len;++i)
#define MSVC_UNKO(x)x
#define rep(...)MSVC_UNKO(_overload3(__VA_ARGS__,repi,_rep,_rep)(__VA_ARGS__))
#define all(c)c.begin(),c.end()
#define write(x)cout<<(x)<<'\n'
using namespace std; using ll = long long; template<class T>using vv = vector<vector<T>>;
template<class T>auto vvec(int n, int m, T v) { return vv<T>(n, vector<T>(m, v)); }
constexpr int INF = 1 << 29, MOD = int(1e9) + 7; constexpr ll LINF = 1LL << 60;
struct aaa { aaa() { cin.tie(0); ios::sync_with_stdio(0); cout << fixed << setprecision(10); }; }aaaa;
struct PrimeFactorization {
vector<pair<int, int>> factors;
void factor(ll n) {
int sqrt_n = (int)(sqrt(n) + 0.5);
primes.clear();
isPrime.assign(sqrt_n + 1, true);
for (int k = 2; k <= sqrt_n; ++k) {
if (!isPrime[k]) continue;
primes.push_back(k);
for (int m = k * 2; m <= sqrt_n; m += k) isPrime[m] = false;
}
factors.clear();
for (int i = 0; i < (int)primes.size() && n > 1; ++i) {
if (n % primes[i] != 0) continue;
factors.emplace_back(primes[i], 0);
for (; n % primes[i] == 0; n /= primes[i]) factors.back().second++;
}
if (n > 1) factors.emplace_back(n, 1);
sort(factors.begin(), factors.end());
}
pair<int, int> operator [](int i) const { return factors[i]; }
int size() const { return factors.size(); }
private:
vector<int> primes;
vector<bool> isPrime;
};
int main() {
ll N;
cin >> N;
if (N == 1) {
write(0);
return 0;
}
PrimeFactorization pf;
pf.factor(N);
int ans = 0;
rep(i, pf.size()) {
int exp = pf[i].second;
rep(e, 1, pf[i].second + 1) {
if (e <= exp) {
ans++;
exp -= e;
}
else break;
}
}
write(ans);
}
Code 2: h,w = map(int, input().split())
a = list(map(int, input().split())) + [0]
b = list(map(int, input().split())) + [0]
mod = 10**9 + 7
a.sort(reverse=True)
b.sort(reverse=True)
if len(set(a)) <= h or len(set(b)) <= w:
print(0); exit(0)
cnt = 1
ai,bi = 0,0
for i in range(h*w,0,-1):
while a[ai] > i: ai += 1
while b[bi] > i: bi += 1
if a[ai] == b[bi] == i: pass
elif a[ai] == i: cnt *= bi
elif b[bi] == i: cnt *= ai
else: cnt *= ai*bi - h*w + i
cnt %= mod
print(cnt) |
Java |
import java.util.Scanner;
public class Main {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
if (n % 2 == 1) {
int a = 1;
int b = n;
for (int i = 0; i < m; ++i) {
System.out.println(a + " " + b);
a++;
b--;
}
} else {
int aOdd = 1;
int bOdd = n;
int [] used = new int[n + 1];
for (int i = 0; i < (m + 1) / 2; ++i) {
System.out.println(aOdd + " " + bOdd);
used[aOdd] = 1;
used[bOdd] = 1;
aOdd++;
bOdd--;
}
int aEven = 2;
int bEven = n;
while (used[aEven] == 1 || used[bEven] == 1) {
aEven++;
bEven--;
}
for (int i = 0; i < m - (m + 1) / 2; ++i) {
System.out.println(aEven + " " + bEven);
aEven++;
bEven--;
}
}
}
}
| Python | import heapq as hq
n,q = map(int,input().split())
a = [[] for i in range(n)]
for i in range(q):
k = list(map(int,input().split()))
if k[0] == 0:
hq.heappush(a[k[1]],-k[2])
elif k[0] == 1:
a[k[1]] and print(-a[k[1]][0])
else:
a[k[1]] and hq.heappop(a[k[1]])
| No | Do these codes solve the same problem?
Code 1:
import java.util.Scanner;
public class Main {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
if (n % 2 == 1) {
int a = 1;
int b = n;
for (int i = 0; i < m; ++i) {
System.out.println(a + " " + b);
a++;
b--;
}
} else {
int aOdd = 1;
int bOdd = n;
int [] used = new int[n + 1];
for (int i = 0; i < (m + 1) / 2; ++i) {
System.out.println(aOdd + " " + bOdd);
used[aOdd] = 1;
used[bOdd] = 1;
aOdd++;
bOdd--;
}
int aEven = 2;
int bEven = n;
while (used[aEven] == 1 || used[bEven] == 1) {
aEven++;
bEven--;
}
for (int i = 0; i < m - (m + 1) / 2; ++i) {
System.out.println(aEven + " " + bEven);
aEven++;
bEven--;
}
}
}
}
Code 2: import heapq as hq
n,q = map(int,input().split())
a = [[] for i in range(n)]
for i in range(q):
k = list(map(int,input().split()))
if k[0] == 0:
hq.heappush(a[k[1]],-k[2])
elif k[0] == 1:
a[k[1]] and print(-a[k[1]][0])
else:
a[k[1]] and hq.heappop(a[k[1]])
|
C++ | #include<bits/stdc++.h>
#include<math.h>
using namespace std;
#define int long long int
int i,j;
main()
{
int n,m;
cin>>n>>m;
int a[m]; int s=0;
for(i=0;i<m;i++) {cin>>a[i];s=s+a[i];}
if(s<=n) cout<<n-s<<endl;
else cout<<-1<<endl;
}
| Python | a=list(map(int,input().split()))
al=sum(a)
if al <=21:
print("win")
else:
print("bust") | No | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
#include<math.h>
using namespace std;
#define int long long int
int i,j;
main()
{
int n,m;
cin>>n>>m;
int a[m]; int s=0;
for(i=0;i<m;i++) {cin>>a[i];s=s+a[i];}
if(s<=n) cout<<n-s<<endl;
else cout<<-1<<endl;
}
Code 2: a=list(map(int,input().split()))
al=sum(a)
if al <=21:
print("win")
else:
print("bust") |
C | // AOJ 2928 Mail Order
// 2019.4.5 bal4u
#include <stdio.h>
#include <stdlib.h>
//// 高速入力
#if 1
#define gc() getchar_unlocked()
#else
#define gc() getchar()
#endif
int in()
{
int n = 0, c = gc();
do n = 10 * n + (c & 0xf), c = gc(); while (c >= '0');
return n;
}
int H, W;
int _a[100005];
int _b[100005];
int *a, *b;
long long s[100005];
int upper_bound(int x)
{
int m, l = 0, r = W;
while (l < r) {
m = (l + r) >> 1;
if (b[m] == x) return m;
if (b[m] < x) l = m + 1; else r = m;
}
return l - 1;
}
int cmp(const void *a, const void *b) { return *(int *)a - *(int *)b; }
int main()
{
int i, k, t;
long long ans;
H = in(), W = in();
for (i = 0; i < H; i++) _a[i] = in();
for (i = 0; i < W; i++) _b[i] = in();
if (H > W) t = H, H = W, W = t, a = _b, b = _a; // 短い方を H, a[] にする
else a = _a, b = _b;
qsort(b, W, sizeof(int), cmp);
for (i = 0; i < W; i++) s[i + 1] = s[i] + b[i]; // 累計和
ans = 0; for (i = 0; i < H; i++) {
k = upper_bound(a[i]); // バイナリサーチでa[i]を超えない最大値のindexを得る
ans += s[k + 1] + (long long)(W - k - 1)*a[i];
}
printf("%lld\n", ans);
return 0;
}
| C# | using System;
using System.Linq;
using System.Collections.Generic;
namespace N
{
class Program
{
static bool IsOK(int[] arr, int index, int key)
{
if (arr[index] >= key) return true;
else return false;
}
static int Binary_search(int[] arr, int key)
{
int ng = -1;
int ok = arr.Count();
while (ok - ng > 1)
{
int mid = ng + (ok - ng) / 2;
if (IsOK(arr, mid, key)) ok = mid;
else ng = mid;
}
return ok;
}
static void Main(string[] args)
{
int[] x = Console.ReadLine().Split().Select(int.Parse).ToArray();
int[] a = Console.ReadLine().Split().Select(int.Parse).ToArray();
int[] b = Console.ReadLine().Split().Select(int.Parse).ToArray();
Array.Sort(a); Array.Sort(b);
long ret = 0;
for (long i = 0; i < x[0]; i++)
{
ret += (x[1] - (long)Binary_search(b, a[i])) * a[i];
}
for (long i = 0; i < x[1]; i++)
{
ret += (x[0] - (long)Binary_search(a, b[i])) * b[i];
}
Dictionary<int, Tuple<int, int>> dic = new Dictionary<int, Tuple<int, int>>();
for (int i = 0; i < x[0]; i++)
{
if (!dic.ContainsKey(a[i])) dic[a[i]] = new Tuple<int, int>(0, 0);
dic[a[i]] = new Tuple<int, int>(dic[a[i]].Item1 + 1, dic[a[i]].Item2);
}
for (int i = 0; i < x[1]; i++)
{
if (!dic.ContainsKey(b[i])) dic[b[i]] = new Tuple<int, int>(0, 0);
dic[b[i]] = new Tuple<int, int>(dic[b[i]].Item1, dic[b[i]].Item2 + 1);
}
foreach (var item in dic)
{
ret -= (long)item.Key * item.Value.Item1 * item.Value.Item2;
}
Console.WriteLine(ret);
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: // AOJ 2928 Mail Order
// 2019.4.5 bal4u
#include <stdio.h>
#include <stdlib.h>
//// 高速入力
#if 1
#define gc() getchar_unlocked()
#else
#define gc() getchar()
#endif
int in()
{
int n = 0, c = gc();
do n = 10 * n + (c & 0xf), c = gc(); while (c >= '0');
return n;
}
int H, W;
int _a[100005];
int _b[100005];
int *a, *b;
long long s[100005];
int upper_bound(int x)
{
int m, l = 0, r = W;
while (l < r) {
m = (l + r) >> 1;
if (b[m] == x) return m;
if (b[m] < x) l = m + 1; else r = m;
}
return l - 1;
}
int cmp(const void *a, const void *b) { return *(int *)a - *(int *)b; }
int main()
{
int i, k, t;
long long ans;
H = in(), W = in();
for (i = 0; i < H; i++) _a[i] = in();
for (i = 0; i < W; i++) _b[i] = in();
if (H > W) t = H, H = W, W = t, a = _b, b = _a; // 短い方を H, a[] にする
else a = _a, b = _b;
qsort(b, W, sizeof(int), cmp);
for (i = 0; i < W; i++) s[i + 1] = s[i] + b[i]; // 累計和
ans = 0; for (i = 0; i < H; i++) {
k = upper_bound(a[i]); // バイナリサーチでa[i]を超えない最大値のindexを得る
ans += s[k + 1] + (long long)(W - k - 1)*a[i];
}
printf("%lld\n", ans);
return 0;
}
Code 2: using System;
using System.Linq;
using System.Collections.Generic;
namespace N
{
class Program
{
static bool IsOK(int[] arr, int index, int key)
{
if (arr[index] >= key) return true;
else return false;
}
static int Binary_search(int[] arr, int key)
{
int ng = -1;
int ok = arr.Count();
while (ok - ng > 1)
{
int mid = ng + (ok - ng) / 2;
if (IsOK(arr, mid, key)) ok = mid;
else ng = mid;
}
return ok;
}
static void Main(string[] args)
{
int[] x = Console.ReadLine().Split().Select(int.Parse).ToArray();
int[] a = Console.ReadLine().Split().Select(int.Parse).ToArray();
int[] b = Console.ReadLine().Split().Select(int.Parse).ToArray();
Array.Sort(a); Array.Sort(b);
long ret = 0;
for (long i = 0; i < x[0]; i++)
{
ret += (x[1] - (long)Binary_search(b, a[i])) * a[i];
}
for (long i = 0; i < x[1]; i++)
{
ret += (x[0] - (long)Binary_search(a, b[i])) * b[i];
}
Dictionary<int, Tuple<int, int>> dic = new Dictionary<int, Tuple<int, int>>();
for (int i = 0; i < x[0]; i++)
{
if (!dic.ContainsKey(a[i])) dic[a[i]] = new Tuple<int, int>(0, 0);
dic[a[i]] = new Tuple<int, int>(dic[a[i]].Item1 + 1, dic[a[i]].Item2);
}
for (int i = 0; i < x[1]; i++)
{
if (!dic.ContainsKey(b[i])) dic[b[i]] = new Tuple<int, int>(0, 0);
dic[b[i]] = new Tuple<int, int>(dic[b[i]].Item1, dic[b[i]].Item2 + 1);
}
foreach (var item in dic)
{
ret -= (long)item.Key * item.Value.Item1 * item.Value.Item2;
}
Console.WriteLine(ret);
}
}
}
|
Java | import java.util.*;
class Graph {
private int totalVertex;
private LinkedList<LinkedList<Integer>> adjList;
private LinkedList<Boolean> visited;
private ArrayList<Integer>dist;
public Graph() {
totalVertex = 0;
visited = new LinkedList<Boolean>();
dist = new ArrayList<Integer>();
}
public void loadAdjList() {
Scanner in = new Scanner(System.in);
totalVertex = in.nextInt();
adjList = new LinkedList<LinkedList<Integer>>();
for(int i = 0; i < totalVertex; i ++) {
LinkedList<Integer> tmp = new LinkedList<Integer>();
in.nextInt();
int degree = in.nextInt();
for(int j = 0; j < degree; j ++) {
int idx2 = in.nextInt() - 1;
tmp.add(idx2);
}
adjList.add(tmp);
}
in.close();
}
public int nextUnvisited() {
for(int i = 0; i < visited.size(); i ++) {
if(visited.get(i) == false) {
return i;
}
}
return -1;
}
public void preWalk() {
visited.clear();
dist.clear();
for(int i = 0; i < totalVertex; i ++) {
visited.add(false);
dist.add(0);
}
}
public void walk() {
preWalk();
BFS(0);
}
public boolean ifVisited(int v) {
if (v >= 0 && v < totalVertex)
return visited.get(v);
else
return true;
}
public void setVisited(int v) { visited.set(v, true); }
public void BFS(int v) {
int distance = 0;
LinkedList<Integer> queue = new LinkedList<Integer>();
setVisited(v);
queue.add(v);
dist.set(v, distance);
while (queue.size() != 0) {
v = queue.poll();
Iterator<Integer> i = adjList.get(v).listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited.get(n)) {
visited.set(n, true);
dist.set(n, dist.get(v) + 1);
queue.add(n);
}
}
}
}
public void displayEnum() {
for (int i = 0; i < totalVertex; i++) {
if (visited.get(i) == false) {
System.out.print((i + 1) + " " + -1 + "\n");
} else {
System.out.print((i + 1) + " " + dist.get(i) + "\n");
}
}
}
}
public class Main {
public static void main(String[] args) {
Graph g = new Graph();
g.loadAdjList();
g.walk();
g.displayEnum();
}
}
| C++ | #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, x;
cin >> a >> b;
if ((a + b) % 2 == 0) {
x = (a + b) / 2;
} else {
x = (a + b) / 2 + 1;
}
cout << x << endl;
} | No | Do these codes solve the same problem?
Code 1: import java.util.*;
class Graph {
private int totalVertex;
private LinkedList<LinkedList<Integer>> adjList;
private LinkedList<Boolean> visited;
private ArrayList<Integer>dist;
public Graph() {
totalVertex = 0;
visited = new LinkedList<Boolean>();
dist = new ArrayList<Integer>();
}
public void loadAdjList() {
Scanner in = new Scanner(System.in);
totalVertex = in.nextInt();
adjList = new LinkedList<LinkedList<Integer>>();
for(int i = 0; i < totalVertex; i ++) {
LinkedList<Integer> tmp = new LinkedList<Integer>();
in.nextInt();
int degree = in.nextInt();
for(int j = 0; j < degree; j ++) {
int idx2 = in.nextInt() - 1;
tmp.add(idx2);
}
adjList.add(tmp);
}
in.close();
}
public int nextUnvisited() {
for(int i = 0; i < visited.size(); i ++) {
if(visited.get(i) == false) {
return i;
}
}
return -1;
}
public void preWalk() {
visited.clear();
dist.clear();
for(int i = 0; i < totalVertex; i ++) {
visited.add(false);
dist.add(0);
}
}
public void walk() {
preWalk();
BFS(0);
}
public boolean ifVisited(int v) {
if (v >= 0 && v < totalVertex)
return visited.get(v);
else
return true;
}
public void setVisited(int v) { visited.set(v, true); }
public void BFS(int v) {
int distance = 0;
LinkedList<Integer> queue = new LinkedList<Integer>();
setVisited(v);
queue.add(v);
dist.set(v, distance);
while (queue.size() != 0) {
v = queue.poll();
Iterator<Integer> i = adjList.get(v).listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited.get(n)) {
visited.set(n, true);
dist.set(n, dist.get(v) + 1);
queue.add(n);
}
}
}
}
public void displayEnum() {
for (int i = 0; i < totalVertex; i++) {
if (visited.get(i) == false) {
System.out.print((i + 1) + " " + -1 + "\n");
} else {
System.out.print((i + 1) + " " + dist.get(i) + "\n");
}
}
}
}
public class Main {
public static void main(String[] args) {
Graph g = new Graph();
g.loadAdjList();
g.walk();
g.displayEnum();
}
}
Code 2: #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, x;
cin >> a >> b;
if ((a + b) % 2 == 0) {
x = (a + b) / 2;
} else {
x = (a + b) / 2 + 1;
}
cout << x << endl;
} |
C# | using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
int[] X = Console.ReadLine().Split(' ').Select(o => int.Parse(o)).ToArray();
Console.WriteLine(Enumerable.Range(1, X.Max()).Select(P => X.Select(Xi => (int)Math.Pow(Xi - P, 2)).Sum()).Min());
}
} | C++ | bool DBG = false;
// #pragma GCC optimize("Ofast")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
// #pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
//#include <boost/multiprecision/cpp_dec_float.hpp>
//#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using ll = long long;
using ld = long double;
//using i128 = __int128_t;
//using bint = boost::multiprecision::cpp_int
//using d1024 = boost::multiprecision::number<mp::cpp_dec_float<1024>>;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define IFOR(i,a,b) for(int i=((b)-1);i>=(a);--i)
#define RPT(i,a,b) for(int i=(a);i<((a)+(b));++i)
#define IRPT(i,a,b) for(int i=((a)+(b)-1);i>=(a);--i)
#define ALL(x) x.begin(),x.end()
#define RALL(x) x.rbegin(),x.rend()
#define fs first
#define sd second
#define couts(x) cout << (x) << (" ")
#define coutn(x) cout << (x) << ("\n")
#define ncouts(x) numout(x),outst[outst_N++] = ' '
#define ncoutn(x) numout(x),outst[outst_N++] = '\n'
#define scouts(x) strout(x),outst[outst_N++] = ' '
#define scoutn(x) strout(x),outst[outst_N++] = '\n'
#define dcouts(x) if(DBG) couts(x)
#define dcoutn(x) if(DBG) coutn(x)
#define endl "\n"
#define psb push_back
#define ppb pop_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define LBIT(x,a) (((x)>>(a))&1LL)
#define IBIT(x,a) (((x)>>(a))&1)
#define BCOUNT(x) (__builtin_popcount(x))
template<typename T> std::istream &operator>>(std::istream &is, std::vector<T> &vec){ for (auto &v : vec) is >> v; return is; }
template<typename T1, typename T2> std::istream &operator>>(std::istream &is, std::pair<T1,T2> &p){is >> p.first >> p.second; return is; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec){ os << "["; for (auto v : vec) os << v << ","; os << "]"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::deque<T> &vec){ os << "deque["; for (auto v : vec) os << v << ","; os << "]"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::set<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::unordered_set<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::multiset<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::unordered_multiset<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T1, typename T2> std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &pa){ os << "(" << pa.first << "," << pa.second << ")"; return os; }
template<typename TK, typename TV> std::ostream &operator<<(std::ostream &os, const std::map<TK, TV> &mp){ os << "{"; for (auto v : mp) os << v.first << "=>" << v.second << ","; os << "}"; return os; }
template<typename TK, typename TV> std::ostream &operator<<(std::ostream &os, const std::unordered_map<TK, TV> &mp){ os << "{"; for (auto v : mp) os << v.first << "=>" << v.second << ","; os << "}"; return os; }
template<class T> using V = vector<T>;
template<class T> using V2 = V<V<T>>;
template<class T> using V3 = V<V2<T>>;
template<class T> using V4 = V<V3<T>>;
char outst[20'000'000]; int outst_N = 0;
char outst_tmp[200];
template<class NUM >
void numout(NUM n){
if(n<0) { n*=-1; outst[outst_N++] = '-';}
if(n==0){ outst[outst_N++] = '0'; return;}
int cnt = 0;
while(n>0){
outst_tmp[cnt++] = '0' + (n % 10);
n /= 10;
}
IFOR(i,0,cnt){
outst[outst_N++] = outst_tmp[i];
}
}
void strout(std::string s){
for(auto x: s){
outst[outst_N++] = x;
}
}
constexpr ll LINF = 1LL << 60;
constexpr int IINF = 1 << 28;
constexpr ll mod = 1'000'000'007;
void solve(){
int n, k; cin >> n >> k;
string s; cin >> s;
int t = s[0] - '0', t0 = t; V<int> a; int cnt = 0;
FOR(i,0,n){
if(t!=(s[i]-'0') ){
t ^= 1;
a.eb( cnt );
cnt = 0;
}
++cnt;
}
a.eb( cnt);
//coutn( a );
int len = 2*k;
int sum = 0; int r=0;int ans = 0;
for(int l=0; l<a.size(); l++){
while(r<a.size() && r-l<len+((l%2)^t0) ){
sum += a[r];
++r;
}
ans = max(sum,ans); //couts(l); couts(r); couts(t0);coutn(sum);
sum -= a[l];
}
coutn(ans);
}
int main(void){
//std::cout << std::fixed << std::setprecision(20);
cin.tie(0);
//ios::sync_with_stdio(false);
solve();
//printf("%s", outst);
return 0;
}
| No | Do these codes solve the same problem?
Code 1: using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
int[] X = Console.ReadLine().Split(' ').Select(o => int.Parse(o)).ToArray();
Console.WriteLine(Enumerable.Range(1, X.Max()).Select(P => X.Select(Xi => (int)Math.Pow(Xi - P, 2)).Sum()).Min());
}
}
Code 2: bool DBG = false;
// #pragma GCC optimize("Ofast")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
// #pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
//#include <boost/multiprecision/cpp_dec_float.hpp>
//#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using ll = long long;
using ld = long double;
//using i128 = __int128_t;
//using bint = boost::multiprecision::cpp_int
//using d1024 = boost::multiprecision::number<mp::cpp_dec_float<1024>>;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define IFOR(i,a,b) for(int i=((b)-1);i>=(a);--i)
#define RPT(i,a,b) for(int i=(a);i<((a)+(b));++i)
#define IRPT(i,a,b) for(int i=((a)+(b)-1);i>=(a);--i)
#define ALL(x) x.begin(),x.end()
#define RALL(x) x.rbegin(),x.rend()
#define fs first
#define sd second
#define couts(x) cout << (x) << (" ")
#define coutn(x) cout << (x) << ("\n")
#define ncouts(x) numout(x),outst[outst_N++] = ' '
#define ncoutn(x) numout(x),outst[outst_N++] = '\n'
#define scouts(x) strout(x),outst[outst_N++] = ' '
#define scoutn(x) strout(x),outst[outst_N++] = '\n'
#define dcouts(x) if(DBG) couts(x)
#define dcoutn(x) if(DBG) coutn(x)
#define endl "\n"
#define psb push_back
#define ppb pop_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define LBIT(x,a) (((x)>>(a))&1LL)
#define IBIT(x,a) (((x)>>(a))&1)
#define BCOUNT(x) (__builtin_popcount(x))
template<typename T> std::istream &operator>>(std::istream &is, std::vector<T> &vec){ for (auto &v : vec) is >> v; return is; }
template<typename T1, typename T2> std::istream &operator>>(std::istream &is, std::pair<T1,T2> &p){is >> p.first >> p.second; return is; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec){ os << "["; for (auto v : vec) os << v << ","; os << "]"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::deque<T> &vec){ os << "deque["; for (auto v : vec) os << v << ","; os << "]"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::set<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::unordered_set<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::multiset<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> std::ostream &operator<<(std::ostream &os, const std::unordered_multiset<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T1, typename T2> std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &pa){ os << "(" << pa.first << "," << pa.second << ")"; return os; }
template<typename TK, typename TV> std::ostream &operator<<(std::ostream &os, const std::map<TK, TV> &mp){ os << "{"; for (auto v : mp) os << v.first << "=>" << v.second << ","; os << "}"; return os; }
template<typename TK, typename TV> std::ostream &operator<<(std::ostream &os, const std::unordered_map<TK, TV> &mp){ os << "{"; for (auto v : mp) os << v.first << "=>" << v.second << ","; os << "}"; return os; }
template<class T> using V = vector<T>;
template<class T> using V2 = V<V<T>>;
template<class T> using V3 = V<V2<T>>;
template<class T> using V4 = V<V3<T>>;
char outst[20'000'000]; int outst_N = 0;
char outst_tmp[200];
template<class NUM >
void numout(NUM n){
if(n<0) { n*=-1; outst[outst_N++] = '-';}
if(n==0){ outst[outst_N++] = '0'; return;}
int cnt = 0;
while(n>0){
outst_tmp[cnt++] = '0' + (n % 10);
n /= 10;
}
IFOR(i,0,cnt){
outst[outst_N++] = outst_tmp[i];
}
}
void strout(std::string s){
for(auto x: s){
outst[outst_N++] = x;
}
}
constexpr ll LINF = 1LL << 60;
constexpr int IINF = 1 << 28;
constexpr ll mod = 1'000'000'007;
void solve(){
int n, k; cin >> n >> k;
string s; cin >> s;
int t = s[0] - '0', t0 = t; V<int> a; int cnt = 0;
FOR(i,0,n){
if(t!=(s[i]-'0') ){
t ^= 1;
a.eb( cnt );
cnt = 0;
}
++cnt;
}
a.eb( cnt);
//coutn( a );
int len = 2*k;
int sum = 0; int r=0;int ans = 0;
for(int l=0; l<a.size(); l++){
while(r<a.size() && r-l<len+((l%2)^t0) ){
sum += a[r];
++r;
}
ans = max(sum,ans); //couts(l); couts(r); couts(t0);coutn(sum);
sum -= a[l];
}
coutn(ans);
}
int main(void){
//std::cout << std::fixed << std::setprecision(20);
cin.tie(0);
//ios::sync_with_stdio(false);
solve();
//printf("%s", outst);
return 0;
}
|
Go | package main
import (
"fmt"
)
func main() {
var n int
fmt.Scan(&n)
if n == 1 {
fmt.Println("Hello World")
return
}
var a, b int
fmt.Scan(&a, &b)
fmt.Println(a + b)
}
| C# | using System;
using System.Linq;
using System.Collections.Generic;
class Program{
static long Get(long n, long x, long result)
{
//Console.WriteLine($"{n} {x} {result}");
if(x == 0) return result;
if(n < x) return Get(x, n, result);
return Get(x, n % x, result + n / x * x * 3);
}
static void Main()
{
string[] inputs = Console.ReadLine().Split();
long n = long.Parse(inputs[0]);
long x = long.Parse(inputs[1]);
Console.WriteLine(Get(n -x, x, 0));
}
}
| No | Do these codes solve the same problem?
Code 1: package main
import (
"fmt"
)
func main() {
var n int
fmt.Scan(&n)
if n == 1 {
fmt.Println("Hello World")
return
}
var a, b int
fmt.Scan(&a, &b)
fmt.Println(a + b)
}
Code 2: using System;
using System.Linq;
using System.Collections.Generic;
class Program{
static long Get(long n, long x, long result)
{
//Console.WriteLine($"{n} {x} {result}");
if(x == 0) return result;
if(n < x) return Get(x, n, result);
return Get(x, n % x, result + n / x * x * 3);
}
static void Main()
{
string[] inputs = Console.ReadLine().Split();
long n = long.Parse(inputs[0]);
long x = long.Parse(inputs[1]);
Console.WriteLine(Get(n -x, x, 0));
}
}
|
C | #include<stdio.h>
#include<math.h>
typedef struct{
int val;
int node;
}sd;
int sdsortfnc(const void *a,const void *b){
if(((sd*)a)->val < ((sd*)b)->val){return -1;}
if(((sd*)a)->val > ((sd*)b)->val){return 1;}
return 0;
}
void coordinate_comp(int a[],int n){
int i,c=1;
sd dat[524288];
for(i=0;i<n;i++){
dat[i].val=a[i];
dat[i].node=i;
}
qsort(dat,n,sizeof(dat[0]),sdsortfnc);
a[dat[0].node]=c;
for(i=1;i<n;i++){
if(dat[i-1].val!=dat[i].val){c++;}
a[dat[i].node]=c;
}
}
int main(){
int n,t[524288],a[524288],q,i,equ[524288]={0};
double rss[524288];
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d%d",&t[i],&a[i]);
}
scanf("%d",&q);
for(i=0;i<q;i++){
scanf("%d%d",&t[n+i],&t[n+q+i]);
}
coordinate_comp(t,n+2*q);
rss[0]=1.0;
for(i=0;i<n;i++){
equ[t[i]]=a[i];
}
for(i=1;i<524288;i++){
rss[i]=rss[i-1]+log(10.0-(double)equ[i])-log(10.0);
}
for(i=0;i<q;i++){
printf("%.12lf\n",1.0e9*exp(rss[t[n+q+i]]-rss[t[n+i]]));
}
}
| C++ | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i, a, b) for(int i = a; i < b; i++)
int main(){
int N; cin >> N;
vector<pii> P(N+1), K(N+1);
vector<double> CM(N+1);
rep(i, 1, N+1) cin >> P[i].first >> P[i].second;
rep(i, 1, N + 1) K[i] = {P[i].first, i};
CM[0] = 1;
rep(i, 1, N +1) CM[i] = (100.0 - P[i].second *10) / 100.0 * CM[i-1];
int Q; cin >> Q;
vector<pii> query(N);
rep(i, 0, Q) cin >> query[i].first >> query[i].second;
rep(i, 0, Q){
int L = query[i].first, R = query[i].second;
auto it1 = lower_bound(K.begin(), K.end(), make_pair(L,0));
auto it2 = lower_bound(K.begin(), K.end(), make_pair(R,0));
it1--,it2--;
cout << fixed << setprecision(10) << 1e9 * CM[(*it2).second] / CM[(*it1).second] << endl;
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
#include<math.h>
typedef struct{
int val;
int node;
}sd;
int sdsortfnc(const void *a,const void *b){
if(((sd*)a)->val < ((sd*)b)->val){return -1;}
if(((sd*)a)->val > ((sd*)b)->val){return 1;}
return 0;
}
void coordinate_comp(int a[],int n){
int i,c=1;
sd dat[524288];
for(i=0;i<n;i++){
dat[i].val=a[i];
dat[i].node=i;
}
qsort(dat,n,sizeof(dat[0]),sdsortfnc);
a[dat[0].node]=c;
for(i=1;i<n;i++){
if(dat[i-1].val!=dat[i].val){c++;}
a[dat[i].node]=c;
}
}
int main(){
int n,t[524288],a[524288],q,i,equ[524288]={0};
double rss[524288];
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d%d",&t[i],&a[i]);
}
scanf("%d",&q);
for(i=0;i<q;i++){
scanf("%d%d",&t[n+i],&t[n+q+i]);
}
coordinate_comp(t,n+2*q);
rss[0]=1.0;
for(i=0;i<n;i++){
equ[t[i]]=a[i];
}
for(i=1;i<524288;i++){
rss[i]=rss[i-1]+log(10.0-(double)equ[i])-log(10.0);
}
for(i=0;i<q;i++){
printf("%.12lf\n",1.0e9*exp(rss[t[n+q+i]]-rss[t[n+i]]));
}
}
Code 2: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i, a, b) for(int i = a; i < b; i++)
int main(){
int N; cin >> N;
vector<pii> P(N+1), K(N+1);
vector<double> CM(N+1);
rep(i, 1, N+1) cin >> P[i].first >> P[i].second;
rep(i, 1, N + 1) K[i] = {P[i].first, i};
CM[0] = 1;
rep(i, 1, N +1) CM[i] = (100.0 - P[i].second *10) / 100.0 * CM[i-1];
int Q; cin >> Q;
vector<pii> query(N);
rep(i, 0, Q) cin >> query[i].first >> query[i].second;
rep(i, 0, Q){
int L = query[i].first, R = query[i].second;
auto it1 = lower_bound(K.begin(), K.end(), make_pair(L,0));
auto it2 = lower_bound(K.begin(), K.end(), make_pair(R,0));
it1--,it2--;
cout << fixed << setprecision(10) << 1e9 * CM[(*it2).second] / CM[(*it1).second] << endl;
}
}
|
C++ | #pragma comment(linker, "/STACK:102400000,102400000")
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define lson root<<1,l,mid
#define rson root<<1|1,mid+1,r
#define Key_Value ch[ch[root][1]][0]
#define DBN1(a) cerr<<#a<<"="<<(a)<<"\n"
#define DBN2(a,b) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<"\n"
#define DBN3(a,b,c) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<"\n"
#define DBN4(a,b,c,d) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<"\n"
#define DBN5(a,b,c,d,e) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<"\n"
#define DBN6(a,b,c,d,e,f) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<", "<<#f<<"="<<(f)<<"\n"
#define clr(a,x) memset(a,x,sizeof(a))
#define pb push_back
#define mp make_pair
#define ALL(x) x.begin(),x.end()
#define F first
#define S second
using namespace std;
typedef long long ll;
const int maxn=500000+5;
const int INF=0x3f3f3f3f;
const int P=1000000007;
const double PI=acos(-1.0);
template<typename T>
inline T read(T&x){
x=0;int _f=0;char ch=getchar();
while(ch<'0'||ch>'9')_f|=(ch=='-'),ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x=_f?-x:x;
}
template <class T1, class T2>inline void gmax(T1 &a,T2 b){if (b>a) a=b;}
template <class T1, class T2>inline void gmin(T1 &a,T2 b){if (b<a) a=b;}
void up(int&x,int y){x+=y;if(x>=P)x-=P;}
ll x,y;
int main(){
read(x),read(y);
if (x<y) cout<<x<<endl;
else{
if (x%y==0) cout<<-1<<endl;
else cout<<x<<endl;
}
return 0;
}
| Go | package main
import "fmt"
func cal(p int) int {
g := p%10
p = p/10
g += p%10
p = p/10
g += p%10
p = p/10
g += p%10
p = p/10
g += p%10
return g
}
func main() {
var n,a,b,count int
fmt.Scan(&n,&a,&b)
for i := 1 ; i <= n ; i++ {
x := cal(i)
//fmt.Println(i,x)
if a <= x && x <= b {
count += i
}
}
fmt.Println(count)
}
| No | Do these codes solve the same problem?
Code 1: #pragma comment(linker, "/STACK:102400000,102400000")
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define lson root<<1,l,mid
#define rson root<<1|1,mid+1,r
#define Key_Value ch[ch[root][1]][0]
#define DBN1(a) cerr<<#a<<"="<<(a)<<"\n"
#define DBN2(a,b) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<"\n"
#define DBN3(a,b,c) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<"\n"
#define DBN4(a,b,c,d) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<"\n"
#define DBN5(a,b,c,d,e) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<"\n"
#define DBN6(a,b,c,d,e,f) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<", "<<#f<<"="<<(f)<<"\n"
#define clr(a,x) memset(a,x,sizeof(a))
#define pb push_back
#define mp make_pair
#define ALL(x) x.begin(),x.end()
#define F first
#define S second
using namespace std;
typedef long long ll;
const int maxn=500000+5;
const int INF=0x3f3f3f3f;
const int P=1000000007;
const double PI=acos(-1.0);
template<typename T>
inline T read(T&x){
x=0;int _f=0;char ch=getchar();
while(ch<'0'||ch>'9')_f|=(ch=='-'),ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x=_f?-x:x;
}
template <class T1, class T2>inline void gmax(T1 &a,T2 b){if (b>a) a=b;}
template <class T1, class T2>inline void gmin(T1 &a,T2 b){if (b<a) a=b;}
void up(int&x,int y){x+=y;if(x>=P)x-=P;}
ll x,y;
int main(){
read(x),read(y);
if (x<y) cout<<x<<endl;
else{
if (x%y==0) cout<<-1<<endl;
else cout<<x<<endl;
}
return 0;
}
Code 2: package main
import "fmt"
func cal(p int) int {
g := p%10
p = p/10
g += p%10
p = p/10
g += p%10
p = p/10
g += p%10
p = p/10
g += p%10
return g
}
func main() {
var n,a,b,count int
fmt.Scan(&n,&a,&b)
for i := 1 ; i <= n ; i++ {
x := cal(i)
//fmt.Println(i,x)
if a <= x && x <= b {
count += i
}
}
fmt.Println(count)
}
|
C# | using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using StringBuilder = System.Text.StringBuilder;
using System.Numerics;
using Number = System.Int64;
namespace Program
{
public class Solver
{
public void Solve()
{
var n = sc.Integer();
var c = sc.Integer();
var a = sc.Integer(n);
var b = sc.Integer(n);
var dp = new ModInteger[c + 1];
dp[0] = 1;
var range = new ModInteger[420, 420];
for (int i = 1; i < 420; i++)
{
range[i, 0] = 1;
for (int k = 1; k < 420; k++)
range[i, k] = range[i, k - 1] * i;
}
for (int k = 0; k < 420; k++)
for (int i = 1; i < 420; i++)
range[i, k] += range[i - 1, k];
for (int i = 0; i < n; i++)
{
var next = new ModInteger[c + 1];
for (int j = 0; j <= c; j++)
for (int l = 0; j + l <= c; l++)
{
next[j + l] += dp[j] * (range[b[i], l] - range[a[i] - 1, l]);
}
dp = next;
}
IO.Printer.Out.WriteLine(dp[c]);
}
public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput());
static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; }
static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; }
}
}
#region main
static class Ex
{
static public string AsString(this IEnumerable<char> ie) { return new string(System.Linq.Enumerable.ToArray(ie)); }
static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); }
static public void Main()
{
var solver = new Program.Solver();
solver.Solve();
Program.IO.Printer.Out.Flush();
}
}
#endregion
#region Ex
namespace Program.IO
{
using System.IO;
using System.Text;
using System.Globalization;
public class Printer: StreamWriter
{
static Printer() { Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false }; }
public static Printer Out { get; set; }
public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
public Printer(System.IO.Stream stream) : base(stream, new UTF8Encoding(false, true)) { }
public Printer(System.IO.Stream stream, Encoding encoding) : base(stream, encoding) { }
public void Write<T>(string format, T[] source) { base.Write(format, source.OfType<object>().ToArray()); }
public void WriteLine<T>(string format, T[] source) { base.WriteLine(format, source.OfType<object>().ToArray()); }
}
public class StreamScanner
{
public StreamScanner(Stream stream) { str = stream; }
public readonly Stream str;
private readonly byte[] buf = new byte[1024];
private int len, ptr;
public bool isEof = false;
public bool IsEndOfStream { get { return isEof; } }
private byte read()
{
if (isEof) return 0;
if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } }
return buf[ptr++];
}
public char Char() { byte b = 0; do b = read(); while ((b < 33 || 126 < b) && !isEof); return (char)b; }
public string Scan()
{
var sb = new StringBuilder();
for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
sb.Append(b);
return sb.ToString();
}
public string ScanLine()
{
var sb = new StringBuilder();
for (var b = Char(); b != '\n'; b = (char)read())
if (b == 0) break;
else if (b != '\r') sb.Append(b);
return sb.ToString();
}
public long Long()
{
if (isEof) return long.MinValue;
long ret = 0; byte b = 0; var ng = false;
do b = read();
while (b != 0 && b != '-' && (b < '0' || '9' < b));
if (b == 0) return long.MinValue;
if (b == '-') { ng = true; b = read(); }
for (; true; b = read())
{
if (b < '0' || '9' < b)
return ng ? -ret : ret;
else ret = ret * 10 + b - '0';
}
}
public int Integer() { return (isEof) ? int.MinValue : (int)Long(); }
public double Double() { var s = Scan(); return s != "" ? double.Parse(s, CultureInfo.InvariantCulture) : double.NaN; }
private T[] enumerate<T>(int n, Func<T> f)
{
var a = new T[n];
for (int i = 0; i < n; ++i) a[i] = f();
return a;
}
public char[] Char(int n) { return enumerate(n, Char); }
public string[] Scan(int n) { return enumerate(n, Scan); }
public double[] Double(int n) { return enumerate(n, Double); }
public int[] Integer(int n) { return enumerate(n, Integer); }
public long[] Long(int n) { return enumerate(n, Long); }
}
}
#endregion
#region ModNumber
public partial struct ModInteger
{
public const long Mod = (long)1e9 + 7;
public long num;
public ModInteger(long n) : this() { num = n % Mod; if (num < 0) num += Mod; }
public override string ToString() { return num.ToString(); }
public static ModInteger operator +(ModInteger l, ModInteger r) { var n = l.num + r.num; if (n >= Mod) n -= Mod; return new ModInteger() { num = n }; }
public static ModInteger operator -(ModInteger l, ModInteger r) { var n = l.num + Mod - r.num; if (n >= Mod) n -= Mod; return new ModInteger() { num = n }; }
public static ModInteger operator *(ModInteger l, ModInteger r) { return new ModInteger(l.num * r.num); }
public static ModInteger operator ^(ModInteger l, long r) { return ModInteger.Pow(l, r); }
public static implicit operator ModInteger(long n) { return new ModInteger(n); }
public static ModInteger Pow(ModInteger v, long k)
{
ModInteger ret = 1;
var n = k;
for (; n > 0; n >>= 1, v *= v)
{
if ((n & 1) == 1)
ret = ret * v;
}
return ret;
}
}
#endregion | Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
var sc *bufio.Scanner
func nextInt() int {
sc.Scan()
i, e := strconv.Atoi(sc.Text())
if e != nil {
panic(e)
}
return i
}
const MOD = 1000000007
const UBOUND = 400
func main() {
sc = bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
n, c := nextInt(), nextInt()
aArray := make([]int, n)
for ni := range aArray {
aArray[ni] = nextInt()
}
bArray := make([]int, n)
for ni := range bArray {
bArray[ni] = nextInt()
}
powMat := make([][]int, UBOUND+1)
for r := range powMat {
pow := make([]int, UBOUND+1)
for i := range pow {
if r == 0 {
pow[i] = 1
continue
}
pow[i] = (powMat[r-1][i] * i) % MOD
}
powMat[r] = pow
}
powCumSumMat := make([][]int, UBOUND+1)
for r := range powCumSumMat {
powCumSum := make([]int, UBOUND+1)
for x := range powCumSum {
if x == 0 {
powCumSum[x] = powMat[r][x]
continue
}
powCumSum[x] = (powCumSum[x-1] + powMat[r][x]) % MOD
}
powCumSumMat[r] = powCumSum
}
dp := make([][]int, c+1)
for ci := range dp {
dpLine := make([]int, n)
dp[ci] = dpLine
}
for ci, dpLine := range dp {
for ni := range dpLine {
if ni == 0 {
dp[ci][ni] = powCumSumMat[ci][bArray[ni]] - powCumSumMat[ci][aArray[ni]-1]
switch {
case dp[ci][ni] < 0:
dp[ci][ni] += MOD
default:
dp[ci][ni] %= MOD
}
continue
}
for cj := 0; cj <= ci; cj++ {
switch {
case powCumSumMat[cj][bArray[ni]]-powCumSumMat[cj][aArray[ni]-1] < 0:
dp[ci][ni] += dp[ci-cj][ni-1] * (powCumSumMat[cj][bArray[ni]] - powCumSumMat[cj][aArray[ni]-1] + MOD) % MOD
default:
dp[ci][ni] += dp[ci-cj][ni-1] * ((powCumSumMat[cj][bArray[ni]] - powCumSumMat[cj][aArray[ni]-1]) % MOD) % MOD
}
dp[ci][ni] %= MOD
}
}
}
fmt.Println(dp[c][n-1])
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using StringBuilder = System.Text.StringBuilder;
using System.Numerics;
using Number = System.Int64;
namespace Program
{
public class Solver
{
public void Solve()
{
var n = sc.Integer();
var c = sc.Integer();
var a = sc.Integer(n);
var b = sc.Integer(n);
var dp = new ModInteger[c + 1];
dp[0] = 1;
var range = new ModInteger[420, 420];
for (int i = 1; i < 420; i++)
{
range[i, 0] = 1;
for (int k = 1; k < 420; k++)
range[i, k] = range[i, k - 1] * i;
}
for (int k = 0; k < 420; k++)
for (int i = 1; i < 420; i++)
range[i, k] += range[i - 1, k];
for (int i = 0; i < n; i++)
{
var next = new ModInteger[c + 1];
for (int j = 0; j <= c; j++)
for (int l = 0; j + l <= c; l++)
{
next[j + l] += dp[j] * (range[b[i], l] - range[a[i] - 1, l]);
}
dp = next;
}
IO.Printer.Out.WriteLine(dp[c]);
}
public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput());
static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; }
static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; }
}
}
#region main
static class Ex
{
static public string AsString(this IEnumerable<char> ie) { return new string(System.Linq.Enumerable.ToArray(ie)); }
static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); }
static public void Main()
{
var solver = new Program.Solver();
solver.Solve();
Program.IO.Printer.Out.Flush();
}
}
#endregion
#region Ex
namespace Program.IO
{
using System.IO;
using System.Text;
using System.Globalization;
public class Printer: StreamWriter
{
static Printer() { Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false }; }
public static Printer Out { get; set; }
public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
public Printer(System.IO.Stream stream) : base(stream, new UTF8Encoding(false, true)) { }
public Printer(System.IO.Stream stream, Encoding encoding) : base(stream, encoding) { }
public void Write<T>(string format, T[] source) { base.Write(format, source.OfType<object>().ToArray()); }
public void WriteLine<T>(string format, T[] source) { base.WriteLine(format, source.OfType<object>().ToArray()); }
}
public class StreamScanner
{
public StreamScanner(Stream stream) { str = stream; }
public readonly Stream str;
private readonly byte[] buf = new byte[1024];
private int len, ptr;
public bool isEof = false;
public bool IsEndOfStream { get { return isEof; } }
private byte read()
{
if (isEof) return 0;
if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } }
return buf[ptr++];
}
public char Char() { byte b = 0; do b = read(); while ((b < 33 || 126 < b) && !isEof); return (char)b; }
public string Scan()
{
var sb = new StringBuilder();
for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
sb.Append(b);
return sb.ToString();
}
public string ScanLine()
{
var sb = new StringBuilder();
for (var b = Char(); b != '\n'; b = (char)read())
if (b == 0) break;
else if (b != '\r') sb.Append(b);
return sb.ToString();
}
public long Long()
{
if (isEof) return long.MinValue;
long ret = 0; byte b = 0; var ng = false;
do b = read();
while (b != 0 && b != '-' && (b < '0' || '9' < b));
if (b == 0) return long.MinValue;
if (b == '-') { ng = true; b = read(); }
for (; true; b = read())
{
if (b < '0' || '9' < b)
return ng ? -ret : ret;
else ret = ret * 10 + b - '0';
}
}
public int Integer() { return (isEof) ? int.MinValue : (int)Long(); }
public double Double() { var s = Scan(); return s != "" ? double.Parse(s, CultureInfo.InvariantCulture) : double.NaN; }
private T[] enumerate<T>(int n, Func<T> f)
{
var a = new T[n];
for (int i = 0; i < n; ++i) a[i] = f();
return a;
}
public char[] Char(int n) { return enumerate(n, Char); }
public string[] Scan(int n) { return enumerate(n, Scan); }
public double[] Double(int n) { return enumerate(n, Double); }
public int[] Integer(int n) { return enumerate(n, Integer); }
public long[] Long(int n) { return enumerate(n, Long); }
}
}
#endregion
#region ModNumber
public partial struct ModInteger
{
public const long Mod = (long)1e9 + 7;
public long num;
public ModInteger(long n) : this() { num = n % Mod; if (num < 0) num += Mod; }
public override string ToString() { return num.ToString(); }
public static ModInteger operator +(ModInteger l, ModInteger r) { var n = l.num + r.num; if (n >= Mod) n -= Mod; return new ModInteger() { num = n }; }
public static ModInteger operator -(ModInteger l, ModInteger r) { var n = l.num + Mod - r.num; if (n >= Mod) n -= Mod; return new ModInteger() { num = n }; }
public static ModInteger operator *(ModInteger l, ModInteger r) { return new ModInteger(l.num * r.num); }
public static ModInteger operator ^(ModInteger l, long r) { return ModInteger.Pow(l, r); }
public static implicit operator ModInteger(long n) { return new ModInteger(n); }
public static ModInteger Pow(ModInteger v, long k)
{
ModInteger ret = 1;
var n = k;
for (; n > 0; n >>= 1, v *= v)
{
if ((n & 1) == 1)
ret = ret * v;
}
return ret;
}
}
#endregion
Code 2: package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
var sc *bufio.Scanner
func nextInt() int {
sc.Scan()
i, e := strconv.Atoi(sc.Text())
if e != nil {
panic(e)
}
return i
}
const MOD = 1000000007
const UBOUND = 400
func main() {
sc = bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
n, c := nextInt(), nextInt()
aArray := make([]int, n)
for ni := range aArray {
aArray[ni] = nextInt()
}
bArray := make([]int, n)
for ni := range bArray {
bArray[ni] = nextInt()
}
powMat := make([][]int, UBOUND+1)
for r := range powMat {
pow := make([]int, UBOUND+1)
for i := range pow {
if r == 0 {
pow[i] = 1
continue
}
pow[i] = (powMat[r-1][i] * i) % MOD
}
powMat[r] = pow
}
powCumSumMat := make([][]int, UBOUND+1)
for r := range powCumSumMat {
powCumSum := make([]int, UBOUND+1)
for x := range powCumSum {
if x == 0 {
powCumSum[x] = powMat[r][x]
continue
}
powCumSum[x] = (powCumSum[x-1] + powMat[r][x]) % MOD
}
powCumSumMat[r] = powCumSum
}
dp := make([][]int, c+1)
for ci := range dp {
dpLine := make([]int, n)
dp[ci] = dpLine
}
for ci, dpLine := range dp {
for ni := range dpLine {
if ni == 0 {
dp[ci][ni] = powCumSumMat[ci][bArray[ni]] - powCumSumMat[ci][aArray[ni]-1]
switch {
case dp[ci][ni] < 0:
dp[ci][ni] += MOD
default:
dp[ci][ni] %= MOD
}
continue
}
for cj := 0; cj <= ci; cj++ {
switch {
case powCumSumMat[cj][bArray[ni]]-powCumSumMat[cj][aArray[ni]-1] < 0:
dp[ci][ni] += dp[ci-cj][ni-1] * (powCumSumMat[cj][bArray[ni]] - powCumSumMat[cj][aArray[ni]-1] + MOD) % MOD
default:
dp[ci][ni] += dp[ci-cj][ni-1] * ((powCumSumMat[cj][bArray[ni]] - powCumSumMat[cj][aArray[ni]-1]) % MOD) % MOD
}
dp[ci][ni] %= MOD
}
}
}
fmt.Println(dp[c][n-1])
}
|
C++ | #include <bits/stdc++.h>
#include <iostream>
//#include <algorithm>
// #include <iomanip>
#define ll long long
#define map unordered_map
#define set unordered_set
#define pll pair<ll, ll>
#define vll vector<ll>
#define mll map<ll, ll>
using namespace std;
const ll MOD = 1000000007LL;
const ll INF = (1LL << 60LL);
const ll MAX = 100;
// ll cache2[MAX];
// void init_cache2() {
// ll c = 1;
// for (ll i = 0; i < MAX; i++) {
// cache2[i] = c;
// c = (c * 2) % MOD;
// }
// }
ll N, K;
vector<ll> log_list;
ll calc(ll length) {
ll count = 0;
for (ll i = 0; i < log_list.size(); i++) {
ll a = log_list[i];
ll plus = (a - 1) / length;
count += plus;
}
return count;
}
int main() {
// init_cache2();
scanf("%lld %lld", &N, &K);
for (ll i = 0; i < N; i++) {
ll v;
scanf("%lld", &v);
log_list.emplace_back(v);
}
// cout << log2l(1000000000LL) << endl;
ll left = 0;
ll right = 1000000000LL;
for (;;) {
if (1 >= right - left) {
break;
}
ll center = (left + right) / 2;
ll num = calc(center);
if (K < num) {
left = center;
} else {
right = center;
}
}
cout << right << endl;
}
| Python | from decimal import Decimal
a, b, c = map(int, input().split())
if Decimal(a).sqrt() + Decimal(b).sqrt() < Decimal(c).sqrt():
print("Yes")
else:
print("No")
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#include <iostream>
//#include <algorithm>
// #include <iomanip>
#define ll long long
#define map unordered_map
#define set unordered_set
#define pll pair<ll, ll>
#define vll vector<ll>
#define mll map<ll, ll>
using namespace std;
const ll MOD = 1000000007LL;
const ll INF = (1LL << 60LL);
const ll MAX = 100;
// ll cache2[MAX];
// void init_cache2() {
// ll c = 1;
// for (ll i = 0; i < MAX; i++) {
// cache2[i] = c;
// c = (c * 2) % MOD;
// }
// }
ll N, K;
vector<ll> log_list;
ll calc(ll length) {
ll count = 0;
for (ll i = 0; i < log_list.size(); i++) {
ll a = log_list[i];
ll plus = (a - 1) / length;
count += plus;
}
return count;
}
int main() {
// init_cache2();
scanf("%lld %lld", &N, &K);
for (ll i = 0; i < N; i++) {
ll v;
scanf("%lld", &v);
log_list.emplace_back(v);
}
// cout << log2l(1000000000LL) << endl;
ll left = 0;
ll right = 1000000000LL;
for (;;) {
if (1 >= right - left) {
break;
}
ll center = (left + right) / 2;
ll num = calc(center);
if (K < num) {
left = center;
} else {
right = center;
}
}
cout << right << endl;
}
Code 2: from decimal import Decimal
a, b, c = map(int, input().split())
if Decimal(a).sqrt() + Decimal(b).sqrt() < Decimal(c).sqrt():
print("Yes")
else:
print("No")
|
C++ | #include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
template<class T>
struct Vec2
{
Vec2(){}
Vec2(T _x, T _y) : x(_x), y(_y) {}
Vec2 operator+(const Vec2& rhs) const { return Vec2(x + rhs.x, y + rhs.y); }
Vec2 operator-(const Vec2& rhs) const { return Vec2(x - rhs.x, y - rhs.y); }
Vec2 operator*(T s) const { return Vec2(x*s, y*s); }
T dot(const Vec2& rhs) const { return x*rhs.x + y*rhs.y; }
T cross(const Vec2& rhs) const { return x*rhs.y - y*rhs.x; }
double length() const { return sqrt(1.0*x*x + 1.0*y*y); }
bool operator<(const Vec2& rhs) const
{
if (x != rhs.x) return x < rhs.x;
return y < rhs.y;
}
T x;
T y;
};
int main()
{
typedef Vec2<double> Vec2;
double x1, y1, r1, x2, y2, r2;
cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2;
Vec2 C1(x1, y1), C2(x2, y2);
Vec2 D = C2 - C1;
double dc = D.length();
D = D*(1.0 / dc);
double t = acos((dc*dc + r1*r1 - r2*r2) / (2 * dc*r1));
Vec2 m = D*r1*cos(t) + C1;
double h = dc * r1 * sin(t) / dc;
Vec2 int1 = m + Vec2(D.y, -D.x) * h;
Vec2 int2 = m + Vec2(-D.y, D.x) * h;
if (int2 < int1) {
swap(int1, int2);
}
printf("%.10lf %.10lf %.10lf %.10lf\n", int1.x, int1.y, int2.x, int2.y);
return 0;
}
| C# | using System;
using System.Linq;
using System.Collections.Generic;
using static System.Console;
using System.Text;
using System.IO;
namespace AOJ
{
using Vector = Point;
using Line = Segment;
using Polygon = List<Point>;
class Consts
{
public static readonly double EPS = 1e-10;
}
class Point
{
double x, y;
public double X { get { return this.x; } set { this.x = value; } }
public double Y { get { return this.y; } set { this.y = value; } }
public Point(double x = 0, double y = 0)
{
this.x = x;
this.y = y;
}
static public Point operator +(Point p1, Point p2) => new Point(p1.x + p2.x, p1.y + p2.y);
static public Point operator -(Point p1, Point p2) => new Point(p1.x - p2.x, p1.y - p2.y);
static public Point operator *(Point p, double a) => new Point(a * p.x, a * p.y);
static public Point operator *(double a, Point p) => p * a;
static public Point operator /(Point p, double a) => new Point(p.x / a, p.y / a);
static public bool operator <(Point p1, Point p2) => p1.x != p2.x ? p1.x < p2.x : p1.y < p2.y;
static public bool operator >(Point p1, Point p2) => p2 < p1;
static public bool operator ==(Point p1, Point p2) => (p1.x - p2.x) < Consts.EPS && (p1.y - p2.y) < Consts.EPS;
static public bool operator !=(Point p1, Point p2) => !(p1 == p2);
public double abs() => Math.Sqrt(norm());
public double norm() => this.x * this.x + this.y * this.y;
public override bool Equals(object obj)
{
if ((object)obj == null || this.GetType() != obj.GetType())
{
return false;
}
var c = (Point)obj;
return this == c;
}
public override int GetHashCode()
{
return this.x.GetHashCode() ^ this.y.GetHashCode();
}
}
struct Segment
{
public Segment(Point p1,Point p2)
{
this.p1 = p1;
this.p2 = p2;
}
public Point p1, p2;
}
class Circle
{
public Point c;
public double r;
public Circle(Point c, double r)
{
this.c = c;
this.r = r;
}
}
class VecCalc
{
static bool equals(double a, double b) => Math.Abs(a - b) < Consts.EPS;
//内積
static public double dot(Vector a, Vector b)
{
return a.X * b.X + a.Y * b.Y;
}
//外積
static public double cross(Vector a, Vector b)
{
return a.X * b.Y - a.Y * b.X;
}
//16.2 直行判定
static public bool isOrthogonal(Vector a, Vector b)
{
return equals(dot(a, b), 0.0);
}
static public bool isOrthogonal(Point a1, Point a2, Point b1, Point b2)
{
return isOrthogonal(a1 - a2, b1 - b2);
}
static public bool isOrthogonal(Segment s1, Segment s2)
{
return equals(dot(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
//16.2 平行判定
static public bool isParallel(Vector a, Vector b)
{
return equals(cross(a, b), 0.0);
}
static public bool isParallel(Point a1, Point a2, Point b1, Point b2)
{
return isParallel(a1 - a2, b1 - b2);
}
static public bool isParallel(Segment s1, Segment s2)
{
return equals(cross(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
//16.3 射影
static public Point project(Segment s, Point p)
{
Vector b = s.p2 - s.p1;
double r = dot(p - s.p1, b) / b.norm();
return s.p1 + b * r;
}
//16.4 反射
static public Point reflection(Segment s, Point p)
{
return 2 * project(s, p) - p;
//mid = project(s, p) - p;
//return mid + mid - p;
}
//16.5 距離
//2点間の距離
static public double getDistance(Point a, Point b)
{
return (a - b).abs();
}
//直線lと点pの距離
static public double getDistanceLP(Line l,Point p)
{
return Math.Abs(cross(l.p2 - l.p1, p - l.p1) / (l.p2 - l.p1).abs());
}
//線分sと点pの距離
static public double getDistanceSP(Segment s, Point p)
{
if (dot(s.p2 - s.p1, p - s.p1) < 0.0) return (p - s.p1).abs();
if (dot(s.p1 - s.p2, p - s.p2) < 0.0) return (p - s.p2).abs();
return getDistanceLP(s, p);
}
static public double getDistance(Segment s1, Segment s2)
{
if (intersect(s1, s2)) return 0.0;
return Math.Min(
Math.Min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2)),
Math.Min(getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))
);
}
//16.6 反時計回り
static public readonly int COUNTER_CLOCKWISE=1;
static public readonly int CLOCKWISE = -1;
static public readonly int ONLINE_BACK = 2;
static public readonly int ONLINE_FRONT = -2;
static public readonly int ON_SEGMENT = 0;
static public int ccw(Point p0, Point p1, Point p2)
{
Vector a = p1 - p0;
Vector b = p2 - p0;
var dot_ = dot(a, b);
var cross_ = cross(a, b);
if (Consts.EPS < cross_) return COUNTER_CLOCKWISE;
if (cross_ < -Consts.EPS) return CLOCKWISE;
if (dot_ < -Consts.EPS) return ONLINE_BACK;
if (a.norm() < b.norm()) return ONLINE_FRONT;
return ON_SEGMENT;
}
static public int ccw(Segment s, Point p)
{
return ccw(s.p1, s.p2, p);
}
//16.7 線分の交差判定
static public bool intersect(Point p1, Point p2,Point p3,Point p4)
{
return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 &&
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0
);
}
static public bool intersect(Segment s1, Segment s2)
{
return intersect(s1.p1, s1.p2, s2.p1, s2.p2);
}
//16.8 線分の交点
static public Point getCrossPoint(Segment s1, Segment s2)
{
Vector b = s2.p2 - s2.p1;
double d1 = Math.Abs(cross(b, s1.p1 - s2.p1));
double d2 = Math.Abs(cross(b, s1.p2 - s2.p1));
double t = d1 / (d1 + d2);
return s1.p1 + (s1.p2 - s1.p1) * t;
}
//16.9 円と直線の交点
static public Segment getCrossPoints(Circle c, Line l)
{
Vector pr = project(l, c.c);
System.Diagnostics.Debug.Assert((c.c - pr).abs() <= c.r);
Vector e = (l.p2 - l.p1) / (l.p2 - l.p1).abs();
double b = Math.Sqrt(c.r * c.r - (c.c - pr).norm());
return new Segment(pr + e * b, pr - e * b);
}
//16.10 円と円の交点
static double arg(Vector p) { return Math.Atan2(p.Y, p.X); }
static Vector polar(double a, double r) { return new Point(Math.Cos(r) * a, Math.Sin(r) * a); }
static public Segment getCrossPoints(Circle c1 , Circle c2)
{
double d = (c1.c - c2.c).abs();
System.Diagnostics.Debug.Assert(d <= c1.r + c2.r);
double a = Math.Acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));
double t = arg(c2.c - c1.c);
return new Segment(c1.c + polar(c1.r, t + a), c1.c + polar(c1.r, t - a));
}
//他ヘロンの公式を使ったり。高さだす、交点の投影点求める、投影点から平行線へのベクトル出す、みたいなの)
}
class Program
{
static public long[] Sarray() { return ReadLine().Trim().Split().Select(long.Parse).ToArray(); }
static public List<long> Slist() { return ReadLine().Split().Select(long.Parse).ToList(); }
static void Main(string[] args)
{
var cr = Sarray();
var c1 = new Circle(new Vector(cr[0], cr[1]), cr[2]);
cr = Sarray();
var c2 = new Circle(new Vector(cr[0], cr[1]), cr[2]);
var ans = VecCalc.getCrossPoints(c1, c2);
var ans1 = ans.p1;
var ans2 = ans.p2;
if (ans1.X < ans2.X)
{ }
else if (ans2.X < ans1.X)
{
var tmp = ans1;
ans1 = ans2;
ans2 = tmp;
}
else if (ans2.Y < ans1.Y)
{
var tmp = ans1;
ans1 = ans2;
ans2 = tmp;
}
WriteLine($"{ans1.X:F6} {ans1.Y:F6} {ans2.X:F6} {ans2.Y:F6}");
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
template<class T>
struct Vec2
{
Vec2(){}
Vec2(T _x, T _y) : x(_x), y(_y) {}
Vec2 operator+(const Vec2& rhs) const { return Vec2(x + rhs.x, y + rhs.y); }
Vec2 operator-(const Vec2& rhs) const { return Vec2(x - rhs.x, y - rhs.y); }
Vec2 operator*(T s) const { return Vec2(x*s, y*s); }
T dot(const Vec2& rhs) const { return x*rhs.x + y*rhs.y; }
T cross(const Vec2& rhs) const { return x*rhs.y - y*rhs.x; }
double length() const { return sqrt(1.0*x*x + 1.0*y*y); }
bool operator<(const Vec2& rhs) const
{
if (x != rhs.x) return x < rhs.x;
return y < rhs.y;
}
T x;
T y;
};
int main()
{
typedef Vec2<double> Vec2;
double x1, y1, r1, x2, y2, r2;
cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2;
Vec2 C1(x1, y1), C2(x2, y2);
Vec2 D = C2 - C1;
double dc = D.length();
D = D*(1.0 / dc);
double t = acos((dc*dc + r1*r1 - r2*r2) / (2 * dc*r1));
Vec2 m = D*r1*cos(t) + C1;
double h = dc * r1 * sin(t) / dc;
Vec2 int1 = m + Vec2(D.y, -D.x) * h;
Vec2 int2 = m + Vec2(-D.y, D.x) * h;
if (int2 < int1) {
swap(int1, int2);
}
printf("%.10lf %.10lf %.10lf %.10lf\n", int1.x, int1.y, int2.x, int2.y);
return 0;
}
Code 2: using System;
using System.Linq;
using System.Collections.Generic;
using static System.Console;
using System.Text;
using System.IO;
namespace AOJ
{
using Vector = Point;
using Line = Segment;
using Polygon = List<Point>;
class Consts
{
public static readonly double EPS = 1e-10;
}
class Point
{
double x, y;
public double X { get { return this.x; } set { this.x = value; } }
public double Y { get { return this.y; } set { this.y = value; } }
public Point(double x = 0, double y = 0)
{
this.x = x;
this.y = y;
}
static public Point operator +(Point p1, Point p2) => new Point(p1.x + p2.x, p1.y + p2.y);
static public Point operator -(Point p1, Point p2) => new Point(p1.x - p2.x, p1.y - p2.y);
static public Point operator *(Point p, double a) => new Point(a * p.x, a * p.y);
static public Point operator *(double a, Point p) => p * a;
static public Point operator /(Point p, double a) => new Point(p.x / a, p.y / a);
static public bool operator <(Point p1, Point p2) => p1.x != p2.x ? p1.x < p2.x : p1.y < p2.y;
static public bool operator >(Point p1, Point p2) => p2 < p1;
static public bool operator ==(Point p1, Point p2) => (p1.x - p2.x) < Consts.EPS && (p1.y - p2.y) < Consts.EPS;
static public bool operator !=(Point p1, Point p2) => !(p1 == p2);
public double abs() => Math.Sqrt(norm());
public double norm() => this.x * this.x + this.y * this.y;
public override bool Equals(object obj)
{
if ((object)obj == null || this.GetType() != obj.GetType())
{
return false;
}
var c = (Point)obj;
return this == c;
}
public override int GetHashCode()
{
return this.x.GetHashCode() ^ this.y.GetHashCode();
}
}
struct Segment
{
public Segment(Point p1,Point p2)
{
this.p1 = p1;
this.p2 = p2;
}
public Point p1, p2;
}
class Circle
{
public Point c;
public double r;
public Circle(Point c, double r)
{
this.c = c;
this.r = r;
}
}
class VecCalc
{
static bool equals(double a, double b) => Math.Abs(a - b) < Consts.EPS;
//内積
static public double dot(Vector a, Vector b)
{
return a.X * b.X + a.Y * b.Y;
}
//外積
static public double cross(Vector a, Vector b)
{
return a.X * b.Y - a.Y * b.X;
}
//16.2 直行判定
static public bool isOrthogonal(Vector a, Vector b)
{
return equals(dot(a, b), 0.0);
}
static public bool isOrthogonal(Point a1, Point a2, Point b1, Point b2)
{
return isOrthogonal(a1 - a2, b1 - b2);
}
static public bool isOrthogonal(Segment s1, Segment s2)
{
return equals(dot(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
//16.2 平行判定
static public bool isParallel(Vector a, Vector b)
{
return equals(cross(a, b), 0.0);
}
static public bool isParallel(Point a1, Point a2, Point b1, Point b2)
{
return isParallel(a1 - a2, b1 - b2);
}
static public bool isParallel(Segment s1, Segment s2)
{
return equals(cross(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
//16.3 射影
static public Point project(Segment s, Point p)
{
Vector b = s.p2 - s.p1;
double r = dot(p - s.p1, b) / b.norm();
return s.p1 + b * r;
}
//16.4 反射
static public Point reflection(Segment s, Point p)
{
return 2 * project(s, p) - p;
//mid = project(s, p) - p;
//return mid + mid - p;
}
//16.5 距離
//2点間の距離
static public double getDistance(Point a, Point b)
{
return (a - b).abs();
}
//直線lと点pの距離
static public double getDistanceLP(Line l,Point p)
{
return Math.Abs(cross(l.p2 - l.p1, p - l.p1) / (l.p2 - l.p1).abs());
}
//線分sと点pの距離
static public double getDistanceSP(Segment s, Point p)
{
if (dot(s.p2 - s.p1, p - s.p1) < 0.0) return (p - s.p1).abs();
if (dot(s.p1 - s.p2, p - s.p2) < 0.0) return (p - s.p2).abs();
return getDistanceLP(s, p);
}
static public double getDistance(Segment s1, Segment s2)
{
if (intersect(s1, s2)) return 0.0;
return Math.Min(
Math.Min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2)),
Math.Min(getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))
);
}
//16.6 反時計回り
static public readonly int COUNTER_CLOCKWISE=1;
static public readonly int CLOCKWISE = -1;
static public readonly int ONLINE_BACK = 2;
static public readonly int ONLINE_FRONT = -2;
static public readonly int ON_SEGMENT = 0;
static public int ccw(Point p0, Point p1, Point p2)
{
Vector a = p1 - p0;
Vector b = p2 - p0;
var dot_ = dot(a, b);
var cross_ = cross(a, b);
if (Consts.EPS < cross_) return COUNTER_CLOCKWISE;
if (cross_ < -Consts.EPS) return CLOCKWISE;
if (dot_ < -Consts.EPS) return ONLINE_BACK;
if (a.norm() < b.norm()) return ONLINE_FRONT;
return ON_SEGMENT;
}
static public int ccw(Segment s, Point p)
{
return ccw(s.p1, s.p2, p);
}
//16.7 線分の交差判定
static public bool intersect(Point p1, Point p2,Point p3,Point p4)
{
return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 &&
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0
);
}
static public bool intersect(Segment s1, Segment s2)
{
return intersect(s1.p1, s1.p2, s2.p1, s2.p2);
}
//16.8 線分の交点
static public Point getCrossPoint(Segment s1, Segment s2)
{
Vector b = s2.p2 - s2.p1;
double d1 = Math.Abs(cross(b, s1.p1 - s2.p1));
double d2 = Math.Abs(cross(b, s1.p2 - s2.p1));
double t = d1 / (d1 + d2);
return s1.p1 + (s1.p2 - s1.p1) * t;
}
//16.9 円と直線の交点
static public Segment getCrossPoints(Circle c, Line l)
{
Vector pr = project(l, c.c);
System.Diagnostics.Debug.Assert((c.c - pr).abs() <= c.r);
Vector e = (l.p2 - l.p1) / (l.p2 - l.p1).abs();
double b = Math.Sqrt(c.r * c.r - (c.c - pr).norm());
return new Segment(pr + e * b, pr - e * b);
}
//16.10 円と円の交点
static double arg(Vector p) { return Math.Atan2(p.Y, p.X); }
static Vector polar(double a, double r) { return new Point(Math.Cos(r) * a, Math.Sin(r) * a); }
static public Segment getCrossPoints(Circle c1 , Circle c2)
{
double d = (c1.c - c2.c).abs();
System.Diagnostics.Debug.Assert(d <= c1.r + c2.r);
double a = Math.Acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));
double t = arg(c2.c - c1.c);
return new Segment(c1.c + polar(c1.r, t + a), c1.c + polar(c1.r, t - a));
}
//他ヘロンの公式を使ったり。高さだす、交点の投影点求める、投影点から平行線へのベクトル出す、みたいなの)
}
class Program
{
static public long[] Sarray() { return ReadLine().Trim().Split().Select(long.Parse).ToArray(); }
static public List<long> Slist() { return ReadLine().Split().Select(long.Parse).ToList(); }
static void Main(string[] args)
{
var cr = Sarray();
var c1 = new Circle(new Vector(cr[0], cr[1]), cr[2]);
cr = Sarray();
var c2 = new Circle(new Vector(cr[0], cr[1]), cr[2]);
var ans = VecCalc.getCrossPoints(c1, c2);
var ans1 = ans.p1;
var ans2 = ans.p2;
if (ans1.X < ans2.X)
{ }
else if (ans2.X < ans1.X)
{
var tmp = ans1;
ans1 = ans2;
ans2 = tmp;
}
else if (ans2.Y < ans1.Y)
{
var tmp = ans1;
ans1 = ans2;
ans2 = tmp;
}
WriteLine($"{ans1.X:F6} {ans1.Y:F6} {ans2.X:F6} {ans2.Y:F6}");
}
}
}
|
Java | import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
long a[]=new long[n];
for(int i=0;i<n;++i){
a[i]=sc.nextLong();
}
Arrays.sort(a);
long amin[]=new long[n-n/2 +1];
long amax[]=new long[n/2 +1];
long sum=0;
long sum2=0;
for(int i=0;i<n;++i){
if(i<n-n/2) {amin[i]=a[i]; sum=sum-2*a[i];}
else {amax[i-n+n/2]=a[i]; sum=sum+2*a[i];}
}
if(n%2==0)sum=sum-amax[0]+amin[n-n/2-1];
else sum=sum+amin[n-n/2-1]+amin[n-n/2-2];
for(int i=0;i<n;++i){
if(i<n/2) {amin[i]=a[i]; sum2=sum2-2*a[i];}
else {amax[i-n/2]=a[i]; sum2=sum2+2*a[i];}
}
if(n%2==0)sum2=sum2-amax[0]+amin[n/2-1];
else sum2=sum2-amax[0]-amax[1];
System.out.println(Math.max(sum, sum2));
}
} | Kotlin | fun main(args: Array<String>) {
val n = readLine()!!.toInt()
var xs = (1..n).map { readLine()!!.toLong() }.sorted().reversed()
if (n % 2 == 0) {
var ans: Long = 0
(0 until (n/2 - 1)).forEach { ans += 2 * xs[it] }
ans += xs[n/2 - 1]
ans -= xs[n/2]
((n/2 + 1) until n).forEach { ans -= 2 * xs[it] }
println(ans)
} else {
var ans1: Long = 0
(0 until n/2 - 1).forEach { ans1 += 2 * xs[it] }
ans1 += xs[n/2 - 1] + xs[n/2]
((n/2 + 1) until n).forEach { ans1 -= 2 * xs[it] }
var ans2: Long = 0
(0 until n/2).forEach { ans2 += 2 * xs[it] }
ans2 -= xs[n/2] + xs[n/2 + 1]
((n/2 + 2) until n).forEach { ans2 -= 2 * xs[it] }
println(Math.max(ans1, ans2))
}
} | Yes | Do these codes solve the same problem?
Code 1: import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
long a[]=new long[n];
for(int i=0;i<n;++i){
a[i]=sc.nextLong();
}
Arrays.sort(a);
long amin[]=new long[n-n/2 +1];
long amax[]=new long[n/2 +1];
long sum=0;
long sum2=0;
for(int i=0;i<n;++i){
if(i<n-n/2) {amin[i]=a[i]; sum=sum-2*a[i];}
else {amax[i-n+n/2]=a[i]; sum=sum+2*a[i];}
}
if(n%2==0)sum=sum-amax[0]+amin[n-n/2-1];
else sum=sum+amin[n-n/2-1]+amin[n-n/2-2];
for(int i=0;i<n;++i){
if(i<n/2) {amin[i]=a[i]; sum2=sum2-2*a[i];}
else {amax[i-n/2]=a[i]; sum2=sum2+2*a[i];}
}
if(n%2==0)sum2=sum2-amax[0]+amin[n/2-1];
else sum2=sum2-amax[0]-amax[1];
System.out.println(Math.max(sum, sum2));
}
}
Code 2: fun main(args: Array<String>) {
val n = readLine()!!.toInt()
var xs = (1..n).map { readLine()!!.toLong() }.sorted().reversed()
if (n % 2 == 0) {
var ans: Long = 0
(0 until (n/2 - 1)).forEach { ans += 2 * xs[it] }
ans += xs[n/2 - 1]
ans -= xs[n/2]
((n/2 + 1) until n).forEach { ans -= 2 * xs[it] }
println(ans)
} else {
var ans1: Long = 0
(0 until n/2 - 1).forEach { ans1 += 2 * xs[it] }
ans1 += xs[n/2 - 1] + xs[n/2]
((n/2 + 1) until n).forEach { ans1 -= 2 * xs[it] }
var ans2: Long = 0
(0 until n/2).forEach { ans2 += 2 * xs[it] }
ans2 -= xs[n/2] + xs[n/2 + 1]
((n/2 + 2) until n).forEach { ans2 -= 2 * xs[it] }
println(Math.max(ans1, ans2))
}
} |
Python | from itertools import chain
import sys
table1 = dict(zip(
chain(" ',-.?", map(chr, range(65, 91))),
"101 000000 000011 10010001 010001 000001 100101 10011010\
0101 0001 110 01001 10011011 010000 0111 10011000\
0110 00100 10011001 10011110 00101 111 10011111 1000\
00110 00111 10011100 10011101 000010 10010010 10010011 10010000".split()
))
table2 = dict(enumerate(chain(map(chr, range(65, 91)), " .,-'?")))
for l in sys.stdin:
code = "".join(table1[c] for c in l.rstrip("\n"))
code += "0"*(5-(len(code)%5)) if len(code)%5 else ""
print("".join(table2[int(code[i*5:(i+1)*5], 2)] for i in range(len(code)//5)))
| Java | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Map<String, String> m1 = new HashMap<String, String>();
m1.put(" ", "101");
m1.put("'", "000000");
m1.put(",", "000011");
m1.put("-", "10010001");
m1.put(".", "010001");
m1.put("?", "000001");
m1.put("A", "100101");
m1.put("B", "10011010");
m1.put("C", "0101");
m1.put("D", "0001");
m1.put("E", "110");
m1.put("F", "01001");
m1.put("G", "10011011");
m1.put("H", "010000");
m1.put("I", "0111");
m1.put("J", "10011000");
m1.put("K", "0110");
m1.put("L", "00100");
m1.put("M", "10011001");
m1.put("N", "10011110");
m1.put("O", "00101");
m1.put("P", "111");
m1.put("Q", "10011111");
m1.put("R", "1000");
m1.put("S", "00110");
m1.put("T", "00111");
m1.put("U", "10011100");
m1.put("V", "10011101");
m1.put("W", "000010");
m1.put("X", "10010010");
m1.put("Y", "10010011");
m1.put("Z", "10010000");
String[] s = new String[32];
for(int i = 0; i < 26; i++) {
s[i] = Character.toString((char)(i + 'A'));
}
s[26] = " ";
s[27] = ".";
s[28] = ",";
s[29] = "-";
s[30] = "'";
s[31] = "?";
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String S = sc.nextLine();
String t = "";
for(int i = 0; i < S.length(); i++) {
t += m1.get(S.substring(i, i + 1));
}
if(t.length() % 5 != 0) {
int k = 5 - t.length() % 5;
for(int i = 0; i < k; i++) {
t += "0";
}
}
String g = "";
for(int i = 0; i + 5 <= t.length(); i += 5) {
String sub = t.substring(i, i + 5);
g += s[Integer.parseInt(sub, 2)];
}
System.out.println(g);
}
sc.close();
}
}
| Yes | Do these codes solve the same problem?
Code 1: from itertools import chain
import sys
table1 = dict(zip(
chain(" ',-.?", map(chr, range(65, 91))),
"101 000000 000011 10010001 010001 000001 100101 10011010\
0101 0001 110 01001 10011011 010000 0111 10011000\
0110 00100 10011001 10011110 00101 111 10011111 1000\
00110 00111 10011100 10011101 000010 10010010 10010011 10010000".split()
))
table2 = dict(enumerate(chain(map(chr, range(65, 91)), " .,-'?")))
for l in sys.stdin:
code = "".join(table1[c] for c in l.rstrip("\n"))
code += "0"*(5-(len(code)%5)) if len(code)%5 else ""
print("".join(table2[int(code[i*5:(i+1)*5], 2)] for i in range(len(code)//5)))
Code 2: import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Map<String, String> m1 = new HashMap<String, String>();
m1.put(" ", "101");
m1.put("'", "000000");
m1.put(",", "000011");
m1.put("-", "10010001");
m1.put(".", "010001");
m1.put("?", "000001");
m1.put("A", "100101");
m1.put("B", "10011010");
m1.put("C", "0101");
m1.put("D", "0001");
m1.put("E", "110");
m1.put("F", "01001");
m1.put("G", "10011011");
m1.put("H", "010000");
m1.put("I", "0111");
m1.put("J", "10011000");
m1.put("K", "0110");
m1.put("L", "00100");
m1.put("M", "10011001");
m1.put("N", "10011110");
m1.put("O", "00101");
m1.put("P", "111");
m1.put("Q", "10011111");
m1.put("R", "1000");
m1.put("S", "00110");
m1.put("T", "00111");
m1.put("U", "10011100");
m1.put("V", "10011101");
m1.put("W", "000010");
m1.put("X", "10010010");
m1.put("Y", "10010011");
m1.put("Z", "10010000");
String[] s = new String[32];
for(int i = 0; i < 26; i++) {
s[i] = Character.toString((char)(i + 'A'));
}
s[26] = " ";
s[27] = ".";
s[28] = ",";
s[29] = "-";
s[30] = "'";
s[31] = "?";
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String S = sc.nextLine();
String t = "";
for(int i = 0; i < S.length(); i++) {
t += m1.get(S.substring(i, i + 1));
}
if(t.length() % 5 != 0) {
int k = 5 - t.length() % 5;
for(int i = 0; i < k; i++) {
t += "0";
}
}
String g = "";
for(int i = 0; i + 5 <= t.length(); i += 5) {
String sub = t.substring(i, i + 5);
g += s[Integer.parseInt(sub, 2)];
}
System.out.println(g);
}
sc.close();
}
}
|
C++ | #include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <unordered_map>
#include <map>
#include <set>
#include <algorithm>
#include <queue>
#include <stack>
#include <functional>
#include <bitset>
#include <assert.h>
#include <unordered_map>
#include <fstream>
#include <ctime>
#include <complex>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef pair<int,int> pii;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(int i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
const int inf = 1<<30;
const ll linf = 1LL<<62;
const int MAX = 1020000;
ll dy[8] = {1,-1,0,0,1,-1,1,-1};
ll dx[8] = {0,0,1,-1,1,-1,-1,1};
const double pi = acos(-1);
const double eps = 1e-7;
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
if(a>b){
a = b; return true;
}
else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
if(a<b){
a = b; return true;
}
else return false;
}
template<typename T> inline void print(T &a){
rep(i,a.size()) cout << a[i] << " ";
cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){cout << a << " " << b << "\n";}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
cout << a << " " << b << " " << c << "\n";
}
ll pcount(ll x) {return __builtin_popcountll(x);}
const int mod = 1e9 + 7;
//const int mod = 998244353;
template< typename Monoid, typename OperatorMonoid = Monoid >
struct LazySegmentTree {
using F = function< Monoid(Monoid, Monoid) >;
using G = function< Monoid(Monoid, OperatorMonoid) >;
using H = function< OperatorMonoid(OperatorMonoid, OperatorMonoid) >;
int sz, height;
vector< Monoid > data;
vector< OperatorMonoid > lazy;
const F f;
const G g;
const H h;
const Monoid M1;
const OperatorMonoid OM0;
LazySegmentTree(int n, const F f, const G g, const H h,
const Monoid &M1, const OperatorMonoid OM0)
: f(f), g(g), h(h), M1(M1), OM0(OM0) {
sz = 1;
height = 0;
while(sz < n) sz <<= 1, height++;
data.assign(2 * sz, M1);
lazy.assign(2 * sz, OM0);
}
void set(int k, const Monoid &x) {
data[k + sz] = x;
}
void build() {
for(int k = sz - 1; k > 0; k--) {
data[k] = f(data[2 * k + 0], data[2 * k + 1]);
}
}
inline void propagate(int k) {
if(lazy[k] != OM0) {
lazy[2 * k + 0] = h(lazy[2 * k + 0], lazy[k]);
lazy[2 * k + 1] = h(lazy[2 * k + 1], lazy[k]);
data[k] = reflect(k);
lazy[k] = OM0;
}
}
inline Monoid reflect(int k) {
return lazy[k] == OM0 ? data[k] : g(data[k], lazy[k]);
}
inline void recalc(int k) {
while(k >>= 1) data[k] = f(reflect(2 * k + 0), reflect(2 * k + 1));
}
inline void thrust(int k) {
for(int i = height; i > 0; i--) propagate(k >> i);
}
void update(int a, int b, const OperatorMonoid &x) {
thrust(a += sz);
thrust(b += sz - 1);
for(int l = a, r = b + 1; l < r; l >>= 1, r >>= 1) {
if(l & 1) lazy[l] = h(lazy[l], x), ++l;
if(r & 1) --r, lazy[r] = h(lazy[r], x);
}
recalc(a);
recalc(b);
}
Monoid query(int a, int b) {
thrust(a += sz);
thrust(b += sz - 1);
Monoid L = M1, R = M1;
for(int l = a, r = b + 1; l < r; l >>= 1, r >>= 1) {
if(l & 1) L = f(L, reflect(l++));
if(r & 1) R = f(reflect(--r), R);
}
return f(L, R);
}
Monoid operator[](const int &k) {
return query(k, k + 1);
}
template< typename C >
int find_subtree(int a, const C &check, Monoid &M, bool type) {
while(a < sz) {
propagate(a);
Monoid nxt = type ? f(reflect(2 * a + type), M) : f(M, reflect(2 * a + type));
if(check(nxt)) a = 2 * a + type;
else M = nxt, a = 2 * a + 1 - type;
}
return a - sz;
}
template< typename C >
int find_first(int a, const C &check) {
Monoid L = M1;
if(a <= 0) {
if(check(f(L, reflect(1)))) return find_subtree(1, check, L, false);
return -1;
}
thrust(a + sz);
int b = sz;
for(a += sz, b += sz; a < b; a >>= 1, b >>= 1) {
if(a & 1) {
Monoid nxt = f(L, reflect(a));
if(check(nxt)) return find_subtree(a, check, L, false);
L = nxt;
++a;
}
}
return -1;
}
template< typename C >
int find_last(int b, const C &check) {
Monoid R = M1;
if(b >= sz) {
if(check(f(reflect(1), R))) return find_subtree(1, check, R, true);
return -1;
}
thrust(b + sz - 1);
int a = sz;
for(b += sz; a < b; a >>= 1, b >>= 1) {
if(b & 1) {
Monoid nxt = f(reflect(--b), R);
if(check(nxt)) return find_subtree(b, check, R, true);
R = nxt;
}
}
return -1;
}
};
auto f = [](ll a, ll b){return min(a,b);};
auto g = [](ll a, ll b){return a+b;};
auto h = [](ll a, ll b){return a+b;};
int main(){
int n,q; cin >> n >> q;
int y;
vl x(q+1); cin >> x[0] >> y; x[0]--; y--;
vector<LazySegmentTree<ll>> seg1(2,LazySegmentTree<ll>(n,f,g,h,linf,0));
vector<LazySegmentTree<ll>> seg2(2,LazySegmentTree<ll>(n,f,g,h,linf,0));
rep(i,2) rep(j,n){
seg1[i].set(j,1LL<<40);
seg2[i].set(j,1LL<<40);
}
seg1[0].set(y,-y);
seg2[0].set(y,y);
rep(i,2){
seg1[i].build();
seg2[i].build();
}
for(int i=1; i<=q; i++){
cin >> x[i]; x[i]--;
vl mn(2,linf);
rep(j,2){
chmin(mn[j], seg1[j].query(0,x[i]) + x[i]);
chmin(mn[j], seg2[j].query(x[i],n) - x[i]);
}
rep(j,2){
seg1[j].update(0,n,abs(x[i] - x[i-1]));
seg2[j].update(0,n,abs(x[i] - x[i-1]));
ll t = seg1[j][x[i-1]] + x[i-1];
if(t > mn[j^1]){
seg1[j].update(x[i-1], x[i-1]+1, mn[j^1] - t);
seg2[j].update(x[i-1], x[i-1]+1, mn[j^1] + x[i-1] - seg2[j][x[i-1]]);
}
}
}
ll ans = linf;
rep(i,2){
rep(j,n) chmin(ans, seg1[i][j] + j);
}
cout << ans << "\n";
} | Java | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int X = sc.nextInt();
if (X == 3 || X == 5 || X == 7) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
} | No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <unordered_map>
#include <map>
#include <set>
#include <algorithm>
#include <queue>
#include <stack>
#include <functional>
#include <bitset>
#include <assert.h>
#include <unordered_map>
#include <fstream>
#include <ctime>
#include <complex>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef pair<int,int> pii;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(int i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
const int inf = 1<<30;
const ll linf = 1LL<<62;
const int MAX = 1020000;
ll dy[8] = {1,-1,0,0,1,-1,1,-1};
ll dx[8] = {0,0,1,-1,1,-1,-1,1};
const double pi = acos(-1);
const double eps = 1e-7;
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
if(a>b){
a = b; return true;
}
else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
if(a<b){
a = b; return true;
}
else return false;
}
template<typename T> inline void print(T &a){
rep(i,a.size()) cout << a[i] << " ";
cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){cout << a << " " << b << "\n";}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
cout << a << " " << b << " " << c << "\n";
}
ll pcount(ll x) {return __builtin_popcountll(x);}
const int mod = 1e9 + 7;
//const int mod = 998244353;
template< typename Monoid, typename OperatorMonoid = Monoid >
struct LazySegmentTree {
using F = function< Monoid(Monoid, Monoid) >;
using G = function< Monoid(Monoid, OperatorMonoid) >;
using H = function< OperatorMonoid(OperatorMonoid, OperatorMonoid) >;
int sz, height;
vector< Monoid > data;
vector< OperatorMonoid > lazy;
const F f;
const G g;
const H h;
const Monoid M1;
const OperatorMonoid OM0;
LazySegmentTree(int n, const F f, const G g, const H h,
const Monoid &M1, const OperatorMonoid OM0)
: f(f), g(g), h(h), M1(M1), OM0(OM0) {
sz = 1;
height = 0;
while(sz < n) sz <<= 1, height++;
data.assign(2 * sz, M1);
lazy.assign(2 * sz, OM0);
}
void set(int k, const Monoid &x) {
data[k + sz] = x;
}
void build() {
for(int k = sz - 1; k > 0; k--) {
data[k] = f(data[2 * k + 0], data[2 * k + 1]);
}
}
inline void propagate(int k) {
if(lazy[k] != OM0) {
lazy[2 * k + 0] = h(lazy[2 * k + 0], lazy[k]);
lazy[2 * k + 1] = h(lazy[2 * k + 1], lazy[k]);
data[k] = reflect(k);
lazy[k] = OM0;
}
}
inline Monoid reflect(int k) {
return lazy[k] == OM0 ? data[k] : g(data[k], lazy[k]);
}
inline void recalc(int k) {
while(k >>= 1) data[k] = f(reflect(2 * k + 0), reflect(2 * k + 1));
}
inline void thrust(int k) {
for(int i = height; i > 0; i--) propagate(k >> i);
}
void update(int a, int b, const OperatorMonoid &x) {
thrust(a += sz);
thrust(b += sz - 1);
for(int l = a, r = b + 1; l < r; l >>= 1, r >>= 1) {
if(l & 1) lazy[l] = h(lazy[l], x), ++l;
if(r & 1) --r, lazy[r] = h(lazy[r], x);
}
recalc(a);
recalc(b);
}
Monoid query(int a, int b) {
thrust(a += sz);
thrust(b += sz - 1);
Monoid L = M1, R = M1;
for(int l = a, r = b + 1; l < r; l >>= 1, r >>= 1) {
if(l & 1) L = f(L, reflect(l++));
if(r & 1) R = f(reflect(--r), R);
}
return f(L, R);
}
Monoid operator[](const int &k) {
return query(k, k + 1);
}
template< typename C >
int find_subtree(int a, const C &check, Monoid &M, bool type) {
while(a < sz) {
propagate(a);
Monoid nxt = type ? f(reflect(2 * a + type), M) : f(M, reflect(2 * a + type));
if(check(nxt)) a = 2 * a + type;
else M = nxt, a = 2 * a + 1 - type;
}
return a - sz;
}
template< typename C >
int find_first(int a, const C &check) {
Monoid L = M1;
if(a <= 0) {
if(check(f(L, reflect(1)))) return find_subtree(1, check, L, false);
return -1;
}
thrust(a + sz);
int b = sz;
for(a += sz, b += sz; a < b; a >>= 1, b >>= 1) {
if(a & 1) {
Monoid nxt = f(L, reflect(a));
if(check(nxt)) return find_subtree(a, check, L, false);
L = nxt;
++a;
}
}
return -1;
}
template< typename C >
int find_last(int b, const C &check) {
Monoid R = M1;
if(b >= sz) {
if(check(f(reflect(1), R))) return find_subtree(1, check, R, true);
return -1;
}
thrust(b + sz - 1);
int a = sz;
for(b += sz; a < b; a >>= 1, b >>= 1) {
if(b & 1) {
Monoid nxt = f(reflect(--b), R);
if(check(nxt)) return find_subtree(b, check, R, true);
R = nxt;
}
}
return -1;
}
};
auto f = [](ll a, ll b){return min(a,b);};
auto g = [](ll a, ll b){return a+b;};
auto h = [](ll a, ll b){return a+b;};
int main(){
int n,q; cin >> n >> q;
int y;
vl x(q+1); cin >> x[0] >> y; x[0]--; y--;
vector<LazySegmentTree<ll>> seg1(2,LazySegmentTree<ll>(n,f,g,h,linf,0));
vector<LazySegmentTree<ll>> seg2(2,LazySegmentTree<ll>(n,f,g,h,linf,0));
rep(i,2) rep(j,n){
seg1[i].set(j,1LL<<40);
seg2[i].set(j,1LL<<40);
}
seg1[0].set(y,-y);
seg2[0].set(y,y);
rep(i,2){
seg1[i].build();
seg2[i].build();
}
for(int i=1; i<=q; i++){
cin >> x[i]; x[i]--;
vl mn(2,linf);
rep(j,2){
chmin(mn[j], seg1[j].query(0,x[i]) + x[i]);
chmin(mn[j], seg2[j].query(x[i],n) - x[i]);
}
rep(j,2){
seg1[j].update(0,n,abs(x[i] - x[i-1]));
seg2[j].update(0,n,abs(x[i] - x[i-1]));
ll t = seg1[j][x[i-1]] + x[i-1];
if(t > mn[j^1]){
seg1[j].update(x[i-1], x[i-1]+1, mn[j^1] - t);
seg2[j].update(x[i-1], x[i-1]+1, mn[j^1] + x[i-1] - seg2[j][x[i-1]]);
}
}
}
ll ans = linf;
rep(i,2){
rep(j,n) chmin(ans, seg1[i][j] + j);
}
cout << ans << "\n";
}
Code 2: import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int X = sc.nextInt();
if (X == 3 || X == 5 || X == 7) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
} |
C++ | #include<bits/stdc++.h>
using namespace std;
int main(){
int a;
cin>>a;
if (a<2) cout<<1<<endl;
else if(a<4) cout<<2<<endl;
else if(a<8) cout<<4<<endl;
else if(a<16) cout<<8<<endl;
else if(a<32) cout<<16<<endl;
else if(a<64) cout<<32<<endl;
else cout<<64<<endl;
return 0;
} | Python | x,y = map(int,input().split())
ans = 0
if x<4:
ans+=abs(4-x)*100000
if y<4:
ans+=abs(4-y)*100000
if x==y==1:
ans +=400000
print(ans) | No | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
using namespace std;
int main(){
int a;
cin>>a;
if (a<2) cout<<1<<endl;
else if(a<4) cout<<2<<endl;
else if(a<8) cout<<4<<endl;
else if(a<16) cout<<8<<endl;
else if(a<32) cout<<16<<endl;
else if(a<64) cout<<32<<endl;
else cout<<64<<endl;
return 0;
}
Code 2: x,y = map(int,input().split())
ans = 0
if x<4:
ans+=abs(4-x)*100000
if y<4:
ans+=abs(4-y)*100000
if x==y==1:
ans +=400000
print(ans) |
C++ | #include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#define pb push_back
#define mp make_pair
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef unsigned long long ull;
typedef long long ll;
int main() {
int n;
double avg = 0;
vector<double> vd;
cin >> n;
for (int i = 0; i < n; ++i) {
double k;
cin >> k;
avg += k/(double)n;
vd.pb(k);
}
//floor gang
int bottom = (int)floor(avg);
int top = (int)ceil(avg);
int bottom_sum = 0;
int top_sum = 0;
for (double d : vd) {
int i = (int) d;
bottom_sum += (i-bottom)*(i-bottom);
top_sum += (i-top)*(i-top);
}
cout << min(bottom_sum, top_sum) << endl;
return 0;
} | Python | N, K = map(int, input().split(" "))
ans = 0
for n in range(N):
s = n+1
p = 1/N #ダイスの確率
if s>=K:
ans += p
else:
count = 0
while s < K:
count += 1
s = s*2
p = p/2
ans += p
print(ans)
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#define pb push_back
#define mp make_pair
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef unsigned long long ull;
typedef long long ll;
int main() {
int n;
double avg = 0;
vector<double> vd;
cin >> n;
for (int i = 0; i < n; ++i) {
double k;
cin >> k;
avg += k/(double)n;
vd.pb(k);
}
//floor gang
int bottom = (int)floor(avg);
int top = (int)ceil(avg);
int bottom_sum = 0;
int top_sum = 0;
for (double d : vd) {
int i = (int) d;
bottom_sum += (i-bottom)*(i-bottom);
top_sum += (i-top)*(i-top);
}
cout << min(bottom_sum, top_sum) << endl;
return 0;
}
Code 2: N, K = map(int, input().split(" "))
ans = 0
for n in range(N):
s = n+1
p = 1/N #ダイスの確率
if s>=K:
ans += p
else:
count = 0
while s < K:
count += 1
s = s*2
p = p/2
ans += p
print(ans)
|
C# | using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
class Solve{
public Solve(){}
StringBuilder sb;
ReadData re;
public static int Main(){
new Solve().Run();
return 0;
}
void Run(){
sb = new StringBuilder();
re = new ReadData();
Calc();
Console.Write(sb.ToString());
}
void Calc(){
int N = re.i();
long count = 1;
long c = 1;
sb.Append(count+"\n");
for(int i=1;i<N;i++){
if(!OK(count+c,c)){
c *= 10;
}
count += c;
sb.Append(count+"\n");
}
}
bool OK(long X,long N){
return X*Sum(X+N) <= (X+N)*Sum(X);
}
long Sum(long N){
long ans = 0;
while(N > 0){
ans += N % 10;
N /= 10;
}
return ans;
}
}
class ReadData{
string[] str;
int counter;
public ReadData(){
counter = 0;
}
public string s(){
if(counter == 0){
str = Console.ReadLine().Split(' ');
counter = str.Length;
}
counter--;
return str[str.Length-counter-1];
}
public int i(){
return int.Parse(s());
}
public long l(){
return long.Parse(s());
}
public double d(){
return double.Parse(s());
}
public int[] ia(int N){
int[] ans = new int[N];
for(int j=0;j<N;j++){
ans[j] = i();
}
return ans;
}
public int[] ia(){
str = Console.ReadLine().Split(' ');
counter = 0;
int[] ans = new int[str.Length];
for(int j=0;j<str.Length;j++){
ans[j] = int.Parse(str[j]);
}
return ans;
}
public long[] la(int N){
long[] ans = new long[N];
for(int j=0;j<N;j++){
ans[j] = l();
}
return ans;
}
public long[] la(){
str = Console.ReadLine().Split(' ');
counter = 0;
long[] ans = new long[str.Length];
for(int j=0;j<str.Length;j++){
ans[j] = long.Parse(str[j]);
}
return ans;
}
public double[] da(int N){
double[] ans = new double[N];
for(int j=0;j<N;j++){
ans[j] = d();
}
return ans;
}
public double[] da(){
str = Console.ReadLine().Split(' ');
counter = 0;
double[] ans = new double[str.Length];
for(int j=0;j<str.Length;j++){
ans[j] = double.Parse(str[j]);
}
return ans;
}
public List<int>[] g(int N,int[] f,int[] t){
List<int>[] ans = new List<int>[N];
for(int j=0;j<N;j++){
ans[j] = new List<int>();
}
for(int j=0;j<f.Length;j++){
ans[f[j]].Add(t[j]);
ans[t[j]].Add(f[j]);
}
return ans;
}
public List<int>[] g(int N,int M){
List<int>[] ans = new List<int>[N];
for(int j=0;j<N;j++){
ans[j] = new List<int>();
}
for(int j=0;j<M;j++){
int f = i()-1;
int t = i()-1;
ans[f].Add(t);
ans[t].Add(f);
}
return ans;
}
public List<int>[] g(){
int N = i();
int M = i();
List<int>[] ans = new List<int>[N];
for(int j=0;j<N;j++){
ans[j] = new List<int>();
}
for(int j=0;j<M;j++){
int f = i()-1;
int t = i()-1;
ans[f].Add(t);
ans[t].Add(f);
}
return ans;
}
}
public static class Define{
public const long mod = 1000000007;
}
public static class Debug{
public static void Print(double[,,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
for(int l=0;l<k.GetLength(2);l++){
Console.Write(k[i,j,l]+" ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
public static void Print(double[,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
Console.Write(k[i,j]+" ");
}
Console.WriteLine();
}
}
public static void Print(double[] k){
for(int i=0;i<k.Length;i++){
Console.WriteLine(k[i]);
}
}
public static void Print(long[,,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
for(int l=0;l<k.GetLength(2);l++){
Console.Write(k[i,j,l]+" ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
public static void Print(long[,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
Console.Write(k[i,j]+" ");
}
Console.WriteLine();
}
}
public static void Print(long[] k){
for(int i=0;i<k.Length;i++){
Console.WriteLine(k[i]);
}
}
public static void Print(int[,,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
for(int l=0;l<k.GetLength(2);l++){
Console.Write(k[i,j,l]+" ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
public static void Print(int[,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
Console.Write(k[i,j]+" ");
}
Console.WriteLine();
}
}
public static void Print(int[] k){
for(int i=0;i<k.Length;i++){
Console.WriteLine(k[i]);
}
}
}
| Go | package main
import (
"fmt"
"math"
"os"
"strconv"
)
func main() {
var k,n int64
fmt.Scan(&k)
for i:=int64(0);i<9;i++ {
if i == k { os.Exit(0) }
fmt.Println(i+1)
}
n = 19
for i:=k-9;i>0;i-- {
fmt.Println(f(n))
n = f(n+1)
}
}
func f(n int64) int64 {
var u int = int(math.Log10(float64(n)))+1
var e int64 = 10
var m int64 = 10*int64(float64(n)/10.0+1)-1
for d:=1;d<u;d++ {
e *= 10
x := e*int64(float64(n)/float64(e)+1)-1
if float64(m)/float64(s(m)) > float64(x)/float64(s(x)) { m = x }
}
return m
}
func s(n int64) int64 {
var s string
var m,t int64
s = strconv.FormatInt(n,10)
m = 0
for i:=0;i<len(s);i++ {
t,_ = strconv.ParseInt(s[i:i+1],10,64)
m += t
}
return m
} | Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
class Solve{
public Solve(){}
StringBuilder sb;
ReadData re;
public static int Main(){
new Solve().Run();
return 0;
}
void Run(){
sb = new StringBuilder();
re = new ReadData();
Calc();
Console.Write(sb.ToString());
}
void Calc(){
int N = re.i();
long count = 1;
long c = 1;
sb.Append(count+"\n");
for(int i=1;i<N;i++){
if(!OK(count+c,c)){
c *= 10;
}
count += c;
sb.Append(count+"\n");
}
}
bool OK(long X,long N){
return X*Sum(X+N) <= (X+N)*Sum(X);
}
long Sum(long N){
long ans = 0;
while(N > 0){
ans += N % 10;
N /= 10;
}
return ans;
}
}
class ReadData{
string[] str;
int counter;
public ReadData(){
counter = 0;
}
public string s(){
if(counter == 0){
str = Console.ReadLine().Split(' ');
counter = str.Length;
}
counter--;
return str[str.Length-counter-1];
}
public int i(){
return int.Parse(s());
}
public long l(){
return long.Parse(s());
}
public double d(){
return double.Parse(s());
}
public int[] ia(int N){
int[] ans = new int[N];
for(int j=0;j<N;j++){
ans[j] = i();
}
return ans;
}
public int[] ia(){
str = Console.ReadLine().Split(' ');
counter = 0;
int[] ans = new int[str.Length];
for(int j=0;j<str.Length;j++){
ans[j] = int.Parse(str[j]);
}
return ans;
}
public long[] la(int N){
long[] ans = new long[N];
for(int j=0;j<N;j++){
ans[j] = l();
}
return ans;
}
public long[] la(){
str = Console.ReadLine().Split(' ');
counter = 0;
long[] ans = new long[str.Length];
for(int j=0;j<str.Length;j++){
ans[j] = long.Parse(str[j]);
}
return ans;
}
public double[] da(int N){
double[] ans = new double[N];
for(int j=0;j<N;j++){
ans[j] = d();
}
return ans;
}
public double[] da(){
str = Console.ReadLine().Split(' ');
counter = 0;
double[] ans = new double[str.Length];
for(int j=0;j<str.Length;j++){
ans[j] = double.Parse(str[j]);
}
return ans;
}
public List<int>[] g(int N,int[] f,int[] t){
List<int>[] ans = new List<int>[N];
for(int j=0;j<N;j++){
ans[j] = new List<int>();
}
for(int j=0;j<f.Length;j++){
ans[f[j]].Add(t[j]);
ans[t[j]].Add(f[j]);
}
return ans;
}
public List<int>[] g(int N,int M){
List<int>[] ans = new List<int>[N];
for(int j=0;j<N;j++){
ans[j] = new List<int>();
}
for(int j=0;j<M;j++){
int f = i()-1;
int t = i()-1;
ans[f].Add(t);
ans[t].Add(f);
}
return ans;
}
public List<int>[] g(){
int N = i();
int M = i();
List<int>[] ans = new List<int>[N];
for(int j=0;j<N;j++){
ans[j] = new List<int>();
}
for(int j=0;j<M;j++){
int f = i()-1;
int t = i()-1;
ans[f].Add(t);
ans[t].Add(f);
}
return ans;
}
}
public static class Define{
public const long mod = 1000000007;
}
public static class Debug{
public static void Print(double[,,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
for(int l=0;l<k.GetLength(2);l++){
Console.Write(k[i,j,l]+" ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
public static void Print(double[,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
Console.Write(k[i,j]+" ");
}
Console.WriteLine();
}
}
public static void Print(double[] k){
for(int i=0;i<k.Length;i++){
Console.WriteLine(k[i]);
}
}
public static void Print(long[,,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
for(int l=0;l<k.GetLength(2);l++){
Console.Write(k[i,j,l]+" ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
public static void Print(long[,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
Console.Write(k[i,j]+" ");
}
Console.WriteLine();
}
}
public static void Print(long[] k){
for(int i=0;i<k.Length;i++){
Console.WriteLine(k[i]);
}
}
public static void Print(int[,,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
for(int l=0;l<k.GetLength(2);l++){
Console.Write(k[i,j,l]+" ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
public static void Print(int[,] k){
for(int i=0;i<k.GetLength(0);i++){
for(int j=0;j<k.GetLength(1);j++){
Console.Write(k[i,j]+" ");
}
Console.WriteLine();
}
}
public static void Print(int[] k){
for(int i=0;i<k.Length;i++){
Console.WriteLine(k[i]);
}
}
}
Code 2: package main
import (
"fmt"
"math"
"os"
"strconv"
)
func main() {
var k,n int64
fmt.Scan(&k)
for i:=int64(0);i<9;i++ {
if i == k { os.Exit(0) }
fmt.Println(i+1)
}
n = 19
for i:=k-9;i>0;i-- {
fmt.Println(f(n))
n = f(n+1)
}
}
func f(n int64) int64 {
var u int = int(math.Log10(float64(n)))+1
var e int64 = 10
var m int64 = 10*int64(float64(n)/10.0+1)-1
for d:=1;d<u;d++ {
e *= 10
x := e*int64(float64(n)/float64(e)+1)-1
if float64(m)/float64(s(m)) > float64(x)/float64(s(x)) { m = x }
}
return m
}
func s(n int64) int64 {
var s string
var m,t int64
s = strconv.FormatInt(n,10)
m = 0
for i:=0;i<len(s);i++ {
t,_ = strconv.ParseInt(s[i:i+1],10,64)
m += t
}
return m
} |
Python | def e():
N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
v = [wv[i][1] for i in range(len(wv))]
V = sum(v)
dp = [[10 ** 9] * (V + 1) for _ in range(N + 1)]
dp[0][0] = 0
for i in range(N):
for j in range(V + 1):
if j - wv[i][1] >= 0:
dp[i + 1][j] = min(dp[i + 1][j],
dp[i][j - wv[i][1]] + wv[i][0])
dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])
for k, p in enumerate(dp[-1]):
if p <= W:
r = k
return r
if __name__ == '__main__':
ans = e()
print(ans) | C++ | #include <bits/stdc++.h>
using namespace std;
using lli = long long int;
template <class T>ostream &operator<<(ostream &o,const vector<T>&v)
{o<<"{";for(int i=0;i<(int)v.size();i++)o<<(i>0?", ":"")<<v[i];o<<"}";return o;}
template <class T>ostream &operator<<(ostream &o,const pair<T, T>&p)
{o<<"("<<p.first<<", "<<p.second<<")";return o;}
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
int A, B, M;
vector<int> a, b;
int res = INT_MAX;
int mina, minb;
int main(void){
cin >> A >> B >> M;
rep(i, A){
int ak;
cin >> ak;
a.push_back(ak);
}
rep(i, B){
int bk;
cin >> bk;
b.push_back(bk);
}
rep(i, M){
int x, y, c;
cin >> x >> y >> c;
res = min(res, a[x-1]+b[y-1]-c);
}
mina = *min_element(a.begin(), a.end());
minb = *min_element(b.begin(), b.end());
res = min(res, mina+minb);
cout << res << endl;
return 0;
}
| No | Do these codes solve the same problem?
Code 1: def e():
N, W = map(int, input().split())
wv = [list(map(int, input().split())) for _ in range(N)]
v = [wv[i][1] for i in range(len(wv))]
V = sum(v)
dp = [[10 ** 9] * (V + 1) for _ in range(N + 1)]
dp[0][0] = 0
for i in range(N):
for j in range(V + 1):
if j - wv[i][1] >= 0:
dp[i + 1][j] = min(dp[i + 1][j],
dp[i][j - wv[i][1]] + wv[i][0])
dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])
for k, p in enumerate(dp[-1]):
if p <= W:
r = k
return r
if __name__ == '__main__':
ans = e()
print(ans)
Code 2: #include <bits/stdc++.h>
using namespace std;
using lli = long long int;
template <class T>ostream &operator<<(ostream &o,const vector<T>&v)
{o<<"{";for(int i=0;i<(int)v.size();i++)o<<(i>0?", ":"")<<v[i];o<<"}";return o;}
template <class T>ostream &operator<<(ostream &o,const pair<T, T>&p)
{o<<"("<<p.first<<", "<<p.second<<")";return o;}
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
int A, B, M;
vector<int> a, b;
int res = INT_MAX;
int mina, minb;
int main(void){
cin >> A >> B >> M;
rep(i, A){
int ak;
cin >> ak;
a.push_back(ak);
}
rep(i, B){
int bk;
cin >> bk;
b.push_back(bk);
}
rep(i, M){
int x, y, c;
cin >> x >> y >> c;
res = min(res, a[x-1]+b[y-1]-c);
}
mina = *min_element(a.begin(), a.end());
minb = *min_element(b.begin(), b.end());
res = min(res, mina+minb);
cout << res << endl;
return 0;
}
|
C | #include<stdio.h>
int main(){
int a,b,d,r;
double f;
scanf("%d %d",&a,&b);
d=a / b;
r=a % b;
f=(double) a / b;
printf("%d %d %.5lf\n",d,r,f);
return 0;
} | C++ | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> P;
const LL mod=1000000007;
const LL INF=100000000000;
string u="abcdefghijklmnopqrstuvwxyz";
int main(){
string s;
cin >> s;
cout << "2018";
for(int i=4;i<s.length();i++){
cout << s[i];
}
cout << "\n";
return 0;
} | No | Do these codes solve the same problem?
Code 1: #include<stdio.h>
int main(){
int a,b,d,r;
double f;
scanf("%d %d",&a,&b);
d=a / b;
r=a % b;
f=(double) a / b;
printf("%d %d %.5lf\n",d,r,f);
return 0;
}
Code 2: #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> P;
const LL mod=1000000007;
const LL INF=100000000000;
string u="abcdefghijklmnopqrstuvwxyz";
int main(){
string s;
cin >> s;
cout << "2018";
for(int i=4;i<s.length();i++){
cout << s[i];
}
cout << "\n";
return 0;
} |
Python | import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))
X, N = mi()
A = li()
flag = [0] * (205)
for num in A:
flag[num] = 1
if not flag[X]:
print(X)
exit()
i = 1
while True:
if not flag[X - i]:
print(X-i)
exit()
elif not flag[X + i]:
print(X+i)
exit()
i += 1 | C++ | #include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <memory>
#include <complex>
#include <numeric>
#include <cstdio>
#include <iomanip>
#define REP(i,m,n) for(int i=int(m);i<int(n);i++)
#define EACH(i,c) for (auto &(i): c)
#define all(c) begin(c),end(c)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort(begin(c),end(c))
#define pb emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
#ifdef LOCAL
#define DEBUG(s) cout << (s) << endl
#define dump(x) cerr << #x << " = " << (x) << endl
#define BR cout << endl;
#else
#define DEBUG(s) do{}while(0)
#define dump(x) do{}while(0)
#define BR
#endif
using namespace std;
using UI = unsigned int;
using UL = unsigned long;
using LL = long long int;
using ULL = unsigned long long;
using VI = vector<int>;
using VVI = vector<VI>;
using VLL = vector<LL>;
using VS = vector<string>;
using PII = pair<int,int>;
using VP = vector<PII>;
//struct edge {int from, to, cost;};
constexpr double EPS = 1e-10;
constexpr double PI = acos(-1.0);
//constexpr int INF = INT_MAX;
template<class T> inline T sqr(T x) {return x*x;}
void resolve() {
string s;
cin >> s;
string t;
REP(i,0,s.size()) if (s[i] != 'x') t += s[i];
int l = 0, r = s.size()-1;
int cnt = 0;
while (l < r) {
if (s[l] == s[r]) {
++l; --r;
} else if (s[l] == 'x') {
++cnt;
++l;
} else if (s[r] == 'x') {
++cnt;
--r;
} else {
cout << -1 << endl;
return;
}
}
cout << cnt << endl;
}
int main() {
resolve();
return 0;
} | No | Do these codes solve the same problem?
Code 1: import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))
X, N = mi()
A = li()
flag = [0] * (205)
for num in A:
flag[num] = 1
if not flag[X]:
print(X)
exit()
i = 1
while True:
if not flag[X - i]:
print(X-i)
exit()
elif not flag[X + i]:
print(X+i)
exit()
i += 1
Code 2: #include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <memory>
#include <complex>
#include <numeric>
#include <cstdio>
#include <iomanip>
#define REP(i,m,n) for(int i=int(m);i<int(n);i++)
#define EACH(i,c) for (auto &(i): c)
#define all(c) begin(c),end(c)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort(begin(c),end(c))
#define pb emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
#ifdef LOCAL
#define DEBUG(s) cout << (s) << endl
#define dump(x) cerr << #x << " = " << (x) << endl
#define BR cout << endl;
#else
#define DEBUG(s) do{}while(0)
#define dump(x) do{}while(0)
#define BR
#endif
using namespace std;
using UI = unsigned int;
using UL = unsigned long;
using LL = long long int;
using ULL = unsigned long long;
using VI = vector<int>;
using VVI = vector<VI>;
using VLL = vector<LL>;
using VS = vector<string>;
using PII = pair<int,int>;
using VP = vector<PII>;
//struct edge {int from, to, cost;};
constexpr double EPS = 1e-10;
constexpr double PI = acos(-1.0);
//constexpr int INF = INT_MAX;
template<class T> inline T sqr(T x) {return x*x;}
void resolve() {
string s;
cin >> s;
string t;
REP(i,0,s.size()) if (s[i] != 'x') t += s[i];
int l = 0, r = s.size()-1;
int cnt = 0;
while (l < r) {
if (s[l] == s[r]) {
++l; --r;
} else if (s[l] == 'x') {
++cnt;
++l;
} else if (s[r] == 'x') {
++cnt;
--r;
} else {
cout << -1 << endl;
return;
}
}
cout << cnt << endl;
}
int main() {
resolve();
return 0;
} |
Python | n = int(input())
if n%9 == 0:
print('Yes')
else:
print('No') | Java | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] chars={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String str=sc.next();
for(int i=0;i<26;i++){
if((str.length()-str.replaceAll(chars[i],"").length())%2==1){
System.out.println("No");
return;
}
}
System.out.println("Yes");
}
} | No | Do these codes solve the same problem?
Code 1: n = int(input())
if n%9 == 0:
print('Yes')
else:
print('No')
Code 2: import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] chars={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String str=sc.next();
for(int i=0;i<26;i++){
if((str.length()-str.replaceAll(chars[i],"").length())%2==1){
System.out.println("No");
return;
}
}
System.out.println("Yes");
}
} |
Python | a, b, c = map(int, input().split())
spareA = a-b
ans = c - spareA
ans = ans if ans >= 0 else 0
print(ans) | C | #include <stdio.h>
struct card
{
char suit;
int num;
};
int bubbleSort(struct card C[], int num)
{
struct card temp;
int cnt = 0;
for (int i = 0; i < num; i++)
{
for (int j = num - 1; j >= i + 1; j--)
{
if (C[j].num < C[j - 1].num)
{
temp = C[j - 1];
C[j - 1] = C[j];
C[j] = temp;
cnt++;
}
}
}
return cnt;
}
int insertSort(struct card C[], int num)
{
struct card temp;
int cnt = 0, min = 0;
for (int i = 0; i < num; i++)
{
min = i;
for (int j = i; j < num; j++)
{
if (C[j].num < C[min].num)
{
min = j;
}
}
if (i != min) cnt++;
temp = C[i];
C[i] = C[min];
C[min] = temp;
}
return cnt;
}
int isstable(struct card C1[], struct card C2[], int num)
{
for (int i = 0; i < num; i++)
{
if (C1[i].suit != C2[i].suit) return -1;
}
return 1;
}
int main()
{
struct card C1[100];
struct card C2[100];
int num, temp_n,re = 0;
char temp_c;
scanf(" %d", &num);
for (int i = 0; i < num; i++)
{
scanf(" %c %d", &temp_c, &temp_n);
C1[i].suit = temp_c;
C1[i].num = temp_n;
C2[i].suit = temp_c;
C2[i].num = temp_n;
}
bubbleSort(C1, num);
insertSort(C2, num);
for (int i = 0; i < num; i++)
{
printf("%c%d", C1[i].suit, C1[i].num);
if (i < num - 1) printf(" ");
}
printf("\nStable\n");
for (int i = 0; i < num; i++)
{
printf("%c%d", C2[i].suit, C2[i].num);
if (i < num - 1) printf(" ");
}
if ((re = isstable(C1, C2, num)) == -1) printf("\nNot stable\n");
else printf("\nStable\n");
return 0;
}
| No | Do these codes solve the same problem?
Code 1: a, b, c = map(int, input().split())
spareA = a-b
ans = c - spareA
ans = ans if ans >= 0 else 0
print(ans)
Code 2: #include <stdio.h>
struct card
{
char suit;
int num;
};
int bubbleSort(struct card C[], int num)
{
struct card temp;
int cnt = 0;
for (int i = 0; i < num; i++)
{
for (int j = num - 1; j >= i + 1; j--)
{
if (C[j].num < C[j - 1].num)
{
temp = C[j - 1];
C[j - 1] = C[j];
C[j] = temp;
cnt++;
}
}
}
return cnt;
}
int insertSort(struct card C[], int num)
{
struct card temp;
int cnt = 0, min = 0;
for (int i = 0; i < num; i++)
{
min = i;
for (int j = i; j < num; j++)
{
if (C[j].num < C[min].num)
{
min = j;
}
}
if (i != min) cnt++;
temp = C[i];
C[i] = C[min];
C[min] = temp;
}
return cnt;
}
int isstable(struct card C1[], struct card C2[], int num)
{
for (int i = 0; i < num; i++)
{
if (C1[i].suit != C2[i].suit) return -1;
}
return 1;
}
int main()
{
struct card C1[100];
struct card C2[100];
int num, temp_n,re = 0;
char temp_c;
scanf(" %d", &num);
for (int i = 0; i < num; i++)
{
scanf(" %c %d", &temp_c, &temp_n);
C1[i].suit = temp_c;
C1[i].num = temp_n;
C2[i].suit = temp_c;
C2[i].num = temp_n;
}
bubbleSort(C1, num);
insertSort(C2, num);
for (int i = 0; i < num; i++)
{
printf("%c%d", C1[i].suit, C1[i].num);
if (i < num - 1) printf(" ");
}
printf("\nStable\n");
for (int i = 0; i < num; i++)
{
printf("%c%d", C2[i].suit, C2[i].num);
if (i < num - 1) printf(" ");
}
if ((re = isstable(C1, C2, num)) == -1) printf("\nNot stable\n");
else printf("\nStable\n");
return 0;
}
|
C | #include <stdio.h>
int main(void){
while(1){
int n,ice,i,ice0=0,ice1=0,ice2=0,ice3=0,ice4=0,ice5=0,ice6=0,ice7=0,ice8=0,ice9=0;
scanf("%d",&n);
if(n==0){
break;
}
for(i=1;i<=n;i++){
scanf("%d",&ice);
if(ice==0){
ice0++;
}
if(ice==1){
ice1++;
}
if(ice==2){
ice2++;
}
if(ice==03){
ice3++;
}
if(ice==4){
ice4++;
}
if(ice==5){
ice5++;
}
if(ice==6){
ice6++;
}
if(ice==7){
ice7++;
}
if(ice==8){
ice8++;
}
if(ice==9){
ice9++;
}
}
for(i=1;i<=ice0;i++){
printf("*");
}
if(ice0==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice1;i++){
printf("*");
}
if(ice1==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice2;i++){
printf("*");
}
if(ice2==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice3;i++){
printf("*");
}
if(ice3==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice4;i++){
printf("*");
}
if(ice4==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice5;i++){
printf("*");
}
if(ice5==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice6;i++){
printf("*");
}
if(ice6==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice7;i++){
printf("*");
}
if(ice7==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice8;i++){
printf("*");
}
if(ice8==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice9;i++){
printf("*");
}
if(ice9==0){
printf("-");
}
printf("\n");
}
}
| Java | import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
while (true) {
int isZero = scan.nextInt();
if (isZero == 0) {
break;
} else {
int cnt = isZero;
int[] kind = new int[10];
for (int i = 0; i < cnt; i++) {
int tmp = scan.nextInt();
kind[tmp]++;
}
for (int i : kind) {
if (i > 0) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
} else {
System.out.println("-");
}
}
}
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <stdio.h>
int main(void){
while(1){
int n,ice,i,ice0=0,ice1=0,ice2=0,ice3=0,ice4=0,ice5=0,ice6=0,ice7=0,ice8=0,ice9=0;
scanf("%d",&n);
if(n==0){
break;
}
for(i=1;i<=n;i++){
scanf("%d",&ice);
if(ice==0){
ice0++;
}
if(ice==1){
ice1++;
}
if(ice==2){
ice2++;
}
if(ice==03){
ice3++;
}
if(ice==4){
ice4++;
}
if(ice==5){
ice5++;
}
if(ice==6){
ice6++;
}
if(ice==7){
ice7++;
}
if(ice==8){
ice8++;
}
if(ice==9){
ice9++;
}
}
for(i=1;i<=ice0;i++){
printf("*");
}
if(ice0==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice1;i++){
printf("*");
}
if(ice1==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice2;i++){
printf("*");
}
if(ice2==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice3;i++){
printf("*");
}
if(ice3==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice4;i++){
printf("*");
}
if(ice4==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice5;i++){
printf("*");
}
if(ice5==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice6;i++){
printf("*");
}
if(ice6==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice7;i++){
printf("*");
}
if(ice7==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice8;i++){
printf("*");
}
if(ice8==0){
printf("-");
}
printf("\n");
for(i=1;i<=ice9;i++){
printf("*");
}
if(ice9==0){
printf("-");
}
printf("\n");
}
}
Code 2: import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
while (true) {
int isZero = scan.nextInt();
if (isZero == 0) {
break;
} else {
int cnt = isZero;
int[] kind = new int[10];
for (int i = 0; i < cnt; i++) {
int tmp = scan.nextInt();
kind[tmp]++;
}
for (int i : kind) {
if (i > 0) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
} else {
System.out.println("-");
}
}
}
}
}
}
|
C++ | #include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define lfs cout<<fixed<<setprecision(10)
#define ALL(a) (a).begin(),(a).end()
#define ALLR(a) (a).rbegin(),(a).rend()
#define spa << " " <<
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD = 1e9+7;
//const ll MOD = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T>
bool chmin(T &a,T b){if(a>b){a=b;return true;}else return false;}
template<typename T>
bool chmax(T &a,T b){if(a<b){a=b;return true;}else return false;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>
void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}
template<typename T>
void debug(vector<vector<T>>&v,ll h,ll w){for(ll i=0;i<h;i++)
{cout<<v[i][0];for(ll j=1;j<w;j++)cout spa v[i][j];cout<<endl;}};
void debug(vector<string>&v,ll h,ll w){for(ll i=0;i<h;i++)
{for(ll j=0;j<w;j++)cout<<v[i][j];cout<<endl;}};
template<typename T>
void debug(vector<T>&v,ll n){if(n!=0)cout<<v[0];
for(ll i=1;i<n;i++)cout spa v[i];cout<<endl;};
template<typename T>
vector<vector<T>>vec(ll x, ll y, T w){
vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,0,-1,0,1,1,-1,-1};
vector<ll>dy={0,1,0,-1,1,-1,1,-1};
template<typename T>
vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>
auto make_v(size_t a,Ts... ts){
return vector<decltype(make_v(ts...))>(a,make_v(ts...));
}
ostream &operator<<(ostream &os, pair<ll, ll>&p){
return os << p.first << " " << p.second;
}
struct SCC{
ll n;
vector<vector<ll>>G,Gr;
vector<ll>index;//各ノードが属する強連結成分の番号
vector<ll>ret;//dfsに使う
SCC(vector<vector<ll>>g):G(g),n(g.size()){
index.assign(n,-1LL);
build();
}
void build(){
Gr.assign(n,vector<ll>());
for(ll i=0;i<n;i++){
for(ll j=0;j<G[i].size();j++){
Gr[G[i][j]].push_back(i);
}
}
for(ll i=0;i<n;i++)if(index[i]==-1)dfs1(i);
fill(ALL(index),-1);
ll cnt=0;
reverse(ALL(ret));
for(ll i=0;i<n;i++){
if(index[ret[i]]==-1){
dfs2(ret[i],cnt);
cnt++;
}
}
}
void dfs1(ll k){
index[k]=1;
for(ll i=0;i<G[k].size();i++){
if(index[G[k][i]]==-1)dfs1(G[k][i]);
}
ret.push_back(k);
}
void dfs2(ll k, ll idx){
index[k]=idx;
for(ll i=0;i<Gr[k].size();i++){
if(index[Gr[k][i]]==-1)dfs2(Gr[k][i],idx);
}
}
vector<vector<ll>>edges;
void build_edges(){
edges.assign(*max_element(ALL(index))+1,vector<ll>());
for(ll i=0;i<n;i++){
for(ll j=0;j<G[i].size();j++){
if(index[i]!=index[G[i][j]]){
edges[index[i]].push_back(index[G[i][j]]);
}
}
}
}
vector<ll>output(){return index;};
};
int main(){
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
ll res=0,buf=0;
bool judge = true;
ll n,m;cin>>n>>m;
vector<vector<ll>>g(n);
rep(i,0,m){
ll a,b;cin>>a>>b;
g[a].PB(b);
}
SCC scc(g);
auto idx=scc.output();
ll mx=*max_element(ALL(idx))+1;
vector<vector<ll>>v(mx);
rep(i,0,n)v[idx[i]].PB(i);
cout<<mx<<endl;
rep(i,0,mx){
cout<<v[i].size();
for(auto z:v[i])cout<<" "<<z;
cout<<endl;
}
return 0;
} | Java | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.nio.charset.Charset;
import java.util.NoSuchElementException;
import java.io.OutputStream;
import java.nio.CharBuffer;
import java.util.Collection;
import java.io.IOException;
import java.nio.charset.CharsetDecoder;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.io.UncheckedIOException;
import java.util.List;
import java.security.AccessControlException;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper reloaded plug-in
* Actual solution is at the top
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner2 in = new LightScanner2(inputStream);
LightWriter2 out = new LightWriter2(outputStream);
SCC solver = new SCC();
solver.solve(1, in, out);
out.close();
}
static class SCC {
public void solve(int testNumber, LightScanner2 in, LightWriter2 out) {
int n = in.ints(), m = in.ints();
SCC.Node[] nodes = new SCC.Node[n];
for (int i = 0; i < n; i++) nodes[i] = new SCC.Node(i);
for (int i = 0; i < m; i++) {
int x = in.ints(), y = in.ints();
nodes[x].next.add(nodes[y]);
nodes[y].prev.add(nodes[x]);
}
List<? extends Collection<SCC.Node>> groups = SCCDecomposition.decompose(nodes);
out.ans(groups.size()).ln();
for (Collection<SCC.Node> group : groups) {
out.ans(group.size());
for (SCC.Node node : group) out.ans(node.getIndex());
out.ln();
}
}
private static class Node implements NodeLike<SCC.Node> {
final int index;
final List<SCC.Node> next = new ArrayList<>();
final List<SCC.Node> prev = new ArrayList<>();
Node(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
public Collection<SCC.Node> getNextNodes() {
return next;
}
public Collection<SCC.Node> getPrevNodes() {
return prev;
}
}
}
static class SCCDecomposition {
private SCCDecomposition() {
throw new UnsupportedOperationException();
}
public static <T extends NodeLike<T>> List<? extends Collection<T>> decompose(T... nodes) {
return decompose(Arrays.asList(nodes));
}
public static <T extends NodeLike<T>> List<? extends Collection<T>> decompose(List<T> nodes) {
int n = nodes.size(), allocated = 0;
boolean[] visited = new boolean[n];
int[] counter = new int[n];
for (int i = 0; i < n; i++) {
if (visited[i]) continue;
allocated = allocate(nodes.get(i), allocated, counter, visited);
}
int[] order = new int[n];
for (int i = 0; i < n; i++) order[n - counter[i] - 1] = i;
List<List<T>> result = new ArrayList<>();
for (int i : order) {
if (counter[i] == -1) continue;
List<T> group = new ArrayList<>();
makeGroup(nodes.get(i), counter, group);
result.add(group);
}
return result;
}
private static int allocate(NodeLike<?> node, int allocated, int[] counter, boolean[] visited) {
visited[node.getIndex()] = true;
for (NodeLike<?> next : node.getNextNodes()) {
if (visited[next.getIndex()]) continue;
allocated = allocate(next, allocated, counter, visited);
}
counter[node.getIndex()] = allocated;
return allocated + 1;
}
private static <T extends NodeLike<T>> void makeGroup(T node, int[] counter, List<T> group) {
counter[node.getIndex()] = -1;
group.add(node);
for (T next : node.getPrevNodes()) {
if (counter[next.getIndex()] == -1) continue;
makeGroup(next, counter, group);
}
}
}
static class LightScanner2 extends LightScannerAdapter {
private static final int BUF_SIZE = 32 * 1024;
private final InputStream stream;
private final byte[] buf = new byte[BUF_SIZE];
private int ptr;
private int len;
public LightScanner2(InputStream stream) {
this.stream = stream;
}
private int read() {
if (ptr < len) return buf[ptr++];
try {
ptr = 0;
len = stream.read(buf);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
if (len == -1) return -1;
return buf[ptr++];
}
private void skip() {
int b;
while (isTokenSeparator(b = read()) && b != -1) ;
if (b == -1) throw new NoSuchElementException("EOF");
ptr--;
}
public int ints() {
long x = longs();
if (x < Integer.MIN_VALUE || Integer.MAX_VALUE < x) throw new NumberFormatException("Overflow");
return (int) x;
}
public long longs() {
skip();
int b = read();
boolean negate;
if (b == '-') {
negate = true;
b = read();
} else negate = false;
long x = 0;
for (; !isTokenSeparator(b); b = read()) {
if ('0' <= b && b <= '9') x = x * 10 + b - '0';
else throw new NumberFormatException("Unexpected character '" + b + "'");
}
return negate ? -x : x;
}
public void close() {
try {
stream.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static boolean isTokenSeparator(int b) {
return b < 33 || 126 < b;
}
}
static abstract class LightScannerAdapter implements AutoCloseable {
public abstract void close();
}
static class LightWriter2 implements AutoCloseable {
private static final int BUF_SIZE = 32 * 1024;
private static final int BUF_THRESHOLD = 1024;
private final OutputStream out;
private final byte[] buf = new byte[BUF_SIZE];
private int ptr;
private final Field fastStringAccess;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter2(OutputStream out) {
this.out = out;
Field f;
try {
f = String.class.getDeclaredField("value");
f.setAccessible(true);
if (f.getType() != byte[].class) f = null;
} catch (ReflectiveOperationException | AccessControlException ignored) {
f = null;
}
this.fastStringAccess = f;
}
public LightWriter2(Writer out) {
this.out = new LightWriter2.WriterOutputStream(out);
this.fastStringAccess = null;
}
private void allocate(int n) {
if (ptr + n <= BUF_SIZE) return;
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
if (BUF_SIZE < n) throw new IllegalArgumentException("Internal buffer exceeded");
}
public void close() {
try {
out.write(buf, 0, ptr);
ptr = 0;
out.flush();
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public LightWriter2 print(char c) {
allocate(1);
buf[ptr++] = (byte) c;
breaked = false;
return this;
}
public LightWriter2 print(String s) {
byte[] bytes;
if (this.fastStringAccess == null) bytes = s.getBytes();
else {
try {
bytes = (byte[]) fastStringAccess.get(s);
} catch (IllegalAccessException ignored) {
bytes = s.getBytes();
}
}
int n = bytes.length;
if (n <= BUF_THRESHOLD) {
allocate(n);
System.arraycopy(bytes, 0, buf, ptr, n);
ptr += n;
return this;
}
try {
out.write(buf, 0, ptr);
ptr = 0;
out.write(bytes);
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter2 ans(int i) {
if (!breaked) {
print(' ');
}
breaked = false;
if (i == 0) return print('0');
if (i < 0) {
print('-');
i = -i;
}
int n = 0;
long t = i;
while (t > 0) {
t /= 10;
n++;
}
allocate(n);
for (int j = 1; j <= n; j++) {
buf[ptr + n - j] = (byte) (i % 10 + '0');
i /= 10;
}
ptr += n;
return this;
}
public LightWriter2 ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
private static class WriterOutputStream extends OutputStream {
final Writer writer;
final CharsetDecoder decoder;
WriterOutputStream(Writer writer) {
this.writer = writer;
this.decoder = StandardCharsets.UTF_8.newDecoder();
}
public void write(int b) throws IOException {
writer.write(b);
}
public void write(byte[] b) throws IOException {
writer.write(decoder.decode(ByteBuffer.wrap(b)).array());
}
public void write(byte[] b, int off, int len) throws IOException {
writer.write(decoder.decode(ByteBuffer.wrap(b, off, len)).array());
}
public void flush() throws IOException {
writer.flush();
}
public void close() throws IOException {
writer.close();
}
}
}
static interface NodeLike<T extends NodeLike<T>> {
int getIndex();
Collection<T> getNextNodes();
default Collection<T> getPrevNodes() {
// default implementation for an *undirected* graph
return getNextNodes();
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define lfs cout<<fixed<<setprecision(10)
#define ALL(a) (a).begin(),(a).end()
#define ALLR(a) (a).rbegin(),(a).rend()
#define spa << " " <<
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD = 1e9+7;
//const ll MOD = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T>
bool chmin(T &a,T b){if(a>b){a=b;return true;}else return false;}
template<typename T>
bool chmax(T &a,T b){if(a<b){a=b;return true;}else return false;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>
void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}
template<typename T>
void debug(vector<vector<T>>&v,ll h,ll w){for(ll i=0;i<h;i++)
{cout<<v[i][0];for(ll j=1;j<w;j++)cout spa v[i][j];cout<<endl;}};
void debug(vector<string>&v,ll h,ll w){for(ll i=0;i<h;i++)
{for(ll j=0;j<w;j++)cout<<v[i][j];cout<<endl;}};
template<typename T>
void debug(vector<T>&v,ll n){if(n!=0)cout<<v[0];
for(ll i=1;i<n;i++)cout spa v[i];cout<<endl;};
template<typename T>
vector<vector<T>>vec(ll x, ll y, T w){
vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,0,-1,0,1,1,-1,-1};
vector<ll>dy={0,1,0,-1,1,-1,1,-1};
template<typename T>
vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>
auto make_v(size_t a,Ts... ts){
return vector<decltype(make_v(ts...))>(a,make_v(ts...));
}
ostream &operator<<(ostream &os, pair<ll, ll>&p){
return os << p.first << " " << p.second;
}
struct SCC{
ll n;
vector<vector<ll>>G,Gr;
vector<ll>index;//各ノードが属する強連結成分の番号
vector<ll>ret;//dfsに使う
SCC(vector<vector<ll>>g):G(g),n(g.size()){
index.assign(n,-1LL);
build();
}
void build(){
Gr.assign(n,vector<ll>());
for(ll i=0;i<n;i++){
for(ll j=0;j<G[i].size();j++){
Gr[G[i][j]].push_back(i);
}
}
for(ll i=0;i<n;i++)if(index[i]==-1)dfs1(i);
fill(ALL(index),-1);
ll cnt=0;
reverse(ALL(ret));
for(ll i=0;i<n;i++){
if(index[ret[i]]==-1){
dfs2(ret[i],cnt);
cnt++;
}
}
}
void dfs1(ll k){
index[k]=1;
for(ll i=0;i<G[k].size();i++){
if(index[G[k][i]]==-1)dfs1(G[k][i]);
}
ret.push_back(k);
}
void dfs2(ll k, ll idx){
index[k]=idx;
for(ll i=0;i<Gr[k].size();i++){
if(index[Gr[k][i]]==-1)dfs2(Gr[k][i],idx);
}
}
vector<vector<ll>>edges;
void build_edges(){
edges.assign(*max_element(ALL(index))+1,vector<ll>());
for(ll i=0;i<n;i++){
for(ll j=0;j<G[i].size();j++){
if(index[i]!=index[G[i][j]]){
edges[index[i]].push_back(index[G[i][j]]);
}
}
}
}
vector<ll>output(){return index;};
};
int main(){
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
ll res=0,buf=0;
bool judge = true;
ll n,m;cin>>n>>m;
vector<vector<ll>>g(n);
rep(i,0,m){
ll a,b;cin>>a>>b;
g[a].PB(b);
}
SCC scc(g);
auto idx=scc.output();
ll mx=*max_element(ALL(idx))+1;
vector<vector<ll>>v(mx);
rep(i,0,n)v[idx[i]].PB(i);
cout<<mx<<endl;
rep(i,0,mx){
cout<<v[i].size();
for(auto z:v[i])cout<<" "<<z;
cout<<endl;
}
return 0;
}
Code 2: import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.nio.charset.Charset;
import java.util.NoSuchElementException;
import java.io.OutputStream;
import java.nio.CharBuffer;
import java.util.Collection;
import java.io.IOException;
import java.nio.charset.CharsetDecoder;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.io.UncheckedIOException;
import java.util.List;
import java.security.AccessControlException;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper reloaded plug-in
* Actual solution is at the top
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner2 in = new LightScanner2(inputStream);
LightWriter2 out = new LightWriter2(outputStream);
SCC solver = new SCC();
solver.solve(1, in, out);
out.close();
}
static class SCC {
public void solve(int testNumber, LightScanner2 in, LightWriter2 out) {
int n = in.ints(), m = in.ints();
SCC.Node[] nodes = new SCC.Node[n];
for (int i = 0; i < n; i++) nodes[i] = new SCC.Node(i);
for (int i = 0; i < m; i++) {
int x = in.ints(), y = in.ints();
nodes[x].next.add(nodes[y]);
nodes[y].prev.add(nodes[x]);
}
List<? extends Collection<SCC.Node>> groups = SCCDecomposition.decompose(nodes);
out.ans(groups.size()).ln();
for (Collection<SCC.Node> group : groups) {
out.ans(group.size());
for (SCC.Node node : group) out.ans(node.getIndex());
out.ln();
}
}
private static class Node implements NodeLike<SCC.Node> {
final int index;
final List<SCC.Node> next = new ArrayList<>();
final List<SCC.Node> prev = new ArrayList<>();
Node(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
public Collection<SCC.Node> getNextNodes() {
return next;
}
public Collection<SCC.Node> getPrevNodes() {
return prev;
}
}
}
static class SCCDecomposition {
private SCCDecomposition() {
throw new UnsupportedOperationException();
}
public static <T extends NodeLike<T>> List<? extends Collection<T>> decompose(T... nodes) {
return decompose(Arrays.asList(nodes));
}
public static <T extends NodeLike<T>> List<? extends Collection<T>> decompose(List<T> nodes) {
int n = nodes.size(), allocated = 0;
boolean[] visited = new boolean[n];
int[] counter = new int[n];
for (int i = 0; i < n; i++) {
if (visited[i]) continue;
allocated = allocate(nodes.get(i), allocated, counter, visited);
}
int[] order = new int[n];
for (int i = 0; i < n; i++) order[n - counter[i] - 1] = i;
List<List<T>> result = new ArrayList<>();
for (int i : order) {
if (counter[i] == -1) continue;
List<T> group = new ArrayList<>();
makeGroup(nodes.get(i), counter, group);
result.add(group);
}
return result;
}
private static int allocate(NodeLike<?> node, int allocated, int[] counter, boolean[] visited) {
visited[node.getIndex()] = true;
for (NodeLike<?> next : node.getNextNodes()) {
if (visited[next.getIndex()]) continue;
allocated = allocate(next, allocated, counter, visited);
}
counter[node.getIndex()] = allocated;
return allocated + 1;
}
private static <T extends NodeLike<T>> void makeGroup(T node, int[] counter, List<T> group) {
counter[node.getIndex()] = -1;
group.add(node);
for (T next : node.getPrevNodes()) {
if (counter[next.getIndex()] == -1) continue;
makeGroup(next, counter, group);
}
}
}
static class LightScanner2 extends LightScannerAdapter {
private static final int BUF_SIZE = 32 * 1024;
private final InputStream stream;
private final byte[] buf = new byte[BUF_SIZE];
private int ptr;
private int len;
public LightScanner2(InputStream stream) {
this.stream = stream;
}
private int read() {
if (ptr < len) return buf[ptr++];
try {
ptr = 0;
len = stream.read(buf);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
if (len == -1) return -1;
return buf[ptr++];
}
private void skip() {
int b;
while (isTokenSeparator(b = read()) && b != -1) ;
if (b == -1) throw new NoSuchElementException("EOF");
ptr--;
}
public int ints() {
long x = longs();
if (x < Integer.MIN_VALUE || Integer.MAX_VALUE < x) throw new NumberFormatException("Overflow");
return (int) x;
}
public long longs() {
skip();
int b = read();
boolean negate;
if (b == '-') {
negate = true;
b = read();
} else negate = false;
long x = 0;
for (; !isTokenSeparator(b); b = read()) {
if ('0' <= b && b <= '9') x = x * 10 + b - '0';
else throw new NumberFormatException("Unexpected character '" + b + "'");
}
return negate ? -x : x;
}
public void close() {
try {
stream.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static boolean isTokenSeparator(int b) {
return b < 33 || 126 < b;
}
}
static abstract class LightScannerAdapter implements AutoCloseable {
public abstract void close();
}
static class LightWriter2 implements AutoCloseable {
private static final int BUF_SIZE = 32 * 1024;
private static final int BUF_THRESHOLD = 1024;
private final OutputStream out;
private final byte[] buf = new byte[BUF_SIZE];
private int ptr;
private final Field fastStringAccess;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter2(OutputStream out) {
this.out = out;
Field f;
try {
f = String.class.getDeclaredField("value");
f.setAccessible(true);
if (f.getType() != byte[].class) f = null;
} catch (ReflectiveOperationException | AccessControlException ignored) {
f = null;
}
this.fastStringAccess = f;
}
public LightWriter2(Writer out) {
this.out = new LightWriter2.WriterOutputStream(out);
this.fastStringAccess = null;
}
private void allocate(int n) {
if (ptr + n <= BUF_SIZE) return;
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
if (BUF_SIZE < n) throw new IllegalArgumentException("Internal buffer exceeded");
}
public void close() {
try {
out.write(buf, 0, ptr);
ptr = 0;
out.flush();
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public LightWriter2 print(char c) {
allocate(1);
buf[ptr++] = (byte) c;
breaked = false;
return this;
}
public LightWriter2 print(String s) {
byte[] bytes;
if (this.fastStringAccess == null) bytes = s.getBytes();
else {
try {
bytes = (byte[]) fastStringAccess.get(s);
} catch (IllegalAccessException ignored) {
bytes = s.getBytes();
}
}
int n = bytes.length;
if (n <= BUF_THRESHOLD) {
allocate(n);
System.arraycopy(bytes, 0, buf, ptr, n);
ptr += n;
return this;
}
try {
out.write(buf, 0, ptr);
ptr = 0;
out.write(bytes);
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter2 ans(int i) {
if (!breaked) {
print(' ');
}
breaked = false;
if (i == 0) return print('0');
if (i < 0) {
print('-');
i = -i;
}
int n = 0;
long t = i;
while (t > 0) {
t /= 10;
n++;
}
allocate(n);
for (int j = 1; j <= n; j++) {
buf[ptr + n - j] = (byte) (i % 10 + '0');
i /= 10;
}
ptr += n;
return this;
}
public LightWriter2 ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
private static class WriterOutputStream extends OutputStream {
final Writer writer;
final CharsetDecoder decoder;
WriterOutputStream(Writer writer) {
this.writer = writer;
this.decoder = StandardCharsets.UTF_8.newDecoder();
}
public void write(int b) throws IOException {
writer.write(b);
}
public void write(byte[] b) throws IOException {
writer.write(decoder.decode(ByteBuffer.wrap(b)).array());
}
public void write(byte[] b, int off, int len) throws IOException {
writer.write(decoder.decode(ByteBuffer.wrap(b, off, len)).array());
}
public void flush() throws IOException {
writer.flush();
}
public void close() throws IOException {
writer.close();
}
}
}
static interface NodeLike<T extends NodeLike<T>> {
int getIndex();
Collection<T> getNextNodes();
default Collection<T> getPrevNodes() {
// default implementation for an *undirected* graph
return getNextNodes();
}
}
}
|
C# | using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string[] str = Console.ReadLine().Split();
long L = long.Parse(str[0]);
long R = long.Parse(str[1]);
long D = long.Parse(str[2]);
long ans = 0;
for(var i=L;i<=R;i++){
if(i%D==0){
ans++;
}
}
Console.WriteLine(ans);
}
} | C++ | #include<bits/stdc++.h>
using namespace std;
#if defined __has_include
# if __has_include(<bits/debug_aamir.h>)
# define dbg(...) DEBUG(#__VA_ARGS__, __VA_ARGS__);
# include<bits/debug_aamir.h>
# else
# define dbg(...)
# endif
#endif
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef long long ll;
typedef pair<ll, ll> pll;
#define sz(x) int(x.size())
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define rep(i, begin, end) for(__typeof(end) i=begin; i<end; i++)
#define per(i, begin, end) for(__typeof(end) i=begin; i>=end; i--)
#define fi first
#define se second
#define fastio ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
constexpr int INF = 1e9 + 1;
constexpr ll LLINF = 1e18 + 1;
template<typename T>
T gcd(T a, T b){ return b ? gcd(b, a%b): a; }
template<typename T>
T lcm(T a, T b){ return a/gcd(a, b) * b; }
ii operator + (ii &a, ii &b){
return {a.fi+b.fi, a.se+b.se};
}
int main()
{
fastio;
string s, t;
cin >> s >> t;
int n=s.length(), m=t.length();
vector<vi> dp(n+1, vi(m+1));
vector<ii> ch = {{1, 0}, {0, 1}, {1, 1}};
ii cur, next;
dbg(s, t);
rep(i, 0, n){
rep(j, 0, m){
cur = {i, j};
rep(c, 0, 3) if(c != 2 || s[i]==t[j]){
next = cur + ch[c];
if(next.fi>n || next.se>m) continue;
dp[next.fi][next.se] = max(dp[next.fi][next.se], dp[cur.fi][cur.se] + (c==2));
}
}
}
rep(i, 0, n)
dp[i+1][m] = max(dp[i+1][m], dp[i][m]);
rep(j, 0, m)
dp[n][j+1] = max(dp[n][j+1], dp[n][j]);
dbg(dp);
string sol="";
cur = {n, m};
while(cur.fi && cur.se){
rep(c, 0, 3){
next = cur;
next.fi -= ch[c].fi;
next.se -= ch[c].se;
if(dp[next.fi][next.se] + (c==2) == dp[cur.fi][cur.se]){
if(c==2)
sol.push_back(s[next.fi]);
cur = next;
break;
}
}
}
dbg(sol);
reverse(sol.begin(), sol.end());
cout << sol << '\n';
}
| No | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string[] str = Console.ReadLine().Split();
long L = long.Parse(str[0]);
long R = long.Parse(str[1]);
long D = long.Parse(str[2]);
long ans = 0;
for(var i=L;i<=R;i++){
if(i%D==0){
ans++;
}
}
Console.WriteLine(ans);
}
}
Code 2: #include<bits/stdc++.h>
using namespace std;
#if defined __has_include
# if __has_include(<bits/debug_aamir.h>)
# define dbg(...) DEBUG(#__VA_ARGS__, __VA_ARGS__);
# include<bits/debug_aamir.h>
# else
# define dbg(...)
# endif
#endif
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef long long ll;
typedef pair<ll, ll> pll;
#define sz(x) int(x.size())
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define rep(i, begin, end) for(__typeof(end) i=begin; i<end; i++)
#define per(i, begin, end) for(__typeof(end) i=begin; i>=end; i--)
#define fi first
#define se second
#define fastio ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
constexpr int INF = 1e9 + 1;
constexpr ll LLINF = 1e18 + 1;
template<typename T>
T gcd(T a, T b){ return b ? gcd(b, a%b): a; }
template<typename T>
T lcm(T a, T b){ return a/gcd(a, b) * b; }
ii operator + (ii &a, ii &b){
return {a.fi+b.fi, a.se+b.se};
}
int main()
{
fastio;
string s, t;
cin >> s >> t;
int n=s.length(), m=t.length();
vector<vi> dp(n+1, vi(m+1));
vector<ii> ch = {{1, 0}, {0, 1}, {1, 1}};
ii cur, next;
dbg(s, t);
rep(i, 0, n){
rep(j, 0, m){
cur = {i, j};
rep(c, 0, 3) if(c != 2 || s[i]==t[j]){
next = cur + ch[c];
if(next.fi>n || next.se>m) continue;
dp[next.fi][next.se] = max(dp[next.fi][next.se], dp[cur.fi][cur.se] + (c==2));
}
}
}
rep(i, 0, n)
dp[i+1][m] = max(dp[i+1][m], dp[i][m]);
rep(j, 0, m)
dp[n][j+1] = max(dp[n][j+1], dp[n][j]);
dbg(dp);
string sol="";
cur = {n, m};
while(cur.fi && cur.se){
rep(c, 0, 3){
next = cur;
next.fi -= ch[c].fi;
next.se -= ch[c].se;
if(dp[next.fi][next.se] + (c==2) == dp[cur.fi][cur.se]){
if(c==2)
sol.push_back(s[next.fi]);
cur = next;
break;
}
}
}
dbg(sol);
reverse(sol.begin(), sol.end());
cout << sol << '\n';
}
|
Python | import sys
input = sys.stdin.readline
N,M=map(int,input().split())
S=input().strip()
ANS=[]
NOW=N
while NOW!=0:
for i in range(M,0,-1):
if NOW-i>=0 and S[NOW-i]=="0":
NOW-=i
ANS.append(i)
break
else:
print(-1)
sys.exit()
print(*ANS[::-1]) | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;
namespace Program
{
public static class ABC146F
{
static public int numberOfRandomCases = 0;
static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
{
}
static public void Solve()
{
var N = NN;
var M = NN;
var S = NS;
var seg = new LIB_LazySegTree<Tuple<int, int>, Tuple<int, int>>(N + 1, Tuple.Create(1000000000, 0), Tuple.Create(1000000000, 0), (x, y) =>
{
if (x.Item1 <= y.Item1) return x;
else return y;
}, (x, y) =>
{
if (x.Item1 <= y.Item1) return x;
else return y;
}, (x, y) =>
{
if (x.Item1 <= y.Item1) return x;
else return y;
});
seg[0] = Tuple.Create(0, 0);
for (var i = 0; i <= N; i++)
{
if (S[i] == '1') continue;
seg.Update(i, Min(i + M + 1, N + 1), Tuple.Create(seg[i].Item1 + 1, i));
}
if (seg[N].Item1 == 1000000000)
{
Console.WriteLine(-1);
}
else
{
var now = N;
var ans = new List<long>();
while (now != 0)
{
var before = seg[now].Item2;
ans.Add(now - before);
now = before;
}
ans.Reverse();
Console.WriteLine(string.Join(" ", ans));
}
}
static class Console_
{
static Queue<string> param = new Queue<string>();
public static string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
}
class Printer : StreamWriter
{
public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
}
static public void Main(string[] args) { if (args.Length == 0) { Console.SetOut(new Printer(Console.OpenStandardOutput())); } var t = new Thread(Solve, 134217728); t.Start(); t.Join(); Console.Out.Flush(); }
static long NN => long.Parse(Console_.NextString());
static double ND => double.Parse(Console_.NextString());
static string NS => Console_.NextString();
static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
static IEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => x.OrderBy(_ => xorshift);
static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
static IEnumerator<uint> _xsi = _xsc();
static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
}
}namespace Library {
class LIB_LazySegTree<T, E>
{
int n, height;
T ti;
E ei;
Func<T, T, T> f;
Func<T, E, T> g;
Func<E, E, E> h;
T[] dat;
E[] laz;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LIB_LazySegTree(long _n, T _ti, E _ei, Func<T, T, T> _f, Func<T, E, T> _g, Func<E, E, E> _h)
{
n = 1; height = 0;
while (n < _n) { n <<= 1; ++height; }
ti = _ti;
ei = _ei;
f = _f;
g = _g;
h = _h;
dat = Enumerable.Repeat(ti, n << 1).ToArray();
laz = Enumerable.Repeat(ei, n << 1).ToArray();
for (var i = n - 1; i > 0; i--) dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LIB_LazySegTree(IEnumerable<T> l, T _ti, E _ei, Func<T, T, T> _f, Func<T, E, T> _g, Func<E, E, E> _h) : this(l.Count(), _ti, _ei, _f, _g, _h)
{
var idx = 0;
foreach (var item in l) dat[n + idx++] = item;
for (var i = n - 1; i > 0; i--) dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
T Reflect(long i) => laz[i].Equals(ei) ? dat[i] : g(dat[i], laz[i]);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Eval(long i)
{
if (laz[i].Equals(ei)) return;
laz[(i << 1) | 0] = h(laz[(i << 1) | 0], laz[i]);
laz[(i << 1) | 1] = h(laz[(i << 1) | 1], laz[i]);
dat[i] = Reflect(i);
laz[i] = ei;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Thrust(long i)
{
for (var j = height; j > 0; j--) Eval(i >> j);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Recalc(long i)
{
while ((i >>= 1) > 0) dat[i] = f(Reflect((i << 1) | 0), Reflect((i << 1) | 1));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Update(long l, long r, E v)
{
Thrust(l += n); Thrust(r += n - 1);
for (long li = l, ri = r + 1; li < ri; li >>= 1, ri >>= 1)
{
if ((li & 1) == 1) { laz[li] = h(laz[li], v); ++li; }
if ((ri & 1) == 1) { --ri; laz[ri] = h(laz[ri], v); }
}
Recalc(l); Recalc(r);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Query(long l, long r)
{
Thrust(l += n); Thrust(r += n - 1);
var vl = ti; var vr = ti;
for (long li = l, ri = r + 1; li < ri; li >>= 1, ri >>= 1)
{
if ((li & 1) == 1) vl = f(vl, Reflect(li++));
if ((ri & 1) == 1) vr = f(Reflect(--ri), vr);
}
return f(vl, vr);
}
public T this[long idx]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { Thrust(idx += n); return Reflect(idx); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set { Thrust(idx += n); dat[idx] = value; laz[idx] = ei; Recalc(idx); }
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: import sys
input = sys.stdin.readline
N,M=map(int,input().split())
S=input().strip()
ANS=[]
NOW=N
while NOW!=0:
for i in range(M,0,-1):
if NOW-i>=0 and S[NOW-i]=="0":
NOW-=i
ANS.append(i)
break
else:
print(-1)
sys.exit()
print(*ANS[::-1])
Code 2: using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;
namespace Program
{
public static class ABC146F
{
static public int numberOfRandomCases = 0;
static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
{
}
static public void Solve()
{
var N = NN;
var M = NN;
var S = NS;
var seg = new LIB_LazySegTree<Tuple<int, int>, Tuple<int, int>>(N + 1, Tuple.Create(1000000000, 0), Tuple.Create(1000000000, 0), (x, y) =>
{
if (x.Item1 <= y.Item1) return x;
else return y;
}, (x, y) =>
{
if (x.Item1 <= y.Item1) return x;
else return y;
}, (x, y) =>
{
if (x.Item1 <= y.Item1) return x;
else return y;
});
seg[0] = Tuple.Create(0, 0);
for (var i = 0; i <= N; i++)
{
if (S[i] == '1') continue;
seg.Update(i, Min(i + M + 1, N + 1), Tuple.Create(seg[i].Item1 + 1, i));
}
if (seg[N].Item1 == 1000000000)
{
Console.WriteLine(-1);
}
else
{
var now = N;
var ans = new List<long>();
while (now != 0)
{
var before = seg[now].Item2;
ans.Add(now - before);
now = before;
}
ans.Reverse();
Console.WriteLine(string.Join(" ", ans));
}
}
static class Console_
{
static Queue<string> param = new Queue<string>();
public static string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
}
class Printer : StreamWriter
{
public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
}
static public void Main(string[] args) { if (args.Length == 0) { Console.SetOut(new Printer(Console.OpenStandardOutput())); } var t = new Thread(Solve, 134217728); t.Start(); t.Join(); Console.Out.Flush(); }
static long NN => long.Parse(Console_.NextString());
static double ND => double.Parse(Console_.NextString());
static string NS => Console_.NextString();
static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
static IEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => x.OrderBy(_ => xorshift);
static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
static IEnumerator<uint> _xsi = _xsc();
static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
}
}namespace Library {
class LIB_LazySegTree<T, E>
{
int n, height;
T ti;
E ei;
Func<T, T, T> f;
Func<T, E, T> g;
Func<E, E, E> h;
T[] dat;
E[] laz;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LIB_LazySegTree(long _n, T _ti, E _ei, Func<T, T, T> _f, Func<T, E, T> _g, Func<E, E, E> _h)
{
n = 1; height = 0;
while (n < _n) { n <<= 1; ++height; }
ti = _ti;
ei = _ei;
f = _f;
g = _g;
h = _h;
dat = Enumerable.Repeat(ti, n << 1).ToArray();
laz = Enumerable.Repeat(ei, n << 1).ToArray();
for (var i = n - 1; i > 0; i--) dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LIB_LazySegTree(IEnumerable<T> l, T _ti, E _ei, Func<T, T, T> _f, Func<T, E, T> _g, Func<E, E, E> _h) : this(l.Count(), _ti, _ei, _f, _g, _h)
{
var idx = 0;
foreach (var item in l) dat[n + idx++] = item;
for (var i = n - 1; i > 0; i--) dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
T Reflect(long i) => laz[i].Equals(ei) ? dat[i] : g(dat[i], laz[i]);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Eval(long i)
{
if (laz[i].Equals(ei)) return;
laz[(i << 1) | 0] = h(laz[(i << 1) | 0], laz[i]);
laz[(i << 1) | 1] = h(laz[(i << 1) | 1], laz[i]);
dat[i] = Reflect(i);
laz[i] = ei;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Thrust(long i)
{
for (var j = height; j > 0; j--) Eval(i >> j);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Recalc(long i)
{
while ((i >>= 1) > 0) dat[i] = f(Reflect((i << 1) | 0), Reflect((i << 1) | 1));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Update(long l, long r, E v)
{
Thrust(l += n); Thrust(r += n - 1);
for (long li = l, ri = r + 1; li < ri; li >>= 1, ri >>= 1)
{
if ((li & 1) == 1) { laz[li] = h(laz[li], v); ++li; }
if ((ri & 1) == 1) { --ri; laz[ri] = h(laz[ri], v); }
}
Recalc(l); Recalc(r);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Query(long l, long r)
{
Thrust(l += n); Thrust(r += n - 1);
var vl = ti; var vr = ti;
for (long li = l, ri = r + 1; li < ri; li >>= 1, ri >>= 1)
{
if ((li & 1) == 1) vl = f(vl, Reflect(li++));
if ((ri & 1) == 1) vr = f(Reflect(--ri), vr);
}
return f(vl, vr);
}
public T this[long idx]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { Thrust(idx += n); return Reflect(idx); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set { Thrust(idx += n); dat[idx] = value; laz[idx] = ei; Recalc(idx); }
}
}
}
|
JavaScript | (function () {
var input = '';
function main () {
var i,
inputLen,
inputContent,
BookIndex = {};
inputLen = input.length - 1;
for (i = 0; i < inputLen; i += 1) {
inputContent = input[i].split(' ');
if (BookIndex.hasOwnProperty(inputContent[0])) {
BookIndex[inputContent[0]].push(inputContent[1]);
BookIndex[inputContent[0]].sort(sortNum);
} else {
BookIndex[inputContent[0]] = [];
BookIndex[inputContent[0]].push(inputContent[1]);
}
}
BookIndex = sortHash(BookIndex);
for (var prop in BookIndex) {
console.log(prop);
console.log(concatenateArrayElem(BookIndex[prop]));
}
}
// Array.sortでの数値昇順化のための比較関数
function sortNum (a, b) {
return a - b;
}
// 連想配列の辞書順化
function sortHash (hash) {
var i,
keysLen,
keys = [],
sortedHash = {};
for (var k in hash) {
keys.push(k);
}
keys.sort();
keysLen = keys.length;
for (i = 0; i < keysLen; i += 1) {
sortedHash[keys[i]] = hash[keys[i]];
}
return sortedHash;
}
function concatenateArrayElem(ary) {
var i,
resultStr = '',
len = ary.length;
for (i = 0; i < len; i += 1) {
resultStr += ary[i];
if (i != len - 1) {
resultStr += ' ';
}
}
return resultStr;
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
input += chunk;
});
process.stdin.on('end', function () {
input = input.split('\n');
main();
});
}()); | PHP | <?php
$arr = array();
while($line = trim(fgets(STDIN))) {
list($name,$page) = explode(" ",trim($line));
$name = trim($name);
$page = intval($page);
$arr[$name][] = $page;
}
// var_dump($arr);
ksort($arr);
foreach($arr as $k => $v) {
sort($v);
echo $k . PHP_EOL;
echo implode(" ",$v) . PHP_EOL;
}
| Yes | Do these codes solve the same problem?
Code 1: (function () {
var input = '';
function main () {
var i,
inputLen,
inputContent,
BookIndex = {};
inputLen = input.length - 1;
for (i = 0; i < inputLen; i += 1) {
inputContent = input[i].split(' ');
if (BookIndex.hasOwnProperty(inputContent[0])) {
BookIndex[inputContent[0]].push(inputContent[1]);
BookIndex[inputContent[0]].sort(sortNum);
} else {
BookIndex[inputContent[0]] = [];
BookIndex[inputContent[0]].push(inputContent[1]);
}
}
BookIndex = sortHash(BookIndex);
for (var prop in BookIndex) {
console.log(prop);
console.log(concatenateArrayElem(BookIndex[prop]));
}
}
// Array.sortでの数値昇順化のための比較関数
function sortNum (a, b) {
return a - b;
}
// 連想配列の辞書順化
function sortHash (hash) {
var i,
keysLen,
keys = [],
sortedHash = {};
for (var k in hash) {
keys.push(k);
}
keys.sort();
keysLen = keys.length;
for (i = 0; i < keysLen; i += 1) {
sortedHash[keys[i]] = hash[keys[i]];
}
return sortedHash;
}
function concatenateArrayElem(ary) {
var i,
resultStr = '',
len = ary.length;
for (i = 0; i < len; i += 1) {
resultStr += ary[i];
if (i != len - 1) {
resultStr += ' ';
}
}
return resultStr;
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
input += chunk;
});
process.stdin.on('end', function () {
input = input.split('\n');
main();
});
}());
Code 2: <?php
$arr = array();
while($line = trim(fgets(STDIN))) {
list($name,$page) = explode(" ",trim($line));
$name = trim($name);
$page = intval($page);
$arr[$name][] = $page;
}
// var_dump($arr);
ksort($arr);
foreach($arr as $k => $v) {
sort($v);
echo $k . PHP_EOL;
echo implode(" ",$v) . PHP_EOL;
}
|
C++ | //Dragon_warrior7(IITK)
#pragma GCC optimize ("Ofast")
#pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize ("-ffloat-store")
#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//using namespace __gnu_pbds;
#define ll long long
#define pb push_back
#define nl cout << '\n'
#define sor(x) sort(x.begin(), x.end())
#define rev(v) reverse(v.begin(), v.end())
#define lb(v, temp) lower_bound(v.begin(), v.end(), temp)
#define ub(v, temp) upper_bound(v.begin(), v.end(), temp)
#define fi first
#define se second
#define llmax 1000000000000000000
#define pll pair<ll, ll>
#define ull unsigned ll
#define vll vector<ll>
#define rub cout << "\n------------------------------------\n"
#define deb(x) cout<<#x<<' '<<'='<<' '<<x<<'\n'
//typedef tree < int , null_type , greater<int> , rb_tree_tag , tree_order_statistics_node_update > oset;
void read(vector<ll> &v)
{
for (int i = 0; i < v.size(); i++)
cin >> v[i];
}
// const int mod=1e9+7;
// ll power(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
// ll modInverse(ll a){return power(a,mod-2);}
ll n,m,a,b,c,k,temp,x,y;
void solveforthiscase(const int & test)
{//deb(test);
cin>>n;
vll v(n);
read(v);
ll count4=0;
ll count2=0;
for(int i=0;i<n;i++)
{
if(v[i]%4==0)
count4++;
else
if(v[i]%2==0)
count2++;
}
if(count4*2+1>=n)
{
cout<<"Yes";
}
else if(count4*2+count2>=n)
{
cout<<"Yes";
}
else
cout<<"No";
return ;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test=1;
// cin>>test;
for(int i=1;i<=test;i++)
{
solveforthiscase(i);
}
} | Java |
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
System.out.println((x - z)/(y + z));
}
}
| No | Do these codes solve the same problem?
Code 1: //Dragon_warrior7(IITK)
#pragma GCC optimize ("Ofast")
#pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize ("-ffloat-store")
#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//using namespace __gnu_pbds;
#define ll long long
#define pb push_back
#define nl cout << '\n'
#define sor(x) sort(x.begin(), x.end())
#define rev(v) reverse(v.begin(), v.end())
#define lb(v, temp) lower_bound(v.begin(), v.end(), temp)
#define ub(v, temp) upper_bound(v.begin(), v.end(), temp)
#define fi first
#define se second
#define llmax 1000000000000000000
#define pll pair<ll, ll>
#define ull unsigned ll
#define vll vector<ll>
#define rub cout << "\n------------------------------------\n"
#define deb(x) cout<<#x<<' '<<'='<<' '<<x<<'\n'
//typedef tree < int , null_type , greater<int> , rb_tree_tag , tree_order_statistics_node_update > oset;
void read(vector<ll> &v)
{
for (int i = 0; i < v.size(); i++)
cin >> v[i];
}
// const int mod=1e9+7;
// ll power(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
// ll modInverse(ll a){return power(a,mod-2);}
ll n,m,a,b,c,k,temp,x,y;
void solveforthiscase(const int & test)
{//deb(test);
cin>>n;
vll v(n);
read(v);
ll count4=0;
ll count2=0;
for(int i=0;i<n;i++)
{
if(v[i]%4==0)
count4++;
else
if(v[i]%2==0)
count2++;
}
if(count4*2+1>=n)
{
cout<<"Yes";
}
else if(count4*2+count2>=n)
{
cout<<"Yes";
}
else
cout<<"No";
return ;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test=1;
// cin>>test;
for(int i=1;i<=test;i++)
{
solveforthiscase(i);
}
}
Code 2:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
System.out.println((x - z)/(y + z));
}
}
|
C | /*
AOJ #1568
title:String Conversion
@kankichi57301
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char s[100001],t[100001];
int s_cnt[26],t_cnt[26];
int n;
int comp( const void * a , const void * b ) {
if( *( int * )a > *( int * )b ) {
return 1;
}
else
if( *( int * )a == *( int * )b ) {
return 0;
}
return -1;
}
int solve(int s_c[],int t_c[])
{
int i,ret;
qsort(s_c,26,sizeof(int),comp);
qsort(t_c,26,sizeof(int),comp);
for(i=0,ret=0;i<26;i++)
if(s_c[i]>t_c[i])
ret += (s_c[i]-t_c[i]);
return(ret);
}
int main()
{
int i,ret;
scanf("%d",&n);
scanf("%s",s);
scanf("%s",t);
for(i=0;i<n;i++)
{
s_cnt[s[i]-'a']++;
t_cnt[t[i]-'a']++;
}
ret=solve(s_cnt,t_cnt);
printf("%d\n",ret);
return(0);
}
| C# | using System.Linq;
using System.Collections.Generic;
using System;
public class Hello
{
public static void Main()
{
var aL = "abcdefghijklmnopqrstuvwxyz";
var d = new Dictionary<char, int>();
for (int i = 0; i < 26; i++) d[aL[i]] = i;
var a = new int[26];
var b = new int[26];
var n = int.Parse(Console.ReadLine().Trim());
var s = Console.ReadLine().Trim();
var t = Console.ReadLine().Trim();
for (int i = 0; i < n; i++) { a[d[s[i]]]++; b[d[t[i]]]++; }
var a2 = a.Where(x => x >= 1).OrderByDescending(x => x).ToArray();
var b2 = b.Where(x => x >= 1).OrderByDescending(x => x).ToArray();
var imin = Math.Min(a2.Length, b2.Length);
for (int i = 0; i < imin; i++)
a2[i] = Math.Max(a2[i] - b2[i], 0);
Console.WriteLine(a2.Sum());
}
}
| Yes | Do these codes solve the same problem?
Code 1: /*
AOJ #1568
title:String Conversion
@kankichi57301
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char s[100001],t[100001];
int s_cnt[26],t_cnt[26];
int n;
int comp( const void * a , const void * b ) {
if( *( int * )a > *( int * )b ) {
return 1;
}
else
if( *( int * )a == *( int * )b ) {
return 0;
}
return -1;
}
int solve(int s_c[],int t_c[])
{
int i,ret;
qsort(s_c,26,sizeof(int),comp);
qsort(t_c,26,sizeof(int),comp);
for(i=0,ret=0;i<26;i++)
if(s_c[i]>t_c[i])
ret += (s_c[i]-t_c[i]);
return(ret);
}
int main()
{
int i,ret;
scanf("%d",&n);
scanf("%s",s);
scanf("%s",t);
for(i=0;i<n;i++)
{
s_cnt[s[i]-'a']++;
t_cnt[t[i]-'a']++;
}
ret=solve(s_cnt,t_cnt);
printf("%d\n",ret);
return(0);
}
Code 2: using System.Linq;
using System.Collections.Generic;
using System;
public class Hello
{
public static void Main()
{
var aL = "abcdefghijklmnopqrstuvwxyz";
var d = new Dictionary<char, int>();
for (int i = 0; i < 26; i++) d[aL[i]] = i;
var a = new int[26];
var b = new int[26];
var n = int.Parse(Console.ReadLine().Trim());
var s = Console.ReadLine().Trim();
var t = Console.ReadLine().Trim();
for (int i = 0; i < n; i++) { a[d[s[i]]]++; b[d[t[i]]]++; }
var a2 = a.Where(x => x >= 1).OrderByDescending(x => x).ToArray();
var b2 = b.Where(x => x >= 1).OrderByDescending(x => x).ToArray();
var imin = Math.Min(a2.Length, b2.Length);
for (int i = 0; i < imin; i++)
a2[i] = Math.Max(a2[i] - b2[i], 0);
Console.WriteLine(a2.Sum());
}
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
# define REP(i,n) for (int i=0;i<(n);++i)
# define PER(i,n) for (int i=(N-1);i>=0;--i)
# define rep(i,a,b) for(int i=a;i<(b);++i)
# define p(s) std::cout << s ;
# define pl(s) std::cout << s << endl;
# define printIf(j,s1,s2) cout << (j ? s1 : s2) << endl;
# define YES(j) cout << (j ? "YES" : "NO") << endl;
# define Yes(j) std::cout << (j ? "Yes" : "No") << endl;
# define yes(j) std::cout << (j ? "yes" : "no") << endl;
# define all(v) v.begin(),v.end()
# define showVector(v) REP(i,v.size()){p(v[i]);p(" ")} pl("")
template<class T> inline bool chmin(T &a, T b){ if(a > b) { a = b; return true;} return false;}
template<class T> inline bool chmax(T &a, T b){ if(a < b) { a = b; return true;} return false;}
typedef long long int ll;
typedef pair<ll,ll> P_ii;
typedef pair<double,double> P_dd;
template<class T>
vector<T> make_vec(size_t a){
return vector<T>(a);
}
template<class T, class... Ts>
auto make_vec(size_t a, Ts... ts){
return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}
template<typename T,typename V>
typename enable_if<is_class<T>::value==0>::type
fill_v(T &t,const V &v){t=v;}
template<typename T,typename V>
typename enable_if<is_class<T>::value!=0>::type
fill_v(T &t,const V &v){
for(auto &e:t) fill_v(e,v);
}
const int MOD = 1000000007;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
void addM(long long &a, long long b) {
a += b;
if (a >= MOD) a -= MOD;
}
void mulM(long long &a, long long b) {
a = ((a%MOD)*(b%MOD))%MOD ;
}
const int MAX = 510000;
long long fac[MAX], finv[MAX], inv[MAX];
// テーブルを作る前処理
void COMinit() {
fac[0] = fac[1] = 1;
finv[0] = finv[1] = 1;
inv[1] = 1;
for (int i = 2; i < MAX; 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;
}
}
// 二項係数計算
long long COM(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;
}
vector<pair<long long, long long> > prime_factorize(long long n) {
vector<pair<long long, long long> > res;
for (long long p = 2; p * p <= n; ++p) {
if (n % p != 0) continue;
int num = 0;
while (n % p == 0) { ++num; n /= p; }
res.push_back(make_pair(p, num));
}
if (n != 1) res.push_back(make_pair(n, 1));
return res;
}
int main() {
int N, K;
cin >> N >> K;
string s1, s2;
cin >> s1;
s2 = s1;
// Rにする
int cnt = 0;
for(int i = s1.find('R'); i < N; i++) {
if(s1[i] == 'R') continue;
int j = i;
while(s1[j] == 'L') {
s1[j] = 'R';
j++;
}
cnt++;
if(K == cnt) break;
}
ll ansR = 0;
if(K > cnt) {
ansR = N - 1;
} else {
for(int i = 0; i < N - 1; i++) {
if(s1[i] == s1[i + 1]) ansR++;
}
}
// Lにする
cnt = 0;
for(int i = s2.find('L'); i < N; i++) {
if(s2[i] == 'L') continue;
int j = i;
while(s2[j] == 'R') {
s2[j] = 'L';
j++;
}
cnt++;
if(K == cnt) break;
}
ll ansL = 0;
if(K > cnt) {
ansR = N - 1;
} else {
for(int i = 0; i < N - 1; i++) {
if(s2[i] == s2[i + 1]) ansL++;
}
}
cout << max(ansL, ansR) << endl;
return 0;
} | Python | a=int(input());
if a<1200:print("ABC");
elif a<2800:print("ARC");
else:print("AGC"); | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
# define REP(i,n) for (int i=0;i<(n);++i)
# define PER(i,n) for (int i=(N-1);i>=0;--i)
# define rep(i,a,b) for(int i=a;i<(b);++i)
# define p(s) std::cout << s ;
# define pl(s) std::cout << s << endl;
# define printIf(j,s1,s2) cout << (j ? s1 : s2) << endl;
# define YES(j) cout << (j ? "YES" : "NO") << endl;
# define Yes(j) std::cout << (j ? "Yes" : "No") << endl;
# define yes(j) std::cout << (j ? "yes" : "no") << endl;
# define all(v) v.begin(),v.end()
# define showVector(v) REP(i,v.size()){p(v[i]);p(" ")} pl("")
template<class T> inline bool chmin(T &a, T b){ if(a > b) { a = b; return true;} return false;}
template<class T> inline bool chmax(T &a, T b){ if(a < b) { a = b; return true;} return false;}
typedef long long int ll;
typedef pair<ll,ll> P_ii;
typedef pair<double,double> P_dd;
template<class T>
vector<T> make_vec(size_t a){
return vector<T>(a);
}
template<class T, class... Ts>
auto make_vec(size_t a, Ts... ts){
return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}
template<typename T,typename V>
typename enable_if<is_class<T>::value==0>::type
fill_v(T &t,const V &v){t=v;}
template<typename T,typename V>
typename enable_if<is_class<T>::value!=0>::type
fill_v(T &t,const V &v){
for(auto &e:t) fill_v(e,v);
}
const int MOD = 1000000007;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
void addM(long long &a, long long b) {
a += b;
if (a >= MOD) a -= MOD;
}
void mulM(long long &a, long long b) {
a = ((a%MOD)*(b%MOD))%MOD ;
}
const int MAX = 510000;
long long fac[MAX], finv[MAX], inv[MAX];
// テーブルを作る前処理
void COMinit() {
fac[0] = fac[1] = 1;
finv[0] = finv[1] = 1;
inv[1] = 1;
for (int i = 2; i < MAX; 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;
}
}
// 二項係数計算
long long COM(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;
}
vector<pair<long long, long long> > prime_factorize(long long n) {
vector<pair<long long, long long> > res;
for (long long p = 2; p * p <= n; ++p) {
if (n % p != 0) continue;
int num = 0;
while (n % p == 0) { ++num; n /= p; }
res.push_back(make_pair(p, num));
}
if (n != 1) res.push_back(make_pair(n, 1));
return res;
}
int main() {
int N, K;
cin >> N >> K;
string s1, s2;
cin >> s1;
s2 = s1;
// Rにする
int cnt = 0;
for(int i = s1.find('R'); i < N; i++) {
if(s1[i] == 'R') continue;
int j = i;
while(s1[j] == 'L') {
s1[j] = 'R';
j++;
}
cnt++;
if(K == cnt) break;
}
ll ansR = 0;
if(K > cnt) {
ansR = N - 1;
} else {
for(int i = 0; i < N - 1; i++) {
if(s1[i] == s1[i + 1]) ansR++;
}
}
// Lにする
cnt = 0;
for(int i = s2.find('L'); i < N; i++) {
if(s2[i] == 'L') continue;
int j = i;
while(s2[j] == 'R') {
s2[j] = 'L';
j++;
}
cnt++;
if(K == cnt) break;
}
ll ansL = 0;
if(K > cnt) {
ansR = N - 1;
} else {
for(int i = 0; i < N - 1; i++) {
if(s2[i] == s2[i + 1]) ansL++;
}
}
cout << max(ansL, ansR) << endl;
return 0;
}
Code 2: a=int(input());
if a<1200:print("ABC");
elif a<2800:print("ARC");
else:print("AGC"); |
Python | n,k = map(int,input().split())
cc = [1] * n
for _ in range(k):
d = input()
lis = list(map(int,input().split()))
for l in lis:
cc[l-1] = 0
print(sum(cc)) | C++ | // D.
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
using namespace std;
static const long long MOD = 1000000007;
int main(int argc, char *argv[]) {
int n;
cin >> n;
string s[2];
cin >> s[0] >> s[1];
int st = -1;
long long ans = 1;
for (int i = 0; i < n; ++i) {
if (s[0][i] == s[1][i]) {
switch (st) {
case 1:
ans *= 2;
break;
case 2:
break;
default:
ans = 3;
break;
}
st = 1;
} else {
switch (st) {
case 1:
ans *= 2;
break;
case 2:
ans *= 3;
break;
default:
ans = 6;
break;
}
st = 2;
++i;
}
ans %= MOD;
}
cout << ans << endl;
return 0;
}
| No | Do these codes solve the same problem?
Code 1: n,k = map(int,input().split())
cc = [1] * n
for _ in range(k):
d = input()
lis = list(map(int,input().split()))
for l in lis:
cc[l-1] = 0
print(sum(cc))
Code 2: // D.
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
using namespace std;
static const long long MOD = 1000000007;
int main(int argc, char *argv[]) {
int n;
cin >> n;
string s[2];
cin >> s[0] >> s[1];
int st = -1;
long long ans = 1;
for (int i = 0; i < n; ++i) {
if (s[0][i] == s[1][i]) {
switch (st) {
case 1:
ans *= 2;
break;
case 2:
break;
default:
ans = 3;
break;
}
st = 1;
} else {
switch (st) {
case 1:
ans *= 2;
break;
case 2:
ans *= 3;
break;
default:
ans = 6;
break;
}
st = 2;
++i;
}
ans %= MOD;
}
cout << ans << endl;
return 0;
}
|
C++ | #include <bits/stdc++.h>
#include <fstream>
#include <cstdio>
using namespace std;
// vector<pair<int,int> > v;
// cin.ignore();//twice getline(cin,s);
// g++ iterator.cpp -std=c++17
// cout<<(A + B == C ? "YES" : "NO")<<endl;
// __gcd(a,b)
// string s=to_string(n);
// string p=s.substr(0,len);
// string q=s.insert(0,str);
// sort(arr, arr+n, greater<int>());
// cout<<fixed<<setprecision(9)<<pi<<endl
// const double pi = acos(-1.0);
// sort(v.rbegin(),v.rend());
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define vll vector<ll>
#define mll map<ll,ll >
#define mlli map<ll,ll>::iterator
#define size size()
#define endl "\n"
#define ll long long int
#define ld long double
void fast(){ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);}
int main(void)
{
fast();
string s;
cin>>s;
/*
string p = ""; // Not efficient no use of extra var creation
for(int i=0;i<s.length();i++)
{
p = p+'x';
}
cout<<p<<endl;
*/
// Efficient manner
for(int i=0;i<s.size;i++)
{
s[i]='x';
}
cout<<s<<endl;
} | Python | import math
N = int(input())
print(math.floor(math.sqrt(N))**2) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#include <fstream>
#include <cstdio>
using namespace std;
// vector<pair<int,int> > v;
// cin.ignore();//twice getline(cin,s);
// g++ iterator.cpp -std=c++17
// cout<<(A + B == C ? "YES" : "NO")<<endl;
// __gcd(a,b)
// string s=to_string(n);
// string p=s.substr(0,len);
// string q=s.insert(0,str);
// sort(arr, arr+n, greater<int>());
// cout<<fixed<<setprecision(9)<<pi<<endl
// const double pi = acos(-1.0);
// sort(v.rbegin(),v.rend());
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define vll vector<ll>
#define mll map<ll,ll >
#define mlli map<ll,ll>::iterator
#define size size()
#define endl "\n"
#define ll long long int
#define ld long double
void fast(){ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);}
int main(void)
{
fast();
string s;
cin>>s;
/*
string p = ""; // Not efficient no use of extra var creation
for(int i=0;i<s.length();i++)
{
p = p+'x';
}
cout<<p<<endl;
*/
// Efficient manner
for(int i=0;i<s.size;i++)
{
s[i]='x';
}
cout<<s<<endl;
}
Code 2: import math
N = int(input())
print(math.floor(math.sqrt(N))**2) |
Python | # -*- coding: utf-8 -*-
x = int(input())
ans = 0
q, mod = divmod(x, 500)
ans += q*1000
q, mod = divmod(mod, 5)
ans += q*5
print(ans) | C++ | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n, ans = 0, a = 0, b = 0, cnt = 1;
cin>> n;
vector<int> p(n), q(n), order(n);
for(int i=0;i<n;i++){
cin>>p[i];
}
for(int i=0;i<n;i++){
cin>>q[i];
}
for(int i=0;i<n;i++){
order[i] = i+1;
}
do{
bool pflag = true, qflag = true;
for(int i=0;i<n;i++){
if(order[i]!=p[i]){
pflag = false;
break;
}
}
for(int i=0;i<n;i++){
if(order[i]!=q[i]){
qflag = false;
break;
}
}
if(pflag) a = cnt;
if(qflag) b = cnt;
cnt++;
}while(next_permutation(order.begin(), order.end()));
ans = abs(a-b);
cout<< ans <<endl;
}
| No | Do these codes solve the same problem?
Code 1: # -*- coding: utf-8 -*-
x = int(input())
ans = 0
q, mod = divmod(x, 500)
ans += q*1000
q, mod = divmod(mod, 5)
ans += q*5
print(ans)
Code 2: #include<bits/stdc++.h>
using namespace std;
int main()
{
int n, ans = 0, a = 0, b = 0, cnt = 1;
cin>> n;
vector<int> p(n), q(n), order(n);
for(int i=0;i<n;i++){
cin>>p[i];
}
for(int i=0;i<n;i++){
cin>>q[i];
}
for(int i=0;i<n;i++){
order[i] = i+1;
}
do{
bool pflag = true, qflag = true;
for(int i=0;i<n;i++){
if(order[i]!=p[i]){
pflag = false;
break;
}
}
for(int i=0;i<n;i++){
if(order[i]!=q[i]){
qflag = false;
break;
}
}
if(pflag) a = cnt;
if(qflag) b = cnt;
cnt++;
}while(next_permutation(order.begin(), order.end()));
ans = abs(a-b);
cout<< ans <<endl;
}
|
Python | H, W = map(int, input().split())
ans = H * W // 2
if H == 1 or W == 1:
ans = 1
elif (H & 1) and (W & 1):
ans += 1
print(ans)
| C++ | #include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
using namespace std;
int main(){
int n,m,i;
int ansac=0,ansp=0;
cin>>n>>m;
vector<int>ac(n);
vector<int>penalty(n);
rep(i,m){
int p;
string s;
cin>>p>>s;
p--;
if(ac[p])
continue;
if(s=="AC")
ac[p]=1;
else{
penalty[p]++;
}
}
rep(i,n){
ansac+=ac[i];
if(ac[i])
ansp+=penalty[i];
}
cout<<ansac<<" "<<ansp<<endl;
}
| No | Do these codes solve the same problem?
Code 1: H, W = map(int, input().split())
ans = H * W // 2
if H == 1 or W == 1:
ans = 1
elif (H & 1) and (W & 1):
ans += 1
print(ans)
Code 2: #include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
using namespace std;
int main(){
int n,m,i;
int ansac=0,ansp=0;
cin>>n>>m;
vector<int>ac(n);
vector<int>penalty(n);
rep(i,m){
int p;
string s;
cin>>p>>s;
p--;
if(ac[p])
continue;
if(s=="AC")
ac[p]=1;
else{
penalty[p]++;
}
}
rep(i,n){
ansac+=ac[i];
if(ac[i])
ansp+=penalty[i];
}
cout<<ansac<<" "<<ansp<<endl;
}
|
C++ | #include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <string>
#include <stack> // s.top()
#include <bitset>
#include <queue> // s.front()
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
#define print(x) cout<<(x)<<endl
#define INF10 1001001001
#define INF5 100000
#define EPS 1e-10
int main() {
int N;
cin >> N;
vector<int> p(N);
for (int i = 0; i < N; i++) {
cin >> p[i];
}
vector<int> ans(p.begin(), p.end());
sort(ans.begin(), ans.end());
int in_f = 1;
for (int i = 0; i < N; i++) {
if (ans[i] != p[i]) {
in_f = 0;
break;
}
}
if (in_f) {
print("YES");
return 0;
}
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
int tmp = p[i];
p[i] = p[j];
p[j] = tmp;
int flag = 1;
for (int k = 0; k < N; k++) {
if (ans[k] != p[k]) {
flag = 0;
break;
}
}
if (flag) {
print("YES");
return 0;
}
tmp = p[i];
p[i] = p[j];
p[j] = tmp;
}
}
print("NO");
return 0;
}
| Python | h,w=map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
lst=[]
for i in range(1,n+1):
for j in range(a[i-1]):
lst.append(str(i))
lst.reverse()
ans=[[0]*w for i in range(h)]
for i in range(h):
if i%2==0:
for j in range(w):
ans[i][j]=lst.pop()
else:
for j in range(w-1,-1,-1):
ans[i][j]=lst.pop()
for i in ans:
print(' '.join(i))
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <string>
#include <stack> // s.top()
#include <bitset>
#include <queue> // s.front()
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
#define print(x) cout<<(x)<<endl
#define INF10 1001001001
#define INF5 100000
#define EPS 1e-10
int main() {
int N;
cin >> N;
vector<int> p(N);
for (int i = 0; i < N; i++) {
cin >> p[i];
}
vector<int> ans(p.begin(), p.end());
sort(ans.begin(), ans.end());
int in_f = 1;
for (int i = 0; i < N; i++) {
if (ans[i] != p[i]) {
in_f = 0;
break;
}
}
if (in_f) {
print("YES");
return 0;
}
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
int tmp = p[i];
p[i] = p[j];
p[j] = tmp;
int flag = 1;
for (int k = 0; k < N; k++) {
if (ans[k] != p[k]) {
flag = 0;
break;
}
}
if (flag) {
print("YES");
return 0;
}
tmp = p[i];
p[i] = p[j];
p[j] = tmp;
}
}
print("NO");
return 0;
}
Code 2: h,w=map(int,input().split())
n=int(input())
a=list(map(int,input().split()))
lst=[]
for i in range(1,n+1):
for j in range(a[i-1]):
lst.append(str(i))
lst.reverse()
ans=[[0]*w for i in range(h)]
for i in range(h):
if i%2==0:
for j in range(w):
ans[i][j]=lst.pop()
else:
for j in range(w-1,-1,-1):
ans[i][j]=lst.pop()
for i in ans:
print(' '.join(i))
|
C | #include<stdio.h>
int J, Y;
char pass[64];
void parse(int pos, int j, int y){
if ( j == J && y == Y ){
pass[pos] = '\0';
printf("%s\n", pass); return;
} else if ( j == 5 && y <= 3 || y == 5 && j <= 3){
return;
}
if ( j > J || y > Y ) return;
pass[pos] = 'A';
parse(pos+1, j+1, y);
pass[pos] = 'B';
parse(pos+1, j, y+1);
}
int main(){
scanf("%d %d", &J, &Y);
parse(0, 0, 0);
return 0;
}
| Java | import java.util.*;
public class Main{
Scanner sc = new Scanner(System.in);
public Main(){
int j = sc.nextInt();
int y = sc.nextInt();
parse(0, 0, j, y, "");
}
void parse(int a, int b, int j, int y, String p){
if ( a == j && b == y ){
System.out.println(p);
return;
}
if ( a >= 5 && b <= 3 ) return;
if ( b >= 5 && a <= 3 ) return;
if ( a+1 <= j && b <= y ) parse(a+1, b, j, y, p+"A");
if ( a <= j && b+1 <= y ) parse(a, b+1, j, y, p+"B");
}
public static void main(String[] a){ new Main(); }
}
| Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
int J, Y;
char pass[64];
void parse(int pos, int j, int y){
if ( j == J && y == Y ){
pass[pos] = '\0';
printf("%s\n", pass); return;
} else if ( j == 5 && y <= 3 || y == 5 && j <= 3){
return;
}
if ( j > J || y > Y ) return;
pass[pos] = 'A';
parse(pos+1, j+1, y);
pass[pos] = 'B';
parse(pos+1, j, y+1);
}
int main(){
scanf("%d %d", &J, &Y);
parse(0, 0, 0);
return 0;
}
Code 2: import java.util.*;
public class Main{
Scanner sc = new Scanner(System.in);
public Main(){
int j = sc.nextInt();
int y = sc.nextInt();
parse(0, 0, j, y, "");
}
void parse(int a, int b, int j, int y, String p){
if ( a == j && b == y ){
System.out.println(p);
return;
}
if ( a >= 5 && b <= 3 ) return;
if ( b >= 5 && a <= 3 ) return;
if ( a+1 <= j && b <= y ) parse(a+1, b, j, y, p+"A");
if ( a <= j && b+1 <= y ) parse(a, b+1, j, y, p+"B");
}
public static void main(String[] a){ new Main(); }
}
|
Java | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov ([email protected])
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
AColorfulSubsequence solver = new AColorfulSubsequence();
solver.solve(1, in, out);
out.close();
}
static class AColorfulSubsequence {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
char[] s = in.readCharArray(n);
int[] qty = new int[26];
for (char c : s) {
qty[c - 'a']++;
}
long answer = 1;
for (int i = 0; i < 26; i++) {
answer *= qty[i] + 1;
answer %= MiscUtils.MOD7;
}
answer--;
out.printLine(answer);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class MiscUtils {
public static final int MOD7 = (int) (1e9 + 7);
}
}
| Go | package main
import (
"fmt"
)
const mod = 1000000007
func main() {
scanInt()
letter_count := make(map[byte]int)
S := scanString()
for i := 0; i < len(S); i++ {
letter_count[S[i]]++
}
result := 1
for _, count := range letter_count {
result *= (count + 1)
result %= mod
}
result += 1000000006
result %= mod
fmt.Println(result)
}
func scanInt() (num int) {
fmt.Scan(&num)
return
}
func scanInts(len int) (nums []int) {
var num int
for i := 0; i < len; i++ {
fmt.Scan(&num)
nums = append(nums, num)
}
return
}
func scanString() (str string) {
fmt.Scan(&str)
return
}
func scanStrings(len int) (strs []string) {
var str string
for i := 0; i < len; i++ {
fmt.Scan(&str)
strs = append(strs, str)
}
return
} | Yes | Do these codes solve the same problem?
Code 1: import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov ([email protected])
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
AColorfulSubsequence solver = new AColorfulSubsequence();
solver.solve(1, in, out);
out.close();
}
static class AColorfulSubsequence {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
char[] s = in.readCharArray(n);
int[] qty = new int[26];
for (char c : s) {
qty[c - 'a']++;
}
long answer = 1;
for (int i = 0; i < 26; i++) {
answer *= qty[i] + 1;
answer %= MiscUtils.MOD7;
}
answer--;
out.printLine(answer);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class MiscUtils {
public static final int MOD7 = (int) (1e9 + 7);
}
}
Code 2: package main
import (
"fmt"
)
const mod = 1000000007
func main() {
scanInt()
letter_count := make(map[byte]int)
S := scanString()
for i := 0; i < len(S); i++ {
letter_count[S[i]]++
}
result := 1
for _, count := range letter_count {
result *= (count + 1)
result %= mod
}
result += 1000000006
result %= mod
fmt.Println(result)
}
func scanInt() (num int) {
fmt.Scan(&num)
return
}
func scanInts(len int) (nums []int) {
var num int
for i := 0; i < len; i++ {
fmt.Scan(&num)
nums = append(nums, num)
}
return
}
func scanString() (str string) {
fmt.Scan(&str)
return
}
func scanStrings(len int) (strs []string) {
var str string
for i := 0; i < len; i++ {
fmt.Scan(&str)
strs = append(strs, str)
}
return
} |
C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Math;
public static class P
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
var s = Console.ReadLine();
var rCount = (long)s.Count(x => x == 'R');
var gCount = (long)s.Count(x => x == 'G');
var bCount = (long)s.Count(x => x == 'B');
var res = rCount * gCount * bCount;
for (int i = 1; i < s.Length - 1; i++)
{
for (int j = i - 1, k = i + 1; 0 <= j && k < s.Length; j--, k++)
{
if (s[i] != s[j] && s[i] != s[k] && s[j] != s[k]) res--;
}
}
Console.WriteLine(res);
}
static long GCD(long a, long b)
{
while (true)
{
if (b == 0) return a;
a %= b;
if (a == 0) return b;
b %= a;
}
}
} | Go | package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
)
const INFINITY = math.MaxInt64/2 - 1
func exec(stdin *Stdin, stdout *Stdout) {
n := stdin.ReadInt()
s := stdin.Read()
a := []int{0, 0, 0}
for i := 0; i < n; i++ {
if s[i] == 'R' {
a[0]++
} else if s[i] == 'G' {
a[1]++
} else {
a[2]++
}
}
ans := a[0] * a[1] * a[2]
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
k := j + (j - i)
if k < n && s[i] != s[j] && s[i] != s[k] && s[j] != s[k] {
ans--
}
}
}
stdout.Println(ans)
}
func main() {
stdout := NewStdout()
defer stdout.Flush()
exec(NewStdin(bufio.ScanWords), stdout)
}
type Stdin struct {
stdin *bufio.Scanner
}
func NewStdin(split bufio.SplitFunc) *Stdin {
s := Stdin{bufio.NewScanner(os.Stdin)}
s.stdin.Split(split)
s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
return &s
}
func (s *Stdin) Read() string {
s.stdin.Scan()
return s.stdin.Text()
}
func (s *Stdin) ReadInt() int {
n, _ := strconv.Atoi(s.Read())
return n
}
func (s *Stdin) ReadFloat64() float64 {
n, _ := strconv.ParseFloat(s.Read(), 64)
return n
}
type Stdout struct {
stdout *bufio.Writer
}
func NewStdout() *Stdout {
return &Stdout{bufio.NewWriter(os.Stdout)}
}
func (s *Stdout) Flush() {
s.stdout.Flush()
}
func (s *Stdout) Println(a ...interface{}) {
fmt.Fprintln(s.stdout, a...)
}
func Min(a int, b ...int) int {
for _, v := range b {
if v < a {
a = v
}
}
return a
}
func Max(a int, b ...int) int {
for _, v := range b {
if a < v {
a = v
}
}
return a
}
func Abs(x int) int {
if x > 0 {
return x
} else {
return x * -1
}
}
func Pow(x, y int) int {
z := 1
for y > 0 {
if y%2 == 0 {
x *= x
y /= 2
} else {
z *= x
y -= 1
}
}
return z
}
func CreateMatrix(x, y int) [][]int {
matrix := make([][]int, x)
for i := 0; i < x; i++ {
matrix[i] = make([]int, y)
}
return matrix
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Math;
public static class P
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
var s = Console.ReadLine();
var rCount = (long)s.Count(x => x == 'R');
var gCount = (long)s.Count(x => x == 'G');
var bCount = (long)s.Count(x => x == 'B');
var res = rCount * gCount * bCount;
for (int i = 1; i < s.Length - 1; i++)
{
for (int j = i - 1, k = i + 1; 0 <= j && k < s.Length; j--, k++)
{
if (s[i] != s[j] && s[i] != s[k] && s[j] != s[k]) res--;
}
}
Console.WriteLine(res);
}
static long GCD(long a, long b)
{
while (true)
{
if (b == 0) return a;
a %= b;
if (a == 0) return b;
b %= a;
}
}
}
Code 2: package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
)
const INFINITY = math.MaxInt64/2 - 1
func exec(stdin *Stdin, stdout *Stdout) {
n := stdin.ReadInt()
s := stdin.Read()
a := []int{0, 0, 0}
for i := 0; i < n; i++ {
if s[i] == 'R' {
a[0]++
} else if s[i] == 'G' {
a[1]++
} else {
a[2]++
}
}
ans := a[0] * a[1] * a[2]
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
k := j + (j - i)
if k < n && s[i] != s[j] && s[i] != s[k] && s[j] != s[k] {
ans--
}
}
}
stdout.Println(ans)
}
func main() {
stdout := NewStdout()
defer stdout.Flush()
exec(NewStdin(bufio.ScanWords), stdout)
}
type Stdin struct {
stdin *bufio.Scanner
}
func NewStdin(split bufio.SplitFunc) *Stdin {
s := Stdin{bufio.NewScanner(os.Stdin)}
s.stdin.Split(split)
s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
return &s
}
func (s *Stdin) Read() string {
s.stdin.Scan()
return s.stdin.Text()
}
func (s *Stdin) ReadInt() int {
n, _ := strconv.Atoi(s.Read())
return n
}
func (s *Stdin) ReadFloat64() float64 {
n, _ := strconv.ParseFloat(s.Read(), 64)
return n
}
type Stdout struct {
stdout *bufio.Writer
}
func NewStdout() *Stdout {
return &Stdout{bufio.NewWriter(os.Stdout)}
}
func (s *Stdout) Flush() {
s.stdout.Flush()
}
func (s *Stdout) Println(a ...interface{}) {
fmt.Fprintln(s.stdout, a...)
}
func Min(a int, b ...int) int {
for _, v := range b {
if v < a {
a = v
}
}
return a
}
func Max(a int, b ...int) int {
for _, v := range b {
if a < v {
a = v
}
}
return a
}
func Abs(x int) int {
if x > 0 {
return x
} else {
return x * -1
}
}
func Pow(x, y int) int {
z := 1
for y > 0 {
if y%2 == 0 {
x *= x
y /= 2
} else {
z *= x
y -= 1
}
}
return z
}
func CreateMatrix(x, y int) [][]int {
matrix := make([][]int, x)
for i := 0; i < x; i++ {
matrix[i] = make([]int, y)
}
return matrix
}
|
Python | n = int(input())
b = list(map(int, input().split()))
rev_b = b[::-1]
rev_a = [None for _ in range(n)]
rev_a[0] = rev_b[0]
for i in range(1, n-1):
rev_a[i] = min([rev_b[i], rev_b[i-1]])
rev_a[n-1] = rev_b[n-2]
print(sum(rev_a)) | C++ | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll dp[100005][13];
int main() {
string s;
cin >> s;
s = ' ' + s;
dp[0][0] = 1;
for (int i = 1; i < s.length(); i++) {
if (s[i] == '?') {
for (int j = 0; j < 13; j++)
for (int k = 0; k <= 9; k++) {
dp[i][(10 * j + k) % 13] += dp[i - 1][j];
}
} else {
for (int j = 0; j < 13; j++)
dp[i][(10 * j + s[i] - '0') % 13] += dp[i - 1][j];
}
for (int j = 0; j < 13; j++)
dp[i][j] %= 1000000007;
}
cout << dp[s.length() - 1][5] << endl;
} | No | Do these codes solve the same problem?
Code 1: n = int(input())
b = list(map(int, input().split()))
rev_b = b[::-1]
rev_a = [None for _ in range(n)]
rev_a[0] = rev_b[0]
for i in range(1, n-1):
rev_a[i] = min([rev_b[i], rev_b[i-1]])
rev_a[n-1] = rev_b[n-2]
print(sum(rev_a))
Code 2: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll dp[100005][13];
int main() {
string s;
cin >> s;
s = ' ' + s;
dp[0][0] = 1;
for (int i = 1; i < s.length(); i++) {
if (s[i] == '?') {
for (int j = 0; j < 13; j++)
for (int k = 0; k <= 9; k++) {
dp[i][(10 * j + k) % 13] += dp[i - 1][j];
}
} else {
for (int j = 0; j < 13; j++)
dp[i][(10 * j + s[i] - '0') % 13] += dp[i - 1][j];
}
for (int j = 0; j < 13; j++)
dp[i][j] %= 1000000007;
}
cout << dp[s.length() - 1][5] << endl;
} |
C++ | #include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <utility>
#include <algorithm>
#include <numeric>
#include <functional>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
//const long double PIL = 3.141592653589793238462643383279502884L;
//const double PI = 3.14159265358979323846;
typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<pair<int,int>> vii;
#define sz(a) int((a).size())
#define all(c) (c).begin(), (c).end()
const int N = 301;
int n;
double dp[N][N][N];
double dfs(int a, int b, int c) {
if (dp[a][b][c] >= 0.5) return dp[a][b][c];
int m = a + b + c;
double ks = (double)n / m;
double ret = 0;
if (a) ret += (dfs(a-1, b, c) + ks) * a / m;
if (b) ret += (dfs(a+1, b-1, c) + ks) * b / m;
if (c) ret += (dfs(a, b+1, c-1) + ks) * c / m;
return dp[a][b][c] = ret;
}
int main() {
//~ ios::sync_with_stdio(0);
//~ cin.tie(0);
scanf("%d", &n);
vi cnt(4);
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
cnt[x]++;
}
for (int a = 0; a <= n; a++)
for (int b = 0; b <= n; b++)
for (int c = 0; c <= n; c++) dp[a][b][c] = -1;
dp[0][0][0] = 0;
printf("%.10f\n", dfs(cnt[1], cnt[2], cnt[3]));
}
| Python | n = int(input())
print(sum(filter(lambda x : x % 3 != 0 and x % 5 != 0, range(1, n+1)))) | No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <utility>
#include <algorithm>
#include <numeric>
#include <functional>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
//const long double PIL = 3.141592653589793238462643383279502884L;
//const double PI = 3.14159265358979323846;
typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<pair<int,int>> vii;
#define sz(a) int((a).size())
#define all(c) (c).begin(), (c).end()
const int N = 301;
int n;
double dp[N][N][N];
double dfs(int a, int b, int c) {
if (dp[a][b][c] >= 0.5) return dp[a][b][c];
int m = a + b + c;
double ks = (double)n / m;
double ret = 0;
if (a) ret += (dfs(a-1, b, c) + ks) * a / m;
if (b) ret += (dfs(a+1, b-1, c) + ks) * b / m;
if (c) ret += (dfs(a, b+1, c-1) + ks) * c / m;
return dp[a][b][c] = ret;
}
int main() {
//~ ios::sync_with_stdio(0);
//~ cin.tie(0);
scanf("%d", &n);
vi cnt(4);
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
cnt[x]++;
}
for (int a = 0; a <= n; a++)
for (int b = 0; b <= n; b++)
for (int c = 0; c <= n; c++) dp[a][b][c] = -1;
dp[0][0][0] = 0;
printf("%.10f\n", dfs(cnt[1], cnt[2], cnt[3]));
}
Code 2: n = int(input())
print(sum(filter(lambda x : x % 3 != 0 and x % 5 != 0, range(1, n+1)))) |
C++ | #include <bits/stdc++.h>
#define fo(i, a, b) for (int i = a; i < b; i++)
#define re(i, n) fo(i, 0, n)
using namespace std;
typedef long long ll;
int main()
{
int n;
cin >> n;
vector<int> h(n);
re(i, n) cin >> h[i];
int c = 1;
int max = h[0];
fo(i, 1, n) {
if (max <= h[i]) {
c++;
max = h[i];
}
}
cout << c << endl;
return 0;
}
| Python | S=input()
contest=["ABC","ARC"]
if S==contest[0]:
print(contest[1])
else:
print(contest[0]) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#define fo(i, a, b) for (int i = a; i < b; i++)
#define re(i, n) fo(i, 0, n)
using namespace std;
typedef long long ll;
int main()
{
int n;
cin >> n;
vector<int> h(n);
re(i, n) cin >> h[i];
int c = 1;
int max = h[0];
fo(i, 1, n) {
if (max <= h[i]) {
c++;
max = h[i];
}
}
cout << c << endl;
return 0;
}
Code 2: S=input()
contest=["ABC","ARC"]
if S==contest[0]:
print(contest[1])
else:
print(contest[0]) |
Python | # -*- coding: utf-8 -*-
import sys
import itertools#これは色々使える組み込み関数みたいなやつ
#import math#数学的計算はこれでいける。普通に0.5乗しても計算可能
#w=input()
from operator import itemgetter
from sys import stdin
#input = sys.stdin.readline#こっちの方が入力が早いが使える時に使っていこう
from math import factorial
N=3
M=3
i=0
j=0
k=0
number_list=list(map(int, input().split(" ")))
N=number_list[0]
M=number_list[1]
#print(N,M)
if N >=2:
i=factorial(N) / factorial(2) /factorial(N-2)
else:
i=0
if M>=2:
j=factorial(M) / factorial(2) /factorial(M-2)
else:
j=0
print(int(i+j))
#N=int(input())
#A=int(input())
#B=int(input())
#print(N)
"1行1つの整数を入力を取得し、整数と取得する"
#number_list=list(map(int, input().split(" ")))#数字の時
#print(number_list)
"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#メモ
for i in number_list:#こっちの方がrage使うより早いらしい
print(number_list[i-1])
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''
x=[]
y=[]
for i in range(N):
x1, y1=[int(i) for i in input().split()]
x.append(x1)
y.append(y1)
print(x)
print(y)
"複数行に2数値を入力する形式 x座標とy座標を入力するイメージ"
'''
'''
mixlist=[]
for i in range(N):
a,b=input().split()
mixlist.append((int(a),b))
print(mixlist)
"複数行にintとstrを複合して入力するやつ,今回はリスト一つで処理している"
'''
'''
#array=[input().split()for i in range(N)]
#print(type(array[0][0]))
#print(array)
"正方行列にstr型の値を入力"
'''
#brray=[list(map(int, input().split(" ")))for i in range(N)]
#print(type(brray[0][0]))
#print(brray)
'''
入力
1 2
4 5
7 8
出力結果
[[1, 2], [4, 5], [7, 8]]
'''
"列数に関して自由度の高いint型の値を入力するタイプの行列"
#以下に別解を記載
#N, M = [int(i) for i in input().split()]
'''
table = [[int(i) for i in input().split()] for m in range(m)]
print(type(N))
print(N)
print(type(M))
print(M)
print(type(table))
print(table)
'''
#s=input()
#a=[int(i) for i in s]
#print(a[0])
#print([a])
#単数値.桁ごとに分割したい.入力と出力は以下の通り
#イメージとして1桁ごとにリストに値を入れているかんじ
'''
入力
1234
出力
1
[[1, 2, 3, 4]]
'''
'''
word_list= input().split(" ")
print(word_list[0])
"連続文字列の入力"
"qw er ty とかの入力に使う"
"入力すると空白で区切ったところでlistの番号が与えられる"
'''
'''
A, B, C=stdin.readline().rstrip().split()#何個でもいけることが多い
print(A)
"リストではなく独立したstr型を入れるなら以下のやり方でOK"
'''
#a= stdin.readline().rstrip()
#print(a.upper())
"aという変数に入っているものを大文字にして出力"
#なんかうまく入力されるけど
#a=[[int(i) for i in 1.strip()]for 1 in sys.stdin]
#a = [[int(c) for c in l.strip()] for l in sys.stdin]]
#print(a)
#複数行の数値を入力して正方行列を作成
| C++ | #include <bits/stdc++.h>
using namespace std;
#define forsn(i, s, n) for(int i=s;i<int(n);i++)
#define forn(i, n) forsn(i, 0, n)
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
typedef long long tint;
const int INF = 1e6;
const long double PI = acos(-1);
int main() {
int a, b, x; cin >> a >> b >> x;
if(a > x) cout << "NO" << endl;
else if(a+b >= x) cout << "YES" << endl;
else cout << "NO" << endl;
}
| No | Do these codes solve the same problem?
Code 1: # -*- coding: utf-8 -*-
import sys
import itertools#これは色々使える組み込み関数みたいなやつ
#import math#数学的計算はこれでいける。普通に0.5乗しても計算可能
#w=input()
from operator import itemgetter
from sys import stdin
#input = sys.stdin.readline#こっちの方が入力が早いが使える時に使っていこう
from math import factorial
N=3
M=3
i=0
j=0
k=0
number_list=list(map(int, input().split(" ")))
N=number_list[0]
M=number_list[1]
#print(N,M)
if N >=2:
i=factorial(N) / factorial(2) /factorial(N-2)
else:
i=0
if M>=2:
j=factorial(M) / factorial(2) /factorial(M-2)
else:
j=0
print(int(i+j))
#N=int(input())
#A=int(input())
#B=int(input())
#print(N)
"1行1つの整数を入力を取得し、整数と取得する"
#number_list=list(map(int, input().split(" ")))#数字の時
#print(number_list)
"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#メモ
for i in number_list:#こっちの方がrage使うより早いらしい
print(number_list[i-1])
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''
x=[]
y=[]
for i in range(N):
x1, y1=[int(i) for i in input().split()]
x.append(x1)
y.append(y1)
print(x)
print(y)
"複数行に2数値を入力する形式 x座標とy座標を入力するイメージ"
'''
'''
mixlist=[]
for i in range(N):
a,b=input().split()
mixlist.append((int(a),b))
print(mixlist)
"複数行にintとstrを複合して入力するやつ,今回はリスト一つで処理している"
'''
'''
#array=[input().split()for i in range(N)]
#print(type(array[0][0]))
#print(array)
"正方行列にstr型の値を入力"
'''
#brray=[list(map(int, input().split(" ")))for i in range(N)]
#print(type(brray[0][0]))
#print(brray)
'''
入力
1 2
4 5
7 8
出力結果
[[1, 2], [4, 5], [7, 8]]
'''
"列数に関して自由度の高いint型の値を入力するタイプの行列"
#以下に別解を記載
#N, M = [int(i) for i in input().split()]
'''
table = [[int(i) for i in input().split()] for m in range(m)]
print(type(N))
print(N)
print(type(M))
print(M)
print(type(table))
print(table)
'''
#s=input()
#a=[int(i) for i in s]
#print(a[0])
#print([a])
#単数値.桁ごとに分割したい.入力と出力は以下の通り
#イメージとして1桁ごとにリストに値を入れているかんじ
'''
入力
1234
出力
1
[[1, 2, 3, 4]]
'''
'''
word_list= input().split(" ")
print(word_list[0])
"連続文字列の入力"
"qw er ty とかの入力に使う"
"入力すると空白で区切ったところでlistの番号が与えられる"
'''
'''
A, B, C=stdin.readline().rstrip().split()#何個でもいけることが多い
print(A)
"リストではなく独立したstr型を入れるなら以下のやり方でOK"
'''
#a= stdin.readline().rstrip()
#print(a.upper())
"aという変数に入っているものを大文字にして出力"
#なんかうまく入力されるけど
#a=[[int(i) for i in 1.strip()]for 1 in sys.stdin]
#a = [[int(c) for c in l.strip()] for l in sys.stdin]]
#print(a)
#複数行の数値を入力して正方行列を作成
Code 2: #include <bits/stdc++.h>
using namespace std;
#define forsn(i, s, n) for(int i=s;i<int(n);i++)
#define forn(i, n) forsn(i, 0, n)
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
typedef long long tint;
const int INF = 1e6;
const long double PI = acos(-1);
int main() {
int a, b, x; cin >> a >> b >> x;
if(a > x) cout << "NO" << endl;
else if(a+b >= x) cout << "YES" << endl;
else cout << "NO" << endl;
}
|
Kotlin | fun main(args: Array<String>) {
val s = readLine()!!
if (s <= "2019/04/30") {
println("Heisei")
} else {
println("TBD")
}
} | Go | package main
import (
"fmt"
)
func main() {
var y, m, d int
fmt.Scanf("%d/%d/%d\n", &y, &m, &d)
if y < 2019 {
fmt.Println("Heisei")
return
}
if 2019 < y {
fmt.Println("TBD")
return
}
if m <= 4 {
fmt.Println("Heisei")
return
}
fmt.Println("TBD")
} | Yes | Do these codes solve the same problem?
Code 1: fun main(args: Array<String>) {
val s = readLine()!!
if (s <= "2019/04/30") {
println("Heisei")
} else {
println("TBD")
}
}
Code 2: package main
import (
"fmt"
)
func main() {
var y, m, d int
fmt.Scanf("%d/%d/%d\n", &y, &m, &d)
if y < 2019 {
fmt.Println("Heisei")
return
}
if 2019 < y {
fmt.Println("TBD")
return
}
if m <= 4 {
fmt.Println("Heisei")
return
}
fmt.Println("TBD")
} |
JavaScript | function main(input) {
const strList = input.split("\n").filter(v => v != "");
strList.pop();
const ans = strList
.map(str => {
return sumChar(str);
})
.join("\n");
console.log(ans);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
function sumChar(str) {
const chars = str.split("");
const sum = chars.reduce((memo, value) => {
memo += Number(value);
return memo;
}, 0);
return sum;
}
| Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
var sc = bufio.NewScanner(os.Stdin)
func main() {
var a []string
for sc.Scan() {
b := sc.Text()
if "0" == b {
break
}
a = append(a, b)
}
for _, v := range a {
c := 0
for _, v2 := range v {
d, _ := strconv.Atoi(string(v2))
c += d
}
fmt.Println(c)
}
}
| Yes | Do these codes solve the same problem?
Code 1: function main(input) {
const strList = input.split("\n").filter(v => v != "");
strList.pop();
const ans = strList
.map(str => {
return sumChar(str);
})
.join("\n");
console.log(ans);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
function sumChar(str) {
const chars = str.split("");
const sum = chars.reduce((memo, value) => {
memo += Number(value);
return memo;
}, 0);
return sum;
}
Code 2: package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
var sc = bufio.NewScanner(os.Stdin)
func main() {
var a []string
for sc.Scan() {
b := sc.Text()
if "0" == b {
break
}
a = append(a, b)
}
for _, v := range a {
c := 0
for _, v2 := range v {
d, _ := strconv.Atoi(string(v2))
c += d
}
fmt.Println(c)
}
}
|
Python | n = int(input())
a = list(map(int, input().split()))
x = 0
for a_i in a:
x ^= a_i
for a_i in a:
print(x ^ a_i) | C++ | #include <bits/stdc++.h>
using namespace std;
using ll =long long;
#define SORT(a) sort((a).begin(),(a).end())
#define rSORT(a) reverse((a).begin(),(a).end())
#define For(i, a, b) for(int i = (a) ; i < (b) ; ++i)
#define rep(i, n) For(i, 0, n)
#define debug(x) cout << #x << " = " << (x) << endl;
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
bool coY() {cout <<"Yes"<<endl;}
bool coN(){cout <<"No"<<endl;}
const ll INF = 1LL << 60;
string s;
//Write From this Line
ll n,ans=0;
void dfs(ll x,ll a,ll b,ll c){
if(x>n) return;
if(a&&b&&c) ans++;
dfs(x*10+3,1,b,c);
dfs(x*10+5,a,1,c);
dfs(x*10+7,a,b,1);
}
const int mod = 1e9+7;
int main()
{
cin >> n;
dfs(0,0,0,0);
cout <<ans << endl;
}
| No | Do these codes solve the same problem?
Code 1: n = int(input())
a = list(map(int, input().split()))
x = 0
for a_i in a:
x ^= a_i
for a_i in a:
print(x ^ a_i)
Code 2: #include <bits/stdc++.h>
using namespace std;
using ll =long long;
#define SORT(a) sort((a).begin(),(a).end())
#define rSORT(a) reverse((a).begin(),(a).end())
#define For(i, a, b) for(int i = (a) ; i < (b) ; ++i)
#define rep(i, n) For(i, 0, n)
#define debug(x) cout << #x << " = " << (x) << endl;
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
bool coY() {cout <<"Yes"<<endl;}
bool coN(){cout <<"No"<<endl;}
const ll INF = 1LL << 60;
string s;
//Write From this Line
ll n,ans=0;
void dfs(ll x,ll a,ll b,ll c){
if(x>n) return;
if(a&&b&&c) ans++;
dfs(x*10+3,1,b,c);
dfs(x*10+5,a,1,c);
dfs(x*10+7,a,b,1);
}
const int mod = 1e9+7;
int main()
{
cin >> n;
dfs(0,0,0,0);
cout <<ans << endl;
}
|
C++ | #include <bits/stdc++.h>
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define int long long
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 0x3f3f3f3f;
const int N = 2e6+10;
struct node {
int l,r,mid,ma;
} tree[N];
int a[N],ans[N];
vector<int>e[N];
int n;
void pp(int x) {
tree[x].ma=max(tree[ls].ma,tree[rs].ma);
}
void build(int x,int l,int r) {
tree[x]= {l,r,(l+r)/2,0};
if(l==r) {
return ;
}
int mid=tree[x].mid;
build(ls,l,mid);
build(rs,mid+1,r);
}
void modify(int x,int pos,int k) {
if(tree[x].l==pos && tree[x].r==pos) {
tree[x].ma=k;
return ;
}
int mid=tree[x].mid;
if(pos<=mid) modify(ls,pos,k);
if(pos>mid) modify(rs,pos,k);
pp(x);
}
int query(int x,int l,int r) {
if(l<=tree[x].l&&tree[x].r<=r) {
return tree[x].ma;
}
int mid=tree[x].mid;
int res=0;
if(l<=mid) res=max(res,query(ls,l,r));
if(r>mid) res=max(res,query(rs,l,r));
return res;
}
void dfs(int u,int fa) {
int now=a[u];
int sum=query(1,1,now-1)+1;
int pre=query(1,now,now);
modify(1,now,max(sum,pre));
ans[u]=query(1,1,n+5);
for(auto v:e[u]) {
if(v==fa) continue;
dfs(v,u);
}
modify(1,now,pre);
}
signed main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
read(n);
vector<int>b;
for(int i=1; i<=n; i++) {
read(a[i]);
b.pb(a[i]);
}
sort(all(b));
b.erase(unique(all(b)),b.end());
for(int i=1; i<=n; i++) a[i]=lower_bound(all(b),a[i])-b.begin()+2;
for(int i=1; i<n; i++) {
int u,v;
read(u,v);
e[u].pb(v);
e[v].pb(u);
}
build(1,1,n+5);
dfs(1,1);
for(int i=1; i<=n; i++) cout<<ans[i]<<"\n";
return 0;
}
| Python | import math
n, x = list(map(int, input().split())) # 整数
array = list(map(int, input().strip().split()))
array.sort()
ans = 0
l = len(array)
for i in array:
l -= 1
x = x-i
if l == 0:
if x != 0:
break
if x < 0:
break
ans += 1
print(ans) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define int long long
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 0x3f3f3f3f;
const int N = 2e6+10;
struct node {
int l,r,mid,ma;
} tree[N];
int a[N],ans[N];
vector<int>e[N];
int n;
void pp(int x) {
tree[x].ma=max(tree[ls].ma,tree[rs].ma);
}
void build(int x,int l,int r) {
tree[x]= {l,r,(l+r)/2,0};
if(l==r) {
return ;
}
int mid=tree[x].mid;
build(ls,l,mid);
build(rs,mid+1,r);
}
void modify(int x,int pos,int k) {
if(tree[x].l==pos && tree[x].r==pos) {
tree[x].ma=k;
return ;
}
int mid=tree[x].mid;
if(pos<=mid) modify(ls,pos,k);
if(pos>mid) modify(rs,pos,k);
pp(x);
}
int query(int x,int l,int r) {
if(l<=tree[x].l&&tree[x].r<=r) {
return tree[x].ma;
}
int mid=tree[x].mid;
int res=0;
if(l<=mid) res=max(res,query(ls,l,r));
if(r>mid) res=max(res,query(rs,l,r));
return res;
}
void dfs(int u,int fa) {
int now=a[u];
int sum=query(1,1,now-1)+1;
int pre=query(1,now,now);
modify(1,now,max(sum,pre));
ans[u]=query(1,1,n+5);
for(auto v:e[u]) {
if(v==fa) continue;
dfs(v,u);
}
modify(1,now,pre);
}
signed main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
read(n);
vector<int>b;
for(int i=1; i<=n; i++) {
read(a[i]);
b.pb(a[i]);
}
sort(all(b));
b.erase(unique(all(b)),b.end());
for(int i=1; i<=n; i++) a[i]=lower_bound(all(b),a[i])-b.begin()+2;
for(int i=1; i<n; i++) {
int u,v;
read(u,v);
e[u].pb(v);
e[v].pb(u);
}
build(1,1,n+5);
dfs(1,1);
for(int i=1; i<=n; i++) cout<<ans[i]<<"\n";
return 0;
}
Code 2: import math
n, x = list(map(int, input().split())) # 整数
array = list(map(int, input().strip().split()))
array.sort()
ans = 0
l = len(array)
for i in array:
l -= 1
x = x-i
if l == 0:
if x != 0:
break
if x < 0:
break
ans += 1
print(ans) |
TypeScript | function main(input) {
input = input.trim();
const [m, d] = input.split(' ').map(n => Number(n));
let result = 0;
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= d; j++) {
const d1 = j%10;
const d10 = Math.floor(j/10);
if (2 <= d1 && 2 <= d10 && i === d1 * d10) {
result++;
}
}
}
console.log(result);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8')); | PHP | <?php
fscanf(STDIN, "%d%d", $m, $d);
if($d < 10){
echo 0;
exit;
}
$ans =0;
for($i=11; $i <= $d; $i++){
$one = ($i % 10);
$ten = intdiv($i, 10);
if($one < 2|| $ten < 2){
continue;
}
$today = $one * $ten;
for($j =1; $j<=$m;$j++){
if($today == $j){
$ans++;
}
}
}
echo $ans; | Yes | Do these codes solve the same problem?
Code 1: function main(input) {
input = input.trim();
const [m, d] = input.split(' ').map(n => Number(n));
let result = 0;
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= d; j++) {
const d1 = j%10;
const d10 = Math.floor(j/10);
if (2 <= d1 && 2 <= d10 && i === d1 * d10) {
result++;
}
}
}
console.log(result);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
Code 2: <?php
fscanf(STDIN, "%d%d", $m, $d);
if($d < 10){
echo 0;
exit;
}
$ans =0;
for($i=11; $i <= $d; $i++){
$one = ($i % 10);
$ten = intdiv($i, 10);
if($one < 2|| $ten < 2){
continue;
}
$today = $one * $ten;
for($j =1; $j<=$m;$j++){
if($today == $j){
$ans++;
}
}
}
echo $ans; |
Python | def main():
N = int( input())
S = input()
ans = 0
for i in range(N-2):
if S[i] == "A" and S[i+1] == "B" and S[i+2] == "C":
ans += 1
print(ans)
if __name__ == '__main__':
main() | C# |
using System;
class IDONTKNOWCSHARP
{
public static void Main()
{
string mozi = "";
int aa = int.Parse(Console.ReadLine());
for (int i = 0; i <aa; i++)
{
mozi += "ACL";
}
Console.WriteLine(mozi);
// Console.ReadLine();
}
static int[] Convert(string[] v)
{
var temp = new int[v.Length];
for (int i = 0; i < temp.Length; i++)
{
temp[i] = int.Parse(v[i]);
}
return temp;
}
static string[] GetLines()
{
return Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
}
} | No | Do these codes solve the same problem?
Code 1: def main():
N = int( input())
S = input()
ans = 0
for i in range(N-2):
if S[i] == "A" and S[i+1] == "B" and S[i+2] == "C":
ans += 1
print(ans)
if __name__ == '__main__':
main()
Code 2:
using System;
class IDONTKNOWCSHARP
{
public static void Main()
{
string mozi = "";
int aa = int.Parse(Console.ReadLine());
for (int i = 0; i <aa; i++)
{
mozi += "ACL";
}
Console.WriteLine(mozi);
// Console.ReadLine();
}
static int[] Convert(string[] v)
{
var temp = new int[v.Length];
for (int i = 0; i < temp.Length; i++)
{
temp[i] = int.Parse(v[i]);
}
return temp;
}
static string[] GetLines()
{
return Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
}
} |
C |
#include <stdio.h>
struct road{
int from;
int to;
int distance;
};
int calc_longest(int, int, int, int*, struct road*, int);
void calc_shortestDistance(int, int, int, int*, struct road*, int, int*);
int main(void)
{
int N, M, K;
struct road roads[100000];
int mall[3001];
int max_distance;
int longest_d;
int i;
scanf("%d %d %d", &N, &M, &K);
max_distance=0;
for(i=0; i<M; i++){
scanf("%d %d %d", &roads[i].from, &roads[i].to, &roads[i].distance);
if(max_distance<roads[i].distance) max_distance=roads[i].distance;
}
for(i=0; i<K; i++){
scanf("%d", &mall[i]);
}
longest_d=calc_longest(N, M, K, mall, roads, max_distance);
printf("%d\n", longest_d);
return 0;
}
int calc_longest(int N, int M, int K, int* mall, struct road* roads, int max_distance)
{
int i;
float longest_d, tmp_d;
int longest_int;
int d[3001];
for(i=1; i<=N; i++) d[i]=max_distance*(M+1);
calc_shortestDistance(N, M, K, mall, roads, max_distance, d);
longest_d=0.0f;
for(i=0; i<M; i++){
tmp_d=(float)(d[roads[i].from]+d[roads[i].to]+roads[i].distance);
tmp_d/=2.0f;
if(longest_d<tmp_d) longest_d=tmp_d;
}
longest_int=longest_d+0.5f;
return longest_int;
}
void calc_shortestDistance(int city_size, int n, int mall_size, int* mall, struct road* roads, int max_distance, int* d)
{
int is_searched[3001]; //0:is not searched, 1:is searched.
int min_d, min_city;
int i;
for(i=1; i<=city_size; i++) is_searched[i]=0;
for(i=1; i<=city_size; i++) d[i]=max_distance*n+1;
for(i=0; i<mall_size; i++) d[mall[i]]=0;
while(1){
min_d=max_distance*n+1;
for(i=1; i<=city_size; i++){
if(!is_searched[i] && d[i]<min_d){
min_d=d[i];
min_city=i;
}
}
if(min_d==max_distance*n+1) break;
for(i=0; i<n; i++){
if(roads[i].from==min_city){
if(d[roads[i].to]>min_d+roads[i].distance) d[roads[i].to]=min_d+roads[i].distance;
}
else if(roads[i].to==min_city){
if(d[roads[i].from]>min_d+roads[i].distance) d[roads[i].from]=min_d+roads[i].distance;
}
}
is_searched[min_city]=1;
}
return;
} | Java |
import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
public class Main {
int INF = 1 << 28;
//long INF = 1L << 62;
double EPS = 1e-10;
void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
E[] G = new E[n];
for(int i=0;i<n;i++) G[i] = new E();
for(int i=0;i<m;i++) {
int a = sc.nextInt() - 1, b = sc.nextInt() - 1, l = sc.nextInt();
G[a].add(new V(b, 2*l));
G[b].add(new V(a, 2*l));
}
int[] sp = new int[k];
int[] dist = new int[n]; fill(dist, INF);
PriorityQueue<S> que = new PriorityQueue<S>();
int max = 0;
for(int i=0;i<k;i++) {
sp[i] = sc.nextInt() - 1;
dist[sp[i]] = 0;
for(V v: G[sp[i]]) if(dist[v.t] > v.l){
que.add(new S(v.t, v.l));
}
}
for(;!que.isEmpty();) {
S cur = que.remove();
if(dist[cur.p] == INF) {
dist[cur.p] = cur.c;
max = max(max, cur.c);
} else {
max = max(max, ( dist[cur.p] + cur.c ) / 2);
continue;
}
for(V v: G[cur.p]) if(dist[v.t] > v.l){
que.add(new S(v.t, cur.c + v.l));
}
}
System.out.println((max+1) / 2);
}
class S implements Comparable<S>{
int p, c;
S(int p, int c){
this.p = p;
this.c = c;
}
public int compareTo(S arg0) {
// TODO Auto-generated method stub
return c - arg0.c;
}
}
class V {
int t, l;
V(int t, int l) {
this.t = t; this.l = l;
}
}
class E extends ArrayList<V> {}
void debug(Object... os) {
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args) {
new Main().run();
}
} | Yes | Do these codes solve the same problem?
Code 1:
#include <stdio.h>
struct road{
int from;
int to;
int distance;
};
int calc_longest(int, int, int, int*, struct road*, int);
void calc_shortestDistance(int, int, int, int*, struct road*, int, int*);
int main(void)
{
int N, M, K;
struct road roads[100000];
int mall[3001];
int max_distance;
int longest_d;
int i;
scanf("%d %d %d", &N, &M, &K);
max_distance=0;
for(i=0; i<M; i++){
scanf("%d %d %d", &roads[i].from, &roads[i].to, &roads[i].distance);
if(max_distance<roads[i].distance) max_distance=roads[i].distance;
}
for(i=0; i<K; i++){
scanf("%d", &mall[i]);
}
longest_d=calc_longest(N, M, K, mall, roads, max_distance);
printf("%d\n", longest_d);
return 0;
}
int calc_longest(int N, int M, int K, int* mall, struct road* roads, int max_distance)
{
int i;
float longest_d, tmp_d;
int longest_int;
int d[3001];
for(i=1; i<=N; i++) d[i]=max_distance*(M+1);
calc_shortestDistance(N, M, K, mall, roads, max_distance, d);
longest_d=0.0f;
for(i=0; i<M; i++){
tmp_d=(float)(d[roads[i].from]+d[roads[i].to]+roads[i].distance);
tmp_d/=2.0f;
if(longest_d<tmp_d) longest_d=tmp_d;
}
longest_int=longest_d+0.5f;
return longest_int;
}
void calc_shortestDistance(int city_size, int n, int mall_size, int* mall, struct road* roads, int max_distance, int* d)
{
int is_searched[3001]; //0:is not searched, 1:is searched.
int min_d, min_city;
int i;
for(i=1; i<=city_size; i++) is_searched[i]=0;
for(i=1; i<=city_size; i++) d[i]=max_distance*n+1;
for(i=0; i<mall_size; i++) d[mall[i]]=0;
while(1){
min_d=max_distance*n+1;
for(i=1; i<=city_size; i++){
if(!is_searched[i] && d[i]<min_d){
min_d=d[i];
min_city=i;
}
}
if(min_d==max_distance*n+1) break;
for(i=0; i<n; i++){
if(roads[i].from==min_city){
if(d[roads[i].to]>min_d+roads[i].distance) d[roads[i].to]=min_d+roads[i].distance;
}
else if(roads[i].to==min_city){
if(d[roads[i].from]>min_d+roads[i].distance) d[roads[i].from]=min_d+roads[i].distance;
}
}
is_searched[min_city]=1;
}
return;
}
Code 2:
import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
public class Main {
int INF = 1 << 28;
//long INF = 1L << 62;
double EPS = 1e-10;
void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
E[] G = new E[n];
for(int i=0;i<n;i++) G[i] = new E();
for(int i=0;i<m;i++) {
int a = sc.nextInt() - 1, b = sc.nextInt() - 1, l = sc.nextInt();
G[a].add(new V(b, 2*l));
G[b].add(new V(a, 2*l));
}
int[] sp = new int[k];
int[] dist = new int[n]; fill(dist, INF);
PriorityQueue<S> que = new PriorityQueue<S>();
int max = 0;
for(int i=0;i<k;i++) {
sp[i] = sc.nextInt() - 1;
dist[sp[i]] = 0;
for(V v: G[sp[i]]) if(dist[v.t] > v.l){
que.add(new S(v.t, v.l));
}
}
for(;!que.isEmpty();) {
S cur = que.remove();
if(dist[cur.p] == INF) {
dist[cur.p] = cur.c;
max = max(max, cur.c);
} else {
max = max(max, ( dist[cur.p] + cur.c ) / 2);
continue;
}
for(V v: G[cur.p]) if(dist[v.t] > v.l){
que.add(new S(v.t, cur.c + v.l));
}
}
System.out.println((max+1) / 2);
}
class S implements Comparable<S>{
int p, c;
S(int p, int c){
this.p = p;
this.c = c;
}
public int compareTo(S arg0) {
// TODO Auto-generated method stub
return c - arg0.c;
}
}
class V {
int t, l;
V(int t, int l) {
this.t = t; this.l = l;
}
}
class E extends ArrayList<V> {}
void debug(Object... os) {
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args) {
new Main().run();
}
} |
Java | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Main() throws IOException {
try {
//br = new BufferedReader( new FileReader("input.txt") );
//in = new Reader("input.txt");
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
}
void go() throws Exception {
long time = System.currentTimeMillis();
//int t = in.nextInt();
int t = 1;
while (t > 0) {
solve();
t--;
}
//System.err.println(System.currentTimeMillis() - time);
out.flush();
out.close();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.000000001;
int n;
int m;
//ArrayList<Integer>[] g = new ArrayList[200000];
void solve() throws IOException {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
long ans = 0;
int[] bits = new int[20];
int p = 0;
for (int i = 0; i < n; i++) {
int x = a[i];
for (int j = 0; j < 20; j++)
if ((x & (1 << j)) != 0) bits[j]++;
while (!check(bits)) {
for (int j = 0; j < 20; j++)
if ((a[p] & (1 << j)) != 0) bits[j]--;
p++;
}
ans += i - p + 1;
}
out.println(ans);
}
boolean check(int[] b) {
boolean res = true;
for (int i = 0; i < b.length; i++) res &= b[i] < 2;
return res;
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a > p.a) return 1;
if (a < p.a) return -1;
if (b > p.b) return 1;
if (b < p.b) return -1;
return 0;
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
static class InputReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public InputReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public InputReader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
} | Go | package main
import (
"bufio"
"os"
"strconv"
"fmt"
)
var sc = bufio.NewScanner(os.Stdin)
func nextString() string {
if !sc.Scan() {
panic("failed scan string")
}
return sc.Text()
}
func nextInt() int {
if !sc.Scan() {
panic("failed scan int")
}
i, e := strconv.Atoi(sc.Text())
if e != nil {
panic(e)
}
return i
}
func main() {
sc.Split(bufio.ScanWords)
n := nextInt()
as := make([]uint64, n)
for i := 0; i < n; i++ {
as[i] = uint64(nextInt())
}
var r int
var l int
var sum uint64
var count int
for l = 0; l < n; l++ {
for as[l]&sum != 0 {
sum -= as[r]
r += 1
}
//fmt.Printf("r: %v, l: %v\n", r, l)
sum += as[l]
count += l - r + 1
}
fmt.Println(count)
}
func check(as []uint64) bool {
if len(as) == 0 {
return false
}
xor := as[0]
sum := as[0]
for _, a := range as[1:] {
xor ^= a
sum += a
if xor != sum {
return false
}
}
//if xor == sum {
// fmt.Printf("xor: %v, sum: %v\n", xor, sum)
//}
return xor == sum
}
| Yes | Do these codes solve the same problem?
Code 1: import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Main() throws IOException {
try {
//br = new BufferedReader( new FileReader("input.txt") );
//in = new Reader("input.txt");
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
}
void go() throws Exception {
long time = System.currentTimeMillis();
//int t = in.nextInt();
int t = 1;
while (t > 0) {
solve();
t--;
}
//System.err.println(System.currentTimeMillis() - time);
out.flush();
out.close();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.000000001;
int n;
int m;
//ArrayList<Integer>[] g = new ArrayList[200000];
void solve() throws IOException {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
long ans = 0;
int[] bits = new int[20];
int p = 0;
for (int i = 0; i < n; i++) {
int x = a[i];
for (int j = 0; j < 20; j++)
if ((x & (1 << j)) != 0) bits[j]++;
while (!check(bits)) {
for (int j = 0; j < 20; j++)
if ((a[p] & (1 << j)) != 0) bits[j]--;
p++;
}
ans += i - p + 1;
}
out.println(ans);
}
boolean check(int[] b) {
boolean res = true;
for (int i = 0; i < b.length; i++) res &= b[i] < 2;
return res;
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a > p.a) return 1;
if (a < p.a) return -1;
if (b > p.b) return 1;
if (b < p.b) return -1;
return 0;
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
static class InputReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public InputReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public InputReader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
Code 2: package main
import (
"bufio"
"os"
"strconv"
"fmt"
)
var sc = bufio.NewScanner(os.Stdin)
func nextString() string {
if !sc.Scan() {
panic("failed scan string")
}
return sc.Text()
}
func nextInt() int {
if !sc.Scan() {
panic("failed scan int")
}
i, e := strconv.Atoi(sc.Text())
if e != nil {
panic(e)
}
return i
}
func main() {
sc.Split(bufio.ScanWords)
n := nextInt()
as := make([]uint64, n)
for i := 0; i < n; i++ {
as[i] = uint64(nextInt())
}
var r int
var l int
var sum uint64
var count int
for l = 0; l < n; l++ {
for as[l]&sum != 0 {
sum -= as[r]
r += 1
}
//fmt.Printf("r: %v, l: %v\n", r, l)
sum += as[l]
count += l - r + 1
}
fmt.Println(count)
}
func check(as []uint64) bool {
if len(as) == 0 {
return false
}
xor := as[0]
sum := as[0]
for _, a := range as[1:] {
xor ^= a
sum += a
if xor != sum {
return false
}
}
//if xor == sum {
// fmt.Printf("xor: %v, sum: %v\n", xor, sum)
//}
return xor == sum
}
|
Python | n=int(input())
s=input()
ans=0
ans+=s.count("OX")
s=s.replace('OX','')
ans+=s.count("XO")
print(ans)
| PHP | <?php
$target_count = intval(trim(fgets(STDIN)));
$target_arr = trim(fgets(STDIN));
$count = 0;
for ($i = 1; $i < $target_count;) {
$prev = $target_arr[$i-1];
if ($prev != $target_arr[$i]) {
$count++;
$i += 2;
} else {
$i++;
}
}
echo $count."\n";
| Yes | Do these codes solve the same problem?
Code 1: n=int(input())
s=input()
ans=0
ans+=s.count("OX")
s=s.replace('OX','')
ans+=s.count("XO")
print(ans)
Code 2: <?php
$target_count = intval(trim(fgets(STDIN)));
$target_arr = trim(fgets(STDIN));
$count = 0;
for ($i = 1; $i < $target_count;) {
$prev = $target_arr[$i-1];
if ($prev != $target_arr[$i]) {
$count++;
$i += 2;
} else {
$i++;
}
}
echo $count."\n";
|
C | #include<stdio.h>
#include<stdlib.h>
#define ll long long
#define rep(i,l,r)for(ll i=(l);i<(r);i++)
#define INF ((1LL<<62)-(1LL<<31))
#define max(p,q)((p)>(q)?(p):(q))
int M,q;
//辺の情報を個別に持つタイプ
typedef struct edge{ll s,g,c;}E;
typedef struct graph{
int vcnt,ecnt;
E e[200010];//適宜変える(ecnt)
int id[100010];//適宜変える(vcnt)
}G;
G g;
int esort(const void*a,const void*b){
E*p=(E*)a,*q=(E*)b;
if((*p).s<(*q).s)return -1;
if((*p).s>(*q).s)return 1;
if((*p).g<(*q).g)return -1;
return 1;
}
void readgraph(){
//適宜変える
int n,m;
scanf("%d%d%d%d",&n,&m,&M,&q);
rep(i,0,m){
ll x,y,c;
scanf("%lld%lld%lld",&x,&y,&c);
g.e[i].s=y;
g.e[i].g=x;
g.e[i].c=c;
}
g.vcnt=n+1;
g.ecnt=m;
qsort(g.e,g.ecnt,sizeof(E),esort);
int p=0;
rep(i,0,g.vcnt){
while(p<g.ecnt&&g.e[p].s<i)p++;
g.id[i]=p;
}
g.id[g.vcnt]=g.ecnt;//番兵
}
//プラキュー(二分ヒープ)(優先度変更ありバージョン)
ll heapN,heap[1<<20],heapinv[1<<20];
int PQhikaku(int i,int j);//jの方が優先度が高いならtrueを返す
void PQchange(int n);
void heap_utod(int n){
if(2*n>heapN)return;
int rflag=(2*n+1<=heapN)&&(PQhikaku(2*n,2*n+1));
if(PQhikaku(n,2*n+rflag)){
ll temp=heap[2*n+rflag];
heap[2*n+rflag]=heap[n];
heap[n]=temp;
heapinv[heap[n]]=n;
heapinv[heap[2*n+rflag]]=2*n+rflag;
heap_utod(2*n+rflag);
}
}
void heap_dtou(int n){
if(n==1||PQhikaku(n,n/2))return;
ll temp=heap[n];
heap[n]=heap[n/2];
heap[n/2]=temp;
heapinv[heap[n]]=n;
heapinv[heap[n/2]]=n/2;
heap_dtou(n/2);
}
ll PQpop(){
ll rr=heap[1];
heapinv[heap[1]]=0;
heap[1]=heap[heapN--];
heapinv[heap[1]]=1;
heap_utod(1);
return rr;
}
void PQpush(ll n){
heap[++heapN]=n;
heapinv[heap[heapN]]=heapN;
heap_dtou(heapN);
}
//早い方のダイクストラ
//グラフと始点を引いて各点への最短距離・最短経路を返す
//プラキューが必要
//O((E+V)logV)
ll daikusutorappp[100010];
void daikusutora2(int r){
rep(i,0,g.vcnt)daikusutorappp[i]=i%M==r?0:INF;
rep(i,0,g.vcnt)PQpush(i);
while(heapN){
ll mv=PQpop();
for(ll t=g.id[mv];t<g.ecnt&&g.e[t].s==mv;t++){
if(daikusutorappp[g.e[t].g]>daikusutorappp[mv]+g.e[t].c){
daikusutorappp[g.e[t].g]=daikusutorappp[mv]+g.e[t].c;
PQchange(g.e[t].g);
}
}
}
}
int PQhikaku(int i,int j){return daikusutorappp[heap[i]]>daikusutorappp[heap[j]];}
void PQchange(int n){if(heapinv[n])heap_dtou(heapinv[n]);}
ll dd[10][100010];
int main(){
readgraph();
rep(i,0,M){
daikusutora2(i);
rep(j,0,g.vcnt)dd[i][j]=daikusutorappp[j];
}
long long ans=0;
while(q--){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
ll temp=0;
rep(i,0,M){
ll xx=dd[i][x];
ll yy=dd[i][y];
temp=max(temp,z-xx-yy);
}
ans+=temp;
}
printf("%lld\n",ans);
}
| Java |
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
public class Main {
InputStream is;
int __t__ = 1;
int __f__ = 0;
int __FILE_DEBUG_FLAG__ = __f__;
String __DEBUG_FILE_NAME__ = "src/H1";
FastScanner in;
PrintWriter out;
class Edge {
int to;
int cost;
Edge(int to, int cost) {
this.to = to;
this.cost = cost;
}
}
class State implements Comparable<State> {
int u;
long cost;
State(int u, long cost) {
this.u = u;
this.cost = cost;
}
public int compareTo(State s) {
return Long.compare(cost, s.cost);
}
public String toString() {
return "(" + u + ", " + cost + ")";
}
}
ArrayList<Edge>[] g;
@SuppressWarnings("unchecked")
public void solve() {
int N = in.nextInt(), M = in.nextInt(), R = in.nextInt(), Q = in.nextInt();
g = new ArrayList[N+R];
for (int i = 0; i < N + R; i++)
g[i] = new ArrayList<Edge>();
for (int i = 0; i < N; i++) {
g[N+i%R].add(new Edge(i, 0));
}
for (int i = 0; i < M; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1, c = in.nextInt();
g[b].add(new Edge(a, c));
}
long[][] costs = new long[R][];
for (int i = 0; i < R; i++) {
long[] minCost = new long[N+R];
Arrays.fill(minCost, (long) 1e16);
PriorityQueue<State> pq = new PriorityQueue<>();
minCost[N+i] = 0;
pq.add(new State(N+i, 0));
while (!pq.isEmpty()) {
State st = pq.poll();
if (st.cost > minCost[st.u]) continue;
for (Edge e : g[st.u]) {
long ncost = minCost[st.u] + e.cost;
if (ncost < minCost[e.to]) {
minCost[e.to] = ncost;
pq.add(new State(e.to, ncost));
}
}
}
costs[i] = minCost;
}
long res = 0;
for (int q = 0; q < Q; q++) {
int x = in.nextInt() - 1, y = in.nextInt() - 1, z = in.nextInt();
long c = Long.MAX_VALUE;
for (int i = 0; i < R; i++) {
c = Math.min(c, costs[i][x] + costs[i][y]);
}
if (c <= z)
res += z - c;
}
System.out.println(res);
}
public void run() {
if (__FILE_DEBUG_FLAG__ == __t__) {
try {
is = new FileInputStream(__DEBUG_FILE_NAME__);
} catch (FileNotFoundException e) {
// TODO ????????????????????? catch ????????????
e.printStackTrace();
}
System.out.println("FILE_INPUT!");
} else {
is = System.in;
}
in = new FastScanner(is);
out = new PrintWriter(System.out);
Thread t = new Thread(null, new Runnable() {
@Override
public void run() {
solve();
}
}, "lul", 1 << 30);
t.start();
}
public static void main(String[] args) {
new Main().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextIntArray(m);
}
return map;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextLongArray(m);
}
return map;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextDoubleArray(m);
}
return map;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
} | Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
#include<stdlib.h>
#define ll long long
#define rep(i,l,r)for(ll i=(l);i<(r);i++)
#define INF ((1LL<<62)-(1LL<<31))
#define max(p,q)((p)>(q)?(p):(q))
int M,q;
//辺の情報を個別に持つタイプ
typedef struct edge{ll s,g,c;}E;
typedef struct graph{
int vcnt,ecnt;
E e[200010];//適宜変える(ecnt)
int id[100010];//適宜変える(vcnt)
}G;
G g;
int esort(const void*a,const void*b){
E*p=(E*)a,*q=(E*)b;
if((*p).s<(*q).s)return -1;
if((*p).s>(*q).s)return 1;
if((*p).g<(*q).g)return -1;
return 1;
}
void readgraph(){
//適宜変える
int n,m;
scanf("%d%d%d%d",&n,&m,&M,&q);
rep(i,0,m){
ll x,y,c;
scanf("%lld%lld%lld",&x,&y,&c);
g.e[i].s=y;
g.e[i].g=x;
g.e[i].c=c;
}
g.vcnt=n+1;
g.ecnt=m;
qsort(g.e,g.ecnt,sizeof(E),esort);
int p=0;
rep(i,0,g.vcnt){
while(p<g.ecnt&&g.e[p].s<i)p++;
g.id[i]=p;
}
g.id[g.vcnt]=g.ecnt;//番兵
}
//プラキュー(二分ヒープ)(優先度変更ありバージョン)
ll heapN,heap[1<<20],heapinv[1<<20];
int PQhikaku(int i,int j);//jの方が優先度が高いならtrueを返す
void PQchange(int n);
void heap_utod(int n){
if(2*n>heapN)return;
int rflag=(2*n+1<=heapN)&&(PQhikaku(2*n,2*n+1));
if(PQhikaku(n,2*n+rflag)){
ll temp=heap[2*n+rflag];
heap[2*n+rflag]=heap[n];
heap[n]=temp;
heapinv[heap[n]]=n;
heapinv[heap[2*n+rflag]]=2*n+rflag;
heap_utod(2*n+rflag);
}
}
void heap_dtou(int n){
if(n==1||PQhikaku(n,n/2))return;
ll temp=heap[n];
heap[n]=heap[n/2];
heap[n/2]=temp;
heapinv[heap[n]]=n;
heapinv[heap[n/2]]=n/2;
heap_dtou(n/2);
}
ll PQpop(){
ll rr=heap[1];
heapinv[heap[1]]=0;
heap[1]=heap[heapN--];
heapinv[heap[1]]=1;
heap_utod(1);
return rr;
}
void PQpush(ll n){
heap[++heapN]=n;
heapinv[heap[heapN]]=heapN;
heap_dtou(heapN);
}
//早い方のダイクストラ
//グラフと始点を引いて各点への最短距離・最短経路を返す
//プラキューが必要
//O((E+V)logV)
ll daikusutorappp[100010];
void daikusutora2(int r){
rep(i,0,g.vcnt)daikusutorappp[i]=i%M==r?0:INF;
rep(i,0,g.vcnt)PQpush(i);
while(heapN){
ll mv=PQpop();
for(ll t=g.id[mv];t<g.ecnt&&g.e[t].s==mv;t++){
if(daikusutorappp[g.e[t].g]>daikusutorappp[mv]+g.e[t].c){
daikusutorappp[g.e[t].g]=daikusutorappp[mv]+g.e[t].c;
PQchange(g.e[t].g);
}
}
}
}
int PQhikaku(int i,int j){return daikusutorappp[heap[i]]>daikusutorappp[heap[j]];}
void PQchange(int n){if(heapinv[n])heap_dtou(heapinv[n]);}
ll dd[10][100010];
int main(){
readgraph();
rep(i,0,M){
daikusutora2(i);
rep(j,0,g.vcnt)dd[i][j]=daikusutorappp[j];
}
long long ans=0;
while(q--){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
ll temp=0;
rep(i,0,M){
ll xx=dd[i][x];
ll yy=dd[i][y];
temp=max(temp,z-xx-yy);
}
ans+=temp;
}
printf("%lld\n",ans);
}
Code 2:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
public class Main {
InputStream is;
int __t__ = 1;
int __f__ = 0;
int __FILE_DEBUG_FLAG__ = __f__;
String __DEBUG_FILE_NAME__ = "src/H1";
FastScanner in;
PrintWriter out;
class Edge {
int to;
int cost;
Edge(int to, int cost) {
this.to = to;
this.cost = cost;
}
}
class State implements Comparable<State> {
int u;
long cost;
State(int u, long cost) {
this.u = u;
this.cost = cost;
}
public int compareTo(State s) {
return Long.compare(cost, s.cost);
}
public String toString() {
return "(" + u + ", " + cost + ")";
}
}
ArrayList<Edge>[] g;
@SuppressWarnings("unchecked")
public void solve() {
int N = in.nextInt(), M = in.nextInt(), R = in.nextInt(), Q = in.nextInt();
g = new ArrayList[N+R];
for (int i = 0; i < N + R; i++)
g[i] = new ArrayList<Edge>();
for (int i = 0; i < N; i++) {
g[N+i%R].add(new Edge(i, 0));
}
for (int i = 0; i < M; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1, c = in.nextInt();
g[b].add(new Edge(a, c));
}
long[][] costs = new long[R][];
for (int i = 0; i < R; i++) {
long[] minCost = new long[N+R];
Arrays.fill(minCost, (long) 1e16);
PriorityQueue<State> pq = new PriorityQueue<>();
minCost[N+i] = 0;
pq.add(new State(N+i, 0));
while (!pq.isEmpty()) {
State st = pq.poll();
if (st.cost > minCost[st.u]) continue;
for (Edge e : g[st.u]) {
long ncost = minCost[st.u] + e.cost;
if (ncost < minCost[e.to]) {
minCost[e.to] = ncost;
pq.add(new State(e.to, ncost));
}
}
}
costs[i] = minCost;
}
long res = 0;
for (int q = 0; q < Q; q++) {
int x = in.nextInt() - 1, y = in.nextInt() - 1, z = in.nextInt();
long c = Long.MAX_VALUE;
for (int i = 0; i < R; i++) {
c = Math.min(c, costs[i][x] + costs[i][y]);
}
if (c <= z)
res += z - c;
}
System.out.println(res);
}
public void run() {
if (__FILE_DEBUG_FLAG__ == __t__) {
try {
is = new FileInputStream(__DEBUG_FILE_NAME__);
} catch (FileNotFoundException e) {
// TODO ????????????????????? catch ????????????
e.printStackTrace();
}
System.out.println("FILE_INPUT!");
} else {
is = System.in;
}
in = new FastScanner(is);
out = new PrintWriter(System.out);
Thread t = new Thread(null, new Runnable() {
@Override
public void run() {
solve();
}
}, "lul", 1 << 30);
t.start();
}
public static void main(String[] args) {
new Main().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextIntArray(m);
}
return map;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextLongArray(m);
}
return map;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextDoubleArray(m);
}
return map;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
} |
C++ | #include<iostream>
using namespace std;
#define ll long long
int main()
{
ll n;
cin>>n;
ll arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
ll mx=0,ans=0;
for(int i=0;i<n;i++){
if(arr[i]>=mx)
mx=arr[i];
else
ans+=mx-arr[i];
}
cout<<ans<<endl;
return 0;
} | Python | W, H = map(int,input().strip().split(' '))
w, h = map(int,input().strip().split(' '))
white = (W*H)-(w*h)-(W-w)*h-(H-h)*w
print(white)
| No | Do these codes solve the same problem?
Code 1: #include<iostream>
using namespace std;
#define ll long long
int main()
{
ll n;
cin>>n;
ll arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
ll mx=0,ans=0;
for(int i=0;i<n;i++){
if(arr[i]>=mx)
mx=arr[i];
else
ans+=mx-arr[i];
}
cout<<ans<<endl;
return 0;
}
Code 2: W, H = map(int,input().strip().split(' '))
w, h = map(int,input().strip().split(' '))
white = (W*H)-(w*h)-(W-w)*h-(H-h)*w
print(white)
|
C++ | #include <iostream>
using namespace std;
int main() {
int d;
while(cin >> d) {
int sum=0;
for(int i=1; i<600/d; i++) {
sum+=(d*i)*(d*i)*d;
}
cout << sum << endl;
}
return 0;
}
| Python | output = []
while True:
try:
d = int(input())
except :
break
sum = 0
for x in range(1,600//d):
sum = sum + d * (d*x) * (d*x)
output.append(sum)
for x in range(len(output)):
print(output[x])
| Yes | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int main() {
int d;
while(cin >> d) {
int sum=0;
for(int i=1; i<600/d; i++) {
sum+=(d*i)*(d*i)*d;
}
cout << sum << endl;
}
return 0;
}
Code 2: output = []
while True:
try:
d = int(input())
except :
break
sum = 0
for x in range(1,600//d):
sum = sum + d * (d*x) * (d*x)
output.append(sum)
for x in range(len(output)):
print(output[x])
|
Python | while True:
w, h = map(int, input().split())
if w == 0 and h == 0:
break
ywalls = [[0]*w for _ in range(h)]
xwalls = [[0]*w for _ in range(h)]
for i in range(2*h-1):
walls = map(int, input().split())
if i%2==0:
for j, ele in enumerate(walls):
ywalls[i//2][j]=ele
else:
for j, ele in enumerate(walls):
xwalls[i//2][j]=ele
d = [[-1]*w for _ in range(h)]
sx, sy = 0, 0
gx, gy = w-1, h-1
from collections import deque
q = deque([])
q.append((sx, sy))
d[sx][sy] = 0
while len(q)>0:
cur = q.popleft()
#print(cur)
curx, cury = cur[0], cur[1]
if curx==gx and cury==gy:
break
for dx in range(-1, 2):
for dy in range(-1, 2):
if (dx==0 and dy!=0) or (dx!=0 and dy==0):
nx, ny = curx+dx, cury+dy
if 0<=nx<w and 0<=ny<h and d[ny][nx]==-1:
tx, ty = curx, cury
if dx==-1:
tx -=1
elif dy==-1:
ty -=1
if dx!=0 and ywalls[ty][tx]==0:
q.append((nx, ny))
d[ny][nx] = d[cury][curx]+1
elif dy!=0 and xwalls[ty][tx]==0:
q.append((nx, ny))
d[ny][nx] = d[cury][curx]+1
print(d[gy][gx]+1)
| JavaScript | /*
?§£????????????:How Many Islands?
(http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1160&lang=jp)
Status:Accepted
??????:
???????????????????????£??????????????????????????£????????????????????¨??????????????¨???????????°??????????????????????????¨???????????¨?????§?????????
?????????????????§????????????????§£??????????????????????????????????????±???????????°???????????°????????¨?????????????????????????????????????????????????????????
*/
var log = console.log;
if (typeof process != "undefined") {
var input = "";
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
input += chunk;
});
process.stdin.on('end', function() {
var lines = input.split("\n");
main(lines);
});
}
function main(lines) {
lines = lines.map(function(line) {
return line.split(" ").filter(function(e) {
return e != "";
}).map(function(e) {
return Number(e);
});
});
while (lines[0][0] != 0 && lines[0][1] != 0) {
var fl = lines.shift();
var W = fl[0];
var H = fl[1];
var set = lines.slice(0, 2 * H - 1);
lines = lines.slice(2 * H - 1);
processSet(W, H, set);
}
}
function processSet(W, H, set) {
//log(set);
function is_able_to(pos1, pos2) {
if (pos1[0] != pos2[0]) {
//????§????
//?\???°index???????´?????????????..1,3,5..
var walls = set[2 * Math.min(pos1[0], pos2[0]) + 1];
var inq = walls[pos1[1]];
return Boolean(inq != 1); //1??§????????£??????ok
} else if (pos1[0] == pos2[0]) {
//?¨??§????
//??¶??°index???????´?????????????..0,2,4..
//?£??????????????????\??£????????¨???
var walls = set[2 * pos1[0]];
//??¬?????????????????¨???
var inq = walls[Math.min(pos1[1], pos2[1])];
return Boolean(inq != 1); //1??§????????£??????ok
}
return false;
}
var mins = [];
for (var h = 0; h < H; h++) {
mins[h] = [];
for (var w = 0; w < W; w++) {
mins[h][w] = Infinity;
}
}
mins[0][0] = 1;
var stack = [];
stack.push([0, 0]);
var ngs = [
[-1, 0],
[0, -1],
[0, 1],
[1, 0]
];
while (stack.length > 0) {
var now = stack.shift();
var ns = mins[now[0]][now[1]];
//log("now at " + now);
ngs.forEach(function(d) {
var pos2 = [];
pos2[0] = now[0] + d[0];
pos2[1] = now[1] + d[1];
if (
0 <= pos2[0] && pos2[0] < H &&
0 <= pos2[1] && pos2[1] < W
) {
if (is_able_to(now, pos2)) {
if (mins[pos2[0]][pos2[1]] == Infinity) {
//not visited
mins[pos2[0]][pos2[1]] = ns + 1;
stack.push(pos2);
}
}
}
});
}
if (mins[H - 1][W - 1] == Infinity) {
log(0);
} else {
log(mins[H - 1][W - 1]);
}
} | Yes | Do these codes solve the same problem?
Code 1: while True:
w, h = map(int, input().split())
if w == 0 and h == 0:
break
ywalls = [[0]*w for _ in range(h)]
xwalls = [[0]*w for _ in range(h)]
for i in range(2*h-1):
walls = map(int, input().split())
if i%2==0:
for j, ele in enumerate(walls):
ywalls[i//2][j]=ele
else:
for j, ele in enumerate(walls):
xwalls[i//2][j]=ele
d = [[-1]*w for _ in range(h)]
sx, sy = 0, 0
gx, gy = w-1, h-1
from collections import deque
q = deque([])
q.append((sx, sy))
d[sx][sy] = 0
while len(q)>0:
cur = q.popleft()
#print(cur)
curx, cury = cur[0], cur[1]
if curx==gx and cury==gy:
break
for dx in range(-1, 2):
for dy in range(-1, 2):
if (dx==0 and dy!=0) or (dx!=0 and dy==0):
nx, ny = curx+dx, cury+dy
if 0<=nx<w and 0<=ny<h and d[ny][nx]==-1:
tx, ty = curx, cury
if dx==-1:
tx -=1
elif dy==-1:
ty -=1
if dx!=0 and ywalls[ty][tx]==0:
q.append((nx, ny))
d[ny][nx] = d[cury][curx]+1
elif dy!=0 and xwalls[ty][tx]==0:
q.append((nx, ny))
d[ny][nx] = d[cury][curx]+1
print(d[gy][gx]+1)
Code 2: /*
?§£????????????:How Many Islands?
(http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1160&lang=jp)
Status:Accepted
??????:
???????????????????????£??????????????????????????£????????????????????¨??????????????¨???????????°??????????????????????????¨???????????¨?????§?????????
?????????????????§????????????????§£??????????????????????????????????????±???????????°???????????°????????¨?????????????????????????????????????????????????????????
*/
var log = console.log;
if (typeof process != "undefined") {
var input = "";
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
input += chunk;
});
process.stdin.on('end', function() {
var lines = input.split("\n");
main(lines);
});
}
function main(lines) {
lines = lines.map(function(line) {
return line.split(" ").filter(function(e) {
return e != "";
}).map(function(e) {
return Number(e);
});
});
while (lines[0][0] != 0 && lines[0][1] != 0) {
var fl = lines.shift();
var W = fl[0];
var H = fl[1];
var set = lines.slice(0, 2 * H - 1);
lines = lines.slice(2 * H - 1);
processSet(W, H, set);
}
}
function processSet(W, H, set) {
//log(set);
function is_able_to(pos1, pos2) {
if (pos1[0] != pos2[0]) {
//????§????
//?\???°index???????´?????????????..1,3,5..
var walls = set[2 * Math.min(pos1[0], pos2[0]) + 1];
var inq = walls[pos1[1]];
return Boolean(inq != 1); //1??§????????£??????ok
} else if (pos1[0] == pos2[0]) {
//?¨??§????
//??¶??°index???????´?????????????..0,2,4..
//?£??????????????????\??£????????¨???
var walls = set[2 * pos1[0]];
//??¬?????????????????¨???
var inq = walls[Math.min(pos1[1], pos2[1])];
return Boolean(inq != 1); //1??§????????£??????ok
}
return false;
}
var mins = [];
for (var h = 0; h < H; h++) {
mins[h] = [];
for (var w = 0; w < W; w++) {
mins[h][w] = Infinity;
}
}
mins[0][0] = 1;
var stack = [];
stack.push([0, 0]);
var ngs = [
[-1, 0],
[0, -1],
[0, 1],
[1, 0]
];
while (stack.length > 0) {
var now = stack.shift();
var ns = mins[now[0]][now[1]];
//log("now at " + now);
ngs.forEach(function(d) {
var pos2 = [];
pos2[0] = now[0] + d[0];
pos2[1] = now[1] + d[1];
if (
0 <= pos2[0] && pos2[0] < H &&
0 <= pos2[1] && pos2[1] < W
) {
if (is_able_to(now, pos2)) {
if (mins[pos2[0]][pos2[1]] == Infinity) {
//not visited
mins[pos2[0]][pos2[1]] = ns + 1;
stack.push(pos2);
}
}
}
});
}
if (mins[H - 1][W - 1] == Infinity) {
log(0);
} else {
log(mins[H - 1][W - 1]);
}
} |
Go | package main
import (
"fmt"
)
func main() {
var i1 string
var i int
var cnt int
fmt.Scan(&i1)
for i = 0; i < len(i1)-1; i++ {
s := string(i1[i])
ns := string(i1[i+1])
if s == ns {
if ns == "0" {
i1 = replaceAtIndex(i1, '1', i+1)
cnt++
}
if ns == "1" {
i1= replaceAtIndex(i1, '0', i+1)
cnt++
}
}
}
fmt.Print(cnt)
}
func replaceAtIndex(str string, replacement rune, index int) string {
return str[:index] + string(replacement) + str[index+1:]
} | C++ | #include<iostream>
#include<vector>
using namespace std;
int main()
{
long long int n;
cin>>n;
long long int w;
cin>>w;
vector<long long int> W(n+1,0);
vector<long long int> V(n+1,0);
for(int i=1;i<=n;i++)
{
cin>>W[i]>>V[i];
}
vector<vector<long long int>> dp(n+1,vector<long long> (w+1,0));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=w;j++)
{
if(W[i]<=j)
{
dp[i][j]=max(dp[i-1][j-W[i]]+V[i],dp[i-1][j]);
}
else
{
dp[i][j]=dp[i-1][j];
}
}
// cout<<dp[i][w];
}
cout<<dp[n][w];
} | No | Do these codes solve the same problem?
Code 1: package main
import (
"fmt"
)
func main() {
var i1 string
var i int
var cnt int
fmt.Scan(&i1)
for i = 0; i < len(i1)-1; i++ {
s := string(i1[i])
ns := string(i1[i+1])
if s == ns {
if ns == "0" {
i1 = replaceAtIndex(i1, '1', i+1)
cnt++
}
if ns == "1" {
i1= replaceAtIndex(i1, '0', i+1)
cnt++
}
}
}
fmt.Print(cnt)
}
func replaceAtIndex(str string, replacement rune, index int) string {
return str[:index] + string(replacement) + str[index+1:]
}
Code 2: #include<iostream>
#include<vector>
using namespace std;
int main()
{
long long int n;
cin>>n;
long long int w;
cin>>w;
vector<long long int> W(n+1,0);
vector<long long int> V(n+1,0);
for(int i=1;i<=n;i++)
{
cin>>W[i]>>V[i];
}
vector<vector<long long int>> dp(n+1,vector<long long> (w+1,0));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=w;j++)
{
if(W[i]<=j)
{
dp[i][j]=max(dp[i-1][j-W[i]]+V[i],dp[i-1][j]);
}
else
{
dp[i][j]=dp[i-1][j];
}
}
// cout<<dp[i][w];
}
cout<<dp[n][w];
} |
C++ | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int>P;
int main(){
for(int n;cin>>n,n;){
vector<P>V;
for(int a,b;n--;){
cin>>a>>b;
V.push_back(P(a,b));
}
cin>>n;
for(int a,b;n--;){
cin>>a>>b;
V.push_back(P(a,b));
}
V.push_back(P(0,0));
sort(V.begin(),V.end());
int dp[201]={0};
int ans=0;
for(int i=0;i<V.size();i++){
ans = max(ans,dp[i]);
for(int j=i+1;j<V.size();j++){
if(V[i].first<V[j].first && V[i].second<V[j].second){
dp[j] = max(dp[i]+1,dp[j]);
}
}
}
cout<<ans<<endl;
}
return 0;
}
| Python | while True:
n=int(input())
if n==0:
break
dolls=[]
for i in range(n):
h,r=[int(j) for j in input().split(" ")]
dolls.append((h,r))
m=int(input())
for j in range(m):
h,r=[int(j) for j in input().split(" ")]
dolls.append((h,r))
dolls=sorted(dolls,key=lambda w:(w[0],-1*w[1]))
r=[i[1] for i in dolls]
table=[1 for i in range(len(r))]
for i in range(len(r)):
for j in range(i):
if r[j]<r[i]:
table[i]=max(table[i],table[j]+1)
print(max(table))
| Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int>P;
int main(){
for(int n;cin>>n,n;){
vector<P>V;
for(int a,b;n--;){
cin>>a>>b;
V.push_back(P(a,b));
}
cin>>n;
for(int a,b;n--;){
cin>>a>>b;
V.push_back(P(a,b));
}
V.push_back(P(0,0));
sort(V.begin(),V.end());
int dp[201]={0};
int ans=0;
for(int i=0;i<V.size();i++){
ans = max(ans,dp[i]);
for(int j=i+1;j<V.size();j++){
if(V[i].first<V[j].first && V[i].second<V[j].second){
dp[j] = max(dp[i]+1,dp[j]);
}
}
}
cout<<ans<<endl;
}
return 0;
}
Code 2: while True:
n=int(input())
if n==0:
break
dolls=[]
for i in range(n):
h,r=[int(j) for j in input().split(" ")]
dolls.append((h,r))
m=int(input())
for j in range(m):
h,r=[int(j) for j in input().split(" ")]
dolls.append((h,r))
dolls=sorted(dolls,key=lambda w:(w[0],-1*w[1]))
r=[i[1] for i in dolls]
table=[1 for i in range(len(r))]
for i in range(len(r)):
for j in range(i):
if r[j]<r[i]:
table[i]=max(table[i],table[j]+1)
print(max(table))
|
PHP | <?php
try{
$input = explode(" ", fgets(STDIN));
// NとRに分割
$n = $input[0];
$r = $input[1];
// 0未満は弾く
if($n < 0 || $r < 0){
echo("input error.");
exit;
}
// 内部レーティング出す
if($n < 10){
$ir = 100 * (10 - $n) + $r;
}else{
$ir = $r;
}
print_r($ir);
exit;
}catch(Exception $e){
echo("input is invalid.");
} | Python | import math
A,B=map(int,input().split())
nuki=[]
for i in range(1001):
if math.floor(i*0.08)==A and math.floor(i*0.1)==B:
nuki+=[i]
print(min(nuki) if len(nuki)!=0 else -1) | No | Do these codes solve the same problem?
Code 1: <?php
try{
$input = explode(" ", fgets(STDIN));
// NとRに分割
$n = $input[0];
$r = $input[1];
// 0未満は弾く
if($n < 0 || $r < 0){
echo("input error.");
exit;
}
// 内部レーティング出す
if($n < 10){
$ir = 100 * (10 - $n) + $r;
}else{
$ir = $r;
}
print_r($ir);
exit;
}catch(Exception $e){
echo("input is invalid.");
}
Code 2: import math
A,B=map(int,input().split())
nuki=[]
for i in range(1001):
if math.floor(i*0.08)==A and math.floor(i*0.1)==B:
nuki+=[i]
print(min(nuki) if len(nuki)!=0 else -1) |
JavaScript | var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
for(var i=0;i<7;i++){
var arr=Arr[i].split(" ").map(Number);
console.log(arr[0]-arr[1]);
} | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using static System.Console;
using static System.Math;
namespace AtCoder
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 7; i++)
{
var ab = ReadInts();
WriteLine(Abs(ab[0] - ab[1]));
}
}
private static string Read() { return ReadLine(); }
private static string[] Reads() { return (Read().Split()); }
private static int ReadInt() { return int.Parse(Read()); }
private static long ReadLong() { return long.Parse(Read()); }
private static double ReadDouble() { return double.Parse(Read()); }
private static int[] ReadInts() { return Array.ConvertAll(Read().Split(), int.Parse); }
private static long[] ReadLongs() { return Array.ConvertAll(Read().Split(), long.Parse); }
private static double[] ReadDoubles() { return Array.ConvertAll(Read().Split(), double.Parse); }
}
}
| Yes | Do these codes solve the same problem?
Code 1: var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
for(var i=0;i<7;i++){
var arr=Arr[i].split(" ").map(Number);
console.log(arr[0]-arr[1]);
}
Code 2: using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using static System.Console;
using static System.Math;
namespace AtCoder
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 7; i++)
{
var ab = ReadInts();
WriteLine(Abs(ab[0] - ab[1]));
}
}
private static string Read() { return ReadLine(); }
private static string[] Reads() { return (Read().Split()); }
private static int ReadInt() { return int.Parse(Read()); }
private static long ReadLong() { return long.Parse(Read()); }
private static double ReadDouble() { return double.Parse(Read()); }
private static int[] ReadInts() { return Array.ConvertAll(Read().Split(), int.Parse); }
private static long[] ReadLongs() { return Array.ConvertAll(Read().Split(), long.Parse); }
private static double[] ReadDoubles() { return Array.ConvertAll(Read().Split(), double.Parse); }
}
}
|
Java | import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Scanner;
class UnionFind{
int Parent[];
UnionFind(int n){//Initialize by -1
Parent=new int[n];
Arrays.fill(Parent, -1);
}
int root(int A) {//In which tree is A?
if(Parent[A]<0)return A;
return Parent[A]=root(Parent[A]);
}
int size(int A) {//size of tree which is include A
return -Parent[root(A)];
}
boolean connect(int A,int B) {//Connect A and B
A=root(A);
B=root(B);
if(A==B) return false;
if(size(A)<size(B)) {int C=0;C=B;B=A;A=C;}//SWAP
Parent[A]+=Parent[B];
Parent[B]=A;
return true;
}
}
public class Main {
static FastScanner scan=new FastScanner();
static Scanner scanner=new Scanner(System.in);
static Random rand=new Random();
static long mod=1000000007;
static double eps=0.0000000001;
static int big=Integer.MAX_VALUE;
static long modlcm(long a,long b) {return a*b*modint(gcd(a,b),mod);}
static long gcd (long a, long b) {return b>0?gcd(b,a%b):a;}
static long lcm (long a, long b) {return a*b/gcd(a,b);}
static int max(int a,int b) {return a>b?a:b;}
static int min(int a,int b) {return a<b?a:b;}
static long lmax(long a,long b) {return Math.max(a, b);}
static long lmin(long a,long b) {return Math.min(a, b);}
static long factorial(int i) {return i==1?1:i*factorial(i-1);}
public static void main(String[] args) {
String str=scan.next();
char c[]=str.toCharArray();
System.out.println(c[0]!=c[1]||c[0]!=c[2]||c[1]!=c[2]?"Yes":"No");
}
static int lower_bound(int a[],int key) {
int right=a.length;
int left=0;
while(right-left>0) {
int mid=(right+left)/2;
if(a[mid]<key) {
left=mid;
}
else {
right=mid;
}
}
return left;
}
static int upper_bound(int a[],int key) {
int right=a.length;
int left=0;
while(right-left>0) {
int mid=(right+left)/2;
if(a[mid]<=key) {
left=mid;
}
else {
right=mid;
}
}
return left;
}
static boolean isPrime (long n) {
if (n==2) return true;
if (n<2 || n%2==0) return false;
double d = Math.sqrt(n);
for (int i=3; i<=d; i+=2)if(n%i==0){return false;}
return true;
}
static int upper_division(int a,int b) {
if(a%b==0) {
return a/b;
}
else {
return a/b+1;
}
}
static long lupper_division(long a,long b) {
if(a%b==0) {
return a/b;
}
else {
return a/b+1;
}
}
static int[] setArray(int a) {
int b[]=new int[a];
for(int i=0;i<a;i++) {
b[i]=scan.nextInt();
}
return b;
}
static long[] lsetArray(int a) {
long b[]=new long[a];
for(int i=0;i<a;i++) {
b[i]=scan.nextLong();
}
return b;
}
static String reverce(String str) {
String strr="";
for(int i=str.length()-1;i>=0;i--) {
strr+=str.charAt(i);
}
return strr;
}
public static void printArray(int[] que) {
for(int i=0;i<que.length-1;i++) {
System.out.print(que[i]+" ");
}
System.out.println(que[que.length-1]);
}
public static int[][] doublesort(int[][]a) {
Arrays.sort(a,(x,y)->Integer.compare(x[0],y[0]));
return a;
}
public static long[][] ldoublesort(long[][]a) {
Arrays.sort(a,(x,y)->Long.compare(x[0],y[0]));
return a;
}
static long modpow(long x,long n,long mo) {
long sum=1;
while(n>0) {
if((n&1)==1) {
sum=sum*x%mo;
}
x=x*x%mo;
n>>=1;
}
return sum;
}
public static char[] revch(char ch[]) {
char ret[]=new char[ch.length];
for(int i=ch.length-1,j=0;i>=0;i--,j++) {
ret[j]=ch[i];
}
return ret;
}
public static int[] revint(int ch[]) {
int ret[]=new int[ch.length];
for(int i=ch.length-1,j=0;i>=0;i--,j++) {
ret[j]=ch[i];
}
return ret;
}
public static void warshall_floyd(int v[][],int n) {
for(int k=0;k<n;k++)
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
v[i][j]=min(v[i][j],v[i][k]+v[k][j]);
}
public static long modint(long a,long m) {
long b=m,u=1,v=0;
while(b!=0) {
long t=a/b;
a-=t*b;
long x=a;
a=b;
b=x;
u-=t*v;
x=u;
u=v;
v=x;
}
u%=m;
if(u<0)u+=m;
return u;
}
}
class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b)){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() { return Double.parseDouble(next());}
public char nextchar() {
try { return (char)System.in.read(); } catch(Exception e) {
throw new RuntimeException(e);
}
}
}
| JavaScript | function Main(input) {
if(input=="AAA"||input=="BBB"){
console.log("No")
}else{
console.log("Yes")
}
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
| Yes | Do these codes solve the same problem?
Code 1: import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Scanner;
class UnionFind{
int Parent[];
UnionFind(int n){//Initialize by -1
Parent=new int[n];
Arrays.fill(Parent, -1);
}
int root(int A) {//In which tree is A?
if(Parent[A]<0)return A;
return Parent[A]=root(Parent[A]);
}
int size(int A) {//size of tree which is include A
return -Parent[root(A)];
}
boolean connect(int A,int B) {//Connect A and B
A=root(A);
B=root(B);
if(A==B) return false;
if(size(A)<size(B)) {int C=0;C=B;B=A;A=C;}//SWAP
Parent[A]+=Parent[B];
Parent[B]=A;
return true;
}
}
public class Main {
static FastScanner scan=new FastScanner();
static Scanner scanner=new Scanner(System.in);
static Random rand=new Random();
static long mod=1000000007;
static double eps=0.0000000001;
static int big=Integer.MAX_VALUE;
static long modlcm(long a,long b) {return a*b*modint(gcd(a,b),mod);}
static long gcd (long a, long b) {return b>0?gcd(b,a%b):a;}
static long lcm (long a, long b) {return a*b/gcd(a,b);}
static int max(int a,int b) {return a>b?a:b;}
static int min(int a,int b) {return a<b?a:b;}
static long lmax(long a,long b) {return Math.max(a, b);}
static long lmin(long a,long b) {return Math.min(a, b);}
static long factorial(int i) {return i==1?1:i*factorial(i-1);}
public static void main(String[] args) {
String str=scan.next();
char c[]=str.toCharArray();
System.out.println(c[0]!=c[1]||c[0]!=c[2]||c[1]!=c[2]?"Yes":"No");
}
static int lower_bound(int a[],int key) {
int right=a.length;
int left=0;
while(right-left>0) {
int mid=(right+left)/2;
if(a[mid]<key) {
left=mid;
}
else {
right=mid;
}
}
return left;
}
static int upper_bound(int a[],int key) {
int right=a.length;
int left=0;
while(right-left>0) {
int mid=(right+left)/2;
if(a[mid]<=key) {
left=mid;
}
else {
right=mid;
}
}
return left;
}
static boolean isPrime (long n) {
if (n==2) return true;
if (n<2 || n%2==0) return false;
double d = Math.sqrt(n);
for (int i=3; i<=d; i+=2)if(n%i==0){return false;}
return true;
}
static int upper_division(int a,int b) {
if(a%b==0) {
return a/b;
}
else {
return a/b+1;
}
}
static long lupper_division(long a,long b) {
if(a%b==0) {
return a/b;
}
else {
return a/b+1;
}
}
static int[] setArray(int a) {
int b[]=new int[a];
for(int i=0;i<a;i++) {
b[i]=scan.nextInt();
}
return b;
}
static long[] lsetArray(int a) {
long b[]=new long[a];
for(int i=0;i<a;i++) {
b[i]=scan.nextLong();
}
return b;
}
static String reverce(String str) {
String strr="";
for(int i=str.length()-1;i>=0;i--) {
strr+=str.charAt(i);
}
return strr;
}
public static void printArray(int[] que) {
for(int i=0;i<que.length-1;i++) {
System.out.print(que[i]+" ");
}
System.out.println(que[que.length-1]);
}
public static int[][] doublesort(int[][]a) {
Arrays.sort(a,(x,y)->Integer.compare(x[0],y[0]));
return a;
}
public static long[][] ldoublesort(long[][]a) {
Arrays.sort(a,(x,y)->Long.compare(x[0],y[0]));
return a;
}
static long modpow(long x,long n,long mo) {
long sum=1;
while(n>0) {
if((n&1)==1) {
sum=sum*x%mo;
}
x=x*x%mo;
n>>=1;
}
return sum;
}
public static char[] revch(char ch[]) {
char ret[]=new char[ch.length];
for(int i=ch.length-1,j=0;i>=0;i--,j++) {
ret[j]=ch[i];
}
return ret;
}
public static int[] revint(int ch[]) {
int ret[]=new int[ch.length];
for(int i=ch.length-1,j=0;i>=0;i--,j++) {
ret[j]=ch[i];
}
return ret;
}
public static void warshall_floyd(int v[][],int n) {
for(int k=0;k<n;k++)
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
v[i][j]=min(v[i][j],v[i][k]+v[k][j]);
}
public static long modint(long a,long m) {
long b=m,u=1,v=0;
while(b!=0) {
long t=a/b;
a-=t*b;
long x=a;
a=b;
b=x;
u-=t*v;
x=u;
u=v;
v=x;
}
u%=m;
if(u<0)u+=m;
return u;
}
}
class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b)){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() { return Double.parseDouble(next());}
public char nextchar() {
try { return (char)System.in.read(); } catch(Exception e) {
throw new RuntimeException(e);
}
}
}
Code 2: function Main(input) {
if(input=="AAA"||input=="BBB"){
console.log("No")
}else{
console.log("Yes")
}
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
|
C++ | #include<bits/stdc++.h>
#include <iostream>
#include <list>
#define ll long long int
using namespace std;
int main()
{
int t,m,i,cnt=0;cin>>t;
int ara[t];
for( i=1;i<=t;i++)cin>>ara[i];
for( i=1;i<=t;i+=2)
{
if(ara[i]%2)cnt++;
}
cout<<cnt<<"\n";
}
| Python | # coding: utf-8
# Your code here!
N = input()
if N[0] == N[2]:
print('Yes')
else:
print('No') | No | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
#include <iostream>
#include <list>
#define ll long long int
using namespace std;
int main()
{
int t,m,i,cnt=0;cin>>t;
int ara[t];
for( i=1;i<=t;i++)cin>>ara[i];
for( i=1;i<=t;i+=2)
{
if(ara[i]%2)cnt++;
}
cout<<cnt<<"\n";
}
Code 2: # coding: utf-8
# Your code here!
N = input()
if N[0] == N[2]:
print('Yes')
else:
print('No') |
Python | n = list(map(int, input().split()))
n.sort()
print("YES" if n[0] == 5 and n[1] == 5 and n[2] == 7 else "NO")
| Java | import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
b[i] = a[i];
}
HashMap<Integer, Integer> map = new HashMap<>();
Arrays.sort(b);
int cnt = 1;
for (int i = 0; i < n; i++) {
if(!map.containsKey(b[i])){
map.put(b[i], cnt++);
}
}
long ans = 0L;
BIT bit = new BIT(n);
for (int i = 0; i < n; i++) {
ans += i - bit.sum(map.get(a[i]));
bit.add(map.get(a[i]), 1);
}
System.out.println(ans);
sc.close();
}
}
class BIT {
public int n;
public long[] bit;
public BIT(int n){
this.n = n;
bit = new long[n+1];
}
public long sum(int i){
long s = 0L;
while(0 < i){
s += bit[i];
i -= i & -i;
}
return s;
}
public void add(int i, int x){
while(i <= n){
bit[i] += x;
i += i & -i;
}
}
}
| No | Do these codes solve the same problem?
Code 1: n = list(map(int, input().split()))
n.sort()
print("YES" if n[0] == 5 and n[1] == 5 and n[2] == 7 else "NO")
Code 2: import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
b[i] = a[i];
}
HashMap<Integer, Integer> map = new HashMap<>();
Arrays.sort(b);
int cnt = 1;
for (int i = 0; i < n; i++) {
if(!map.containsKey(b[i])){
map.put(b[i], cnt++);
}
}
long ans = 0L;
BIT bit = new BIT(n);
for (int i = 0; i < n; i++) {
ans += i - bit.sum(map.get(a[i]));
bit.add(map.get(a[i]), 1);
}
System.out.println(ans);
sc.close();
}
}
class BIT {
public int n;
public long[] bit;
public BIT(int n){
this.n = n;
bit = new long[n+1];
}
public long sum(int i){
long s = 0L;
while(0 < i){
s += bit[i];
i -= i & -i;
}
return s;
}
public void add(int i, int x){
while(i <= n){
bit[i] += x;
i += i & -i;
}
}
}
|
Python | import sys
input = sys.stdin.buffer.readline
def convolve(a, b):
"""配列a, bの畳み込みをNTT(number-theoretical transform)によって計算する。
res[k] = (sum{i = 0..k} a[i] * b[k - i]) % MOD
"""
MOD = 998244353
ROOT = 5
def ntt(a, inverse=False):
# バタフライ演算用の配置入れ替え
for i in range(n):
j = 0
for k in range(log_sz):
j |= (i >> k & 1) << (log_sz - 1 - k)
if i < j:
a[i], a[j] = a[j], a[i]
h = pow(ROOT, (MOD - 1) * pow(n, MOD - 2, MOD) % MOD, MOD)
if inverse:
h = pow(h, MOD - 2, MOD)
# バタフライ演算
m = 1
while m < n:
zeta_pow = 1
zeta = pow(h, n // (2 * m), MOD)
for j in range(m):
for k in range(0, n, 2 * m):
s = a[j + k]
t = a[j + k + m] * zeta_pow
a[j + k] = (s + t) % MOD
a[j + k + m] = (s - t) % MOD
zeta_pow *= zeta
zeta_pow %= MOD
m <<= 1
# 逆変換時には配列のサイズの逆元をかける
if inverse:
n_inv = pow(n, MOD - 2, MOD)
for i in range(n):
a[i] *= n_inv
a[i] %= MOD
return a
def intt(a):
return ntt(a, inverse=True)
n = 1 << (len(a) + len(b) - 1).bit_length()
log_sz = n.bit_length() - 1
a = a + [0] * (n - len(a))
b = b + [0] * (n - len(b))
# in-placeで計算を進めることに注意
ntt(a), ntt(b)
for i, val in enumerate(b):
a[i] *= val
a[i] %= MOD
intt(a)
return a
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(*convolve(a, b)[:n + m - 1]) | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;
namespace Program
{
public static class ProblemF
{
static bool SAIKI = false;
static public int numberOfRandomCases = 0;
static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
{
}
static public void Solve()
{
var N = NN;
var M = NN;
var aList = NNList(N);
var bList = NNList(M);
var cList = LIB_NTT.Multiply(aList, bList, 998244353);
Console.WriteLine(cList.Join(" "));
}
class Printer : StreamWriter
{
public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
}
static LIB_FastIO fastio = new LIB_FastIODebug();
static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
static long NN => fastio.Long();
static double ND => fastio.Double();
static string NS => fastio.Scan();
static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
static string Join<T>(this IEnumerable<T> x, string separator = "") => string.Join(separator, x);
static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
static IEnumerator<uint> _xsi = _xsc();
static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
}
}
namespace Library {
class LIB_FastIO
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LIB_FastIO() { str = Console.OpenStandardInput(); }
readonly Stream str;
readonly byte[] buf = new byte[1024];
int len, ptr;
public bool isEof = false;
public bool IsEndOfStream
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return isEof; }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
byte read()
{
if (isEof) throw new EndOfStreamException();
if (ptr >= len)
{
ptr = 0;
if ((len = str.Read(buf, 0, 1024)) <= 0)
{
isEof = true;
return 0;
}
}
return buf[ptr++];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
char Char()
{
byte b = 0;
do b = read();
while (b < 33 || 126 < b);
return (char)b;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
virtual public string Scan()
{
var sb = new StringBuilder();
for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
sb.Append(b);
return sb.ToString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
virtual public long Long()
{
long ret = 0; byte b = 0; var ng = false;
do b = read();
while (b != '-' && (b < '0' || '9' < b));
if (b == '-') { ng = true; b = read(); }
for (; true; b = read())
{
if (b < '0' || '9' < b)
return ng ? -ret : ret;
else ret = ret * 10 + b - '0';
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
}
class LIB_FastIODebug : LIB_FastIO
{
Queue<string> param = new Queue<string>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LIB_FastIODebug() { }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string Scan() => NextString();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override long Long() => long.Parse(NextString());
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override double Double() => double.Parse(NextString());
}
class LIB_NTT
{
uint mod;
uint root;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
LIB_NTT(uint mod, uint root) { this.mod = mod; this.root = root; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint add(uint x, uint y) => (x + y < mod) ? (x + y) : (x + y - mod);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint sub(uint x, uint y) => (x >= y) ? (x - y) : (mod - y + x);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint mul(uint x, uint y) => (uint)((ulong)x * y % mod);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint pow(uint x, uint n)
{
uint res = 1;
while (n > 0)
{
if ((n & 1) != 0) res = mul(res, x);
x = mul(x, x);
n >>= 1;
}
return res;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint inverse(uint x)
{
long b = mod, r = 1, u = 0, t = 0, x2 = x;
while (b > 0)
{
var q = x2 / b;
t = u;
u = r - q * u;
r = t;
t = b;
b = x2 - q * b;
x2 = t;
}
return (uint)(r < 0 ? r + mod : r);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void ntt(ref uint[] a, bool rev = false)
{
var n = (uint)a.Length;
if (n == 1) return;
var b = new uint[n];
var s = pow(root, rev ? (mod - 1 - (mod - 1) / n) : (mod - 1) / n);
var kp = Enumerable.Repeat((uint)1, (int)(n / 2 + 1)).ToArray();
uint i, j, k, l, r;
for (i = 0; i < n / 2; ++i) kp[i + 1] = mul(kp[i], s);
for (i = 1, l = n / 2; i < n; i <<= 1, l >>= 1)
{
for (j = 0, r = 0; j < l; ++j, r += i)
{
for (k = 0, s = kp[i * j]; k < i; ++k)
{
var p = a[k + r]; var q = a[k + r + n / 2];
b[k + 2 * r] = add(p, q);
b[k + 2 * r + i] = mul(sub(p, q), s);
}
}
var t = a; a = b; b = t;
}
if (rev)
{
s = inverse(n);
for (i = 0; i < n; ++i) a[i] = mul(a[i], s);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static uint[] Multiply(uint[] a, uint[] b, uint mod, uint root)
{
var n = a.Length + b.Length - 1;
var t = 1;
while (t < n) t <<= 1;
var na = new uint[t];
var nb = new uint[t];
for (var i = 0; i < a.Length; ++i) na[i] = a[i];
for (var i = 0; i < b.Length; ++i) nb[i] = b[i];
var ntt = new LIB_NTT(mod, root);
ntt.ntt(ref na);
ntt.ntt(ref nb);
for (var i = 0; i < t; ++i) na[i] = ntt.mul(na[i], nb[i]);
ntt.ntt(ref na, true);
return na.Take(n).ToArray();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static public long[] Multiply(long[] a, long[] b) => Multiply(a.Select(e => (uint)e).ToArray(), b.Select(e => (uint)e).ToArray(), 998244353, 3).Select(e => (long)e).ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static public long[] Multiply(long[] a, long[] b, long mod)
{
if (mod == 998244353) return Multiply(a, b);
var m1 = new LIB_NTT(1045430273, 3);
var m2 = new LIB_NTT(1051721729, 6);
var m3 = new LIB_NTT(1053818881, 7);
var uinta = a.Select(e => (uint)e).ToArray();
var uintb = b.Select(e => (uint)e).ToArray();
var x = Multiply(uinta, uintb, m1.mod, m1.root);
var y = Multiply(uinta, uintb, m2.mod, m2.root);
var z = Multiply(uinta, uintb, m3.mod, m3.root);
var m1_inv_m2 = m2.inverse(m1.mod);
var m12_inv_m3 = m3.inverse(m3.mul(m1.mod, m2.mod));
var m12_mod = (long)m1.mod * m2.mod % mod;
var ret = new long[x.Length];
for (var i = 0; i < x.Length; ++i)
{
var v1 = m2.mul(m2.sub(m2.add(y[i], m2.mod), x[i]), m1_inv_m2);
var v2 = m3.mul(m3.sub(m3.sub(m3.add(z[i], m3.mod), x[i]), m3.mul(m1.mod, v1)), m12_inv_m3);
ret[i] = (x[i] + ((long)m1.mod * v1 % mod) + ((long)m12_mod * v2 % mod)) % mod;
}
return ret;
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: import sys
input = sys.stdin.buffer.readline
def convolve(a, b):
"""配列a, bの畳み込みをNTT(number-theoretical transform)によって計算する。
res[k] = (sum{i = 0..k} a[i] * b[k - i]) % MOD
"""
MOD = 998244353
ROOT = 5
def ntt(a, inverse=False):
# バタフライ演算用の配置入れ替え
for i in range(n):
j = 0
for k in range(log_sz):
j |= (i >> k & 1) << (log_sz - 1 - k)
if i < j:
a[i], a[j] = a[j], a[i]
h = pow(ROOT, (MOD - 1) * pow(n, MOD - 2, MOD) % MOD, MOD)
if inverse:
h = pow(h, MOD - 2, MOD)
# バタフライ演算
m = 1
while m < n:
zeta_pow = 1
zeta = pow(h, n // (2 * m), MOD)
for j in range(m):
for k in range(0, n, 2 * m):
s = a[j + k]
t = a[j + k + m] * zeta_pow
a[j + k] = (s + t) % MOD
a[j + k + m] = (s - t) % MOD
zeta_pow *= zeta
zeta_pow %= MOD
m <<= 1
# 逆変換時には配列のサイズの逆元をかける
if inverse:
n_inv = pow(n, MOD - 2, MOD)
for i in range(n):
a[i] *= n_inv
a[i] %= MOD
return a
def intt(a):
return ntt(a, inverse=True)
n = 1 << (len(a) + len(b) - 1).bit_length()
log_sz = n.bit_length() - 1
a = a + [0] * (n - len(a))
b = b + [0] * (n - len(b))
# in-placeで計算を進めることに注意
ntt(a), ntt(b)
for i, val in enumerate(b):
a[i] *= val
a[i] %= MOD
intt(a)
return a
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(*convolve(a, b)[:n + m - 1])
Code 2: using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;
namespace Program
{
public static class ProblemF
{
static bool SAIKI = false;
static public int numberOfRandomCases = 0;
static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
{
}
static public void Solve()
{
var N = NN;
var M = NN;
var aList = NNList(N);
var bList = NNList(M);
var cList = LIB_NTT.Multiply(aList, bList, 998244353);
Console.WriteLine(cList.Join(" "));
}
class Printer : StreamWriter
{
public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
}
static LIB_FastIO fastio = new LIB_FastIODebug();
static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
static long NN => fastio.Long();
static double ND => fastio.Double();
static string NS => fastio.Scan();
static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
static string Join<T>(this IEnumerable<T> x, string separator = "") => string.Join(separator, x);
static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
static IEnumerator<uint> _xsi = _xsc();
static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
}
}
namespace Library {
class LIB_FastIO
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LIB_FastIO() { str = Console.OpenStandardInput(); }
readonly Stream str;
readonly byte[] buf = new byte[1024];
int len, ptr;
public bool isEof = false;
public bool IsEndOfStream
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return isEof; }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
byte read()
{
if (isEof) throw new EndOfStreamException();
if (ptr >= len)
{
ptr = 0;
if ((len = str.Read(buf, 0, 1024)) <= 0)
{
isEof = true;
return 0;
}
}
return buf[ptr++];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
char Char()
{
byte b = 0;
do b = read();
while (b < 33 || 126 < b);
return (char)b;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
virtual public string Scan()
{
var sb = new StringBuilder();
for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
sb.Append(b);
return sb.ToString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
virtual public long Long()
{
long ret = 0; byte b = 0; var ng = false;
do b = read();
while (b != '-' && (b < '0' || '9' < b));
if (b == '-') { ng = true; b = read(); }
for (; true; b = read())
{
if (b < '0' || '9' < b)
return ng ? -ret : ret;
else ret = ret * 10 + b - '0';
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
}
class LIB_FastIODebug : LIB_FastIO
{
Queue<string> param = new Queue<string>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LIB_FastIODebug() { }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string Scan() => NextString();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override long Long() => long.Parse(NextString());
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override double Double() => double.Parse(NextString());
}
class LIB_NTT
{
uint mod;
uint root;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
LIB_NTT(uint mod, uint root) { this.mod = mod; this.root = root; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint add(uint x, uint y) => (x + y < mod) ? (x + y) : (x + y - mod);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint sub(uint x, uint y) => (x >= y) ? (x - y) : (mod - y + x);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint mul(uint x, uint y) => (uint)((ulong)x * y % mod);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint pow(uint x, uint n)
{
uint res = 1;
while (n > 0)
{
if ((n & 1) != 0) res = mul(res, x);
x = mul(x, x);
n >>= 1;
}
return res;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
uint inverse(uint x)
{
long b = mod, r = 1, u = 0, t = 0, x2 = x;
while (b > 0)
{
var q = x2 / b;
t = u;
u = r - q * u;
r = t;
t = b;
b = x2 - q * b;
x2 = t;
}
return (uint)(r < 0 ? r + mod : r);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void ntt(ref uint[] a, bool rev = false)
{
var n = (uint)a.Length;
if (n == 1) return;
var b = new uint[n];
var s = pow(root, rev ? (mod - 1 - (mod - 1) / n) : (mod - 1) / n);
var kp = Enumerable.Repeat((uint)1, (int)(n / 2 + 1)).ToArray();
uint i, j, k, l, r;
for (i = 0; i < n / 2; ++i) kp[i + 1] = mul(kp[i], s);
for (i = 1, l = n / 2; i < n; i <<= 1, l >>= 1)
{
for (j = 0, r = 0; j < l; ++j, r += i)
{
for (k = 0, s = kp[i * j]; k < i; ++k)
{
var p = a[k + r]; var q = a[k + r + n / 2];
b[k + 2 * r] = add(p, q);
b[k + 2 * r + i] = mul(sub(p, q), s);
}
}
var t = a; a = b; b = t;
}
if (rev)
{
s = inverse(n);
for (i = 0; i < n; ++i) a[i] = mul(a[i], s);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static uint[] Multiply(uint[] a, uint[] b, uint mod, uint root)
{
var n = a.Length + b.Length - 1;
var t = 1;
while (t < n) t <<= 1;
var na = new uint[t];
var nb = new uint[t];
for (var i = 0; i < a.Length; ++i) na[i] = a[i];
for (var i = 0; i < b.Length; ++i) nb[i] = b[i];
var ntt = new LIB_NTT(mod, root);
ntt.ntt(ref na);
ntt.ntt(ref nb);
for (var i = 0; i < t; ++i) na[i] = ntt.mul(na[i], nb[i]);
ntt.ntt(ref na, true);
return na.Take(n).ToArray();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static public long[] Multiply(long[] a, long[] b) => Multiply(a.Select(e => (uint)e).ToArray(), b.Select(e => (uint)e).ToArray(), 998244353, 3).Select(e => (long)e).ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static public long[] Multiply(long[] a, long[] b, long mod)
{
if (mod == 998244353) return Multiply(a, b);
var m1 = new LIB_NTT(1045430273, 3);
var m2 = new LIB_NTT(1051721729, 6);
var m3 = new LIB_NTT(1053818881, 7);
var uinta = a.Select(e => (uint)e).ToArray();
var uintb = b.Select(e => (uint)e).ToArray();
var x = Multiply(uinta, uintb, m1.mod, m1.root);
var y = Multiply(uinta, uintb, m2.mod, m2.root);
var z = Multiply(uinta, uintb, m3.mod, m3.root);
var m1_inv_m2 = m2.inverse(m1.mod);
var m12_inv_m3 = m3.inverse(m3.mul(m1.mod, m2.mod));
var m12_mod = (long)m1.mod * m2.mod % mod;
var ret = new long[x.Length];
for (var i = 0; i < x.Length; ++i)
{
var v1 = m2.mul(m2.sub(m2.add(y[i], m2.mod), x[i]), m1_inv_m2);
var v2 = m3.mul(m3.sub(m3.sub(m3.add(z[i], m3.mod), x[i]), m3.mul(m1.mod, v1)), m12_inv_m3);
ret[i] = (x[i] + ((long)m1.mod * v1 % mod) + ((long)m12_mod * v2 % mod)) % mod;
}
return ret;
}
}
}
|
C++ | #include <iostream>
using std::cin;
using std::cout;
using std::endl;
static int const MODULO = 1e9 + 7;
static inline long
mmul(long a, long b)
{
long ret = a * b;
return ret < MODULO ? ret : ret % MODULO;
}
int
main()
{
int N;
cin >> N;
long p = 1;
for (int i = 1; i <= N; i++)
{
p = mmul(p, i);
}
cout << p << endl;
return 0;
}
| C | #include<stdio.h>
int main(){
int a[3];
int b;
int c;
scanf("%d",&a[0]);
scanf("%d",&a[1]);
b = a[0]/(2*a[1]+1);
c = a[0]%(2*a[1]+1);
if(c == 0){
printf("%d",b);
}else{
printf("%d",b+1);
}
} | No | Do these codes solve the same problem?
Code 1: #include <iostream>
using std::cin;
using std::cout;
using std::endl;
static int const MODULO = 1e9 + 7;
static inline long
mmul(long a, long b)
{
long ret = a * b;
return ret < MODULO ? ret : ret % MODULO;
}
int
main()
{
int N;
cin >> N;
long p = 1;
for (int i = 1; i <= N; i++)
{
p = mmul(p, i);
}
cout << p << endl;
return 0;
}
Code 2: #include<stdio.h>
int main(){
int a[3];
int b;
int c;
scanf("%d",&a[0]);
scanf("%d",&a[1]);
b = a[0]/(2*a[1]+1);
c = a[0]%(2*a[1]+1);
if(c == 0){
printf("%d",b);
}else{
printf("%d",b+1);
}
} |
C++ | #include <iostream>
#include <iomanip>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cctype>
#include <cassert>
#include <climits>
#include <string>
#include <bitset>
#include <cfloat>
#include <unordered_set>
#include <cstring>
#pragma GCC optimize("Ofast")
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int, int>> vpii;
typedef vector<vector<int>> vvi;
typedef vector<vector<char>> vvc;
typedef vector<vector<string>> vvs;
typedef vector<vector<ll>> vvll;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i <= (n); ++i)
#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)
#define drep(i, n) for (int i = (n)-1; i >= 0; --i)
#define fin(ans) cout << (ans) << '\n'
#define mp(p, q) make_pair(p, q)
#define pb(n) push_back(n)
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define Sort(a) sort(a.begin(), a.end())
#define Rort(a) sort(a.rbegin(), a.rend())
#define MATHPI acos(-1)
#define itn int;
int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
template <class T>
inline bool chmax(T &a, T b)
{
if (a < b)
{
a = b;
return 1;
}
return 0;
}
template <class T>
inline bool chmin(T &a, T b)
{
if (a > b)
{
a = b;
return 1;
}
return 0;
}
struct io
{
io()
{
ios::sync_with_stdio(false);
cin.tie(0);
}
};
const int INF = INT_MAX;
const ll LLINF = 1LL << 60;
const ll MOD = 1000000007;
const double EPS = 1e-9;
int main() {
int n,m;
cin >> n >> m;
vi s(m);
vi c(m);
rep(i,m) cin >> s[i] >> c[i];
rep(i,1000){
string str = to_string(i);
bool flg = true;
if (str.size() != n) flg = false;
for (int j=0; j<m; j++){
if (str[s[j]-1] != (char)(c[j]+'0')) flg = false;
}
if (flg){
cout << i;
return 0;
}
}
cout << -1;
} | Python | a=input()
b=input()
c=input()
print(a[0]+b[1]+c[2]) | No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <iomanip>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cctype>
#include <cassert>
#include <climits>
#include <string>
#include <bitset>
#include <cfloat>
#include <unordered_set>
#include <cstring>
#pragma GCC optimize("Ofast")
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int, int>> vpii;
typedef vector<vector<int>> vvi;
typedef vector<vector<char>> vvc;
typedef vector<vector<string>> vvs;
typedef vector<vector<ll>> vvll;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i <= (n); ++i)
#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)
#define drep(i, n) for (int i = (n)-1; i >= 0; --i)
#define fin(ans) cout << (ans) << '\n'
#define mp(p, q) make_pair(p, q)
#define pb(n) push_back(n)
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define Sort(a) sort(a.begin(), a.end())
#define Rort(a) sort(a.rbegin(), a.rend())
#define MATHPI acos(-1)
#define itn int;
int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
template <class T>
inline bool chmax(T &a, T b)
{
if (a < b)
{
a = b;
return 1;
}
return 0;
}
template <class T>
inline bool chmin(T &a, T b)
{
if (a > b)
{
a = b;
return 1;
}
return 0;
}
struct io
{
io()
{
ios::sync_with_stdio(false);
cin.tie(0);
}
};
const int INF = INT_MAX;
const ll LLINF = 1LL << 60;
const ll MOD = 1000000007;
const double EPS = 1e-9;
int main() {
int n,m;
cin >> n >> m;
vi s(m);
vi c(m);
rep(i,m) cin >> s[i] >> c[i];
rep(i,1000){
string str = to_string(i);
bool flg = true;
if (str.size() != n) flg = false;
for (int j=0; j<m; j++){
if (str[s[j]-1] != (char)(c[j]+'0')) flg = false;
}
if (flg){
cout << i;
return 0;
}
}
cout << -1;
}
Code 2: a=input()
b=input()
c=input()
print(a[0]+b[1]+c[2]) |
C | #include<stdio.h>
int dp[100][256][101];
long long mod,p[101];
int main(){
int n,k,i,a[255],j,ii;
long long sum=0;
scanf("%d %d",&n,&k);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
mod=1000000007;
p[0]=1;
for(i=1;i<=n;i++){
p[i]=i*p[i-1];
p[i]%=mod;
}
dp[0][0][0]=1;
dp[0][a[0]][1]=1;
for(i=1;i<n;i++){
for(j=0;j<256;j++){
for(ii=0;ii<i+1;ii++){
dp[i][j][ii+1]+=dp[i-1][j^a[i]][ii];
dp[i][j][ii+1]%=mod;
dp[i][j][ii]+=dp[i-1][j][ii];
dp[i][j][ii]%=mod;
}
}
}
for(i=1;i<=n;i++){
sum+=dp[n-1][k][i]*p[i];
sum%=mod;
}
printf("%lld\n",sum);
return 0;
}
| C++ | #include <string>
#include <vector>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
#include<functional>
#include<list>
#include<deque>
#include<bitset>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<cstring>
#include<sstream>
#include<complex>
#include<iomanip>
#include<numeric>
#include<cassert>
#define X first
#define Y second
#define pb push_back
#define rep(X,Y) for (int (X) = 0;(X) < (Y);++(X))
#define reps(X,S,Y) for (int (X) = S;(X) < (Y);++(X))
#define rrep(X,Y) for (int (X) = (Y)-1;(X) >=0;--(X))
#define repe(X,Y) for ((X) = 0;(X) < (Y);++(X))
#define peat(X,Y) for (;(X) < (Y);++(X))
#define all(X) (X).begin(),(X).end()
#define rall(X) (X).rbegin(),(X).rend()
#define eb emplace_back
#define UNIQUE(X) (X).erase(unique(all(X)),(X).end())
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template<class T> using vv=vector<vector<T>>;
template<class T> ostream& operator<<(ostream &os, const vector<T> &t) {
os<<"{"; rep(i,t.size()) {os<<t[i]<<",";} os<<"}"<<endl; return os;}
template<class S, class T> ostream& operator<<(ostream &os, const pair<S,T> &t) { return os<<"("<<t.first<<","<<t.second<<")";}
template<class T> inline bool MX(T &l,const T &r){return l<r?l=r,1:0;}
template<class T> inline bool MN(T &l,const T &r){return l>r?l=r,1:0;}
const ll MOD=1e9+7;
ll dp[111][111][333];
int main(){
ios_base::sync_with_stdio(false);
cout<<fixed<<setprecision(0);
int n,t;
cin>>n>>t;
vector<int> a(n);
rep(i,n) cin>>a[i];
dp[0][0][0]=1;
rep(i,n)rep(j,n+1)rep(k,256){
(dp[i+1][j+1][k^a[i]]+=dp[i][j][k])%=MOD;
(dp[i+1][j][k]+=dp[i][j][k])%=MOD;
}
//rep(k,n+1){rep(i,n+1){rep(j,16) cout<<dp[k][i][j]<<",";cout<<endl;}cout<<endl;}
ll re=(t==0),f=1;
reps(i,1,n+1){
(f*=i)%=MOD;
//cout<<dp[n][i][t]<<endl;
(re+=dp[n][i][t]*f%MOD)%=MOD;
}
cout<<re<<endl;
return 0;
}
| Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
int dp[100][256][101];
long long mod,p[101];
int main(){
int n,k,i,a[255],j,ii;
long long sum=0;
scanf("%d %d",&n,&k);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
mod=1000000007;
p[0]=1;
for(i=1;i<=n;i++){
p[i]=i*p[i-1];
p[i]%=mod;
}
dp[0][0][0]=1;
dp[0][a[0]][1]=1;
for(i=1;i<n;i++){
for(j=0;j<256;j++){
for(ii=0;ii<i+1;ii++){
dp[i][j][ii+1]+=dp[i-1][j^a[i]][ii];
dp[i][j][ii+1]%=mod;
dp[i][j][ii]+=dp[i-1][j][ii];
dp[i][j][ii]%=mod;
}
}
}
for(i=1;i<=n;i++){
sum+=dp[n-1][k][i]*p[i];
sum%=mod;
}
printf("%lld\n",sum);
return 0;
}
Code 2: #include <string>
#include <vector>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
#include<functional>
#include<list>
#include<deque>
#include<bitset>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<cstring>
#include<sstream>
#include<complex>
#include<iomanip>
#include<numeric>
#include<cassert>
#define X first
#define Y second
#define pb push_back
#define rep(X,Y) for (int (X) = 0;(X) < (Y);++(X))
#define reps(X,S,Y) for (int (X) = S;(X) < (Y);++(X))
#define rrep(X,Y) for (int (X) = (Y)-1;(X) >=0;--(X))
#define repe(X,Y) for ((X) = 0;(X) < (Y);++(X))
#define peat(X,Y) for (;(X) < (Y);++(X))
#define all(X) (X).begin(),(X).end()
#define rall(X) (X).rbegin(),(X).rend()
#define eb emplace_back
#define UNIQUE(X) (X).erase(unique(all(X)),(X).end())
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template<class T> using vv=vector<vector<T>>;
template<class T> ostream& operator<<(ostream &os, const vector<T> &t) {
os<<"{"; rep(i,t.size()) {os<<t[i]<<",";} os<<"}"<<endl; return os;}
template<class S, class T> ostream& operator<<(ostream &os, const pair<S,T> &t) { return os<<"("<<t.first<<","<<t.second<<")";}
template<class T> inline bool MX(T &l,const T &r){return l<r?l=r,1:0;}
template<class T> inline bool MN(T &l,const T &r){return l>r?l=r,1:0;}
const ll MOD=1e9+7;
ll dp[111][111][333];
int main(){
ios_base::sync_with_stdio(false);
cout<<fixed<<setprecision(0);
int n,t;
cin>>n>>t;
vector<int> a(n);
rep(i,n) cin>>a[i];
dp[0][0][0]=1;
rep(i,n)rep(j,n+1)rep(k,256){
(dp[i+1][j+1][k^a[i]]+=dp[i][j][k])%=MOD;
(dp[i+1][j][k]+=dp[i][j][k])%=MOD;
}
//rep(k,n+1){rep(i,n+1){rep(j,16) cout<<dp[k][i][j]<<",";cout<<endl;}cout<<endl;}
ll re=(t==0),f=1;
reps(i,1,n+1){
(f*=i)%=MOD;
//cout<<dp[n][i][t]<<endl;
(re+=dp[n][i][t]*f%MOD)%=MOD;
}
cout<<re<<endl;
return 0;
}
|
JavaScript | function main(input) {
var temp = input.split('\n');
var house = [];
var bar = "";
for (var l =0; l < 20; l++) {
bar += "#";
}
for (var j =0; j < 12; j++) {
house[j] = Array(10).fill(0);
}
for (var i = 0; i < temp[0]; i++) {
var arr = temp[(i+1)].split(' ').map(Number);
var b = arr[0];
var f = arr[1];
var r = arr[2];
var v = arr[3];
house[((b-1)*3)+f-1][(r-1)] += v;
}
for (var k = 0; k < house.length; k++) {
console.log(" "+house[k].join(' '));
if((k+1)%3 == 0 && k != 0 && k != house.length-1) {
console.log(bar);
}
}
}
var x = require('fs').readFileSync('/dev/stdin', 'utf-8');
main(x);
| Kotlin | fun main(args: Array<String>) {
val n = readLine()!!.toInt()
val a = arrayListOf<ArrayList<ArrayList<Int>>>()
for (i in 0 until 4) {
a.add(ArrayList())
for (j in 0 until 3) {
a[i].add(ArrayList())
for (k in 0 until 10) {
a[i][j].add(0)
}
}
}
for (i in 0 until n) {
val (b, f, r, v) = readLine()!!.split(" ").map { it.toInt() - 1 }
a[b][f][r] += v + 1
}
for (i in 0 until 4) {
if (i != 0) println("#".repeat(20))
for (j in 0 until 3) {
println(" " + a[i][j].joinToString(" "))
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: function main(input) {
var temp = input.split('\n');
var house = [];
var bar = "";
for (var l =0; l < 20; l++) {
bar += "#";
}
for (var j =0; j < 12; j++) {
house[j] = Array(10).fill(0);
}
for (var i = 0; i < temp[0]; i++) {
var arr = temp[(i+1)].split(' ').map(Number);
var b = arr[0];
var f = arr[1];
var r = arr[2];
var v = arr[3];
house[((b-1)*3)+f-1][(r-1)] += v;
}
for (var k = 0; k < house.length; k++) {
console.log(" "+house[k].join(' '));
if((k+1)%3 == 0 && k != 0 && k != house.length-1) {
console.log(bar);
}
}
}
var x = require('fs').readFileSync('/dev/stdin', 'utf-8');
main(x);
Code 2: fun main(args: Array<String>) {
val n = readLine()!!.toInt()
val a = arrayListOf<ArrayList<ArrayList<Int>>>()
for (i in 0 until 4) {
a.add(ArrayList())
for (j in 0 until 3) {
a[i].add(ArrayList())
for (k in 0 until 10) {
a[i][j].add(0)
}
}
}
for (i in 0 until n) {
val (b, f, r, v) = readLine()!!.split(" ").map { it.toInt() - 1 }
a[b][f][r] += v + 1
}
for (i in 0 until 4) {
if (i != 0) println("#".repeat(20))
for (j in 0 until 3) {
println(" " + a[i][j].joinToString(" "))
}
}
}
|
Python | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np
N = int(readline())
A = np.array(read().split(), np.int64)
I = np.argsort(A)[::-1].tolist()
A = A[I].tolist()
dp = np.zeros(1, np.int64)
for n, (i, x) in enumerate(zip(I, A)):
newdp = np.zeros(len(dp) + 1, np.int64)
left_ind = np.arange(len(dp))
right_ind = N - 1 - n + left_ind
left_cost = x * np.abs(left_ind - i)
right_cost = x * np.abs(right_ind - i)
np.maximum(newdp[:-1], dp + right_cost, out=newdp[:-1])
np.maximum(newdp[1:], dp + left_cost, out=newdp[1:])
dp = newdp
print(dp.max())
| PHP | <?php
$N = (int)trim(fgets(STDIN));
$A = explode(' ', fgets(STDIN));
$A = array_map(function ($a) {
return (int)$a;
}, $A);
$ans = 0;
$dp = [];
$dp[0][0] = 0;
for ($i = 0; $i < $N; $i++) {
$max_A = max($A);
$index = array_keys($A, $max_A)[0];
$A[$index] = 0;
$dp[$i + 1][0] = $dp[$i][0] + $max_A * abs($N - ($i + 1) - $index);
for ($l = 0; $l < $i; $l++) {
$dp[$i + 1][$l + 1] = max($dp[$i][$l + 1] + $max_A * abs(($N - ($i - $l)) - $index), $dp[$i][$l] + $max_A * abs($index - $l));
}
$dp[$i + 1][$i + 1] = $dp[$i][$i] + $max_A * abs($index - $i);
}
for ($i = 0; $i <= $N; $i++) {
$ans = max($dp[$N][$i], $ans);
}
echo $ans; | Yes | Do these codes solve the same problem?
Code 1: import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np
N = int(readline())
A = np.array(read().split(), np.int64)
I = np.argsort(A)[::-1].tolist()
A = A[I].tolist()
dp = np.zeros(1, np.int64)
for n, (i, x) in enumerate(zip(I, A)):
newdp = np.zeros(len(dp) + 1, np.int64)
left_ind = np.arange(len(dp))
right_ind = N - 1 - n + left_ind
left_cost = x * np.abs(left_ind - i)
right_cost = x * np.abs(right_ind - i)
np.maximum(newdp[:-1], dp + right_cost, out=newdp[:-1])
np.maximum(newdp[1:], dp + left_cost, out=newdp[1:])
dp = newdp
print(dp.max())
Code 2: <?php
$N = (int)trim(fgets(STDIN));
$A = explode(' ', fgets(STDIN));
$A = array_map(function ($a) {
return (int)$a;
}, $A);
$ans = 0;
$dp = [];
$dp[0][0] = 0;
for ($i = 0; $i < $N; $i++) {
$max_A = max($A);
$index = array_keys($A, $max_A)[0];
$A[$index] = 0;
$dp[$i + 1][0] = $dp[$i][0] + $max_A * abs($N - ($i + 1) - $index);
for ($l = 0; $l < $i; $l++) {
$dp[$i + 1][$l + 1] = max($dp[$i][$l + 1] + $max_A * abs(($N - ($i - $l)) - $index), $dp[$i][$l] + $max_A * abs($index - $l));
}
$dp[$i + 1][$i + 1] = $dp[$i][$i] + $max_A * abs($index - $i);
}
for ($i = 0; $i <= $N; $i++) {
$ans = max($dp[$N][$i], $ans);
}
echo $ans; |
Kotlin | fun main(args: Array<String>) {
val (H, W) = readInputLine().split(" ").map { it.toInt() }
readInputLine()
val aList = readInputLine().split(" ").map { it.toInt() }
val ans = Array(H, { IntArray(W) } )
var nowH = 0
var nowW = 0
for ((index, a) in aList.withIndex()) {
for (j in 1..a) {
ans[nowH][nowW] = index + 1
if (nowH % 2 == 0) {
nowW++
if (nowW >= W) {
nowW--
nowH++
}
} else {
nowW--
if (nowW < 0) {
nowW++
nowH++
}
}
}
}
for (a in ans) {
println(a.joinToString(" "))
}
}
fun readInputLine(): String {
return readLine()!!
}
| PHP | <?php
fscanf(STDIN, "%d %d", $h, $w);
fscanf(STDIN, "%d", $n);
$a = explode(' ', trim(fgets(STDIN)));
$x = $y = 0;
for ($i = 0; $i < $n; $i++) {
$p = $i + 1;
while ($a[$i]--) {
$c[$x][$y] = $p;
if ($y == $w - 1) {
$x++;
$y = 0;
} else {
$y++;
}
}
}
for ($i = 0; $i < $h; $i++) {
if ($i % 2) krsort($c[$i]);
$ans[] = implode(' ', $c[$i]);
}
echo implode("\n", $ans); | Yes | Do these codes solve the same problem?
Code 1: fun main(args: Array<String>) {
val (H, W) = readInputLine().split(" ").map { it.toInt() }
readInputLine()
val aList = readInputLine().split(" ").map { it.toInt() }
val ans = Array(H, { IntArray(W) } )
var nowH = 0
var nowW = 0
for ((index, a) in aList.withIndex()) {
for (j in 1..a) {
ans[nowH][nowW] = index + 1
if (nowH % 2 == 0) {
nowW++
if (nowW >= W) {
nowW--
nowH++
}
} else {
nowW--
if (nowW < 0) {
nowW++
nowH++
}
}
}
}
for (a in ans) {
println(a.joinToString(" "))
}
}
fun readInputLine(): String {
return readLine()!!
}
Code 2: <?php
fscanf(STDIN, "%d %d", $h, $w);
fscanf(STDIN, "%d", $n);
$a = explode(' ', trim(fgets(STDIN)));
$x = $y = 0;
for ($i = 0; $i < $n; $i++) {
$p = $i + 1;
while ($a[$i]--) {
$c[$x][$y] = $p;
if ($y == $w - 1) {
$x++;
$y = 0;
} else {
$y++;
}
}
}
for ($i = 0; $i < $h; $i++) {
if ($i % 2) krsort($c[$i]);
$ans[] = implode(' ', $c[$i]);
}
echo implode("\n", $ans); |
Kotlin | import java.util.*
import kotlin.*
import java.io.InputStream
import java.lang.NumberFormatException
import java.lang.StringBuilder
fun main(args: Array<String>) {
Program().solve()
}
class Program {
fun f(b: Long, n: Long): Long = if (n < b) n else f(b, n / b) + n % b
fun solve() {
val sc = FastScanner()
val n = sc.nextLong()
val s = sc.nextLong()
// b <= √n nは三桁以上 実際に計算
var a = 2L
while (a * a <= n) {
if (f(a, n) == s) {
println(a)
return
}
a++
}
// √n < b <= n nは2桁
// s = floor(n/b) + n%b
// floor(n/b) * b = n-(s-floor(n/b))
// b = n-(s-floor(n/b)) /(floor(n/b))
for (nPerB in a - 1 downTo 1) {
val t = n - (s - nPerB)
if (t % nPerB == 0L) {
val b = t / nPerB
if (b in a..n && f(b, n) == s) {
println(b)
return
}
}
}
// n < b nは1桁
// b = n+1 (s == n)
if (s == n) {
println(n + 1)
return
}
println(-1)
}
}
class FastScanner {
companion object {
val input: InputStream = System.`in`
val buffer = ByteArray(1024) { 0 }
fun isPrintableChar(c: Int): Boolean = c in 33..126
}
var ptr = 0
var buflen = 0
private fun hasNextByte(): Boolean {
if (ptr < buflen) {
return true
} else {
ptr = 0
buflen = input.read(buffer)
if (buflen <= 0) {
return false
}
}
return true
}
private fun readByte(): Int = if (hasNextByte()) buffer[ptr++].toInt() else -1
private fun skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr].toInt())) ptr++
}
fun hasNext(): Boolean {
skipUnprintable()
return hasNextByte()
}
fun next(): String {
if (!hasNext()) throw NoSuchElementException()
val sb = StringBuilder()
var b = readByte()
while (isPrintableChar(b)) {
sb.appendCodePoint(b)
b = readByte()
}
return sb.toString()
}
fun nextInt(): Int {
if (!hasNext()) throw NoSuchElementException()
var n = 0
var b = readByte()
// '-' = 45
val minus = b == 45
if (minus) {
b = readByte()
}
// '0' = 48 '9' = 57
if (b !in 48..57) {
throw NumberFormatException()
}
while (true) {
if (b in 48..57) {
n *= 10
n += b - 48
} else if (b == -1 || !isPrintableChar(b)) {
return if (minus) -n else n
} else {
throw NumberFormatException()
}
b = readByte()
}
}
fun nextLong(): Long {
if (!hasNext()) throw NoSuchElementException()
var n = 0L
var b = readByte()
// '-' = 45
val minus = b == 45
if (minus) {
b = readByte()
}
// '0' = 48 '9' = 57
if (b !in 48..57) {
throw NumberFormatException()
}
while (true) {
if (b in 48..57) {
n *= 10
n += b - 48
} else if (b == -1 || !isPrintableChar(b)) {
return if (minus) -n else n
} else {
throw NumberFormatException()
}
b = readByte()
}
}
fun nextDouble(): Double = next().toDouble()
}
| Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main(){
n := nextInt64()
s := nextInt64()
var ans int64
if s > n {
// s > nである場合、該当するbは存在しない
fmt.Println(-1)
os.Exit(0)
} else if s == n {
// sとnが等しい場合、n+1が最小のbとなる
fmt.Println(n+1)
os.Exit(0)
}
for i := int64(2); i*i<=n; i++{
if chk(n, i, s) {
fmt.Println(i)
os.Exit(0)
}
}
now := n-s
ans = -1
for i := int64(1); i*i<=now; i++{
if now%i==0 {
x := i+1
if chk(n,x,s) {
if ans==-1 || ans>x {
ans = x
}
}
x = now/i+1;
if chk(n,x,s) {
if ans==-1 || ans>x {
ans=x
}
}
}
}
fmt.Println(ans);
}
// nとiからdigitSumを計算し、sと一致するかチェックする
func chk(n, i, s int64) bool{
digitSum := int64(0)
x := n
for x > 0 {
digitSum += x%i
x /= i
}
return digitSum == s
}
/* templates */
func Max(a []int) int {
r := a[0]
for i := 0; i < len(a); i++ {
if r < a[i] {
r = a[i]
}
}
return r
}
func Min(a []int) int {
r := a[0]
for i := 0; i < len(a); i++ {
if r > a[i] {
r = a[i]
}
}
return r
}
func Sum(a []int) (r int) {
for i := range a {
r += a[i]
}
return r
}
func Abs(a float64) float64 {
if a < 0 {
return -a
}
return a
}
type Pair struct {
a, b int
}
type Pairs []Pair
func (p Pairs) Len() int {
return len(p)
}
func (p Pairs) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p Pairs) Less(i, j int) bool {
return p[i].b < p[j].b
}
var nextReader func() string
func init() {
nextReader = NewScanner()
}
func NewScanner() func() string {
r := bufio.NewScanner(os.Stdin)
r.Buffer(make([]byte, 1024), int(1e+11))
r.Split(bufio.ScanWords)
return func() string {
r.Scan()
return r.Text()
}
}
func nextString() string {
return nextReader()
}
func nextInt64() int64 {
v, _ := strconv.ParseInt(nextReader(), 10, 64)
return v
}
func nextInt() int {
v, _ := strconv.Atoi(nextReader())
return v
}
func nextInts(n int) []int {
r := make([]int, n)
for i := 0; i < n; i++ {
r[i] = nextInt()
}
return r
}
func nextStrings(n int) []string {
r := make([]string, n)
for i := 0; i < n; i++ {
r[i] = nextString()
}
return r
}
func nextFloat64() float64 {
f, _ := strconv.ParseFloat(nextReader(), 64)
return f
}
| Yes | Do these codes solve the same problem?
Code 1: import java.util.*
import kotlin.*
import java.io.InputStream
import java.lang.NumberFormatException
import java.lang.StringBuilder
fun main(args: Array<String>) {
Program().solve()
}
class Program {
fun f(b: Long, n: Long): Long = if (n < b) n else f(b, n / b) + n % b
fun solve() {
val sc = FastScanner()
val n = sc.nextLong()
val s = sc.nextLong()
// b <= √n nは三桁以上 実際に計算
var a = 2L
while (a * a <= n) {
if (f(a, n) == s) {
println(a)
return
}
a++
}
// √n < b <= n nは2桁
// s = floor(n/b) + n%b
// floor(n/b) * b = n-(s-floor(n/b))
// b = n-(s-floor(n/b)) /(floor(n/b))
for (nPerB in a - 1 downTo 1) {
val t = n - (s - nPerB)
if (t % nPerB == 0L) {
val b = t / nPerB
if (b in a..n && f(b, n) == s) {
println(b)
return
}
}
}
// n < b nは1桁
// b = n+1 (s == n)
if (s == n) {
println(n + 1)
return
}
println(-1)
}
}
class FastScanner {
companion object {
val input: InputStream = System.`in`
val buffer = ByteArray(1024) { 0 }
fun isPrintableChar(c: Int): Boolean = c in 33..126
}
var ptr = 0
var buflen = 0
private fun hasNextByte(): Boolean {
if (ptr < buflen) {
return true
} else {
ptr = 0
buflen = input.read(buffer)
if (buflen <= 0) {
return false
}
}
return true
}
private fun readByte(): Int = if (hasNextByte()) buffer[ptr++].toInt() else -1
private fun skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr].toInt())) ptr++
}
fun hasNext(): Boolean {
skipUnprintable()
return hasNextByte()
}
fun next(): String {
if (!hasNext()) throw NoSuchElementException()
val sb = StringBuilder()
var b = readByte()
while (isPrintableChar(b)) {
sb.appendCodePoint(b)
b = readByte()
}
return sb.toString()
}
fun nextInt(): Int {
if (!hasNext()) throw NoSuchElementException()
var n = 0
var b = readByte()
// '-' = 45
val minus = b == 45
if (minus) {
b = readByte()
}
// '0' = 48 '9' = 57
if (b !in 48..57) {
throw NumberFormatException()
}
while (true) {
if (b in 48..57) {
n *= 10
n += b - 48
} else if (b == -1 || !isPrintableChar(b)) {
return if (minus) -n else n
} else {
throw NumberFormatException()
}
b = readByte()
}
}
fun nextLong(): Long {
if (!hasNext()) throw NoSuchElementException()
var n = 0L
var b = readByte()
// '-' = 45
val minus = b == 45
if (minus) {
b = readByte()
}
// '0' = 48 '9' = 57
if (b !in 48..57) {
throw NumberFormatException()
}
while (true) {
if (b in 48..57) {
n *= 10
n += b - 48
} else if (b == -1 || !isPrintableChar(b)) {
return if (minus) -n else n
} else {
throw NumberFormatException()
}
b = readByte()
}
}
fun nextDouble(): Double = next().toDouble()
}
Code 2: package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main(){
n := nextInt64()
s := nextInt64()
var ans int64
if s > n {
// s > nである場合、該当するbは存在しない
fmt.Println(-1)
os.Exit(0)
} else if s == n {
// sとnが等しい場合、n+1が最小のbとなる
fmt.Println(n+1)
os.Exit(0)
}
for i := int64(2); i*i<=n; i++{
if chk(n, i, s) {
fmt.Println(i)
os.Exit(0)
}
}
now := n-s
ans = -1
for i := int64(1); i*i<=now; i++{
if now%i==0 {
x := i+1
if chk(n,x,s) {
if ans==-1 || ans>x {
ans = x
}
}
x = now/i+1;
if chk(n,x,s) {
if ans==-1 || ans>x {
ans=x
}
}
}
}
fmt.Println(ans);
}
// nとiからdigitSumを計算し、sと一致するかチェックする
func chk(n, i, s int64) bool{
digitSum := int64(0)
x := n
for x > 0 {
digitSum += x%i
x /= i
}
return digitSum == s
}
/* templates */
func Max(a []int) int {
r := a[0]
for i := 0; i < len(a); i++ {
if r < a[i] {
r = a[i]
}
}
return r
}
func Min(a []int) int {
r := a[0]
for i := 0; i < len(a); i++ {
if r > a[i] {
r = a[i]
}
}
return r
}
func Sum(a []int) (r int) {
for i := range a {
r += a[i]
}
return r
}
func Abs(a float64) float64 {
if a < 0 {
return -a
}
return a
}
type Pair struct {
a, b int
}
type Pairs []Pair
func (p Pairs) Len() int {
return len(p)
}
func (p Pairs) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p Pairs) Less(i, j int) bool {
return p[i].b < p[j].b
}
var nextReader func() string
func init() {
nextReader = NewScanner()
}
func NewScanner() func() string {
r := bufio.NewScanner(os.Stdin)
r.Buffer(make([]byte, 1024), int(1e+11))
r.Split(bufio.ScanWords)
return func() string {
r.Scan()
return r.Text()
}
}
func nextString() string {
return nextReader()
}
func nextInt64() int64 {
v, _ := strconv.ParseInt(nextReader(), 10, 64)
return v
}
func nextInt() int {
v, _ := strconv.Atoi(nextReader())
return v
}
func nextInts(n int) []int {
r := make([]int, n)
for i := 0; i < n; i++ {
r[i] = nextInt()
}
return r
}
func nextStrings(n int) []string {
r := make([]string, n)
for i := 0; i < n; i++ {
r[i] = nextString()
}
return r
}
func nextFloat64() float64 {
f, _ := strconv.ParseFloat(nextReader(), 64)
return f
}
|
Java | import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
long sum=0;
for(int i=0;i<n;i++)
{
sum+=scan.nextInt();
}
System.out.println(sum/n);
}
} | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0134
{
public class Program
{
public static void Main(string[] args)
{
int n = RInt(); long sum = 0;
for (int i = 0 ; i < n ; i++) sum += RLong();
Console.WriteLine(sum / n);
}
static string RSt() { return Console.ReadLine(); }
static int RInt() { return int.Parse(Console.ReadLine().Trim()); }
static long RLong() { return long.Parse(Console.ReadLine().Trim()); }
static double RDouble() { return double.Parse(Console.ReadLine()); }
static string[] RStAr(char sep = ' ') { return Console.ReadLine().Trim().Split(sep); }
static int[] RIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => int.Parse(e)); }
static long[] RLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => long.Parse(e)); }
static double[] RDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => double.Parse(e)); }
static string WAr<T>(IEnumerable<T> array, string sep = " ") { return string.Join(sep, array.Select(x => x.ToString()).ToArray()); }
}
}
| Yes | Do these codes solve the same problem?
Code 1: import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
long sum=0;
for(int i=0;i<n;i++)
{
sum+=scan.nextInt();
}
System.out.println(sum/n);
}
}
Code 2: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0134
{
public class Program
{
public static void Main(string[] args)
{
int n = RInt(); long sum = 0;
for (int i = 0 ; i < n ; i++) sum += RLong();
Console.WriteLine(sum / n);
}
static string RSt() { return Console.ReadLine(); }
static int RInt() { return int.Parse(Console.ReadLine().Trim()); }
static long RLong() { return long.Parse(Console.ReadLine().Trim()); }
static double RDouble() { return double.Parse(Console.ReadLine()); }
static string[] RStAr(char sep = ' ') { return Console.ReadLine().Trim().Split(sep); }
static int[] RIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => int.Parse(e)); }
static long[] RLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => long.Parse(e)); }
static double[] RDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => double.Parse(e)); }
static string WAr<T>(IEnumerable<T> array, string sep = " ") { return string.Join(sep, array.Select(x => x.ToString()).ToArray()); }
}
}
|
C++ | #include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int dx[5] = {-1, 0, 0, 0, 1};
const int dy[5] = {0, -1, 0, 1, 0};
// Self settings
// clang-format off
#define MAX_N 100000
#define REP(i, N) for (int i = 0; i < (int)(N); ++i)
// clang-format on
int N;
ll A[MAX_N * 2], B[MAX_N * 2];
priority_queue<P, vector<P>, greater<P>> que;
void solve()
{
REP(i, N) que.push(P(B[i], A[i]));
bool f = true;
int now = 0;
while (!que.empty()) {
P p = que.top();
que.pop();
now += p.second;
if (now > p.first) {
f = false;
break;
}
}
printf("%s\n", f ? "Yes" : "No");
}
int main(void)
{
cin >> N;
REP(i, N) cin >> A[i] >> B[i];
solve();
return 0;
}
| Python | s, w = map(int, input().split())
if s <= w:
print('unsafe')
else:
print('safe') | No | Do these codes solve the same problem?
Code 1: #include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int dx[5] = {-1, 0, 0, 0, 1};
const int dy[5] = {0, -1, 0, 1, 0};
// Self settings
// clang-format off
#define MAX_N 100000
#define REP(i, N) for (int i = 0; i < (int)(N); ++i)
// clang-format on
int N;
ll A[MAX_N * 2], B[MAX_N * 2];
priority_queue<P, vector<P>, greater<P>> que;
void solve()
{
REP(i, N) que.push(P(B[i], A[i]));
bool f = true;
int now = 0;
while (!que.empty()) {
P p = que.top();
que.pop();
now += p.second;
if (now > p.first) {
f = false;
break;
}
}
printf("%s\n", f ? "Yes" : "No");
}
int main(void)
{
cin >> N;
REP(i, N) cin >> A[i] >> B[i];
solve();
return 0;
}
Code 2: s, w = map(int, input().split())
if s <= w:
print('unsafe')
else:
print('safe') |
Java | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int a[] = new int[n+2];
a[0]=0;
for(int i=1;i<n+1;i++) {
a[i]=sc.nextInt();
}
a[n+1]=0;
int sum=0;
for(int i=1;i<n+2;i++) {
sum+=Math.abs(a[i-1]-a[i]);
}
for(int i=1;i<n+1;i++) {
int num = sum;
num -=Math.abs(a[i-1]-a[i])+Math.abs(a[i]-a[i+1]);
num += Math.abs(a[i-1]-a[i+1]);
System.out.println(num);
}
}
} | Python |
a,b=(int(x) for x in input().split())
if(a<=b):
print('unsafe')
else:
print('safe')
| 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);
int n=sc.nextInt();
int a[] = new int[n+2];
a[0]=0;
for(int i=1;i<n+1;i++) {
a[i]=sc.nextInt();
}
a[n+1]=0;
int sum=0;
for(int i=1;i<n+2;i++) {
sum+=Math.abs(a[i-1]-a[i]);
}
for(int i=1;i<n+1;i++) {
int num = sum;
num -=Math.abs(a[i-1]-a[i])+Math.abs(a[i]-a[i+1]);
num += Math.abs(a[i-1]-a[i+1]);
System.out.println(num);
}
}
}
Code 2:
a,b=(int(x) for x in input().split())
if(a<=b):
print('unsafe')
else:
print('safe')
|
Python | i = 0
while 1:
x = int(input())
if x == 0:
break
i += 1
print('Case ' + str(i) + ': ' + str(x))
| C++ | #include <algorithm>
#include <assert.h>
#include <bitset>
#include <cfloat>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits.h>
#include <list>
#include <map>
#include <math.h>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <string.h>
#include <time.h>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define rep(i,n) for(int i=0;i<n;i++)
#define REP(i,n) for(int i=1;i<=n;i++)
#define int long long
#define ll long long
#define eps LDBL_EPSILON
#define mod (ll)1000000007
#define INF LLONG_MAX/10
#define P pair<int,int>
#define prique priority_queue
using namespace std;
int n;
char s[310][310], b[310][310];
bool check() {
rep(i, n) {
rep(j, n) {
if (b[i][j] != b[j][i])return false;
}
}
return true;
}
signed main() {
cin >> n;
rep(i, n) {
rep(j, n)cin >> s[i][j];
}
int ans = 0;
rep(i, n) {
rep(j, n) {
rep(k, n)b[j][k] = s[j][(k + i) % n];
}
if (check())ans++;
}
cout << ans * n << endl;
return 0;
} | No | Do these codes solve the same problem?
Code 1: i = 0
while 1:
x = int(input())
if x == 0:
break
i += 1
print('Case ' + str(i) + ': ' + str(x))
Code 2: #include <algorithm>
#include <assert.h>
#include <bitset>
#include <cfloat>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits.h>
#include <list>
#include <map>
#include <math.h>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <string.h>
#include <time.h>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define rep(i,n) for(int i=0;i<n;i++)
#define REP(i,n) for(int i=1;i<=n;i++)
#define int long long
#define ll long long
#define eps LDBL_EPSILON
#define mod (ll)1000000007
#define INF LLONG_MAX/10
#define P pair<int,int>
#define prique priority_queue
using namespace std;
int n;
char s[310][310], b[310][310];
bool check() {
rep(i, n) {
rep(j, n) {
if (b[i][j] != b[j][i])return false;
}
}
return true;
}
signed main() {
cin >> n;
rep(i, n) {
rep(j, n)cin >> s[i][j];
}
int ans = 0;
rep(i, n) {
rep(j, n) {
rep(k, n)b[j][k] = s[j][(k + i) % n];
}
if (check())ans++;
}
cout << ans * n << endl;
return 0;
} |
Java | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni(), x = ni(), y = ni(), z = ni();
int mod = 1000000007;
long[][] dp = new long[n+1][1<<x+y+z];
long[] ep = new long[n+1];
dp[0][0] = 1;
for(int i = 0;i < n;i++){
for(int j = 0;j < 1<<x+y+z;j++){
for(int k = 1;k <= 10;k++){
int nj = (j<<k|1<<k-1)&(1<<x+y+z)-1;
if(nj<<~(z-1)<0 && nj<<~(y+z-1)<0 && nj<<~(x+y+z-1)<0){
ep[i+1] += dp[i][j];
if(ep[i+1] >= mod)ep[i+1] -= mod;
}else{
dp[i+1][nj] += dp[i][j];
if(dp[i+1][nj] >= mod)dp[i+1][nj] -= mod;
}
}
}
ep[i+1] += ep[i] * 10;
ep[i+1] %= mod;
}
out.println(ep[n]);
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
long G = System.currentTimeMillis();
tr(G-S+"ms");
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double nd() { return Double.parseDouble(ns()); }
private static char nc() { return (char)skip(); }
private static String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private static int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private static int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
| Kotlin | fun main(args: Array<String>) {
val (n, x, y, z) = readLine()!!.split(" ").map { it.toInt() }
val MOD = (1e9 + 7).toInt()
val m = 1 shl (x + y + z - 1);
val ng = (1 shl (z - 1)) or (1 shl (y + z - 1)) or (1 shl (x + y + z - 1))
var dp = Array(n + 1) { LongArray(m) { 0L } }
dp[0][0] = 1L
for (i in 0 until n) {
for (j in 1..10) {
for (b in 0 until m) {
var nb = ((b shl j) or (1 shl (j - 1)))
if ((nb and ng) != ng) {
nb = nb and (m - 1)
dp[i + 1][nb] = (dp[i + 1][nb] + dp[i][b]) % MOD
}
}
}
}
var ans = 1L
for (i in 0 until n) {
ans = (ans * 10) % MOD
}
for (b in 0 until m) {
ans = (ans - dp[n][b] + MOD) % MOD
}
println(ans)
}
| Yes | Do these codes solve the same problem?
Code 1: import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni(), x = ni(), y = ni(), z = ni();
int mod = 1000000007;
long[][] dp = new long[n+1][1<<x+y+z];
long[] ep = new long[n+1];
dp[0][0] = 1;
for(int i = 0;i < n;i++){
for(int j = 0;j < 1<<x+y+z;j++){
for(int k = 1;k <= 10;k++){
int nj = (j<<k|1<<k-1)&(1<<x+y+z)-1;
if(nj<<~(z-1)<0 && nj<<~(y+z-1)<0 && nj<<~(x+y+z-1)<0){
ep[i+1] += dp[i][j];
if(ep[i+1] >= mod)ep[i+1] -= mod;
}else{
dp[i+1][nj] += dp[i][j];
if(dp[i+1][nj] >= mod)dp[i+1][nj] -= mod;
}
}
}
ep[i+1] += ep[i] * 10;
ep[i+1] %= mod;
}
out.println(ep[n]);
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
long G = System.currentTimeMillis();
tr(G-S+"ms");
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double nd() { return Double.parseDouble(ns()); }
private static char nc() { return (char)skip(); }
private static String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private static int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private static int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
Code 2: fun main(args: Array<String>) {
val (n, x, y, z) = readLine()!!.split(" ").map { it.toInt() }
val MOD = (1e9 + 7).toInt()
val m = 1 shl (x + y + z - 1);
val ng = (1 shl (z - 1)) or (1 shl (y + z - 1)) or (1 shl (x + y + z - 1))
var dp = Array(n + 1) { LongArray(m) { 0L } }
dp[0][0] = 1L
for (i in 0 until n) {
for (j in 1..10) {
for (b in 0 until m) {
var nb = ((b shl j) or (1 shl (j - 1)))
if ((nb and ng) != ng) {
nb = nb and (m - 1)
dp[i + 1][nb] = (dp[i + 1][nb] + dp[i][b]) % MOD
}
}
}
}
var ans = 1L
for (i in 0 until n) {
ans = (ans * 10) % MOD
}
for (b in 0 until m) {
ans = (ans - dp[n][b] + MOD) % MOD
}
println(ans)
}
|
C++ | #include <iostream>
using namespace std;
int main()
{
int a,c;
char b;
cin>>a>>b>>c;
if(b=='+')
cout<<a+c;
else
cout<<a-c;
} | Python | n, a, b, c, d = map(int, input().split())
s = str(input())
if c>d: #ABDC
if s[b-2:d+1].find("...")!=-1 and s[a-1:c].find("##")==-1:
print("Yes")
else:
print("No")
elif s[a-1:c].find("##")==-1 and s[b-1:d].find("##")==-1:
print("Yes")
else:
print("No")
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int main()
{
int a,c;
char b;
cin>>a>>b>>c;
if(b=='+')
cout<<a+c;
else
cout<<a-c;
}
Code 2: n, a, b, c, d = map(int, input().split())
s = str(input())
if c>d: #ABDC
if s[b-2:d+1].find("...")!=-1 and s[a-1:c].find("##")==-1:
print("Yes")
else:
print("No")
elif s[a-1:c].find("##")==-1 and s[b-1:d].find("##")==-1:
print("Yes")
else:
print("No")
|
Python | # Sort II - Partition
def partition(A,p,r):
x = A[r]
i = p - 1
for j in range(p,r,1):
if A[j] <= x:
i += 1
tmp = A[i]
A[i] = A[j]
A[j] = tmp
tmp = A[i+1]
A[i+1] = A[r]
A[r] = tmp
return i + 1
n = int(input())
A = list(map(int,input().split()))
q = partition(A,0,len(A)-1)
print(*['['+str(a)+']' if i==q else a for i,a in enumerate(A)])
| C# | using System;
class B{
static int n;
static int[] A;
public static void Main(){
n = int.Parse(Console.ReadLine());
string[] str = Console.ReadLine().Split(' ');
A = new int[n];
for(int i = 0;i < n;i++){
A[i] = int.Parse(str[i]);
}
int x = calc.partition(A,0,n-1);
int l = 0;
foreach(int y in A){
Console.Write(y);
l++;
if(l == x) Console.Write(" [");
else if(l == x + 1) Console.Write("] ");
else if(l == n) Console.WriteLine("");
else Console.Write(" ");
}
}
}
class calc{
public static int partition(int[] A,int p,int r){
int x = A[r];
int i = p - 1;
for(int j = p;j < r;j++){
if(A[j] <= x){
i++;
Swap(ref A[i],ref A[j]);
}
}
Swap(ref A[i+1],ref A[r]);
return i+1;
}
public static void Swap(ref int x,ref int y){
int temp;
temp = x;
x = y;
y = temp;
}
}
| Yes | Do these codes solve the same problem?
Code 1: # Sort II - Partition
def partition(A,p,r):
x = A[r]
i = p - 1
for j in range(p,r,1):
if A[j] <= x:
i += 1
tmp = A[i]
A[i] = A[j]
A[j] = tmp
tmp = A[i+1]
A[i+1] = A[r]
A[r] = tmp
return i + 1
n = int(input())
A = list(map(int,input().split()))
q = partition(A,0,len(A)-1)
print(*['['+str(a)+']' if i==q else a for i,a in enumerate(A)])
Code 2: using System;
class B{
static int n;
static int[] A;
public static void Main(){
n = int.Parse(Console.ReadLine());
string[] str = Console.ReadLine().Split(' ');
A = new int[n];
for(int i = 0;i < n;i++){
A[i] = int.Parse(str[i]);
}
int x = calc.partition(A,0,n-1);
int l = 0;
foreach(int y in A){
Console.Write(y);
l++;
if(l == x) Console.Write(" [");
else if(l == x + 1) Console.Write("] ");
else if(l == n) Console.WriteLine("");
else Console.Write(" ");
}
}
}
class calc{
public static int partition(int[] A,int p,int r){
int x = A[r];
int i = p - 1;
for(int j = p;j < r;j++){
if(A[j] <= x){
i++;
Swap(ref A[i],ref A[j]);
}
}
Swap(ref A[i+1],ref A[r]);
return i+1;
}
public static void Swap(ref int x,ref int y){
int temp;
temp = x;
x = y;
y = temp;
}
}
|
C++ | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <map>
#include <deque>
using namespace std;
#define REP(i,n) for(int i = 0; i < n; i++)
#define ALL(v) v.begin(),v.end()
typedef long long ll;
typedef pair<int,int> pi;
typedef pair<ll,ll> pll;
typedef pair<string,string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pi> vpi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
double EPS = 1e-9;
int INFi = 1000000005;
long long INFll = 1000000000000000005ll;
double PI = acos(-1);
int dirx[8] = {-1,0,0,1,-1,-1,1,1};
int diry[8] = {0,1,-1,0,-1,1,-1,1};
ll MOD = 1000000007;
int main(){
string s;
cin >> s;
bool flag = true;
if(s[0]==s[s.size()-1])flag = !flag;
if(s.size() %2 == 0)flag = !flag;
if(flag) cout << "First" << endl;
else cout << "Second" << endl;
return 0;
}
| Python | N = input()
n = [v for v in N]
l = len(n)
C = []
for i in range(2**(l-1)):
c = ''
for j in range(l):
c += n[j]
if i >> j & 1:
c += '+'
else:
c += '-'
if eval(c[:-1]) == 7:
print('{}=7'.format(c[:-1]))
exit()
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <map>
#include <deque>
using namespace std;
#define REP(i,n) for(int i = 0; i < n; i++)
#define ALL(v) v.begin(),v.end()
typedef long long ll;
typedef pair<int,int> pi;
typedef pair<ll,ll> pll;
typedef pair<string,string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pi> vpi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
double EPS = 1e-9;
int INFi = 1000000005;
long long INFll = 1000000000000000005ll;
double PI = acos(-1);
int dirx[8] = {-1,0,0,1,-1,-1,1,1};
int diry[8] = {0,1,-1,0,-1,1,-1,1};
ll MOD = 1000000007;
int main(){
string s;
cin >> s;
bool flag = true;
if(s[0]==s[s.size()-1])flag = !flag;
if(s.size() %2 == 0)flag = !flag;
if(flag) cout << "First" << endl;
else cout << "Second" << endl;
return 0;
}
Code 2: N = input()
n = [v for v in N]
l = len(n)
C = []
for i in range(2**(l-1)):
c = ''
for j in range(l):
c += n[j]
if i >> j & 1:
c += '+'
else:
c += '-'
if eval(c[:-1]) == 7:
print('{}=7'.format(c[:-1]))
exit()
|
Python | ref = list("AADINNUY")
aizu = "AIZUNYAN"
inp = raw_input()
if len(inp) < 8:
print inp
else:
ans = ""
l = len(inp)
i = 0
while i < l:
if i <= l - 8 and sorted(inp[i:i+8]) == ref:
ans += aizu
i += 8
else:
ans += inp[i]
i += 1
print ans
| Java | import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int[] base = new int[26];
char[] org = "AIDUNYAN".toCharArray();
for (char c : org) {
base[c - 'A']++;
}
char[] next = "AIZUNYAN".toCharArray();
char[] arr = sc.next().toCharArray();
int length = arr.length;
int left = 0;
int right = -1;
int[] count = new int[26];
while (right < length) {
while (right < length && right - left < org.length - 1) {
right++;
if (right < length) {
count[arr[right] - 'A']++;
}
}
if (right >= length) {
break;
}
if (equals(count, base)) {
for (int i = left; i <= right; i++) {
arr[i] = next[i - left];
}
left = right + 1;
Arrays.fill(count, 0);
} else {
count[arr[left] - 'A']--;
left++;
}
}
System.out.println(arr);
}
static boolean equals(int[] arr, int[] another) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] != another[i]) {
return false;
}
}
return true;
}
}
| Yes | Do these codes solve the same problem?
Code 1: ref = list("AADINNUY")
aizu = "AIZUNYAN"
inp = raw_input()
if len(inp) < 8:
print inp
else:
ans = ""
l = len(inp)
i = 0
while i < l:
if i <= l - 8 and sorted(inp[i:i+8]) == ref:
ans += aizu
i += 8
else:
ans += inp[i]
i += 1
print ans
Code 2: import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int[] base = new int[26];
char[] org = "AIDUNYAN".toCharArray();
for (char c : org) {
base[c - 'A']++;
}
char[] next = "AIZUNYAN".toCharArray();
char[] arr = sc.next().toCharArray();
int length = arr.length;
int left = 0;
int right = -1;
int[] count = new int[26];
while (right < length) {
while (right < length && right - left < org.length - 1) {
right++;
if (right < length) {
count[arr[right] - 'A']++;
}
}
if (right >= length) {
break;
}
if (equals(count, base)) {
for (int i = left; i <= right; i++) {
arr[i] = next[i - left];
}
left = right + 1;
Arrays.fill(count, 0);
} else {
count[arr[left] - 'A']--;
left++;
}
}
System.out.println(arr);
}
static boolean equals(int[] arr, int[] another) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] != another[i]) {
return false;
}
}
return true;
}
}
|
C# | using System;
using System.Linq;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var N = int.Parse(Console.ReadLine());
var odd = 0;
var even = 0;
for(int i = 1; i <= N; i++)
{
if (i % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
Console.WriteLine(((double)odd / (even + odd)).ToString());
}
}
}
| C++ | /** Created by: Marcos Portales
Codeforces User: marcosportales
Country: Cuba
**/
#include<bits/stdc++.h>
using namespace std;
/// Macros:
#define int long long
#define f first
#define s second
#define db(x) cerr << #x << ": " << (x) << '\n';
#define pb push_back
#define lb lower_bound
#define up upper_bound
#define all(x) x.begin() , x.end()
#define rall(x) x.rbegin() , x.rend()
#define enl '\n'
#define vi vector<int>
#define sz size
#define rep(i,n) for(int i=0;i<(n);i++)
#define rep2(i,n) for(int i=1;i<=(n);i++)
typedef pair<int,int> ii;
typedef long double ld;
typedef unsigned long long ull;
/// Constraints:
const int maxn = 2*1e5+1;
const int mod = 1000000009;
const ld eps = 1e-9;
const int inf = ((1ll<<31ll)-1ll);
const int INF = 10000000000000000ll;
const ld pi = acos(-1);
/// Prime Numbers:
// 2, 173, 179, 181, 197, 311, 331, 737, 1009, 2011, 2027, 3079, 4001, 10037, 10079, 20011, 20089;
// 100003, 100019, 100043, 200003, 200017, 1000003, 1000033, 1000037, 1000081;
// 2000003, 2000029, 2000039, 1000000007, 1000000021, 2000000099;
/// Functions:
#define lg2(x) 31 - __builtin_clz(x)
#define lgx(x,b) ( log(x) / log(b) )
/// Red-Black Tree Template ---------------------------------
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
//typedef tree < long long , null_type , less<long long> , rb_tree_tag , tree_order_statistics_node_update > ordered_set;
/// Quick Pow------------------------------------------------
int qpow(int b,int e){
if( !e ) return 1;
if( e & 1 ) return qpow(b,e-1) * b;
int pwur = qpow(b,e>>1);
return pwur * pwur;
}
int modinv(int x){
return qpow(x,mod-2);
}
/// Criba de Eratostenes ------------------------------------
const int pr=10000;
map<int,int>isp;
void criba(){
for(int i=0;i<=pr;i++)isp[i]=i;
isp[0]=isp[1]=-1;
for(int i=2;i*i<=pr;i++){
if(isp[i]==i){
for(int j=i+i;j<=pr;j+=i)
isp[j]=i;
}
}
}
/// My Code -------------------------------------------------
int32_t main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cout.setf(ios::fixed); cout.precision(0);
srand(time(NULL));
///freopen("a.in","r",stdin);
///freopen("a.out","w",stdout);
///criba();
int a,b,c,x,y;
cin>>a>>b>>c>>x>>y;
if(x<y){
swap(a,b);
swap(x,y);
}
int ans1=0,ans2=a*x+b*y,ans3=2*x*c;
ans1+=2*c*y;
x-=y;
ans1+=a*x;
cout<<min({ans1,ans2,ans3})<<enl;
return 0;
}
| No | Do these codes solve the same problem?
Code 1: using System;
using System.Linq;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var N = int.Parse(Console.ReadLine());
var odd = 0;
var even = 0;
for(int i = 1; i <= N; i++)
{
if (i % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
Console.WriteLine(((double)odd / (even + odd)).ToString());
}
}
}
Code 2: /** Created by: Marcos Portales
Codeforces User: marcosportales
Country: Cuba
**/
#include<bits/stdc++.h>
using namespace std;
/// Macros:
#define int long long
#define f first
#define s second
#define db(x) cerr << #x << ": " << (x) << '\n';
#define pb push_back
#define lb lower_bound
#define up upper_bound
#define all(x) x.begin() , x.end()
#define rall(x) x.rbegin() , x.rend()
#define enl '\n'
#define vi vector<int>
#define sz size
#define rep(i,n) for(int i=0;i<(n);i++)
#define rep2(i,n) for(int i=1;i<=(n);i++)
typedef pair<int,int> ii;
typedef long double ld;
typedef unsigned long long ull;
/// Constraints:
const int maxn = 2*1e5+1;
const int mod = 1000000009;
const ld eps = 1e-9;
const int inf = ((1ll<<31ll)-1ll);
const int INF = 10000000000000000ll;
const ld pi = acos(-1);
/// Prime Numbers:
// 2, 173, 179, 181, 197, 311, 331, 737, 1009, 2011, 2027, 3079, 4001, 10037, 10079, 20011, 20089;
// 100003, 100019, 100043, 200003, 200017, 1000003, 1000033, 1000037, 1000081;
// 2000003, 2000029, 2000039, 1000000007, 1000000021, 2000000099;
/// Functions:
#define lg2(x) 31 - __builtin_clz(x)
#define lgx(x,b) ( log(x) / log(b) )
/// Red-Black Tree Template ---------------------------------
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
//typedef tree < long long , null_type , less<long long> , rb_tree_tag , tree_order_statistics_node_update > ordered_set;
/// Quick Pow------------------------------------------------
int qpow(int b,int e){
if( !e ) return 1;
if( e & 1 ) return qpow(b,e-1) * b;
int pwur = qpow(b,e>>1);
return pwur * pwur;
}
int modinv(int x){
return qpow(x,mod-2);
}
/// Criba de Eratostenes ------------------------------------
const int pr=10000;
map<int,int>isp;
void criba(){
for(int i=0;i<=pr;i++)isp[i]=i;
isp[0]=isp[1]=-1;
for(int i=2;i*i<=pr;i++){
if(isp[i]==i){
for(int j=i+i;j<=pr;j+=i)
isp[j]=i;
}
}
}
/// My Code -------------------------------------------------
int32_t main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cout.setf(ios::fixed); cout.precision(0);
srand(time(NULL));
///freopen("a.in","r",stdin);
///freopen("a.out","w",stdout);
///criba();
int a,b,c,x,y;
cin>>a>>b>>c>>x>>y;
if(x<y){
swap(a,b);
swap(x,y);
}
int ans1=0,ans2=a*x+b*y,ans3=2*x*c;
ans1+=2*c*y;
x-=y;
ans1+=a*x;
cout<<min({ans1,ans2,ans3})<<enl;
return 0;
}
|
C++ | #include <iostream>
#include <string>
using namespace std;
int main() {
string S, T;
cin >> S >> T;
int count = 0;
for (int i = 0; i < S.size(); i++){
if (S[i] != T[i]) count++;
}
cout << count << endl;
} | Python | from itertools import permutations
n,m,r=map(int,input().split())
visit=list(map(int,input().split()))
dist=[[10**9]*n for i in range(n)]
for i in range(m):
a,b,c=map(int,input().split())
dist[a-1][b-1],dist[b-1][a-1]=c,c
for i in range(n):
dist[i-1][i-1]=0
for i in range(n):
for j in range(n):
for k in range(n):
dist[j][k]=min(dist[j][k],dist[j][i]+dist[i][k])
ans=10**9
check=permutations(visit)
for i in check:
c=0
for j in range(1,r):
c+=dist[i[j-1]-1][i[j]-1]
if c<ans:ans=c
print(ans)
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <string>
using namespace std;
int main() {
string S, T;
cin >> S >> T;
int count = 0;
for (int i = 0; i < S.size(); i++){
if (S[i] != T[i]) count++;
}
cout << count << endl;
}
Code 2: from itertools import permutations
n,m,r=map(int,input().split())
visit=list(map(int,input().split()))
dist=[[10**9]*n for i in range(n)]
for i in range(m):
a,b,c=map(int,input().split())
dist[a-1][b-1],dist[b-1][a-1]=c,c
for i in range(n):
dist[i-1][i-1]=0
for i in range(n):
for j in range(n):
for k in range(n):
dist[j][k]=min(dist[j][k],dist[j][i]+dist[i][k])
ans=10**9
check=permutations(visit)
for i in check:
c=0
for j in range(1,r):
c+=dist[i[j-1]-1][i[j]-1]
if c<ans:ans=c
print(ans)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.