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 N;
int A[210];
int main() {
cin >> N;
for (int i = 0; i < N; ++i) cin >> A[i];
int counter = 0;
while (true){
bool exist_odd = false; // A[i] がすべて偶数かどうかを判定するフラグ
for (int i = 0; i < N; ++i) {
if (A[i] % 2 != 0) exist_odd = true; // 奇数があったらフラグを立てる
}
if (exist_odd) break;
for (int i = 0; i < N; ++i) A[i] /= 2;
counter += 1;
}
cout << counter << endl;
} | Python | from collections import defaultdict
N = int(input())
A = [int(n) for n in input().split()]
record = defaultdict(int)
count = 0
for i in range(len(A)):
cur = i-A[i]
count += record[cur]
record[i+A[i]] += 1
print(count)
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int N;
int A[210];
int main() {
cin >> N;
for (int i = 0; i < N; ++i) cin >> A[i];
int counter = 0;
while (true){
bool exist_odd = false; // A[i] がすべて偶数かどうかを判定するフラグ
for (int i = 0; i < N; ++i) {
if (A[i] % 2 != 0) exist_odd = true; // 奇数があったらフラグを立てる
}
if (exist_odd) break;
for (int i = 0; i < N; ++i) A[i] /= 2;
counter += 1;
}
cout << counter << endl;
}
Code 2: from collections import defaultdict
N = int(input())
A = [int(n) for n in input().split()]
record = defaultdict(int)
count = 0
for i in range(len(A)):
cur = i-A[i]
count += record[cur]
record[i+A[i]] += 1
print(count)
|
Python | def pos(a, b, seq):
st = set([a])
for k in seq:
new_st = set(st)
for v in st:
new_st.add(v%k)
st = new_st
return b in st
def main():
n = input()
aa = map(int, raw_input().split())
bb = map(int, raw_input().split())
def ok(seq):
for a,b in zip(aa,bb):
if not pos(a,b,seq):
return False
return True
u = []
for j in xrange(60,0,-1):
if not ok(u + range(j-1,0,-1)):
u.append(j)
#print u
if 59 in u:
print -1
return
else:
print sum(2**k for k in u)
main()
| C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics;
class Myon
{
public Myon() { }
public static int Main()
{
new Myon().calc();
return 0;
}
Scanner cin;
int C = 52;
void calc()
{
cin = new Scanner();
int N = cin.nextInt();
int[] A = cin.ArrayInt(N);
int[] B = cin.ArrayInt(N);
long result = (1L << C) - 1;
for (int i = 0; i < N; i++)
{
if(!check(result, A[i], B[i]))
{
Console.WriteLine(-1);
return;
}
}
for (int i = C - 1; i >= 0; i--)
{
long next = result - (1L << i);
bool flag = true;
for (int j = 0; j < N; j++)
{
if (!check(next, A[j], B[j]))
{
flag = false;
break;
}
}
if (flag) result = next;
}
Console.WriteLine(result * 2);
}
bool check(long flag, int a, int b)
{
bool[] ok = new bool[C];
ok[a] = true;
for (int i = C - 1; i >= 0; i--)
{
if ((flag >> i) % 2 == 0) continue;
for (int j = i; j < C; j++)
{
if(ok[j]) ok[j % (i + 1)] = true;
}
if (ok[b]) return true;
}
if (ok[b]) return true;
return false;
}
}
class Scanner
{
string[] s;
int i;
char[] cs = new char[] { ' ' };
public Scanner()
{
s = new string[0];
i = 0;
}
public string next()
{
if (i < s.Length) return s[i++];
string st = Console.ReadLine();
while (st == "") st = Console.ReadLine();
s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
if (s.Length == 0) return next();
i = 0;
return s[i++];
}
public int nextInt()
{
return int.Parse(next());
}
public int[] ArrayInt(int N, int add = 0)
{
int[] Array = new int[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextInt() + add;
}
return Array;
}
public long nextLong()
{
return long.Parse(next());
}
public long[] ArrayLong(int N, long add = 0)
{
long[] Array = new long[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextLong() + add;
}
return Array;
}
public double nextDouble()
{
return double.Parse(next());
}
public double[] ArrayDouble(int N, double add = 0)
{
double[] Array = new double[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextDouble() + add;
}
return Array;
}
}
| Yes | Do these codes solve the same problem?
Code 1: def pos(a, b, seq):
st = set([a])
for k in seq:
new_st = set(st)
for v in st:
new_st.add(v%k)
st = new_st
return b in st
def main():
n = input()
aa = map(int, raw_input().split())
bb = map(int, raw_input().split())
def ok(seq):
for a,b in zip(aa,bb):
if not pos(a,b,seq):
return False
return True
u = []
for j in xrange(60,0,-1):
if not ok(u + range(j-1,0,-1)):
u.append(j)
#print u
if 59 in u:
print -1
return
else:
print sum(2**k for k in u)
main()
Code 2: using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics;
class Myon
{
public Myon() { }
public static int Main()
{
new Myon().calc();
return 0;
}
Scanner cin;
int C = 52;
void calc()
{
cin = new Scanner();
int N = cin.nextInt();
int[] A = cin.ArrayInt(N);
int[] B = cin.ArrayInt(N);
long result = (1L << C) - 1;
for (int i = 0; i < N; i++)
{
if(!check(result, A[i], B[i]))
{
Console.WriteLine(-1);
return;
}
}
for (int i = C - 1; i >= 0; i--)
{
long next = result - (1L << i);
bool flag = true;
for (int j = 0; j < N; j++)
{
if (!check(next, A[j], B[j]))
{
flag = false;
break;
}
}
if (flag) result = next;
}
Console.WriteLine(result * 2);
}
bool check(long flag, int a, int b)
{
bool[] ok = new bool[C];
ok[a] = true;
for (int i = C - 1; i >= 0; i--)
{
if ((flag >> i) % 2 == 0) continue;
for (int j = i; j < C; j++)
{
if(ok[j]) ok[j % (i + 1)] = true;
}
if (ok[b]) return true;
}
if (ok[b]) return true;
return false;
}
}
class Scanner
{
string[] s;
int i;
char[] cs = new char[] { ' ' };
public Scanner()
{
s = new string[0];
i = 0;
}
public string next()
{
if (i < s.Length) return s[i++];
string st = Console.ReadLine();
while (st == "") st = Console.ReadLine();
s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
if (s.Length == 0) return next();
i = 0;
return s[i++];
}
public int nextInt()
{
return int.Parse(next());
}
public int[] ArrayInt(int N, int add = 0)
{
int[] Array = new int[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextInt() + add;
}
return Array;
}
public long nextLong()
{
return long.Parse(next());
}
public long[] ArrayLong(int N, long add = 0)
{
long[] Array = new long[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextLong() + add;
}
return Array;
}
public double nextDouble()
{
return double.Parse(next());
}
public double[] ArrayDouble(int N, double add = 0)
{
double[] Array = new double[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextDouble() + add;
}
return Array;
}
}
|
Kotlin | fun main(args: Array<String>) {
val i = readLine()!!.toInt()
println(if(i%2==1) i/2+1 else i/2)
} | C++ | #include <iostream>
using namespace std;
int main() {
int N, i;
cin >> N >> i;
cout << N-i + 1 << endl;
return 0;
} | No | Do these codes solve the same problem?
Code 1: fun main(args: Array<String>) {
val i = readLine()!!.toInt()
println(if(i%2==1) i/2+1 else i/2)
}
Code 2: #include <iostream>
using namespace std;
int main() {
int N, i;
cin >> N >> i;
cout << N-i + 1 << endl;
return 0;
} |
C++ | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e9 + 1;
int mod = 1e9 + 7;
#define INF 0x3f3f3f3f
typedef pair<int, int> pii;
int main()
{
#ifndef ONLINE_JUDGE
//freopen("in.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
// ios::sync_with_stdio(0);
int n, m;
while (~scanf("%d%d", &n, &m))
{
int ans = 0;
int mid = (int)sqrt(m) + 1;
for (int i = 1; i <= mid; i++)
{
if (m % i == 0)
{
int t = m/i;
if (t >= n)
{
ans = max(ans, i);
}
if (i >= n)
{
ans = max(ans, t);
}
}
}
printf("%d\n", ans);
}
return 0;
} | Python | # -*- coding: utf-8 -*-
n, x = map(int, input().split())
m = [int(input()) for i in range(n)]
m.sort()
x -= sum(m)
ans = 0
ans += len(m)
ans += x//m[0]
print(ans) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e9 + 1;
int mod = 1e9 + 7;
#define INF 0x3f3f3f3f
typedef pair<int, int> pii;
int main()
{
#ifndef ONLINE_JUDGE
//freopen("in.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
// ios::sync_with_stdio(0);
int n, m;
while (~scanf("%d%d", &n, &m))
{
int ans = 0;
int mid = (int)sqrt(m) + 1;
for (int i = 1; i <= mid; i++)
{
if (m % i == 0)
{
int t = m/i;
if (t >= n)
{
ans = max(ans, i);
}
if (i >= n)
{
ans = max(ans, t);
}
}
}
printf("%d\n", ans);
}
return 0;
}
Code 2: # -*- coding: utf-8 -*-
n, x = map(int, input().split())
m = [int(input()) for i in range(n)]
m.sort()
x -= sum(m)
ans = 0
ans += len(m)
ans += x//m[0]
print(ans) |
C++ | #include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <vector>
using namespace std;
// BEGIN NO SAD
#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 vector<int> vi;
// END NO SAD
typedef long long ll;
typedef pair<int, int> pii;
void solve() {
int n;
string s;
cin >> n >> s;
if(n%2) {
cout << "No\n";
return;
}
for(int i = 0; i < n/2; i++) {
if(s[i] != s[i+n/2]) {
cout << "No\n";
return;
}
}
cout << "Yes\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
solve();
}
| Python | #--Echo
N = int(input())
S = list(input())
number = len(S)
harf = int(N / 2)
if(number % 2 != 0):
print("No")
else:
if(S[0:harf] == S[harf:N]):
print("Yes")
else:
print("No")
| Yes | Do these codes solve the same problem?
Code 1: #include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <vector>
using namespace std;
// BEGIN NO SAD
#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 vector<int> vi;
// END NO SAD
typedef long long ll;
typedef pair<int, int> pii;
void solve() {
int n;
string s;
cin >> n >> s;
if(n%2) {
cout << "No\n";
return;
}
for(int i = 0; i < n/2; i++) {
if(s[i] != s[i+n/2]) {
cout << "No\n";
return;
}
}
cout << "Yes\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
solve();
}
Code 2: #--Echo
N = int(input())
S = list(input())
number = len(S)
harf = int(N / 2)
if(number % 2 != 0):
print("No")
else:
if(S[0:harf] == S[harf:N]):
print("Yes")
else:
print("No")
|
C++ | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
int n,t;
cin >> n >> t;
vector<ll> a(n);
ll mod=1000000007;
for(int i=0; i<n; i++) cin >> a[i];
sort(a.begin(),a.end());
ll ans=1;
for(int i=0; i<n; i++) {
ans*=distance(lower_bound(a.begin(),a.end(),a[i]-t),a.begin()+i)+1;
ans%=mod;
}
cout << ans << endl;
return 0;
}
| Python | from collections import Counter
MOD = 10**9+7
n, t = map(int, input().split())
d = [int(input()) for _ in range(n)]
d.sort(reverse=True)
c = Counter(d)
cum = [0 for _ in range(200002)]
for i in range(100000, 0, -1):
cum[i] = cum[i+1] + c[i]
ans = 1
for i, x in enumerate(d):
mul = i+1 - cum[x+t+1]
ans *= mul
ans %= MOD
print(ans)
| Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
int n,t;
cin >> n >> t;
vector<ll> a(n);
ll mod=1000000007;
for(int i=0; i<n; i++) cin >> a[i];
sort(a.begin(),a.end());
ll ans=1;
for(int i=0; i<n; i++) {
ans*=distance(lower_bound(a.begin(),a.end(),a[i]-t),a.begin()+i)+1;
ans%=mod;
}
cout << ans << endl;
return 0;
}
Code 2: from collections import Counter
MOD = 10**9+7
n, t = map(int, input().split())
d = [int(input()) for _ in range(n)]
d.sort(reverse=True)
c = Counter(d)
cum = [0 for _ in range(200002)]
for i in range(100000, 0, -1):
cum[i] = cum[i+1] + c[i]
ans = 1
for i, x in enumerate(d):
mul = i+1 - cum[x+t+1]
ans *= mul
ans %= MOD
print(ans)
|
C++ | #include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<unordered_map>
using namespace std;
typedef long long ll;
#define chmax(a,b) a=max(a,b)
#define chmin(a,b) a=min(a,b)
#define mod 1000000007
#define mad(a,b) a=(a+b)%mod
#define N 200010
int main(){
cin.tie(0);
ios::sync_with_stdio(0);
ll n;
string s[110];
cin>>n;
bool ok=1;
for(int i=0;i<n;i++){
cin>>s[i];
for(int j=0;j<i;j++)if(s[i]==s[j])ok=0;
}
for(int i=0;i<n-1;i++){
if(s[i].back()!=s[i+1][0])ok=0;
}
cout<<(ok?"Yes":"No")<<endl;
}
| C | #include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int arr[9], N, P[9], Q[9], s, t;
bool flg[9];
void dfs(int x){
if(x == N){
bool p=true, q = true;
for(int i=0; i<N; i++){
if(P[i] > arr[i])break;
if(P[i] < arr[i]){
p = false;
break;
}
}
for(int i=0; i<N; i++){
if(Q[i] > arr[i])break;
if(Q[i] < arr[i]){
q = false;
break;
}
}
s += p;
t += q;
}
for(int i=0; i<N; i++){
if(!flg[i]){
flg[i] = true;
arr[x] = i + 1;
dfs(x + 1);
flg[i] = false;
}
}
return;
}
int main(){
scanf("%d", &N);
for(int i=0; i<N; i++)scanf("%d", P+i);
for(int i=0; i<N; i++)scanf("%d", Q+i);
dfs(0);
printf("%d\n", abs(s - t));
return 0;
}
| No | Do these codes solve the same problem?
Code 1: #include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<unordered_map>
using namespace std;
typedef long long ll;
#define chmax(a,b) a=max(a,b)
#define chmin(a,b) a=min(a,b)
#define mod 1000000007
#define mad(a,b) a=(a+b)%mod
#define N 200010
int main(){
cin.tie(0);
ios::sync_with_stdio(0);
ll n;
string s[110];
cin>>n;
bool ok=1;
for(int i=0;i<n;i++){
cin>>s[i];
for(int j=0;j<i;j++)if(s[i]==s[j])ok=0;
}
for(int i=0;i<n-1;i++){
if(s[i].back()!=s[i+1][0])ok=0;
}
cout<<(ok?"Yes":"No")<<endl;
}
Code 2: #include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int arr[9], N, P[9], Q[9], s, t;
bool flg[9];
void dfs(int x){
if(x == N){
bool p=true, q = true;
for(int i=0; i<N; i++){
if(P[i] > arr[i])break;
if(P[i] < arr[i]){
p = false;
break;
}
}
for(int i=0; i<N; i++){
if(Q[i] > arr[i])break;
if(Q[i] < arr[i]){
q = false;
break;
}
}
s += p;
t += q;
}
for(int i=0; i<N; i++){
if(!flg[i]){
flg[i] = true;
arr[x] = i + 1;
dfs(x + 1);
flg[i] = false;
}
}
return;
}
int main(){
scanf("%d", &N);
for(int i=0; i<N; i++)scanf("%d", P+i);
for(int i=0; i<N; i++)scanf("%d", Q+i);
dfs(0);
printf("%d\n", abs(s - t));
return 0;
}
|
C++ |
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#define pi 3.14159265358979323846264338
using namespace std;
int main() {
int h, w;
while (cin >> h >> w) {
if (h == 0 && w == 0) {
break;
}
for (int i = 0; i < h; i++) {
for(int j = 0; j < w; j++) {
cout << "#";
}
cout << endl;
}
cout << endl;
}
} | Python | n,a = map(int,input().split())
x = list(map(int,input().split()))
x = [t-a for t in x]
p = [0]*5010
p[0] = 1
q = [0]*5010
for t in x:
for i in range(5010):
q[i] = p[i] + p[(i-t)%5010]
for i in range(5010):
p[i] = q[i]
print(p[0]-1) | No | Do these codes solve the same problem?
Code 1:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#define pi 3.14159265358979323846264338
using namespace std;
int main() {
int h, w;
while (cin >> h >> w) {
if (h == 0 && w == 0) {
break;
}
for (int i = 0; i < h; i++) {
for(int j = 0; j < w; j++) {
cout << "#";
}
cout << endl;
}
cout << endl;
}
}
Code 2: n,a = map(int,input().split())
x = list(map(int,input().split()))
x = [t-a for t in x]
p = [0]*5010
p[0] = 1
q = [0]*5010
for t in x:
for i in range(5010):
q[i] = p[i] + p[(i-t)%5010]
for i in range(5010):
p[i] = q[i]
print(p[0]-1) |
Python | def f_c():
s = input()
co, ce = 0, 0
for i in range(len(s)):
if i%2!=0:
co = co+1 if s[i]!="1" else co
ce = ce+1 if s[i]!="0" else ce
else:
co = co+1 if s[i]!="0" else co
ce = ce+1 if s[i]!="1" else ce
print(min(co, ce))
if __name__ == "__main__":
f_c()
| C++ | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
#define pb push_back
#define f(i,n) for(i=0;i<n;i++)
#define F(i,a,b) for(i=a;a<=b;i++)
#define arr(a,n) for( i=0;i<n;i++)cin>>a[i];
#define fi first
#define se second
#define mp make_pair
#define mod 1000000007
#define YES cout<<"YES"<<endl;
#define Yes cout<<"Yes"<<endl;
#define NO cout<<"NO"<<endl;
#define No cout<<"No"<<endl;
#define yes cout<<"yes"<<endl;
#define no cout<<"no"<<endl;
#define vi vector<ll>
#define ed end()
#define bg begin()
#define sz size()
#define ln length()
#define s() sort(a,a+n);
#define sr() sort(a,a+n,greater<ll>());
#define v() sort(v.begin(),v.end());
#define vr() sort(v.begin(),v.end(),greater<ll>());
#define mod 1000000007
#define fast() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
int main() {
/*#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input.txt", "r", stdin);
// for writing output to output.txt
freopen("output.txt", "w", stdout);
#endif*/
/*
Ofcourse it's Hard.
It's supposed to be Hard.
If it's easy everyone would do it.
HARD IS WHAT MAKES IT GREAT
YESTERDAY U SAID TOMORROW
SLOWLY BECOMING THE PERSON I
SHOULD HAVE BEEN A LONG TIME AGO
SAME TASK CAN'T BE FOUND DIFFICULT TWICE
BTBHWSITW
SPRH TU KAB P
CP IS ALL ABOUT THINKING
YOU HAVE MUCH MORE POTENTIAL THAN U THINK
AJIT SHIDDAT 10
UR DAILY ROUTINE
*/
fast();
//ll t;cin>>t;while(t--)
{
ll a,b,k,i=1,count=0;
cin>>a>>b>>k;
vi v;
while(i<=min(a,b))
{
if(a%i==0&&b%i==0)
{
count++;
v.pb(i);
}
i++;
}
cout<<v[v.size()-k]<<endl;
}
return 0;
} | No | Do these codes solve the same problem?
Code 1: def f_c():
s = input()
co, ce = 0, 0
for i in range(len(s)):
if i%2!=0:
co = co+1 if s[i]!="1" else co
ce = ce+1 if s[i]!="0" else ce
else:
co = co+1 if s[i]!="0" else co
ce = ce+1 if s[i]!="1" else ce
print(min(co, ce))
if __name__ == "__main__":
f_c()
Code 2: #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
#define pb push_back
#define f(i,n) for(i=0;i<n;i++)
#define F(i,a,b) for(i=a;a<=b;i++)
#define arr(a,n) for( i=0;i<n;i++)cin>>a[i];
#define fi first
#define se second
#define mp make_pair
#define mod 1000000007
#define YES cout<<"YES"<<endl;
#define Yes cout<<"Yes"<<endl;
#define NO cout<<"NO"<<endl;
#define No cout<<"No"<<endl;
#define yes cout<<"yes"<<endl;
#define no cout<<"no"<<endl;
#define vi vector<ll>
#define ed end()
#define bg begin()
#define sz size()
#define ln length()
#define s() sort(a,a+n);
#define sr() sort(a,a+n,greater<ll>());
#define v() sort(v.begin(),v.end());
#define vr() sort(v.begin(),v.end(),greater<ll>());
#define mod 1000000007
#define fast() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
int main() {
/*#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input.txt", "r", stdin);
// for writing output to output.txt
freopen("output.txt", "w", stdout);
#endif*/
/*
Ofcourse it's Hard.
It's supposed to be Hard.
If it's easy everyone would do it.
HARD IS WHAT MAKES IT GREAT
YESTERDAY U SAID TOMORROW
SLOWLY BECOMING THE PERSON I
SHOULD HAVE BEEN A LONG TIME AGO
SAME TASK CAN'T BE FOUND DIFFICULT TWICE
BTBHWSITW
SPRH TU KAB P
CP IS ALL ABOUT THINKING
YOU HAVE MUCH MORE POTENTIAL THAN U THINK
AJIT SHIDDAT 10
UR DAILY ROUTINE
*/
fast();
//ll t;cin>>t;while(t--)
{
ll a,b,k,i=1,count=0;
cin>>a>>b>>k;
vi v;
while(i<=min(a,b))
{
if(a%i==0&&b%i==0)
{
count++;
v.pb(i);
}
i++;
}
cout<<v[v.size()-k]<<endl;
}
return 0;
} |
C | #include<stdio.h>
#include<string.h>
#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)<(y)?(y):(x))
#define rep(i,n) for(int i=0;(i)<(n);(i)++)
#define INF 1000000000
int n;
int t[16][17];
int main(void){
while(1){
scanf("%d",&n);
if(n==0) break;
rep(i,n){
rep(j,n+1){
scanf("%d",&t[i][j]);
}
}
int dp[1<<n];
rep(i,(1<<n)) dp[i]=INF;
dp[0]=0;
for(int i=0;i<(1<<n);i++){
for(int j=0;j<n;j++){
if(!(i&(1<<j))){
int v=t[j][0];
for(int k=0;k<n;k++)
if(i&(1<<k))v=min(v,t[j][k+1]);
dp[i|(1<<j)]=min(dp[i|(1<<j)],dp[i]+v);
}
}
}
printf("%d\n",dp[(1<<n)-1]);
}
}
| Java | import java.util.*;
class Main{
boolean debug=false;
int INF=1<<28;
int N;
int[][] t;
int[] dp;
void solve(){
Scanner sc=new Scanner(System.in);
while(true){
N=sc.nextInt();
if(N==0)break;
t=new int[N][N+1];
for(int i=0;i<N;i++){
for(int j=0;j<N+1;j++){
t[i][j]=sc.nextInt();
}}
dp=new int[(1<<N)];
Arrays.fill(dp,INF);
dp[0]=0;
for(int S=0;S<(1<<N);S++){
for(int i=0;i<N;i++){
if(((S>>i)&1)==0){
int mintime=t[i][0];
for(int j=0;j<N;j++){
if(((S>>j)&1)==1){
mintime=Math.min(mintime,t[i][j+1]);
}
}
dp[S+(1<<i)]=Math.min(dp[S+(1<<i)],dp[S]+mintime);
}
}
}
System.out.println(dp[(1<<N)-1]);
}
}
public static void main(String[] args){
new Main().solve();
}
} | Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
#include<string.h>
#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)<(y)?(y):(x))
#define rep(i,n) for(int i=0;(i)<(n);(i)++)
#define INF 1000000000
int n;
int t[16][17];
int main(void){
while(1){
scanf("%d",&n);
if(n==0) break;
rep(i,n){
rep(j,n+1){
scanf("%d",&t[i][j]);
}
}
int dp[1<<n];
rep(i,(1<<n)) dp[i]=INF;
dp[0]=0;
for(int i=0;i<(1<<n);i++){
for(int j=0;j<n;j++){
if(!(i&(1<<j))){
int v=t[j][0];
for(int k=0;k<n;k++)
if(i&(1<<k))v=min(v,t[j][k+1]);
dp[i|(1<<j)]=min(dp[i|(1<<j)],dp[i]+v);
}
}
}
printf("%d\n",dp[(1<<n)-1]);
}
}
Code 2: import java.util.*;
class Main{
boolean debug=false;
int INF=1<<28;
int N;
int[][] t;
int[] dp;
void solve(){
Scanner sc=new Scanner(System.in);
while(true){
N=sc.nextInt();
if(N==0)break;
t=new int[N][N+1];
for(int i=0;i<N;i++){
for(int j=0;j<N+1;j++){
t[i][j]=sc.nextInt();
}}
dp=new int[(1<<N)];
Arrays.fill(dp,INF);
dp[0]=0;
for(int S=0;S<(1<<N);S++){
for(int i=0;i<N;i++){
if(((S>>i)&1)==0){
int mintime=t[i][0];
for(int j=0;j<N;j++){
if(((S>>j)&1)==1){
mintime=Math.min(mintime,t[i][j+1]);
}
}
dp[S+(1<<i)]=Math.min(dp[S+(1<<i)],dp[S]+mintime);
}
}
}
System.out.println(dp[(1<<N)-1]);
}
}
public static void main(String[] args){
new Main().solve();
}
} |
C++ | #include<deque>
#include<queue>
#include<vector>
#include<algorithm>
#include<iostream>
#include<set>
#include<cmath>
#include<tuple>
#include<string>
#include<chrono>
#include<functional>
#include<iterator>
#include<random>
#include<unordered_set>
#include<array>
#include<map>
#include<iomanip>
#include<assert.h>
#include<list>
#include<bitset>
#include<stack>
#include<memory>
#include<numeric>
using namespace std;
using namespace std::chrono;
typedef long long int llint;
typedef long double lldo;
#define mp make_pair
#define mt make_tuple
#define pub push_back
#define puf push_front
#define pob pop_back
#define pof pop_front
#define fir first
#define sec second
#define res resize
#define ins insert
#define era erase
/*cout<<fixed<<setprecision(20);cin.tie(0);ios::sync_with_stdio(false);*/
const int mod=1000000007;
const llint big=2.19e15+1;
const long double pai=3.141592653589793238462643383279502884197;
const long double eps=1e-4;
template <class T,class U>bool mineq(T& a,U b){if(a>b){a=b;return true;}return false;}
template <class T,class U>bool maxeq(T& a,U b){if(a<b){a=b;return true;}return false;}
llint gcd(llint a,llint b){if(a%b==0){return b;}else return gcd(b,a%b);}
llint lcm(llint a,llint b){if(a==0){return b;}return a/gcd(a,b)*b;}
template<class T> void SO(T& ve){sort(ve.begin(),ve.end());}
template<class T> void REV(T& ve){reverse(ve.begin(),ve.end());}
template<class T>llint LBI(const vector<T>&ar,T in){return lower_bound(ar.begin(),ar.end(),in)-ar.begin();}
template<class T>llint UBI(const vector<T>&ar,T in){return upper_bound(ar.begin(),ar.end(),in)-ar.begin();}
int main(void){
llint i,n,a,b;cin>>n>>a>>b;
n%=12;
for(i=0;i<n;i++){
if(i%2==0){a=a-b;}
else{b=a+b;}
}cout<<a<<" "<<b<<endl;
return 0;
}
| Java | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long n=sc.nextLong();
long a=sc.nextInt();
long b=sc.nextInt();
n%=12;
for(int i=1;i<n+1;i++){
if(i%2==1)a=a-b;
else b=a+b;
}
System.out.println(a+" "+b);
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include<deque>
#include<queue>
#include<vector>
#include<algorithm>
#include<iostream>
#include<set>
#include<cmath>
#include<tuple>
#include<string>
#include<chrono>
#include<functional>
#include<iterator>
#include<random>
#include<unordered_set>
#include<array>
#include<map>
#include<iomanip>
#include<assert.h>
#include<list>
#include<bitset>
#include<stack>
#include<memory>
#include<numeric>
using namespace std;
using namespace std::chrono;
typedef long long int llint;
typedef long double lldo;
#define mp make_pair
#define mt make_tuple
#define pub push_back
#define puf push_front
#define pob pop_back
#define pof pop_front
#define fir first
#define sec second
#define res resize
#define ins insert
#define era erase
/*cout<<fixed<<setprecision(20);cin.tie(0);ios::sync_with_stdio(false);*/
const int mod=1000000007;
const llint big=2.19e15+1;
const long double pai=3.141592653589793238462643383279502884197;
const long double eps=1e-4;
template <class T,class U>bool mineq(T& a,U b){if(a>b){a=b;return true;}return false;}
template <class T,class U>bool maxeq(T& a,U b){if(a<b){a=b;return true;}return false;}
llint gcd(llint a,llint b){if(a%b==0){return b;}else return gcd(b,a%b);}
llint lcm(llint a,llint b){if(a==0){return b;}return a/gcd(a,b)*b;}
template<class T> void SO(T& ve){sort(ve.begin(),ve.end());}
template<class T> void REV(T& ve){reverse(ve.begin(),ve.end());}
template<class T>llint LBI(const vector<T>&ar,T in){return lower_bound(ar.begin(),ar.end(),in)-ar.begin();}
template<class T>llint UBI(const vector<T>&ar,T in){return upper_bound(ar.begin(),ar.end(),in)-ar.begin();}
int main(void){
llint i,n,a,b;cin>>n>>a>>b;
n%=12;
for(i=0;i<n;i++){
if(i%2==0){a=a-b;}
else{b=a+b;}
}cout<<a<<" "<<b<<endl;
return 0;
}
Code 2: import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long n=sc.nextLong();
long a=sc.nextInt();
long b=sc.nextInt();
n%=12;
for(int i=1;i<n+1;i++){
if(i%2==1)a=a-b;
else b=a+b;
}
System.out.println(a+" "+b);
}
}
|
C | #include <stdio.h>
int t[100],k[100],s[100];
void Answer(int j);
int main(void){
int a,b,c,i,j;
char str[100];
for(j=0; ;j++){
fgets(str,sizeof(str),stdin);
sscanf(str,"%d %d %d",&a,&b,&c);
if(a==-1 && b ==-1) break;
t[j]=a; k[j]=b; s[j]=c;
}
Answer(j);
return 0;
}
void Answer(int j){
int i;
for(i=0;i<j;i++){
if((t[i]==-1) || (k[i]==-1))
printf("F\n");
else if(t[i]+k[i]<30)
printf("F\n");
else if((30<=t[i]+k[i] && t[i]+k[i]<50) && s[i]<50)
printf("D\n");
else if((30<=t[i]+k[i] && t[i]+k[i]<50) && s[i]>=50)
printf("C\n");
else if((50<=t[i]+k[i] && t[i]+k[i]<65))
printf("C\n");
else if((65<=t[i]+k[i]) && (t[i]+k[i]<80))
printf("B\n");
else if(80<=t[i]+k[i])
printf("A\n");
}
} | Java |
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String S = sc.next();
int A=Integer.parseInt(S.substring(0,1));
int B=Integer.parseInt(S.substring(1,2));
int C=Integer.parseInt(S.substring(2,3));
int D=Integer.parseInt(S.substring(3,4));
int tar=7-A;
String cA=S.substring(0,1);
String cB=S.substring(1,2);
String cC=S.substring(2,3);
String cD=S.substring(3,4);
if(B+C+D==tar){
System.out.println(cA+"+"+cB+"+"+cC+"+"+cD+"=7");
return;
}else if(B+C-D==tar){
System.out.println(cA+"+"+cB+"+"+cC+"-"+cD+"=7");
return;
}else if(B-C+D==tar){
System.out.println(cA+"+"+cB+"-"+cC+"+"+cD+"=7");
return;
}else if(B-C-D==tar){
System.out.println(cA+"+"+cB+"-"+cC+"-"+cD+"=7");
return;
}else if(-B+C+D==tar){
System.out.println(cA+"-"+cB+"+"+cC+"+"+cD+"=7");
return;
}else if(-B+C-D==tar){
System.out.println(cA+"-"+cB+"+"+cC+"-"+cD+"=7");
return;
}else if(-B-C+D==tar){
System.out.println(cA+"-"+cB+"-"+cC+"+"+cD+"=7");
return;
}else if(-B-C-D==tar){
System.out.println(cA+"-"+cB+"-"+cC+"-"+cD+"=7");
return;
}
}
}
| No | Do these codes solve the same problem?
Code 1: #include <stdio.h>
int t[100],k[100],s[100];
void Answer(int j);
int main(void){
int a,b,c,i,j;
char str[100];
for(j=0; ;j++){
fgets(str,sizeof(str),stdin);
sscanf(str,"%d %d %d",&a,&b,&c);
if(a==-1 && b ==-1) break;
t[j]=a; k[j]=b; s[j]=c;
}
Answer(j);
return 0;
}
void Answer(int j){
int i;
for(i=0;i<j;i++){
if((t[i]==-1) || (k[i]==-1))
printf("F\n");
else if(t[i]+k[i]<30)
printf("F\n");
else if((30<=t[i]+k[i] && t[i]+k[i]<50) && s[i]<50)
printf("D\n");
else if((30<=t[i]+k[i] && t[i]+k[i]<50) && s[i]>=50)
printf("C\n");
else if((50<=t[i]+k[i] && t[i]+k[i]<65))
printf("C\n");
else if((65<=t[i]+k[i]) && (t[i]+k[i]<80))
printf("B\n");
else if(80<=t[i]+k[i])
printf("A\n");
}
}
Code 2:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String S = sc.next();
int A=Integer.parseInt(S.substring(0,1));
int B=Integer.parseInt(S.substring(1,2));
int C=Integer.parseInt(S.substring(2,3));
int D=Integer.parseInt(S.substring(3,4));
int tar=7-A;
String cA=S.substring(0,1);
String cB=S.substring(1,2);
String cC=S.substring(2,3);
String cD=S.substring(3,4);
if(B+C+D==tar){
System.out.println(cA+"+"+cB+"+"+cC+"+"+cD+"=7");
return;
}else if(B+C-D==tar){
System.out.println(cA+"+"+cB+"+"+cC+"-"+cD+"=7");
return;
}else if(B-C+D==tar){
System.out.println(cA+"+"+cB+"-"+cC+"+"+cD+"=7");
return;
}else if(B-C-D==tar){
System.out.println(cA+"+"+cB+"-"+cC+"-"+cD+"=7");
return;
}else if(-B+C+D==tar){
System.out.println(cA+"-"+cB+"+"+cC+"+"+cD+"=7");
return;
}else if(-B+C-D==tar){
System.out.println(cA+"-"+cB+"+"+cC+"-"+cD+"=7");
return;
}else if(-B-C+D==tar){
System.out.println(cA+"-"+cB+"-"+cC+"+"+cD+"=7");
return;
}else if(-B-C-D==tar){
System.out.println(cA+"-"+cB+"-"+cC+"-"+cD+"=7");
return;
}
}
}
|
C++ | #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using pp = pair<ll,ll>;
const ll amari = 1e9+7;
const char BC = 'A' - 'a';
#define ben(a) a.begin(),a.end()
#define pb(a,b) a.push_back(b)
//fixed << setprecision(20)
int main(){
string s;
cin >> s;
int ok = 0;
if(s[0] == s[1] || s[1] == s[2] || s[2] == s[3])ok = 1;
if(ok)cout << "Bad" << endl;
else cout << "Good" << endl;
return 0;
} | Python | import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
return list(map(int,input().split()))
def m():
return map(int,input().split())
def onem():
return int(input())
def s(x):
a = []
aa = x[0]
su = 1
for i in range(len(x)-1):
if aa == x[i+1]:
a.append([aa,su])
aa = x[i+1]
su = 1
else:
su += 1
a.append([aa,su])
return a
def jo(x):
return " ".join(map(str,x))
w,h,x,y= m()
if w/2 == x and h/2 == y:
print("{0} {1}".format(w*h/2,1))
else:
print("{0} {1}".format(w*h/2,0))
| No | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using pp = pair<ll,ll>;
const ll amari = 1e9+7;
const char BC = 'A' - 'a';
#define ben(a) a.begin(),a.end()
#define pb(a,b) a.push_back(b)
//fixed << setprecision(20)
int main(){
string s;
cin >> s;
int ok = 0;
if(s[0] == s[1] || s[1] == s[2] || s[2] == s[3])ok = 1;
if(ok)cout << "Bad" << endl;
else cout << "Good" << endl;
return 0;
}
Code 2: import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
return list(map(int,input().split()))
def m():
return map(int,input().split())
def onem():
return int(input())
def s(x):
a = []
aa = x[0]
su = 1
for i in range(len(x)-1):
if aa == x[i+1]:
a.append([aa,su])
aa = x[i+1]
su = 1
else:
su += 1
a.append([aa,su])
return a
def jo(x):
return " ".join(map(str,x))
w,h,x,y= m()
if w/2 == x and h/2 == y:
print("{0} {1}".format(w*h/2,1))
else:
print("{0} {1}".format(w*h/2,0))
|
Java | import java.util.*;
public class Main {
static List<Integer> henkan(String n){
List<Integer> m = new ArrayList<Integer>();
for(int i=0;i<n.length();i++)m.add(Integer.parseInt(n.charAt(i)+""));
return m;
}
static int big (List<Integer> m){
String a = "";
Collections.sort(m);
for(int s=m.size()-1;s>=0;s--)a+=m.get(s);
return Integer.parseInt(a);
}
static int small (List<Integer> m){
String a = "";
Collections.sort(m);
for(int s=0;s<m.size();s++)a+=m.get(s);
return Integer.parseInt(a);
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n=in.nextInt();
for(int k=0;k<n;k++){
String input = in.next();
List<Integer> m = henkan(input);
System.out.println(big(m)-small(m));
}
}
} | Python | n = int(input())
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = dp[i - 1] + 1
power = 6
while power <= i:
dp[i] = min(dp[i], dp[i - power] + 1)
power *= 6
power = 9
while power <= i:
dp[i] = min(dp[i], dp[i - power] + 1)
power *= 9
print(dp[n])
| No | Do these codes solve the same problem?
Code 1: import java.util.*;
public class Main {
static List<Integer> henkan(String n){
List<Integer> m = new ArrayList<Integer>();
for(int i=0;i<n.length();i++)m.add(Integer.parseInt(n.charAt(i)+""));
return m;
}
static int big (List<Integer> m){
String a = "";
Collections.sort(m);
for(int s=m.size()-1;s>=0;s--)a+=m.get(s);
return Integer.parseInt(a);
}
static int small (List<Integer> m){
String a = "";
Collections.sort(m);
for(int s=0;s<m.size();s++)a+=m.get(s);
return Integer.parseInt(a);
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n=in.nextInt();
for(int k=0;k<n;k++){
String input = in.next();
List<Integer> m = henkan(input);
System.out.println(big(m)-small(m));
}
}
}
Code 2: n = int(input())
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = dp[i - 1] + 1
power = 6
while power <= i:
dp[i] = min(dp[i], dp[i - power] + 1)
power *= 6
power = 9
while power <= i:
dp[i] = min(dp[i], dp[i - power] + 1)
power *= 9
print(dp[n])
|
TypeScript | import { readFileSync } from "fs";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const range = (n: number | bigint) => [...Array(Number(n))].map((_, i) => i);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const tuple = <T extends unknown[]>(...ts: T) => ts;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [cin, nCin, bCin] = (() => {
const inputs = readFileSync("/dev/stdin", "utf-8").split(/[\n|\s]+/);
let count = 0;
const cin = () => inputs[count++];
return tuple(
cin,
() => Number(cin()),
() => BigInt(cin())
);
})();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const isNumber = (x: unknown): x is number => typeof x === "number";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const isBigint = (x: unknown): x is bigint => typeof x === "bigint";
type NumberOrBigintOrElse<T> = number | bigint extends T
? undefined
: T extends number
? number
: T extends bigint
? bigint
: undefined;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const max = <T extends number | bigint>(...ts: T[]) =>
(ts.length === 0
? undefined
: isNumber(ts[0])
? Math.max(...(ts as number[]))
: (ts as bigint[]).reduce((acc, t) =>
acc >= t ? acc : t
)) as NumberOrBigintOrElse<T>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const min = <T extends number | bigint>(...ts: T[]) =>
(ts.length === 0
? undefined
: isNumber(ts[0])
? Math.min(...(ts as number[]))
: (ts as bigint[]).reduce((acc, t) =>
acc <= t ? acc : t
)) as NumberOrBigintOrElse<T>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const abs = <T extends number | bigint>(t: T) =>
(isNumber(t)
? Math.abs(t)
: isBigint(t)
? t >= 0n
? t
: -t
: undefined) as NumberOrBigintOrElse<T>;
/**
* Program
*/
const P = 10n ** 9n + 7n;
const addP = (x: bigint, y: bigint) => ((x % P) + (y % P)) % P;
const subP = (x: bigint, y: bigint) => ((x % P) - (y % P) + P) % P;
const prodP = (x: bigint, y: bigint) => ((x % P) * (y % P)) % P;
const pow = (x: bigint, n: bigint): bigint => {
let tmpN = n;
const isEvens: boolean[] = [];
while (tmpN !== 1n) {
isEvens.push(tmpN % 2n === 0n);
tmpN /= 2n;
}
return isEvens.reduceRight((acc, b) => {
const tmp = prodP(acc, acc);
return b ? tmp : prodP(x, tmp);
}, x);
};
const getAns = (N: bigint): string =>
addP(subP(pow(10n, N), prodP(2n, pow(9n, N))), pow(8n, N)).toString();
{
const N = bCin();
const ans = getAns(N);
console.log(ans);
}
| Java | import java.util.Scanner;
class Main{
public void yatary() {
Scanner sc = new Scanner(System.in);
int a;
int b;
int c;
int i;
int x;
int y=0;
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
for(i=a;i<=b;i++){
x = c%i;
if(x==0){
y++;
}
}
System.out.println(y);
}
public static void main(String[] args){
new Main().yatary();
}
} | No | Do these codes solve the same problem?
Code 1: import { readFileSync } from "fs";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const range = (n: number | bigint) => [...Array(Number(n))].map((_, i) => i);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const tuple = <T extends unknown[]>(...ts: T) => ts;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [cin, nCin, bCin] = (() => {
const inputs = readFileSync("/dev/stdin", "utf-8").split(/[\n|\s]+/);
let count = 0;
const cin = () => inputs[count++];
return tuple(
cin,
() => Number(cin()),
() => BigInt(cin())
);
})();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const isNumber = (x: unknown): x is number => typeof x === "number";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const isBigint = (x: unknown): x is bigint => typeof x === "bigint";
type NumberOrBigintOrElse<T> = number | bigint extends T
? undefined
: T extends number
? number
: T extends bigint
? bigint
: undefined;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const max = <T extends number | bigint>(...ts: T[]) =>
(ts.length === 0
? undefined
: isNumber(ts[0])
? Math.max(...(ts as number[]))
: (ts as bigint[]).reduce((acc, t) =>
acc >= t ? acc : t
)) as NumberOrBigintOrElse<T>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const min = <T extends number | bigint>(...ts: T[]) =>
(ts.length === 0
? undefined
: isNumber(ts[0])
? Math.min(...(ts as number[]))
: (ts as bigint[]).reduce((acc, t) =>
acc <= t ? acc : t
)) as NumberOrBigintOrElse<T>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const abs = <T extends number | bigint>(t: T) =>
(isNumber(t)
? Math.abs(t)
: isBigint(t)
? t >= 0n
? t
: -t
: undefined) as NumberOrBigintOrElse<T>;
/**
* Program
*/
const P = 10n ** 9n + 7n;
const addP = (x: bigint, y: bigint) => ((x % P) + (y % P)) % P;
const subP = (x: bigint, y: bigint) => ((x % P) - (y % P) + P) % P;
const prodP = (x: bigint, y: bigint) => ((x % P) * (y % P)) % P;
const pow = (x: bigint, n: bigint): bigint => {
let tmpN = n;
const isEvens: boolean[] = [];
while (tmpN !== 1n) {
isEvens.push(tmpN % 2n === 0n);
tmpN /= 2n;
}
return isEvens.reduceRight((acc, b) => {
const tmp = prodP(acc, acc);
return b ? tmp : prodP(x, tmp);
}, x);
};
const getAns = (N: bigint): string =>
addP(subP(pow(10n, N), prodP(2n, pow(9n, N))), pow(8n, N)).toString();
{
const N = bCin();
const ans = getAns(N);
console.log(ans);
}
Code 2: import java.util.Scanner;
class Main{
public void yatary() {
Scanner sc = new Scanner(System.in);
int a;
int b;
int c;
int i;
int x;
int y=0;
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
for(i=a;i<=b;i++){
x = c%i;
if(x==0){
y++;
}
}
System.out.println(y);
}
public static void main(String[] args){
new Main().yatary();
}
} |
C | #include<stdio.h>
const int sz = 1<<23;
const long mod = 998244353l;
long modpow(long x, long y, long m){
long res = 1l, tmp = x;
while(y){
if(y&1) res = res * tmp % m;
tmp = tmp * tmp % m;
y >>= 1;
}
return res;
}
void dft(long f[], int n){
if(n == 1)return;
long f0[n/2], f1[n/2];
for(int i=0; i<n/2; i++){
f0[i] = f[2*i + 0];
f1[i] = f[2*i + 1];
}
dft(f0, n/2);
dft(f1, n/2);
long zeta = modpow(15311432, sz / n, mod), pow_zeta = 1l;
for(int i=0; i<n; i++){
f[i] = (f0[i % (n/2)] + pow_zeta * f1[i % (n/2)]) % mod;
pow_zeta = (pow_zeta * zeta) % mod;
}
return;
}
void idft(long f[], int n){
if(n == 1)return;
long f0[n/2], f1[n/2];
for(int i=0; i<n/2; i++){
f0[i] = f[2*i + 0];
f1[i] = f[2*i + 1];
}
idft(f0, n/2);
idft(f1, n/2);
long zeta = modpow(469870224, sz / n, mod), pow_zeta = 1l;
for(int i=0; i<n; i++){
f[i] = (f0[i % (n/2)] + pow_zeta * f1[i % (n/2)]) % mod;
pow_zeta = (pow_zeta * zeta) % mod;
}
return;
}
#define t 1<<20
long a[t], b[t];
int N, M;
int main(){
scanf("%d%d", &N, &M);
for(int i=0; i<N; i++)scanf("%ld", &a[i]);
for(int i=0; i<M; i++)scanf("%ld", &b[i]);
dft(a, t); dft(b, t);
for(int i=0; i<t; i++)a[i] = (a[i]*b[i]) % mod;
idft(a, t);
for(int i=0; i<N+M-1; i++){
if(i)putchar(32);
printf("%ld", a[i] * 998243401 % mod);
}putchar(10);
return 0;
} | Go | package main
/*
#define true 1
#define false 0
#define bool int
// @param m `1 <= m`
// @return x mod m
long long safe_mod(long long x, long long m) {
x %= m;
if (x < 0) x += m;
return x;
}
// Fast moduler by barrett reduction
// Reference: https://en.wikipedia.org/wiki/Barrett_reduction
// NOTE: reconsider after Ice Lake
//
// @param a `0 <= a < m`
// @param b `0 <= b < m`
// @return `a * b % m`
unsigned int barrett_mul(unsigned int _m, unsigned long long im, unsigned int a,
unsigned int b) {
// [1] m = 1
// a = b = im = 0, so okay
// [2] m >= 2
// im = ceil(2^64 / m)
// -> im * m = 2^64 + r (0 <= r < m)
// let z = a*b = c*m + d (0 <= c, d < m)
// a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im
// c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1)
// < 2^64 * 2
// ((ab * im) >> 64) == c or c + 1
unsigned long long z = a;
z *= b;
#ifdef _MSC_VER
unsigned long long x;
_umul128(z, im, &x);
#else
unsigned long long x =
(unsigned long long)(((unsigned __int128)(z)*im) >> 64);
#endif
unsigned int v = (unsigned int)(z - x * _m);
if (_m <= v) v += _m;
return v;
}
unsigned long long barrett_im(unsigned int m) {
return (unsigned long long)(-1) / m + 1;
}
// @param n `0 <= n`
// @param m `1 <= m`
// @return `(x ** n) % m`
long long pow_mod(long long x, long long n, int m) {
if (m == 1) return 0;
unsigned int _m = (unsigned int)(m);
unsigned long long r = 1;
unsigned long long y = safe_mod(x, m);
while (n) {
if (n & 1) r = (r * y) % _m;
y = (y * y) % _m;
n >>= 1;
}
return r;
}
// Reference:
// M. Forisek and J. Jancina,
// Fast Primality Testing for Integers That Fit into a Machine Word
// @param n `0 <= n`
bool is_prime(int n) {
if (n <= 1) return false;
if (n == 2 || n == 7 || n == 61) return true;
if (n % 2 == 0) return false;
long long d = n - 1;
while (d % 2 == 0) d /= 2;
long long as[] = {2, 7, 61};
for (int i = 0; i < sizeof(as) / sizeof(long long); i++) {
long long a = as[i];
long long t = d;
long long y = pow_mod(a, t, n);
while (t != n - 1 && y != 1 && y != n - 1) {
y = y * y % n;
t <<= 1;
}
if (y != n - 1 && t % 2 == 0) {
return false;
}
}
return true;
}
// @param b `1 <= b`
// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g
void inv_gcd(long long a, long long b, long long *g, long long *x) {
a = safe_mod(a, b);
if (a == 0) {
*g = b;
*x = 0;
return;
}
// Contracts:
// [1] s - m0 * a = 0 (mod b)
// [2] t - m1 * a = 0 (mod b)
// [3] s * |m1| + t * |m0| <= b
long long s = b, t = a;
long long m0 = 0, m1 = 1;
while (t) {
long long u = s / t;
s -= t * u;
m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b
// [3]:
// (s - t * u) * |m1| + t * |m0 - m1 * u|
// <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)
// = s * |m1| + t * |m0| <= b
long long tmp = s;
s = t;
t = tmp;
tmp = m0;
m0 = m1;
m1 = tmp;
}
// by [3]: |m0| <= b/g
// by g != b: |m0| < b/g
if (m0 < 0) m0 += b / s;
*g = s;
*x = m0;
return;
}
// Compile time primitive root
// @param m must be prime
// @return primitive root (and minimum in now)
int primitive_root(int m) {
if (m == 2) return 1;
if (m == 167772161) return 3;
if (m == 469762049) return 3;
if (m == 754974721) return 11;
if (m == 998244353) return 3;
int divs[20] = {};
divs[0] = 2;
int cnt = 1;
int x = (m - 1) / 2;
while (x % 2 == 0) x /= 2;
for (int i = 3; (long long)(i)*i <= x; i += 2) {
if (x % i == 0) {
divs[cnt++] = i;
while (x % i == 0) {
x /= i;
}
}
}
if (x > 1) {
divs[cnt++] = x;
}
for (int g = 2;; g++) {
bool ok = true;
for (int i = 0; i < cnt; i++) {
if (pow_mod(g, (m - 1) / divs[i], m) == 1) {
ok = false;
break;
}
}
if (ok) return g;
}
}
*/
import "C" // do not insert blank lines above
import (
"bufio"
"bytes"
"fmt"
"io"
"math/bits"
"os"
"strconv"
)
var DEBUG = true
func main() {
defer Flush()
N := readi()
M := readi()
_, a := readInts(N)
_, b := readInts(M)
c := Convolution998244353Int(a, b)
sp := ""
for i := 0; i < len(c); i++ {
printf("%s%d", sp, c[i])
sp = " "
}
println()
}
// Code generated by genmaps.go; DO NOT EDIT.
type Mod1000000007Int int
func NewMod1000000007Int(v int) Mod1000000007Int {
return Mod1000000007Int(v % 1000000007)
}
func (v Mod1000000007Int) Mod() int {
return 1000000007
}
func (v Mod1000000007Int) Val() int {
return int(v)
}
func (v Mod1000000007Int) Negate() Mod1000000007Int {
return 1000000007 - v
}
func (v *Mod1000000007Int) Inc() {
*v = (*v + 1) % 1000000007
}
func (v *Mod1000000007Int) Dec() {
*v = (*v - 1 + 1000000007) % 1000000007
}
func (v Mod1000000007Int) Add(x Mod1000000007Int) Mod1000000007Int {
return (v + x) % 1000000007
}
func (v Mod1000000007Int) Sub(x Mod1000000007Int) Mod1000000007Int {
return (v + 1000000007 - x) % 1000000007
}
func (v Mod1000000007Int) Mul(x Mod1000000007Int) Mod1000000007Int {
return (v * x) % 1000000007
}
func (v Mod1000000007Int) Div(x Mod1000000007Int) Mod1000000007Int {
return (v * x.Inv()) % 1000000007
}
func (v Mod1000000007Int) Pow(n int) Mod1000000007Int {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return 1
}
x := int(v)
r := int(1)
for 0 < n {
if n&1 == 1 {
r = r * x % 1000000007
}
x = x * x % 1000000007
n >>= 1
}
return Mod1000000007Int(r)
}
func (v Mod1000000007Int) Inv() Mod1000000007Int {
if true {
if v == 0 {
panic("must be non zero")
}
return v.Pow(1000000007 - 2)
} else {
g, x := InvGCD(int64(v), 1000000007)
if g != 1 {
panic("g != 1")
}
return Mod1000000007Int(x)
}
}
type Mod998244353Int int
func NewMod998244353Int(v int) Mod998244353Int {
return Mod998244353Int(v % 998244353)
}
func (v Mod998244353Int) Mod() int {
return 998244353
}
func (v Mod998244353Int) Val() int {
return int(v)
}
func (v Mod998244353Int) Negate() Mod998244353Int {
return 998244353 - v
}
func (v *Mod998244353Int) Inc() {
*v = (*v + 1) % 998244353
}
func (v *Mod998244353Int) Dec() {
*v = (*v - 1 + 998244353) % 998244353
}
func (v Mod998244353Int) Add(x Mod998244353Int) Mod998244353Int {
return (v + x) % 998244353
}
func (v Mod998244353Int) Sub(x Mod998244353Int) Mod998244353Int {
return (v + 998244353 - x) % 998244353
}
func (v Mod998244353Int) Mul(x Mod998244353Int) Mod998244353Int {
return (v * x) % 998244353
}
func (v Mod998244353Int) Div(x Mod998244353Int) Mod998244353Int {
return (v * x.Inv()) % 998244353
}
func (v Mod998244353Int) Pow(n int) Mod998244353Int {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return 1
}
x := int(v)
r := int(1)
for 0 < n {
if n&1 == 1 {
r = r * x % 998244353
}
x = x * x % 998244353
n >>= 1
}
return Mod998244353Int(r)
}
func (v Mod998244353Int) Inv() Mod998244353Int {
if true {
if v == 0 {
panic("must be non zero")
}
return v.Pow(998244353 - 2)
} else {
g, x := InvGCD(int64(v), 998244353)
if g != 1 {
panic("g != 1")
}
return Mod998244353Int(x)
}
}
type Mod1000000007Int64 int64
func NewMod1000000007Int64(v int64) Mod1000000007Int64 {
return Mod1000000007Int64(v % 1000000007)
}
func (v Mod1000000007Int64) Mod() int64 {
return 1000000007
}
func (v Mod1000000007Int64) Val() int64 {
return int64(v)
}
func (v Mod1000000007Int64) Negate() Mod1000000007Int64 {
return 1000000007 - v
}
func (v *Mod1000000007Int64) Inc() {
*v = (*v + 1) % 1000000007
}
func (v *Mod1000000007Int64) Dec() {
*v = (*v - 1 + 1000000007) % 1000000007
}
func (v Mod1000000007Int64) Add(x Mod1000000007Int64) Mod1000000007Int64 {
return (v + x) % 1000000007
}
func (v Mod1000000007Int64) Sub(x Mod1000000007Int64) Mod1000000007Int64 {
return (v + 1000000007 - x) % 1000000007
}
func (v Mod1000000007Int64) Mul(x Mod1000000007Int64) Mod1000000007Int64 {
return (v * x) % 1000000007
}
func (v Mod1000000007Int64) Div(x Mod1000000007Int64) Mod1000000007Int64 {
return (v * x.Inv()) % 1000000007
}
func (v Mod1000000007Int64) Pow(n int64) Mod1000000007Int64 {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return 1
}
x := int64(v)
r := int64(1)
for 0 < n {
if n&1 == 1 {
r = r * x % 1000000007
}
x = x * x % 1000000007
n >>= 1
}
return Mod1000000007Int64(r)
}
func (v Mod1000000007Int64) Inv() Mod1000000007Int64 {
if true {
if v == 0 {
panic("must be non zero")
}
return v.Pow(1000000007 - 2)
} else {
g, x := InvGCD(int64(v), 1000000007)
if g != 1 {
panic("g != 1")
}
return Mod1000000007Int64(x)
}
}
type Mod998244353Int64 int64
func NewMod998244353Int64(v int64) Mod998244353Int64 {
return Mod998244353Int64(v % 998244353)
}
func (v Mod998244353Int64) Mod() int64 {
return 998244353
}
func (v Mod998244353Int64) Val() int64 {
return int64(v)
}
func (v Mod998244353Int64) Negate() Mod998244353Int64 {
return 998244353 - v
}
func (v *Mod998244353Int64) Inc() {
*v = (*v + 1) % 998244353
}
func (v *Mod998244353Int64) Dec() {
*v = (*v - 1 + 998244353) % 998244353
}
func (v Mod998244353Int64) Add(x Mod998244353Int64) Mod998244353Int64 {
return (v + x) % 998244353
}
func (v Mod998244353Int64) Sub(x Mod998244353Int64) Mod998244353Int64 {
return (v + 998244353 - x) % 998244353
}
func (v Mod998244353Int64) Mul(x Mod998244353Int64) Mod998244353Int64 {
return (v * x) % 998244353
}
func (v Mod998244353Int64) Div(x Mod998244353Int64) Mod998244353Int64 {
return (v * x.Inv()) % 998244353
}
func (v Mod998244353Int64) Pow(n int64) Mod998244353Int64 {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return 1
}
x := int64(v)
r := int64(1)
for 0 < n {
if n&1 == 1 {
r = r * x % 998244353
}
x = x * x % 998244353
n >>= 1
}
return Mod998244353Int64(r)
}
func (v Mod998244353Int64) Inv() Mod998244353Int64 {
if true {
if v == 0 {
panic("must be non zero")
}
return v.Pow(998244353 - 2)
} else {
g, x := InvGCD(int64(v), 998244353)
if g != 1 {
panic("g != 1")
}
return Mod998244353Int64(x)
}
}
type DynamicModInt struct {
v int64
bt Barrett
isPrime bool
}
func NewDynamicModInt(v int) DynamicModInt {
return DynamicModInt{
v: int64(v),
}
}
func (d *DynamicModInt) SetMod(m int) {
if m < 1 {
panic("modulo must be more than 0")
}
d.bt = NewBarrett(uint(m))
d.v %= d.umod()
d.isPrime = IsPrime(m)
}
func (d DynamicModInt) umod() int64 {
return int64(d.bt.Umod())
}
func (d DynamicModInt) Mod() int {
return int(d.umod())
}
func (d DynamicModInt) Val() int {
return int(d.v)
}
func (d DynamicModInt) Negate() DynamicModInt {
return DynamicModInt{
v: d.umod() - d.v,
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d *DynamicModInt) Inc() {
d.v = (d.v + 1) % d.umod()
}
func (d *DynamicModInt) Dec() {
d.v = (d.v - 1 + d.umod()) % d.umod()
}
func (d DynamicModInt) Add(x DynamicModInt) DynamicModInt {
return DynamicModInt{
v: (d.v + x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Sub(x DynamicModInt) DynamicModInt {
return DynamicModInt{
v: (d.v + d.umod() - x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Mul(x DynamicModInt) DynamicModInt {
return DynamicModInt{
v: (d.v * x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Div(x DynamicModInt) DynamicModInt {
return DynamicModInt{
v: (d.v * x.Inv().v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Pow(n int) DynamicModInt {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return DynamicModInt{
v: 1,
bt: d.bt,
isPrime: d.isPrime,
}
}
x := int64(d.v)
r := int64(1)
for 0 < n {
if n&1 == 1 {
r = r * x % d.umod()
}
x = x * x % d.umod()
n >>= 1
}
return DynamicModInt{
v: r,
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Inv() DynamicModInt {
if d.isPrime {
if d.v == 0 {
panic("must be non zero")
}
return d.Pow(int(d.umod()) - 2)
} else {
g, x := InvGCD(int64(d.v), d.umod())
if g != 1 {
panic("g != 1")
}
return DynamicModInt{
v: x,
bt: d.bt,
isPrime: d.isPrime,
}
}
}
type DynamicModInt64 struct {
v int64
bt Barrett
isPrime bool
}
func NewDynamicModInt64(v int64) DynamicModInt64 {
return DynamicModInt64{
v: int64(v),
}
}
func (d *DynamicModInt64) SetMod(m int) {
if m < 1 {
panic("modulo must be more than 0")
}
d.bt = NewBarrett(uint(m))
d.v %= d.umod()
d.isPrime = IsPrime(m)
}
func (d DynamicModInt64) umod() int64 {
return int64(d.bt.Umod())
}
func (d DynamicModInt64) Mod() int64 {
return int64(d.umod())
}
func (d DynamicModInt64) Val() int64 {
return int64(d.v)
}
func (d DynamicModInt64) Negate() DynamicModInt64 {
return DynamicModInt64{
v: d.umod() - d.v,
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d *DynamicModInt64) Inc() {
d.v = (d.v + 1) % d.umod()
}
func (d *DynamicModInt64) Dec() {
d.v = (d.v - 1 + d.umod()) % d.umod()
}
func (d DynamicModInt64) Add(x DynamicModInt64) DynamicModInt64 {
return DynamicModInt64{
v: (d.v + x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Sub(x DynamicModInt64) DynamicModInt64 {
return DynamicModInt64{
v: (d.v + d.umod() - x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Mul(x DynamicModInt64) DynamicModInt64 {
return DynamicModInt64{
v: (d.v * x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Div(x DynamicModInt64) DynamicModInt64 {
return DynamicModInt64{
v: (d.v * x.Inv().v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Pow(n int64) DynamicModInt64 {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return DynamicModInt64{
v: 1,
bt: d.bt,
isPrime: d.isPrime,
}
}
x := int64(d.v)
r := int64(1)
for 0 < n {
if n&1 == 1 {
r = r * x % d.umod()
}
x = x * x % d.umod()
n >>= 1
}
return DynamicModInt64{
v: r,
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Inv() DynamicModInt64 {
if d.isPrime {
if d.v == 0 {
panic("must be non zero")
}
return d.Pow(int64(d.umod()) - 2)
} else {
g, x := InvGCD(int64(d.v), d.umod())
if g != 1 {
panic("g != 1")
}
return DynamicModInt64{
v: x,
bt: d.bt,
isPrime: d.isPrime,
}
}
}
// Code generated by genmaps.go; DO NOT EDIT.
var (
butterfly1000000007Int_sum_e [30]Mod1000000007Int
)
func init() {
g := PrimitiveRoot(1000000007) % 1000000007
var es [30]Mod1000000007Int
var ies [30]Mod1000000007Int
cnt2 := BSF(1000000007 - 1)
e := Mod1000000007Int(g).Pow((1000000007 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod1000000007Int(1)
for i := 0; i < cnt2; i++ {
butterfly1000000007Int_sum_e[i] = es[i].Mul(now)
now = now.Mul(ies[i])
}
}
func butterfly1000000007Int(a []Mod1000000007Int) {
n := len(a)
h := CeilPow2(n)
for ph := 1; ph <= h; ph++ {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
now := Mod1000000007Int(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p].Mul(now)
a[i+offset] = l.Add(r)
a[i+offset+p] = l.Sub(r)
}
now = now.Mul(butterfly1000000007Int_sum_e[BSF(^(uint(s)))])
}
}
}
var (
butterflyInv1000000007Int_sum_e [30]Mod1000000007Int
)
func init() {
g := PrimitiveRoot(1000000007) % 1000000007
var es [30]Mod1000000007Int
var ies [30]Mod1000000007Int
cnt2 := BSF(1000000007 - 1)
e := Mod1000000007Int(g).Pow((1000000007 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod1000000007Int(1)
for i := 0; i < cnt2-2; i++ {
butterflyInv1000000007Int_sum_e[i] = ies[i].Mul(now)
now = now.Mul(es[i])
}
}
func butterflyInv1000000007Int(a []Mod1000000007Int) {
n := len(a)
h := CeilPow2(n)
for ph := h; ph >= 1; ph-- {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
inow := Mod1000000007Int(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p]
a[i+offset] = l.Add(r)
a[i+offset+p] = Mod1000000007Int(uint64(1000000007+l.Val()-r.Val()) % uint64(1000000007) * uint64(inow.Val()) % uint64(1000000007))
}
inow = inow.Mul(butterflyInv1000000007Int_sum_e[BSF(^(uint(s)))])
}
}
}
func ConvolutionMod1000000007Int(a, b []Mod1000000007Int) []Mod1000000007Int {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
resize := func(a []Mod1000000007Int, z int) []Mod1000000007Int {
n := len(a)
if n < z {
return append(a, make([]Mod1000000007Int, z-n)...)
}
return a[:z]
}
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]Mod1000000007Int, 0)
}
if min(n, m) <= 60 {
if n < m {
n, m = m, n
a, b = b, a
}
ans := make([]Mod1000000007Int, n+m-1)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
ans[i+j] = ans[i+j].Add(a[i].Mul(b[j]))
}
}
return ans
}
z := 1 << CeilPow2(n+m-1)
a = resize(a, z)
butterfly1000000007Int(a)
b = resize(b, z)
butterfly1000000007Int(b)
for i := 0; i < z; i++ {
a[i] = a[i].Mul(b[i])
}
butterflyInv1000000007Int(a)
resize(a, n+m-1)
iz := NewMod1000000007Int(int(z)).Inv()
for i := 0; i < n+m-1; i++ {
a[i] = a[i].Mul(iz)
}
return a
}
func Convolution1000000007Int(a, b []int) []int {
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]int, 0)
}
a2 := make([]Mod1000000007Int, n)
b2 := make([]Mod1000000007Int, m)
for i := range a {
a2[i] = NewMod1000000007Int(a[i])
}
for i := range b {
b2[i] = NewMod1000000007Int(b[i])
}
c2 := ConvolutionMod1000000007Int(a2, b2)
c := make([]int, n+m-1)
for i := 0; i < n+m-1; i++ {
c[i] = c2[i].Val()
}
return c
}
var (
butterfly998244353Int_sum_e [30]Mod998244353Int
)
func init() {
g := PrimitiveRoot(998244353) % 998244353
var es [30]Mod998244353Int
var ies [30]Mod998244353Int
cnt2 := BSF(998244353 - 1)
e := Mod998244353Int(g).Pow((998244353 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod998244353Int(1)
for i := 0; i < cnt2; i++ {
butterfly998244353Int_sum_e[i] = es[i].Mul(now)
now = now.Mul(ies[i])
}
}
func butterfly998244353Int(a []Mod998244353Int) {
n := len(a)
h := CeilPow2(n)
for ph := 1; ph <= h; ph++ {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
now := Mod998244353Int(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p].Mul(now)
a[i+offset] = l.Add(r)
a[i+offset+p] = l.Sub(r)
}
now = now.Mul(butterfly998244353Int_sum_e[BSF(^(uint(s)))])
}
}
}
var (
butterflyInv998244353Int_sum_e [30]Mod998244353Int
)
func init() {
g := PrimitiveRoot(998244353) % 998244353
var es [30]Mod998244353Int
var ies [30]Mod998244353Int
cnt2 := BSF(998244353 - 1)
e := Mod998244353Int(g).Pow((998244353 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod998244353Int(1)
for i := 0; i < cnt2-2; i++ {
butterflyInv998244353Int_sum_e[i] = ies[i].Mul(now)
now = now.Mul(es[i])
}
}
func butterflyInv998244353Int(a []Mod998244353Int) {
n := len(a)
h := CeilPow2(n)
for ph := h; ph >= 1; ph-- {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
inow := Mod998244353Int(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p]
a[i+offset] = l.Add(r)
a[i+offset+p] = Mod998244353Int(uint64(998244353+l.Val()-r.Val()) % uint64(998244353) * uint64(inow.Val()) % uint64(998244353))
}
inow = inow.Mul(butterflyInv998244353Int_sum_e[BSF(^(uint(s)))])
}
}
}
func ConvolutionMod998244353Int(a, b []Mod998244353Int) []Mod998244353Int {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
resize := func(a []Mod998244353Int, z int) []Mod998244353Int {
n := len(a)
if n < z {
return append(a, make([]Mod998244353Int, z-n)...)
}
return a[:z]
}
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]Mod998244353Int, 0)
}
if min(n, m) <= 60 {
if n < m {
n, m = m, n
a, b = b, a
}
ans := make([]Mod998244353Int, n+m-1)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
ans[i+j] = ans[i+j].Add(a[i].Mul(b[j]))
}
}
return ans
}
z := 1 << CeilPow2(n+m-1)
a = resize(a, z)
butterfly998244353Int(a)
b = resize(b, z)
butterfly998244353Int(b)
for i := 0; i < z; i++ {
a[i] = a[i].Mul(b[i])
}
butterflyInv998244353Int(a)
resize(a, n+m-1)
iz := NewMod998244353Int(int(z)).Inv()
for i := 0; i < n+m-1; i++ {
a[i] = a[i].Mul(iz)
}
return a
}
func Convolution998244353Int(a, b []int) []int {
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]int, 0)
}
a2 := make([]Mod998244353Int, n)
b2 := make([]Mod998244353Int, m)
for i := range a {
a2[i] = NewMod998244353Int(a[i])
}
for i := range b {
b2[i] = NewMod998244353Int(b[i])
}
c2 := ConvolutionMod998244353Int(a2, b2)
c := make([]int, n+m-1)
for i := 0; i < n+m-1; i++ {
c[i] = c2[i].Val()
}
return c
}
var (
butterfly1000000007Int64_sum_e [30]Mod1000000007Int64
)
func init() {
g := PrimitiveRoot(1000000007) % 1000000007
var es [30]Mod1000000007Int64
var ies [30]Mod1000000007Int64
cnt2 := BSF(1000000007 - 1)
e := Mod1000000007Int64(g).Pow((1000000007 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod1000000007Int64(1)
for i := 0; i < cnt2; i++ {
butterfly1000000007Int64_sum_e[i] = es[i].Mul(now)
now = now.Mul(ies[i])
}
}
func butterfly1000000007Int64(a []Mod1000000007Int64) {
n := len(a)
h := CeilPow2(n)
for ph := 1; ph <= h; ph++ {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
now := Mod1000000007Int64(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p].Mul(now)
a[i+offset] = l.Add(r)
a[i+offset+p] = l.Sub(r)
}
now = now.Mul(butterfly1000000007Int64_sum_e[BSF(^(uint(s)))])
}
}
}
var (
butterflyInv1000000007Int64_sum_e [30]Mod1000000007Int64
)
func init() {
g := PrimitiveRoot(1000000007) % 1000000007
var es [30]Mod1000000007Int64
var ies [30]Mod1000000007Int64
cnt2 := BSF(1000000007 - 1)
e := Mod1000000007Int64(g).Pow((1000000007 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod1000000007Int64(1)
for i := 0; i < cnt2-2; i++ {
butterflyInv1000000007Int64_sum_e[i] = ies[i].Mul(now)
now = now.Mul(es[i])
}
}
func butterflyInv1000000007Int64(a []Mod1000000007Int64) {
n := len(a)
h := CeilPow2(n)
for ph := h; ph >= 1; ph-- {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
inow := Mod1000000007Int64(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p]
a[i+offset] = l.Add(r)
a[i+offset+p] = Mod1000000007Int64(uint64(1000000007+l.Val()-r.Val()) % uint64(1000000007) * uint64(inow.Val()) % uint64(1000000007))
}
inow = inow.Mul(butterflyInv1000000007Int64_sum_e[BSF(^(uint(s)))])
}
}
}
func ConvolutionMod1000000007Int64(a, b []Mod1000000007Int64) []Mod1000000007Int64 {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
resize := func(a []Mod1000000007Int64, z int) []Mod1000000007Int64 {
n := len(a)
if n < z {
return append(a, make([]Mod1000000007Int64, z-n)...)
}
return a[:z]
}
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]Mod1000000007Int64, 0)
}
if min(n, m) <= 60 {
if n < m {
n, m = m, n
a, b = b, a
}
ans := make([]Mod1000000007Int64, n+m-1)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
ans[i+j] = ans[i+j].Add(a[i].Mul(b[j]))
}
}
return ans
}
z := 1 << CeilPow2(n+m-1)
a = resize(a, z)
butterfly1000000007Int64(a)
b = resize(b, z)
butterfly1000000007Int64(b)
for i := 0; i < z; i++ {
a[i] = a[i].Mul(b[i])
}
butterflyInv1000000007Int64(a)
resize(a, n+m-1)
iz := NewMod1000000007Int64(int64(z)).Inv()
for i := 0; i < n+m-1; i++ {
a[i] = a[i].Mul(iz)
}
return a
}
func Convolution1000000007Int64(a, b []int64) []int64 {
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]int64, 0)
}
a2 := make([]Mod1000000007Int64, n)
b2 := make([]Mod1000000007Int64, m)
for i := range a {
a2[i] = NewMod1000000007Int64(a[i])
}
for i := range b {
b2[i] = NewMod1000000007Int64(b[i])
}
c2 := ConvolutionMod1000000007Int64(a2, b2)
c := make([]int64, n+m-1)
for i := 0; i < n+m-1; i++ {
c[i] = c2[i].Val()
}
return c
}
var (
butterfly998244353Int64_sum_e [30]Mod998244353Int64
)
func init() {
g := PrimitiveRoot(998244353) % 998244353
var es [30]Mod998244353Int64
var ies [30]Mod998244353Int64
cnt2 := BSF(998244353 - 1)
e := Mod998244353Int64(g).Pow((998244353 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod998244353Int64(1)
for i := 0; i < cnt2; i++ {
butterfly998244353Int64_sum_e[i] = es[i].Mul(now)
now = now.Mul(ies[i])
}
}
func butterfly998244353Int64(a []Mod998244353Int64) {
n := len(a)
h := CeilPow2(n)
for ph := 1; ph <= h; ph++ {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
now := Mod998244353Int64(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p].Mul(now)
a[i+offset] = l.Add(r)
a[i+offset+p] = l.Sub(r)
}
now = now.Mul(butterfly998244353Int64_sum_e[BSF(^(uint(s)))])
}
}
}
var (
butterflyInv998244353Int64_sum_e [30]Mod998244353Int64
)
func init() {
g := PrimitiveRoot(998244353) % 998244353
var es [30]Mod998244353Int64
var ies [30]Mod998244353Int64
cnt2 := BSF(998244353 - 1)
e := Mod998244353Int64(g).Pow((998244353 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod998244353Int64(1)
for i := 0; i < cnt2-2; i++ {
butterflyInv998244353Int64_sum_e[i] = ies[i].Mul(now)
now = now.Mul(es[i])
}
}
func butterflyInv998244353Int64(a []Mod998244353Int64) {
n := len(a)
h := CeilPow2(n)
for ph := h; ph >= 1; ph-- {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
inow := Mod998244353Int64(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p]
a[i+offset] = l.Add(r)
a[i+offset+p] = Mod998244353Int64(uint64(998244353+l.Val()-r.Val()) % uint64(998244353) * uint64(inow.Val()) % uint64(998244353))
}
inow = inow.Mul(butterflyInv998244353Int64_sum_e[BSF(^(uint(s)))])
}
}
}
func ConvolutionMod998244353Int64(a, b []Mod998244353Int64) []Mod998244353Int64 {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
resize := func(a []Mod998244353Int64, z int) []Mod998244353Int64 {
n := len(a)
if n < z {
return append(a, make([]Mod998244353Int64, z-n)...)
}
return a[:z]
}
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]Mod998244353Int64, 0)
}
if min(n, m) <= 60 {
if n < m {
n, m = m, n
a, b = b, a
}
ans := make([]Mod998244353Int64, n+m-1)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
ans[i+j] = ans[i+j].Add(a[i].Mul(b[j]))
}
}
return ans
}
z := 1 << CeilPow2(n+m-1)
a = resize(a, z)
butterfly998244353Int64(a)
b = resize(b, z)
butterfly998244353Int64(b)
for i := 0; i < z; i++ {
a[i] = a[i].Mul(b[i])
}
butterflyInv998244353Int64(a)
resize(a, n+m-1)
iz := NewMod998244353Int64(int64(z)).Inv()
for i := 0; i < n+m-1; i++ {
a[i] = a[i].Mul(iz)
}
return a
}
func Convolution998244353Int64(a, b []int64) []int64 {
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]int64, 0)
}
a2 := make([]Mod998244353Int64, n)
b2 := make([]Mod998244353Int64, m)
for i := range a {
a2[i] = NewMod998244353Int64(a[i])
}
for i := range b {
b2[i] = NewMod998244353Int64(b[i])
}
c2 := ConvolutionMod998244353Int64(a2, b2)
c := make([]int64, n+m-1)
for i := 0; i < n+m-1; i++ {
c[i] = c2[i].Val()
}
return c
}
func SafeMod(x, m int64) int64 {
return int64(C.safe_mod(C.longlong(x), C.longlong(m)))
}
type Barrett struct {
m C.uint
im C.ulonglong
}
func NewBarrett(m uint) Barrett {
return Barrett{
m: C.uint(m),
im: C.barrett_im(C.uint(m)),
}
}
func (bt Barrett) Umod() uint {
return uint(bt.m)
}
func (bt Barrett) Mul(a, b uint) uint {
return uint(C.barrett_mul(bt.m, bt.im, C.uint(a), C.uint(b)))
}
func PowMod(x, n int64, m int) int64 {
return int64(C.pow_mod(C.longlong(x), C.longlong(n), C.int(m)))
}
func IsPrime(n int) bool {
return C.is_prime(C.int(n)) != 0
}
func InvGCD(a, b int64) (int64, int64) {
var g, x C.longlong
C.inv_gcd(C.longlong(a), C.longlong(b), &g, &x)
return int64(g), int64(x)
}
func PrimitiveRoot(m int) int {
return int(C.primitive_root(C.int(m)))
}
func CeilPow2(n int) int {
x := uint(0)
for uint(1<<x) < uint(n) {
x++
}
return int(x)
}
func BSF(n uint) int {
return bits.TrailingZeros(n)
}
// -----------------------------------------------------------------------------
// IO helper functions
// Returns next token from input. It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)
// Holds a buffer for output. It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer
// Holds an io.Writer. It must be initialized by SetOutput()
var OutputWriter io.Writer
// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
SetUnbefferedInput(r)
OutputBuffer = nil
OutputWriter = w
}
// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
OutputBuffer = bufio.NewWriter(w)
OutputWriter = OutputBuffer
}
// Flushes OutputBuffer
func Flush() {
if OutputBuffer != nil {
OutputBuffer.Flush()
}
}
// Returns true if c is a white space
func IsSpace(c byte) bool {
switch c {
case '\t', '\n', '\v', '\f', '\r', ' ':
return true
}
return false
}
func IsNewLine(c byte) bool {
switch c {
case '\n', '\r':
return true
}
return false
}
// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
buf := new(bytes.Buffer)
var b []byte
var i int
rest := func() ([]byte, error) {
for i < len(b) && IsSpace(b[i]) {
i++
}
if i == len(b) {
return nil, io.ErrUnexpectedEOF
}
j := i
for i < len(b) && !IsSpace(b[i]) {
i++
}
return b[j:i], nil
}
initial := func() ([]byte, error) {
io.Copy(buf, r)
b = buf.Bytes()
nextToken = rest
return rest()
}
nextToken = initial
restLn := func() ([]byte, error) {
for i < len(b) && IsNewLine(b[i]) {
i++
}
if i == len(b) {
return nil, io.ErrUnexpectedEOF
}
j := i
for i < len(b) && !IsNewLine(b[i]) {
i++
}
return b[j:i], nil
}
initialLn := func() ([]byte, error) {
io.Copy(buf, r)
b = buf.Bytes()
nextLine = restLn
return restLn()
}
nextLine = initialLn
}
// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
buf := bufio.NewReader(r)
var b []byte
var i int
nextToken = func() ([]byte, error) {
var err error
if i == len(b) {
b, err = buf.ReadBytes('\n')
if err != nil {
return nil, err
}
i = 0
j := len(b) - 1
for 0 <= j && IsSpace(b[j]) {
j--
}
b = b[0 : j+1]
}
for i < len(b) && IsSpace(b[i]) {
i++
}
j := i
for i < len(b) && !IsSpace(b[i]) {
i++
}
if i == j {
return nil, io.ErrUnexpectedEOF
}
return b[j:i], nil
}
}
// -----------------------------------------------------------------------------
// IO functions
// Reads next token and return it as []byte
func readb() []byte {
b, err := nextToken()
if err != nil {
panic(err)
}
return b[:len(b):len(b)]
}
func readberr() ([]byte, error) {
b, err := nextToken()
return b[:len(b):len(b)], err
}
// Reads next token and return it as string
func reads() string {
return string(readb())
}
func readserr() (string, error) {
b, err := readberr()
return string(b), err
}
// Read next line as []byte. Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
b, err := nextLine()
if err != nil {
panic(err)
}
return b[:len(b):len(b)]
}
func readblnerr() ([]byte, error) {
b, err := nextLine()
return b[:len(b):len(b)], err
}
// Read next line as string
func readsln() string {
return string(readbln())
}
func readslnerr() (string, error) {
b, err := readblnerr()
return string(b), err
}
// Reads next token and return it as int64
func readll() int64 {
i, err := strconv.ParseInt(reads(), 10, 64)
if err != nil {
panic(err.Error())
}
return i
}
func readllerr() (int64, error) {
s, err := readserr()
if err != nil {
return 0, fmt.Errorf("reading string: %w", err)
}
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, fmt.Errorf("parsing int: %w", err)
}
return i, nil
}
// Reads next token and return it as int
func readi() int {
return int(readll())
}
func readierr() (int, error) {
i, err := readllerr()
return int(i), err
}
// Reads next token and return it as float64
func readf() float64 {
f, err := strconv.ParseFloat(reads(), 64)
if err != nil {
panic(err.Error())
}
return f
}
func readferr() (float64, error) {
s, err := readserr()
if err != nil {
return 0, fmt.Errorf("reading string: %w", err)
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, fmt.Errorf("parsing float: %w", err)
}
return f, nil
}
// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
return fmt.Fprintf(OutputWriter, f, args...)
}
// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
return fmt.Fprintln(OutputWriter, args...)
}
// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
return fmt.Fprintf(os.Stderr, f, args...)
}
// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
return fmt.Fprintln(os.Stderr, args...)
}
func dbgf(f string, args ...interface{}) {
if !DEBUG {
return
}
fmt.Fprintf(os.Stderr, f, args...)
}
func dbg(args ...interface{}) {
if !DEBUG {
return
}
fmt.Fprintln(os.Stderr, args...)
}
// -----------------------------------------------------------------------------
// Utilities
func sumSlice(a []int) int {
var res int
for _, v := range a {
res += v
}
return res
}
func sumSlicell(a []int64) int64 {
var res int64
for _, v := range a {
res += v
}
return res
}
func readInts(N int) (int, []int) {
if N == 0 {
N = readi()
}
a := make([]int, N)
for i := range a {
a[i] = readi()
}
return N, a
}
func readIntsll(N int) (int, []int64) {
if N == 0 {
N = readi()
}
a := make([]int64, N)
for i := range a {
a[i] = readll()
}
return N, a
}
// -----------------------------------------------------------------------------
// Simple math functions
const (
// big prime
INF = 1000000007
INF2 = 1000000009
INF3 = 998244353
)
func min(a, b int) int {
if a < b {
return a
}
return b
}
func minll(a, b int64) int64 {
if a < b {
return a
}
return b
}
func minf(a, b float64) float64 {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a < b {
return b
}
return a
}
func maxll(a, b int64) int64 {
if a < b {
return b
}
return a
}
func maxf(a, b float64) float64 {
if a < b {
return b
}
return a
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
func absll(a int64) int64 {
if a < 0 {
return -a
}
return a
}
func absf(a float64) float64 {
if a < 0 {
return -a
}
return a
}
// egcd(a, b) returns d, x, y:
// d is gcd(a,b)
// x, y are integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
if b == 0 {
return a, 1, 0
}
d, x, y := egcd(b, a%b)
return d, y, x - a/b*y
}
func egcdll(a, b int64) (int64, int64, int64) {
if b == 0 {
return a, 1, 0
}
d, x, y := egcdll(b, a%b)
return d, y, x - a/b*y
}
func gcd(a, b int) int {
d, _, _ := egcd(a, b)
return d
}
func gcdll(a, b int64) int64 {
d, _, _ := egcdll(a, b)
return d
}
// set up IO functions
func init() {
// for non-interactive
SetInput(os.Stdin)
SetOutput(os.Stdout)
// Enable below when interactive. Its ok to leave above intact.
// SetInteractive(os.Stdout, os.Stdin)
}
| Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
const int sz = 1<<23;
const long mod = 998244353l;
long modpow(long x, long y, long m){
long res = 1l, tmp = x;
while(y){
if(y&1) res = res * tmp % m;
tmp = tmp * tmp % m;
y >>= 1;
}
return res;
}
void dft(long f[], int n){
if(n == 1)return;
long f0[n/2], f1[n/2];
for(int i=0; i<n/2; i++){
f0[i] = f[2*i + 0];
f1[i] = f[2*i + 1];
}
dft(f0, n/2);
dft(f1, n/2);
long zeta = modpow(15311432, sz / n, mod), pow_zeta = 1l;
for(int i=0; i<n; i++){
f[i] = (f0[i % (n/2)] + pow_zeta * f1[i % (n/2)]) % mod;
pow_zeta = (pow_zeta * zeta) % mod;
}
return;
}
void idft(long f[], int n){
if(n == 1)return;
long f0[n/2], f1[n/2];
for(int i=0; i<n/2; i++){
f0[i] = f[2*i + 0];
f1[i] = f[2*i + 1];
}
idft(f0, n/2);
idft(f1, n/2);
long zeta = modpow(469870224, sz / n, mod), pow_zeta = 1l;
for(int i=0; i<n; i++){
f[i] = (f0[i % (n/2)] + pow_zeta * f1[i % (n/2)]) % mod;
pow_zeta = (pow_zeta * zeta) % mod;
}
return;
}
#define t 1<<20
long a[t], b[t];
int N, M;
int main(){
scanf("%d%d", &N, &M);
for(int i=0; i<N; i++)scanf("%ld", &a[i]);
for(int i=0; i<M; i++)scanf("%ld", &b[i]);
dft(a, t); dft(b, t);
for(int i=0; i<t; i++)a[i] = (a[i]*b[i]) % mod;
idft(a, t);
for(int i=0; i<N+M-1; i++){
if(i)putchar(32);
printf("%ld", a[i] * 998243401 % mod);
}putchar(10);
return 0;
}
Code 2: package main
/*
#define true 1
#define false 0
#define bool int
// @param m `1 <= m`
// @return x mod m
long long safe_mod(long long x, long long m) {
x %= m;
if (x < 0) x += m;
return x;
}
// Fast moduler by barrett reduction
// Reference: https://en.wikipedia.org/wiki/Barrett_reduction
// NOTE: reconsider after Ice Lake
//
// @param a `0 <= a < m`
// @param b `0 <= b < m`
// @return `a * b % m`
unsigned int barrett_mul(unsigned int _m, unsigned long long im, unsigned int a,
unsigned int b) {
// [1] m = 1
// a = b = im = 0, so okay
// [2] m >= 2
// im = ceil(2^64 / m)
// -> im * m = 2^64 + r (0 <= r < m)
// let z = a*b = c*m + d (0 <= c, d < m)
// a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im
// c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1)
// < 2^64 * 2
// ((ab * im) >> 64) == c or c + 1
unsigned long long z = a;
z *= b;
#ifdef _MSC_VER
unsigned long long x;
_umul128(z, im, &x);
#else
unsigned long long x =
(unsigned long long)(((unsigned __int128)(z)*im) >> 64);
#endif
unsigned int v = (unsigned int)(z - x * _m);
if (_m <= v) v += _m;
return v;
}
unsigned long long barrett_im(unsigned int m) {
return (unsigned long long)(-1) / m + 1;
}
// @param n `0 <= n`
// @param m `1 <= m`
// @return `(x ** n) % m`
long long pow_mod(long long x, long long n, int m) {
if (m == 1) return 0;
unsigned int _m = (unsigned int)(m);
unsigned long long r = 1;
unsigned long long y = safe_mod(x, m);
while (n) {
if (n & 1) r = (r * y) % _m;
y = (y * y) % _m;
n >>= 1;
}
return r;
}
// Reference:
// M. Forisek and J. Jancina,
// Fast Primality Testing for Integers That Fit into a Machine Word
// @param n `0 <= n`
bool is_prime(int n) {
if (n <= 1) return false;
if (n == 2 || n == 7 || n == 61) return true;
if (n % 2 == 0) return false;
long long d = n - 1;
while (d % 2 == 0) d /= 2;
long long as[] = {2, 7, 61};
for (int i = 0; i < sizeof(as) / sizeof(long long); i++) {
long long a = as[i];
long long t = d;
long long y = pow_mod(a, t, n);
while (t != n - 1 && y != 1 && y != n - 1) {
y = y * y % n;
t <<= 1;
}
if (y != n - 1 && t % 2 == 0) {
return false;
}
}
return true;
}
// @param b `1 <= b`
// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g
void inv_gcd(long long a, long long b, long long *g, long long *x) {
a = safe_mod(a, b);
if (a == 0) {
*g = b;
*x = 0;
return;
}
// Contracts:
// [1] s - m0 * a = 0 (mod b)
// [2] t - m1 * a = 0 (mod b)
// [3] s * |m1| + t * |m0| <= b
long long s = b, t = a;
long long m0 = 0, m1 = 1;
while (t) {
long long u = s / t;
s -= t * u;
m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b
// [3]:
// (s - t * u) * |m1| + t * |m0 - m1 * u|
// <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)
// = s * |m1| + t * |m0| <= b
long long tmp = s;
s = t;
t = tmp;
tmp = m0;
m0 = m1;
m1 = tmp;
}
// by [3]: |m0| <= b/g
// by g != b: |m0| < b/g
if (m0 < 0) m0 += b / s;
*g = s;
*x = m0;
return;
}
// Compile time primitive root
// @param m must be prime
// @return primitive root (and minimum in now)
int primitive_root(int m) {
if (m == 2) return 1;
if (m == 167772161) return 3;
if (m == 469762049) return 3;
if (m == 754974721) return 11;
if (m == 998244353) return 3;
int divs[20] = {};
divs[0] = 2;
int cnt = 1;
int x = (m - 1) / 2;
while (x % 2 == 0) x /= 2;
for (int i = 3; (long long)(i)*i <= x; i += 2) {
if (x % i == 0) {
divs[cnt++] = i;
while (x % i == 0) {
x /= i;
}
}
}
if (x > 1) {
divs[cnt++] = x;
}
for (int g = 2;; g++) {
bool ok = true;
for (int i = 0; i < cnt; i++) {
if (pow_mod(g, (m - 1) / divs[i], m) == 1) {
ok = false;
break;
}
}
if (ok) return g;
}
}
*/
import "C" // do not insert blank lines above
import (
"bufio"
"bytes"
"fmt"
"io"
"math/bits"
"os"
"strconv"
)
var DEBUG = true
func main() {
defer Flush()
N := readi()
M := readi()
_, a := readInts(N)
_, b := readInts(M)
c := Convolution998244353Int(a, b)
sp := ""
for i := 0; i < len(c); i++ {
printf("%s%d", sp, c[i])
sp = " "
}
println()
}
// Code generated by genmaps.go; DO NOT EDIT.
type Mod1000000007Int int
func NewMod1000000007Int(v int) Mod1000000007Int {
return Mod1000000007Int(v % 1000000007)
}
func (v Mod1000000007Int) Mod() int {
return 1000000007
}
func (v Mod1000000007Int) Val() int {
return int(v)
}
func (v Mod1000000007Int) Negate() Mod1000000007Int {
return 1000000007 - v
}
func (v *Mod1000000007Int) Inc() {
*v = (*v + 1) % 1000000007
}
func (v *Mod1000000007Int) Dec() {
*v = (*v - 1 + 1000000007) % 1000000007
}
func (v Mod1000000007Int) Add(x Mod1000000007Int) Mod1000000007Int {
return (v + x) % 1000000007
}
func (v Mod1000000007Int) Sub(x Mod1000000007Int) Mod1000000007Int {
return (v + 1000000007 - x) % 1000000007
}
func (v Mod1000000007Int) Mul(x Mod1000000007Int) Mod1000000007Int {
return (v * x) % 1000000007
}
func (v Mod1000000007Int) Div(x Mod1000000007Int) Mod1000000007Int {
return (v * x.Inv()) % 1000000007
}
func (v Mod1000000007Int) Pow(n int) Mod1000000007Int {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return 1
}
x := int(v)
r := int(1)
for 0 < n {
if n&1 == 1 {
r = r * x % 1000000007
}
x = x * x % 1000000007
n >>= 1
}
return Mod1000000007Int(r)
}
func (v Mod1000000007Int) Inv() Mod1000000007Int {
if true {
if v == 0 {
panic("must be non zero")
}
return v.Pow(1000000007 - 2)
} else {
g, x := InvGCD(int64(v), 1000000007)
if g != 1 {
panic("g != 1")
}
return Mod1000000007Int(x)
}
}
type Mod998244353Int int
func NewMod998244353Int(v int) Mod998244353Int {
return Mod998244353Int(v % 998244353)
}
func (v Mod998244353Int) Mod() int {
return 998244353
}
func (v Mod998244353Int) Val() int {
return int(v)
}
func (v Mod998244353Int) Negate() Mod998244353Int {
return 998244353 - v
}
func (v *Mod998244353Int) Inc() {
*v = (*v + 1) % 998244353
}
func (v *Mod998244353Int) Dec() {
*v = (*v - 1 + 998244353) % 998244353
}
func (v Mod998244353Int) Add(x Mod998244353Int) Mod998244353Int {
return (v + x) % 998244353
}
func (v Mod998244353Int) Sub(x Mod998244353Int) Mod998244353Int {
return (v + 998244353 - x) % 998244353
}
func (v Mod998244353Int) Mul(x Mod998244353Int) Mod998244353Int {
return (v * x) % 998244353
}
func (v Mod998244353Int) Div(x Mod998244353Int) Mod998244353Int {
return (v * x.Inv()) % 998244353
}
func (v Mod998244353Int) Pow(n int) Mod998244353Int {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return 1
}
x := int(v)
r := int(1)
for 0 < n {
if n&1 == 1 {
r = r * x % 998244353
}
x = x * x % 998244353
n >>= 1
}
return Mod998244353Int(r)
}
func (v Mod998244353Int) Inv() Mod998244353Int {
if true {
if v == 0 {
panic("must be non zero")
}
return v.Pow(998244353 - 2)
} else {
g, x := InvGCD(int64(v), 998244353)
if g != 1 {
panic("g != 1")
}
return Mod998244353Int(x)
}
}
type Mod1000000007Int64 int64
func NewMod1000000007Int64(v int64) Mod1000000007Int64 {
return Mod1000000007Int64(v % 1000000007)
}
func (v Mod1000000007Int64) Mod() int64 {
return 1000000007
}
func (v Mod1000000007Int64) Val() int64 {
return int64(v)
}
func (v Mod1000000007Int64) Negate() Mod1000000007Int64 {
return 1000000007 - v
}
func (v *Mod1000000007Int64) Inc() {
*v = (*v + 1) % 1000000007
}
func (v *Mod1000000007Int64) Dec() {
*v = (*v - 1 + 1000000007) % 1000000007
}
func (v Mod1000000007Int64) Add(x Mod1000000007Int64) Mod1000000007Int64 {
return (v + x) % 1000000007
}
func (v Mod1000000007Int64) Sub(x Mod1000000007Int64) Mod1000000007Int64 {
return (v + 1000000007 - x) % 1000000007
}
func (v Mod1000000007Int64) Mul(x Mod1000000007Int64) Mod1000000007Int64 {
return (v * x) % 1000000007
}
func (v Mod1000000007Int64) Div(x Mod1000000007Int64) Mod1000000007Int64 {
return (v * x.Inv()) % 1000000007
}
func (v Mod1000000007Int64) Pow(n int64) Mod1000000007Int64 {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return 1
}
x := int64(v)
r := int64(1)
for 0 < n {
if n&1 == 1 {
r = r * x % 1000000007
}
x = x * x % 1000000007
n >>= 1
}
return Mod1000000007Int64(r)
}
func (v Mod1000000007Int64) Inv() Mod1000000007Int64 {
if true {
if v == 0 {
panic("must be non zero")
}
return v.Pow(1000000007 - 2)
} else {
g, x := InvGCD(int64(v), 1000000007)
if g != 1 {
panic("g != 1")
}
return Mod1000000007Int64(x)
}
}
type Mod998244353Int64 int64
func NewMod998244353Int64(v int64) Mod998244353Int64 {
return Mod998244353Int64(v % 998244353)
}
func (v Mod998244353Int64) Mod() int64 {
return 998244353
}
func (v Mod998244353Int64) Val() int64 {
return int64(v)
}
func (v Mod998244353Int64) Negate() Mod998244353Int64 {
return 998244353 - v
}
func (v *Mod998244353Int64) Inc() {
*v = (*v + 1) % 998244353
}
func (v *Mod998244353Int64) Dec() {
*v = (*v - 1 + 998244353) % 998244353
}
func (v Mod998244353Int64) Add(x Mod998244353Int64) Mod998244353Int64 {
return (v + x) % 998244353
}
func (v Mod998244353Int64) Sub(x Mod998244353Int64) Mod998244353Int64 {
return (v + 998244353 - x) % 998244353
}
func (v Mod998244353Int64) Mul(x Mod998244353Int64) Mod998244353Int64 {
return (v * x) % 998244353
}
func (v Mod998244353Int64) Div(x Mod998244353Int64) Mod998244353Int64 {
return (v * x.Inv()) % 998244353
}
func (v Mod998244353Int64) Pow(n int64) Mod998244353Int64 {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return 1
}
x := int64(v)
r := int64(1)
for 0 < n {
if n&1 == 1 {
r = r * x % 998244353
}
x = x * x % 998244353
n >>= 1
}
return Mod998244353Int64(r)
}
func (v Mod998244353Int64) Inv() Mod998244353Int64 {
if true {
if v == 0 {
panic("must be non zero")
}
return v.Pow(998244353 - 2)
} else {
g, x := InvGCD(int64(v), 998244353)
if g != 1 {
panic("g != 1")
}
return Mod998244353Int64(x)
}
}
type DynamicModInt struct {
v int64
bt Barrett
isPrime bool
}
func NewDynamicModInt(v int) DynamicModInt {
return DynamicModInt{
v: int64(v),
}
}
func (d *DynamicModInt) SetMod(m int) {
if m < 1 {
panic("modulo must be more than 0")
}
d.bt = NewBarrett(uint(m))
d.v %= d.umod()
d.isPrime = IsPrime(m)
}
func (d DynamicModInt) umod() int64 {
return int64(d.bt.Umod())
}
func (d DynamicModInt) Mod() int {
return int(d.umod())
}
func (d DynamicModInt) Val() int {
return int(d.v)
}
func (d DynamicModInt) Negate() DynamicModInt {
return DynamicModInt{
v: d.umod() - d.v,
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d *DynamicModInt) Inc() {
d.v = (d.v + 1) % d.umod()
}
func (d *DynamicModInt) Dec() {
d.v = (d.v - 1 + d.umod()) % d.umod()
}
func (d DynamicModInt) Add(x DynamicModInt) DynamicModInt {
return DynamicModInt{
v: (d.v + x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Sub(x DynamicModInt) DynamicModInt {
return DynamicModInt{
v: (d.v + d.umod() - x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Mul(x DynamicModInt) DynamicModInt {
return DynamicModInt{
v: (d.v * x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Div(x DynamicModInt) DynamicModInt {
return DynamicModInt{
v: (d.v * x.Inv().v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Pow(n int) DynamicModInt {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return DynamicModInt{
v: 1,
bt: d.bt,
isPrime: d.isPrime,
}
}
x := int64(d.v)
r := int64(1)
for 0 < n {
if n&1 == 1 {
r = r * x % d.umod()
}
x = x * x % d.umod()
n >>= 1
}
return DynamicModInt{
v: r,
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt) Inv() DynamicModInt {
if d.isPrime {
if d.v == 0 {
panic("must be non zero")
}
return d.Pow(int(d.umod()) - 2)
} else {
g, x := InvGCD(int64(d.v), d.umod())
if g != 1 {
panic("g != 1")
}
return DynamicModInt{
v: x,
bt: d.bt,
isPrime: d.isPrime,
}
}
}
type DynamicModInt64 struct {
v int64
bt Barrett
isPrime bool
}
func NewDynamicModInt64(v int64) DynamicModInt64 {
return DynamicModInt64{
v: int64(v),
}
}
func (d *DynamicModInt64) SetMod(m int) {
if m < 1 {
panic("modulo must be more than 0")
}
d.bt = NewBarrett(uint(m))
d.v %= d.umod()
d.isPrime = IsPrime(m)
}
func (d DynamicModInt64) umod() int64 {
return int64(d.bt.Umod())
}
func (d DynamicModInt64) Mod() int64 {
return int64(d.umod())
}
func (d DynamicModInt64) Val() int64 {
return int64(d.v)
}
func (d DynamicModInt64) Negate() DynamicModInt64 {
return DynamicModInt64{
v: d.umod() - d.v,
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d *DynamicModInt64) Inc() {
d.v = (d.v + 1) % d.umod()
}
func (d *DynamicModInt64) Dec() {
d.v = (d.v - 1 + d.umod()) % d.umod()
}
func (d DynamicModInt64) Add(x DynamicModInt64) DynamicModInt64 {
return DynamicModInt64{
v: (d.v + x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Sub(x DynamicModInt64) DynamicModInt64 {
return DynamicModInt64{
v: (d.v + d.umod() - x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Mul(x DynamicModInt64) DynamicModInt64 {
return DynamicModInt64{
v: (d.v * x.v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Div(x DynamicModInt64) DynamicModInt64 {
return DynamicModInt64{
v: (d.v * x.Inv().v) % d.umod(),
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Pow(n int64) DynamicModInt64 {
if n < 0 {
panic("n msut be more than or equal to 0")
}
if n == 0 {
return DynamicModInt64{
v: 1,
bt: d.bt,
isPrime: d.isPrime,
}
}
x := int64(d.v)
r := int64(1)
for 0 < n {
if n&1 == 1 {
r = r * x % d.umod()
}
x = x * x % d.umod()
n >>= 1
}
return DynamicModInt64{
v: r,
bt: d.bt,
isPrime: d.isPrime,
}
}
func (d DynamicModInt64) Inv() DynamicModInt64 {
if d.isPrime {
if d.v == 0 {
panic("must be non zero")
}
return d.Pow(int64(d.umod()) - 2)
} else {
g, x := InvGCD(int64(d.v), d.umod())
if g != 1 {
panic("g != 1")
}
return DynamicModInt64{
v: x,
bt: d.bt,
isPrime: d.isPrime,
}
}
}
// Code generated by genmaps.go; DO NOT EDIT.
var (
butterfly1000000007Int_sum_e [30]Mod1000000007Int
)
func init() {
g := PrimitiveRoot(1000000007) % 1000000007
var es [30]Mod1000000007Int
var ies [30]Mod1000000007Int
cnt2 := BSF(1000000007 - 1)
e := Mod1000000007Int(g).Pow((1000000007 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod1000000007Int(1)
for i := 0; i < cnt2; i++ {
butterfly1000000007Int_sum_e[i] = es[i].Mul(now)
now = now.Mul(ies[i])
}
}
func butterfly1000000007Int(a []Mod1000000007Int) {
n := len(a)
h := CeilPow2(n)
for ph := 1; ph <= h; ph++ {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
now := Mod1000000007Int(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p].Mul(now)
a[i+offset] = l.Add(r)
a[i+offset+p] = l.Sub(r)
}
now = now.Mul(butterfly1000000007Int_sum_e[BSF(^(uint(s)))])
}
}
}
var (
butterflyInv1000000007Int_sum_e [30]Mod1000000007Int
)
func init() {
g := PrimitiveRoot(1000000007) % 1000000007
var es [30]Mod1000000007Int
var ies [30]Mod1000000007Int
cnt2 := BSF(1000000007 - 1)
e := Mod1000000007Int(g).Pow((1000000007 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod1000000007Int(1)
for i := 0; i < cnt2-2; i++ {
butterflyInv1000000007Int_sum_e[i] = ies[i].Mul(now)
now = now.Mul(es[i])
}
}
func butterflyInv1000000007Int(a []Mod1000000007Int) {
n := len(a)
h := CeilPow2(n)
for ph := h; ph >= 1; ph-- {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
inow := Mod1000000007Int(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p]
a[i+offset] = l.Add(r)
a[i+offset+p] = Mod1000000007Int(uint64(1000000007+l.Val()-r.Val()) % uint64(1000000007) * uint64(inow.Val()) % uint64(1000000007))
}
inow = inow.Mul(butterflyInv1000000007Int_sum_e[BSF(^(uint(s)))])
}
}
}
func ConvolutionMod1000000007Int(a, b []Mod1000000007Int) []Mod1000000007Int {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
resize := func(a []Mod1000000007Int, z int) []Mod1000000007Int {
n := len(a)
if n < z {
return append(a, make([]Mod1000000007Int, z-n)...)
}
return a[:z]
}
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]Mod1000000007Int, 0)
}
if min(n, m) <= 60 {
if n < m {
n, m = m, n
a, b = b, a
}
ans := make([]Mod1000000007Int, n+m-1)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
ans[i+j] = ans[i+j].Add(a[i].Mul(b[j]))
}
}
return ans
}
z := 1 << CeilPow2(n+m-1)
a = resize(a, z)
butterfly1000000007Int(a)
b = resize(b, z)
butterfly1000000007Int(b)
for i := 0; i < z; i++ {
a[i] = a[i].Mul(b[i])
}
butterflyInv1000000007Int(a)
resize(a, n+m-1)
iz := NewMod1000000007Int(int(z)).Inv()
for i := 0; i < n+m-1; i++ {
a[i] = a[i].Mul(iz)
}
return a
}
func Convolution1000000007Int(a, b []int) []int {
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]int, 0)
}
a2 := make([]Mod1000000007Int, n)
b2 := make([]Mod1000000007Int, m)
for i := range a {
a2[i] = NewMod1000000007Int(a[i])
}
for i := range b {
b2[i] = NewMod1000000007Int(b[i])
}
c2 := ConvolutionMod1000000007Int(a2, b2)
c := make([]int, n+m-1)
for i := 0; i < n+m-1; i++ {
c[i] = c2[i].Val()
}
return c
}
var (
butterfly998244353Int_sum_e [30]Mod998244353Int
)
func init() {
g := PrimitiveRoot(998244353) % 998244353
var es [30]Mod998244353Int
var ies [30]Mod998244353Int
cnt2 := BSF(998244353 - 1)
e := Mod998244353Int(g).Pow((998244353 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod998244353Int(1)
for i := 0; i < cnt2; i++ {
butterfly998244353Int_sum_e[i] = es[i].Mul(now)
now = now.Mul(ies[i])
}
}
func butterfly998244353Int(a []Mod998244353Int) {
n := len(a)
h := CeilPow2(n)
for ph := 1; ph <= h; ph++ {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
now := Mod998244353Int(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p].Mul(now)
a[i+offset] = l.Add(r)
a[i+offset+p] = l.Sub(r)
}
now = now.Mul(butterfly998244353Int_sum_e[BSF(^(uint(s)))])
}
}
}
var (
butterflyInv998244353Int_sum_e [30]Mod998244353Int
)
func init() {
g := PrimitiveRoot(998244353) % 998244353
var es [30]Mod998244353Int
var ies [30]Mod998244353Int
cnt2 := BSF(998244353 - 1)
e := Mod998244353Int(g).Pow((998244353 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod998244353Int(1)
for i := 0; i < cnt2-2; i++ {
butterflyInv998244353Int_sum_e[i] = ies[i].Mul(now)
now = now.Mul(es[i])
}
}
func butterflyInv998244353Int(a []Mod998244353Int) {
n := len(a)
h := CeilPow2(n)
for ph := h; ph >= 1; ph-- {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
inow := Mod998244353Int(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p]
a[i+offset] = l.Add(r)
a[i+offset+p] = Mod998244353Int(uint64(998244353+l.Val()-r.Val()) % uint64(998244353) * uint64(inow.Val()) % uint64(998244353))
}
inow = inow.Mul(butterflyInv998244353Int_sum_e[BSF(^(uint(s)))])
}
}
}
func ConvolutionMod998244353Int(a, b []Mod998244353Int) []Mod998244353Int {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
resize := func(a []Mod998244353Int, z int) []Mod998244353Int {
n := len(a)
if n < z {
return append(a, make([]Mod998244353Int, z-n)...)
}
return a[:z]
}
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]Mod998244353Int, 0)
}
if min(n, m) <= 60 {
if n < m {
n, m = m, n
a, b = b, a
}
ans := make([]Mod998244353Int, n+m-1)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
ans[i+j] = ans[i+j].Add(a[i].Mul(b[j]))
}
}
return ans
}
z := 1 << CeilPow2(n+m-1)
a = resize(a, z)
butterfly998244353Int(a)
b = resize(b, z)
butterfly998244353Int(b)
for i := 0; i < z; i++ {
a[i] = a[i].Mul(b[i])
}
butterflyInv998244353Int(a)
resize(a, n+m-1)
iz := NewMod998244353Int(int(z)).Inv()
for i := 0; i < n+m-1; i++ {
a[i] = a[i].Mul(iz)
}
return a
}
func Convolution998244353Int(a, b []int) []int {
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]int, 0)
}
a2 := make([]Mod998244353Int, n)
b2 := make([]Mod998244353Int, m)
for i := range a {
a2[i] = NewMod998244353Int(a[i])
}
for i := range b {
b2[i] = NewMod998244353Int(b[i])
}
c2 := ConvolutionMod998244353Int(a2, b2)
c := make([]int, n+m-1)
for i := 0; i < n+m-1; i++ {
c[i] = c2[i].Val()
}
return c
}
var (
butterfly1000000007Int64_sum_e [30]Mod1000000007Int64
)
func init() {
g := PrimitiveRoot(1000000007) % 1000000007
var es [30]Mod1000000007Int64
var ies [30]Mod1000000007Int64
cnt2 := BSF(1000000007 - 1)
e := Mod1000000007Int64(g).Pow((1000000007 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod1000000007Int64(1)
for i := 0; i < cnt2; i++ {
butterfly1000000007Int64_sum_e[i] = es[i].Mul(now)
now = now.Mul(ies[i])
}
}
func butterfly1000000007Int64(a []Mod1000000007Int64) {
n := len(a)
h := CeilPow2(n)
for ph := 1; ph <= h; ph++ {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
now := Mod1000000007Int64(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p].Mul(now)
a[i+offset] = l.Add(r)
a[i+offset+p] = l.Sub(r)
}
now = now.Mul(butterfly1000000007Int64_sum_e[BSF(^(uint(s)))])
}
}
}
var (
butterflyInv1000000007Int64_sum_e [30]Mod1000000007Int64
)
func init() {
g := PrimitiveRoot(1000000007) % 1000000007
var es [30]Mod1000000007Int64
var ies [30]Mod1000000007Int64
cnt2 := BSF(1000000007 - 1)
e := Mod1000000007Int64(g).Pow((1000000007 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod1000000007Int64(1)
for i := 0; i < cnt2-2; i++ {
butterflyInv1000000007Int64_sum_e[i] = ies[i].Mul(now)
now = now.Mul(es[i])
}
}
func butterflyInv1000000007Int64(a []Mod1000000007Int64) {
n := len(a)
h := CeilPow2(n)
for ph := h; ph >= 1; ph-- {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
inow := Mod1000000007Int64(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p]
a[i+offset] = l.Add(r)
a[i+offset+p] = Mod1000000007Int64(uint64(1000000007+l.Val()-r.Val()) % uint64(1000000007) * uint64(inow.Val()) % uint64(1000000007))
}
inow = inow.Mul(butterflyInv1000000007Int64_sum_e[BSF(^(uint(s)))])
}
}
}
func ConvolutionMod1000000007Int64(a, b []Mod1000000007Int64) []Mod1000000007Int64 {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
resize := func(a []Mod1000000007Int64, z int) []Mod1000000007Int64 {
n := len(a)
if n < z {
return append(a, make([]Mod1000000007Int64, z-n)...)
}
return a[:z]
}
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]Mod1000000007Int64, 0)
}
if min(n, m) <= 60 {
if n < m {
n, m = m, n
a, b = b, a
}
ans := make([]Mod1000000007Int64, n+m-1)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
ans[i+j] = ans[i+j].Add(a[i].Mul(b[j]))
}
}
return ans
}
z := 1 << CeilPow2(n+m-1)
a = resize(a, z)
butterfly1000000007Int64(a)
b = resize(b, z)
butterfly1000000007Int64(b)
for i := 0; i < z; i++ {
a[i] = a[i].Mul(b[i])
}
butterflyInv1000000007Int64(a)
resize(a, n+m-1)
iz := NewMod1000000007Int64(int64(z)).Inv()
for i := 0; i < n+m-1; i++ {
a[i] = a[i].Mul(iz)
}
return a
}
func Convolution1000000007Int64(a, b []int64) []int64 {
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]int64, 0)
}
a2 := make([]Mod1000000007Int64, n)
b2 := make([]Mod1000000007Int64, m)
for i := range a {
a2[i] = NewMod1000000007Int64(a[i])
}
for i := range b {
b2[i] = NewMod1000000007Int64(b[i])
}
c2 := ConvolutionMod1000000007Int64(a2, b2)
c := make([]int64, n+m-1)
for i := 0; i < n+m-1; i++ {
c[i] = c2[i].Val()
}
return c
}
var (
butterfly998244353Int64_sum_e [30]Mod998244353Int64
)
func init() {
g := PrimitiveRoot(998244353) % 998244353
var es [30]Mod998244353Int64
var ies [30]Mod998244353Int64
cnt2 := BSF(998244353 - 1)
e := Mod998244353Int64(g).Pow((998244353 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod998244353Int64(1)
for i := 0; i < cnt2; i++ {
butterfly998244353Int64_sum_e[i] = es[i].Mul(now)
now = now.Mul(ies[i])
}
}
func butterfly998244353Int64(a []Mod998244353Int64) {
n := len(a)
h := CeilPow2(n)
for ph := 1; ph <= h; ph++ {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
now := Mod998244353Int64(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p].Mul(now)
a[i+offset] = l.Add(r)
a[i+offset+p] = l.Sub(r)
}
now = now.Mul(butterfly998244353Int64_sum_e[BSF(^(uint(s)))])
}
}
}
var (
butterflyInv998244353Int64_sum_e [30]Mod998244353Int64
)
func init() {
g := PrimitiveRoot(998244353) % 998244353
var es [30]Mod998244353Int64
var ies [30]Mod998244353Int64
cnt2 := BSF(998244353 - 1)
e := Mod998244353Int64(g).Pow((998244353 - 1) >> uint(cnt2))
ie := e.Inv()
for i := cnt2; i >= 2; i-- {
es[i-2] = e
ies[i-2] = ie
e = e.Mul(e)
ie = ie.Mul(ie)
}
now := Mod998244353Int64(1)
for i := 0; i < cnt2-2; i++ {
butterflyInv998244353Int64_sum_e[i] = ies[i].Mul(now)
now = now.Mul(es[i])
}
}
func butterflyInv998244353Int64(a []Mod998244353Int64) {
n := len(a)
h := CeilPow2(n)
for ph := h; ph >= 1; ph-- {
w := 1 << uint(ph-1)
p := 1 << uint(h-ph)
inow := Mod998244353Int64(1)
for s := 0; s < w; s++ {
offset := s << uint(h-ph+1)
for i := 0; i < p; i++ {
l := a[i+offset]
r := a[i+offset+p]
a[i+offset] = l.Add(r)
a[i+offset+p] = Mod998244353Int64(uint64(998244353+l.Val()-r.Val()) % uint64(998244353) * uint64(inow.Val()) % uint64(998244353))
}
inow = inow.Mul(butterflyInv998244353Int64_sum_e[BSF(^(uint(s)))])
}
}
}
func ConvolutionMod998244353Int64(a, b []Mod998244353Int64) []Mod998244353Int64 {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
resize := func(a []Mod998244353Int64, z int) []Mod998244353Int64 {
n := len(a)
if n < z {
return append(a, make([]Mod998244353Int64, z-n)...)
}
return a[:z]
}
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]Mod998244353Int64, 0)
}
if min(n, m) <= 60 {
if n < m {
n, m = m, n
a, b = b, a
}
ans := make([]Mod998244353Int64, n+m-1)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
ans[i+j] = ans[i+j].Add(a[i].Mul(b[j]))
}
}
return ans
}
z := 1 << CeilPow2(n+m-1)
a = resize(a, z)
butterfly998244353Int64(a)
b = resize(b, z)
butterfly998244353Int64(b)
for i := 0; i < z; i++ {
a[i] = a[i].Mul(b[i])
}
butterflyInv998244353Int64(a)
resize(a, n+m-1)
iz := NewMod998244353Int64(int64(z)).Inv()
for i := 0; i < n+m-1; i++ {
a[i] = a[i].Mul(iz)
}
return a
}
func Convolution998244353Int64(a, b []int64) []int64 {
n := len(a)
m := len(b)
if n == 0 || m == 0 {
return make([]int64, 0)
}
a2 := make([]Mod998244353Int64, n)
b2 := make([]Mod998244353Int64, m)
for i := range a {
a2[i] = NewMod998244353Int64(a[i])
}
for i := range b {
b2[i] = NewMod998244353Int64(b[i])
}
c2 := ConvolutionMod998244353Int64(a2, b2)
c := make([]int64, n+m-1)
for i := 0; i < n+m-1; i++ {
c[i] = c2[i].Val()
}
return c
}
func SafeMod(x, m int64) int64 {
return int64(C.safe_mod(C.longlong(x), C.longlong(m)))
}
type Barrett struct {
m C.uint
im C.ulonglong
}
func NewBarrett(m uint) Barrett {
return Barrett{
m: C.uint(m),
im: C.barrett_im(C.uint(m)),
}
}
func (bt Barrett) Umod() uint {
return uint(bt.m)
}
func (bt Barrett) Mul(a, b uint) uint {
return uint(C.barrett_mul(bt.m, bt.im, C.uint(a), C.uint(b)))
}
func PowMod(x, n int64, m int) int64 {
return int64(C.pow_mod(C.longlong(x), C.longlong(n), C.int(m)))
}
func IsPrime(n int) bool {
return C.is_prime(C.int(n)) != 0
}
func InvGCD(a, b int64) (int64, int64) {
var g, x C.longlong
C.inv_gcd(C.longlong(a), C.longlong(b), &g, &x)
return int64(g), int64(x)
}
func PrimitiveRoot(m int) int {
return int(C.primitive_root(C.int(m)))
}
func CeilPow2(n int) int {
x := uint(0)
for uint(1<<x) < uint(n) {
x++
}
return int(x)
}
func BSF(n uint) int {
return bits.TrailingZeros(n)
}
// -----------------------------------------------------------------------------
// IO helper functions
// Returns next token from input. It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)
// Holds a buffer for output. It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer
// Holds an io.Writer. It must be initialized by SetOutput()
var OutputWriter io.Writer
// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
SetUnbefferedInput(r)
OutputBuffer = nil
OutputWriter = w
}
// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
OutputBuffer = bufio.NewWriter(w)
OutputWriter = OutputBuffer
}
// Flushes OutputBuffer
func Flush() {
if OutputBuffer != nil {
OutputBuffer.Flush()
}
}
// Returns true if c is a white space
func IsSpace(c byte) bool {
switch c {
case '\t', '\n', '\v', '\f', '\r', ' ':
return true
}
return false
}
func IsNewLine(c byte) bool {
switch c {
case '\n', '\r':
return true
}
return false
}
// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
buf := new(bytes.Buffer)
var b []byte
var i int
rest := func() ([]byte, error) {
for i < len(b) && IsSpace(b[i]) {
i++
}
if i == len(b) {
return nil, io.ErrUnexpectedEOF
}
j := i
for i < len(b) && !IsSpace(b[i]) {
i++
}
return b[j:i], nil
}
initial := func() ([]byte, error) {
io.Copy(buf, r)
b = buf.Bytes()
nextToken = rest
return rest()
}
nextToken = initial
restLn := func() ([]byte, error) {
for i < len(b) && IsNewLine(b[i]) {
i++
}
if i == len(b) {
return nil, io.ErrUnexpectedEOF
}
j := i
for i < len(b) && !IsNewLine(b[i]) {
i++
}
return b[j:i], nil
}
initialLn := func() ([]byte, error) {
io.Copy(buf, r)
b = buf.Bytes()
nextLine = restLn
return restLn()
}
nextLine = initialLn
}
// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
buf := bufio.NewReader(r)
var b []byte
var i int
nextToken = func() ([]byte, error) {
var err error
if i == len(b) {
b, err = buf.ReadBytes('\n')
if err != nil {
return nil, err
}
i = 0
j := len(b) - 1
for 0 <= j && IsSpace(b[j]) {
j--
}
b = b[0 : j+1]
}
for i < len(b) && IsSpace(b[i]) {
i++
}
j := i
for i < len(b) && !IsSpace(b[i]) {
i++
}
if i == j {
return nil, io.ErrUnexpectedEOF
}
return b[j:i], nil
}
}
// -----------------------------------------------------------------------------
// IO functions
// Reads next token and return it as []byte
func readb() []byte {
b, err := nextToken()
if err != nil {
panic(err)
}
return b[:len(b):len(b)]
}
func readberr() ([]byte, error) {
b, err := nextToken()
return b[:len(b):len(b)], err
}
// Reads next token and return it as string
func reads() string {
return string(readb())
}
func readserr() (string, error) {
b, err := readberr()
return string(b), err
}
// Read next line as []byte. Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
b, err := nextLine()
if err != nil {
panic(err)
}
return b[:len(b):len(b)]
}
func readblnerr() ([]byte, error) {
b, err := nextLine()
return b[:len(b):len(b)], err
}
// Read next line as string
func readsln() string {
return string(readbln())
}
func readslnerr() (string, error) {
b, err := readblnerr()
return string(b), err
}
// Reads next token and return it as int64
func readll() int64 {
i, err := strconv.ParseInt(reads(), 10, 64)
if err != nil {
panic(err.Error())
}
return i
}
func readllerr() (int64, error) {
s, err := readserr()
if err != nil {
return 0, fmt.Errorf("reading string: %w", err)
}
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, fmt.Errorf("parsing int: %w", err)
}
return i, nil
}
// Reads next token and return it as int
func readi() int {
return int(readll())
}
func readierr() (int, error) {
i, err := readllerr()
return int(i), err
}
// Reads next token and return it as float64
func readf() float64 {
f, err := strconv.ParseFloat(reads(), 64)
if err != nil {
panic(err.Error())
}
return f
}
func readferr() (float64, error) {
s, err := readserr()
if err != nil {
return 0, fmt.Errorf("reading string: %w", err)
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, fmt.Errorf("parsing float: %w", err)
}
return f, nil
}
// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
return fmt.Fprintf(OutputWriter, f, args...)
}
// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
return fmt.Fprintln(OutputWriter, args...)
}
// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
return fmt.Fprintf(os.Stderr, f, args...)
}
// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
return fmt.Fprintln(os.Stderr, args...)
}
func dbgf(f string, args ...interface{}) {
if !DEBUG {
return
}
fmt.Fprintf(os.Stderr, f, args...)
}
func dbg(args ...interface{}) {
if !DEBUG {
return
}
fmt.Fprintln(os.Stderr, args...)
}
// -----------------------------------------------------------------------------
// Utilities
func sumSlice(a []int) int {
var res int
for _, v := range a {
res += v
}
return res
}
func sumSlicell(a []int64) int64 {
var res int64
for _, v := range a {
res += v
}
return res
}
func readInts(N int) (int, []int) {
if N == 0 {
N = readi()
}
a := make([]int, N)
for i := range a {
a[i] = readi()
}
return N, a
}
func readIntsll(N int) (int, []int64) {
if N == 0 {
N = readi()
}
a := make([]int64, N)
for i := range a {
a[i] = readll()
}
return N, a
}
// -----------------------------------------------------------------------------
// Simple math functions
const (
// big prime
INF = 1000000007
INF2 = 1000000009
INF3 = 998244353
)
func min(a, b int) int {
if a < b {
return a
}
return b
}
func minll(a, b int64) int64 {
if a < b {
return a
}
return b
}
func minf(a, b float64) float64 {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a < b {
return b
}
return a
}
func maxll(a, b int64) int64 {
if a < b {
return b
}
return a
}
func maxf(a, b float64) float64 {
if a < b {
return b
}
return a
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
func absll(a int64) int64 {
if a < 0 {
return -a
}
return a
}
func absf(a float64) float64 {
if a < 0 {
return -a
}
return a
}
// egcd(a, b) returns d, x, y:
// d is gcd(a,b)
// x, y are integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
if b == 0 {
return a, 1, 0
}
d, x, y := egcd(b, a%b)
return d, y, x - a/b*y
}
func egcdll(a, b int64) (int64, int64, int64) {
if b == 0 {
return a, 1, 0
}
d, x, y := egcdll(b, a%b)
return d, y, x - a/b*y
}
func gcd(a, b int) int {
d, _, _ := egcd(a, b)
return d
}
func gcdll(a, b int64) int64 {
d, _, _ := egcdll(a, b)
return d
}
// set up IO functions
func init() {
// for non-interactive
SetInput(os.Stdin)
SetOutput(os.Stdout)
// Enable below when interactive. Its ok to leave above intact.
// SetInteractive(os.Stdout, os.Stdin)
}
|
C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ITP2_2_D
{
public class Program
{
public static void Main(string[] args)
{
int[] n = ReadIntAr();
List<MyLinkedList<int>> li = new List<MyLinkedList<int>>();
for (int i = 0 ; i < n[0] ; i++) li.Add(new MyLinkedList<int>());
for (int i = 0 ; i < n[1] ; i++)
{
int[] line = ReadIntAr();
switch (line[0])
{
case 0: li[line[1]].InsertLast(line[2]); break;
case 1: Console.WriteLine(String.Join(" ", li[line[1]].Select(x => x.ToString()).ToArray())); break;
case 2:
{
li[line[2]].Concat(li[line[1]]);
li[line[1]].Clear();
}
break;
}
}
}
public class MyLinkedList<T> : IEnumerable<T>
{
public class Node
{
public T Value { get; set; }
public Node Next { get; set; }
public Node Prev { get; set; }
internal Node(T val, Node prev, Node next)
{
Value = val; Prev = prev; Next = next;
}
}
public Node Dummy { get; set; }
public MyLinkedList()
{
Clear();
}
public Node First { get{ return Dummy.Next; } }
public Node Last { get { return Dummy.Prev; } }
public Node End { get { return Dummy; } }
public int Count
{
get
{
int i = 0;
for (Node n = this.First ; n != this.End ; n = n.Next)
++i;
return i;
}
}
public Node InsertAfter(Node n, T elem)
{
Node m = new Node(elem, n, n.Next);
n.Next.Prev = m;
n.Next = m;
return m;
}
public Node InsertBefore(Node n, T elem)
{
Node m = new Node(elem, n.Prev, n);
n.Prev.Next = m;
n.Prev = m;
return m;
}
public Node InsertFirst(T elem)
{
return InsertAfter(Dummy, elem);
}
public Node InsertLast(T elem)
{
return InsertBefore(this.Dummy, elem);
}
public Node Erase(Node n)
{
if (n == Dummy) return Dummy;
n.Prev.Next = n.Next;
n.Next.Prev = n.Prev;
return n.Next;
}
public void EraseFirst()
{
Erase(First);
}
public void EraseLast()
{
Erase(Last);
}
public void Concat(MyLinkedList<T> other)
{
Dummy.Prev.Next = other.Dummy.Next;
other.Dummy.Next.Prev = Dummy.Prev.Next;
other.Dummy.Prev.Next = Dummy;
Dummy.Prev = other.Dummy.Prev;
}
public void Clear()
{
Dummy = new Node(default(T), null, null);
Dummy.Next = Dummy;
Dummy.Prev = Dummy;
}
public IEnumerator<T> GetEnumerator()
{
for (Node n = First ; n != End ; n = n.Next)
yield return n.Value;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
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)); }
}
}
| Go | package main
import (
"bufio"
"bytes"
"fmt"
"os"
"strconv"
)
type List struct {
head *Node
tail *Node
}
type Node struct {
next *Node
prev *Node
v int
}
func NewList() List {
head, tail := &Node{}, &Node{}
head.next, tail.prev = tail, head
return List{head, tail}
}
func (l *List) Insert(x int) {
node := &Node{}
node.v = x
node.next, node.prev = l.tail, l.tail.prev
l.tail.prev, l.tail.prev.next = node, node
}
func (l List) String() string {
var b bytes.Buffer
node := l.head.next
for node != l.tail {
b.WriteString(fmt.Sprint(node.v))
node = node.next
if node != l.tail {
b.WriteString(" ")
}
}
return b.String()
}
func (l *List) Dump(w *bufio.Writer) {
w.WriteString(fmt.Sprintln(l))
}
func Splice(s *List, t *List) {
tTailP := t.tail.prev
sHeadN := s.head.next
sTailP := s.tail.prev
// t: h 1 2 3 t
// s: h 4 5 6 t
// ^
tTailP.next = sHeadN
sTailP.next = sHeadN.prev
// t: h 1 2 3 t
// s: h 4 5 6 t
// ^
sTailP.next = t.tail
t.tail.prev = sTailP
*s = NewList()
}
func NextInt(sc *bufio.Scanner) (int, error) {
sc.Scan()
return strconv.Atoi(sc.Text())
}
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
w := bufio.NewWriter(os.Stdout)
n, _ := NextInt(sc)
s := make([]List, n)
for i := 0; i < n; i++ {
s[i] = NewList()
}
q, _ := NextInt(sc)
for i := 0; i < q; i++ {
cmd, _ := NextInt(sc)
t, _ := NextInt(sc)
// fmt.Println(t, ":", s[t])
switch cmd {
case 0:
x, _ := NextInt(sc)
s[t].Insert(x)
case 1:
s[t].Dump(w)
case 2:
tt, _ := NextInt(sc)
// fmt.Println("before:", s[t],",",s[tt])
Splice(&s[t], &s[tt])
// fmt.Println(" after:", s[t],",",s[tt])
}
}
w.Flush()
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ITP2_2_D
{
public class Program
{
public static void Main(string[] args)
{
int[] n = ReadIntAr();
List<MyLinkedList<int>> li = new List<MyLinkedList<int>>();
for (int i = 0 ; i < n[0] ; i++) li.Add(new MyLinkedList<int>());
for (int i = 0 ; i < n[1] ; i++)
{
int[] line = ReadIntAr();
switch (line[0])
{
case 0: li[line[1]].InsertLast(line[2]); break;
case 1: Console.WriteLine(String.Join(" ", li[line[1]].Select(x => x.ToString()).ToArray())); break;
case 2:
{
li[line[2]].Concat(li[line[1]]);
li[line[1]].Clear();
}
break;
}
}
}
public class MyLinkedList<T> : IEnumerable<T>
{
public class Node
{
public T Value { get; set; }
public Node Next { get; set; }
public Node Prev { get; set; }
internal Node(T val, Node prev, Node next)
{
Value = val; Prev = prev; Next = next;
}
}
public Node Dummy { get; set; }
public MyLinkedList()
{
Clear();
}
public Node First { get{ return Dummy.Next; } }
public Node Last { get { return Dummy.Prev; } }
public Node End { get { return Dummy; } }
public int Count
{
get
{
int i = 0;
for (Node n = this.First ; n != this.End ; n = n.Next)
++i;
return i;
}
}
public Node InsertAfter(Node n, T elem)
{
Node m = new Node(elem, n, n.Next);
n.Next.Prev = m;
n.Next = m;
return m;
}
public Node InsertBefore(Node n, T elem)
{
Node m = new Node(elem, n.Prev, n);
n.Prev.Next = m;
n.Prev = m;
return m;
}
public Node InsertFirst(T elem)
{
return InsertAfter(Dummy, elem);
}
public Node InsertLast(T elem)
{
return InsertBefore(this.Dummy, elem);
}
public Node Erase(Node n)
{
if (n == Dummy) return Dummy;
n.Prev.Next = n.Next;
n.Next.Prev = n.Prev;
return n.Next;
}
public void EraseFirst()
{
Erase(First);
}
public void EraseLast()
{
Erase(Last);
}
public void Concat(MyLinkedList<T> other)
{
Dummy.Prev.Next = other.Dummy.Next;
other.Dummy.Next.Prev = Dummy.Prev.Next;
other.Dummy.Prev.Next = Dummy;
Dummy.Prev = other.Dummy.Prev;
}
public void Clear()
{
Dummy = new Node(default(T), null, null);
Dummy.Next = Dummy;
Dummy.Prev = Dummy;
}
public IEnumerator<T> GetEnumerator()
{
for (Node n = First ; n != End ; n = n.Next)
yield return n.Value;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
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)); }
}
}
Code 2: package main
import (
"bufio"
"bytes"
"fmt"
"os"
"strconv"
)
type List struct {
head *Node
tail *Node
}
type Node struct {
next *Node
prev *Node
v int
}
func NewList() List {
head, tail := &Node{}, &Node{}
head.next, tail.prev = tail, head
return List{head, tail}
}
func (l *List) Insert(x int) {
node := &Node{}
node.v = x
node.next, node.prev = l.tail, l.tail.prev
l.tail.prev, l.tail.prev.next = node, node
}
func (l List) String() string {
var b bytes.Buffer
node := l.head.next
for node != l.tail {
b.WriteString(fmt.Sprint(node.v))
node = node.next
if node != l.tail {
b.WriteString(" ")
}
}
return b.String()
}
func (l *List) Dump(w *bufio.Writer) {
w.WriteString(fmt.Sprintln(l))
}
func Splice(s *List, t *List) {
tTailP := t.tail.prev
sHeadN := s.head.next
sTailP := s.tail.prev
// t: h 1 2 3 t
// s: h 4 5 6 t
// ^
tTailP.next = sHeadN
sTailP.next = sHeadN.prev
// t: h 1 2 3 t
// s: h 4 5 6 t
// ^
sTailP.next = t.tail
t.tail.prev = sTailP
*s = NewList()
}
func NextInt(sc *bufio.Scanner) (int, error) {
sc.Scan()
return strconv.Atoi(sc.Text())
}
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
w := bufio.NewWriter(os.Stdout)
n, _ := NextInt(sc)
s := make([]List, n)
for i := 0; i < n; i++ {
s[i] = NewList()
}
q, _ := NextInt(sc)
for i := 0; i < q; i++ {
cmd, _ := NextInt(sc)
t, _ := NextInt(sc)
// fmt.Println(t, ":", s[t])
switch cmd {
case 0:
x, _ := NextInt(sc)
s[t].Insert(x)
case 1:
s[t].Dump(w)
case 2:
tt, _ := NextInt(sc)
// fmt.Println("before:", s[t],",",s[tt])
Splice(&s[t], &s[tt])
// fmt.Println(" after:", s[t],",",s[tt])
}
}
w.Flush()
}
|
C | #include <stdio.h>
#include <string.h>
int nat_m,nat_h[111111],nat_n[111111*2],nat_t[111111*2];
int nat_c[111111];
int neko_m,neko_h[111111],neko_n[111111*2],neko_t[111111*2];
int neko_c[111111],neko_c_natsu[111111];
int q[555555],inq[111111],hd,tl;
int nat_natsu_c[111111],neko_natsu_c[111111];
int main(void)
{
int n,m,nat,neko,u,v,i,e,p,res,T;
char c;
scanf("%d",&T);
while( T-- ) {
scanf("%d%d",&n,&m);
scanf("%d%d",&nat,&neko);
nat_m = neko_m = 0;
for(i = 0; i <= n; i++) {
nat_h[i] = neko_h[i] = -1;
neko_c[i] = neko_c_natsu[i] = 1<<21;
nat_c[i] = 1<<21;
}
#define add_edge1(n,h,t,m,u,v) (n[m]=h[u],h[u]=m,t[m]=v,++m)
for( i = 0; i < m; i++ ) {
scanf("%d%d %c",&u,&v,&c);
if( c == 'N' ) {
add_edge1(nat_n,nat_h,nat_t,nat_m,u,v);
add_edge1(nat_n,nat_h,nat_t,nat_m,v,u);
}
if( c == 'L' ) {
add_edge1(neko_n,neko_h,neko_t,neko_m,u,v);
add_edge1(neko_n,neko_h,neko_t,neko_m,v,u);
}
}
nat_c[nat] = 0;
hd = tl = 0;
q[tl++] = nat;
while( hd != tl ) {
p = q[hd++];
for( e = nat_h[p]; e != -1; e = nat_n[e] ) {
if( nat_c[nat_t[e]] > nat_c[p]+1 ) {
nat_c[nat_t[e]] = nat_c[p]+1;
q[tl++] = nat_t[e];
}
}
}
memset(inq,0,sizeof(inq));
hd = tl = 0;
q[tl++] = 0; neko_c_natsu[0] = 0; inq[neko] = 1;
while( hd != tl ) {
p = q[hd++]; inq[p] = 0;
if( neko_c_natsu[p] == 0 ) {
for(e = neko_h[p]; e != -1; e = neko_n[e]) {
if( neko_c_natsu[neko_t[e]] > neko_c_natsu[p] ) {
neko_c_natsu[neko_t[e]] = neko_c_natsu[p];
if( !inq[neko_t[e]] ) {
inq[neko_t[e]] = 1;
q[tl++] = neko_t[e];
}
}
}
}
for(e = nat_h[p]; e != -1; e = nat_n[e]) {
if( neko_c_natsu[nat_t[e]] > neko_c_natsu[p]+1 ) {
neko_c_natsu[nat_t[e]] = neko_c_natsu[p]+1;
if( !inq[nat_t[e]] ) {
inq[nat_t[e]] = 1;
q[tl++] = nat_t[e];
}
}
}
}
memset(inq,0,sizeof(inq));
hd = tl = 0;
q[tl++] = neko; neko_c[neko] = 0; inq[neko] = 1;
while( hd != tl ) {
p = q[hd++]; inq[p] = 0;
if( neko_c[p] == 0 ) {
for(e = neko_h[p]; e != -1; e = neko_n[e]) {
if( neko_c[neko_t[e]] > neko_c[p] ) {
neko_c[neko_t[e]] = neko_c[p];
if( !inq[neko_t[e]] ) {
inq[neko_t[e]] = 1;
q[tl++] = neko_t[e];
}
}
}
}
for(e = nat_h[p]; e != -1; e = nat_n[e]) {
if( neko_c[nat_t[e]] > neko_c[p]+1 ) {
neko_c[nat_t[e]] = neko_c[p]+1;
if( !inq[nat_t[e]] ) {
inq[nat_t[e]] = 1;
q[tl++] = nat_t[e];
}
}
}
}
res = 1<<21;
if( neko_c[0] == 0 ) res = 0;
for( i = 0; i <= n; i++ ) {
int k = nat_c[i]+neko_c[i]+neko_c_natsu[i];
if( res > k ) res = k;
}
printf("%d\n",res);
}
return 0;
} | C++ | #include <iostream>
#include <utility>
#include <tuple>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <algorithm>
#include <functional>
#include <climits>
#include <numeric>
#include <queue>
#include <cmath>
#include <iomanip>
#include <array>
#include <string>
#include <stack>
#include <cassert>
#include <memory>
#include <random>
int main() {
int t; std::cin >> t;
for (; t > 0; --t) {
int n, m; std::cin >> n >> m;
int human_start, cat_start; std::cin >> human_start >> cat_start;
std::vector<std::vector<int>> rooms(n + 1), for_cat(n + 1);
for (auto i = 0; i < m; ++i) {
int a, b; std::string type; std::cin >> a >> b >> type;
if (type == "N") {
rooms[a].push_back(b);
rooms[b].push_back(a);
}
else {
for_cat[a].push_back(b);
for_cat[b].push_back(a);
}
}
std::queue<int> queue;
std::vector<bool> can_move_from_start(n + 1, false), can_move_to_goal(n + 1, false);
can_move_from_start[cat_start] = true; queue.push(cat_start);
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : for_cat[top]) if (!can_move_from_start[next]) {
can_move_from_start[next] = true;
queue.push(next);
}
}
can_move_to_goal[0] = true; queue.push(0);
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : for_cat[top]) if (!can_move_to_goal[next]) {
can_move_to_goal[next] = true;
queue.push(next);
}
}
std::vector<int> from_start(n + 1, INT_MAX), to_goal(n + 1, INT_MAX), from_cat(n + 1, INT_MAX);
for (auto i = 0; i < can_move_to_goal.size(); ++i) if (can_move_to_goal[i]) {
to_goal[i] = 0; queue.push(i);
}
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : rooms[top]) if (to_goal[next] == INT_MAX) {
to_goal[next] = to_goal[top] + 1;
queue.push(next);
}
}
from_start[human_start] = 0; queue.push(human_start);
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : rooms[top]) if (from_start[next] == INT_MAX) {
from_start[next] = from_start[top] + 1;
queue.push(next);
}
}
for (auto i = 0; i < can_move_from_start.size(); ++i) if (can_move_from_start[i]) {
from_cat[i] = 0; queue.push(i);
}
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : rooms[top]) if (from_cat[next] == INT_MAX) {
from_cat[next] = from_cat[top] + 1;
queue.push(next);
}
}
int min_open = INT_MAX;
for (auto i = 0; i < n + 1; ++i) {
if (from_start[i] == INT_MAX || to_goal[i] == INT_MAX || from_cat[i] == INT_MAX) continue;
if (can_move_from_start[i] && can_move_to_goal[i]) {
min_open = 0;
break;
}
min_open = std::min(min_open, from_start[i] + to_goal[i] + from_cat[i]);
}
std::cout << min_open << '\n';
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <stdio.h>
#include <string.h>
int nat_m,nat_h[111111],nat_n[111111*2],nat_t[111111*2];
int nat_c[111111];
int neko_m,neko_h[111111],neko_n[111111*2],neko_t[111111*2];
int neko_c[111111],neko_c_natsu[111111];
int q[555555],inq[111111],hd,tl;
int nat_natsu_c[111111],neko_natsu_c[111111];
int main(void)
{
int n,m,nat,neko,u,v,i,e,p,res,T;
char c;
scanf("%d",&T);
while( T-- ) {
scanf("%d%d",&n,&m);
scanf("%d%d",&nat,&neko);
nat_m = neko_m = 0;
for(i = 0; i <= n; i++) {
nat_h[i] = neko_h[i] = -1;
neko_c[i] = neko_c_natsu[i] = 1<<21;
nat_c[i] = 1<<21;
}
#define add_edge1(n,h,t,m,u,v) (n[m]=h[u],h[u]=m,t[m]=v,++m)
for( i = 0; i < m; i++ ) {
scanf("%d%d %c",&u,&v,&c);
if( c == 'N' ) {
add_edge1(nat_n,nat_h,nat_t,nat_m,u,v);
add_edge1(nat_n,nat_h,nat_t,nat_m,v,u);
}
if( c == 'L' ) {
add_edge1(neko_n,neko_h,neko_t,neko_m,u,v);
add_edge1(neko_n,neko_h,neko_t,neko_m,v,u);
}
}
nat_c[nat] = 0;
hd = tl = 0;
q[tl++] = nat;
while( hd != tl ) {
p = q[hd++];
for( e = nat_h[p]; e != -1; e = nat_n[e] ) {
if( nat_c[nat_t[e]] > nat_c[p]+1 ) {
nat_c[nat_t[e]] = nat_c[p]+1;
q[tl++] = nat_t[e];
}
}
}
memset(inq,0,sizeof(inq));
hd = tl = 0;
q[tl++] = 0; neko_c_natsu[0] = 0; inq[neko] = 1;
while( hd != tl ) {
p = q[hd++]; inq[p] = 0;
if( neko_c_natsu[p] == 0 ) {
for(e = neko_h[p]; e != -1; e = neko_n[e]) {
if( neko_c_natsu[neko_t[e]] > neko_c_natsu[p] ) {
neko_c_natsu[neko_t[e]] = neko_c_natsu[p];
if( !inq[neko_t[e]] ) {
inq[neko_t[e]] = 1;
q[tl++] = neko_t[e];
}
}
}
}
for(e = nat_h[p]; e != -1; e = nat_n[e]) {
if( neko_c_natsu[nat_t[e]] > neko_c_natsu[p]+1 ) {
neko_c_natsu[nat_t[e]] = neko_c_natsu[p]+1;
if( !inq[nat_t[e]] ) {
inq[nat_t[e]] = 1;
q[tl++] = nat_t[e];
}
}
}
}
memset(inq,0,sizeof(inq));
hd = tl = 0;
q[tl++] = neko; neko_c[neko] = 0; inq[neko] = 1;
while( hd != tl ) {
p = q[hd++]; inq[p] = 0;
if( neko_c[p] == 0 ) {
for(e = neko_h[p]; e != -1; e = neko_n[e]) {
if( neko_c[neko_t[e]] > neko_c[p] ) {
neko_c[neko_t[e]] = neko_c[p];
if( !inq[neko_t[e]] ) {
inq[neko_t[e]] = 1;
q[tl++] = neko_t[e];
}
}
}
}
for(e = nat_h[p]; e != -1; e = nat_n[e]) {
if( neko_c[nat_t[e]] > neko_c[p]+1 ) {
neko_c[nat_t[e]] = neko_c[p]+1;
if( !inq[nat_t[e]] ) {
inq[nat_t[e]] = 1;
q[tl++] = nat_t[e];
}
}
}
}
res = 1<<21;
if( neko_c[0] == 0 ) res = 0;
for( i = 0; i <= n; i++ ) {
int k = nat_c[i]+neko_c[i]+neko_c_natsu[i];
if( res > k ) res = k;
}
printf("%d\n",res);
}
return 0;
}
Code 2: #include <iostream>
#include <utility>
#include <tuple>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <algorithm>
#include <functional>
#include <climits>
#include <numeric>
#include <queue>
#include <cmath>
#include <iomanip>
#include <array>
#include <string>
#include <stack>
#include <cassert>
#include <memory>
#include <random>
int main() {
int t; std::cin >> t;
for (; t > 0; --t) {
int n, m; std::cin >> n >> m;
int human_start, cat_start; std::cin >> human_start >> cat_start;
std::vector<std::vector<int>> rooms(n + 1), for_cat(n + 1);
for (auto i = 0; i < m; ++i) {
int a, b; std::string type; std::cin >> a >> b >> type;
if (type == "N") {
rooms[a].push_back(b);
rooms[b].push_back(a);
}
else {
for_cat[a].push_back(b);
for_cat[b].push_back(a);
}
}
std::queue<int> queue;
std::vector<bool> can_move_from_start(n + 1, false), can_move_to_goal(n + 1, false);
can_move_from_start[cat_start] = true; queue.push(cat_start);
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : for_cat[top]) if (!can_move_from_start[next]) {
can_move_from_start[next] = true;
queue.push(next);
}
}
can_move_to_goal[0] = true; queue.push(0);
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : for_cat[top]) if (!can_move_to_goal[next]) {
can_move_to_goal[next] = true;
queue.push(next);
}
}
std::vector<int> from_start(n + 1, INT_MAX), to_goal(n + 1, INT_MAX), from_cat(n + 1, INT_MAX);
for (auto i = 0; i < can_move_to_goal.size(); ++i) if (can_move_to_goal[i]) {
to_goal[i] = 0; queue.push(i);
}
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : rooms[top]) if (to_goal[next] == INT_MAX) {
to_goal[next] = to_goal[top] + 1;
queue.push(next);
}
}
from_start[human_start] = 0; queue.push(human_start);
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : rooms[top]) if (from_start[next] == INT_MAX) {
from_start[next] = from_start[top] + 1;
queue.push(next);
}
}
for (auto i = 0; i < can_move_from_start.size(); ++i) if (can_move_from_start[i]) {
from_cat[i] = 0; queue.push(i);
}
while (!queue.empty()) {
const auto top = queue.front(); queue.pop();
for (const auto next : rooms[top]) if (from_cat[next] == INT_MAX) {
from_cat[next] = from_cat[top] + 1;
queue.push(next);
}
}
int min_open = INT_MAX;
for (auto i = 0; i < n + 1; ++i) {
if (from_start[i] == INT_MAX || to_goal[i] == INT_MAX || from_cat[i] == INT_MAX) continue;
if (can_move_from_start[i] && can_move_to_goal[i]) {
min_open = 0;
break;
}
min_open = std::min(min_open, from_start[i] + to_goal[i] + from_cat[i]);
}
std::cout << min_open << '\n';
}
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
typedef long long ll;
ll xL[MAXN], xR[MAXN], C, preL[MAXN], preR[MAXN], mxL[MAXN], mxR[MAXN];
int vL[MAXN], vR[MAXN], N;
int main(){
scanf("%d %lld", &N, &C);
for(int i=1; i<=N; ++i){
scanf("%lld %d", &xL[i], &vL[i]);
xR[N - i + 1] = C - xL[i];
vR[N - i + 1] = vL[i];
}
for(int i=1; i<=N; ++i) preL[i] = preL[i - 1] - xL[i] + xL[i - 1] + vL[i];
for(int i=1; i<=N; ++i) preR[i] = preR[i - 1] - xR[i] + xR[i - 1] + vR[i];
for(int i=1; i<=N; ++i) mxR[i] = max(mxR[i - 1], preR[i]);
for(int i=1; i<=N; ++i) mxL[i] = max(mxL[i - 1], preL[i]);
ll best = 0;
for(int L=0; L<=N; ++L){
ll cur = preL[L];
if(cur > best) best = cur;
cur = cur - xL[L] + mxR[N - L];
if(cur > best) best = cur;
}
for(int R=0; R<=N; ++R){
ll cur = preR[R];
if(cur > best) best = cur;
cur = cur - xR[R] + mxL[N - R];
if(cur > best) best = cur;
}
printf("%lld\n", best);
return 0;
} | Go | package main
import (
"fmt"
"sort"
)
func main() {
var n int
var c int64
fmt.Scan(&n, &c)
s := make([]sushi, n)
for i := range s {
fmt.Scan(&s[i].x, &s[i].v)
}
sort.Sort(counter(s))
s = append([]sushi{sushi{0, 0}}, s...)
s = append(s, sushi{c, 0})
eatr := make([]int64, len(s))
eatr[0] = s[0].v
for i := 1; i < len(s); i++ {
eatr[i] = eatr[i-1] + s[i].v
}
eatl := make([]int64, len(s))
eatl[len(s)-1] = s[len(s)-1].v
for i := len(s) - 2; i >= 0; i-- {
eatl[i] = eatl[i+1] + s[i].v
}
maxr := make([]int64, len(s))
maxr[0] = eatr[0] - s[0].x
for i := 1; i < len(s); i++ {
maxr[i] = eatr[i] - s[i].x
if maxr[i-1] > maxr[i] {
maxr[i] = maxr[i-1]
}
}
maxr2 := make([]int64, len(s))
maxr2[0] = eatr[0] - 2*s[0].x
for i := 1; i < len(s); i++ {
maxr2[i] = eatr[i] - 2*s[i].x
if maxr2[i-1] > maxr2[i] {
maxr2[i] = maxr2[i-1]
}
}
var max int64
for i := 1; i < len(s); i++ {
call := eatl[i] - c + s[i].x
cal := maxr2[i-1] + call
if cal > max {
max = cal
}
call = eatl[i] - 2*c + 2*s[i].x
cal = maxr[i-1] + call
if cal > max {
max = cal
}
}
fmt.Println(max)
}
type sushi struct {
x, v int64
}
type counter []sushi
func (c counter) Len() int { return len(c) }
func (c counter) Less(i, j int) bool { return c[i].x < c[j].x }
func (c counter) Swap(i, j int) { c[i], c[j] = c[j], c[i] } | Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
typedef long long ll;
ll xL[MAXN], xR[MAXN], C, preL[MAXN], preR[MAXN], mxL[MAXN], mxR[MAXN];
int vL[MAXN], vR[MAXN], N;
int main(){
scanf("%d %lld", &N, &C);
for(int i=1; i<=N; ++i){
scanf("%lld %d", &xL[i], &vL[i]);
xR[N - i + 1] = C - xL[i];
vR[N - i + 1] = vL[i];
}
for(int i=1; i<=N; ++i) preL[i] = preL[i - 1] - xL[i] + xL[i - 1] + vL[i];
for(int i=1; i<=N; ++i) preR[i] = preR[i - 1] - xR[i] + xR[i - 1] + vR[i];
for(int i=1; i<=N; ++i) mxR[i] = max(mxR[i - 1], preR[i]);
for(int i=1; i<=N; ++i) mxL[i] = max(mxL[i - 1], preL[i]);
ll best = 0;
for(int L=0; L<=N; ++L){
ll cur = preL[L];
if(cur > best) best = cur;
cur = cur - xL[L] + mxR[N - L];
if(cur > best) best = cur;
}
for(int R=0; R<=N; ++R){
ll cur = preR[R];
if(cur > best) best = cur;
cur = cur - xR[R] + mxL[N - R];
if(cur > best) best = cur;
}
printf("%lld\n", best);
return 0;
}
Code 2: package main
import (
"fmt"
"sort"
)
func main() {
var n int
var c int64
fmt.Scan(&n, &c)
s := make([]sushi, n)
for i := range s {
fmt.Scan(&s[i].x, &s[i].v)
}
sort.Sort(counter(s))
s = append([]sushi{sushi{0, 0}}, s...)
s = append(s, sushi{c, 0})
eatr := make([]int64, len(s))
eatr[0] = s[0].v
for i := 1; i < len(s); i++ {
eatr[i] = eatr[i-1] + s[i].v
}
eatl := make([]int64, len(s))
eatl[len(s)-1] = s[len(s)-1].v
for i := len(s) - 2; i >= 0; i-- {
eatl[i] = eatl[i+1] + s[i].v
}
maxr := make([]int64, len(s))
maxr[0] = eatr[0] - s[0].x
for i := 1; i < len(s); i++ {
maxr[i] = eatr[i] - s[i].x
if maxr[i-1] > maxr[i] {
maxr[i] = maxr[i-1]
}
}
maxr2 := make([]int64, len(s))
maxr2[0] = eatr[0] - 2*s[0].x
for i := 1; i < len(s); i++ {
maxr2[i] = eatr[i] - 2*s[i].x
if maxr2[i-1] > maxr2[i] {
maxr2[i] = maxr2[i-1]
}
}
var max int64
for i := 1; i < len(s); i++ {
call := eatl[i] - c + s[i].x
cal := maxr2[i-1] + call
if cal > max {
max = cal
}
call = eatl[i] - 2*c + 2*s[i].x
cal = maxr[i-1] + call
if cal > max {
max = cal
}
}
fmt.Println(max)
}
type sushi struct {
x, v int64
}
type counter []sushi
func (c counter) Len() int { return len(c) }
func (c counter) Less(i, j int) bool { return c[i].x < c[j].x }
func (c counter) Swap(i, j int) { c[i], c[j] = c[j], c[i] } |
Python | a,b,c,d = map(int, input().split())
ans = 1<<30
def go(x, y):
global ans
ans = min(ans, abs(x-y))
go(a+b,c+d)
go(a+c,b+d)
go(a+d,b+c)
print(ans)
| Java | import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int d1 = Math.abs((a+b)-(c+d));
int d2 = Math.abs((a+c)-(b+d));
int d3 = Math.abs((a+d)-(b+c));
System.out.println(Math.min(Math.min(d1,d2), d3));
}
}
| Yes | Do these codes solve the same problem?
Code 1: a,b,c,d = map(int, input().split())
ans = 1<<30
def go(x, y):
global ans
ans = min(ans, abs(x-y))
go(a+b,c+d)
go(a+c,b+d)
go(a+d,b+c)
print(ans)
Code 2: import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int d1 = Math.abs((a+b)-(c+d));
int d2 = Math.abs((a+c)-(b+d));
int d3 = Math.abs((a+d)-(b+c));
System.out.println(Math.min(Math.min(d1,d2), d3));
}
}
|
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 h = o.a();
var w = o.a();
var n = o.a();
var a = o.l();
var x = 0, y = 0, z = 1;
var ans = Array(h).fill(0).map(a=>[]);
for(var i = 1; i <= n; i++){
for(var j = 0; j < a[i-1]; j++){
ans[y][x] = i;
if(z === 1 && y === h-1){
x++;
z = -1;
}else if(z === -1 && y === 0){
x++;
z = 1;
}else{
y += z;
}
}
}
return ans.map(a=>a.join(" ")).join("\n");
} | 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.Convert;
using static System.Math;
using static Extentions;
class IO
{
int idx;
string[] input = In.ReadToEnd().Split(new[] { " ", "\n", "\r" },
StringSplitOptions.RemoveEmptyEntries);
T Get<T>(Func<string, T> parser) => parser(input[idx++]);
public string S => Get(s => s);
public char C => Get(char.Parse);
public int I => Get(int.Parse);
public long L => Get(long.Parse);
public double F => Get(double.Parse);
public decimal D => Get(decimal.Parse);
public BigInteger B => Get(BigInteger.Parse);
T[] Gets<T>(int n, Func<string, T> parser)
=> input.Skip((idx += n) - n).Take(n).Select(parser).ToArray();
public string[] Ss(int n) => Gets(n, s => s);
public char[] Cs(int n) => Gets(n, char.Parse);
public int[] Is(int n) => Gets(n, int.Parse);
public long[] Ls(int n) => Gets(n, long.Parse);
public double[] Fs(int n) => Gets(n, double.Parse);
public decimal[] Ds(int n) => Gets(n, decimal.Parse);
public BigInteger[] Bs(int n) => Gets(n, BigInteger.Parse);
public void Write<T>(params T[] xs) => WriteLine(string.Join(" ", xs));
public void Write(params object[] xs) => WriteLine(string.Join(" ", xs));
}
static class Extentions
{
}
static class Program
{
public static void Main()
{
var sw = new StreamWriter(OpenStandardOutput()) { NewLine = "\n" };
#if DEBUG
sw.AutoFlush = true;
#else
sw.AutoFlush = false;
#endif
SetOut(sw);
Solve(new IO());
Out.Flush();
}
static void Solve(IO io)
{
var h = io.I;
var w = io.I;
var n = io.I;
var a = io.Is(n);
var seq = new List<int>();
for (var i = 0; i < n; i++)
{
for (var j = 0; j < a[i]; j++)
{
seq.Add(i + 1);
}
}
var ans = new int[h, w];
var cnt = 0;
for (var i = 0; i < h; i++)
{
for (var j = 0; j < w; j++)
{
var idx = i % 2 == 0 ? j : w - j - 1;
ans[i, idx] = seq[cnt++];
}
}
for (var i = 0; i < h; i++)
{
for (var j = 0; j < w; j++)
{
Write(ans[i, j] + " ");
}
WriteLine();
}
}
} | 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 h = o.a();
var w = o.a();
var n = o.a();
var a = o.l();
var x = 0, y = 0, z = 1;
var ans = Array(h).fill(0).map(a=>[]);
for(var i = 1; i <= n; i++){
for(var j = 0; j < a[i-1]; j++){
ans[y][x] = i;
if(z === 1 && y === h-1){
x++;
z = -1;
}else if(z === -1 && y === 0){
x++;
z = 1;
}else{
y += z;
}
}
}
return ans.map(a=>a.join(" ")).join("\n");
}
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.Convert;
using static System.Math;
using static Extentions;
class IO
{
int idx;
string[] input = In.ReadToEnd().Split(new[] { " ", "\n", "\r" },
StringSplitOptions.RemoveEmptyEntries);
T Get<T>(Func<string, T> parser) => parser(input[idx++]);
public string S => Get(s => s);
public char C => Get(char.Parse);
public int I => Get(int.Parse);
public long L => Get(long.Parse);
public double F => Get(double.Parse);
public decimal D => Get(decimal.Parse);
public BigInteger B => Get(BigInteger.Parse);
T[] Gets<T>(int n, Func<string, T> parser)
=> input.Skip((idx += n) - n).Take(n).Select(parser).ToArray();
public string[] Ss(int n) => Gets(n, s => s);
public char[] Cs(int n) => Gets(n, char.Parse);
public int[] Is(int n) => Gets(n, int.Parse);
public long[] Ls(int n) => Gets(n, long.Parse);
public double[] Fs(int n) => Gets(n, double.Parse);
public decimal[] Ds(int n) => Gets(n, decimal.Parse);
public BigInteger[] Bs(int n) => Gets(n, BigInteger.Parse);
public void Write<T>(params T[] xs) => WriteLine(string.Join(" ", xs));
public void Write(params object[] xs) => WriteLine(string.Join(" ", xs));
}
static class Extentions
{
}
static class Program
{
public static void Main()
{
var sw = new StreamWriter(OpenStandardOutput()) { NewLine = "\n" };
#if DEBUG
sw.AutoFlush = true;
#else
sw.AutoFlush = false;
#endif
SetOut(sw);
Solve(new IO());
Out.Flush();
}
static void Solve(IO io)
{
var h = io.I;
var w = io.I;
var n = io.I;
var a = io.Is(n);
var seq = new List<int>();
for (var i = 0; i < n; i++)
{
for (var j = 0; j < a[i]; j++)
{
seq.Add(i + 1);
}
}
var ans = new int[h, w];
var cnt = 0;
for (var i = 0; i < h; i++)
{
for (var j = 0; j < w; j++)
{
var idx = i % 2 == 0 ? j : w - j - 1;
ans[i, idx] = seq[cnt++];
}
}
for (var i = 0; i < h; i++)
{
for (var j = 0; j < w; j++)
{
Write(ans[i, j] + " ");
}
WriteLine();
}
}
} |
C++ | #define _CRT_SECURE_NO_WARNINGS
#pragma target("avx")
#pragma optimize("O3")
#pragma optimize("unroll-loops")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#define rep(i,n) for(int i=0;i<(lint)(n);i++)
#define REP(i,n) for(int i=1;i<=(lint)(n);i++)
#define all(V) V.begin(),V.end()
typedef long long lint;
typedef unsigned long long ulint;
typedef std::pair<lint, lint> P;
constexpr int INF = INT_MAX/2;
constexpr lint LINF = LLONG_MAX/2;
constexpr double eps = DBL_EPSILON;
constexpr double PI=3.141592653589793238462643383279;
template<class T>
class prique :public std::priority_queue<T, std::vector<T>, std::greater<T>> {};
template <class T, class U>
inline bool chmax(T& lhs, const U& rhs) {
if (lhs < rhs) {
lhs = rhs;
return 1;
}
return 0;
}
template <class T, class U>
inline bool chmin(T& lhs, const U& rhs) {
if (lhs > rhs) {
lhs = rhs;
return 1;
}
return 0;
}
inline lint gcd(lint a, lint b) {
while (b) {
lint c = a;
a = b; b = c % b;
}
return a;
}
inline lint lcm(lint a, lint b) {
return a / gcd(a, b) * b;
}
bool isprime(lint n) {
if (n == 1)return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)return false;
}
return true;
}
template<typename T>
T mypow(T a, unsigned int b) {
if (!b)return T(1);
if (b & 1)return mypow(a, b - 1) * a;
T memo = mypow(a, b >> 1);
return memo * memo;
}
lint modpow(lint a, lint b, lint m) {
if (!b)return 1;
if (b & 1)return modpow(a, b - 1, m) * a % m;
lint memo = modpow(a, b >> 1, m);
return memo * memo % m;
}
template<typename T>
void printArray(std::vector<T>& vec) {
rep(i, vec.size() - 1)std::cout << vec[i] << " ";
std::cout << vec.back() << std::endl;
}
template<typename T>
void printArray(T l, T r) {
T rprev = r;
rprev--;
for (T i = l; i != rprev; i++) {
std::cout << *i << " ";
}
std::cout << *rprev << std::endl;
}
class BIT {
unsigned int n;
std::vector<lint> bit;
public:
BIT(unsigned int n) :n(n) {
bit.resize(n + 1, 0);
}
void add(int a, lint x) {
while (a <= n) {
bit[a] += x;
a += a & -a;
}
}
lint query(int a) {
lint cnt = 0;
while (a > 0) {
cnt += bit[a];
a -= a & -a;
}
return cnt;
}
void clear() {
bit.assign(n + 1, 0);
}
unsigned int lower_bound(int x){
int p=0,k=1;
while(k*2<=n)k*=2;
while(k>0){
if(p+k<=n&&bit[p+k]<x){
x-=bit[p+k];
p+=k;
}
k/=2;
}
return p+1;
}
unsigned int upper_bound(int x){
int p=0,k=1;
while(k*2<=n)k*=2;
while(k>0){
if(p+k<=n&&bit[p+k]<=x){
x-=bit[p+k];
p+=k;
}
k/=2;
}
return p+1;
}
};
lint n,q,a;
int main(){
std::cin>>n>>q;
BIT bit(n);
REP(i,n){
std::cin>>a;
bit.add(i,a);
}
rep(i,q){
int t;
std::cin>>t;
if(t==0){
lint p,x;
std::cin>>p>>x;
p++;
bit.add(p,x);
}
else{
int l,r;
std::cin>>l>>r;
l++;r++;
std::cout<<bit.query(r-1)-(l==1?0:bit.query(l-1))<<std::endl;
}
}
return 0;
} | TypeScript |
export default class FenwickTree {
/**
* Constructor creates empty fenwick tree of size 'arraySize',
* however, array size is size+1, because index is 1-based.
*
* @param {number} arraySize
*/
arraySize;
treeArray;
constructor(arraySize) {
this.arraySize = arraySize;
// Fill tree array with zeros.
this.treeArray = Array(this.arraySize + 1).fill(0);
}
/**
* Adds value to existing value at position.
*
* @param {number} position
* @param {number} value
* @return {FenwickTree}
*/
increase(position, value) {
if (position < 1 || position > this.arraySize) {
throw new Error('Position is out of allowed range');
}
for (let i = position; i <= this.arraySize; i += (i & -i)) {
this.treeArray[i] += value;
}
return this;
}
/**
* Query sum from index 1 to position.
*
* @param {number} position
* @return {number}
*/
query(position) {
if (position < 1 || position > this.arraySize) {
throw new Error('Position is out of allowed range');
}
let sum = 0;
for (let i = position; i > 0; i -= (i & -i)) {
sum += this.treeArray[i];
}
return sum;
}
/**
* Query sum from index leftIndex to rightIndex.
*
* @param {number} leftIndex
* @param {number} rightIndex
* @return {number}
*/
queryRange(leftIndex, rightIndex) {
if (leftIndex > rightIndex) {
throw new Error('Left index can not be greater than right one');
}
if (leftIndex === 1) {
return this.query(rightIndex);
}
return this.query(rightIndex) - this.query(leftIndex - 1);
}
}
let input = require("fs").readFileSync("/dev/stdin", "utf8"); let cin = input.split(/ |\n/), cid = 0; function next() { return +cin[cid++]; }function nexts(n,a?){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}//input from catoonさん
//go();//黒魔術ですよ
function main() {
let ans = [];
let n = next();
let q = next();
let bit = new FenwickTree(n+1);
// let tmp = nexts(n);
for(let i =0;i<n;i++){
bit.increase(i+1,next());
}
for (let i = 0; i < q; i++) {
let x = next();
let l = next();
let r = next();
if (x === 1) {
ans.push(bit.queryRange(l+1,r));
}
else{
bit.increase(l+1,r);
}
}
let rick = ans.join('\n');
return rick;
}
let stream = process.stdout;
function write(data, n) { if (!stream.write(data)) { stream.once('drain', n); } else { process.nextTick(n); } } write(main(), next);
function go(){var i=require("util"),u={};function o(f?,t?){f=f||8192,Object.keys(u).forEach(function(e){console[e]=function(){var o=i.format.apply(this,arguments);"string"==typeof t?o=t+o:"function"==typeof t&&(o=t()+o);var n=Buffer.byteLength(o);u[e].size+=n,u[e].buf.push(o),u[e].size>f&&c()}})}function c(){Object.keys(u).forEach(function(o){u[o].size&&u[o].func(u[o].buf.join("\n")),u[o].buf.length=0,u[o].size=0})}process.on("exit",c),module.exports=o,module.exports.flush=c,["warn","log","error","info"].forEach(function(o){u[o]={func:console[o].bind(console),size:0,buf:[]}}),o()}
| Yes | Do these codes solve the same problem?
Code 1: #define _CRT_SECURE_NO_WARNINGS
#pragma target("avx")
#pragma optimize("O3")
#pragma optimize("unroll-loops")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#define rep(i,n) for(int i=0;i<(lint)(n);i++)
#define REP(i,n) for(int i=1;i<=(lint)(n);i++)
#define all(V) V.begin(),V.end()
typedef long long lint;
typedef unsigned long long ulint;
typedef std::pair<lint, lint> P;
constexpr int INF = INT_MAX/2;
constexpr lint LINF = LLONG_MAX/2;
constexpr double eps = DBL_EPSILON;
constexpr double PI=3.141592653589793238462643383279;
template<class T>
class prique :public std::priority_queue<T, std::vector<T>, std::greater<T>> {};
template <class T, class U>
inline bool chmax(T& lhs, const U& rhs) {
if (lhs < rhs) {
lhs = rhs;
return 1;
}
return 0;
}
template <class T, class U>
inline bool chmin(T& lhs, const U& rhs) {
if (lhs > rhs) {
lhs = rhs;
return 1;
}
return 0;
}
inline lint gcd(lint a, lint b) {
while (b) {
lint c = a;
a = b; b = c % b;
}
return a;
}
inline lint lcm(lint a, lint b) {
return a / gcd(a, b) * b;
}
bool isprime(lint n) {
if (n == 1)return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)return false;
}
return true;
}
template<typename T>
T mypow(T a, unsigned int b) {
if (!b)return T(1);
if (b & 1)return mypow(a, b - 1) * a;
T memo = mypow(a, b >> 1);
return memo * memo;
}
lint modpow(lint a, lint b, lint m) {
if (!b)return 1;
if (b & 1)return modpow(a, b - 1, m) * a % m;
lint memo = modpow(a, b >> 1, m);
return memo * memo % m;
}
template<typename T>
void printArray(std::vector<T>& vec) {
rep(i, vec.size() - 1)std::cout << vec[i] << " ";
std::cout << vec.back() << std::endl;
}
template<typename T>
void printArray(T l, T r) {
T rprev = r;
rprev--;
for (T i = l; i != rprev; i++) {
std::cout << *i << " ";
}
std::cout << *rprev << std::endl;
}
class BIT {
unsigned int n;
std::vector<lint> bit;
public:
BIT(unsigned int n) :n(n) {
bit.resize(n + 1, 0);
}
void add(int a, lint x) {
while (a <= n) {
bit[a] += x;
a += a & -a;
}
}
lint query(int a) {
lint cnt = 0;
while (a > 0) {
cnt += bit[a];
a -= a & -a;
}
return cnt;
}
void clear() {
bit.assign(n + 1, 0);
}
unsigned int lower_bound(int x){
int p=0,k=1;
while(k*2<=n)k*=2;
while(k>0){
if(p+k<=n&&bit[p+k]<x){
x-=bit[p+k];
p+=k;
}
k/=2;
}
return p+1;
}
unsigned int upper_bound(int x){
int p=0,k=1;
while(k*2<=n)k*=2;
while(k>0){
if(p+k<=n&&bit[p+k]<=x){
x-=bit[p+k];
p+=k;
}
k/=2;
}
return p+1;
}
};
lint n,q,a;
int main(){
std::cin>>n>>q;
BIT bit(n);
REP(i,n){
std::cin>>a;
bit.add(i,a);
}
rep(i,q){
int t;
std::cin>>t;
if(t==0){
lint p,x;
std::cin>>p>>x;
p++;
bit.add(p,x);
}
else{
int l,r;
std::cin>>l>>r;
l++;r++;
std::cout<<bit.query(r-1)-(l==1?0:bit.query(l-1))<<std::endl;
}
}
return 0;
}
Code 2:
export default class FenwickTree {
/**
* Constructor creates empty fenwick tree of size 'arraySize',
* however, array size is size+1, because index is 1-based.
*
* @param {number} arraySize
*/
arraySize;
treeArray;
constructor(arraySize) {
this.arraySize = arraySize;
// Fill tree array with zeros.
this.treeArray = Array(this.arraySize + 1).fill(0);
}
/**
* Adds value to existing value at position.
*
* @param {number} position
* @param {number} value
* @return {FenwickTree}
*/
increase(position, value) {
if (position < 1 || position > this.arraySize) {
throw new Error('Position is out of allowed range');
}
for (let i = position; i <= this.arraySize; i += (i & -i)) {
this.treeArray[i] += value;
}
return this;
}
/**
* Query sum from index 1 to position.
*
* @param {number} position
* @return {number}
*/
query(position) {
if (position < 1 || position > this.arraySize) {
throw new Error('Position is out of allowed range');
}
let sum = 0;
for (let i = position; i > 0; i -= (i & -i)) {
sum += this.treeArray[i];
}
return sum;
}
/**
* Query sum from index leftIndex to rightIndex.
*
* @param {number} leftIndex
* @param {number} rightIndex
* @return {number}
*/
queryRange(leftIndex, rightIndex) {
if (leftIndex > rightIndex) {
throw new Error('Left index can not be greater than right one');
}
if (leftIndex === 1) {
return this.query(rightIndex);
}
return this.query(rightIndex) - this.query(leftIndex - 1);
}
}
let input = require("fs").readFileSync("/dev/stdin", "utf8"); let cin = input.split(/ |\n/), cid = 0; function next() { return +cin[cid++]; }function nexts(n,a?){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}//input from catoonさん
//go();//黒魔術ですよ
function main() {
let ans = [];
let n = next();
let q = next();
let bit = new FenwickTree(n+1);
// let tmp = nexts(n);
for(let i =0;i<n;i++){
bit.increase(i+1,next());
}
for (let i = 0; i < q; i++) {
let x = next();
let l = next();
let r = next();
if (x === 1) {
ans.push(bit.queryRange(l+1,r));
}
else{
bit.increase(l+1,r);
}
}
let rick = ans.join('\n');
return rick;
}
let stream = process.stdout;
function write(data, n) { if (!stream.write(data)) { stream.once('drain', n); } else { process.nextTick(n); } } write(main(), next);
function go(){var i=require("util"),u={};function o(f?,t?){f=f||8192,Object.keys(u).forEach(function(e){console[e]=function(){var o=i.format.apply(this,arguments);"string"==typeof t?o=t+o:"function"==typeof t&&(o=t()+o);var n=Buffer.byteLength(o);u[e].size+=n,u[e].buf.push(o),u[e].size>f&&c()}})}function c(){Object.keys(u).forEach(function(o){u[o].size&&u[o].func(u[o].buf.join("\n")),u[o].buf.length=0,u[o].size=0})}process.on("exit",c),module.exports=o,module.exports.flush=c,["warn","log","error","info"].forEach(function(o){u[o]={func:console[o].bind(console),size:0,buf:[]}}),o()}
|
C | #include <stdio.h>
int main(void){
int n,max = 0;
int a[100];
for(int i=0; i<100; i++){
a[i] = 0;
}
while(scanf("%d",&n)!=EOF){
a[n]++;
}
for(int n=0; n<100; n++){
if(a[n] > max){
max = a[n];
}
}
for(int n=0; n<100; n++){
if(a[n] == max){
printf("%d\n",n);
}
}
return 0;
}
| C++ | #include <iostream>
#include <cmath>
using namespace std;
int main(){
long N;
cin >> N;
long long power = 1.0;
for(double i = 1; i <= N; ++i){
power = fmod(power * i, (pow(10.0,9.0) + 7));
}
cout << power << endl;
return 0;
} | No | Do these codes solve the same problem?
Code 1: #include <stdio.h>
int main(void){
int n,max = 0;
int a[100];
for(int i=0; i<100; i++){
a[i] = 0;
}
while(scanf("%d",&n)!=EOF){
a[n]++;
}
for(int n=0; n<100; n++){
if(a[n] > max){
max = a[n];
}
}
for(int n=0; n<100; n++){
if(a[n] == max){
printf("%d\n",n);
}
}
return 0;
}
Code 2: #include <iostream>
#include <cmath>
using namespace std;
int main(){
long N;
cin >> N;
long long power = 1.0;
for(double i = 1; i <= N; ++i){
power = fmod(power * i, (pow(10.0,9.0) + 7));
}
cout << power << endl;
return 0;
} |
C++ | #include <bits/stdc++.h>
using namespace std;
int n,c,a[31],b[31],dp[31][1<<16];
void solve(){
memset(dp,-1,sizeof(dp));
dp[0][0]=0;
for(int i=0;i<n;i++){
for(int j=0;j<(1<<16);j++){
if(dp[i][j]<0)continue;
int nj=(j|a[i]);
for(int k=0;k<c;k++){
int cal=(nj&b[k]);
int pop=__builtin_popcount(cal);
dp[i+1][nj-cal]=max(dp[i+1][nj-cal],dp[i][j]+pop);
}
}
}
int ans=0;
for(int i=0;i<(1<<16);i++)ans=max(ans,dp[n][i]);
cout<<ans<<endl;
}
int main(){
while(cin>>n>>c,n){
for(int i=0;i<n;i++){
a[i]=0;
for(int j=0;j<16;j++){
int x;cin>>x;
a[i]=(a[i]<<1)+x;
}
}
for(int i=0;i<c;i++){
b[i]=0;
for(int j=0;j<16;j++){
int x;cin>>x;
b[i]=(b[i]<<1)+x;
}
}
solve();
}
return 0;
}
| C# | using System;
using static System.Math;
public class hello
{
static int jmax = 1 << 16;
public static void Main()
{
while (true)
{
string[] line = Console.ReadLine().Trim().Split(' ');
var n = int.Parse(line[0]);
var c = int.Parse(line[1]);
if (n == 0 && c == 0) break;
var a = getArray(n);
var b = getArray(c);
var dp = new int[n + 1, jmax];
for (int i = 0; i < n + 1; i++)
for (int j = 0; j < jmax; j++) dp[i, j] = -1;
var ans = getAns(dp, a, b, n, c);
Console.WriteLine(ans);
}
}
static int getAns(int[,] dp, int[] a, int[] b, int n, int c)
{
dp[0, 0] = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < jmax; j++)
if (dp[i, j] != -1)
{
var nj = j | a[i];
for (int k = 0; k < c; k++)
{
var t2 = nj & (~b[k]);
var pt = countBit(nj & b[k]);
dp[i + 1, t2] = Max(dp[i + 1, t2], dp[i, j] + pt);
}
}
var ans = 0;
for (int i = 0; i < jmax; i++)
ans = Max(ans, dp[n, i]);
return ans;
}
static int countBit(int bits)
{
bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555);
bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333);
bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f);
bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff);
return (bits & 0x0000ffff) + (bits >> 16 & 0x0000ffff);
}
static int[] getArray(int n)
{
var a = new int[n];
for (int i = 0; i < n; i++)
{
var s = Console.ReadLine().Trim().Replace(" ", "");
a[i] = Convert.ToInt32(s, 2);
}
return a;
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int n,c,a[31],b[31],dp[31][1<<16];
void solve(){
memset(dp,-1,sizeof(dp));
dp[0][0]=0;
for(int i=0;i<n;i++){
for(int j=0;j<(1<<16);j++){
if(dp[i][j]<0)continue;
int nj=(j|a[i]);
for(int k=0;k<c;k++){
int cal=(nj&b[k]);
int pop=__builtin_popcount(cal);
dp[i+1][nj-cal]=max(dp[i+1][nj-cal],dp[i][j]+pop);
}
}
}
int ans=0;
for(int i=0;i<(1<<16);i++)ans=max(ans,dp[n][i]);
cout<<ans<<endl;
}
int main(){
while(cin>>n>>c,n){
for(int i=0;i<n;i++){
a[i]=0;
for(int j=0;j<16;j++){
int x;cin>>x;
a[i]=(a[i]<<1)+x;
}
}
for(int i=0;i<c;i++){
b[i]=0;
for(int j=0;j<16;j++){
int x;cin>>x;
b[i]=(b[i]<<1)+x;
}
}
solve();
}
return 0;
}
Code 2: using System;
using static System.Math;
public class hello
{
static int jmax = 1 << 16;
public static void Main()
{
while (true)
{
string[] line = Console.ReadLine().Trim().Split(' ');
var n = int.Parse(line[0]);
var c = int.Parse(line[1]);
if (n == 0 && c == 0) break;
var a = getArray(n);
var b = getArray(c);
var dp = new int[n + 1, jmax];
for (int i = 0; i < n + 1; i++)
for (int j = 0; j < jmax; j++) dp[i, j] = -1;
var ans = getAns(dp, a, b, n, c);
Console.WriteLine(ans);
}
}
static int getAns(int[,] dp, int[] a, int[] b, int n, int c)
{
dp[0, 0] = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < jmax; j++)
if (dp[i, j] != -1)
{
var nj = j | a[i];
for (int k = 0; k < c; k++)
{
var t2 = nj & (~b[k]);
var pt = countBit(nj & b[k]);
dp[i + 1, t2] = Max(dp[i + 1, t2], dp[i, j] + pt);
}
}
var ans = 0;
for (int i = 0; i < jmax; i++)
ans = Max(ans, dp[n, i]);
return ans;
}
static int countBit(int bits)
{
bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555);
bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333);
bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f);
bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff);
return (bits & 0x0000ffff) + (bits >> 16 & 0x0000ffff);
}
static int[] getArray(int n)
{
var a = new int[n];
for (int i = 0; i < n; i++)
{
var s = Console.ReadLine().Trim().Replace(" ", "");
a[i] = Convert.ToInt32(s, 2);
}
return a;
}
}
|
Python | import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) #空白あり
N,M,C = MI()
B = LI()
ans = 0
for i in range(N):
A = LI()
if C + sum(A[j]*B[j] for j in range(M)) > 0:
ans += 1
print(ans)
| Java | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int city = sc.nextInt();
long[] monster = new long[city+1];
long[] brave = new long[city];
long anser = 0;
for(int i=0;i<city+1;i++) {
monster[i] = sc.nextLong();
}
for(int i =0;i<city;i++) {
brave[i] = sc.nextLong();
}
//勇者の攻撃がなくなるまで
for(int i = 0; i<brave.length;i++) {
//AとBの小さいほうをanserにいれる
anser += Math.min(monster[i],brave[i]);
//A(i+1)と(B-A)の小さいほうを入れる。
anser += Math.min(monster[i+1],Math.max(brave[i]-monster[i], 0));
//A(i+1) = A(i+1)とmax(0,(B-A))の小さいほうを引く
monster[i+1] -= Math.min(monster[i+1],Math.max(brave[i]-monster[i], 0));
}
System.out.println(anser);
}
} | No | Do these codes solve the same problem?
Code 1: import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) #空白あり
N,M,C = MI()
B = LI()
ans = 0
for i in range(N):
A = LI()
if C + sum(A[j]*B[j] for j in range(M)) > 0:
ans += 1
print(ans)
Code 2: import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int city = sc.nextInt();
long[] monster = new long[city+1];
long[] brave = new long[city];
long anser = 0;
for(int i=0;i<city+1;i++) {
monster[i] = sc.nextLong();
}
for(int i =0;i<city;i++) {
brave[i] = sc.nextLong();
}
//勇者の攻撃がなくなるまで
for(int i = 0; i<brave.length;i++) {
//AとBの小さいほうをanserにいれる
anser += Math.min(monster[i],brave[i]);
//A(i+1)と(B-A)の小さいほうを入れる。
anser += Math.min(monster[i+1],Math.max(brave[i]-monster[i], 0));
//A(i+1) = A(i+1)とmax(0,(B-A))の小さいほうを引く
monster[i+1] -= Math.min(monster[i+1],Math.max(brave[i]-monster[i], 0));
}
System.out.println(anser);
}
} |
C++ | #include <algorithm>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <map>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <list>
#include <cstdio>
#define INF 1LL<<60
#define MOD 1000000007ll
#define EPS 1e-10
#define REP(i,m) for(long long i=0; i<m; i++)
#define FOR(i,n,m) for(long long i=n; i<m; i++)
#define pb push_back
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> P;
typedef long double ld;
int main(){
int n;
cin >> n;
int a[n];
REP(i, n) cin >> a[i];
sort(a, a+n);
if(a[n-1] - a[0] > 1){
cout << "No" << endl;
return 0;
}
int M = 0, N;
N = a[n-1];
while(a[M] == (N-1)) M++;
if(M <= (N-1) && (2*N-M) <= n) cout << "Yes" << endl;
else if(M == 0 && N == (n-1)) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
| Python | import sys
def resolve(in_):
s, w = map(int, next(in_).split())
return 'safe' if s > w else 'unsafe'
def main():
answer = resolve(sys.stdin.buffer)
print(answer)
if __name__ == '__main__':
main() | No | Do these codes solve the same problem?
Code 1: #include <algorithm>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <map>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <list>
#include <cstdio>
#define INF 1LL<<60
#define MOD 1000000007ll
#define EPS 1e-10
#define REP(i,m) for(long long i=0; i<m; i++)
#define FOR(i,n,m) for(long long i=n; i<m; i++)
#define pb push_back
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> P;
typedef long double ld;
int main(){
int n;
cin >> n;
int a[n];
REP(i, n) cin >> a[i];
sort(a, a+n);
if(a[n-1] - a[0] > 1){
cout << "No" << endl;
return 0;
}
int M = 0, N;
N = a[n-1];
while(a[M] == (N-1)) M++;
if(M <= (N-1) && (2*N-M) <= n) cout << "Yes" << endl;
else if(M == 0 && N == (n-1)) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
Code 2: import sys
def resolve(in_):
s, w = map(int, next(in_).split())
return 'safe' if s > w else 'unsafe'
def main():
answer = resolve(sys.stdin.buffer)
print(answer)
if __name__ == '__main__':
main() |
C++ | // include
// ------------------------------------------------
#include <bits/stdc++.h>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
// func
// ------------------------------------------------
int CalcSumOfDigit(int n); // 各桁の和を計算する。
// define
// ------------------------------------------------
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define sz(a) int((a).size())
#define rep(i,n) for(int(i)=0;(i)<(n);(i)++)
#define repe(i,n) for(int(i)=0;(i)<=(n);(i)++)
#define vsort(v) sort((v).begin(),(v).end())
// code
// ------------------------------------------------
int main() {
int n,m;
cin >> n >> m;
int a = 0;
int nn,mm;
nn = (n - 1) > 0 ? (n - 1) : 0;
mm = (m - 1) > 0 ? (m - 1) : 0;
a = n * nn / 2 + mm * m / 2;
cout << a << endl;
return 0;
}
// funcの実体
// ------------------------------------------------
int CalcSumOfDigit(int n)
{
int s = 0;
while(n)
{
s += n % 10;
n = n / 10;
}
return s;
} | Python | a=input().rstrip().split(" ")
if a[0]==a[1]:
print("Yes")
else:
print("No") | No | Do these codes solve the same problem?
Code 1: // include
// ------------------------------------------------
#include <bits/stdc++.h>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
// func
// ------------------------------------------------
int CalcSumOfDigit(int n); // 各桁の和を計算する。
// define
// ------------------------------------------------
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define sz(a) int((a).size())
#define rep(i,n) for(int(i)=0;(i)<(n);(i)++)
#define repe(i,n) for(int(i)=0;(i)<=(n);(i)++)
#define vsort(v) sort((v).begin(),(v).end())
// code
// ------------------------------------------------
int main() {
int n,m;
cin >> n >> m;
int a = 0;
int nn,mm;
nn = (n - 1) > 0 ? (n - 1) : 0;
mm = (m - 1) > 0 ? (m - 1) : 0;
a = n * nn / 2 + mm * m / 2;
cout << a << endl;
return 0;
}
// funcの実体
// ------------------------------------------------
int CalcSumOfDigit(int n)
{
int s = 0;
while(n)
{
s += n % 10;
n = n / 10;
}
return s;
}
Code 2: a=input().rstrip().split(" ")
if a[0]==a[1]:
print("Yes")
else:
print("No") |
Python | A, B, C = map(int, input().strip().split())
print("Yes" if A+B >= C else "No")
| C++ | #include<bits/stdc++.h>
using namespace std;
#define rep(i,j,n) for(int i=(int)(j);i<(int)(n);i++)
#define REP(i,j,n) for(int i=(int)(j);i<=(int)(n);i++)
#define MOD 1000000007
#define int long long
#define ALL(a) (a).begin(),(a).end()
#define vi vector<int>
#define vii vector<vi>
#define pii pair<int,int>
#define priq priority_queue<int>
#define disup(A,key) distance(A.begin(),upper_bound(ALL(A),(int)(key)))
#define dislow(A,key) distance(A.begin(),lower_bound(ALL(A),(int)(key)))
signed main(){
int N,M;
cin>>N>>M;
vi A(N);
rep(i,0,N) cin>>A[i];
sort(ALL(A));
vector<pii> B(M);
rep(i,0,M){
cin>>B[i].second>>B[i].first;
}
sort(ALL(B));
int memo=M-1;
int ans=0;
rep(i,0,N){
if(A[i]<B[memo].first){
ans+=B[memo].first;
B[memo].second--;
if(B[memo].second==0)
memo--;
}
else
ans+=A[i];
}
cout<<ans;
}
| No | Do these codes solve the same problem?
Code 1: A, B, C = map(int, input().strip().split())
print("Yes" if A+B >= C else "No")
Code 2: #include<bits/stdc++.h>
using namespace std;
#define rep(i,j,n) for(int i=(int)(j);i<(int)(n);i++)
#define REP(i,j,n) for(int i=(int)(j);i<=(int)(n);i++)
#define MOD 1000000007
#define int long long
#define ALL(a) (a).begin(),(a).end()
#define vi vector<int>
#define vii vector<vi>
#define pii pair<int,int>
#define priq priority_queue<int>
#define disup(A,key) distance(A.begin(),upper_bound(ALL(A),(int)(key)))
#define dislow(A,key) distance(A.begin(),lower_bound(ALL(A),(int)(key)))
signed main(){
int N,M;
cin>>N>>M;
vi A(N);
rep(i,0,N) cin>>A[i];
sort(ALL(A));
vector<pii> B(M);
rep(i,0,M){
cin>>B[i].second>>B[i].first;
}
sort(ALL(B));
int memo=M-1;
int ans=0;
rep(i,0,N){
if(A[i]<B[memo].first){
ans+=B[memo].first;
B[memo].second--;
if(B[memo].second==0)
memo--;
}
else
ans+=A[i];
}
cout<<ans;
}
|
C# | using System;
using System.Linq;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using SB = System.Text.StringBuilder;
using Number = System.Int64;
using System.Numerics;
using static System.Math;
//using static MathEx;
namespace Program
{
public class Solver
{
public void Solve()
{
var n = ri;
var a = Enumerate(3 * n, x => rl);
var L = Enumerate(3 * n + 1, x => -1L << 60);
var R = Enumerate(3 * n + 1, x => -1L << 60);
{
var pq = new PriorityQueue<long>();
var v = 0L;
for (int i = 0; i < 2 * n; i++)
{
pq.Enqueue(a[i]);
v += a[i];
while (pq.Count > n)
v -= pq.Dequeue();
if (pq.Count == n)
L[i + 1] = v;
}
v = 0L;
pq = new PriorityQueue<long>((l, r) => r.CompareTo(l));
for (int i = 3 * n - 1, cnt = 1; i > 0; i--, cnt++)
{
pq.Enqueue(a[i]);
v += a[i];
while (pq.Count > n) v -= pq.Dequeue();
if (pq.Count == n)
R[cnt] = v;
}
}
var max = long.MinValue;
for (int i = n; i <= 2 * n; i++)
max = Max(max, L[i] - R[3 * n - i]);
IO.Printer.Out.WriteLine(max);
}
int ri => sc.Integer();
long rl => sc.Long();
double rd => sc.Double();
string rs => sc.Scan();
char rc => sc.Char();
[System.Diagnostics.Conditional("DEBUG")]
void put(params object[] a) => Debug.WriteLine(string.Join(" ", a));
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 BinaryHeap
public class PriorityQueue<T>
{
readonly List<T> heap = new List<T>();
readonly IComparer<T> cmp;
public PriorityQueue() { cmp = Comparer<T>.Default; }
public PriorityQueue(Comparison<T> f) { cmp = Comparer<T>.Create(f); }
public PriorityQueue(IComparer<T> c) { cmp = c; }
public void Enqueue(T item)
{
var i = heap.Count;
heap.Add(item);
while (i > 0)
{
var p = (i - 1) / 2;
if (cmp.Compare(heap[p], item) <= 0)
break;
heap[i] = heap[p];
i = p;
}
heap[i] = item;
}
public T Dequeue()
{
var ret = heap[0];
var i = 0;
var x = heap[heap.Count - 1];
while ((i * 2) + 1 < heap.Count - 1)
{
var a = i * 2 + 1;
var b = i * 2 + 2;
if (b < heap.Count - 1 && cmp.Compare(heap[b], heap[a]) < 0) a = b;
if (cmp.Compare(heap[a], x) >= 0)
break;
heap[i] = heap[a];
i = a;
}
heap[i] = x;
heap.RemoveAt(heap.Count - 1);
return ret;
}
public T Peek() { return heap[0]; }
public int Count { get { return heap.Count; } }
public bool Any() { return heap.Count > 0; }
public T[] Items
{
get
{
var ret = heap.ToArray();
Array.Sort(ret, cmp);
return ret;
}
}
}
#endregion | PHP | <?php
/*
Problem URL : http://arc074.contest.atcoder.jp/tasks/arc074_b
Score :
Result :
Time : ms
Memory : KB
*/
// $queue = new SplPriorityQueue();
// $queue->insert('a', 10);
// $queue->insert('b', 100);
// $queue->insert('c', 50);
// $queue->insert('d', 50);
// $queue->insert('e', 1);
// // 個数 → 5
// print('count:' . $queue->count());
// $queue->setExtractFlags (SplPriorityQueue::EXTR_DATA);
// $queue->setExtractFlags (SplPriorityQueue::EXTR_BOTH);
// $queue->setExtractFlags (SplPriorityQueue::EXTR_PRIORITY);
// $arr = $queue->extract();
// print('count:' . $queue->count());
// var_dump($arr);
// $queue->insert('f', 55);
// $arr = $queue->extract();
// var_dump($arr);
// $queue->insert('', 45);
// $arr = $queue->extract();
// var_dump($arr);
// exit;
ini_set('error_reporting', E_ALL & ~E_NOTICE);
fscanf(STDIN, "%d", $N);
$a = explode(" ", trim(fgets(STDIN)));
$b = array_reverse($a);
$ans = -PHP_INT_MAX;
$x = array_slice($a, 0, $N);
$y = array_slice($b, 0, $N);
$queue1 = new SplPriorityQueue();
$queue2 = new SplPriorityQueue();
$queue1->setExtractFlags (SplPriorityQueue::EXTR_PRIORITY);
$queue2->setExtractFlags (SplPriorityQueue::EXTR_PRIORITY);
for ($i = 0; $i < $N; $i++) {
$queue1->insert('', PHP_INT_MAX - $a[$i]);
$totalA += $a[$i];
$queue2->insert('', $b[$i]);
$totalB += $b[$i];
}
for ($i = $N; $i <= $N * 2; $i++) {
$sumX[$i] = $totalA;
$sumY[$i] = $totalB;
$queue1->insert('', PHP_INT_MAX - $a[$i]);
$queue2->insert('', $b[$i]);
$pop1 = PHP_INT_MAX - $queue1->extract();
$pop2 = $queue2->extract();
$totalA += ($a[$i] - $pop1);
$totalB += ($b[$i] - $pop2);
}
for ($i = $N; $i <= $N * 2; $i++) {
$tmp = $sumX[$i] - $sumY[$N * 3 - $i];
$ans = max($ans, $tmp);
}
echo $ans . PHP_EOL;
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Linq;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using SB = System.Text.StringBuilder;
using Number = System.Int64;
using System.Numerics;
using static System.Math;
//using static MathEx;
namespace Program
{
public class Solver
{
public void Solve()
{
var n = ri;
var a = Enumerate(3 * n, x => rl);
var L = Enumerate(3 * n + 1, x => -1L << 60);
var R = Enumerate(3 * n + 1, x => -1L << 60);
{
var pq = new PriorityQueue<long>();
var v = 0L;
for (int i = 0; i < 2 * n; i++)
{
pq.Enqueue(a[i]);
v += a[i];
while (pq.Count > n)
v -= pq.Dequeue();
if (pq.Count == n)
L[i + 1] = v;
}
v = 0L;
pq = new PriorityQueue<long>((l, r) => r.CompareTo(l));
for (int i = 3 * n - 1, cnt = 1; i > 0; i--, cnt++)
{
pq.Enqueue(a[i]);
v += a[i];
while (pq.Count > n) v -= pq.Dequeue();
if (pq.Count == n)
R[cnt] = v;
}
}
var max = long.MinValue;
for (int i = n; i <= 2 * n; i++)
max = Max(max, L[i] - R[3 * n - i]);
IO.Printer.Out.WriteLine(max);
}
int ri => sc.Integer();
long rl => sc.Long();
double rd => sc.Double();
string rs => sc.Scan();
char rc => sc.Char();
[System.Diagnostics.Conditional("DEBUG")]
void put(params object[] a) => Debug.WriteLine(string.Join(" ", a));
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 BinaryHeap
public class PriorityQueue<T>
{
readonly List<T> heap = new List<T>();
readonly IComparer<T> cmp;
public PriorityQueue() { cmp = Comparer<T>.Default; }
public PriorityQueue(Comparison<T> f) { cmp = Comparer<T>.Create(f); }
public PriorityQueue(IComparer<T> c) { cmp = c; }
public void Enqueue(T item)
{
var i = heap.Count;
heap.Add(item);
while (i > 0)
{
var p = (i - 1) / 2;
if (cmp.Compare(heap[p], item) <= 0)
break;
heap[i] = heap[p];
i = p;
}
heap[i] = item;
}
public T Dequeue()
{
var ret = heap[0];
var i = 0;
var x = heap[heap.Count - 1];
while ((i * 2) + 1 < heap.Count - 1)
{
var a = i * 2 + 1;
var b = i * 2 + 2;
if (b < heap.Count - 1 && cmp.Compare(heap[b], heap[a]) < 0) a = b;
if (cmp.Compare(heap[a], x) >= 0)
break;
heap[i] = heap[a];
i = a;
}
heap[i] = x;
heap.RemoveAt(heap.Count - 1);
return ret;
}
public T Peek() { return heap[0]; }
public int Count { get { return heap.Count; } }
public bool Any() { return heap.Count > 0; }
public T[] Items
{
get
{
var ret = heap.ToArray();
Array.Sort(ret, cmp);
return ret;
}
}
}
#endregion
Code 2: <?php
/*
Problem URL : http://arc074.contest.atcoder.jp/tasks/arc074_b
Score :
Result :
Time : ms
Memory : KB
*/
// $queue = new SplPriorityQueue();
// $queue->insert('a', 10);
// $queue->insert('b', 100);
// $queue->insert('c', 50);
// $queue->insert('d', 50);
// $queue->insert('e', 1);
// // 個数 → 5
// print('count:' . $queue->count());
// $queue->setExtractFlags (SplPriorityQueue::EXTR_DATA);
// $queue->setExtractFlags (SplPriorityQueue::EXTR_BOTH);
// $queue->setExtractFlags (SplPriorityQueue::EXTR_PRIORITY);
// $arr = $queue->extract();
// print('count:' . $queue->count());
// var_dump($arr);
// $queue->insert('f', 55);
// $arr = $queue->extract();
// var_dump($arr);
// $queue->insert('', 45);
// $arr = $queue->extract();
// var_dump($arr);
// exit;
ini_set('error_reporting', E_ALL & ~E_NOTICE);
fscanf(STDIN, "%d", $N);
$a = explode(" ", trim(fgets(STDIN)));
$b = array_reverse($a);
$ans = -PHP_INT_MAX;
$x = array_slice($a, 0, $N);
$y = array_slice($b, 0, $N);
$queue1 = new SplPriorityQueue();
$queue2 = new SplPriorityQueue();
$queue1->setExtractFlags (SplPriorityQueue::EXTR_PRIORITY);
$queue2->setExtractFlags (SplPriorityQueue::EXTR_PRIORITY);
for ($i = 0; $i < $N; $i++) {
$queue1->insert('', PHP_INT_MAX - $a[$i]);
$totalA += $a[$i];
$queue2->insert('', $b[$i]);
$totalB += $b[$i];
}
for ($i = $N; $i <= $N * 2; $i++) {
$sumX[$i] = $totalA;
$sumY[$i] = $totalB;
$queue1->insert('', PHP_INT_MAX - $a[$i]);
$queue2->insert('', $b[$i]);
$pop1 = PHP_INT_MAX - $queue1->extract();
$pop2 = $queue2->extract();
$totalA += ($a[$i] - $pop1);
$totalB += ($b[$i] - $pop2);
}
for ($i = $N; $i <= $N * 2; $i++) {
$tmp = $sumX[$i] - $sumY[$N * 3 - $i];
$ans = max($ans, $tmp);
}
echo $ans . PHP_EOL;
|
C | // AOJ 1322 ASCII Expression
// 2018.3.5 bal4u
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define M 2011
int n, W;
char buf[22][85], *p;
int expr(int bs, int tp, int bm);
int powmod(int a, int n)
{
int ans = 1;
while (n) {
if (n & 1) ans = (ans * a) % M;
a = (a * a) % M;
n >>= 1;
}
return ans;
}
int parse(int c, int tp, int bm)
{
int bs;
for ( ; c < W; c++) {
for (bs = tp; bs < bm; bs++) if (buf[bs][c] != '.') goto done;
}
done:
p = buf[bs] + c;
return expr(bs, tp, bm);
}
int primary(int bs, int tp, int bm)
{
int x;
if (*p == '(' && *(p+1) == '.') {
p += 2, x = expr(bs, tp, bm), p += 2;
} else x = *p++ & 0xf;
return x;
}
int powexpr(int bs, int tp, int bm)
{
int d;
int x = primary(bs, tp, bm);
if (tp <= bs-1 && *p > ' ' && isdigit(d=buf[bs-1][p-buf[bs]])) {
x = powmod(x, d & 0xf), p++;
}
return x;
}
int factor(int bs, int tp, int bm)
{
int x, c, si, bo;
if (*p != '-') x = powexpr(bs, tp, bm);
else {
if (*(p+1) == '.') {
p += 2;
x = M - factor(bs, tp, bm);
if (x >= M) x -= M;
} else {
c = p-buf[bs];
si = parse(c, tp , bs);
bo = parse(c, bs+1, bm);
p = buf[bs]+c;
while (*p == '-') p++;
x = (si * powmod(bo, M-2)) % M;
}
}
return x;
}
int term(int bs, int tp, int bm)
{
int x = factor(bs, tp, bm);
while (*p == '.' && *(p+1) == '*' && *(p+2) == '.') {
p += 3;
x = (x * factor(bs, tp, bm)) % M;
}
return x;
}
int expr(int bs, int tp, int bm)
{
char op;
int x = term(bs, tp, bm), y;
while (*p == '.' && (*(p+1) == '+' || *(p+1) == '-') && *(p+2) == '.') {
op = *(p+1), p += 3;
y = term(bs, tp, bm);
if (op == '+') { x += y; if (x >= M) x -= M; }
else { x -= y; if (x < 0 ) x += M; }
}
return x;
}
int main()
{
int r;
while (fgets(p=buf[0], 10, stdin) && *p != '0') {
n = atoi(buf[0]);
for (r = 0; r < n; r++) {
fgets(buf[r], 85, stdin);
if (!r) { p = buf[0]; while (*p > ' ') p++; W = p-buf[0]; }
}
printf("%d\n", parse(0, 0, n));
}
return 0;
}
| 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()
{
while (true) Solve();
}
static int h, w;
static string[] expr;
public static void Solve()
{
h = int.Parse(Console.ReadLine());
if (h == 0) Environment.Exit(0);
expr = Enumerable.Repeat(0, h).Select(_ => Console.ReadLine()).ToArray();
w = expr[0].Length;
Console.WriteLine(Eval(0, h - 1, 0, w - 1));
}
static ModInt Eval(int ymin, int ymax, int xmin, int xmax)
{
int baseY = -1;
while (true)
{
for (int i = ymin; i <= ymax; i++)
{
if (expr[i][xmin] != '.') baseY = i;
}
if (baseY != -1) break;
xmin++;
}
int x = xmin;
List<ModInt> nums = new List<ModInt>() { EvalSingleTerm(baseY, ymin, ymax, ref x) };
List<char> ops = new List<char>();
while (true)
{
x += 2;
if (x > xmax) break;
var op = expr[baseY][x];
if (op != '+' && op != '-' && op != '*') break;
x += 2;
if (x > xmax) break;
var num = EvalSingleTerm(baseY, ymin, ymax, ref x);
if (op == '*') nums[nums.Count - 1] *= num;
else
{
ops.Add(op);
nums.Add(num);
}
}
var res = nums[0];
for (int i = 1; i < nums.Count; i++)
{
if (ops[i - 1] == '+') res += nums[i];
else res -= nums[i];
}
return res;
}
static ModInt EvalSingleTerm(int baseY, int ymin, int ymax, ref int x)
{
if (expr[baseY][x] == '-')
{
if (expr[baseY][x + 1] != '-')
{
x += 2;
return -EvalSingleTerm(baseY, ymin, ymax, ref x);
}
else
{
var xmin = x + 1;
for (; x + 1 < w && expr[baseY][x + 1] == '-'; x++) ;
return Eval(ymin, baseY - 1, xmin, x - 1) / Eval(baseY + 1, ymax, xmin, x - 1);
}
}
ModInt res;
if (expr[baseY][x] == '(')
{
var depth = 0;
var xmin = x + 2;
for (; x < w; x++)
{
if (expr[baseY][x] == '(') depth++;
if (expr[baseY][x] == ')') depth--;
if (depth == 0) break;
}
res = Eval(ymin, ymax, xmin, x - 2);
}
else res = expr[baseY][x] - '0';
if (ymin <= baseY - 1 && x + 1 < w && expr[baseY - 1][x + 1] != '.') res = Power(res, expr[baseY - 1][++x] - '0');
return res;
}
static ModInt Power(ModInt n, long m)
{
ModInt pow = n;
ModInt res = 1;
while (m > 0)
{
if ((m & 1) == 1) res *= pow;
pow *= pow;
m >>= 1;
}
return res;
}
}
struct ModInt
{
public const int Mod = 2011;
const long POSITIVIZER = ((long)Mod) << 31;
long Data;
public ModInt(long data) { if ((Data = data % Mod) < 0) Data += Mod; }
public static implicit operator long(ModInt modInt) => modInt.Data;
public static implicit operator ModInt(long val) => new ModInt(val);
public static ModInt operator +(ModInt a, int b) => new ModInt() { Data = (a.Data + b + POSITIVIZER) % Mod };
public static ModInt operator +(ModInt a, long b) => new ModInt(a.Data + b);
public static ModInt operator +(ModInt a, ModInt b) { long res = a.Data + b.Data; return new ModInt() { Data = res >= Mod ? res - Mod : res }; }
public static ModInt operator -(ModInt a, int b) => new ModInt() { Data = (a.Data - b + POSITIVIZER) % Mod };
public static ModInt operator -(ModInt a, long b) => new ModInt(a.Data - b);
public static ModInt operator -(ModInt a, ModInt b) { long res = a.Data - b.Data; return new ModInt() { Data = res < 0 ? res + Mod : res }; }
public static ModInt operator *(ModInt a, int b) => new ModInt(a.Data * b);
public static ModInt operator *(ModInt a, long b) => a * new ModInt(b);
public static ModInt operator *(ModInt a, ModInt b) => new ModInt() { Data = a.Data * b.Data % Mod };
public static ModInt operator /(ModInt a, ModInt b) => new ModInt() { Data = a.Data * GetInverse(b) % Mod };
public static bool operator ==(ModInt a, ModInt b) => a.Data == b.Data;
public static bool operator !=(ModInt a, ModInt b) => a.Data != b.Data;
public override string ToString() => Data.ToString();
public override bool Equals(object obj) => (ModInt)obj == this;
public override int GetHashCode() => (int)Data;
static long GetInverse(long a)
{
long div, p = Mod, x1 = 1, y1 = 0, x2 = 0, y2 = 1;
while (true)
{
if (p == 1) return x2 + Mod; div = a / p; x1 -= x2 * div; y1 -= y2 * div; a %= p;
if (a == 1) return x1 + Mod; div = p / a; x2 -= x1 * div; y2 -= y1 * div; p %= a;
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: // AOJ 1322 ASCII Expression
// 2018.3.5 bal4u
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define M 2011
int n, W;
char buf[22][85], *p;
int expr(int bs, int tp, int bm);
int powmod(int a, int n)
{
int ans = 1;
while (n) {
if (n & 1) ans = (ans * a) % M;
a = (a * a) % M;
n >>= 1;
}
return ans;
}
int parse(int c, int tp, int bm)
{
int bs;
for ( ; c < W; c++) {
for (bs = tp; bs < bm; bs++) if (buf[bs][c] != '.') goto done;
}
done:
p = buf[bs] + c;
return expr(bs, tp, bm);
}
int primary(int bs, int tp, int bm)
{
int x;
if (*p == '(' && *(p+1) == '.') {
p += 2, x = expr(bs, tp, bm), p += 2;
} else x = *p++ & 0xf;
return x;
}
int powexpr(int bs, int tp, int bm)
{
int d;
int x = primary(bs, tp, bm);
if (tp <= bs-1 && *p > ' ' && isdigit(d=buf[bs-1][p-buf[bs]])) {
x = powmod(x, d & 0xf), p++;
}
return x;
}
int factor(int bs, int tp, int bm)
{
int x, c, si, bo;
if (*p != '-') x = powexpr(bs, tp, bm);
else {
if (*(p+1) == '.') {
p += 2;
x = M - factor(bs, tp, bm);
if (x >= M) x -= M;
} else {
c = p-buf[bs];
si = parse(c, tp , bs);
bo = parse(c, bs+1, bm);
p = buf[bs]+c;
while (*p == '-') p++;
x = (si * powmod(bo, M-2)) % M;
}
}
return x;
}
int term(int bs, int tp, int bm)
{
int x = factor(bs, tp, bm);
while (*p == '.' && *(p+1) == '*' && *(p+2) == '.') {
p += 3;
x = (x * factor(bs, tp, bm)) % M;
}
return x;
}
int expr(int bs, int tp, int bm)
{
char op;
int x = term(bs, tp, bm), y;
while (*p == '.' && (*(p+1) == '+' || *(p+1) == '-') && *(p+2) == '.') {
op = *(p+1), p += 3;
y = term(bs, tp, bm);
if (op == '+') { x += y; if (x >= M) x -= M; }
else { x -= y; if (x < 0 ) x += M; }
}
return x;
}
int main()
{
int r;
while (fgets(p=buf[0], 10, stdin) && *p != '0') {
n = atoi(buf[0]);
for (r = 0; r < n; r++) {
fgets(buf[r], 85, stdin);
if (!r) { p = buf[0]; while (*p > ' ') p++; W = p-buf[0]; }
}
printf("%d\n", parse(0, 0, n));
}
return 0;
}
Code 2: 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()
{
while (true) Solve();
}
static int h, w;
static string[] expr;
public static void Solve()
{
h = int.Parse(Console.ReadLine());
if (h == 0) Environment.Exit(0);
expr = Enumerable.Repeat(0, h).Select(_ => Console.ReadLine()).ToArray();
w = expr[0].Length;
Console.WriteLine(Eval(0, h - 1, 0, w - 1));
}
static ModInt Eval(int ymin, int ymax, int xmin, int xmax)
{
int baseY = -1;
while (true)
{
for (int i = ymin; i <= ymax; i++)
{
if (expr[i][xmin] != '.') baseY = i;
}
if (baseY != -1) break;
xmin++;
}
int x = xmin;
List<ModInt> nums = new List<ModInt>() { EvalSingleTerm(baseY, ymin, ymax, ref x) };
List<char> ops = new List<char>();
while (true)
{
x += 2;
if (x > xmax) break;
var op = expr[baseY][x];
if (op != '+' && op != '-' && op != '*') break;
x += 2;
if (x > xmax) break;
var num = EvalSingleTerm(baseY, ymin, ymax, ref x);
if (op == '*') nums[nums.Count - 1] *= num;
else
{
ops.Add(op);
nums.Add(num);
}
}
var res = nums[0];
for (int i = 1; i < nums.Count; i++)
{
if (ops[i - 1] == '+') res += nums[i];
else res -= nums[i];
}
return res;
}
static ModInt EvalSingleTerm(int baseY, int ymin, int ymax, ref int x)
{
if (expr[baseY][x] == '-')
{
if (expr[baseY][x + 1] != '-')
{
x += 2;
return -EvalSingleTerm(baseY, ymin, ymax, ref x);
}
else
{
var xmin = x + 1;
for (; x + 1 < w && expr[baseY][x + 1] == '-'; x++) ;
return Eval(ymin, baseY - 1, xmin, x - 1) / Eval(baseY + 1, ymax, xmin, x - 1);
}
}
ModInt res;
if (expr[baseY][x] == '(')
{
var depth = 0;
var xmin = x + 2;
for (; x < w; x++)
{
if (expr[baseY][x] == '(') depth++;
if (expr[baseY][x] == ')') depth--;
if (depth == 0) break;
}
res = Eval(ymin, ymax, xmin, x - 2);
}
else res = expr[baseY][x] - '0';
if (ymin <= baseY - 1 && x + 1 < w && expr[baseY - 1][x + 1] != '.') res = Power(res, expr[baseY - 1][++x] - '0');
return res;
}
static ModInt Power(ModInt n, long m)
{
ModInt pow = n;
ModInt res = 1;
while (m > 0)
{
if ((m & 1) == 1) res *= pow;
pow *= pow;
m >>= 1;
}
return res;
}
}
struct ModInt
{
public const int Mod = 2011;
const long POSITIVIZER = ((long)Mod) << 31;
long Data;
public ModInt(long data) { if ((Data = data % Mod) < 0) Data += Mod; }
public static implicit operator long(ModInt modInt) => modInt.Data;
public static implicit operator ModInt(long val) => new ModInt(val);
public static ModInt operator +(ModInt a, int b) => new ModInt() { Data = (a.Data + b + POSITIVIZER) % Mod };
public static ModInt operator +(ModInt a, long b) => new ModInt(a.Data + b);
public static ModInt operator +(ModInt a, ModInt b) { long res = a.Data + b.Data; return new ModInt() { Data = res >= Mod ? res - Mod : res }; }
public static ModInt operator -(ModInt a, int b) => new ModInt() { Data = (a.Data - b + POSITIVIZER) % Mod };
public static ModInt operator -(ModInt a, long b) => new ModInt(a.Data - b);
public static ModInt operator -(ModInt a, ModInt b) { long res = a.Data - b.Data; return new ModInt() { Data = res < 0 ? res + Mod : res }; }
public static ModInt operator *(ModInt a, int b) => new ModInt(a.Data * b);
public static ModInt operator *(ModInt a, long b) => a * new ModInt(b);
public static ModInt operator *(ModInt a, ModInt b) => new ModInt() { Data = a.Data * b.Data % Mod };
public static ModInt operator /(ModInt a, ModInt b) => new ModInt() { Data = a.Data * GetInverse(b) % Mod };
public static bool operator ==(ModInt a, ModInt b) => a.Data == b.Data;
public static bool operator !=(ModInt a, ModInt b) => a.Data != b.Data;
public override string ToString() => Data.ToString();
public override bool Equals(object obj) => (ModInt)obj == this;
public override int GetHashCode() => (int)Data;
static long GetInverse(long a)
{
long div, p = Mod, x1 = 1, y1 = 0, x2 = 0, y2 = 1;
while (true)
{
if (p == 1) return x2 + Mod; div = a / p; x1 -= x2 * div; y1 -= y2 * div; a %= p;
if (a == 1) return x1 + Mod; div = p / a; x2 -= x1 * div; y2 -= y1 * div; p %= a;
}
}
}
|
Python | x,y,z=map(int,input().split())
if x+y+z>21:
print('bust')
else:
print('win') | C++ | #include <bits/stdc++.h>
typedef long long LL;
using namespace std;
int main() {
int n, a, b;
cin >> n >> a >> b;
string s;
cin >> s;
int pass = 0, fpass = 0;
for (int i = 0; i < n; i ++) {
if (s[i] == 'c') {
cout << "No" << endl;
} else if (s[i] == 'a') {
if (pass < a + b) {
cout << "Yes" << endl;
pass ++;
} else {
cout << "No" << endl;
}
} else {
if (pass < a + b && fpass < b) {
cout << "Yes" << endl;
pass ++, fpass ++;
} else {
cout << "No" << endl;
}
}
}
} | No | Do these codes solve the same problem?
Code 1: x,y,z=map(int,input().split())
if x+y+z>21:
print('bust')
else:
print('win')
Code 2: #include <bits/stdc++.h>
typedef long long LL;
using namespace std;
int main() {
int n, a, b;
cin >> n >> a >> b;
string s;
cin >> s;
int pass = 0, fpass = 0;
for (int i = 0; i < n; i ++) {
if (s[i] == 'c') {
cout << "No" << endl;
} else if (s[i] == 'a') {
if (pass < a + b) {
cout << "Yes" << endl;
pass ++;
} else {
cout << "No" << endl;
}
} else {
if (pass < a + b && fpass < b) {
cout << "Yes" << endl;
pass ++, fpass ++;
} else {
cout << "No" << endl;
}
}
}
} |
C | #include<stdio.h>
#define MAX 1000
#define WIMAX 10000
int n, a[MAX], s;
int b[MAX], T[WIMAX + 1];
int partition(int a[], int p, int r){
int i, j;
int t, x;
x = a[r];
i = p - 1;
for(j = p ; j < r ; j++){
if(a[j] <= x){
i++;
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
t = a[i + 1];
a[i + 1] = a[r];
a[r] = t;
return i + 1;
}
void quickSort(int a[], int p, int r){
int q;
if(p < r){
q = partition(a, p, r);
quickSort(a, p, q - 1);
quickSort(a, q + 1, r);
}
}
int solve(){
int i, cur, S, m, an, v, ans = 0 ;
int V[MAX];
for(i = 0 ; i < n ; i++){
b[i] = a[i];
V[i] = 0;
}
quickSort(b, 0, n - 1);
for(i = 0 ; i < n ; i++) T[b[i]] = i;
for(i = 0 ; i < n ; i++){
if(V[i]) continue;
cur = i;
S = 0;
m = WIMAX;
an = 0;
while(1){
V[cur] = 1;
an++;
v = a[cur];
if(v < m) m = v;
S += v;
cur = T[v];
if(V[cur]) break;
}
if(S + (an -2) * m < m + S + (an + 1) * s) ans += S + (an -2) * m;
else ans += m + S + (an + 1) * s;
}
return ans;
}
int main(){
int i;
scanf("%d", &n);
s = WIMAX;
for(i = 0 ; i < n ; i++){
scanf("%d", &a[i]);
if(a[i] < s) s = a[i];
}
int ans = solve();
printf("%d\n", ans);
return 0;
}
| Go | package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
func getScanner(fp *os.File) *bufio.Scanner {
scanner := bufio.NewScanner(fp)
scanner.Split(bufio.ScanWords)
scanner.Buffer(make([]byte, 500001), 500000)
return scanner
}
func getNextString(scanner *bufio.Scanner) string {
scanner.Scan()
return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
i, _ := strconv.Atoi(getNextString(scanner))
return i
}
func main() {
fp := os.Stdin
if len(os.Args) > 1 {
fp, _ = os.Open(os.Args[1])
}
scanner := getScanner(fp)
writer := bufio.NewWriter(os.Stdout)
n := getNextInt(scanner)
ww := make([]int, n)
sorted := make([]int, n)
vv := make([]bool, n)
min := 1 << 30
for i := 0; i < n; i++ {
ww[i] = getNextInt(scanner)
if min > ww[i] {
min = ww[i]
}
sorted[i] = ww[i]
vv[i] = false
}
ttt := make(map[int]int, 0)
sort.Sort(sort.IntSlice(sorted))
for i := 0; i < n; i++ {
ttt[sorted[i]] = i
}
ans := 0
for i := 0; i < n; i++ {
if vv[i] {
continue
}
cur := i
s := 0
m := 1 << 30
an := 0
for {
vv[cur] = true
an++
v := ww[cur]
if m > v {
m = v
}
s += v
cur = ttt[v]
if vv[cur] {
break
}
}
ans += minint(s+(an-2)*m, m+s+(an+1)*min)
}
fmt.Fprintln(writer, ans)
writer.Flush()
}
func minint(a int, b int) int {
if a < b {
return a
}
return b
}
| Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
#define MAX 1000
#define WIMAX 10000
int n, a[MAX], s;
int b[MAX], T[WIMAX + 1];
int partition(int a[], int p, int r){
int i, j;
int t, x;
x = a[r];
i = p - 1;
for(j = p ; j < r ; j++){
if(a[j] <= x){
i++;
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
t = a[i + 1];
a[i + 1] = a[r];
a[r] = t;
return i + 1;
}
void quickSort(int a[], int p, int r){
int q;
if(p < r){
q = partition(a, p, r);
quickSort(a, p, q - 1);
quickSort(a, q + 1, r);
}
}
int solve(){
int i, cur, S, m, an, v, ans = 0 ;
int V[MAX];
for(i = 0 ; i < n ; i++){
b[i] = a[i];
V[i] = 0;
}
quickSort(b, 0, n - 1);
for(i = 0 ; i < n ; i++) T[b[i]] = i;
for(i = 0 ; i < n ; i++){
if(V[i]) continue;
cur = i;
S = 0;
m = WIMAX;
an = 0;
while(1){
V[cur] = 1;
an++;
v = a[cur];
if(v < m) m = v;
S += v;
cur = T[v];
if(V[cur]) break;
}
if(S + (an -2) * m < m + S + (an + 1) * s) ans += S + (an -2) * m;
else ans += m + S + (an + 1) * s;
}
return ans;
}
int main(){
int i;
scanf("%d", &n);
s = WIMAX;
for(i = 0 ; i < n ; i++){
scanf("%d", &a[i]);
if(a[i] < s) s = a[i];
}
int ans = solve();
printf("%d\n", ans);
return 0;
}
Code 2: package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
func getScanner(fp *os.File) *bufio.Scanner {
scanner := bufio.NewScanner(fp)
scanner.Split(bufio.ScanWords)
scanner.Buffer(make([]byte, 500001), 500000)
return scanner
}
func getNextString(scanner *bufio.Scanner) string {
scanner.Scan()
return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
i, _ := strconv.Atoi(getNextString(scanner))
return i
}
func main() {
fp := os.Stdin
if len(os.Args) > 1 {
fp, _ = os.Open(os.Args[1])
}
scanner := getScanner(fp)
writer := bufio.NewWriter(os.Stdout)
n := getNextInt(scanner)
ww := make([]int, n)
sorted := make([]int, n)
vv := make([]bool, n)
min := 1 << 30
for i := 0; i < n; i++ {
ww[i] = getNextInt(scanner)
if min > ww[i] {
min = ww[i]
}
sorted[i] = ww[i]
vv[i] = false
}
ttt := make(map[int]int, 0)
sort.Sort(sort.IntSlice(sorted))
for i := 0; i < n; i++ {
ttt[sorted[i]] = i
}
ans := 0
for i := 0; i < n; i++ {
if vv[i] {
continue
}
cur := i
s := 0
m := 1 << 30
an := 0
for {
vv[cur] = true
an++
v := ww[cur]
if m > v {
m = v
}
s += v
cur = ttt[v]
if vv[cur] {
break
}
}
ans += minint(s+(an-2)*m, m+s+(an+1)*min)
}
fmt.Fprintln(writer, ans)
writer.Flush()
}
func minint(a int, b int) int {
if a < b {
return a
}
return b
}
|
Python | S = list(input())
C = 0
ans = 0
for i in range(len(S)):
if S[i] == 'A' or S[i] == 'C' or S[i] == 'G' or S[i] == 'T':
C += 1
ans = max(C,ans)
else:
C = 0
print(ans)
| C | #include<stdio.h>
int main(void)
{
int r, d, x, ans, i;
scanf("%d%d%d", &r, &d, &x);
ans = r * x - d;
for(i = 1; i <= 10; i++)
{
printf("%d\n", ans);
ans = ans * r - d;
}
return 0;
}
| No | Do these codes solve the same problem?
Code 1: S = list(input())
C = 0
ans = 0
for i in range(len(S)):
if S[i] == 'A' or S[i] == 'C' or S[i] == 'G' or S[i] == 'T':
C += 1
ans = max(C,ans)
else:
C = 0
print(ans)
Code 2: #include<stdio.h>
int main(void)
{
int r, d, x, ans, i;
scanf("%d%d%d", &r, &d, &x);
ans = r * x - d;
for(i = 1; i <= 10; i++)
{
printf("%d\n", ans);
ans = ans * r - d;
}
return 0;
}
|
C++ | // Bismillahir Rahmanir Rahim
//ALGO:
#include<bits/stdc++.h>
#define pb push_back
#define F first
#define S second
#define all(v) v.begin(), v.end()
#define FILL(a, x) memset(a, x, sizeof(a))
#define ll long long
#define Fast ios_base::sync_with_stdio(false);cin.tie(NULL);
#define INF INT_MAX
#define MX 1000010
#define mod 998244353
#define dout if(debug) cout
#define FR(i, n) for(int i=0; i<n; i++)
#define FOR(i, n) for(int i=1; i<=n; i++)
const double Pi=acos(-1);
using namespace std;
int debug=01;
void solve(){
ll n, k;
cin>>n>>k;
ll x[k], y[k], cnt[n+1]={0};
for(ll i=0; i<k; i++)cin>>x[i]>>y[i];
cnt[1]=1;
ll sum=0;
for(ll i=2; i<=n; i++){
for(ll j=0; j<k; j++){
if(i-x[j]>0)sum=(sum+cnt[i-x[j]])%mod;
if(i-y[j]-1>0)sum=(sum-cnt[i-y[j]-1]+mod)%mod;
}
cnt[i]=sum;
}
cout<<cnt[n];
}
int main() {
Fast
int tst=1;
//cin>>tst;
for(int T=1; T<=tst; T++){
//cout<<"Case "<<T<<": ";
solve();
}
}
| Python |
class StrAlg:
@staticmethod
def sa_naive(s):
n = len(s)
sa = list(range(n))
sa.sort(key=lambda x: s[x:])
return sa
@staticmethod
def sa_doubling(s):
n = len(s)
sa = list(range(n))
rnk = s
tmp = [0] * n
k = 1
while k < n:
sa.sort(key=lambda x: (rnk[x], rnk[x + k])
if x + k < n else (rnk[x], -1))
tmp[sa[0]] = 0
for i in range(1, n):
tmp[sa[i]] = tmp[sa[i - 1]]
x = (rnk[sa[i - 1]], rnk[sa[i - 1] + k]) if sa[i - 1] + \
k < n else (rnk[sa[i - 1]], -1)
y = (rnk[sa[i]], rnk[sa[i] + k]) if sa[i] + \
k < n else (rnk[sa[i]], -1)
if x < y:
tmp[sa[i]] += 1
k *= 2
tmp, rnk = rnk, tmp
return sa
@staticmethod
def sa_is(s, upper):
n = len(s)
if n == 0:
return []
if n == 1:
return [0]
if n == 2:
if s[0] < s[1]:
return [0, 1]
else:
return [1, 0]
if n < 10:
return StrAlg.sa_naive(s)
if n < 50:
return StrAlg.sa_doubling(s)
ls = [0] * n
for i in range(n - 1)[::-1]:
ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1]
sum_l = [0] * (upper + 1)
sum_s = [0] * (upper + 1)
for i in range(n):
if ls[i]:
sum_l[s[i] + 1] += 1
else:
sum_s[s[i]] += 1
for i in range(upper):
sum_s[i] += sum_l[i]
if i < upper:
sum_l[i + 1] += sum_s[i]
lms_map = [-1] * (n + 1)
m = 0
for i in range(1, n):
if not ls[i - 1] and ls[i]:
lms_map[i] = m
m += 1
lms = []
for i in range(1, n):
if not ls[i - 1] and ls[i]:
lms.append(i)
sa = [-1] * n
buf = sum_s.copy()
for d in lms:
if d == n:
continue
sa[buf[s[d]]] = d
buf[s[d]] += 1
buf = sum_l.copy()
sa[buf[s[n - 1]]] = n - 1
buf[s[n - 1]] += 1
for i in range(n):
v = sa[i]
if v >= 1 and not ls[v - 1]:
sa[buf[s[v - 1]]] = v - 1
buf[s[v - 1]] += 1
buf = sum_l.copy()
for i in range(n)[::-1]:
v = sa[i]
if v >= 1 and ls[v - 1]:
buf[s[v - 1] + 1] -= 1
sa[buf[s[v - 1] + 1]] = v - 1
if m:
sorted_lms = []
for v in sa:
if lms_map[v] != -1:
sorted_lms.append(v)
rec_s = [0] * m
rec_upper = 0
rec_s[lms_map[sorted_lms[0]]] = 0
for i in range(1, m):
l = sorted_lms[i - 1]
r = sorted_lms[i]
end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n
end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n
same = True
if end_l - l != end_r - r:
same = False
else:
while l < end_l:
if s[l] != s[r]:
break
l += 1
r += 1
if l == n or s[l] != s[r]:
same = False
if not same:
rec_upper += 1
rec_s[lms_map[sorted_lms[i]]] = rec_upper
rec_sa = StrAlg.sa_is(rec_s, rec_upper)
for i in range(m):
sorted_lms[i] = lms[rec_sa[i]]
sa = [-1] * n
buf = sum_s.copy()
for d in sorted_lms:
if d == n:
continue
sa[buf[s[d]]] = d
buf[s[d]] += 1
buf = sum_l.copy()
sa[buf[s[n - 1]]] = n - 1
buf[s[n - 1]] += 1
for i in range(n):
v = sa[i]
if v >= 1 and not ls[v - 1]:
sa[buf[s[v - 1]]] = v - 1
buf[s[v - 1]] += 1
buf = sum_l.copy()
for i in range(n)[::-1]:
v = sa[i]
if v >= 1 and ls[v - 1]:
buf[s[v - 1] + 1] -= 1
sa[buf[s[v - 1] + 1]] = v - 1
return sa
@staticmethod
def suffix_array(s, upper=255):
if type(s) is str:
s = [ord(c) for c in s]
return StrAlg.sa_is(s, upper)
@staticmethod
def lcp_array(s, sa):
n = len(s)
#assert n >= 1
s2 = [ord(c) for c in s]
rnk = [0] * n
for i in range(n):
rnk[sa[i]] = i
lcp = [0] * (n - 1)
h = 0
for i in range(n):
if h > 0:
h -= 1
if rnk[i] == 0:
continue
j = sa[rnk[i] - 1]
while j + h < n and i + h < n:
if s[j + h] != s[i + h]:
break
h += 1
lcp[rnk[i] - 1] = h
return lcp
@staticmethod
def z_algorithm(s):
n = len(s)
s2 = [ord(c) for c in s]
if n == 0:
return []
z = [0] * n
j = 0
for i in range(1, n):
z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j])
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
if j + z[j] < i + z[i]:
j = i
z[0] = n
return z
def atcoder_practice2_i():
S = input()
n = len(S)
ans = (n+1)*n // 2
sa = StrAlg.suffix_array(S)
ans -= sum(StrAlg.lcp_array(S, sa))
print(ans)
if __name__ == "__main__":
atcoder_practice2_i()
| No | Do these codes solve the same problem?
Code 1: // Bismillahir Rahmanir Rahim
//ALGO:
#include<bits/stdc++.h>
#define pb push_back
#define F first
#define S second
#define all(v) v.begin(), v.end()
#define FILL(a, x) memset(a, x, sizeof(a))
#define ll long long
#define Fast ios_base::sync_with_stdio(false);cin.tie(NULL);
#define INF INT_MAX
#define MX 1000010
#define mod 998244353
#define dout if(debug) cout
#define FR(i, n) for(int i=0; i<n; i++)
#define FOR(i, n) for(int i=1; i<=n; i++)
const double Pi=acos(-1);
using namespace std;
int debug=01;
void solve(){
ll n, k;
cin>>n>>k;
ll x[k], y[k], cnt[n+1]={0};
for(ll i=0; i<k; i++)cin>>x[i]>>y[i];
cnt[1]=1;
ll sum=0;
for(ll i=2; i<=n; i++){
for(ll j=0; j<k; j++){
if(i-x[j]>0)sum=(sum+cnt[i-x[j]])%mod;
if(i-y[j]-1>0)sum=(sum-cnt[i-y[j]-1]+mod)%mod;
}
cnt[i]=sum;
}
cout<<cnt[n];
}
int main() {
Fast
int tst=1;
//cin>>tst;
for(int T=1; T<=tst; T++){
//cout<<"Case "<<T<<": ";
solve();
}
}
Code 2:
class StrAlg:
@staticmethod
def sa_naive(s):
n = len(s)
sa = list(range(n))
sa.sort(key=lambda x: s[x:])
return sa
@staticmethod
def sa_doubling(s):
n = len(s)
sa = list(range(n))
rnk = s
tmp = [0] * n
k = 1
while k < n:
sa.sort(key=lambda x: (rnk[x], rnk[x + k])
if x + k < n else (rnk[x], -1))
tmp[sa[0]] = 0
for i in range(1, n):
tmp[sa[i]] = tmp[sa[i - 1]]
x = (rnk[sa[i - 1]], rnk[sa[i - 1] + k]) if sa[i - 1] + \
k < n else (rnk[sa[i - 1]], -1)
y = (rnk[sa[i]], rnk[sa[i] + k]) if sa[i] + \
k < n else (rnk[sa[i]], -1)
if x < y:
tmp[sa[i]] += 1
k *= 2
tmp, rnk = rnk, tmp
return sa
@staticmethod
def sa_is(s, upper):
n = len(s)
if n == 0:
return []
if n == 1:
return [0]
if n == 2:
if s[0] < s[1]:
return [0, 1]
else:
return [1, 0]
if n < 10:
return StrAlg.sa_naive(s)
if n < 50:
return StrAlg.sa_doubling(s)
ls = [0] * n
for i in range(n - 1)[::-1]:
ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1]
sum_l = [0] * (upper + 1)
sum_s = [0] * (upper + 1)
for i in range(n):
if ls[i]:
sum_l[s[i] + 1] += 1
else:
sum_s[s[i]] += 1
for i in range(upper):
sum_s[i] += sum_l[i]
if i < upper:
sum_l[i + 1] += sum_s[i]
lms_map = [-1] * (n + 1)
m = 0
for i in range(1, n):
if not ls[i - 1] and ls[i]:
lms_map[i] = m
m += 1
lms = []
for i in range(1, n):
if not ls[i - 1] and ls[i]:
lms.append(i)
sa = [-1] * n
buf = sum_s.copy()
for d in lms:
if d == n:
continue
sa[buf[s[d]]] = d
buf[s[d]] += 1
buf = sum_l.copy()
sa[buf[s[n - 1]]] = n - 1
buf[s[n - 1]] += 1
for i in range(n):
v = sa[i]
if v >= 1 and not ls[v - 1]:
sa[buf[s[v - 1]]] = v - 1
buf[s[v - 1]] += 1
buf = sum_l.copy()
for i in range(n)[::-1]:
v = sa[i]
if v >= 1 and ls[v - 1]:
buf[s[v - 1] + 1] -= 1
sa[buf[s[v - 1] + 1]] = v - 1
if m:
sorted_lms = []
for v in sa:
if lms_map[v] != -1:
sorted_lms.append(v)
rec_s = [0] * m
rec_upper = 0
rec_s[lms_map[sorted_lms[0]]] = 0
for i in range(1, m):
l = sorted_lms[i - 1]
r = sorted_lms[i]
end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n
end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n
same = True
if end_l - l != end_r - r:
same = False
else:
while l < end_l:
if s[l] != s[r]:
break
l += 1
r += 1
if l == n or s[l] != s[r]:
same = False
if not same:
rec_upper += 1
rec_s[lms_map[sorted_lms[i]]] = rec_upper
rec_sa = StrAlg.sa_is(rec_s, rec_upper)
for i in range(m):
sorted_lms[i] = lms[rec_sa[i]]
sa = [-1] * n
buf = sum_s.copy()
for d in sorted_lms:
if d == n:
continue
sa[buf[s[d]]] = d
buf[s[d]] += 1
buf = sum_l.copy()
sa[buf[s[n - 1]]] = n - 1
buf[s[n - 1]] += 1
for i in range(n):
v = sa[i]
if v >= 1 and not ls[v - 1]:
sa[buf[s[v - 1]]] = v - 1
buf[s[v - 1]] += 1
buf = sum_l.copy()
for i in range(n)[::-1]:
v = sa[i]
if v >= 1 and ls[v - 1]:
buf[s[v - 1] + 1] -= 1
sa[buf[s[v - 1] + 1]] = v - 1
return sa
@staticmethod
def suffix_array(s, upper=255):
if type(s) is str:
s = [ord(c) for c in s]
return StrAlg.sa_is(s, upper)
@staticmethod
def lcp_array(s, sa):
n = len(s)
#assert n >= 1
s2 = [ord(c) for c in s]
rnk = [0] * n
for i in range(n):
rnk[sa[i]] = i
lcp = [0] * (n - 1)
h = 0
for i in range(n):
if h > 0:
h -= 1
if rnk[i] == 0:
continue
j = sa[rnk[i] - 1]
while j + h < n and i + h < n:
if s[j + h] != s[i + h]:
break
h += 1
lcp[rnk[i] - 1] = h
return lcp
@staticmethod
def z_algorithm(s):
n = len(s)
s2 = [ord(c) for c in s]
if n == 0:
return []
z = [0] * n
j = 0
for i in range(1, n):
z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j])
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
if j + z[j] < i + z[i]:
j = i
z[0] = n
return z
def atcoder_practice2_i():
S = input()
n = len(S)
ans = (n+1)*n // 2
sa = StrAlg.suffix_array(S)
ans -= sum(StrAlg.lcp_array(S, sa))
print(ans)
if __name__ == "__main__":
atcoder_practice2_i()
|
C++ | #include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
#include <tuple>
#include <set>
#include <assert.h>
#include <sstream>
#include <string>
//#include <bits/stdc++.h>
#define maxs(x,y) x = max(x,y)
#define mins(x,y) x = min(x,y)
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define repr(i, n) for (int i = (n) - 1; i >= 0; i--)
#define FOR(i,i0,n) for(int (i)=(i0);(i)<(n);(i)++)
#define FORR(i,i0,n) for(int (i)=(n)-1; (i)>=(i0);(i)--)
#define SORT(x) sort(x.begin(),x.end())
#define SORTR(x) sort(x.begin(),x.end(),greater <>())
#define rn return
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
using namespace std;
using ll = long long;
typedef std::pair<ll,ll> P;
//#include <boost/multiprecision/cpp_int.hpp>
//using bint = boost::multiprecision::cpp_int;
const int mod = 1000000007;
int main(){
int n,m;
cin >> n >> m;
vector<int> ans(n,0);
if (n == 1 && m == 0){
cout << 0;
rn 0;
}
rep(i,m){
int s,c;
cin >> s >> c;
s--;
if (m == 1 && n == 1 && c == 0){
cout << 0;
rn 0;
}
if (s == 0 && c == 0){
cout << -1;
rn 0;
}
if (ans[s] != c && ans[s] != 0){
cout << -1;
rn 0;
}
ans[s] = c;
}
if (ans[0] == 0) ans[0] =1;
rep(i,n) cout << ans[i];
}
| C | #include <stdio.h>
#include <math.h>
int main(void){
double q;
while(scanf("%lf", &q)!=EOF) {
if(q==-1)
break;
double x, a;
x=q/2;
while(1){
if(fabs(x*x*x-q)<0.00001*q)
break;
x=x-((x*x*x-q)/(3*x*x));
x = x;
}
printf("%.6f\n",x);
}
return 0;
}
| No | Do these codes solve the same problem?
Code 1: #include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
#include <tuple>
#include <set>
#include <assert.h>
#include <sstream>
#include <string>
//#include <bits/stdc++.h>
#define maxs(x,y) x = max(x,y)
#define mins(x,y) x = min(x,y)
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define repr(i, n) for (int i = (n) - 1; i >= 0; i--)
#define FOR(i,i0,n) for(int (i)=(i0);(i)<(n);(i)++)
#define FORR(i,i0,n) for(int (i)=(n)-1; (i)>=(i0);(i)--)
#define SORT(x) sort(x.begin(),x.end())
#define SORTR(x) sort(x.begin(),x.end(),greater <>())
#define rn return
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
using namespace std;
using ll = long long;
typedef std::pair<ll,ll> P;
//#include <boost/multiprecision/cpp_int.hpp>
//using bint = boost::multiprecision::cpp_int;
const int mod = 1000000007;
int main(){
int n,m;
cin >> n >> m;
vector<int> ans(n,0);
if (n == 1 && m == 0){
cout << 0;
rn 0;
}
rep(i,m){
int s,c;
cin >> s >> c;
s--;
if (m == 1 && n == 1 && c == 0){
cout << 0;
rn 0;
}
if (s == 0 && c == 0){
cout << -1;
rn 0;
}
if (ans[s] != c && ans[s] != 0){
cout << -1;
rn 0;
}
ans[s] = c;
}
if (ans[0] == 0) ans[0] =1;
rep(i,n) cout << ans[i];
}
Code 2: #include <stdio.h>
#include <math.h>
int main(void){
double q;
while(scanf("%lf", &q)!=EOF) {
if(q==-1)
break;
double x, a;
x=q/2;
while(1){
if(fabs(x*x*x-q)<0.00001*q)
break;
x=x-((x*x*x-q)/(3*x*x));
x = x;
}
printf("%.6f\n",x);
}
return 0;
}
|
C++ | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define forn(a, e) for (i64 a = 0; a < (i64)(e); a++)
#define forr(a, s, e) for (i64 a = s; a < (i64)(e); a++)
#define fore(e, a) for (auto& e : a)
#ifdef LOCAL
#define logv(a) {cerr << #a << " = "; fore(e, a) {cerr << e << " ";} cerr << "\n";}
#define logvp(a) {cerr << #a << " = "; fore(e, a) {cerr << "(" << e.first << ", " << e.second << ") ";} cerr << "\n";}
#define logvv(a) {cerr << #a << " = \n"; fore(r, a) { fore(e, r) {cerr << e << " ";} cerr << "\n";} }
#define logvf(a, field) {cerr << #a"."#field << " = \n"; fore(e, a) { cerr << e.field << " ";} cerr << "\n"; }
#define logvff(a, f1, f2) {cerr << #a".{"#f1 << ", "#f2 << "} = \n"; fore(e, a) { cerr << "(" << e.f1 <<", " << e.f2 << ") ";} cerr << "\n"; }
#define logs(a) cerr << #a << " = " << (a) << "\n";
#define logss(a, b) cerr << #a << " = " << (a) << ", " << #b << " = " << (b) << "\n";
#define logp(a) cerr << #a << " = " << "(" << a.first << ", " << a.second << ")" << "\n";
#define cond(pred, stmt) if (pred) { stmt }
#else
#define logv(a)
#define logvp(a)
#define logvv(a)
#define logvf(a, field)
#define logvff(a, f1, f2)
#define logs(a)
#define logss(a, b)
#define logp(a)
#define cond(pred, stmt)
#endif
using iip = pair<int, int>;
using llp = pair<i64, i64>;
using ivec = vector<int>;
using llvec = vector<i64>;
using svec = vector<string>;
template<typename T> using vec = vector<T>;
template<typename T, typename Dim>
auto make_vec(T value, Dim dim) { return vector<T>(dim, value); }
template<typename T, typename Dim1, typename... Dim>
auto make_vec(T value, Dim1 dim1, Dim... dims) { return make_vec(make_vec(value, dims...), dim1); }
template<typename T>
bool uax(T& v, const T& newv) { if (v < newv) { v = newv; return true; } else return false; }
template<typename T>
bool uin(T& v, const T& newv) { if (v > newv) { v = newv; return true; } else return false; }
template<typename T>
istream& operator>>(istream& is, vector<T>& c) { for (auto& e : c) is >> e; return is; }
template<typename T, size_t N>
istream& operator>>(istream& is, array<T, N>& c) { for (auto& e : c) is >> e; return is; }
template<typename ...T>
istream& read(T&... args) { return (cin >> ... >> args); }
static mt19937 rande(123123);
template<typename T>
T rand_int(T from, T to) { uniform_int_distribution<T> distr(from, to); return distr(rande); }
const i64 INF = 1e18;
const i64 M = 1e9 + 7;
i64 bpow(i64 a, i64 p) {
if (p == 1) {
return a;
}
if (p == 0) {
return 1;
}
i64 res = bpow(a, p / 2);
res *= res;
res %= M;
if (p % 2) {
res *= a;
res %= M;
}
return res;
}
i64 inv(i64 a) {
return bpow(a, M - 2);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
rande.seed(chrono::steady_clock::now().time_since_epoch().count());
int n;
while (read(n)) {
ivec a(n);
read(a);
ivec sa = a;
sort(sa.begin(), sa.end());
int ans = 0;
forn(i, n) {
int pos = lower_bound(sa.begin(), sa.end(), a[i]) - sa.begin();
if (pos % 2 != i % 2) {
ans++;
}
// if (a[i] % 2)
// if (a[i] % 2 == 0) {
// a1.push_back(a[i]);
// } else {
// a2.push_back(a[i]);
// }
}
assert(ans % 2 == 0);
cout << ans / 2 << endl;
// sort(a1.begin(), a1.end());
// sort(a2.begin(), a2.end());
}
} | C# | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var S = Console.ReadLine();
var T = Console.ReadLine();
var sMap = new Dictionary<char, char>();
var tMap = new Dictionary<char, char>();
for (int i = 0; i < S.Length; i++)
{
var s = S[i];
var t = T[i];
if (sMap.ContainsKey(s))
{
if (sMap[s] != t)
{
Console.WriteLine("No");
return;
}
}
else
{
sMap.Add(s, t);
}
if (tMap.ContainsKey(t))
{
if (tMap[t] != s)
{
Console.WriteLine("No");
return;
}
}
else
{
tMap.Add(t, s);
}
}
Console.WriteLine("Yes");
}
}
| No | Do these codes solve the same problem?
Code 1: #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define forn(a, e) for (i64 a = 0; a < (i64)(e); a++)
#define forr(a, s, e) for (i64 a = s; a < (i64)(e); a++)
#define fore(e, a) for (auto& e : a)
#ifdef LOCAL
#define logv(a) {cerr << #a << " = "; fore(e, a) {cerr << e << " ";} cerr << "\n";}
#define logvp(a) {cerr << #a << " = "; fore(e, a) {cerr << "(" << e.first << ", " << e.second << ") ";} cerr << "\n";}
#define logvv(a) {cerr << #a << " = \n"; fore(r, a) { fore(e, r) {cerr << e << " ";} cerr << "\n";} }
#define logvf(a, field) {cerr << #a"."#field << " = \n"; fore(e, a) { cerr << e.field << " ";} cerr << "\n"; }
#define logvff(a, f1, f2) {cerr << #a".{"#f1 << ", "#f2 << "} = \n"; fore(e, a) { cerr << "(" << e.f1 <<", " << e.f2 << ") ";} cerr << "\n"; }
#define logs(a) cerr << #a << " = " << (a) << "\n";
#define logss(a, b) cerr << #a << " = " << (a) << ", " << #b << " = " << (b) << "\n";
#define logp(a) cerr << #a << " = " << "(" << a.first << ", " << a.second << ")" << "\n";
#define cond(pred, stmt) if (pred) { stmt }
#else
#define logv(a)
#define logvp(a)
#define logvv(a)
#define logvf(a, field)
#define logvff(a, f1, f2)
#define logs(a)
#define logss(a, b)
#define logp(a)
#define cond(pred, stmt)
#endif
using iip = pair<int, int>;
using llp = pair<i64, i64>;
using ivec = vector<int>;
using llvec = vector<i64>;
using svec = vector<string>;
template<typename T> using vec = vector<T>;
template<typename T, typename Dim>
auto make_vec(T value, Dim dim) { return vector<T>(dim, value); }
template<typename T, typename Dim1, typename... Dim>
auto make_vec(T value, Dim1 dim1, Dim... dims) { return make_vec(make_vec(value, dims...), dim1); }
template<typename T>
bool uax(T& v, const T& newv) { if (v < newv) { v = newv; return true; } else return false; }
template<typename T>
bool uin(T& v, const T& newv) { if (v > newv) { v = newv; return true; } else return false; }
template<typename T>
istream& operator>>(istream& is, vector<T>& c) { for (auto& e : c) is >> e; return is; }
template<typename T, size_t N>
istream& operator>>(istream& is, array<T, N>& c) { for (auto& e : c) is >> e; return is; }
template<typename ...T>
istream& read(T&... args) { return (cin >> ... >> args); }
static mt19937 rande(123123);
template<typename T>
T rand_int(T from, T to) { uniform_int_distribution<T> distr(from, to); return distr(rande); }
const i64 INF = 1e18;
const i64 M = 1e9 + 7;
i64 bpow(i64 a, i64 p) {
if (p == 1) {
return a;
}
if (p == 0) {
return 1;
}
i64 res = bpow(a, p / 2);
res *= res;
res %= M;
if (p % 2) {
res *= a;
res %= M;
}
return res;
}
i64 inv(i64 a) {
return bpow(a, M - 2);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
rande.seed(chrono::steady_clock::now().time_since_epoch().count());
int n;
while (read(n)) {
ivec a(n);
read(a);
ivec sa = a;
sort(sa.begin(), sa.end());
int ans = 0;
forn(i, n) {
int pos = lower_bound(sa.begin(), sa.end(), a[i]) - sa.begin();
if (pos % 2 != i % 2) {
ans++;
}
// if (a[i] % 2)
// if (a[i] % 2 == 0) {
// a1.push_back(a[i]);
// } else {
// a2.push_back(a[i]);
// }
}
assert(ans % 2 == 0);
cout << ans / 2 << endl;
// sort(a1.begin(), a1.end());
// sort(a2.begin(), a2.end());
}
}
Code 2: using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var S = Console.ReadLine();
var T = Console.ReadLine();
var sMap = new Dictionary<char, char>();
var tMap = new Dictionary<char, char>();
for (int i = 0; i < S.Length; i++)
{
var s = S[i];
var t = T[i];
if (sMap.ContainsKey(s))
{
if (sMap[s] != t)
{
Console.WriteLine("No");
return;
}
}
else
{
sMap.Add(s, t);
}
if (tMap.ContainsKey(t))
{
if (tMap[t] != s)
{
Console.WriteLine("No");
return;
}
}
else
{
tMap.Add(t, s);
}
}
Console.WriteLine("Yes");
}
}
|
Python | N = int(input())
if N==1:
print('Hello World')
else:
A,B = [int(input()) for _ in range(2)]
print(A+B) | C | #include <stdio.h>
int main(){
int a,b,c,d;
int m;
scanf("%d %d %d %d",&a,&b,&c,&d);
int x[a];
int y[b];
//scanf("%d",&m);
for(int i=0;i<a;i++){
scanf("%d",&x[i]);
}
//scanf("%d",&m);
for(int i=0;i<b;i++){
scanf("%d",&y[i]);
}
int p=x[0];
for(int i=0;i<a-1;i++){
if(p<x[i+1]){
p=x[i+1];
}
}
//printf("%d",p);
int q=y[0];
for(int i=0;i<b-1;i++){
if(q>y[i+1]){
q=y[i+1];
}
}
//printf("%d",q);
if(p<q&&p<d&&q>c){
printf("No War");
}else{
printf("War");
}
return 0;
} | No | Do these codes solve the same problem?
Code 1: N = int(input())
if N==1:
print('Hello World')
else:
A,B = [int(input()) for _ in range(2)]
print(A+B)
Code 2: #include <stdio.h>
int main(){
int a,b,c,d;
int m;
scanf("%d %d %d %d",&a,&b,&c,&d);
int x[a];
int y[b];
//scanf("%d",&m);
for(int i=0;i<a;i++){
scanf("%d",&x[i]);
}
//scanf("%d",&m);
for(int i=0;i<b;i++){
scanf("%d",&y[i]);
}
int p=x[0];
for(int i=0;i<a-1;i++){
if(p<x[i+1]){
p=x[i+1];
}
}
//printf("%d",p);
int q=y[0];
for(int i=0;i<b-1;i++){
if(q>y[i+1]){
q=y[i+1];
}
}
//printf("%d",q);
if(p<q&&p<d&&q>c){
printf("No War");
}else{
printf("War");
}
return 0;
} |
Python | x = int(input())
l=[]
for i in range(x):
l.append(int(input()))
MIN = 999999999999999999999999999999999999999
MAX = -9999999999999999999999999999999999999
for i in l:
if i - MIN > MAX:
MAX = i - MIN
if i < MIN:
MIN = i
print(MAX) | C++ | #include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> A(N), B(N), C(N);
for (int i = 0; i < N; i++) cin >> A.at(i);
for (int i = 0; i < N; i++) cin >> B.at(i);
int fact = 1;
for (int i = 0; i < N; i++) { //階乗の計算
fact *= (i+1);
C.at(i) = fact;
}
int a=0, b=0, count_a=0, count_b=0;
/*exa. 42531 4xxxxの時、12345~35421より大きいので、(5-1)!*(4-0-1)番目より大きい
42xxxの時、41235~41532より大きいので、(4-1)!*(3-0-1)を足す
425xxの時、42135~42351より大きいので、(3-1)!*(5-2-1)を足す
式の階乗の部分は位に依存、
後ろの部分は(その位の数)-(左の位にあるその位の数より大きい個数)-1*/
for (int i = 0; i < N-1; i++) {
int D=0, E=0;
for (int j = 0; j < i; j++) {
if(A.at(j)<A.at(i)) D++;
if(B.at(j)<B.at(i)) E++;
}
a += C.at(N-i-2)*(A.at(i)-D-1);
b += C.at(N-i-2)*(B.at(i)-E-1);
}
if(a>=b) cout << a-b << endl;
else cout << b-a << endl;
} | No | Do these codes solve the same problem?
Code 1: x = int(input())
l=[]
for i in range(x):
l.append(int(input()))
MIN = 999999999999999999999999999999999999999
MAX = -9999999999999999999999999999999999999
for i in l:
if i - MIN > MAX:
MAX = i - MIN
if i < MIN:
MIN = i
print(MAX)
Code 2: #include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> A(N), B(N), C(N);
for (int i = 0; i < N; i++) cin >> A.at(i);
for (int i = 0; i < N; i++) cin >> B.at(i);
int fact = 1;
for (int i = 0; i < N; i++) { //階乗の計算
fact *= (i+1);
C.at(i) = fact;
}
int a=0, b=0, count_a=0, count_b=0;
/*exa. 42531 4xxxxの時、12345~35421より大きいので、(5-1)!*(4-0-1)番目より大きい
42xxxの時、41235~41532より大きいので、(4-1)!*(3-0-1)を足す
425xxの時、42135~42351より大きいので、(3-1)!*(5-2-1)を足す
式の階乗の部分は位に依存、
後ろの部分は(その位の数)-(左の位にあるその位の数より大きい個数)-1*/
for (int i = 0; i < N-1; i++) {
int D=0, E=0;
for (int j = 0; j < i; j++) {
if(A.at(j)<A.at(i)) D++;
if(B.at(j)<B.at(i)) E++;
}
a += C.at(N-i-2)*(A.at(i)-D-1);
b += C.at(N-i-2)*(B.at(i)-E-1);
}
if(a>=b) cout << a-b << endl;
else cout << b-a << endl;
} |
Python | N, K = map(int, input().split())
ans = K * (K-1)**(N-1)
print(ans) | C++ | #include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef pair<int,int>PII;
const int maxn = 2e5 + 10;
int t,n,m;
vector<int>G[maxn];
int value[maxn];
int main(void) {
int n,m;
cin >> n >> m;
int u,v,a;
for(int i = 1; i <= n; i ++) {
scanf("%d",&a);
value[i] = a;
}
for(int i = 1; i <= m; i ++) {
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
int ans = 0;
for(int i = 1; i <= n; i ++) {
bool flag = true;
for(int j = 0; j < G[i].size(); j ++) {
if(value[i] <= value[G[i][j]]) {
flag = false;
break;
}
}
if(flag || G[i].size() == 0) ans ++;
}
cout << ans << endl;
return 0;
} | No | Do these codes solve the same problem?
Code 1: N, K = map(int, input().split())
ans = K * (K-1)**(N-1)
print(ans)
Code 2: #include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef pair<int,int>PII;
const int maxn = 2e5 + 10;
int t,n,m;
vector<int>G[maxn];
int value[maxn];
int main(void) {
int n,m;
cin >> n >> m;
int u,v,a;
for(int i = 1; i <= n; i ++) {
scanf("%d",&a);
value[i] = a;
}
for(int i = 1; i <= m; i ++) {
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
int ans = 0;
for(int i = 1; i <= n; i ++) {
bool flag = true;
for(int j = 0; j < G[i].size(); j ++) {
if(value[i] <= value[G[i][j]]) {
flag = false;
break;
}
}
if(flag || G[i].size() == 0) ans ++;
}
cout << ans << endl;
return 0;
} |
Java | import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Scanner;
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 class Main {
static FastScanner scan=new FastScanner();
static Scanner scanner=new Scanner(System.in);
static long mod=1000000007;
static double eps=0.0000000001;
static int big=Integer.MAX_VALUE;
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 factorial(int i) {return i==1?1:i*factorial(i-1);}
static int lower_bound(int a[],int key) {
int low=0,high=a.length;
while(low<high) {
int mid=((high-low)/2)+low;
if(a[mid]<=key)low=mid+1;
else high=mid;
}
return high;
}
static int upper_bound(int a[],int key) {
int low=0,high=a.length;
while(low<high) {
int mid=((high-low)/2)+low;
if(a[mid]<key)low=mid+1;
else high=mid;
}
return high;
}
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 long lmax(long a,long b) {return Math.max(a, b);}
static long lmin(long a,long b) {return Math.min(a, b);}
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(char[] ch) {
for(int i=0;i<ch.length-1;i++) {
System.out.print(ch[i]+" ");
}
System.out.println(ch[ch.length-1]);
}
public static int[][] doublesort(int[][]a) {
Arrays.sort(a,(x,y)->Integer.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 void main(String[] args) {
int a=scan.nextInt();
while(true) {
if(isPrime(a)) {
System.out.println(a);
return;
}
a++;
}
}
} | TypeScript | const isPrime = n => {
if (n < 2) return false;
if (n === 2 || n === 3 || n === 5) return true;
if (n % 2 === 0 || n % 3 === 0 || n % 5 === 0) return false;
let prime = 7;
let step = 4;
const limit = Math.sqrt(n);
while (prime <= limit) {
if (n % prime === 0) return false;
prime += step;
step = 6 - step;
}
return true;
};
const main = (input) => {
const x = Number(input.trim())
let result = x
if (result === 2) {
console.log(result)
return
}
if (result%2 === 0) result++
while(true) {
if (isPrime(result)) break;
result += 2
}
console.log(result)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))
| 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.Scanner;
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 class Main {
static FastScanner scan=new FastScanner();
static Scanner scanner=new Scanner(System.in);
static long mod=1000000007;
static double eps=0.0000000001;
static int big=Integer.MAX_VALUE;
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 factorial(int i) {return i==1?1:i*factorial(i-1);}
static int lower_bound(int a[],int key) {
int low=0,high=a.length;
while(low<high) {
int mid=((high-low)/2)+low;
if(a[mid]<=key)low=mid+1;
else high=mid;
}
return high;
}
static int upper_bound(int a[],int key) {
int low=0,high=a.length;
while(low<high) {
int mid=((high-low)/2)+low;
if(a[mid]<key)low=mid+1;
else high=mid;
}
return high;
}
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 long lmax(long a,long b) {return Math.max(a, b);}
static long lmin(long a,long b) {return Math.min(a, b);}
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(char[] ch) {
for(int i=0;i<ch.length-1;i++) {
System.out.print(ch[i]+" ");
}
System.out.println(ch[ch.length-1]);
}
public static int[][] doublesort(int[][]a) {
Arrays.sort(a,(x,y)->Integer.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 void main(String[] args) {
int a=scan.nextInt();
while(true) {
if(isPrime(a)) {
System.out.println(a);
return;
}
a++;
}
}
}
Code 2: const isPrime = n => {
if (n < 2) return false;
if (n === 2 || n === 3 || n === 5) return true;
if (n % 2 === 0 || n % 3 === 0 || n % 5 === 0) return false;
let prime = 7;
let step = 4;
const limit = Math.sqrt(n);
while (prime <= limit) {
if (n % prime === 0) return false;
prime += step;
step = 6 - step;
}
return true;
};
const main = (input) => {
const x = Number(input.trim())
let result = x
if (result === 2) {
console.log(result)
return
}
if (result%2 === 0) result++
while(true) {
if (isPrime(result)) break;
result += 2
}
console.log(result)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))
|
C | #include <stdio.h>
#include <stdlib.h>
#define max(p,q)((p)>(q)?(p):(q))
#define min(p,q)((p)<(q)?(p):(q))
typedef struct Point{long long x,y;}P;
void readpoint(P*p){scanf("%lld%lld",&p->x,&p->y);}
long long crossproduct(P p,P q,P o){return (p.x-o.x)*(q.y-o.y)-(p.y-o.y)*(q.x-o.x);}
long long area(P*p,int n){
//凸包の点が順に与えられる(向き不問)
long long s=0;
for(int i=2;i<n;i++)s+=crossproduct(p[i-1],p[i],p[0]);
return llabs(s/2);
}
P p[110];
P x[5];
int main(){
int n;
while(scanf("%d",&n),n){
for(int i=0;i<n;i++)readpoint(p+i);
for(int i=0;i<4;i++)readpoint(x+i);
long long l=min(x[0].x,x[2].x);
long long r=max(x[0].x,x[2].x);
long long d=min(x[0].y,x[2].y);
long long u=max(x[0].y,x[2].y);
long long mado=area(p,n);
for(int i=0;i<n;i++){
p[i].x=max(l,min(r,p[i].x));
p[i].y=max(d,min(u,p[i].y));
}
printf("%lld\n",mado-area(p,n));
}
}
| C++ | #include <bits/stdc++.h>
using namespace std;
int compress(vector<int>& xs, vector<int>& x) {
const int N = x.size();
sort(xs.begin(), xs.end());
xs.erase(unique(xs.begin(), xs.end()), xs.end());
for(int i=0; i<N; ++i) {
x[i] = lower_bound(xs.begin(), xs.end(), x[i]) - xs.begin();
}
return xs.size();
}
int main() {
int N;
while(cin >> N, N) {
vector<int> x(N), y(N);
vector<int> xs, ys;
vector<int> a(4), b(4);
for(int i=0; i<N; ++i) {
cin >> x[i] >> y[i];
xs.push_back(x[i]);
ys.push_back(y[i]);
}
for(int i=0; i<4; ++i) {
cin >> a[i] >> b[i];
xs.push_back(a[i]);
ys.push_back(b[i]);
}
int W = compress(xs, x);
int H = compress(ys, y);
int cx1 = 10000, cx2 = 0, cy1 = 10000, cy2 = 0;
for(int i=0; i<4; ++i) {
a[i] = lower_bound(xs.begin(), xs.end(), a[i]) - xs.begin();
b[i] = lower_bound(ys.begin(), ys.end(), b[i]) - ys.begin();
cx1 = min(cx1, a[i]);
cx2 = max(cx2, a[i]);
cy1 = min(cy1, b[i]);
cy2 = max(cy2, b[i]);
}
vector<vector<int>> flag(H, vector<int>(W));
for(int i=0; i<N; ++i) {
int i2 = (i+1)%N;
if(x[i] != x[i2]) {
continue;
}
int miny = min(y[i], y[i2]), maxy = max(y[i], y[i2]);
for(int j=miny; j<maxy; ++j) {
flag[j][x[i]] = 1;
}
}
for(int i=cy1; i<cy2; ++i) {
flag[i][cx1] |= 2;
flag[i][cx2] |= 2;
}
for(int i=0; i<H; ++i) {
for(int j=0; j+1<W; ++j) {
flag[i][j+1] ^= flag[i][j];
}
}
int res = 0;
for(int i=0; i+1<H; ++i) {
for(int j=0; j+1<W; ++j) {
if(flag[i][j] == 1) {
res += (ys[i+1] - ys[i]) * (xs[j+1] - xs[j]);
}
}
}
cout << res << endl;
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <stdio.h>
#include <stdlib.h>
#define max(p,q)((p)>(q)?(p):(q))
#define min(p,q)((p)<(q)?(p):(q))
typedef struct Point{long long x,y;}P;
void readpoint(P*p){scanf("%lld%lld",&p->x,&p->y);}
long long crossproduct(P p,P q,P o){return (p.x-o.x)*(q.y-o.y)-(p.y-o.y)*(q.x-o.x);}
long long area(P*p,int n){
//凸包の点が順に与えられる(向き不問)
long long s=0;
for(int i=2;i<n;i++)s+=crossproduct(p[i-1],p[i],p[0]);
return llabs(s/2);
}
P p[110];
P x[5];
int main(){
int n;
while(scanf("%d",&n),n){
for(int i=0;i<n;i++)readpoint(p+i);
for(int i=0;i<4;i++)readpoint(x+i);
long long l=min(x[0].x,x[2].x);
long long r=max(x[0].x,x[2].x);
long long d=min(x[0].y,x[2].y);
long long u=max(x[0].y,x[2].y);
long long mado=area(p,n);
for(int i=0;i<n;i++){
p[i].x=max(l,min(r,p[i].x));
p[i].y=max(d,min(u,p[i].y));
}
printf("%lld\n",mado-area(p,n));
}
}
Code 2: #include <bits/stdc++.h>
using namespace std;
int compress(vector<int>& xs, vector<int>& x) {
const int N = x.size();
sort(xs.begin(), xs.end());
xs.erase(unique(xs.begin(), xs.end()), xs.end());
for(int i=0; i<N; ++i) {
x[i] = lower_bound(xs.begin(), xs.end(), x[i]) - xs.begin();
}
return xs.size();
}
int main() {
int N;
while(cin >> N, N) {
vector<int> x(N), y(N);
vector<int> xs, ys;
vector<int> a(4), b(4);
for(int i=0; i<N; ++i) {
cin >> x[i] >> y[i];
xs.push_back(x[i]);
ys.push_back(y[i]);
}
for(int i=0; i<4; ++i) {
cin >> a[i] >> b[i];
xs.push_back(a[i]);
ys.push_back(b[i]);
}
int W = compress(xs, x);
int H = compress(ys, y);
int cx1 = 10000, cx2 = 0, cy1 = 10000, cy2 = 0;
for(int i=0; i<4; ++i) {
a[i] = lower_bound(xs.begin(), xs.end(), a[i]) - xs.begin();
b[i] = lower_bound(ys.begin(), ys.end(), b[i]) - ys.begin();
cx1 = min(cx1, a[i]);
cx2 = max(cx2, a[i]);
cy1 = min(cy1, b[i]);
cy2 = max(cy2, b[i]);
}
vector<vector<int>> flag(H, vector<int>(W));
for(int i=0; i<N; ++i) {
int i2 = (i+1)%N;
if(x[i] != x[i2]) {
continue;
}
int miny = min(y[i], y[i2]), maxy = max(y[i], y[i2]);
for(int j=miny; j<maxy; ++j) {
flag[j][x[i]] = 1;
}
}
for(int i=cy1; i<cy2; ++i) {
flag[i][cx1] |= 2;
flag[i][cx2] |= 2;
}
for(int i=0; i<H; ++i) {
for(int j=0; j+1<W; ++j) {
flag[i][j+1] ^= flag[i][j];
}
}
int res = 0;
for(int i=0; i+1<H; ++i) {
for(int j=0; j+1<W; ++j) {
if(flag[i][j] == 1) {
res += (ys[i+1] - ys[i]) * (xs[j+1] - xs[j]);
}
}
}
cout << res << endl;
}
}
|
C | #include<stdio.h>
char p[9][4];
int map[9];
int use[9];
int dic[9];
int ans;
int check(char a, char b){
if(a == 'w' && b == 'W')return 1;
else if(a == 'W' && b == 'w')return 1;
else if(a == 'b' && b == 'B')return 1;
else if(a == 'B' && b == 'b')return 1;
else if(a == 'g' && b == 'G')return 1;
else if(a == 'G' && b == 'g')return 1;
else if(a == 'r' && b == 'R')return 1;
else if(a == 'R' && b == 'r')return 1;
else return 0;
}
char mapdic(int num, int purse){
return p[map[num]][(4+purse-dic[num])%4];
}
void backtrack(int num){
int i,j;
int f1,f2;
if(num == 9)ans++;
else {
for(i=0;i<9;i++){
if(!use[i]){
use[i] = 1;
map[num] = i;
for(j=0;j<4;j++){
dic[num] = j;
f2 = 1;
if(num >= 3){
f1 = check(mapdic(num,0),mapdic(num-3,2));
if(!f1)f2 = 0;
}
if(num % 3 != 0){
f1 = check(mapdic(num,3),mapdic(num-1,1));
if(!f1)f2 = 0;
}
if(f2)backtrack(num+1);
}
use[i] = 0;
}
}
}
}
int main(void){
int i,k,l;
int n;
scanf("%d",&n);
for(k=0;k<n;k++){
for(l=0;l<9;l++){
for(i=0;i<4;i++){
scanf(" %c ",&p[l][i]);
}
}
for(i=0;i<9;i++)use[i] = 0;
ans = 0;
backtrack(0);
printf("%d\n",ans);
}
return 0;
} | Python | p_ch = [True] * 9
rot = ((0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2))
adj = ['c'] * 13
# record indices of right and botoom adjacent edge label. 12 is invalid.
rec_adj = [[0, 2], [1, 3], [12, 4], [5, 7], [6, 8], [12, 9], [10, 12],
[11, 12], [12, 12]]
# refernce indices to top and left adjacent edge label. 12 is invalid.
ref_adj = [[12, 12], [12, 0], [12, 1], [2, 12], [3, 5], [4, 6], [7, 12],
[8, 10], [9, 11]]
tr = dict(zip("RGBWrgbw", "rgbwRGBW"))
def dfs(i = 0, a = []):
if i == 9:
global ans
ans += 1
else:
for j, p in enumerate(pieces):
if p_ch[j]:
ati, ali = ref_adj[i]
for t, r, b, l in rot:
if ati == 12 or tr[p[t]] == adj[ati]:
if ali == 12 or tr[p[l]] == adj[ali]:
ari, abi = rec_adj[i]
adj[ari] = p[r]
adj[abi] = p[b]
p_ch[j] = False
dfs(i + 1)
p_ch[j] = True
from sys import stdin
file_input = stdin
N = int(file_input.readline())
for line in file_input:
pieces = line.split()
ans = 0
dfs()
print(ans)
| Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
char p[9][4];
int map[9];
int use[9];
int dic[9];
int ans;
int check(char a, char b){
if(a == 'w' && b == 'W')return 1;
else if(a == 'W' && b == 'w')return 1;
else if(a == 'b' && b == 'B')return 1;
else if(a == 'B' && b == 'b')return 1;
else if(a == 'g' && b == 'G')return 1;
else if(a == 'G' && b == 'g')return 1;
else if(a == 'r' && b == 'R')return 1;
else if(a == 'R' && b == 'r')return 1;
else return 0;
}
char mapdic(int num, int purse){
return p[map[num]][(4+purse-dic[num])%4];
}
void backtrack(int num){
int i,j;
int f1,f2;
if(num == 9)ans++;
else {
for(i=0;i<9;i++){
if(!use[i]){
use[i] = 1;
map[num] = i;
for(j=0;j<4;j++){
dic[num] = j;
f2 = 1;
if(num >= 3){
f1 = check(mapdic(num,0),mapdic(num-3,2));
if(!f1)f2 = 0;
}
if(num % 3 != 0){
f1 = check(mapdic(num,3),mapdic(num-1,1));
if(!f1)f2 = 0;
}
if(f2)backtrack(num+1);
}
use[i] = 0;
}
}
}
}
int main(void){
int i,k,l;
int n;
scanf("%d",&n);
for(k=0;k<n;k++){
for(l=0;l<9;l++){
for(i=0;i<4;i++){
scanf(" %c ",&p[l][i]);
}
}
for(i=0;i<9;i++)use[i] = 0;
ans = 0;
backtrack(0);
printf("%d\n",ans);
}
return 0;
}
Code 2: p_ch = [True] * 9
rot = ((0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2))
adj = ['c'] * 13
# record indices of right and botoom adjacent edge label. 12 is invalid.
rec_adj = [[0, 2], [1, 3], [12, 4], [5, 7], [6, 8], [12, 9], [10, 12],
[11, 12], [12, 12]]
# refernce indices to top and left adjacent edge label. 12 is invalid.
ref_adj = [[12, 12], [12, 0], [12, 1], [2, 12], [3, 5], [4, 6], [7, 12],
[8, 10], [9, 11]]
tr = dict(zip("RGBWrgbw", "rgbwRGBW"))
def dfs(i = 0, a = []):
if i == 9:
global ans
ans += 1
else:
for j, p in enumerate(pieces):
if p_ch[j]:
ati, ali = ref_adj[i]
for t, r, b, l in rot:
if ati == 12 or tr[p[t]] == adj[ati]:
if ali == 12 or tr[p[l]] == adj[ali]:
ari, abi = rec_adj[i]
adj[ari] = p[r]
adj[abi] = p[b]
p_ch[j] = False
dfs(i + 1)
p_ch[j] = True
from sys import stdin
file_input = stdin
N = int(file_input.readline())
for line in file_input:
pieces = line.split()
ans = 0
dfs()
print(ans)
|
C# | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static bool f = false, t = true;
static void Main(string[] args)
{
int a = Read.Int();
int b = Read.Int();
int c = Read.Int();
int n = Read.Int();
int asn = 0;
for (int i = 0; i <= a; i++)
{
for (int j = 0; j <= b; j++)
{
for (int k = 0; k <= c; k++)
{
if (500 * i + 100 * j + 50 * k == n)
{
asn++;
}
}
}
}
Console.WriteLine(asn);
}
public static long gcd(long a, long b)
{
while (true)
{
if (a == 0) { return b; }
if (b == 0) { return a; }
if (a > b) { a -= b; }
else { b -= a; }
}
}
public static long lcm(long a, long b) { return a / gcd(a, b) * b; }
public static bool IsPrime(int num)
{
if (num < 2) return false;
else if (num == 2) return true;
else if (num % 2 == 0) return false; // 偶数はあらかじめ除く
double sqrtNum = Math.Sqrt(num);
for (int i = 3; i <= sqrtNum; i += 2)
{
if (num % i == 0)
{
// 素数ではない
return false;
}
}
// 素数である
return true;
}
}
public static class Read
{
public static void outl(string n = "") { Console.WriteLine(n); return; }
public static long Long() { return long.Parse(Console.ReadLine()); }
public static long[] longs() { return Console.ReadLine().Split().Select(long.Parse).ToArray(); }
public static int Int() { return int.Parse(Console.ReadLine()); }
public static int[] ints() { return Console.ReadLine().Split().Select(int.Parse).ToArray(); }
public static string Str() { return Console.ReadLine(); }
public static string[] Strs() { return Console.ReadLine().Split(); }
} | Go | package main
import "fmt"
var A, B, C, X int
func main() {
fmt.Scanf("%d", &A)
fmt.Scanf("%d", &B)
fmt.Scanf("%d", &C)
fmt.Scanf("%d", &X)
ans := 0
for i := 0; i <= A; i++ {
if 500*i > X {
break
}
for j := 0; j <= B; j++ {
if 500*i+100*j > X {
break
}
for k := 0; k <= C; k++ {
if 500*i+100*j+50*k == X {
ans++
}
}
}
}
fmt.Println(ans)
}
// Library
func MakeMatrix(w, h int) [][]int {
m := make([][]int, w)
for x := 0; x < w; x++ {
m[x] = make([]int, h)
}
return m
}
func Max(x, y int) int {
if x > y {
return x
}
return y
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static bool f = false, t = true;
static void Main(string[] args)
{
int a = Read.Int();
int b = Read.Int();
int c = Read.Int();
int n = Read.Int();
int asn = 0;
for (int i = 0; i <= a; i++)
{
for (int j = 0; j <= b; j++)
{
for (int k = 0; k <= c; k++)
{
if (500 * i + 100 * j + 50 * k == n)
{
asn++;
}
}
}
}
Console.WriteLine(asn);
}
public static long gcd(long a, long b)
{
while (true)
{
if (a == 0) { return b; }
if (b == 0) { return a; }
if (a > b) { a -= b; }
else { b -= a; }
}
}
public static long lcm(long a, long b) { return a / gcd(a, b) * b; }
public static bool IsPrime(int num)
{
if (num < 2) return false;
else if (num == 2) return true;
else if (num % 2 == 0) return false; // 偶数はあらかじめ除く
double sqrtNum = Math.Sqrt(num);
for (int i = 3; i <= sqrtNum; i += 2)
{
if (num % i == 0)
{
// 素数ではない
return false;
}
}
// 素数である
return true;
}
}
public static class Read
{
public static void outl(string n = "") { Console.WriteLine(n); return; }
public static long Long() { return long.Parse(Console.ReadLine()); }
public static long[] longs() { return Console.ReadLine().Split().Select(long.Parse).ToArray(); }
public static int Int() { return int.Parse(Console.ReadLine()); }
public static int[] ints() { return Console.ReadLine().Split().Select(int.Parse).ToArray(); }
public static string Str() { return Console.ReadLine(); }
public static string[] Strs() { return Console.ReadLine().Split(); }
}
Code 2: package main
import "fmt"
var A, B, C, X int
func main() {
fmt.Scanf("%d", &A)
fmt.Scanf("%d", &B)
fmt.Scanf("%d", &C)
fmt.Scanf("%d", &X)
ans := 0
for i := 0; i <= A; i++ {
if 500*i > X {
break
}
for j := 0; j <= B; j++ {
if 500*i+100*j > X {
break
}
for k := 0; k <= C; k++ {
if 500*i+100*j+50*k == X {
ans++
}
}
}
}
fmt.Println(ans)
}
// Library
func MakeMatrix(w, h int) [][]int {
m := make([][]int, w)
for x := 0; x < w; x++ {
m[x] = make([]int, h)
}
return m
}
func Max(x, y int) int {
if x > y {
return x
}
return y
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i, n) for (int i = 0; i < (n); ++i)
double const PI = 3.1415926535897932384626433;
int main() {
string s;
cin >> s;
rep(i, 3) {
if (s[i] == '1')
cout << 9;
else if (s[i] == '9')
cout << 1;
}
cout << endl;
return 0;
} | Python | print(input()[::-1])
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i, n) for (int i = 0; i < (n); ++i)
double const PI = 3.1415926535897932384626433;
int main() {
string s;
cin >> s;
rep(i, 3) {
if (s[i] == '1')
cout << 9;
else if (s[i] == '9')
cout << 1;
}
cout << endl;
return 0;
}
Code 2: print(input()[::-1])
|
C++ | #include <iostream>
#include <string>
using namespace std;
int main() {
int sum=0;
string s;
while(cin >> s) {
int x=0;
for(int i=0; i<s.size(); i++) {
if(s[i]>='0' && s[i]<='9'){
x*=10;
x+=s[i]-'0';
} else {
sum+=x;
x=0;
}
}
sum+=x;
}
cout << sum << endl;
return 0;
}
| Python | import re,sys
a=0
for l in sys.stdin:
a+=sum(map(int,re.findall(r"\d+",l)))
print(a)
| Yes | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <string>
using namespace std;
int main() {
int sum=0;
string s;
while(cin >> s) {
int x=0;
for(int i=0; i<s.size(); i++) {
if(s[i]>='0' && s[i]<='9'){
x*=10;
x+=s[i]-'0';
} else {
sum+=x;
x=0;
}
}
sum+=x;
}
cout << sum << endl;
return 0;
}
Code 2: import re,sys
a=0
for l in sys.stdin:
a+=sum(map(int,re.findall(r"\d+",l)))
print(a)
|
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 h = ni(), w = ni();
long x = go(h, w);
long y = go(w, h);
out.println(Math.min(x, y));
}
static long go(int h, int w)
{
if(w % 3 == 0)return 0;
long min = h;
for(int i = 1;i < w;i++){
long[] u = {
(long)(h+1)/2*i,
(long)(h/2)*i,
(long)(w-i)*h
};
Arrays.sort(u);
min = Math.min(min, u[2]-u[0]);
}
return min;
}
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 | import java.io.InputStream
import java.math.BigDecimal
import java.math.BigInteger
fun main(args: Array<String>) = input.run {
val n = nextInt()
val m = nextInt()
val ans = mutableListOf<Long>()
fun calc(n: Int, m: Int) {
if (n >= 3) {
ans.add(if (n % 3 == 0) 0 else m.toLong())
}
(1..n - 1).map {
val a = n - it
val b = m / 2
val c = m - b
val areas = arrayOf(it.toLong() * m, a.toLong() * b, a.toLong() * c)
areas.sort()
ans.add(areas[2] - areas[0])
}
}
calc(n, m)
calc(m, n)
println(ans.min())
}
val input = FastScanner()
fun String.toBigInteger() = BigInteger(this)
fun String.toBigDecimal() = BigDecimal(this)
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 nextString(): String? {
var c = skipWhitespace()
if (c < 0) return null
return sb.run {
setLength(0)
do {
append(c.toChar())
c = read()
} while (c > ' '.toInt())
toString()
}
}
fun nextLine(): String? {
var c = read()
if (c < 0) return null
return sb.run {
setLength(0)
while (c >= 0 && c != '\n'.toInt()) {
append(c.toChar())
c = read()
}
toString()
}
}
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 nextDouble() = nextString()?.toDouble() ?: 0.0
fun nextBigInteger(): BigInteger = nextString()?.toBigInteger() ?: BigInteger.ZERO
fun nextBigDecimal(): BigDecimal = nextString()?.toBigDecimal() ?: BigDecimal.ZERO
fun nextStrings(n: Int) = Array<String>(n) { nextString() ?: "" }
fun nextInts(n: Int) = IntArray(n) { nextInt() }
fun nextLongs(n: Int) = LongArray(n) { nextLong() }
fun nextDoubles(n: Int) = DoubleArray(n) { nextDouble() }
fun nextBigIntegers(n: Int) = Array<BigInteger>(n) { nextBigInteger() }
fun nextBigDecimals(n: Int) = Array<BigDecimal>(n) { nextBigDecimal() }
fun nextStrings(n: Int, m: Int) = Array(n) { nextStrings(m) }
fun nextInts(n: Int, m: Int) = Array(n) { nextInts(m) }
fun nextLongs(n: Int, m: Int) = Array(n) { nextLongs(m) }
fun nextDoubles(n: Int, m: Int) = Array(n) { nextDoubles(m) }
fun nextBigIntegers(n: Int, m: Int) = Array(n) { nextBigIntegers(m) }
fun nextBigDecimals(n: Int, m: Int) = Array(n) { nextBigDecimals(m) }
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: 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 h = ni(), w = ni();
long x = go(h, w);
long y = go(w, h);
out.println(Math.min(x, y));
}
static long go(int h, int w)
{
if(w % 3 == 0)return 0;
long min = h;
for(int i = 1;i < w;i++){
long[] u = {
(long)(h+1)/2*i,
(long)(h/2)*i,
(long)(w-i)*h
};
Arrays.sort(u);
min = Math.min(min, u[2]-u[0]);
}
return min;
}
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: import java.io.InputStream
import java.math.BigDecimal
import java.math.BigInteger
fun main(args: Array<String>) = input.run {
val n = nextInt()
val m = nextInt()
val ans = mutableListOf<Long>()
fun calc(n: Int, m: Int) {
if (n >= 3) {
ans.add(if (n % 3 == 0) 0 else m.toLong())
}
(1..n - 1).map {
val a = n - it
val b = m / 2
val c = m - b
val areas = arrayOf(it.toLong() * m, a.toLong() * b, a.toLong() * c)
areas.sort()
ans.add(areas[2] - areas[0])
}
}
calc(n, m)
calc(m, n)
println(ans.min())
}
val input = FastScanner()
fun String.toBigInteger() = BigInteger(this)
fun String.toBigDecimal() = BigDecimal(this)
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 nextString(): String? {
var c = skipWhitespace()
if (c < 0) return null
return sb.run {
setLength(0)
do {
append(c.toChar())
c = read()
} while (c > ' '.toInt())
toString()
}
}
fun nextLine(): String? {
var c = read()
if (c < 0) return null
return sb.run {
setLength(0)
while (c >= 0 && c != '\n'.toInt()) {
append(c.toChar())
c = read()
}
toString()
}
}
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 nextDouble() = nextString()?.toDouble() ?: 0.0
fun nextBigInteger(): BigInteger = nextString()?.toBigInteger() ?: BigInteger.ZERO
fun nextBigDecimal(): BigDecimal = nextString()?.toBigDecimal() ?: BigDecimal.ZERO
fun nextStrings(n: Int) = Array<String>(n) { nextString() ?: "" }
fun nextInts(n: Int) = IntArray(n) { nextInt() }
fun nextLongs(n: Int) = LongArray(n) { nextLong() }
fun nextDoubles(n: Int) = DoubleArray(n) { nextDouble() }
fun nextBigIntegers(n: Int) = Array<BigInteger>(n) { nextBigInteger() }
fun nextBigDecimals(n: Int) = Array<BigDecimal>(n) { nextBigDecimal() }
fun nextStrings(n: Int, m: Int) = Array(n) { nextStrings(m) }
fun nextInts(n: Int, m: Int) = Array(n) { nextInts(m) }
fun nextLongs(n: Int, m: Int) = Array(n) { nextLongs(m) }
fun nextDoubles(n: Int, m: Int) = Array(n) { nextDoubles(m) }
fun nextBigIntegers(n: Int, m: Int) = Array(n) { nextBigIntegers(m) }
fun nextBigDecimals(n: Int, m: Int) = Array(n) { nextBigDecimals(m) }
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()
}
}
|
Python | N=int(input())
L=list(map(int,input().split()))
L.insert(0,0)
H=list()
for _ in range(N+1):
H.append(0)
for i in range(1,N+1):
H[L[i]]+=1
#print(H)
def culc(x):
return x*(x-1)//2
A=0
for j in range(1,N+1):
A+=culc(H[j])
#print(A)
for k in range(1,N+1):
number=L[k]
print(A-(H[number]-1))
| C++ | #include <iostream>
#include <string>
using namespace std;
int main(){
string S;
cin >> S;
if(S <= "2019/04/30") cout << "Heisei" << endl;
else cout << "TBD" << endl;
return 0;
} | No | Do these codes solve the same problem?
Code 1: N=int(input())
L=list(map(int,input().split()))
L.insert(0,0)
H=list()
for _ in range(N+1):
H.append(0)
for i in range(1,N+1):
H[L[i]]+=1
#print(H)
def culc(x):
return x*(x-1)//2
A=0
for j in range(1,N+1):
A+=culc(H[j])
#print(A)
for k in range(1,N+1):
number=L[k]
print(A-(H[number]-1))
Code 2: #include <iostream>
#include <string>
using namespace std;
int main(){
string S;
cin >> S;
if(S <= "2019/04/30") cout << "Heisei" << endl;
else cout << "TBD" << endl;
return 0;
} |
C | #include <stdio.h>
int main(void)
{
int a;
int b;
int c;
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
if(a<=b&&b<=c)
{
printf("%d %d %d\n",a,b,c);
}
else if(a<=c&&c<=b)
{
printf("%d %d %d\n",a,c,b);
}
else if(b<=a&&a<=c)
{
printf("%d %d %d\n",b,a,c);
}
else if(b<=c&&c<=a)
{
printf("%d %d %d\n",b,c,a);
}
else if(c<=a&&a<=b)
{
printf("%d %d %d\n",c,a,b);
}
else if(c<=b&&b<=a)
{
printf("%d %d %d\n",c,b,a);
}
return 0;
} | Python | a,b,c = (int(x) for x in input().split())
ans = 0
if(a == b):
if(c%a == 0):
ans = ans+1
else:
for i in range(a,b+1):
if(c%i == 0):
ans = ans+1
print(ans)
| No | Do these codes solve the same problem?
Code 1: #include <stdio.h>
int main(void)
{
int a;
int b;
int c;
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
if(a<=b&&b<=c)
{
printf("%d %d %d\n",a,b,c);
}
else if(a<=c&&c<=b)
{
printf("%d %d %d\n",a,c,b);
}
else if(b<=a&&a<=c)
{
printf("%d %d %d\n",b,a,c);
}
else if(b<=c&&c<=a)
{
printf("%d %d %d\n",b,c,a);
}
else if(c<=a&&a<=b)
{
printf("%d %d %d\n",c,a,b);
}
else if(c<=b&&b<=a)
{
printf("%d %d %d\n",c,b,a);
}
return 0;
}
Code 2: a,b,c = (int(x) for x in input().split())
ans = 0
if(a == b):
if(c%a == 0):
ans = ans+1
else:
for i in range(a,b+1):
if(c%i == 0):
ans = ans+1
print(ans)
|
C++ | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <memory.h>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <set>
#include <map>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <cctype>
#include <fstream>
#include <cmath>
using namespace std;
#define rep(i, n) for(int i = 0; i< (int)(n); i++)
#define all(c) (c).begin(), (c).end()
#define iter(c) __typeof((c).begin())
#define pb(e) push_back(e)
#define foreach(c, i) for(iter(c) i = (c).begin(); i != c.end(); ++i)
typedef long long ll;
typedef pair<ll, ll> P;
const ll mod = 1000 * 1000 * 1000 + 9;
const double EPS = 1e-10;
const int sz = 60;
const int smalln = 510;
const int maxn = 2000010;
int X[sz], Y[sz];
ll p[maxn], p_inv[maxn];
bool ng[smalln][smalln];
int dist[smalln][smalln];
ll memo[smalln][smalln];
ll dp[sz][sz][2];
ll modpow(ll p, ll n, ll mod){
ll res = 1;
while(n > 0){
if(n & 1){
res = (res * p) % mod;
}
p = (p * p) % mod;
n >>= 1;
}
return res;
}
void init(){
p[0] = 1;
p_inv[0] = 1;
rep(i, maxn - 1){
p[i+1] = p[i] * (i + 1) % mod;
p_inv[i+1] = modpow(p[i+1], mod - 2, mod);
}
}
ll comb(int n, int r){
if(n < r) return 0;
ll res = p[n] * p_inv[r] % mod;
return res * p_inv[n-r] % mod;
}
ll bfs(int N, int M){
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
memset(ng, false, sizeof(ng));
memset(memo, 0, sizeof(memo));
memset(dist, -1, sizeof(dist));
rep(i, M) if(X[i] < smalln && Y[i] < smalln) ng[X[i]][Y[i]] = true;
memo[1][1] = 1;
queue<P> que;
que.push(P(1, 1));
while(!que.empty()){
int x = que.front().first;
int y = que.front().second;
que.pop();
rep(i, 4){
int x2 = x + dx[i];
int y2 = y + dy[i];
if(1 <= x2 && x2 <= N && 1 <= y2 && y2 <= N && !ng[x2][y2] &&
(dist[x2][y2] < 0 || dist[x2][y2] >= dist[x][y] + 1)){
if(dist[x2][y2] != dist[x][y] + 1){
dist[x2][y2] = dist[x][y] + 1;
que.push(P(x2, y2));
}
memo[x2][y2] += memo[x][y];
memo[x2][y2] %= mod;
}
}
}
return memo[N][N];
}
ll calc(int M, int x1, int x2, int y1, int y2){
ll res = 0;
memset(dp, 0, sizeof(dp));
dp[0][0][0] = 1;
rep(i, M) rep(j, i + 1)rep(k, 2){
dp[i+1][j][k] += dp[i][j][k];
dp[i+1][j][k] %= mod;
int prex = j == 0 ? x1 : X[j-1];
int prey = j == 0 ? y1 : Y[j-1];
int dx = X[i] - prex;
int dy = Y[i] - prey;
if(dx >= 0 && dy >= 0){
dp[i+1][i+1][1 - k] += dp[i][j][k] * comb(dx + dy, dx);
dp[i+1][i+1][1 - k] %= mod;
}
}
rep(i, M + 1){
int lastx = i == 0 ? x1 : X[i-1];
int lasty = i == 0 ? y1 : Y[i-1];
int dx = x2 - lastx;
int dy = y2 - lasty;
if(dx >= 0 && dy >= 0){
res += (dp[M][i][0] - dp[M][i][1]) * comb(dx + dy, dx) % mod;
}
}
return (res % mod + mod) % mod;
}
int solve(int N, int M){
ll res = 0;
ll cnt1[2 * sz], cnt2[2 * sz];
int best = (int)1e9, len = 2 * M + 1;
int tempX[sz], tempY[sz];
bfs(len, M);
rep(i, len) best = min(best, dist[i+1][len-i]);
rep(i, len) cnt1[i+1] = best == dist[i+1][len-i] ? memo[i+1][len-i] : 0;
rep(i, M) tempX[i] = N + 1 - X[i], tempY[i] = N + 1 - Y[i];
swap(X, tempX);
swap(Y, tempY);
best = (int)1e9;
bfs(len, M);
rep(i, len) best = min(best, dist[i+1][len-i]);
rep(i, len) cnt2[i+1] = best == dist[i+1][len-i] ? memo[i+1][len-i] : 0;
swap(X, tempX);
swap(Y, tempY);
for(int x1 = 1; x1 <= len; x1++){
for(int x2 = N; x2 > N - len; x2--){
int y1 = len + 1 - x1;
int y2 = 2 * N - len - x2 + 1;
ll temp = calc(M, x1, x2, y1, y2) * cnt1[x1] % mod;
temp = temp * cnt2[N-x2+1] % mod;
//cout << x1 << " " << y1 << " " << x2 << " " << y2 << " "<< cnt1[x1] << " " << cnt2[N-x2+1] << endl;
res += temp;
}
}
return res % mod;
}
int main(){
int N, M;
cin >> N >> M;
init();
rep(i, M) cin >> X[i] >> Y[i];
rep(i, M)rep(j, M - 1) if(X[j] > X[j+1] || (X[j] == X[j+1] && Y[j] > Y[j+1])){
swap(X[j], X[j+1]);
swap(Y[j], Y[j+1]);
}
if(N < 500){
cout << bfs(N, M) << endl;
}else{
cout << solve(N, M) << endl;
}
return 0;
} | Python | # coding: utf-8
# Your code here!
N,M=map(int,input().split())
l=[]
for _ in range(M):
s,t=map(int,input().split())
l.append([s,t])
for i in range(10**(N-1) if N!=1 else 0,10**N):
temp=list(str(i))
judge=True
for s,t in l:
if temp[s-1]!=str(t):
judge=False
if judge:
print(i)
exit()
print(-1)
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <memory.h>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <set>
#include <map>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <cctype>
#include <fstream>
#include <cmath>
using namespace std;
#define rep(i, n) for(int i = 0; i< (int)(n); i++)
#define all(c) (c).begin(), (c).end()
#define iter(c) __typeof((c).begin())
#define pb(e) push_back(e)
#define foreach(c, i) for(iter(c) i = (c).begin(); i != c.end(); ++i)
typedef long long ll;
typedef pair<ll, ll> P;
const ll mod = 1000 * 1000 * 1000 + 9;
const double EPS = 1e-10;
const int sz = 60;
const int smalln = 510;
const int maxn = 2000010;
int X[sz], Y[sz];
ll p[maxn], p_inv[maxn];
bool ng[smalln][smalln];
int dist[smalln][smalln];
ll memo[smalln][smalln];
ll dp[sz][sz][2];
ll modpow(ll p, ll n, ll mod){
ll res = 1;
while(n > 0){
if(n & 1){
res = (res * p) % mod;
}
p = (p * p) % mod;
n >>= 1;
}
return res;
}
void init(){
p[0] = 1;
p_inv[0] = 1;
rep(i, maxn - 1){
p[i+1] = p[i] * (i + 1) % mod;
p_inv[i+1] = modpow(p[i+1], mod - 2, mod);
}
}
ll comb(int n, int r){
if(n < r) return 0;
ll res = p[n] * p_inv[r] % mod;
return res * p_inv[n-r] % mod;
}
ll bfs(int N, int M){
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
memset(ng, false, sizeof(ng));
memset(memo, 0, sizeof(memo));
memset(dist, -1, sizeof(dist));
rep(i, M) if(X[i] < smalln && Y[i] < smalln) ng[X[i]][Y[i]] = true;
memo[1][1] = 1;
queue<P> que;
que.push(P(1, 1));
while(!que.empty()){
int x = que.front().first;
int y = que.front().second;
que.pop();
rep(i, 4){
int x2 = x + dx[i];
int y2 = y + dy[i];
if(1 <= x2 && x2 <= N && 1 <= y2 && y2 <= N && !ng[x2][y2] &&
(dist[x2][y2] < 0 || dist[x2][y2] >= dist[x][y] + 1)){
if(dist[x2][y2] != dist[x][y] + 1){
dist[x2][y2] = dist[x][y] + 1;
que.push(P(x2, y2));
}
memo[x2][y2] += memo[x][y];
memo[x2][y2] %= mod;
}
}
}
return memo[N][N];
}
ll calc(int M, int x1, int x2, int y1, int y2){
ll res = 0;
memset(dp, 0, sizeof(dp));
dp[0][0][0] = 1;
rep(i, M) rep(j, i + 1)rep(k, 2){
dp[i+1][j][k] += dp[i][j][k];
dp[i+1][j][k] %= mod;
int prex = j == 0 ? x1 : X[j-1];
int prey = j == 0 ? y1 : Y[j-1];
int dx = X[i] - prex;
int dy = Y[i] - prey;
if(dx >= 0 && dy >= 0){
dp[i+1][i+1][1 - k] += dp[i][j][k] * comb(dx + dy, dx);
dp[i+1][i+1][1 - k] %= mod;
}
}
rep(i, M + 1){
int lastx = i == 0 ? x1 : X[i-1];
int lasty = i == 0 ? y1 : Y[i-1];
int dx = x2 - lastx;
int dy = y2 - lasty;
if(dx >= 0 && dy >= 0){
res += (dp[M][i][0] - dp[M][i][1]) * comb(dx + dy, dx) % mod;
}
}
return (res % mod + mod) % mod;
}
int solve(int N, int M){
ll res = 0;
ll cnt1[2 * sz], cnt2[2 * sz];
int best = (int)1e9, len = 2 * M + 1;
int tempX[sz], tempY[sz];
bfs(len, M);
rep(i, len) best = min(best, dist[i+1][len-i]);
rep(i, len) cnt1[i+1] = best == dist[i+1][len-i] ? memo[i+1][len-i] : 0;
rep(i, M) tempX[i] = N + 1 - X[i], tempY[i] = N + 1 - Y[i];
swap(X, tempX);
swap(Y, tempY);
best = (int)1e9;
bfs(len, M);
rep(i, len) best = min(best, dist[i+1][len-i]);
rep(i, len) cnt2[i+1] = best == dist[i+1][len-i] ? memo[i+1][len-i] : 0;
swap(X, tempX);
swap(Y, tempY);
for(int x1 = 1; x1 <= len; x1++){
for(int x2 = N; x2 > N - len; x2--){
int y1 = len + 1 - x1;
int y2 = 2 * N - len - x2 + 1;
ll temp = calc(M, x1, x2, y1, y2) * cnt1[x1] % mod;
temp = temp * cnt2[N-x2+1] % mod;
//cout << x1 << " " << y1 << " " << x2 << " " << y2 << " "<< cnt1[x1] << " " << cnt2[N-x2+1] << endl;
res += temp;
}
}
return res % mod;
}
int main(){
int N, M;
cin >> N >> M;
init();
rep(i, M) cin >> X[i] >> Y[i];
rep(i, M)rep(j, M - 1) if(X[j] > X[j+1] || (X[j] == X[j+1] && Y[j] > Y[j+1])){
swap(X[j], X[j+1]);
swap(Y[j], Y[j+1]);
}
if(N < 500){
cout << bfs(N, M) << endl;
}else{
cout << solve(N, M) << endl;
}
return 0;
}
Code 2: # coding: utf-8
# Your code here!
N,M=map(int,input().split())
l=[]
for _ in range(M):
s,t=map(int,input().split())
l.append([s,t])
for i in range(10**(N-1) if N!=1 else 0,10**N):
temp=list(str(i))
judge=True
for s,t in l:
if temp[s-1]!=str(t):
judge=False
if judge:
print(i)
exit()
print(-1)
|
JavaScript | "use strict";
const main = arg => {
arg = arg.trim().split("\n");
const N = parseInt(arg[0].split(" ")[0]);
const M = parseInt(arg[0].split(" ")[1]);
let answer = 0;
if(N === 1 && M === 1) {
answer = 1;
} else if(N === 1) {
answer = M - 2;
} else if(M === 1) {
answer = N - 2;
} else {
answer = (N - 2) * (M - 2);
}
// 桁溢れ対策 original (id: macco さん)
if (answer > Number.MAX_SAFE_INTEGER) {
const multi_biggerInt = (a, b) => {
const num1 = String(a).split('').map(n => Number(n)).reverse();
const num2 = String(b).split('').map(n => Number(n)).reverse();
let ans = [...Array(num1.length + num2.length)].fill(0);
const checkCarry = () => {
for (let i = 0; i < ans.length; i++) {
if (ans[i] >= 10) {
const upper = Number(String(ans[i]).split('')[0]);
const lower = Number(String(ans[i]).split('')[1]);
ans[i - 1] += upper;
ans[i] = lower;
}
}
}
for (let i = 0; i < num1.length; i++) {
for (let j = 0; j < num2.length; j++) {
const pro = num1[i] * num2[j];
const digit = ans.length - (i + j) - 1;
ans[digit] += pro;
checkCarry();
}
}
for (let i = 0; i < ans.length; i++) {
if (ans[i] !== 0) {
ans = ans.slice(i);
break;
}
}
return ans.join('');
}
answer = multi_biggerInt(Math.abs(N - 2), Math.abs(M - 2));
}
console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
| Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
sc := NewScanner()
N, M := sc.NextInt(), sc.NextInt()
if N == 1 && M == 1 {
fmt.Println(1)
return
}
if N == 1 {
fmt.Println(M - 2)
return
}
if M == 1 {
fmt.Println(N - 2)
return
}
fmt.Println((N - 2) * (M - 2))
}
type Scanner struct {
r *bufio.Reader
buf []byte
p int
}
func NewScanner() *Scanner {
rdr := bufio.NewReaderSize(os.Stdin, 1000)
return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
s.pre()
start := s.p
for ; s.p < len(s.buf); s.p++ {
if s.buf[s.p] == ' ' {
break
}
}
result := string(s.buf[start:s.p])
s.p++
return result
}
func (s *Scanner) NextLine() string {
s.pre()
start := s.p
s.p = len(s.buf)
return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
v, _ := strconv.Atoi(s.Next())
return v
}
func (s *Scanner) NextInt64() int64 {
v, _ := strconv.ParseInt(s.Next(), 10, 64)
return v
}
func (s *Scanner) NextIntArray() []int {
s.pre()
start := s.p
result := []int{}
for ; s.p < len(s.buf)+1; s.p++ {
if s.p == len(s.buf) || s.buf[s.p] == ' ' {
v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
result = append(result, int(v))
start = s.p + 1
}
}
return result
}
func (s *Scanner) NextInt64Array() []int64 {
s.pre()
start := s.p
result := []int64{}
for ; s.p < len(s.buf)+1; s.p++ {
if s.p == len(s.buf) || s.buf[s.p] == ' ' {
v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
result = append(result, v)
start = s.p + 1
}
}
return result
}
func (s *Scanner) NextMap() map[int]bool {
s.pre()
start := s.p
mp := map[int]bool{}
for ; s.p < len(s.buf); s.p++ {
if s.buf[s.p] == ' ' {
v, _ := strconv.Atoi(string(s.buf[start:s.p]))
mp[v] = true
start = s.p + 1
}
}
v, _ := strconv.Atoi(string(s.buf[start:s.p]))
mp[v] = true
return mp
}
func (s *Scanner) pre() {
if s.p >= len(s.buf) {
s.readLine()
s.p = 0
}
}
func (s *Scanner) readLine() {
s.buf = make([]byte, 0)
for {
l, p, e := s.r.ReadLine()
if e != nil {
panic(e)
}
s.buf = append(s.buf, l...)
if !p {
break
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: "use strict";
const main = arg => {
arg = arg.trim().split("\n");
const N = parseInt(arg[0].split(" ")[0]);
const M = parseInt(arg[0].split(" ")[1]);
let answer = 0;
if(N === 1 && M === 1) {
answer = 1;
} else if(N === 1) {
answer = M - 2;
} else if(M === 1) {
answer = N - 2;
} else {
answer = (N - 2) * (M - 2);
}
// 桁溢れ対策 original (id: macco さん)
if (answer > Number.MAX_SAFE_INTEGER) {
const multi_biggerInt = (a, b) => {
const num1 = String(a).split('').map(n => Number(n)).reverse();
const num2 = String(b).split('').map(n => Number(n)).reverse();
let ans = [...Array(num1.length + num2.length)].fill(0);
const checkCarry = () => {
for (let i = 0; i < ans.length; i++) {
if (ans[i] >= 10) {
const upper = Number(String(ans[i]).split('')[0]);
const lower = Number(String(ans[i]).split('')[1]);
ans[i - 1] += upper;
ans[i] = lower;
}
}
}
for (let i = 0; i < num1.length; i++) {
for (let j = 0; j < num2.length; j++) {
const pro = num1[i] * num2[j];
const digit = ans.length - (i + j) - 1;
ans[digit] += pro;
checkCarry();
}
}
for (let i = 0; i < ans.length; i++) {
if (ans[i] !== 0) {
ans = ans.slice(i);
break;
}
}
return ans.join('');
}
answer = multi_biggerInt(Math.abs(N - 2), Math.abs(M - 2));
}
console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
Code 2: package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
sc := NewScanner()
N, M := sc.NextInt(), sc.NextInt()
if N == 1 && M == 1 {
fmt.Println(1)
return
}
if N == 1 {
fmt.Println(M - 2)
return
}
if M == 1 {
fmt.Println(N - 2)
return
}
fmt.Println((N - 2) * (M - 2))
}
type Scanner struct {
r *bufio.Reader
buf []byte
p int
}
func NewScanner() *Scanner {
rdr := bufio.NewReaderSize(os.Stdin, 1000)
return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
s.pre()
start := s.p
for ; s.p < len(s.buf); s.p++ {
if s.buf[s.p] == ' ' {
break
}
}
result := string(s.buf[start:s.p])
s.p++
return result
}
func (s *Scanner) NextLine() string {
s.pre()
start := s.p
s.p = len(s.buf)
return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
v, _ := strconv.Atoi(s.Next())
return v
}
func (s *Scanner) NextInt64() int64 {
v, _ := strconv.ParseInt(s.Next(), 10, 64)
return v
}
func (s *Scanner) NextIntArray() []int {
s.pre()
start := s.p
result := []int{}
for ; s.p < len(s.buf)+1; s.p++ {
if s.p == len(s.buf) || s.buf[s.p] == ' ' {
v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
result = append(result, int(v))
start = s.p + 1
}
}
return result
}
func (s *Scanner) NextInt64Array() []int64 {
s.pre()
start := s.p
result := []int64{}
for ; s.p < len(s.buf)+1; s.p++ {
if s.p == len(s.buf) || s.buf[s.p] == ' ' {
v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
result = append(result, v)
start = s.p + 1
}
}
return result
}
func (s *Scanner) NextMap() map[int]bool {
s.pre()
start := s.p
mp := map[int]bool{}
for ; s.p < len(s.buf); s.p++ {
if s.buf[s.p] == ' ' {
v, _ := strconv.Atoi(string(s.buf[start:s.p]))
mp[v] = true
start = s.p + 1
}
}
v, _ := strconv.Atoi(string(s.buf[start:s.p]))
mp[v] = true
return mp
}
func (s *Scanner) pre() {
if s.p >= len(s.buf) {
s.readLine()
s.p = 0
}
}
func (s *Scanner) readLine() {
s.buf = make([]byte, 0)
for {
l, p, e := s.r.ReadLine()
if e != nil {
panic(e)
}
s.buf = append(s.buf, l...)
if !p {
break
}
}
}
|
C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics;
class Myon
{
public Myon() { }
public static int Main()
{
new Myon().calc();
return 0;
}
Scanner cin;
void calc()
{
cin = new Scanner();
string A = cin.next();
string B = cin.next();
int N = A.Length;
if(A == B)
{
Console.WriteLine(0);
return;
}
if (B.IndexOf("1") == -1)
{
Console.WriteLine(-1);
return;
}
int[] left = new int[N];
int[] right = new int[N];
int MAX = 9999;
for (int i = 0; i < N; i++)
{
if(B[i] == '1')
{
left[i] = right[i] = 0;
}
else
{
left[i] = right[i] = MAX;
}
}
for (int i = 0; i < N - 1; i++)
{
left[i + 1] = Math.Min(left[i + 1], left[i] + 1);
right[i] = Math.Min(right[i], right[i + 1] + 1);
}
left[0] = Math.Min(left[0], left[N - 1] + 1);
right[N - 1] = Math.Min(right[N - 1], right[0] + 1);
for (int i = N - 2; i >= 0; i--)
{
left[i + 1] = Math.Min(left[i + 1], left[i] + 1);
right[i] = Math.Min(right[i], right[i + 1] + 1);
}
left[0] = Math.Min(left[0], left[N - 1] + 1);
right[N - 1] = Math.Min(right[N - 1], right[0] + 1);
for (int i = 0; i < N - 1; i++)
{
left[i + 1] = Math.Min(left[i + 1], left[i] + 1);
right[i] = Math.Min(right[i], right[i + 1] + 1);
}
left[0] = Math.Min(left[0], left[N - 1] + 1);
right[N - 1] = Math.Min(right[N - 1], right[0] + 1);
for (int i = N - 2; i >= 0; i--)
{
left[i + 1] = Math.Min(left[i + 1], left[i] + 1);
right[i] = Math.Min(right[i], right[i + 1] + 1);
}
left[0] = Math.Min(left[0], left[N - 1] + 1);
right[N - 1] = Math.Min(right[N - 1], right[0] + 1);
int best = 99999999;
for (int i = 0; i < N; i++)
{
int swapCost = 0;
List<int> lbase = new List<int>();
for (int j = 0; j < N; j++)
{
if(A[j] != B[(i + j) % N])
{
swapCost++;
lbase.Add(((left[j] << 16) + (right[j])));
}
}
lbase.Sort();
lbase.Reverse();
int moveCost = MAX;
int l = MAX;
int r = 0;
foreach (var item in lbase)
{
int L = item >> 16;
int R = item & 0xFFFF;
l = L;
moveCost = Math.Min(moveCost, calcPos(l, r, i, N));
r = Math.Max(r, R);
}
l = 0;
moveCost = Math.Min(moveCost, calcPos(l, r, i, N));
best = Math.Min(best, swapCost + moveCost);
}
Console.WriteLine(best);
}
int calcPos(int l, int r, int m, int N)
{
int ans = 999999;
//lr
int rdist = Math.Abs(r - m);
ans = Math.Min(ans, l + l + r + Math.Min(rdist, N - rdist));
//rl
int ldist = Math.Abs((N - l) - m);
ans = Math.Min(ans, r + r + l + Math.Min(ldist, N - ldist));
return ans;
}
//swap
void swap<T>(ref T a, ref T b)
{
T c = a;
a = b;
b = c;
}
}
class Scanner
{
string[] s;
int i;
char[] cs = new char[] { ' ' };
public Scanner()
{
s = new string[0];
i = 0;
}
public string next()
{
if (i < s.Length) return s[i++];
string st = Console.ReadLine();
while (st == "") st = Console.ReadLine();
s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
if (s.Length == 0) return next();
i = 0;
return s[i++];
}
public int nextInt()
{
return int.Parse(next());
}
public int[] ArrayInt(int N, int add = 0)
{
int[] Array = new int[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextInt() + add;
}
return Array;
}
public long nextLong()
{
return long.Parse(next());
}
public long[] ArrayLong(int N, long add = 0)
{
long[] Array = new long[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextLong() + add;
}
return Array;
}
public double nextDouble()
{
return double.Parse(next());
}
public double[] ArrayDouble(int N, double add = 0)
{
double[] Array = new double[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextDouble() + add;
}
return Array;
}
} | Kotlin | fun main(args: Array<String>) {
val a = readLine()!!.map { it == '1' }.toBooleanArray()
val b = readLine()!!.map { it == '1' }.toBooleanArray()
fun f(i: Int) = (i + a.size) % a.size
if (b.all { !it }) {
println(if (a.all { !it }) 0 else -1)
return
}
val left = IntArray(a.size)
val right = IntArray(a.size)
var t = b.size - b.lastIndexOf(true) - 1
for (i in left.indices) {
left[i] = if (b[i]) 0 else t + 1
t = left[i]
}
t = b.indexOf(true)
for (i in right.indices.reversed()) {
right[i] = if (b[i]) 0 else t + 1
t = right[i]
}
var res = a.size * 5
for (sh in -a.size..a.size) {
val flip = a.indices
.filter { a[it] != b[f(it + sh)] }
.map {
Pair(
Math.min(left[it], Math.max(left[it] + sh, 0)),
Math.min(right[it], Math.max(right[it] - sh, 0))
)
}
.toTypedArray()
.sortedBy { -it.first }
var shifts = 0
if (!flip.isEmpty()) {
shifts = flip[0].first
var tRight = flip[0].second
for ((pLeft, pRight) in flip.drop(1)) {
shifts = Math.min(shifts, tRight + pLeft)
tRight = Math.max(tRight, pRight)
}
shifts = Math.min(shifts, tRight)
}
res = Math.min(res, shifts * 2 + flip.size + Math.abs(sh))
}
println(res)
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics;
class Myon
{
public Myon() { }
public static int Main()
{
new Myon().calc();
return 0;
}
Scanner cin;
void calc()
{
cin = new Scanner();
string A = cin.next();
string B = cin.next();
int N = A.Length;
if(A == B)
{
Console.WriteLine(0);
return;
}
if (B.IndexOf("1") == -1)
{
Console.WriteLine(-1);
return;
}
int[] left = new int[N];
int[] right = new int[N];
int MAX = 9999;
for (int i = 0; i < N; i++)
{
if(B[i] == '1')
{
left[i] = right[i] = 0;
}
else
{
left[i] = right[i] = MAX;
}
}
for (int i = 0; i < N - 1; i++)
{
left[i + 1] = Math.Min(left[i + 1], left[i] + 1);
right[i] = Math.Min(right[i], right[i + 1] + 1);
}
left[0] = Math.Min(left[0], left[N - 1] + 1);
right[N - 1] = Math.Min(right[N - 1], right[0] + 1);
for (int i = N - 2; i >= 0; i--)
{
left[i + 1] = Math.Min(left[i + 1], left[i] + 1);
right[i] = Math.Min(right[i], right[i + 1] + 1);
}
left[0] = Math.Min(left[0], left[N - 1] + 1);
right[N - 1] = Math.Min(right[N - 1], right[0] + 1);
for (int i = 0; i < N - 1; i++)
{
left[i + 1] = Math.Min(left[i + 1], left[i] + 1);
right[i] = Math.Min(right[i], right[i + 1] + 1);
}
left[0] = Math.Min(left[0], left[N - 1] + 1);
right[N - 1] = Math.Min(right[N - 1], right[0] + 1);
for (int i = N - 2; i >= 0; i--)
{
left[i + 1] = Math.Min(left[i + 1], left[i] + 1);
right[i] = Math.Min(right[i], right[i + 1] + 1);
}
left[0] = Math.Min(left[0], left[N - 1] + 1);
right[N - 1] = Math.Min(right[N - 1], right[0] + 1);
int best = 99999999;
for (int i = 0; i < N; i++)
{
int swapCost = 0;
List<int> lbase = new List<int>();
for (int j = 0; j < N; j++)
{
if(A[j] != B[(i + j) % N])
{
swapCost++;
lbase.Add(((left[j] << 16) + (right[j])));
}
}
lbase.Sort();
lbase.Reverse();
int moveCost = MAX;
int l = MAX;
int r = 0;
foreach (var item in lbase)
{
int L = item >> 16;
int R = item & 0xFFFF;
l = L;
moveCost = Math.Min(moveCost, calcPos(l, r, i, N));
r = Math.Max(r, R);
}
l = 0;
moveCost = Math.Min(moveCost, calcPos(l, r, i, N));
best = Math.Min(best, swapCost + moveCost);
}
Console.WriteLine(best);
}
int calcPos(int l, int r, int m, int N)
{
int ans = 999999;
//lr
int rdist = Math.Abs(r - m);
ans = Math.Min(ans, l + l + r + Math.Min(rdist, N - rdist));
//rl
int ldist = Math.Abs((N - l) - m);
ans = Math.Min(ans, r + r + l + Math.Min(ldist, N - ldist));
return ans;
}
//swap
void swap<T>(ref T a, ref T b)
{
T c = a;
a = b;
b = c;
}
}
class Scanner
{
string[] s;
int i;
char[] cs = new char[] { ' ' };
public Scanner()
{
s = new string[0];
i = 0;
}
public string next()
{
if (i < s.Length) return s[i++];
string st = Console.ReadLine();
while (st == "") st = Console.ReadLine();
s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
if (s.Length == 0) return next();
i = 0;
return s[i++];
}
public int nextInt()
{
return int.Parse(next());
}
public int[] ArrayInt(int N, int add = 0)
{
int[] Array = new int[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextInt() + add;
}
return Array;
}
public long nextLong()
{
return long.Parse(next());
}
public long[] ArrayLong(int N, long add = 0)
{
long[] Array = new long[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextLong() + add;
}
return Array;
}
public double nextDouble()
{
return double.Parse(next());
}
public double[] ArrayDouble(int N, double add = 0)
{
double[] Array = new double[N];
for (int i = 0; i < N; i++)
{
Array[i] = nextDouble() + add;
}
return Array;
}
}
Code 2: fun main(args: Array<String>) {
val a = readLine()!!.map { it == '1' }.toBooleanArray()
val b = readLine()!!.map { it == '1' }.toBooleanArray()
fun f(i: Int) = (i + a.size) % a.size
if (b.all { !it }) {
println(if (a.all { !it }) 0 else -1)
return
}
val left = IntArray(a.size)
val right = IntArray(a.size)
var t = b.size - b.lastIndexOf(true) - 1
for (i in left.indices) {
left[i] = if (b[i]) 0 else t + 1
t = left[i]
}
t = b.indexOf(true)
for (i in right.indices.reversed()) {
right[i] = if (b[i]) 0 else t + 1
t = right[i]
}
var res = a.size * 5
for (sh in -a.size..a.size) {
val flip = a.indices
.filter { a[it] != b[f(it + sh)] }
.map {
Pair(
Math.min(left[it], Math.max(left[it] + sh, 0)),
Math.min(right[it], Math.max(right[it] - sh, 0))
)
}
.toTypedArray()
.sortedBy { -it.first }
var shifts = 0
if (!flip.isEmpty()) {
shifts = flip[0].first
var tRight = flip[0].second
for ((pLeft, pRight) in flip.drop(1)) {
shifts = Math.min(shifts, tRight + pLeft)
tRight = Math.max(tRight, pRight)
}
shifts = Math.min(shifts, tRight)
}
res = Math.min(res, shifts * 2 + flip.size + Math.abs(sh))
}
println(res)
}
|
Python | N = int(input())
CSF = []
for i in range(N-1):
CSF.append(list(map(int,input().split())))
for i in range(N):
if i == N-1:
print(0)
else:
ans = CSF[i][1]+CSF[i][0]
for j in range(i+1,N-1):
if ans < CSF[j][1]:
ans = CSF[j][1]
elif ans%CSF[j][2] != 0:
ans += (CSF[j][2]-ans%CSF[j][2])
ans += CSF[j][0]
print(ans) | C | #include<stdio.h>
int main()
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
int i,cnt=0;
for(i=a;i<=b;++i){
if(c%i==0){
++cnt;
}
}
printf("%d\n",cnt);
return 0;
}
| No | Do these codes solve the same problem?
Code 1: N = int(input())
CSF = []
for i in range(N-1):
CSF.append(list(map(int,input().split())))
for i in range(N):
if i == N-1:
print(0)
else:
ans = CSF[i][1]+CSF[i][0]
for j in range(i+1,N-1):
if ans < CSF[j][1]:
ans = CSF[j][1]
elif ans%CSF[j][2] != 0:
ans += (CSF[j][2]-ans%CSF[j][2])
ans += CSF[j][0]
print(ans)
Code 2: #include<stdio.h>
int main()
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
int i,cnt=0;
for(i=a;i<=b;++i){
if(c%i==0){
++cnt;
}
}
printf("%d\n",cnt);
return 0;
}
|
C++ | #include<iostream>
#include<string>
using namespace std;
int main(void){
string str,ans;
for(;;){
getline(cin,str);
if(str=="END OF INPUT") break;
ans.clear();
for(int i=0;i<str.size();i++){
if(i==0 && str[i]==' ' || str[i-1]==' ' && str[i]==' ') ans+='0';
else if(str[i-1]==' ' || i==0){
char c=0;
for(int j=i;;j++){
if(str[j]==' ' || j==str.size()) break;
c++;
}
ans+=c+48;
}
}
cout << ans << endl;
}
}
| Python | for e in iter(input,'END OF INPUT'):
print(*[len(x)*(x!='')for x in e.split(' ')], sep='')
| Yes | Do these codes solve the same problem?
Code 1: #include<iostream>
#include<string>
using namespace std;
int main(void){
string str,ans;
for(;;){
getline(cin,str);
if(str=="END OF INPUT") break;
ans.clear();
for(int i=0;i<str.size();i++){
if(i==0 && str[i]==' ' || str[i-1]==' ' && str[i]==' ') ans+='0';
else if(str[i-1]==' ' || i==0){
char c=0;
for(int j=i;;j++){
if(str[j]==' ' || j==str.size()) break;
c++;
}
ans+=c+48;
}
}
cout << ans << endl;
}
}
Code 2: for e in iter(input,'END OF INPUT'):
print(*[len(x)*(x!='')for x in e.split(' ')], sep='')
|
C++ | //9-3=6 6-4=2
//2 3 4 6 9
//有可能拿到箱子里两个相同的么
//最大值9 最小值0
//从造数规律来看 放回去的数字一定比之前两个数字小 这意味着不可能拿到比一开始最大数字大的数字
//同时 放回去的数字如果和目前已知的重合了 那么等于没有放回去
//如果第一轮造数字没有出现新数字 当前数字里又没有k 那么一定不可能
//如果第一轮出现了新数字
//10005 2 100
//10003 98 9905
//9 6 4
//2 3
//2 4
//2 5
//3 1
//只要能在哪一轮拿到1就可以得到介质
//2 1342
//而要想拿到1 只需要数字两个互质
//互质的判断 大数余小数不为0
//快速判断一堆数字是否互质 如果不互质 最小的数字一定为其他数字的因数
//那么我们就拿所有数字去余最小数字
//公因数一定能被整除吗
//12 15 18 21
//
//一个质数不行
//如果没有两个互质 就拿不到1 最小步长就是最小公因数
//3 6 9 12 18
//如果没有两个互质 说明每个数都有公因数 那么所有数最小的公因数就是MIN 得到的就是MIN到最大值
//两个偶数一定得2
//两个奇数 15 35
//得最小公因数
//3 18
//7 11
//2 8
//6 4
//6 7 6 9 6 11 6 13 6 15
//最接近的两个数字如果为1的话 那么最小到最大介值都能取得
//最接近的两个数字如果为2的话
int GCD( int a , int b )
{
int x=a%b;
while(x != 0) //即: while(n)
{
a = b;
b = x;
x = a % b;
}
return b; //注意这里返回的是b 不是n
}
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define MAXN 100005
using namespace std;
int a[MAXN],n,k,tem,flag,MIN;
int main()
{
MIN=INF;
scanf("%d %d",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]==k)
{
printf("POSSIBLE\n");
return 0;
}
}
sort(a+1,a+1+n);
for(int i=2;i<=n;i++)
{
MIN=min(MIN,GCD(a[i],a[1]));
if((GCD(a[i],a[1]))==1)
{
flag=1;
break;
}
}
if(flag)
{
if(a[n]>=k)
{
printf("POSSIBLE\n");
}
else
{
printf("IMPOSSIBLE\n");
}
}
else
{
if((k%MIN==0)&&(a[n]>=k))
{
printf("POSSIBLE\n");
}
else
{
printf("IMPOSSIBLE\n");
}
}
}
| C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main(string[] args)
{
int[] arr = Console.ReadLine().Split(' ').Select(v => int.Parse(v)).ToArray();
for (int i = 0; i < arr.Length; i++)
{
if(arr[i] == 0)
{
Console.WriteLine(i+1);
return;
}
}
}
}
| No | Do these codes solve the same problem?
Code 1: //9-3=6 6-4=2
//2 3 4 6 9
//有可能拿到箱子里两个相同的么
//最大值9 最小值0
//从造数规律来看 放回去的数字一定比之前两个数字小 这意味着不可能拿到比一开始最大数字大的数字
//同时 放回去的数字如果和目前已知的重合了 那么等于没有放回去
//如果第一轮造数字没有出现新数字 当前数字里又没有k 那么一定不可能
//如果第一轮出现了新数字
//10005 2 100
//10003 98 9905
//9 6 4
//2 3
//2 4
//2 5
//3 1
//只要能在哪一轮拿到1就可以得到介质
//2 1342
//而要想拿到1 只需要数字两个互质
//互质的判断 大数余小数不为0
//快速判断一堆数字是否互质 如果不互质 最小的数字一定为其他数字的因数
//那么我们就拿所有数字去余最小数字
//公因数一定能被整除吗
//12 15 18 21
//
//一个质数不行
//如果没有两个互质 就拿不到1 最小步长就是最小公因数
//3 6 9 12 18
//如果没有两个互质 说明每个数都有公因数 那么所有数最小的公因数就是MIN 得到的就是MIN到最大值
//两个偶数一定得2
//两个奇数 15 35
//得最小公因数
//3 18
//7 11
//2 8
//6 4
//6 7 6 9 6 11 6 13 6 15
//最接近的两个数字如果为1的话 那么最小到最大介值都能取得
//最接近的两个数字如果为2的话
int GCD( int a , int b )
{
int x=a%b;
while(x != 0) //即: while(n)
{
a = b;
b = x;
x = a % b;
}
return b; //注意这里返回的是b 不是n
}
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define MAXN 100005
using namespace std;
int a[MAXN],n,k,tem,flag,MIN;
int main()
{
MIN=INF;
scanf("%d %d",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]==k)
{
printf("POSSIBLE\n");
return 0;
}
}
sort(a+1,a+1+n);
for(int i=2;i<=n;i++)
{
MIN=min(MIN,GCD(a[i],a[1]));
if((GCD(a[i],a[1]))==1)
{
flag=1;
break;
}
}
if(flag)
{
if(a[n]>=k)
{
printf("POSSIBLE\n");
}
else
{
printf("IMPOSSIBLE\n");
}
}
else
{
if((k%MIN==0)&&(a[n]>=k))
{
printf("POSSIBLE\n");
}
else
{
printf("IMPOSSIBLE\n");
}
}
}
Code 2: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main(string[] args)
{
int[] arr = Console.ReadLine().Split(' ').Select(v => int.Parse(v)).ToArray();
for (int i = 0; i < arr.Length; i++)
{
if(arr[i] == 0)
{
Console.WriteLine(i+1);
return;
}
}
}
}
|
C | l,a[25],i,n,S;main(f){for(;~scanf(S="%d\n",&l);){for(i=l;i--;)scanf(S,a+l+~i);for(n=l?32:0;n;f=!f)n-=f?~-n%5:a[i=-~i%l],printf(S,n*=n>0);}} | Python | # 2020/01/19
n,k,s=map(int,input().split())
if s==10**9:
rest=10**9-1
else:
rest=10**9
ans=[s]*k+[rest]*(n-k)
print(*ans) | No | Do these codes solve the same problem?
Code 1: l,a[25],i,n,S;main(f){for(;~scanf(S="%d\n",&l);){for(i=l;i--;)scanf(S,a+l+~i);for(n=l?32:0;n;f=!f)n-=f?~-n%5:a[i=-~i%l],printf(S,n*=n>0);}}
Code 2: # 2020/01/19
n,k,s=map(int,input().split())
if s==10**9:
rest=10**9-1
else:
rest=10**9
ans=[s]*k+[rest]*(n-k)
print(*ans) |
JavaScript | process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.on('SIGINT', function(){
input_stdin_array = input_stdin.split("\n");
main();
process.exit();
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function main() {
var s = readLine();
for (var i=0; i + 1 < s.length; i++){
if (s[i] == s[i+1]){
console.log((i+1).toString() + " " + (i+2).toString());
return;
}
}
for (var i=0; i + 2 < s.length; i++){
if (s[i] == s[i+2]){
console.log((i+1).toString() + " " + (i+3).toString());
return;
}
}
console.log("-1 -1");
} | Go | package main
import "fmt"
type Pair struct{
fst int
snd int
}
func main() {
var s string
ans := Pair{-1, -1}
fmt.Scan(&s)
for i:=0; i<len(s)-2; i++ {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
ans = Pair{i+1, i+3}
break
}
}
if len(s) == 2 && s[0] == s[1] {
ans = Pair{1, 2}
}
fmt.Println(ans.fst, ans.snd)
} | Yes | Do these codes solve the same problem?
Code 1: process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.on('SIGINT', function(){
input_stdin_array = input_stdin.split("\n");
main();
process.exit();
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function main() {
var s = readLine();
for (var i=0; i + 1 < s.length; i++){
if (s[i] == s[i+1]){
console.log((i+1).toString() + " " + (i+2).toString());
return;
}
}
for (var i=0; i + 2 < s.length; i++){
if (s[i] == s[i+2]){
console.log((i+1).toString() + " " + (i+3).toString());
return;
}
}
console.log("-1 -1");
}
Code 2: package main
import "fmt"
type Pair struct{
fst int
snd int
}
func main() {
var s string
ans := Pair{-1, -1}
fmt.Scan(&s)
for i:=0; i<len(s)-2; i++ {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
ans = Pair{i+1, i+3}
break
}
}
if len(s) == 2 && s[0] == s[1] {
ans = Pair{1, 2}
}
fmt.Println(ans.fst, ans.snd)
} |
C++ | #include <bits/stdc++.h>
using namespace std;
using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template <typename T> void ndarray(vector<T> &vec, int len) { vec.resize(len); }
template <typename T, typename... Args> void ndarray(vector<T> &vec, int len, Args... args) { vec.resize(len); for (auto &v : vec) ndarray(v, args...); }
template <typename V, typename T> void ndfill(V &x, const T &val) { x = val; }
template <typename V, typename T> void ndfill(vector<V> &vec, const T &val) { for (auto &v : vec) ndfill(v, val); }
template <typename T> bool chmax(T &m, const T q) { if (m < q) {m = q; return true;} else return false; }
template <typename T> bool chmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; }
template <typename T1, typename T2> pair<T1, T2> operator+(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first + r.first, l.second + r.second); }
template <typename T1, typename T2> pair<T1, T2> operator-(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first - r.first, l.second - r.second); }
template <typename T> vector<T> srtunq(vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; }
template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto &v : vec) is >> v; return is; }
template <typename... T> istream &operator>>(istream &is, tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename... T> ostream &operator<<(ostream &os, const tuple<T...> &tpl) { std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os; }
template <typename T> ostream &operator<<(ostream &os, const deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename T> ostream &operator<<(ostream &os, const set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const unordered_set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &pa) { os << '(' << pa.first << ',' << pa.second << ')'; return os; }
template <typename TK, typename TV> ostream &operator<<(ostream &os, const map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <typename TK, typename TV> ostream &operator<<(ostream &os, const unordered_map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#define dbg(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ") " << __FILE__ << endl;
// Count elements in [A_begin, ..., A_{end-1}] which satisfy A_i < query
// Complexity: O(N log^2 N) for initialization, O(log^2 N) for each query
// Verified: cntLess <https://codeforces.com/contest/1288/submission/68865506>
struct CountLessThan
{
using T = int;
int N;
int head;
vector<vector<T>> x;
inline void merge(int pos) {
x[pos] = x[pos * 2 + 1];
x[pos].insert(x[pos].end(), x[pos * 2 + 2].begin(), x[pos * 2 + 2].end());
sort(x[pos].begin(), x[pos].end());
}
int _getless(int begin, int end, int pos, int l, int r, T query) const {
if (r <= begin or l >= end) return 0;
if (l >= begin and r <= end) return lower_bound(x[pos].begin(), x[pos].end(), query) - x[pos].begin();
return _getless(begin, end, 2 * pos + 1, l, (l + r) / 2, query) + _getless(begin, end, 2 * pos + 2, (l + r) / 2, r, query);
}
int _getlesseq(int begin, int end, int pos, int l, int r, T query) const {
if (r <= begin or l >= end) return 0;
if (l >= begin and r <= end) return upper_bound(x[pos].begin(), x[pos].end(), query) - x[pos].begin();
return _getlesseq(begin, end, 2 * pos + 1, l, (l + r) / 2, query) + _getlesseq(begin, end, 2 * pos + 2, (l + r) / 2, r, query);
}
CountLessThan() = default;
CountLessThan(const vector<T> &vec) : N(vec.size()) {
int N_tmp = 1; while (N_tmp < N) N_tmp <<= 1;
x.resize(N_tmp*2), head = N_tmp - 1;
for (int i = 0; i < N; i++) x[head + i] = {vec[i]};
for (int i = head - 1; i >= 0; i--) merge(i);
}
int cntLess(int begin, int end, T query) const { return _getless(begin, end, 0, 0, (int)x.size() / 2, query); }
int cntLesseq(int begin, int end, T query) const { return _getlesseq(begin, end, 0, 0, (int)x.size() / 2, query); }
int cntMore(int begin, int end, T query) const {
int tot = max(0, min(end, N) - max(begin, 0));
return tot - cntLesseq(begin, end, query);
}
int cntMoreeq(int begin, int end, T query) const {
int tot = max(0, min(end, N) - max(begin, 0));
return tot - cntLess(begin, end, query);
}
friend ostream &operator<<(ostream &os, const CountLessThan &clt) {
os << '[';
for (int i = 0; i < clt.N; i++) os << clt.x[clt.head + i][0] << ',';
os << ']';
return os;
}
};
int main()
{
int N, Q;
cin >> N >> Q;
vector<int> C(N);
cin >> C;
vector<int> nxt(N, N);
map<int, int> last;
IREP(i, N)
{
if (last.count(C[i])) nxt[i] = last[C[i]];
last[C[i]] = i;
}
CountLessThan st(nxt);
while (Q--)
{
int l, r;
cin >> l >> r;
l--;
cout << r - l - st.cntLess(l, r, r) << '\n';
}
}
| C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using static util;
using P = pair<int, int>;
using Number = System.Int32;
class Program {
static void Main(string[] args) {
var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
var solver = new Solver(sw);
// var t = new Thread(solver.solve, 1 << 26); // 64 MB
// t.Start();
// t.Join();
solver.solve();
sw.Flush();
}
}
class Solver {
StreamWriter sw;
Scan sc;
void Prt(string a) => sw.WriteLine(a);
void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
void Prt(params object[] a) => Prt(string.Join(" ", a));
public Solver(StreamWriter sw) {
this.sw = sw;
this.sc = new Scan();
}
public void solve() {
int n, q;
sc.Multi(out n, out q);
var c = sc.IntArr.Select(x => x - 1).ToArray();
var lis = new List<int>[n];
var que = new List<P>[n];
for (int i = 0; i < n; i++)
{
lis[i] = new List<int>();
que[i] = new List<P>();
}
for (int i = 0; i < n; i++)
{
lis[c[i]].Add(i);
}
for (int i = 0; i < q; i++)
{
int l, r;
sc.Multi(out l, out r);
--l;
que[l].Add(new P(r, i));
}
var idx = new int[n];
var bit = new BIT(n);
for (int i = 0; i < n; i++)
{
if (lis[i].Count > 0) {
bit.add(lis[i][0], 1);
}
idx[i] = 1;
}
var ans = new int[q];
for (int i = 0; i < n; i++)
{
foreach (var item in que[i])
{
ans[item.v2] = bit.sum(i, item.v1);
}
if (idx[c[i]] < lis[c[i]].Count) {
bit.add(lis[c[i]][idx[c[i]]], 1);
++idx[c[i]];
}
}
foreach (var item in ans)
{
Prt(item);
}
}
}
class pair<T, U> : IComparable<pair<T, U>> {
public T v1;
public U v2;
public pair() : this(default(T), default(U)) {}
public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; }
public int CompareTo(pair<T, U> a) {
int c = Comparer<T>.Default.Compare(v1, a.v1);
return c != 0 ? c : Comparer<U>.Default.Compare(v2, a.v2);
}
public override string ToString() => v1 + " " + v2;
public void Deconstruct(out T a, out U b) { a = v1; b = v2; }
}
static class util {
public static readonly int M = 1000000007;
// public static readonly int M = 998244353;
public static readonly long LM = 1L << 60;
public static readonly double eps = 1e-11;
public static void DBG(string a) => Console.Error.WriteLine(a);
public static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
public static void DBG(params object[] a) => DBG(string.Join(" ", a));
public static void Assert(params bool[] conds) {
if (conds.Any(x => !x)) throw new Exception();
}
public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
public static int CompareList<T>(IList<T> a, IList<T> b) where T : IComparable<T> {
for (int i = 0; i < a.Count && i < b.Count; i++)
if (a[i].CompareTo(b[i]) != 0) return a[i].CompareTo(b[i]);
return a.Count.CompareTo(b.Count);
}
public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
public static readonly int[] dd = { 0, 1, 0, -1 };
// static readonly string dstring = "RDLU";
public static IEnumerable<P> adjacents(int i, int j)
=> Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1]));
public static IEnumerable<P> adjacents(int i, int j, int h, int w)
=> adjacents(i, j).Where(p => inside(p.v1, p.v2, h, w));
public static IEnumerable<P> adjacents(this P p) => adjacents(p.v1, p.v2);
public static IEnumerable<P> adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w);
public static IEnumerable<int> all_subset(this int p) {
for (int i = 0; ; i = i - p & p) {
yield return i;
if (i == p) break;
}
}
public static Dictionary<T, int> compress<T>(this IEnumerable<T> a)
=> a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i);
public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.SelectMany(x => x));
public static T[] inv<T>(this Dictionary<T, int> dic) {
var res = new T[dic.Count];
foreach (var item in dic) res[item.Value] = item.Key;
return res;
}
public static void swap<T>(ref T a, ref T b) where T : struct { var t = a; a = b; b = t; }
public static void swap<T>(this IList<T> a, int i, int j) where T : struct { var t = a[i]; a[i] = a[j]; a[j] = t; }
public static T[] copy<T>(this IList<T> a) {
var ret = new T[a.Count];
for (int i = 0; i < a.Count; i++) ret[i] = a[i];
return ret;
}
}
class Scan {
StreamReader sr;
public Scan() { sr = new StreamReader(Console.OpenStandardInput()); }
public Scan(string path) { sr = new StreamReader(path); }
public int Int => int.Parse(Str);
public long Long => long.Parse(Str);
public double Double => double.Parse(Str);
public string Str => sr.ReadLine().Trim();
public pair<T, U> Pair<T, U>() {
T a; U b;
Multi(out a, out b);
return new pair<T, U>(a, b);
}
public P P => Pair<int, int>();
public int[] IntArr => StrArr.Select(int.Parse).ToArray();
public long[] LongArr => StrArr.Select(long.Parse).ToArray();
public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
bool eq<T, U>() => typeof(T).Equals(typeof(U));
T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
: eq<T, long>() ? ct<T, long>(long.Parse(s))
: eq<T, double>() ? ct<T, double>(double.Parse(s))
: eq<T, char>() ? ct<T, char>(s[0])
: ct<T, string>(s);
public void Multi<T>(out T a) => a = cv<T>(Str);
public void Multi<T, U>(out T a, out U b) {
var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]);
}
public void Multi<T, U, V>(out T a, out U b, out V c) {
var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]);
}
public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d) {
var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]);
}
public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e) {
var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]);
}
}
class BIT {
int n;
Number[] bit;
public BIT(int n) {
this.n = n;
bit = new Number[n];
}
public void add(int j, Number w) {
for (int i = j; i < n; i |= i + 1) bit[i] += w;
}
public Number sum(int j) {
Number res = 0;
for (int i = j - 1; i >= 0; i = (i & i + 1) - 1) res += bit[i];
return res;
}
public Number sum(int j, int k) => sum(k) - sum(j);
}
| Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template <typename T> void ndarray(vector<T> &vec, int len) { vec.resize(len); }
template <typename T, typename... Args> void ndarray(vector<T> &vec, int len, Args... args) { vec.resize(len); for (auto &v : vec) ndarray(v, args...); }
template <typename V, typename T> void ndfill(V &x, const T &val) { x = val; }
template <typename V, typename T> void ndfill(vector<V> &vec, const T &val) { for (auto &v : vec) ndfill(v, val); }
template <typename T> bool chmax(T &m, const T q) { if (m < q) {m = q; return true;} else return false; }
template <typename T> bool chmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; }
template <typename T1, typename T2> pair<T1, T2> operator+(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first + r.first, l.second + r.second); }
template <typename T1, typename T2> pair<T1, T2> operator-(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first - r.first, l.second - r.second); }
template <typename T> vector<T> srtunq(vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; }
template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto &v : vec) is >> v; return is; }
template <typename... T> istream &operator>>(istream &is, tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename... T> ostream &operator<<(ostream &os, const tuple<T...> &tpl) { std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os; }
template <typename T> ostream &operator<<(ostream &os, const deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename T> ostream &operator<<(ostream &os, const set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const unordered_set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &pa) { os << '(' << pa.first << ',' << pa.second << ')'; return os; }
template <typename TK, typename TV> ostream &operator<<(ostream &os, const map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <typename TK, typename TV> ostream &operator<<(ostream &os, const unordered_map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#define dbg(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ") " << __FILE__ << endl;
// Count elements in [A_begin, ..., A_{end-1}] which satisfy A_i < query
// Complexity: O(N log^2 N) for initialization, O(log^2 N) for each query
// Verified: cntLess <https://codeforces.com/contest/1288/submission/68865506>
struct CountLessThan
{
using T = int;
int N;
int head;
vector<vector<T>> x;
inline void merge(int pos) {
x[pos] = x[pos * 2 + 1];
x[pos].insert(x[pos].end(), x[pos * 2 + 2].begin(), x[pos * 2 + 2].end());
sort(x[pos].begin(), x[pos].end());
}
int _getless(int begin, int end, int pos, int l, int r, T query) const {
if (r <= begin or l >= end) return 0;
if (l >= begin and r <= end) return lower_bound(x[pos].begin(), x[pos].end(), query) - x[pos].begin();
return _getless(begin, end, 2 * pos + 1, l, (l + r) / 2, query) + _getless(begin, end, 2 * pos + 2, (l + r) / 2, r, query);
}
int _getlesseq(int begin, int end, int pos, int l, int r, T query) const {
if (r <= begin or l >= end) return 0;
if (l >= begin and r <= end) return upper_bound(x[pos].begin(), x[pos].end(), query) - x[pos].begin();
return _getlesseq(begin, end, 2 * pos + 1, l, (l + r) / 2, query) + _getlesseq(begin, end, 2 * pos + 2, (l + r) / 2, r, query);
}
CountLessThan() = default;
CountLessThan(const vector<T> &vec) : N(vec.size()) {
int N_tmp = 1; while (N_tmp < N) N_tmp <<= 1;
x.resize(N_tmp*2), head = N_tmp - 1;
for (int i = 0; i < N; i++) x[head + i] = {vec[i]};
for (int i = head - 1; i >= 0; i--) merge(i);
}
int cntLess(int begin, int end, T query) const { return _getless(begin, end, 0, 0, (int)x.size() / 2, query); }
int cntLesseq(int begin, int end, T query) const { return _getlesseq(begin, end, 0, 0, (int)x.size() / 2, query); }
int cntMore(int begin, int end, T query) const {
int tot = max(0, min(end, N) - max(begin, 0));
return tot - cntLesseq(begin, end, query);
}
int cntMoreeq(int begin, int end, T query) const {
int tot = max(0, min(end, N) - max(begin, 0));
return tot - cntLess(begin, end, query);
}
friend ostream &operator<<(ostream &os, const CountLessThan &clt) {
os << '[';
for (int i = 0; i < clt.N; i++) os << clt.x[clt.head + i][0] << ',';
os << ']';
return os;
}
};
int main()
{
int N, Q;
cin >> N >> Q;
vector<int> C(N);
cin >> C;
vector<int> nxt(N, N);
map<int, int> last;
IREP(i, N)
{
if (last.count(C[i])) nxt[i] = last[C[i]];
last[C[i]] = i;
}
CountLessThan st(nxt);
while (Q--)
{
int l, r;
cin >> l >> r;
l--;
cout << r - l - st.cntLess(l, r, r) << '\n';
}
}
Code 2: using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using static util;
using P = pair<int, int>;
using Number = System.Int32;
class Program {
static void Main(string[] args) {
var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
var solver = new Solver(sw);
// var t = new Thread(solver.solve, 1 << 26); // 64 MB
// t.Start();
// t.Join();
solver.solve();
sw.Flush();
}
}
class Solver {
StreamWriter sw;
Scan sc;
void Prt(string a) => sw.WriteLine(a);
void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
void Prt(params object[] a) => Prt(string.Join(" ", a));
public Solver(StreamWriter sw) {
this.sw = sw;
this.sc = new Scan();
}
public void solve() {
int n, q;
sc.Multi(out n, out q);
var c = sc.IntArr.Select(x => x - 1).ToArray();
var lis = new List<int>[n];
var que = new List<P>[n];
for (int i = 0; i < n; i++)
{
lis[i] = new List<int>();
que[i] = new List<P>();
}
for (int i = 0; i < n; i++)
{
lis[c[i]].Add(i);
}
for (int i = 0; i < q; i++)
{
int l, r;
sc.Multi(out l, out r);
--l;
que[l].Add(new P(r, i));
}
var idx = new int[n];
var bit = new BIT(n);
for (int i = 0; i < n; i++)
{
if (lis[i].Count > 0) {
bit.add(lis[i][0], 1);
}
idx[i] = 1;
}
var ans = new int[q];
for (int i = 0; i < n; i++)
{
foreach (var item in que[i])
{
ans[item.v2] = bit.sum(i, item.v1);
}
if (idx[c[i]] < lis[c[i]].Count) {
bit.add(lis[c[i]][idx[c[i]]], 1);
++idx[c[i]];
}
}
foreach (var item in ans)
{
Prt(item);
}
}
}
class pair<T, U> : IComparable<pair<T, U>> {
public T v1;
public U v2;
public pair() : this(default(T), default(U)) {}
public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; }
public int CompareTo(pair<T, U> a) {
int c = Comparer<T>.Default.Compare(v1, a.v1);
return c != 0 ? c : Comparer<U>.Default.Compare(v2, a.v2);
}
public override string ToString() => v1 + " " + v2;
public void Deconstruct(out T a, out U b) { a = v1; b = v2; }
}
static class util {
public static readonly int M = 1000000007;
// public static readonly int M = 998244353;
public static readonly long LM = 1L << 60;
public static readonly double eps = 1e-11;
public static void DBG(string a) => Console.Error.WriteLine(a);
public static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
public static void DBG(params object[] a) => DBG(string.Join(" ", a));
public static void Assert(params bool[] conds) {
if (conds.Any(x => !x)) throw new Exception();
}
public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
public static int CompareList<T>(IList<T> a, IList<T> b) where T : IComparable<T> {
for (int i = 0; i < a.Count && i < b.Count; i++)
if (a[i].CompareTo(b[i]) != 0) return a[i].CompareTo(b[i]);
return a.Count.CompareTo(b.Count);
}
public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
public static readonly int[] dd = { 0, 1, 0, -1 };
// static readonly string dstring = "RDLU";
public static IEnumerable<P> adjacents(int i, int j)
=> Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1]));
public static IEnumerable<P> adjacents(int i, int j, int h, int w)
=> adjacents(i, j).Where(p => inside(p.v1, p.v2, h, w));
public static IEnumerable<P> adjacents(this P p) => adjacents(p.v1, p.v2);
public static IEnumerable<P> adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w);
public static IEnumerable<int> all_subset(this int p) {
for (int i = 0; ; i = i - p & p) {
yield return i;
if (i == p) break;
}
}
public static Dictionary<T, int> compress<T>(this IEnumerable<T> a)
=> a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i);
public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.SelectMany(x => x));
public static T[] inv<T>(this Dictionary<T, int> dic) {
var res = new T[dic.Count];
foreach (var item in dic) res[item.Value] = item.Key;
return res;
}
public static void swap<T>(ref T a, ref T b) where T : struct { var t = a; a = b; b = t; }
public static void swap<T>(this IList<T> a, int i, int j) where T : struct { var t = a[i]; a[i] = a[j]; a[j] = t; }
public static T[] copy<T>(this IList<T> a) {
var ret = new T[a.Count];
for (int i = 0; i < a.Count; i++) ret[i] = a[i];
return ret;
}
}
class Scan {
StreamReader sr;
public Scan() { sr = new StreamReader(Console.OpenStandardInput()); }
public Scan(string path) { sr = new StreamReader(path); }
public int Int => int.Parse(Str);
public long Long => long.Parse(Str);
public double Double => double.Parse(Str);
public string Str => sr.ReadLine().Trim();
public pair<T, U> Pair<T, U>() {
T a; U b;
Multi(out a, out b);
return new pair<T, U>(a, b);
}
public P P => Pair<int, int>();
public int[] IntArr => StrArr.Select(int.Parse).ToArray();
public long[] LongArr => StrArr.Select(long.Parse).ToArray();
public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
bool eq<T, U>() => typeof(T).Equals(typeof(U));
T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
: eq<T, long>() ? ct<T, long>(long.Parse(s))
: eq<T, double>() ? ct<T, double>(double.Parse(s))
: eq<T, char>() ? ct<T, char>(s[0])
: ct<T, string>(s);
public void Multi<T>(out T a) => a = cv<T>(Str);
public void Multi<T, U>(out T a, out U b) {
var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]);
}
public void Multi<T, U, V>(out T a, out U b, out V c) {
var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]);
}
public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d) {
var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]);
}
public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e) {
var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]);
}
}
class BIT {
int n;
Number[] bit;
public BIT(int n) {
this.n = n;
bit = new Number[n];
}
public void add(int j, Number w) {
for (int i = j; i < n; i |= i + 1) bit[i] += w;
}
public Number sum(int j) {
Number res = 0;
for (int i = j - 1; i >= 0; i = (i & i + 1) - 1) res += bit[i];
return res;
}
public Number sum(int j, int k) => sum(k) - sum(j);
}
|
Python | n = int(input())
a = []
for _ in range(n):
a.append(list(map(int, input().split())))
b = sorted(a, key = lambda x: (x[0], x[1]))
c = sorted(a, key = lambda x: (x[1], x[0]))
ans = 10**10
for i in range(n-1):
temp = (b[i+1][0]-b[i][0])**2 + (b[i+1][1]-b[i][1])**2
if ans > temp:
ans = temp
for i in range(n-1):
temp = (c[i+1][0]-c[i][0])**2 + (c[i+1][1]-c[i][1])**2
if ans > temp:
ans = temp
print(ans)
| C# | using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using static System.Math;
using System.Numerics;
static class Program{
const int mod=(int)1e9+7;
static int n;
static double d=double.MaxValue;
static void Main(){
Sc sc=new Sc();
n=sc.I;
var px=new Pair[n];
var py=new Pair[n];
for(int i = 0;i<n;i++) {
var e=sc.Da;
px[i]=new Pair(e[0],e[1]);
py[i]=new Pair(e[0],e[1]);
}
Array.Sort(px,(u,v)=>{var c=u.x.CompareTo(v.x);return c==0?u.y.CompareTo(v.y):c;});
Array.Sort(py,(u,v)=>{var c=u.y.CompareTo(v.y);return c==0?u.x.CompareTo(v.x):c;});
Fu(px,py);
Console.WriteLine("{0}",d*d);
}
static void Fu(Pair[] px,Pair[] py){
int l=px.Length>>1;
if(px.Length<=3){
d=Min(d,Fdc(px[0],px[1]));
if(px.Length==3){d=Min(d,Min(Fdc(px[0],px[2]),Fdc(px[1],px[2])));}
return;
}
var kx1=new Pair[l];
var ky1=new Pair[l];
var kx2=new Pair[px.Length-l];
var ky2=new Pair[px.Length-l];
for(int i=0,j1=0,j2=0;i<px.Length;i++){
if(i<kx1.Length){kx1[i]=px[i];}
else{kx2[i-kx1.Length]=px[i];}
if(py[i].x<px[l].x||(py[i].x==px[l].x&&py[i].y<px[l].y)){ky1[j1]=py[i];j1++;}
else{ky2[j2]=py[i];j2++;}
}
Fu(kx1,ky1);
Fu(kx2,ky2);
var li=new List<Pair>();
for(int i=0;i<py.Length;i++){
if(Abs(py[i].x-px[l].x)<=d){li.Add(py[i]);}
}
for(int i=0;i<li.Count;i++){
for(int j=i+1;j<i+8&&j<li.Count;j++){d=Min(d,Fdc(li[i],li[j]));}
}
}
static double Fdc(Pair a,Pair b){return Sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}
}
public struct Pair{
public double x,y;
public Pair(double x,double y){this.x=x;this.y=y;}
}
public class Sc{
public int I{get{return int.Parse(Console.ReadLine());}}
public long L{get{return long.Parse(Console.ReadLine());}}
public double D{get{return double.Parse(Console.ReadLine());}}
public string S{get{return Console.ReadLine();}}
public int[] Ia{get{return Array.ConvertAll(Console.ReadLine().Split(),int.Parse);}}
public long[] La{get{return Array.ConvertAll(Console.ReadLine().Split(),long.Parse);}}
public double[] Da{get{return Array.ConvertAll(Console.ReadLine().Split(),double.Parse);}}
public string[] Sa{get{return Console.ReadLine().Split();}}
public object[] Oa{get{return Console.ReadLine().Split();}}
public int[] Ia2{get{return Array.ConvertAll(("0 "+Console.ReadLine()+" 0").Split(),int.Parse);}}
public int[] Ia3(int a){return Array.ConvertAll((a.ToString()+" "+Console.ReadLine()).Split(),int.Parse);}
public int[] Ia3(bool a,int b,bool c,int d){return Array.ConvertAll(((a?b.ToString()+" ":"")+Console.ReadLine()+(c?" "+d.ToString():"")).Split(),int.Parse);}
public long[] La2{get{return Array.ConvertAll(("0 "+Console.ReadLine()+" 0").Split(),long.Parse);}}
public long[] La3(int a){return Array.ConvertAll((a.ToString()+" "+Console.ReadLine()).Split(),long.Parse);}
public long[] La3(bool a,int b,bool c,int d){return Array.ConvertAll(((a?b.ToString()+" ":"")+Console.ReadLine()+(c?" "+d.ToString():"")).Split(),long.Parse);}
public T[] Arr<T>(int n,Func<T> f){var a=new T[n];for(int i=0;i<n;i++){a[i]=f();}return a;}
public T[] Arr<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;}
public T[] Arr<T>(int n,Func<string[],T> f){var a=new T[n];for(int i=0;i<n;i++){a[i]=f(Console.ReadLine().Split());}return a;}
public T[] Arr<T>(int n,Func<int,string[],T> f){var a=new T[n];for(int i=0;i<n;i++){a[i]=f(i,Console.ReadLine().Split());}return a;}
}
| Yes | Do these codes solve the same problem?
Code 1: n = int(input())
a = []
for _ in range(n):
a.append(list(map(int, input().split())))
b = sorted(a, key = lambda x: (x[0], x[1]))
c = sorted(a, key = lambda x: (x[1], x[0]))
ans = 10**10
for i in range(n-1):
temp = (b[i+1][0]-b[i][0])**2 + (b[i+1][1]-b[i][1])**2
if ans > temp:
ans = temp
for i in range(n-1):
temp = (c[i+1][0]-c[i][0])**2 + (c[i+1][1]-c[i][1])**2
if ans > temp:
ans = temp
print(ans)
Code 2: using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using static System.Math;
using System.Numerics;
static class Program{
const int mod=(int)1e9+7;
static int n;
static double d=double.MaxValue;
static void Main(){
Sc sc=new Sc();
n=sc.I;
var px=new Pair[n];
var py=new Pair[n];
for(int i = 0;i<n;i++) {
var e=sc.Da;
px[i]=new Pair(e[0],e[1]);
py[i]=new Pair(e[0],e[1]);
}
Array.Sort(px,(u,v)=>{var c=u.x.CompareTo(v.x);return c==0?u.y.CompareTo(v.y):c;});
Array.Sort(py,(u,v)=>{var c=u.y.CompareTo(v.y);return c==0?u.x.CompareTo(v.x):c;});
Fu(px,py);
Console.WriteLine("{0}",d*d);
}
static void Fu(Pair[] px,Pair[] py){
int l=px.Length>>1;
if(px.Length<=3){
d=Min(d,Fdc(px[0],px[1]));
if(px.Length==3){d=Min(d,Min(Fdc(px[0],px[2]),Fdc(px[1],px[2])));}
return;
}
var kx1=new Pair[l];
var ky1=new Pair[l];
var kx2=new Pair[px.Length-l];
var ky2=new Pair[px.Length-l];
for(int i=0,j1=0,j2=0;i<px.Length;i++){
if(i<kx1.Length){kx1[i]=px[i];}
else{kx2[i-kx1.Length]=px[i];}
if(py[i].x<px[l].x||(py[i].x==px[l].x&&py[i].y<px[l].y)){ky1[j1]=py[i];j1++;}
else{ky2[j2]=py[i];j2++;}
}
Fu(kx1,ky1);
Fu(kx2,ky2);
var li=new List<Pair>();
for(int i=0;i<py.Length;i++){
if(Abs(py[i].x-px[l].x)<=d){li.Add(py[i]);}
}
for(int i=0;i<li.Count;i++){
for(int j=i+1;j<i+8&&j<li.Count;j++){d=Min(d,Fdc(li[i],li[j]));}
}
}
static double Fdc(Pair a,Pair b){return Sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));}
}
public struct Pair{
public double x,y;
public Pair(double x,double y){this.x=x;this.y=y;}
}
public class Sc{
public int I{get{return int.Parse(Console.ReadLine());}}
public long L{get{return long.Parse(Console.ReadLine());}}
public double D{get{return double.Parse(Console.ReadLine());}}
public string S{get{return Console.ReadLine();}}
public int[] Ia{get{return Array.ConvertAll(Console.ReadLine().Split(),int.Parse);}}
public long[] La{get{return Array.ConvertAll(Console.ReadLine().Split(),long.Parse);}}
public double[] Da{get{return Array.ConvertAll(Console.ReadLine().Split(),double.Parse);}}
public string[] Sa{get{return Console.ReadLine().Split();}}
public object[] Oa{get{return Console.ReadLine().Split();}}
public int[] Ia2{get{return Array.ConvertAll(("0 "+Console.ReadLine()+" 0").Split(),int.Parse);}}
public int[] Ia3(int a){return Array.ConvertAll((a.ToString()+" "+Console.ReadLine()).Split(),int.Parse);}
public int[] Ia3(bool a,int b,bool c,int d){return Array.ConvertAll(((a?b.ToString()+" ":"")+Console.ReadLine()+(c?" "+d.ToString():"")).Split(),int.Parse);}
public long[] La2{get{return Array.ConvertAll(("0 "+Console.ReadLine()+" 0").Split(),long.Parse);}}
public long[] La3(int a){return Array.ConvertAll((a.ToString()+" "+Console.ReadLine()).Split(),long.Parse);}
public long[] La3(bool a,int b,bool c,int d){return Array.ConvertAll(((a?b.ToString()+" ":"")+Console.ReadLine()+(c?" "+d.ToString():"")).Split(),long.Parse);}
public T[] Arr<T>(int n,Func<T> f){var a=new T[n];for(int i=0;i<n;i++){a[i]=f();}return a;}
public T[] Arr<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;}
public T[] Arr<T>(int n,Func<string[],T> f){var a=new T[n];for(int i=0;i<n;i++){a[i]=f(Console.ReadLine().Split());}return a;}
public T[] Arr<T>(int n,Func<int,string[],T> f){var a=new T[n];for(int i=0;i<n;i++){a[i]=f(i,Console.ReadLine().Split());}return a;}
}
|
JavaScript | function Main(s){
s = s.split("\n");
var n = s[0].split(" ").map(a=>+a);
var m = n[1];
var q = n[2] - 1;
var t = n[3] - 1;
n = n[0];
var u = [], v = [], a = [], b = [];
for(var i = 0; i < m; i++){
var z = s[i+1].split(" ").map(a=>+a);
u[i] = z[0] - 1; v[i] = z[1] - 1; a[i] = z[2]; b[i] = z[3];
}
var c = dijkstra(u,v,a,q,n);
var d = dijkstra(u,v,b,t,n);
var e = [];
i = n - 1;
e[i] = 1e15 - c[i] - d[i];
for(;i--;)e[i] = Math.max(e[i+1], 1e15 - c[i] - d[i]);
console.log(e.join("\n"));
}
function dijkstra(a,b,c,s,k){
var t = Array(k).fill(0).map(a=>[]);
for(var i = 0; i < a.length; i++)t[a[i]][b[i]] = t[b[i]][a[i]] = c[i];
var r = Array(k).fill(9e99); r[s] = 0;
var f = Array(k).fill(0);
var pq = new PriorityQueue();
pq.push([s,0]);
while(pq.size()){
var x = pq.pop();
if(f[x])continue;
f[x] = 1;
for(i in t[x]){
if(r[i] <= r[x] + t[x][i])continue;
r[i] = r[x] + t[x][i];
pq.push([i,r[i]]);
}
}
return r;
}
var PriorityQueue = function() {
this.heap = new Array();
this.pointer = 0;
};
PriorityQueue.prototype = {
push : function(x) {
var i = this.pointer++;
while (i > 0) {
//親ノードの番号を求める
var p = Math.floor((i - 1) / 2);
//もう逆転してなければ処理を打ち切る
if (this.heap[p][1] <= x[1]) break;
this.heap[i] = this.heap[p];
i = p;
}
this.heap[i] = x;
},
pop : function() {
var ret = this.heap[0];
var x = this.heap[--this.pointer];
var i = 0;
//子ノードがなくなるまでループ
while (i * 2 + 1 < this.pointer) {
var a = i * 2 + 1; //左子ノード
var b = i * 2 + 2; //右子ノード
if (b < this.pointer && this.heap[b][1] < this.heap[a][1]) a = b;
//もう逆転してなければ処理を打ち切る
if (this.heap[a][1] >= x[1]) break;
this.heap[i] = this.heap[a];
i = a;
}
this.heap[i] = x;
//最終ノードを削除する
this.heap.pop();
return ret[0];
},
size : function() {
return this.heap.length;
}
};
Main(require("fs").readFileSync("/dev/stdin","utf8")); | Kotlin | import java.util.PriorityQueue
data class Edge(val from: Int, val to: Int, val cost: Long)
data class State(val v: Int, val cost: Long)
fun compareState(s1: State, s2: State): Int {
if (s1.cost > s2.cost) return 1
if (s1.cost < s2.cost) return -1
return 0
}
fun shortestPath(graph: Array<MutableList<Edge>>, s: Int): LongArray {
val n = graph.size
// Dijkstra from s
// Kotlin 1.0 workaround.
val pq = PriorityQueue<State>(11, { s1: State, s2: State -> compareState(s1, s2) })
val dist = LongArray(n, { Long.MAX_VALUE })
dist[s] = 0
pq.add(State(s, 0L))
while (pq.isNotEmpty()) {
val state = pq.poll()!!
if (dist[state.v] < state.cost) continue
for (e in graph[state.v]) {
if (state.cost + e.cost < dist[e.to]) {
dist[e.to] = state.cost + e.cost
pq.add(State(e.to, state.cost + e.cost))
}
}
}
return dist
}
fun main(args: Array<String>) {
val (n, m, sRaw, tRaw) = readLine()!!.split(" ").map { it.toInt() }
val s = sRaw - 1
val t = tRaw - 1
val aGraph = Array(n, { mutableListOf<Edge>() })
val bGraph = Array(n, { mutableListOf<Edge>() })
repeat(m) {
val (uRaw, vRaw, a, b) = readLine()!!.split(" ").map { it.toInt() }
val u = uRaw - 1
val v = vRaw - 1
aGraph[u].add(Edge(u, v, a.toLong()))
aGraph[v].add(Edge(v, u, a.toLong()))
bGraph[u].add(Edge(u, v, b.toLong()))
bGraph[v].add(Edge(v, u, b.toLong()))
}
val distArrayA = shortestPath(aGraph, s)
val distArrayB = shortestPath(bGraph, t)
val costs = mutableListOf<Long>()
var currentCost = Long.MAX_VALUE
for (i in n - 1 downTo 0) {
currentCost = Math.min(currentCost, distArrayA[i] + distArrayB[i])
costs.add(currentCost)
}
costs.reverse()
val output = StringBuilder()
for (cost in costs) {
output.append(1000000000000000L - cost)
output.append('\n')
}
print(output)
} | Yes | Do these codes solve the same problem?
Code 1: function Main(s){
s = s.split("\n");
var n = s[0].split(" ").map(a=>+a);
var m = n[1];
var q = n[2] - 1;
var t = n[3] - 1;
n = n[0];
var u = [], v = [], a = [], b = [];
for(var i = 0; i < m; i++){
var z = s[i+1].split(" ").map(a=>+a);
u[i] = z[0] - 1; v[i] = z[1] - 1; a[i] = z[2]; b[i] = z[3];
}
var c = dijkstra(u,v,a,q,n);
var d = dijkstra(u,v,b,t,n);
var e = [];
i = n - 1;
e[i] = 1e15 - c[i] - d[i];
for(;i--;)e[i] = Math.max(e[i+1], 1e15 - c[i] - d[i]);
console.log(e.join("\n"));
}
function dijkstra(a,b,c,s,k){
var t = Array(k).fill(0).map(a=>[]);
for(var i = 0; i < a.length; i++)t[a[i]][b[i]] = t[b[i]][a[i]] = c[i];
var r = Array(k).fill(9e99); r[s] = 0;
var f = Array(k).fill(0);
var pq = new PriorityQueue();
pq.push([s,0]);
while(pq.size()){
var x = pq.pop();
if(f[x])continue;
f[x] = 1;
for(i in t[x]){
if(r[i] <= r[x] + t[x][i])continue;
r[i] = r[x] + t[x][i];
pq.push([i,r[i]]);
}
}
return r;
}
var PriorityQueue = function() {
this.heap = new Array();
this.pointer = 0;
};
PriorityQueue.prototype = {
push : function(x) {
var i = this.pointer++;
while (i > 0) {
//親ノードの番号を求める
var p = Math.floor((i - 1) / 2);
//もう逆転してなければ処理を打ち切る
if (this.heap[p][1] <= x[1]) break;
this.heap[i] = this.heap[p];
i = p;
}
this.heap[i] = x;
},
pop : function() {
var ret = this.heap[0];
var x = this.heap[--this.pointer];
var i = 0;
//子ノードがなくなるまでループ
while (i * 2 + 1 < this.pointer) {
var a = i * 2 + 1; //左子ノード
var b = i * 2 + 2; //右子ノード
if (b < this.pointer && this.heap[b][1] < this.heap[a][1]) a = b;
//もう逆転してなければ処理を打ち切る
if (this.heap[a][1] >= x[1]) break;
this.heap[i] = this.heap[a];
i = a;
}
this.heap[i] = x;
//最終ノードを削除する
this.heap.pop();
return ret[0];
},
size : function() {
return this.heap.length;
}
};
Main(require("fs").readFileSync("/dev/stdin","utf8"));
Code 2: import java.util.PriorityQueue
data class Edge(val from: Int, val to: Int, val cost: Long)
data class State(val v: Int, val cost: Long)
fun compareState(s1: State, s2: State): Int {
if (s1.cost > s2.cost) return 1
if (s1.cost < s2.cost) return -1
return 0
}
fun shortestPath(graph: Array<MutableList<Edge>>, s: Int): LongArray {
val n = graph.size
// Dijkstra from s
// Kotlin 1.0 workaround.
val pq = PriorityQueue<State>(11, { s1: State, s2: State -> compareState(s1, s2) })
val dist = LongArray(n, { Long.MAX_VALUE })
dist[s] = 0
pq.add(State(s, 0L))
while (pq.isNotEmpty()) {
val state = pq.poll()!!
if (dist[state.v] < state.cost) continue
for (e in graph[state.v]) {
if (state.cost + e.cost < dist[e.to]) {
dist[e.to] = state.cost + e.cost
pq.add(State(e.to, state.cost + e.cost))
}
}
}
return dist
}
fun main(args: Array<String>) {
val (n, m, sRaw, tRaw) = readLine()!!.split(" ").map { it.toInt() }
val s = sRaw - 1
val t = tRaw - 1
val aGraph = Array(n, { mutableListOf<Edge>() })
val bGraph = Array(n, { mutableListOf<Edge>() })
repeat(m) {
val (uRaw, vRaw, a, b) = readLine()!!.split(" ").map { it.toInt() }
val u = uRaw - 1
val v = vRaw - 1
aGraph[u].add(Edge(u, v, a.toLong()))
aGraph[v].add(Edge(v, u, a.toLong()))
bGraph[u].add(Edge(u, v, b.toLong()))
bGraph[v].add(Edge(v, u, b.toLong()))
}
val distArrayA = shortestPath(aGraph, s)
val distArrayB = shortestPath(bGraph, t)
val costs = mutableListOf<Long>()
var currentCost = Long.MAX_VALUE
for (i in n - 1 downTo 0) {
currentCost = Math.min(currentCost, distArrayA[i] + distArrayB[i])
costs.add(currentCost)
}
costs.reverse()
val output = StringBuilder()
for (cost in costs) {
output.append(1000000000000000L - cost)
output.append('\n')
}
print(output)
} |
C++ | #include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
typedef pair<int,int> P;
int main() {
int n,m;
cin >> n >> m;
vector<P> v[n];
for(int i=0; i<m; i++) {
int x,y,z;
cin >> x >> y >> z;
x--,y--;
v[x].push_back(P(y,z));
v[y].push_back(P(x,z));
}
int M=0,cnt=0;
bool u[n];
memset(u,0,sizeof(u));
for(int k=0; k<n; k++) {
int d[n];
fill(d,d+n,1<<29);
d[k]=0;
vector<int> w[n];
priority_queue<P,vector<P>,greater<P> > que;
que.push(P(0,k));
while(!que.empty()) {
P p=que.top();que.pop();
int x=p.S,c=p.F;
if(d[x]<c) continue;
if(c>M) {
M=c;
memset(u,0,sizeof(u));
}
for(int i=0; i<v[x].size(); i++) {
int y=v[x][i].F,cc=v[x][i].S;
if(d[y]>d[x]+cc) {
d[y]=d[x]+cc;
que.push(P(d[y],y));
w[y].clear();
}
if(d[y]==d[x]+cc) w[y].push_back(x);
}
}
bool uu[n];
memset(uu,0,sizeof(uu));
queue<int> q;
for(int i=0; i<n; i++) {
if(d[i]==M) {
uu[i]=1;
q.push(i);
}
}
while(!q.empty()) {
int x=q.front();q.pop();
for(int i=0; i<w[x].size(); i++) {
int y=w[x][i];
if(uu[y]) continue;
uu[y]=1;
q.push(y);
}
}
for(int i=0; i<n; i++) u[i]|=uu[i];
}
for(int i=0; i<n; i++) if(!u[i]) cnt++;
cout << cnt << endl;
for(int i=0; i<n; i++) if(!u[i]) cout << i+1 << endl;
return 0;
}
| Python | from heapq import heappush, heappop
from collections import deque
n, r = map(int, input().split())
G = [[] for i in range(n)]
for i in range(r):
s, t, d = map(int, input().split())
G[s-1].append((t-1, d))
G[t-1].append((s-1, d))
INF = 10**18
def dijkstra(s):
dist = [INF]*n
dist[s] = 0
que = [(0, s)]
while que:
cost, s = heappop(que)
if dist[s] < cost:
continue
for t, d in G[s]:
if cost + d < dist[t]:
dist[t] = cost + d
heappush(que, (cost + d, t))
ma = max(dist)
assert ma != INF
goal = [i for i in range(n) if dist[i] == ma]
used = set(goal)
deq = deque(goal)
while deq:
s = deq.popleft()
for t, d in G[s]:
if dist[t] + d == dist[s] and t not in used:
used.add(t)
deq.append(t)
return ma, used
A = [dijkstra(s) for s in range(n)]
B = max(ma for ma, used in A)
ans = {i for i in range(n)}
for ma, used in A:
if ma == B:
ans -= used
print(len(ans))
for e in sorted(ans):
print(e+1) | Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
typedef pair<int,int> P;
int main() {
int n,m;
cin >> n >> m;
vector<P> v[n];
for(int i=0; i<m; i++) {
int x,y,z;
cin >> x >> y >> z;
x--,y--;
v[x].push_back(P(y,z));
v[y].push_back(P(x,z));
}
int M=0,cnt=0;
bool u[n];
memset(u,0,sizeof(u));
for(int k=0; k<n; k++) {
int d[n];
fill(d,d+n,1<<29);
d[k]=0;
vector<int> w[n];
priority_queue<P,vector<P>,greater<P> > que;
que.push(P(0,k));
while(!que.empty()) {
P p=que.top();que.pop();
int x=p.S,c=p.F;
if(d[x]<c) continue;
if(c>M) {
M=c;
memset(u,0,sizeof(u));
}
for(int i=0; i<v[x].size(); i++) {
int y=v[x][i].F,cc=v[x][i].S;
if(d[y]>d[x]+cc) {
d[y]=d[x]+cc;
que.push(P(d[y],y));
w[y].clear();
}
if(d[y]==d[x]+cc) w[y].push_back(x);
}
}
bool uu[n];
memset(uu,0,sizeof(uu));
queue<int> q;
for(int i=0; i<n; i++) {
if(d[i]==M) {
uu[i]=1;
q.push(i);
}
}
while(!q.empty()) {
int x=q.front();q.pop();
for(int i=0; i<w[x].size(); i++) {
int y=w[x][i];
if(uu[y]) continue;
uu[y]=1;
q.push(y);
}
}
for(int i=0; i<n; i++) u[i]|=uu[i];
}
for(int i=0; i<n; i++) if(!u[i]) cnt++;
cout << cnt << endl;
for(int i=0; i<n; i++) if(!u[i]) cout << i+1 << endl;
return 0;
}
Code 2: from heapq import heappush, heappop
from collections import deque
n, r = map(int, input().split())
G = [[] for i in range(n)]
for i in range(r):
s, t, d = map(int, input().split())
G[s-1].append((t-1, d))
G[t-1].append((s-1, d))
INF = 10**18
def dijkstra(s):
dist = [INF]*n
dist[s] = 0
que = [(0, s)]
while que:
cost, s = heappop(que)
if dist[s] < cost:
continue
for t, d in G[s]:
if cost + d < dist[t]:
dist[t] = cost + d
heappush(que, (cost + d, t))
ma = max(dist)
assert ma != INF
goal = [i for i in range(n) if dist[i] == ma]
used = set(goal)
deq = deque(goal)
while deq:
s = deq.popleft()
for t, d in G[s]:
if dist[t] + d == dist[s] and t not in used:
used.add(t)
deq.append(t)
return ma, used
A = [dijkstra(s) for s in range(n)]
B = max(ma for ma, used in A)
ans = {i for i in range(n)}
for ma, used in A:
if ma == B:
ans -= used
print(len(ans))
for e in sorted(ans):
print(e+1) |
C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace ABC134C
{
class Program
{
static void Main(string[] args)
{
var N = int.Parse(Console.ReadLine());
var conds = new List<int>(N);
for (var i = 1; i <= N; i++)
conds.Add(int.Parse(Console.ReadLine()));
var max = conds.Max();
var tmp = conds.ToList();
tmp.Sort((a, b) => b - a);
for (var i = 0; i < N; i++)
{
if (conds[i] == max)
Console.WriteLine(tmp[1]);
else
Console.WriteLine(max);
}
}
}
} | Python | N, T = (int(i) for i in input().split())
A = [int(i) for i in input().split()]
print(T + sum(min(A[i + 1] - A[i], T) for i in range(N - 1))) | No | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
using System.Linq;
namespace ABC134C
{
class Program
{
static void Main(string[] args)
{
var N = int.Parse(Console.ReadLine());
var conds = new List<int>(N);
for (var i = 1; i <= N; i++)
conds.Add(int.Parse(Console.ReadLine()));
var max = conds.Max();
var tmp = conds.ToList();
tmp.Sort((a, b) => b - a);
for (var i = 0; i < N; i++)
{
if (conds[i] == max)
Console.WriteLine(tmp[1]);
else
Console.WriteLine(max);
}
}
}
}
Code 2: N, T = (int(i) for i in input().split())
A = [int(i) for i in input().split()]
print(T + sum(min(A[i + 1] - A[i], T) for i in range(N - 1))) |
C# | using static System.Math;
using System;
class M
{
private const int MOD = 1000000007;
private readonly int[] _f;
public int Mul(int a, int b) => (int)(BigMul(a, b) % MOD);
public M(int n)
{
_f = new int[n + 1];
_f[0] = 1;
for (int i = 1; i <= n; ++i)
_f[i] = Mul(_f[i - 1], i);
}
public int Fac(int n) => _f[n];
public int Pow(int a, int m)
{
if (m == 0) return 1;
else if (m == 1) return a;
var p1 = Pow(a, m / 2);
var p2 = Mul(p1, p1);
return ((m % 2) == 0) ? p2 : Mul(p2, a);
}
public int Div(int a, int b) => Mul(a, Pow(b, MOD - 2));
public int Ncr(int n, int r)
{
if (n < r) return 0;
if (n == r) return 1;
var res = Fac(n);
res = Div(res, Fac(r));
res = Div(res, Fac(n - r));
return res;
}
}
public class hello
{
public static void Main()
{
string[] line = Console.ReadLine().Trim().Split(' ');
var n = int.Parse(line[0]);
var k = int.Parse(line[1]);
var md = new M(n + k);
if (n > k) { Console.WriteLine(0); goto exit; }
var ans = md.Ncr(k, n);
Console.WriteLine(ans);
exit:;
}
}
| Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
var scanner = bufio.NewScanner(os.Stdin)
func nextString() string {
scanner.Scan()
return scanner.Text()
}
func nextInt() int {
n, err := strconv.Atoi(nextString())
if err != nil {
fmt.Printf("strconv.Atoi failed: %v\n", err)
}
return n
}
func getCombinationTable(n, k, p int) [][]int {
table := make([][]int, n+1)
table[0] = make([]int, k+1)
table[0][0] = 1
for i := 1; i <= n; i++ {
table[i] = make([]int, k+1)
table[i][0] = 1
for j := 1; j <= k; j++ {
table[i][j] = (table[i-1][j] + table[i-1][j-1]) % p
}
}
return table
}
func main() {
scanner.Split(bufio.ScanWords)
prime := 1000000000 + 7
nBalls := nextInt()
nBoxes := nextInt()
table := getCombinationTable(nBoxes, nBalls, prime)
fmt.Println(table[nBoxes][nBalls])
}
| Yes | Do these codes solve the same problem?
Code 1: using static System.Math;
using System;
class M
{
private const int MOD = 1000000007;
private readonly int[] _f;
public int Mul(int a, int b) => (int)(BigMul(a, b) % MOD);
public M(int n)
{
_f = new int[n + 1];
_f[0] = 1;
for (int i = 1; i <= n; ++i)
_f[i] = Mul(_f[i - 1], i);
}
public int Fac(int n) => _f[n];
public int Pow(int a, int m)
{
if (m == 0) return 1;
else if (m == 1) return a;
var p1 = Pow(a, m / 2);
var p2 = Mul(p1, p1);
return ((m % 2) == 0) ? p2 : Mul(p2, a);
}
public int Div(int a, int b) => Mul(a, Pow(b, MOD - 2));
public int Ncr(int n, int r)
{
if (n < r) return 0;
if (n == r) return 1;
var res = Fac(n);
res = Div(res, Fac(r));
res = Div(res, Fac(n - r));
return res;
}
}
public class hello
{
public static void Main()
{
string[] line = Console.ReadLine().Trim().Split(' ');
var n = int.Parse(line[0]);
var k = int.Parse(line[1]);
var md = new M(n + k);
if (n > k) { Console.WriteLine(0); goto exit; }
var ans = md.Ncr(k, n);
Console.WriteLine(ans);
exit:;
}
}
Code 2: package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
var scanner = bufio.NewScanner(os.Stdin)
func nextString() string {
scanner.Scan()
return scanner.Text()
}
func nextInt() int {
n, err := strconv.Atoi(nextString())
if err != nil {
fmt.Printf("strconv.Atoi failed: %v\n", err)
}
return n
}
func getCombinationTable(n, k, p int) [][]int {
table := make([][]int, n+1)
table[0] = make([]int, k+1)
table[0][0] = 1
for i := 1; i <= n; i++ {
table[i] = make([]int, k+1)
table[i][0] = 1
for j := 1; j <= k; j++ {
table[i][j] = (table[i-1][j] + table[i-1][j-1]) % p
}
}
return table
}
func main() {
scanner.Split(bufio.ScanWords)
prime := 1000000000 + 7
nBalls := nextInt()
nBoxes := nextInt()
table := getCombinationTable(nBoxes, nBalls, prime)
fmt.Println(table[nBoxes][nBalls])
}
|
C++ | #include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <numeric>
#include <utility>
#include <iomanip>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
typedef vector<int> vint;
typedef vector<long long> vll;
typedef pair<int,int> pint;
typedef pair<long long, long long> pll;
#define MP make_pair
#define PB push_back
#define ALL(s) (s).begin(),(s).end()
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define COUT(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << endl
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; }
template<class T1, class T2> ostream& operator << (ostream &s, pair<T1,T2> P)
{ return s << '<' << P.first << ", " << P.second << '>'; }
template<class T> ostream& operator << (ostream &s, vector<T> P)
{ for (int i = 0; i < P.size(); ++i) { if (i > 0) { s << " "; } s << P[i]; } return s << endl; }
template<class T1, class T2> ostream& operator << (ostream &s, map<T1,T2> P)
{ EACH(it, P) { s << "<" << it->first << "->" << it->second << "> "; } return s << endl; }
string str;
set<vint> se;
int main() {
se.clear();
int j[4];
for (int i = 1; i <= 9; ++i) {
for (j[0] = 1; j[0] <= 16; ++j[0]) {
for (j[1] = 1; j[1] <= 16; ++j[1]) {
for (j[2] = 1; j[2] <= 16; ++j[2]) {
for (j[3] = 1; j[3] <= 16; ++j[3]) {
vint tmp(9, 0);
tmp[i-1] = 2;
for (int k = 0; k < 4; ++k) {
if (j[k] <= 9) tmp[j[k]-1] += 3;
else {
tmp[j[k]-10]++;
tmp[j[k]-9]++;
tmp[j[k]-8]++;
}
}
bool check = true;
for (int l = 0; l < 9; ++l) if (tmp[l] > 4) check = false;
if (check) se.insert(tmp);
}
}
}
}
}
while (cin >> str) {
vint vec(9, 0);
for (int i = 0; i < str.size(); ++i) vec[ str[i]-'1' ]++;
vint res;
for (int add = 1; add <= 9; ++add) {
vint tmp = vec;
tmp[add-1]++;
if (se.count(tmp)) res.PB(add);
}
if (res.size() == 0) cout << "0";
else {
for (int i = 0; i < res.size(); ++i) {
cout << res[i];
if (i != res.size()-1) cout << " ";
}
}
cout << endl;
}
return 0;
}
| PHP | <?php
while (true) {
fscanf(STDIN, '%s', $nums);
if (feof(STDIN)) {
break;
}
$nums = str_split($nums);
for ($i = 0; $i < 13; $i++) {
$nums[$i] = (int) $nums[$i];
}
$result = array();
for ($i = 1; $i <= 9; $i++) {
$a = $nums;
$a[] = $i;
sort($a);
$hash = array();
foreach ($a as $v) {
if (!isset($hash[$v])) {
$hash[$v] = 0;
}
$hash[$v]++;
}
if ($hash[$i] > 4) {
continue;
}
$stack = array(array($hash, false));
while (count($stack)) {
$node = array_pop($stack);
$h = update($node[0]);
$f = $node[1];
if (count($h) === 0) {
$result[] = $i;
break;
}
$keys = array_keys($h);
if (!$f && $h[$keys[0]] >= 2) {
$t = $h;
$t[$keys[0]] -= 2;
$stack[] = array($t, true);
}
if ($h[$keys[0]] >= 3) {
$t = $h;
$t[$keys[0]] -= 3;
$stack[] = array($t, $f);
}
if (isset($keys[2]) && $keys[2] - $keys[0] === 2) {
for ($j = 0; $j < 3; $j++) {
$h[$keys[$j]]--;
}
$stack[] = array($h, $f);
}
}
}
echo count($result) > 0 ? implode(' ', $result) : 0;
echo PHP_EOL;
}
function update($nums) {
foreach ($nums as $k => $v) {
if ($v === 0) {
unset($nums[$k]);
}
}
return $nums;
} | Yes | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <numeric>
#include <utility>
#include <iomanip>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
typedef vector<int> vint;
typedef vector<long long> vll;
typedef pair<int,int> pint;
typedef pair<long long, long long> pll;
#define MP make_pair
#define PB push_back
#define ALL(s) (s).begin(),(s).end()
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define COUT(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << endl
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; }
template<class T1, class T2> ostream& operator << (ostream &s, pair<T1,T2> P)
{ return s << '<' << P.first << ", " << P.second << '>'; }
template<class T> ostream& operator << (ostream &s, vector<T> P)
{ for (int i = 0; i < P.size(); ++i) { if (i > 0) { s << " "; } s << P[i]; } return s << endl; }
template<class T1, class T2> ostream& operator << (ostream &s, map<T1,T2> P)
{ EACH(it, P) { s << "<" << it->first << "->" << it->second << "> "; } return s << endl; }
string str;
set<vint> se;
int main() {
se.clear();
int j[4];
for (int i = 1; i <= 9; ++i) {
for (j[0] = 1; j[0] <= 16; ++j[0]) {
for (j[1] = 1; j[1] <= 16; ++j[1]) {
for (j[2] = 1; j[2] <= 16; ++j[2]) {
for (j[3] = 1; j[3] <= 16; ++j[3]) {
vint tmp(9, 0);
tmp[i-1] = 2;
for (int k = 0; k < 4; ++k) {
if (j[k] <= 9) tmp[j[k]-1] += 3;
else {
tmp[j[k]-10]++;
tmp[j[k]-9]++;
tmp[j[k]-8]++;
}
}
bool check = true;
for (int l = 0; l < 9; ++l) if (tmp[l] > 4) check = false;
if (check) se.insert(tmp);
}
}
}
}
}
while (cin >> str) {
vint vec(9, 0);
for (int i = 0; i < str.size(); ++i) vec[ str[i]-'1' ]++;
vint res;
for (int add = 1; add <= 9; ++add) {
vint tmp = vec;
tmp[add-1]++;
if (se.count(tmp)) res.PB(add);
}
if (res.size() == 0) cout << "0";
else {
for (int i = 0; i < res.size(); ++i) {
cout << res[i];
if (i != res.size()-1) cout << " ";
}
}
cout << endl;
}
return 0;
}
Code 2: <?php
while (true) {
fscanf(STDIN, '%s', $nums);
if (feof(STDIN)) {
break;
}
$nums = str_split($nums);
for ($i = 0; $i < 13; $i++) {
$nums[$i] = (int) $nums[$i];
}
$result = array();
for ($i = 1; $i <= 9; $i++) {
$a = $nums;
$a[] = $i;
sort($a);
$hash = array();
foreach ($a as $v) {
if (!isset($hash[$v])) {
$hash[$v] = 0;
}
$hash[$v]++;
}
if ($hash[$i] > 4) {
continue;
}
$stack = array(array($hash, false));
while (count($stack)) {
$node = array_pop($stack);
$h = update($node[0]);
$f = $node[1];
if (count($h) === 0) {
$result[] = $i;
break;
}
$keys = array_keys($h);
if (!$f && $h[$keys[0]] >= 2) {
$t = $h;
$t[$keys[0]] -= 2;
$stack[] = array($t, true);
}
if ($h[$keys[0]] >= 3) {
$t = $h;
$t[$keys[0]] -= 3;
$stack[] = array($t, $f);
}
if (isset($keys[2]) && $keys[2] - $keys[0] === 2) {
for ($j = 0; $j < 3; $j++) {
$h[$keys[$j]]--;
}
$stack[] = array($h, $f);
}
}
}
echo count($result) > 0 ? implode(' ', $result) : 0;
echo PHP_EOL;
}
function update($nums) {
foreach ($nums as $k => $v) {
if ($v === 0) {
unset($nums[$k]);
}
}
return $nums;
} |
Python |
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
MOD=10**9+7
def powmod(b,e):
global MOD
if e==0: return 1
if e&1: return (powmod((b*b)%MOD,e//2)*b)%MOD
return powmod((b*b)%MOD,e//2)
n=int(input())
h=[1]+list(map(int,input().split()))
"""
# naive solution, O(sum h_i)
archive=[]
# do rows
a1=[1]
for i in range(1,n+1):
if h[i]<=h[i-1]:
c=0
while len(a1)>h[i]:
c+=a1.pop(-1)
a1[0]=((a1[0]+c)*2)%MOD
else:
a1[0]=(a1[0]*2)%MOD
mul=powmod(2,h[i]-h[i-1])
for j in range(1,len(a1)):
a1[j]=(a1[j]*mul)%MOD
extras=[a1[0]]
for _ in range(h[i]-h[i-1]-1):
extras.append(extras[-1]*2)
a1+=extras[::-1]
archive.append(a1)
print(sum(a1)%MOD)
"""
# smarter solution? i think it's O(N^2)
root=1 # number of times that this column just alternates
pos=[] # [x,y] means it starts at x, and its size is y blocks
sz=1
for i in range(1,n+1):
if h[i]<=h[i-1]:
c=0
while pos and sz-pos[-1][1]>=h[i]:
a,b=pos.pop(-1)
c+=(a*(powmod(2,b)-1))%MOD
sz-=b
if sz>h[i]:
a,b=pos.pop(-1)
pos.append([(a*powmod(2,sz-h[i]))%MOD,b-(sz-h[i])])
c+=(a*(powmod(2,sz-h[i])-1))%MOD
sz=h[i]
root=((root+c)*2)%MOD
else:
root=(root*2)%MOD
mul=powmod(2,h[i]-h[i-1])
for j in range(len(pos)):
pos[j][0]=(pos[j][0]*mul)%MOD
pos.append([root,h[i]-h[i-1]])
sz=h[i]
# get answer
for a,b in pos:
root+=(a*(powmod(2,b)-1))%MOD
print(root%MOD) | Java | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov (egor@egork.net)
*/
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);
DHistogramColoring solver = new DHistogramColoring();
solver.solve(1, in, out);
out.close();
}
static class DHistogramColoring {
int n;
int[] h;
long[] ways;
int[][] minAt;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
h = in.readIntArray(n);
if (n == 1) {
out.printLine(IntegerUtils.power(2, h[0], MiscUtils.MOD7));
return;
}
long powMult = 1;
for (int i = 0; i < n; i++) {
int max;
if (i == 0) {
max = h[1];
} else if (i == n - 1) {
max = h[n - 2];
} else {
max = Math.max(h[i - 1], h[i + 1]);
}
if (h[i] > max) {
powMult += h[i] - max;
h[i] = max;
}
}
ways = ArrayUtils.createArray(n + 1, -1L);
minAt = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
minAt[i][j] = ArrayUtils.minPosition(h, i, j + 1);
}
}
long answer = go(0);
answer *= IntegerUtils.power(2, powMult, MiscUtils.MOD7);
answer %= MiscUtils.MOD7;
out.printLine(answer);
}
private long go(int at) {
if (ways[at] != -1) {
return ways[at];
}
if (at == n) {
return ways[at] = 1;
}
ways[at] = 0;
int left = at == 0 ? 1 : h[at - 1];
for (int i = at + 1; i <= n; i++) {
int right = i == n ? 1 : h[i];
ways[at] += IntegerUtils.power(2, calculate(at, i - 1, left, right), MiscUtils.MOD7) * go(i) %
MiscUtils.MOD7;
}
ways[at] %= MiscUtils.MOD7;
return ways[at];
}
private long calculate(int from, int to, int leftFixed, int rightFixed) {
if (from > to) {
return 0;
}
int at = minAt[from][to];
return Math.max(0, h[at] - Math.max(leftFixed, rightFixed)) + calculate(from, at - 1, leftFixed, h[at]) +
calculate(at + 1, to, h[at], rightFixed);
}
}
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 IntegerUtils {
public static long power(long base, long exponent, long mod) {
if (base >= mod) {
base %= mod;
}
if (exponent == 0) {
return 1 % mod;
}
long result = power(base, exponent >> 1, mod);
result = result * result % mod;
if ((exponent & 1) != 0) {
result = result * base % mod;
}
return result;
}
}
static class MiscUtils {
public static final int MOD7 = (int) (1e9 + 7);
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static class IntArrayList extends IntAbstractStream implements IntList {
private int size;
private int[] data;
public IntArrayList() {
this(3);
}
public IntArrayList(int capacity) {
data = new int[capacity];
}
public IntArrayList(IntCollection c) {
this(c.size());
addAll(c);
}
public IntArrayList(IntStream c) {
this();
if (c instanceof IntCollection) {
ensureCapacity(((IntCollection) c).size());
}
addAll(c);
}
public IntArrayList(IntArrayList c) {
size = c.size();
data = c.data.clone();
}
public IntArrayList(int[] arr) {
size = arr.length;
data = arr.clone();
}
public int size() {
return size;
}
public int get(int at) {
if (at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size);
}
return data[at];
}
private void ensureCapacity(int capacity) {
if (data.length >= capacity) {
return;
}
capacity = Math.max(2 * data.length, capacity);
data = Arrays.copyOf(data, capacity);
}
public void addAt(int index, int value) {
ensureCapacity(size + 1);
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size) {
System.arraycopy(data, index, data, index + 1, size - index);
}
data[index] = value;
size++;
}
public void removeAt(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size - 1) {
System.arraycopy(data, index + 1, data, index, size - index - 1);
}
size--;
}
public void set(int index, int value) {
if (index >= size) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
data[index] = value;
}
}
static interface IntCollection extends IntStream {
public int size();
default public void add(int value) {
throw new UnsupportedOperationException();
}
default public IntCollection addAll(IntStream values) {
for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
add(it.value());
}
return this;
}
}
static class IntArray extends IntAbstractStream implements IntList {
private int[] data;
public IntArray(int[] arr) {
data = arr;
}
public int size() {
return data.length;
}
public int get(int at) {
return data[at];
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int index, int value) {
data[index] = value;
}
}
static class ArrayUtils {
public static int minPosition(int[] array, int from, int to) {
return new IntArray(array).subList(from, to).minIndex() + from;
}
public static long[] createArray(int count, long value) {
long[] array = new long[count];
Arrays.fill(array, value);
return array;
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
static interface IntReversableCollection extends IntCollection {
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void set(int index, int value);
public abstract void addAt(int index, int value);
public abstract void removeAt(int index);
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void add(int value) {
addAt(size(), value);
}
default public int minIndex() {
int result = Integer.MAX_VALUE;
int size = size();
int at = -1;
for (int i = 0; i < size; i++) {
int current = get(i);
if (current < result) {
result = current;
at = i;
}
}
return at;
}
default public IntList subList(final int from, final int to) {
return new IntList() {
private final int shift;
private final int size;
{
if (from < 0 || from > to || to > IntList.this.size()) {
throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size());
}
shift = from;
size = to - from;
}
public int size() {
return size;
}
public int get(int at) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
return IntList.this.get(at + shift);
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int at, int value) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
IntList.this.set(at + shift, value);
}
public IntList compute() {
return new IntArrayList(this);
}
};
}
}
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 int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
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 interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
}
| Yes | Do these codes solve the same problem?
Code 1:
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
MOD=10**9+7
def powmod(b,e):
global MOD
if e==0: return 1
if e&1: return (powmod((b*b)%MOD,e//2)*b)%MOD
return powmod((b*b)%MOD,e//2)
n=int(input())
h=[1]+list(map(int,input().split()))
"""
# naive solution, O(sum h_i)
archive=[]
# do rows
a1=[1]
for i in range(1,n+1):
if h[i]<=h[i-1]:
c=0
while len(a1)>h[i]:
c+=a1.pop(-1)
a1[0]=((a1[0]+c)*2)%MOD
else:
a1[0]=(a1[0]*2)%MOD
mul=powmod(2,h[i]-h[i-1])
for j in range(1,len(a1)):
a1[j]=(a1[j]*mul)%MOD
extras=[a1[0]]
for _ in range(h[i]-h[i-1]-1):
extras.append(extras[-1]*2)
a1+=extras[::-1]
archive.append(a1)
print(sum(a1)%MOD)
"""
# smarter solution? i think it's O(N^2)
root=1 # number of times that this column just alternates
pos=[] # [x,y] means it starts at x, and its size is y blocks
sz=1
for i in range(1,n+1):
if h[i]<=h[i-1]:
c=0
while pos and sz-pos[-1][1]>=h[i]:
a,b=pos.pop(-1)
c+=(a*(powmod(2,b)-1))%MOD
sz-=b
if sz>h[i]:
a,b=pos.pop(-1)
pos.append([(a*powmod(2,sz-h[i]))%MOD,b-(sz-h[i])])
c+=(a*(powmod(2,sz-h[i])-1))%MOD
sz=h[i]
root=((root+c)*2)%MOD
else:
root=(root*2)%MOD
mul=powmod(2,h[i]-h[i-1])
for j in range(len(pos)):
pos[j][0]=(pos[j][0]*mul)%MOD
pos.append([root,h[i]-h[i-1]])
sz=h[i]
# get answer
for a,b in pos:
root+=(a*(powmod(2,b)-1))%MOD
print(root%MOD)
Code 2: import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov (egor@egork.net)
*/
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);
DHistogramColoring solver = new DHistogramColoring();
solver.solve(1, in, out);
out.close();
}
static class DHistogramColoring {
int n;
int[] h;
long[] ways;
int[][] minAt;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
h = in.readIntArray(n);
if (n == 1) {
out.printLine(IntegerUtils.power(2, h[0], MiscUtils.MOD7));
return;
}
long powMult = 1;
for (int i = 0; i < n; i++) {
int max;
if (i == 0) {
max = h[1];
} else if (i == n - 1) {
max = h[n - 2];
} else {
max = Math.max(h[i - 1], h[i + 1]);
}
if (h[i] > max) {
powMult += h[i] - max;
h[i] = max;
}
}
ways = ArrayUtils.createArray(n + 1, -1L);
minAt = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
minAt[i][j] = ArrayUtils.minPosition(h, i, j + 1);
}
}
long answer = go(0);
answer *= IntegerUtils.power(2, powMult, MiscUtils.MOD7);
answer %= MiscUtils.MOD7;
out.printLine(answer);
}
private long go(int at) {
if (ways[at] != -1) {
return ways[at];
}
if (at == n) {
return ways[at] = 1;
}
ways[at] = 0;
int left = at == 0 ? 1 : h[at - 1];
for (int i = at + 1; i <= n; i++) {
int right = i == n ? 1 : h[i];
ways[at] += IntegerUtils.power(2, calculate(at, i - 1, left, right), MiscUtils.MOD7) * go(i) %
MiscUtils.MOD7;
}
ways[at] %= MiscUtils.MOD7;
return ways[at];
}
private long calculate(int from, int to, int leftFixed, int rightFixed) {
if (from > to) {
return 0;
}
int at = minAt[from][to];
return Math.max(0, h[at] - Math.max(leftFixed, rightFixed)) + calculate(from, at - 1, leftFixed, h[at]) +
calculate(at + 1, to, h[at], rightFixed);
}
}
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 IntegerUtils {
public static long power(long base, long exponent, long mod) {
if (base >= mod) {
base %= mod;
}
if (exponent == 0) {
return 1 % mod;
}
long result = power(base, exponent >> 1, mod);
result = result * result % mod;
if ((exponent & 1) != 0) {
result = result * base % mod;
}
return result;
}
}
static class MiscUtils {
public static final int MOD7 = (int) (1e9 + 7);
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static class IntArrayList extends IntAbstractStream implements IntList {
private int size;
private int[] data;
public IntArrayList() {
this(3);
}
public IntArrayList(int capacity) {
data = new int[capacity];
}
public IntArrayList(IntCollection c) {
this(c.size());
addAll(c);
}
public IntArrayList(IntStream c) {
this();
if (c instanceof IntCollection) {
ensureCapacity(((IntCollection) c).size());
}
addAll(c);
}
public IntArrayList(IntArrayList c) {
size = c.size();
data = c.data.clone();
}
public IntArrayList(int[] arr) {
size = arr.length;
data = arr.clone();
}
public int size() {
return size;
}
public int get(int at) {
if (at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size);
}
return data[at];
}
private void ensureCapacity(int capacity) {
if (data.length >= capacity) {
return;
}
capacity = Math.max(2 * data.length, capacity);
data = Arrays.copyOf(data, capacity);
}
public void addAt(int index, int value) {
ensureCapacity(size + 1);
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size) {
System.arraycopy(data, index, data, index + 1, size - index);
}
data[index] = value;
size++;
}
public void removeAt(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size - 1) {
System.arraycopy(data, index + 1, data, index, size - index - 1);
}
size--;
}
public void set(int index, int value) {
if (index >= size) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
data[index] = value;
}
}
static interface IntCollection extends IntStream {
public int size();
default public void add(int value) {
throw new UnsupportedOperationException();
}
default public IntCollection addAll(IntStream values) {
for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
add(it.value());
}
return this;
}
}
static class IntArray extends IntAbstractStream implements IntList {
private int[] data;
public IntArray(int[] arr) {
data = arr;
}
public int size() {
return data.length;
}
public int get(int at) {
return data[at];
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int index, int value) {
data[index] = value;
}
}
static class ArrayUtils {
public static int minPosition(int[] array, int from, int to) {
return new IntArray(array).subList(from, to).minIndex() + from;
}
public static long[] createArray(int count, long value) {
long[] array = new long[count];
Arrays.fill(array, value);
return array;
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
static interface IntReversableCollection extends IntCollection {
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void set(int index, int value);
public abstract void addAt(int index, int value);
public abstract void removeAt(int index);
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void add(int value) {
addAt(size(), value);
}
default public int minIndex() {
int result = Integer.MAX_VALUE;
int size = size();
int at = -1;
for (int i = 0; i < size; i++) {
int current = get(i);
if (current < result) {
result = current;
at = i;
}
}
return at;
}
default public IntList subList(final int from, final int to) {
return new IntList() {
private final int shift;
private final int size;
{
if (from < 0 || from > to || to > IntList.this.size()) {
throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size());
}
shift = from;
size = to - from;
}
public int size() {
return size;
}
public int get(int at) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
return IntList.this.get(at + shift);
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int at, int value) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
IntList.this.set(at + shift, value);
}
public IntList compute() {
return new IntArrayList(this);
}
};
}
}
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 int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
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 interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
}
|
JavaScript | var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
var whn=arr.shift().split(" ").map(Number);
var xy=arr.shift().split(" ").map(Number);
var n=whn[2]-1;
var X=xy[0];
var Y=xy[1];
var sum=0;
while(n--){
var xy=arr.shift().split(" ").map(Number);
var x=xy[0];
var y=xy[1];
var dx=Math.abs(X-x);
var dy=Math.abs(Y-y);
if((x<X && y<Y) || (x>X && y>Y)){
while(dx>0 && dy>0){
dx--;
dy--;
sum++;
}
}
sum+=dx+dy;
X=x;
Y=y;
}
console.log(sum); | C# | using System;
using System.Collections.Generic;
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)
{
var WHN = ReadInts();
int[] xy = ReadInts();
var ans = 0;
for (int i = 0; i < WHN[2] - 1; i++)
{
var XY = ReadInts();
var cost = (Abs(xy[0] - XY[0]) + Abs(xy[1] - XY[1]));
//右上or左下移動
if (xy[0] < XY[0] && xy[1] < XY[1] || xy[0] > XY[0] && xy[1] > XY[1])
{
var vertical = Abs(xy[0] - XY[0]);
var yoko = Abs(xy[1] - XY[1]);
var m = Min(vertical, yoko);
cost -= m;
}
ans += cost;
xy = XY;
}
WriteLine(ans);
}
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");
var whn=arr.shift().split(" ").map(Number);
var xy=arr.shift().split(" ").map(Number);
var n=whn[2]-1;
var X=xy[0];
var Y=xy[1];
var sum=0;
while(n--){
var xy=arr.shift().split(" ").map(Number);
var x=xy[0];
var y=xy[1];
var dx=Math.abs(X-x);
var dy=Math.abs(Y-y);
if((x<X && y<Y) || (x>X && y>Y)){
while(dx>0 && dy>0){
dx--;
dy--;
sum++;
}
}
sum+=dx+dy;
X=x;
Y=y;
}
console.log(sum);
Code 2: using System;
using System.Collections.Generic;
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)
{
var WHN = ReadInts();
int[] xy = ReadInts();
var ans = 0;
for (int i = 0; i < WHN[2] - 1; i++)
{
var XY = ReadInts();
var cost = (Abs(xy[0] - XY[0]) + Abs(xy[1] - XY[1]));
//右上or左下移動
if (xy[0] < XY[0] && xy[1] < XY[1] || xy[0] > XY[0] && xy[1] > XY[1])
{
var vertical = Abs(xy[0] - XY[0]);
var yoko = Abs(xy[1] - XY[1]);
var m = Min(vertical, yoko);
cost -= m;
}
ans += cost;
xy = XY;
}
WriteLine(ans);
}
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); }
}
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int d, t, s;
int main() {
cin >> d >> t >> s;
cout << (t * s >= d ? "Yes" : "No") << endl;
}
| Python | n, k = list(map(int, input().split()))
price_list = list(map(int, input().split()))
print(sum(sorted(price_list)[0:k])) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int d, t, s;
int main() {
cin >> d >> t >> s;
cout << (t * s >= d ? "Yes" : "No") << endl;
}
Code 2: n, k = list(map(int, input().split()))
price_list = list(map(int, input().split()))
print(sum(sorted(price_list)[0:k])) |
Python | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(read())
alphabets = [chr(ord('a') + x) for x in range(26)]
def dfs(S, i):
if len(S) == N:
yield ''.join(S)
return
for j in range(i):
for w in dfs(S + [alphabets[j]], i):
yield w
for w in dfs(S + [alphabets[i]], i + 1):
yield w
for w in dfs([],0):
print(w) | 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;
using MethodImplAttribute = System.Runtime.CompilerServices.MethodImplAttribute;
using MethodImplOptions = System.Runtime.CompilerServices.MethodImplOptions;
public static class P
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
string[] s = new[] { "a" };
for (int i = 2; i <= n; i++)
{
s = s.SelectMany(Nexts).ToArray();
}
Console.WriteLine(string.Join("\n", s.OrderBy(x => x)));
}
static IEnumerable<string> Nexts(string x)
{
var maxChar = (char)(x.Max() + 1);
for (char i = 'a'; i <= maxChar; i++)
{
yield return x + i;
}
}
}
| 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
N = int(read())
alphabets = [chr(ord('a') + x) for x in range(26)]
def dfs(S, i):
if len(S) == N:
yield ''.join(S)
return
for j in range(i):
for w in dfs(S + [alphabets[j]], i):
yield w
for w in dfs(S + [alphabets[i]], i + 1):
yield w
for w in dfs([],0):
print(w)
Code 2: 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;
using MethodImplAttribute = System.Runtime.CompilerServices.MethodImplAttribute;
using MethodImplOptions = System.Runtime.CompilerServices.MethodImplOptions;
public static class P
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
string[] s = new[] { "a" };
for (int i = 2; i <= n; i++)
{
s = s.SelectMany(Nexts).ToArray();
}
Console.WriteLine(string.Join("\n", s.OrderBy(x => x)));
}
static IEnumerable<string> Nexts(string x)
{
var maxChar = (char)(x.Max() + 1);
for (char i = 'a'; i <= maxChar; i++)
{
yield return x + i;
}
}
}
|
Python | # -*- coding: utf-8 -*-
import numpy as np
N = int(input())
if N % 2 == 0:
ans = 0.5
else:
ans = (N - N // 2) / N
print(ans) | C++ | #include <bits/stdc++.h>
using namespace std;
using ll=long long;
int main(){
int n;
cin>>n;
vector<int> a(n);
for(int i=0;i<n;i++)cin>>a.at(i);
ll sum=0;
for(int i=0;i<n;i++){
sum+=a.at(i)-1;
}
cout<<sum<<endl;
} | No | Do these codes solve the same problem?
Code 1: # -*- coding: utf-8 -*-
import numpy as np
N = int(input())
if N % 2 == 0:
ans = 0.5
else:
ans = (N - N // 2) / N
print(ans)
Code 2: #include <bits/stdc++.h>
using namespace std;
using ll=long long;
int main(){
int n;
cin>>n;
vector<int> a(n);
for(int i=0;i<n;i++)cin>>a.at(i);
ll sum=0;
for(int i=0;i<n;i++){
sum+=a.at(i)-1;
}
cout<<sum<<endl;
} |
Python | def R(S):
return "".join(reversed([c for c in S]))
def solve(S):
l = len(S)
if not S == R(S):
return False
if not S[0: (l - 1) // 2] == R(S[0: (l - 1) // 2]):
return False
if not S[(l - 1) // 2 + 1:] == R(S[(l - 1) // 2 + 1:]):
return False
return True
def main():
if solve(input()):
print('Yes')
else:
print('No')
if __name__ == '__main__':
main() | C | #include<stdio.h>
int main(){ int aa, bb, cc;
scanf ("%d %d %d", &aa, &bb, &cc);
if (aa <= bb && bb <= cc) { printf ("%d %d %d\n", aa, bb, cc); return 0; }
if (aa <= cc && cc <= bb) { printf ("%d %d %d\n", aa, cc, bb); return 0; }
if (bb <= aa && aa <= cc) { printf ("%d %d %d\n", bb, aa, cc); return 0; }
if (bb <= cc && cc <= aa) { printf ("%d %d %d\n", bb, cc, aa); return 0; }
if (cc <= aa && aa <= bb) { printf ("%d %d %d\n", cc, aa, bb); return 0; }
if (cc <= bb && bb <= aa) { printf ("%d %d %d\n", cc, bb, aa); return 0; }
} | No | Do these codes solve the same problem?
Code 1: def R(S):
return "".join(reversed([c for c in S]))
def solve(S):
l = len(S)
if not S == R(S):
return False
if not S[0: (l - 1) // 2] == R(S[0: (l - 1) // 2]):
return False
if not S[(l - 1) // 2 + 1:] == R(S[(l - 1) // 2 + 1:]):
return False
return True
def main():
if solve(input()):
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
Code 2: #include<stdio.h>
int main(){ int aa, bb, cc;
scanf ("%d %d %d", &aa, &bb, &cc);
if (aa <= bb && bb <= cc) { printf ("%d %d %d\n", aa, bb, cc); return 0; }
if (aa <= cc && cc <= bb) { printf ("%d %d %d\n", aa, cc, bb); return 0; }
if (bb <= aa && aa <= cc) { printf ("%d %d %d\n", bb, aa, cc); return 0; }
if (bb <= cc && cc <= aa) { printf ("%d %d %d\n", bb, cc, aa); return 0; }
if (cc <= aa && aa <= bb) { printf ("%d %d %d\n", cc, aa, bb); return 0; }
if (cc <= bb && bb <= aa) { printf ("%d %d %d\n", cc, bb, aa); return 0; }
} |
Python | #!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n,m = LI()
p = [[float(x) for x in input().split()] for i in range(n)]
f = [[sum([(a-b)**2 for (a,b) in zip(p[i],p[j])]) for j in range(n)] for i in range(n)]
l = 1<<n
ans = 0
for b in range(l):
if bin(b).count("1") != m:
continue
s = 0
for i in range(n):
if not b&(1<<i):
continue
x = p[i]
for j in range(i):
if not b&(1<<j):
continue
y = p[j]
s += f[i][j]
if ans < s:
ans = s
print(ans)
return
#Solve
if __name__ == "__main__":
solve()
| C# | using static System.Math;
using System.Collections.Generic;
using System;
public class hello
{
public static void Main()
{
string[] line = Console.ReadLine().Trim().Split(' ');
var n = int.Parse(line[0]);
var m = int.Parse(line[1]);
var c = new double[n, 3];
for (int i = 0; i < n; i++)
{
line = Console.ReadLine().Trim().Split(' ');
for (int j = 0; j < 3; j++)
c[i, j] = double.Parse(line[j]);
}
getAns(n, m, c);
}
static void getAns(int n, int m, double[,] c)
{
var res = 0d;
var imax = 1 << n;
for (int i = 0; i < imax; i++)
{
if (countbit(i) == m)
{
var b = new List<int>();
for (int j = 0; j < n; j++)
if (((i >> j) & 1) == 1) b.Add(j);
res = Max(res, calc(b, c, m));
}
}
Console.WriteLine(res);
}
static double calc(List<int> b, double[,] c, int m)
{
var res = 0d;
for (int i = 0; i < m - 1; i++)
for (int j = i + 1; j < m; j++)
for (int k = 0; k < 3; k++)
res += (c[b[i], k] - c[b[j], k]) * (c[b[i], k] - c[b[j], k]);
return res;
}
static int countbit(int bits)
{
bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555);
bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333);
bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f);
bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff);
return (bits & 0x0000ffff) + (bits >> 16 & 0x0000ffff);
}
}
| Yes | Do these codes solve the same problem?
Code 1: #!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n,m = LI()
p = [[float(x) for x in input().split()] for i in range(n)]
f = [[sum([(a-b)**2 for (a,b) in zip(p[i],p[j])]) for j in range(n)] for i in range(n)]
l = 1<<n
ans = 0
for b in range(l):
if bin(b).count("1") != m:
continue
s = 0
for i in range(n):
if not b&(1<<i):
continue
x = p[i]
for j in range(i):
if not b&(1<<j):
continue
y = p[j]
s += f[i][j]
if ans < s:
ans = s
print(ans)
return
#Solve
if __name__ == "__main__":
solve()
Code 2: using static System.Math;
using System.Collections.Generic;
using System;
public class hello
{
public static void Main()
{
string[] line = Console.ReadLine().Trim().Split(' ');
var n = int.Parse(line[0]);
var m = int.Parse(line[1]);
var c = new double[n, 3];
for (int i = 0; i < n; i++)
{
line = Console.ReadLine().Trim().Split(' ');
for (int j = 0; j < 3; j++)
c[i, j] = double.Parse(line[j]);
}
getAns(n, m, c);
}
static void getAns(int n, int m, double[,] c)
{
var res = 0d;
var imax = 1 << n;
for (int i = 0; i < imax; i++)
{
if (countbit(i) == m)
{
var b = new List<int>();
for (int j = 0; j < n; j++)
if (((i >> j) & 1) == 1) b.Add(j);
res = Max(res, calc(b, c, m));
}
}
Console.WriteLine(res);
}
static double calc(List<int> b, double[,] c, int m)
{
var res = 0d;
for (int i = 0; i < m - 1; i++)
for (int j = i + 1; j < m; j++)
for (int k = 0; k < 3; k++)
res += (c[b[i], k] - c[b[j], k]) * (c[b[i], k] - c[b[j], k]);
return res;
}
static int countbit(int bits)
{
bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555);
bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333);
bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f);
bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff);
return (bits & 0x0000ffff) + (bits >> 16 & 0x0000ffff);
}
}
|
C# | using System;
namespace ABC109A
{
class Program
{
static void Main(string[] args)
{
int a, b;
string[] ss = Console.ReadLine().Split(' ');
a = int.Parse(ss[0]);
b = int.Parse(ss[1]);
if (a * b % 2 == 0)
Console.WriteLine("No");
else
Console.WriteLine("Yes");
Console.ReadKey();
}
}
}
| Python | s = list(input().split("/"))
#print(s)
if(int(s[0]) < 2019):
print("Heisei")
elif(int(s[1]) <= 4):
print("Heisei")
else:
print("TBD") | No | Do these codes solve the same problem?
Code 1: using System;
namespace ABC109A
{
class Program
{
static void Main(string[] args)
{
int a, b;
string[] ss = Console.ReadLine().Split(' ');
a = int.Parse(ss[0]);
b = int.Parse(ss[1]);
if (a * b % 2 == 0)
Console.WriteLine("No");
else
Console.WriteLine("Yes");
Console.ReadKey();
}
}
}
Code 2: s = list(input().split("/"))
#print(s)
if(int(s[0]) < 2019):
print("Heisei")
elif(int(s[1]) <= 4):
print("Heisei")
else:
print("TBD") |
Python | N, A, B = map(int, input().split())
if (B - A) % 2 == 0:
print((B-A) // 2)
else:
print(min(A - 1, N - B) + 1 + (B-A) // 2) | C++ | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define p_ary(ary,a,b) do { cout << "["; for (int count = (a);count < (b);++count) cout << ary[count] << ((b)-1 == count ? "" : ", "); cout << "]\n"; } while(0)
#define p_map(map,it) do {cout << "{";for (auto (it) = map.begin();;++(it)) {if ((it) == map.end()) {cout << "}\n";break;}else cout << "" << (it)->first << "=>" << (it)->second << ", ";}}while(0)
template<typename T1,typename T2>ostream& operator<<(ostream& os,const pair<T1,T2>& a) {os << "(" << a.first << ", " << a.second << ")";return os;}
const char newl = '\n';
int main() {
string s;
cin >> s;
int n = s.size();
for (int i = 0;i < n;++i) {
cout << (s[i] == '?' ? char('D') : s[i]);
}
cout << endl;
} | No | Do these codes solve the same problem?
Code 1: N, A, B = map(int, input().split())
if (B - A) % 2 == 0:
print((B-A) // 2)
else:
print(min(A - 1, N - B) + 1 + (B-A) // 2)
Code 2: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define p_ary(ary,a,b) do { cout << "["; for (int count = (a);count < (b);++count) cout << ary[count] << ((b)-1 == count ? "" : ", "); cout << "]\n"; } while(0)
#define p_map(map,it) do {cout << "{";for (auto (it) = map.begin();;++(it)) {if ((it) == map.end()) {cout << "}\n";break;}else cout << "" << (it)->first << "=>" << (it)->second << ", ";}}while(0)
template<typename T1,typename T2>ostream& operator<<(ostream& os,const pair<T1,T2>& a) {os << "(" << a.first << ", " << a.second << ")";return os;}
const char newl = '\n';
int main() {
string s;
cin >> s;
int n = s.size();
for (int i = 0;i < n;++i) {
cout << (s[i] == '?' ? char('D') : s[i]);
}
cout << endl;
} |
JavaScript | "use strict";
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
console.log(main());
function main(){
var n = o.a();
var s = o.m(n,1);
var x = o.a(1);
var ans = 0;
var f = 0;
for(var i = 0; i < n; i++){
if(s[i][0] === x)f = 1, ans -= s[i][1];
if(f === 0)continue;
ans += +s[i][1];
}
return ans;
} | Kotlin | fun main(args: Array<String>) {
dwacon6thPrelimsA()
}
fun dwacon6thPrelimsA() {
val n = readLine()!!.toInt()
val stList = (1..n).map { readLine()!!.split(' ').let { Pair(it[0], it[1].toInt()) } }
val x = readLine()!!
val indexOfFirst = stList.indexOfFirst { it.first == x }
val answer = stList.slice(indexOfFirst + 1..stList.lastIndex).map { it.second }.sum()
println(answer)
}
| Yes | Do these codes solve the same problem?
Code 1: "use strict";
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
console.log(main());
function main(){
var n = o.a();
var s = o.m(n,1);
var x = o.a(1);
var ans = 0;
var f = 0;
for(var i = 0; i < n; i++){
if(s[i][0] === x)f = 1, ans -= s[i][1];
if(f === 0)continue;
ans += +s[i][1];
}
return ans;
}
Code 2: fun main(args: Array<String>) {
dwacon6thPrelimsA()
}
fun dwacon6thPrelimsA() {
val n = readLine()!!.toInt()
val stList = (1..n).map { readLine()!!.split(' ').let { Pair(it[0], it[1].toInt()) } }
val x = readLine()!!
val indexOfFirst = stList.indexOfFirst { it.first == x }
val answer = stList.slice(indexOfFirst + 1..stList.lastIndex).map { it.second }.sum()
println(answer)
}
|
Java | import java.util.Scanner;
public class Main{
static int n;
static int gx,ex;
static int gy,ey;
static int[][][] memo;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
n =sc.nextInt();
if(n==0)break;
String start=sc.next();
String end=sc.next();
String not=sc.next();
int room[][][]=new int[n][2][2];
int x=0,y=0;
if(start.equals("B"))
x=1;
else if(start.equals("C"))
x=2;
else if(start.equals("D"))
y=1;
else if(start.equals("E")){
x=1;y=1;
}else if(start.equals("F")){
x=2;y=1;
}else if(start.equals("G"))
y=2;
else if(start.equals("H")){
x=1;y=2;
}else if(start.equals("I")){
x=2;y=2;
}
gx=0;gy=0;
if(end.equals("B"))
gx=1;
else if(end.equals("C"))
gx=2;
else if(end.equals("D"))
gy=1;
else if(end.equals("E")){
gx=1;gy=1;
}else if(end.equals("F")){
gx=2;gy=1;
}else if(end.equals("G"))
gy=2;
else if(end.equals("H")){
gx=1;gy=2;
}else if(end.equals("I")){
gx=2;gy=2;
}
ex=0;ey=0;
if(not.equals("B"))
ex=1;
else if(not.equals("C"))
ex=2;
else if(not.equals("D"))
ey=1;
else if(not.equals("E")){
ex=1;ey=1;
}else if(not.equals("F")){
ex=2;ey=1;
}else if(not.equals("G"))
ey=2;
else if(not.equals("H")){
ex=1;ey=2;
}else if(not.equals("I")){
ex=2;ey=2;
}
memo=new int[3][3][n+1];
System.out.printf("%.9f\n",(double)dfs(x,y,0)/Math.pow(4, n));
// Math.pow(4, n)
}
}
static int sx[]={1,0,-1,0};
static int sy[]={0,1,0,-1};
static int dfs(int x, int y, int battery){
// System.out.println(x+" "+y+" "+battery);
if(memo[x][y][battery]>0)return memo[x][y][battery];
int result = 0;
if(battery==n){
if(gx==x&&gy==y)return 1;
else return 0;
}
for(int i=0;i<4;i++){
int nx=x+sx[i];int ny=y+sy[i];
if(nx<0||nx>2||ny<0||ny>2||(nx==ex&&ny==ey))result+=dfs(x,y,battery+1);
else result+=dfs(nx,ny,battery+1);
}
return memo[x][y][battery]=result;
}
} | C# | using System;
using System.Collections.Generic;
using System.Text;
class TEST{
static void Main(){
while(true){
var d=int.Parse(Console.ReadLine());
if(d==0)break;
Sol mySol=new Sol(d);
Console.WriteLine("{0,10:F8}",mySol.Ans);
}
}
}
class Sol{
double ans;
public double Ans{
get{return ans;}
}
public Sol(int d){
double[,][] P=new double[3,3][];
for(int i=0;i<9;i++)P[i%3,i/3]=new double[d+1];
var ss=Console.ReadLine().Split(' ');
int posS;
int posT;
int posB;
for(int i=0;i<9;i++)P[i%3,i/3][0]=0;
posS=(int)(ss[0][0]-'A');
posT=(int)(ss[1][0]-'A');
posB=(int)(ss[2][0]-'A');
P[posS%3,posS/3][0]=1.0;
double[,][] Pd=new double[3,3][];
for(int i=0;i<9;i++){
int x=i%3;
int y=i/3;
Pd[x,y]=new double[5]{0.0,0.25,0.25,0.25,0.25};// 0:pause,1:Left,2:Right,3:Down,4:Up
if(x==0 || (x==posB%3+1 && y==posB/3 ) ){Pd[x,y][0]+=0.25;Pd[x,y][1]-=0.25;}
if(x==2 || (x==posB%3-1 && y==posB/3 ) ){Pd[x,y][0]+=0.25;Pd[x,y][2]-=0.25;}
if(y==0 || (x==posB%3 && y==posB/3+1) ){Pd[x,y][0]+=0.25;Pd[x,y][4]-=0.25;}
if(y==2 || (x==posB%3 && y==posB/3-1) ){Pd[x,y][0]+=0.25;Pd[x,y][3]-=0.25;}
}
for(int j=1;j<=d;j++){
for(int k=0;k<9;k++){
int xx=k%3;
int yy=k/3;
P[xx,yy][j] =P[xx,yy][j-1]*Pd[xx,yy][0];
if(xx+1<=2)P[xx,yy][j]+=P[xx+1,yy][j-1]*Pd[xx+1,yy][1];
if(xx-1>=0)P[xx,yy][j]+=P[xx-1,yy][j-1]*Pd[xx-1,yy][2];
if(yy-1>=0)P[xx,yy][j]+=P[xx,yy-1][j-1]*Pd[xx,yy-1][3];
if(yy+1<=2)P[xx,yy][j]+=P[xx,yy+1][j-1]*Pd[xx,yy+1][4];
}
}
ans=P[posT%3,posT/3][d];
}
} | Yes | Do these codes solve the same problem?
Code 1: import java.util.Scanner;
public class Main{
static int n;
static int gx,ex;
static int gy,ey;
static int[][][] memo;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
n =sc.nextInt();
if(n==0)break;
String start=sc.next();
String end=sc.next();
String not=sc.next();
int room[][][]=new int[n][2][2];
int x=0,y=0;
if(start.equals("B"))
x=1;
else if(start.equals("C"))
x=2;
else if(start.equals("D"))
y=1;
else if(start.equals("E")){
x=1;y=1;
}else if(start.equals("F")){
x=2;y=1;
}else if(start.equals("G"))
y=2;
else if(start.equals("H")){
x=1;y=2;
}else if(start.equals("I")){
x=2;y=2;
}
gx=0;gy=0;
if(end.equals("B"))
gx=1;
else if(end.equals("C"))
gx=2;
else if(end.equals("D"))
gy=1;
else if(end.equals("E")){
gx=1;gy=1;
}else if(end.equals("F")){
gx=2;gy=1;
}else if(end.equals("G"))
gy=2;
else if(end.equals("H")){
gx=1;gy=2;
}else if(end.equals("I")){
gx=2;gy=2;
}
ex=0;ey=0;
if(not.equals("B"))
ex=1;
else if(not.equals("C"))
ex=2;
else if(not.equals("D"))
ey=1;
else if(not.equals("E")){
ex=1;ey=1;
}else if(not.equals("F")){
ex=2;ey=1;
}else if(not.equals("G"))
ey=2;
else if(not.equals("H")){
ex=1;ey=2;
}else if(not.equals("I")){
ex=2;ey=2;
}
memo=new int[3][3][n+1];
System.out.printf("%.9f\n",(double)dfs(x,y,0)/Math.pow(4, n));
// Math.pow(4, n)
}
}
static int sx[]={1,0,-1,0};
static int sy[]={0,1,0,-1};
static int dfs(int x, int y, int battery){
// System.out.println(x+" "+y+" "+battery);
if(memo[x][y][battery]>0)return memo[x][y][battery];
int result = 0;
if(battery==n){
if(gx==x&&gy==y)return 1;
else return 0;
}
for(int i=0;i<4;i++){
int nx=x+sx[i];int ny=y+sy[i];
if(nx<0||nx>2||ny<0||ny>2||(nx==ex&&ny==ey))result+=dfs(x,y,battery+1);
else result+=dfs(nx,ny,battery+1);
}
return memo[x][y][battery]=result;
}
}
Code 2: using System;
using System.Collections.Generic;
using System.Text;
class TEST{
static void Main(){
while(true){
var d=int.Parse(Console.ReadLine());
if(d==0)break;
Sol mySol=new Sol(d);
Console.WriteLine("{0,10:F8}",mySol.Ans);
}
}
}
class Sol{
double ans;
public double Ans{
get{return ans;}
}
public Sol(int d){
double[,][] P=new double[3,3][];
for(int i=0;i<9;i++)P[i%3,i/3]=new double[d+1];
var ss=Console.ReadLine().Split(' ');
int posS;
int posT;
int posB;
for(int i=0;i<9;i++)P[i%3,i/3][0]=0;
posS=(int)(ss[0][0]-'A');
posT=(int)(ss[1][0]-'A');
posB=(int)(ss[2][0]-'A');
P[posS%3,posS/3][0]=1.0;
double[,][] Pd=new double[3,3][];
for(int i=0;i<9;i++){
int x=i%3;
int y=i/3;
Pd[x,y]=new double[5]{0.0,0.25,0.25,0.25,0.25};// 0:pause,1:Left,2:Right,3:Down,4:Up
if(x==0 || (x==posB%3+1 && y==posB/3 ) ){Pd[x,y][0]+=0.25;Pd[x,y][1]-=0.25;}
if(x==2 || (x==posB%3-1 && y==posB/3 ) ){Pd[x,y][0]+=0.25;Pd[x,y][2]-=0.25;}
if(y==0 || (x==posB%3 && y==posB/3+1) ){Pd[x,y][0]+=0.25;Pd[x,y][4]-=0.25;}
if(y==2 || (x==posB%3 && y==posB/3-1) ){Pd[x,y][0]+=0.25;Pd[x,y][3]-=0.25;}
}
for(int j=1;j<=d;j++){
for(int k=0;k<9;k++){
int xx=k%3;
int yy=k/3;
P[xx,yy][j] =P[xx,yy][j-1]*Pd[xx,yy][0];
if(xx+1<=2)P[xx,yy][j]+=P[xx+1,yy][j-1]*Pd[xx+1,yy][1];
if(xx-1>=0)P[xx,yy][j]+=P[xx-1,yy][j-1]*Pd[xx-1,yy][2];
if(yy-1>=0)P[xx,yy][j]+=P[xx,yy-1][j-1]*Pd[xx,yy-1][3];
if(yy+1<=2)P[xx,yy][j]+=P[xx,yy+1][j-1]*Pd[xx,yy+1][4];
}
}
ans=P[posT%3,posT/3][d];
}
} |
C# | using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
// (づ°ω°)づミe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
public void Solve()
{
int n = ReadInt();
int m = ReadInt();
var f = new bool[10];
foreach (int x in ReadIntArray())
f[x] = true;
while (true)
{
bool ok = true;
foreach (char ch in n.ToString())
if (f[ch - '0'])
ok = false;
if (ok)
break;
n++;
}
Write(n);
}
#region Main
protected static TextReader reader;
protected static TextWriter writer;
static void Main()
{
#if DEBUG
reader = new StreamReader("..\\..\\input.txt");
//reader = new StreamReader(Console.OpenStandardInput());
writer = Console.Out;
//writer = new StreamWriter("..\\..\\output.txt");
#else
reader = new StreamReader(Console.OpenStandardInput());
writer = new StreamWriter(Console.OpenStandardOutput());
//reader = new StreamReader("input.txt");
//writer = new StreamWriter("output.txt");
#endif
try
{
new Solver().Solve();
//var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
//thread.Start();
//thread.Join();
}
catch (Exception ex)
{
#if DEBUG
Console.WriteLine(ex);
#else
throw;
#endif
}
reader.Close();
writer.Close();
}
#endregion
#region Read / Write
private static Queue<string> currentLineTokens = new Queue<string>();
private static string[] ReadAndSplitLine() { return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries); }
public static string ReadToken() { while (currentLineTokens.Count == 0)currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue(); }
public static int ReadInt() { return int.Parse(ReadToken()); }
public static long ReadLong() { return long.Parse(ReadToken()); }
public static double ReadDouble() { return double.Parse(ReadToken(), CultureInfo.InvariantCulture); }
public static int[] ReadIntArray() { return ReadAndSplitLine().Select(int.Parse).ToArray(); }
public static long[] ReadLongArray() { return ReadAndSplitLine().Select(long.Parse).ToArray(); }
public static double[] ReadDoubleArray() { return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); }
public static int[][] ReadIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++)matrix[i] = ReadIntArray(); return matrix; }
public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
{
int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++)ret[i][j] = matrix[j][i]; } return ret;
}
public static string[] ReadLines(int quantity) { string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++)lines[i] = reader.ReadLine().Trim(); return lines; }
public static void WriteArray<T>(IEnumerable<T> array) { writer.WriteLine(string.Join(" ", array)); }
public static void Write(params object[] array) { WriteArray(array); }
public static void WriteLines<T>(IEnumerable<T> array) { foreach (var a in array)writer.WriteLine(a); }
private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public new TValue this[TKey key]
{
get { return ContainsKey(key) ? base[key] : default(TValue); }
set { base[key] = value; }
}
}
private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
#endregion
} | Go | package main
import "fmt"
var d = make([]bool, 10)
func check(n int) bool {
for n > 0 {
if d[n%10] {
return false
}
n /= 10
}
return true
}
func main() {
var n, k int
fmt.Scan(&n, &k)
var t int
for i := 0; i < k; i++ {
fmt.Scan(&t)
d[t] = true
}
r := n
for ; !check(r); r++ {
}
fmt.Println(r)
} | Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
// (づ°ω°)づミe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
public void Solve()
{
int n = ReadInt();
int m = ReadInt();
var f = new bool[10];
foreach (int x in ReadIntArray())
f[x] = true;
while (true)
{
bool ok = true;
foreach (char ch in n.ToString())
if (f[ch - '0'])
ok = false;
if (ok)
break;
n++;
}
Write(n);
}
#region Main
protected static TextReader reader;
protected static TextWriter writer;
static void Main()
{
#if DEBUG
reader = new StreamReader("..\\..\\input.txt");
//reader = new StreamReader(Console.OpenStandardInput());
writer = Console.Out;
//writer = new StreamWriter("..\\..\\output.txt");
#else
reader = new StreamReader(Console.OpenStandardInput());
writer = new StreamWriter(Console.OpenStandardOutput());
//reader = new StreamReader("input.txt");
//writer = new StreamWriter("output.txt");
#endif
try
{
new Solver().Solve();
//var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
//thread.Start();
//thread.Join();
}
catch (Exception ex)
{
#if DEBUG
Console.WriteLine(ex);
#else
throw;
#endif
}
reader.Close();
writer.Close();
}
#endregion
#region Read / Write
private static Queue<string> currentLineTokens = new Queue<string>();
private static string[] ReadAndSplitLine() { return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries); }
public static string ReadToken() { while (currentLineTokens.Count == 0)currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue(); }
public static int ReadInt() { return int.Parse(ReadToken()); }
public static long ReadLong() { return long.Parse(ReadToken()); }
public static double ReadDouble() { return double.Parse(ReadToken(), CultureInfo.InvariantCulture); }
public static int[] ReadIntArray() { return ReadAndSplitLine().Select(int.Parse).ToArray(); }
public static long[] ReadLongArray() { return ReadAndSplitLine().Select(long.Parse).ToArray(); }
public static double[] ReadDoubleArray() { return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); }
public static int[][] ReadIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++)matrix[i] = ReadIntArray(); return matrix; }
public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
{
int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++)ret[i][j] = matrix[j][i]; } return ret;
}
public static string[] ReadLines(int quantity) { string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++)lines[i] = reader.ReadLine().Trim(); return lines; }
public static void WriteArray<T>(IEnumerable<T> array) { writer.WriteLine(string.Join(" ", array)); }
public static void Write(params object[] array) { WriteArray(array); }
public static void WriteLines<T>(IEnumerable<T> array) { foreach (var a in array)writer.WriteLine(a); }
private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public new TValue this[TKey key]
{
get { return ContainsKey(key) ? base[key] : default(TValue); }
set { base[key] = value; }
}
}
private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
#endregion
}
Code 2: package main
import "fmt"
var d = make([]bool, 10)
func check(n int) bool {
for n > 0 {
if d[n%10] {
return false
}
n /= 10
}
return true
}
func main() {
var n, k int
fmt.Scan(&n, &k)
var t int
for i := 0; i < k; i++ {
fmt.Scan(&t)
d[t] = true
}
r := n
for ; !check(r); r++ {
}
fmt.Println(r)
} |
Java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.IntUnaryOperator;
import java.util.function.LongUnaryOperator;
class Main {
static In in = new In();
static Out out = new Out();
static long mod = 1000000007;
static long inf = 0xfffffffffffffffL;
void solve() {
int n = in.nextInt();
out.println((n + 1) / 2);
}
public static void main(String[]$) {
new Main().solve();
out.flush();
}
}
class In {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 0x10000);
private StringTokenizer tokenizer;
String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (IOException ignored) {
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
char[][] nextCharArray(int n, int m) {
char[][] a = new char[n][m];
for (int i = 0; i < n; i++) {
a[i] = next().toCharArray();
}
return a;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
int[] nextIntArray(int n, IntUnaryOperator op) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = op.applyAsInt(nextInt());
}
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
long[] nextLongArray(int n, LongUnaryOperator op) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = op.applyAsLong(nextLong());
}
return a;
}
}
class Out {
private static PrintWriter out = new PrintWriter(System.out);
void println(Object... a) {
StringJoiner joiner = new StringJoiner(" ");
for (Object obj : a) {
joiner.add(String.valueOf(obj));
}
out.println(joiner);
}
void flush() {
out.flush();
}
}
| TypeScript | export class Main {
static main(input: string): string {
const tmp: string[] = input.split("\n");
const n: number = tmp[0].split(" ").map(int => parseInt(int))[0];
return `${(n + (n % 2)) / 2}`;
}
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
| Yes | Do these codes solve the same problem?
Code 1: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.IntUnaryOperator;
import java.util.function.LongUnaryOperator;
class Main {
static In in = new In();
static Out out = new Out();
static long mod = 1000000007;
static long inf = 0xfffffffffffffffL;
void solve() {
int n = in.nextInt();
out.println((n + 1) / 2);
}
public static void main(String[]$) {
new Main().solve();
out.flush();
}
}
class In {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 0x10000);
private StringTokenizer tokenizer;
String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (IOException ignored) {
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
char[][] nextCharArray(int n, int m) {
char[][] a = new char[n][m];
for (int i = 0; i < n; i++) {
a[i] = next().toCharArray();
}
return a;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
int[] nextIntArray(int n, IntUnaryOperator op) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = op.applyAsInt(nextInt());
}
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
long[] nextLongArray(int n, LongUnaryOperator op) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = op.applyAsLong(nextLong());
}
return a;
}
}
class Out {
private static PrintWriter out = new PrintWriter(System.out);
void println(Object... a) {
StringJoiner joiner = new StringJoiner(" ");
for (Object obj : a) {
joiner.add(String.valueOf(obj));
}
out.println(joiner);
}
void flush() {
out.flush();
}
}
Code 2: export class Main {
static main(input: string): string {
const tmp: string[] = input.split("\n");
const n: number = tmp[0].split(" ").map(int => parseInt(int))[0];
return `${(n + (n % 2)) / 2}`;
}
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
|
C++ | #include <bits/stdc++.h>
using namespace std;
int main()
{
char ch[2];
scanf("%c",ch);
if(ch[0]=='A')
printf("T");
else if(ch[0]=='T')
printf("A");
else if(ch[0]=='C')
printf("G");
else
printf("C");
return 0;
}
| Python | def main():
X = input()
delcnt = 0
delans = 0
for i in range(len(X)):
if X[i]=='S':
delcnt += 1
if X[i]=='T' and delcnt>0:
delans +=2
delcnt -=1
print(len(X)-delans)
if __name__ == '__main__':
main() | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int main()
{
char ch[2];
scanf("%c",ch);
if(ch[0]=='A')
printf("T");
else if(ch[0]=='T')
printf("A");
else if(ch[0]=='C')
printf("G");
else
printf("C");
return 0;
}
Code 2: def main():
X = input()
delcnt = 0
delans = 0
for i in range(len(X)):
if X[i]=='S':
delcnt += 1
if X[i]=='T' and delcnt>0:
delans +=2
delcnt -=1
print(len(X)-delans)
if __name__ == '__main__':
main() |
Python | N,A,B = map(int,input().split())
ans = 0
for i in range(N+1):
n = str(i)
a = 0
for j in range(len(n)):
a += int(n[j:j+1])
if a >= A and a <= B:
ans += i
print(ans) | C++ | #include <vector>
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
#include <unordered_set>
using namespace std;
typedef long long ll;
typedef vector<int> VI;
ll n, m, L;
vector<vector<ll>> dist;
vector<vector<ll>> d;
const ll LARGE = (ll)1e15;
void initialize() {
dist.resize(n);
d.resize(n);
for (int i = 0; i < n; i++) {
dist[i].resize(n);
d[i].resize(n);
for (int j = 0; j < n; j++) {
if (i == j) {
dist[i][j] = 0;
d[i][j] = 0;
}
else {
dist[i][j] = LARGE;
d[i][j] = LARGE;
}
}
}
}
void solve() {
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
if (dist[i][j] <= L) {
d[i][j] = 1;
}
}
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
}
int main(void)
{
cin >> n >> m >> L;
initialize();
for (int i = 0; i < m; i++) {
ll a, b, c;
cin >> a >> b >> c;
a--;
b--;
dist[a][b] = c;
dist[b][a] = c;
}
solve();
int q;
cin >> q;
vector<ll> ans(q);
for (int i = 0; i < q; i++) {
int s, t;
cin >> s >> t;
s--;
t--;
auto v = d[s][t];
if (v >= LARGE) {
ans[i] = -1;
}
else {
ans[i] = d[s][t] - 1;
}
}
for (int i = 0; i < q; i++) {
cout << ans[i] << endl;
}
return 0;
} | No | Do these codes solve the same problem?
Code 1: N,A,B = map(int,input().split())
ans = 0
for i in range(N+1):
n = str(i)
a = 0
for j in range(len(n)):
a += int(n[j:j+1])
if a >= A and a <= B:
ans += i
print(ans)
Code 2: #include <vector>
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
#include <unordered_set>
using namespace std;
typedef long long ll;
typedef vector<int> VI;
ll n, m, L;
vector<vector<ll>> dist;
vector<vector<ll>> d;
const ll LARGE = (ll)1e15;
void initialize() {
dist.resize(n);
d.resize(n);
for (int i = 0; i < n; i++) {
dist[i].resize(n);
d[i].resize(n);
for (int j = 0; j < n; j++) {
if (i == j) {
dist[i][j] = 0;
d[i][j] = 0;
}
else {
dist[i][j] = LARGE;
d[i][j] = LARGE;
}
}
}
}
void solve() {
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
if (dist[i][j] <= L) {
d[i][j] = 1;
}
}
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
}
int main(void)
{
cin >> n >> m >> L;
initialize();
for (int i = 0; i < m; i++) {
ll a, b, c;
cin >> a >> b >> c;
a--;
b--;
dist[a][b] = c;
dist[b][a] = c;
}
solve();
int q;
cin >> q;
vector<ll> ans(q);
for (int i = 0; i < q; i++) {
int s, t;
cin >> s >> t;
s--;
t--;
auto v = d[s][t];
if (v >= LARGE) {
ans[i] = -1;
}
else {
ans[i] = d[s][t] - 1;
}
}
for (int i = 0; i < q; i++) {
cout << ans[i] << endl;
}
return 0;
} |
C++ | #include <bits/stdc++.h>
using namespace std;
#define rep(i,x,y) for(int i=(x);i<(y);++i)
#define debug(x) #x << "=" << (x)
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl
#else
#define print(x)
#endif
const int inf=1e9;
const int64_t inf64=1e18;
const double eps=1e-9;
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){
os << "[";
for (const auto &v : vec) {
os << v << ",";
}
os << "]";
return os;
}
struct edge{
int from,to;
int64_t cost;
bool operator<(const edge &other)const{
return cost<other.cost;
}
};
class union_find{
private:
vector<int> parent,rank,gs;
int size;
public:
int count_group;
union_find()=default;
union_find(int n){ init(n); }
void init(int n){
size=n;
count_group=n;
parent.resize(size);
rank.assign(size,0);
gs.assign(size,1);
for(int i=0; i<size; ++i) parent[i]=i;
}
int find(int x){
if(parent[x]==x) return x;
else return parent[x]=find(parent[x]);
}
void unite(int x,int y){
x=find(x);
y=find(y);
if(x==y) return;
if(rank[x]<rank[y]){
parent[x]=y;
gs[y]+=gs[x];
} else {
parent[y]=x;
gs[x]+=gs[y];
if(rank[x]==rank[y]) ++rank[x];
}
--count_group;
}
bool is_same_group(int x,int y){
return find(x)==find(y);
}
int group_size(int x){
return gs[find(x)];
};
};
void solve(){
int n,q;
cin >> n >> q;
vector<edge> edges;
vector<int64_t> cost(n,inf64);
rep(i,0,q){
int a,b;
int64_t c;
cin >> a >> b >> c;
edges.push_back(edge({a,b,c}));
cost[a]=min(cost[a],c+1);
cost[b]=min(cost[b],c+2);
}
rep(i,0,n*2) cost[i%n]=min(cost[i%n],cost[(i-1+n)%n]+2);
rep(i,0,n) edges.push_back(edge({i,(i+1)%n,cost[i]}));
sort(edges.begin(),edges.end());
union_find uf(n);
int64_t ans=0;
for(edge &e:edges){
if(uf.is_same_group(e.from,e.to)) continue;
uf.unite(e.from,e.to);
ans+=e.cost;
}
cout << ans << endl;
}
int main(){
std::cin.tie(0);
std::ios::sync_with_stdio(false);
cout.setf(ios::fixed);
cout.precision(10);
solve();
return 0;
}
| Python | N = int(input())
ac = 0
wa = 0
tle = 0
re = 0
for i in range(N):
s = input()
if s == 'AC': ac += 1
if s == 'WA': wa += 1
if s == 'TLE': tle += 1
if s == 'RE': re += 1
print('AC x ' + str(ac))
print('WA x ' + str(wa))
print('TLE x ' + str(tle))
print('RE x ' + str(re)) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
#define rep(i,x,y) for(int i=(x);i<(y);++i)
#define debug(x) #x << "=" << (x)
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl
#else
#define print(x)
#endif
const int inf=1e9;
const int64_t inf64=1e18;
const double eps=1e-9;
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){
os << "[";
for (const auto &v : vec) {
os << v << ",";
}
os << "]";
return os;
}
struct edge{
int from,to;
int64_t cost;
bool operator<(const edge &other)const{
return cost<other.cost;
}
};
class union_find{
private:
vector<int> parent,rank,gs;
int size;
public:
int count_group;
union_find()=default;
union_find(int n){ init(n); }
void init(int n){
size=n;
count_group=n;
parent.resize(size);
rank.assign(size,0);
gs.assign(size,1);
for(int i=0; i<size; ++i) parent[i]=i;
}
int find(int x){
if(parent[x]==x) return x;
else return parent[x]=find(parent[x]);
}
void unite(int x,int y){
x=find(x);
y=find(y);
if(x==y) return;
if(rank[x]<rank[y]){
parent[x]=y;
gs[y]+=gs[x];
} else {
parent[y]=x;
gs[x]+=gs[y];
if(rank[x]==rank[y]) ++rank[x];
}
--count_group;
}
bool is_same_group(int x,int y){
return find(x)==find(y);
}
int group_size(int x){
return gs[find(x)];
};
};
void solve(){
int n,q;
cin >> n >> q;
vector<edge> edges;
vector<int64_t> cost(n,inf64);
rep(i,0,q){
int a,b;
int64_t c;
cin >> a >> b >> c;
edges.push_back(edge({a,b,c}));
cost[a]=min(cost[a],c+1);
cost[b]=min(cost[b],c+2);
}
rep(i,0,n*2) cost[i%n]=min(cost[i%n],cost[(i-1+n)%n]+2);
rep(i,0,n) edges.push_back(edge({i,(i+1)%n,cost[i]}));
sort(edges.begin(),edges.end());
union_find uf(n);
int64_t ans=0;
for(edge &e:edges){
if(uf.is_same_group(e.from,e.to)) continue;
uf.unite(e.from,e.to);
ans+=e.cost;
}
cout << ans << endl;
}
int main(){
std::cin.tie(0);
std::ios::sync_with_stdio(false);
cout.setf(ios::fixed);
cout.precision(10);
solve();
return 0;
}
Code 2: N = int(input())
ac = 0
wa = 0
tle = 0
re = 0
for i in range(N):
s = input()
if s == 'AC': ac += 1
if s == 'WA': wa += 1
if s == 'TLE': tle += 1
if s == 'RE': re += 1
print('AC x ' + str(ac))
print('WA x ' + str(wa))
print('TLE x ' + str(tle))
print('RE x ' + str(re)) |
C |
#include<stdio.h>
int main()
{
int n,m;
int i=0, j=0;
int A[101][101]={0};
int b[101]={0};
int c[101]={0};
scanf("%d %d",&n, &m);
for(i=0; i<n; i++){
for(j=0; j<m; j++){
scanf("%d",&A[i][j]);
}
}
for(j=0; j<m; j++){
scanf("%d",&b[j]);
}
for(i=0; i<n; i++){
for(j=0; j<m; j++){
c[i] += A[i][j] * b[j];
}
}
for(i=0; i<n; i++){
printf("%d\n",c[i]);
}
return 0;
}
| C++ | #include <bits/stdc++.h>
using namespace std;
int main()
{
int N, K, get_person, temp, count = 0;
cin >> N >> K;
vector<int> sunuke(100);
for (int i = 0; i < K; i++)
{
cin >> get_person;
for (int j = 0; j < get_person; j++)
{
cin >> temp;
sunuke.at(temp - 1)++;
}
}
for (int i = 0; i < N; i++)
{
if (sunuke.at(i) == 0)
{
count++;
}
}
cout << count << endl;
return 0;
} | No | Do these codes solve the same problem?
Code 1:
#include<stdio.h>
int main()
{
int n,m;
int i=0, j=0;
int A[101][101]={0};
int b[101]={0};
int c[101]={0};
scanf("%d %d",&n, &m);
for(i=0; i<n; i++){
for(j=0; j<m; j++){
scanf("%d",&A[i][j]);
}
}
for(j=0; j<m; j++){
scanf("%d",&b[j]);
}
for(i=0; i<n; i++){
for(j=0; j<m; j++){
c[i] += A[i][j] * b[j];
}
}
for(i=0; i<n; i++){
printf("%d\n",c[i]);
}
return 0;
}
Code 2: #include <bits/stdc++.h>
using namespace std;
int main()
{
int N, K, get_person, temp, count = 0;
cin >> N >> K;
vector<int> sunuke(100);
for (int i = 0; i < K; i++)
{
cin >> get_person;
for (int j = 0; j < get_person; j++)
{
cin >> temp;
sunuke.at(temp - 1)++;
}
}
for (int i = 0; i < N; i++)
{
if (sunuke.at(i) == 0)
{
count++;
}
}
cout << count << endl;
return 0;
} |
C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ITP2_7_A
{
public class Program
{
public static void Main(string[] args)
{
int n = ReadInt();
HashSet<int> hs = new HashSet<int>();
for (int i = 0 ; i < n ; i++)
{
int[] line = ReadIntAr();
switch (line[0])
{
case 0:
hs.Add(line[1]);
Console.WriteLine(hs.Count());
break;
case 1:
Console.WriteLine(hs.Contains(line[1])?1:0);
break;
}
}
}
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 (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
s := make(map[string]bool)
sum := 0
for sc.Scan() {
inputs := strings.Split(sc.Text(), " ")
if inputs[0] == "0" {
if !s[inputs[1]] {
s[inputs[1]] = true
sum++
}
fmt.Printf("%d\n", sum)
} else if inputs[0] == "1" {
if s[inputs[1]] {
fmt.Println(1)
} else {
fmt.Println(0)
}
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ITP2_7_A
{
public class Program
{
public static void Main(string[] args)
{
int n = ReadInt();
HashSet<int> hs = new HashSet<int>();
for (int i = 0 ; i < n ; i++)
{
int[] line = ReadIntAr();
switch (line[0])
{
case 0:
hs.Add(line[1]);
Console.WriteLine(hs.Count());
break;
case 1:
Console.WriteLine(hs.Contains(line[1])?1:0);
break;
}
}
}
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 (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
s := make(map[string]bool)
sum := 0
for sc.Scan() {
inputs := strings.Split(sc.Text(), " ")
if inputs[0] == "0" {
if !s[inputs[1]] {
s[inputs[1]] = true
sum++
}
fmt.Printf("%d\n", sum)
} else if inputs[0] == "1" {
if s[inputs[1]] {
fmt.Println(1)
} else {
fmt.Println(0)
}
}
}
}
|
Java | import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int[] array = new int[n];
int i;
for(i=0;i<n;i++){
array[i] = sc.nextInt();
}
for(i=n-1;i>=1;i--){
System.out.print(array[i]+" ");
}
System.out.println(array[0]);
sc.close();
}
}
| C++ | #include <iostream>
using namespace std;
int main(){
int N,M,i,a;
cin>>N;
cin>>M;
for(i=0;i<M;i++){
cin>>a;
}
cout << N-M-1<<endl;
return 0;
}
| No | Do these codes solve the same problem?
Code 1: import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int[] array = new int[n];
int i;
for(i=0;i<n;i++){
array[i] = sc.nextInt();
}
for(i=n-1;i>=1;i--){
System.out.print(array[i]+" ");
}
System.out.println(array[0]);
sc.close();
}
}
Code 2: #include <iostream>
using namespace std;
int main(){
int N,M,i,a;
cin>>N;
cin>>M;
for(i=0;i<M;i++){
cin>>a;
}
cout << N-M-1<<endl;
return 0;
}
|
Python | import sys
import collections
input = sys.stdin.readline
n = int(input())
s = [''.join(sorted(input())) for _ in range(n)]
dup = collections.Counter(s).values()
ans = sum(c*(c-1)//2 for c in dup)
print(ans)
| JavaScript | var read = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
obj = init(inLine);
myerr("-----start-----");
var start = new Date();
Main();
var end = new Date() - start;
myerr("----- end -----");
myerr("time : " + (end) + "ms");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
var returnObj = {
list : input, index : 0, max : input.length,
hasNext : function(){return (this.index < this.max);},
next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
};
return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割 7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
var N = nextInt();
var list = new Array(N);
for(var i = 0; i < N; i++){
list[i] = {
child : new Set(),
from : null,
access : false,
color : null,
count : 0
};
}
for(var i = 0; i < N - 1; i++){
var tmp = nextIntArray();
list[tmp[0] - 1].child.add(tmp[1] - 1);
list[tmp[1] - 1].child.add(tmp[0] - 1);
}
var queue = new Array(100007);
queue[0] = 0;
list[0].access = true;
var mae = 0;
var ato = 1;
while(mae != ato){
var parent = queue[mae];
mae++;
if(parent == N - 1){
break;
}
var child = Array.from(list[parent].child);
for(var i = 0; i < child.length; i++){
if(!list[child[i]].access){
list[child[i]].access = true;
list[child[i]].from = parent;
queue[ato] = child[i];
list[child[i]].count = list[parent].count + 1;
ato++;
}
}
}
var cut = Math.ceil(list[N - 1].count / 2);
var now = N - 1;
while(cut != 0){
now = list[now].from;
cut--;
}
list[0].color = "BLACK";
list[N - 1].color = "WHITE";
list[now].color = "BLACK";
bfs(0,"BLACK");
bfs(N - 1,"WHITE");
var w = 0;
var b = 0;
for(var i = 0; i < N; i++){
if(list[i].color == "WHITE"){
w++;
}else{
b++;
}
}
if(b > w){
myout("Fennec");
}else{
myout("Snuke");
}
function bfs(index, color){
var queue = new Array(100007);
var mae = 0;
var ato = 1;
queue[mae] = index;
while(mae != ato){
var parent = queue[mae];
mae++;
var child = Array.from(list[parent].child);
for(var i = 0; i < child.length; i++){
if(list[child[i]].color == null){
queue[ato] = child[i];
ato++;
list[child[i]].color = color;
}
}
}
}
}
| No | Do these codes solve the same problem?
Code 1: import sys
import collections
input = sys.stdin.readline
n = int(input())
s = [''.join(sorted(input())) for _ in range(n)]
dup = collections.Counter(s).values()
ans = sum(c*(c-1)//2 for c in dup)
print(ans)
Code 2: var read = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
obj = init(inLine);
myerr("-----start-----");
var start = new Date();
Main();
var end = new Date() - start;
myerr("----- end -----");
myerr("time : " + (end) + "ms");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
var returnObj = {
list : input, index : 0, max : input.length,
hasNext : function(){return (this.index < this.max);},
next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
};
return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割 7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
var N = nextInt();
var list = new Array(N);
for(var i = 0; i < N; i++){
list[i] = {
child : new Set(),
from : null,
access : false,
color : null,
count : 0
};
}
for(var i = 0; i < N - 1; i++){
var tmp = nextIntArray();
list[tmp[0] - 1].child.add(tmp[1] - 1);
list[tmp[1] - 1].child.add(tmp[0] - 1);
}
var queue = new Array(100007);
queue[0] = 0;
list[0].access = true;
var mae = 0;
var ato = 1;
while(mae != ato){
var parent = queue[mae];
mae++;
if(parent == N - 1){
break;
}
var child = Array.from(list[parent].child);
for(var i = 0; i < child.length; i++){
if(!list[child[i]].access){
list[child[i]].access = true;
list[child[i]].from = parent;
queue[ato] = child[i];
list[child[i]].count = list[parent].count + 1;
ato++;
}
}
}
var cut = Math.ceil(list[N - 1].count / 2);
var now = N - 1;
while(cut != 0){
now = list[now].from;
cut--;
}
list[0].color = "BLACK";
list[N - 1].color = "WHITE";
list[now].color = "BLACK";
bfs(0,"BLACK");
bfs(N - 1,"WHITE");
var w = 0;
var b = 0;
for(var i = 0; i < N; i++){
if(list[i].color == "WHITE"){
w++;
}else{
b++;
}
}
if(b > w){
myout("Fennec");
}else{
myout("Snuke");
}
function bfs(index, color){
var queue = new Array(100007);
var mae = 0;
var ato = 1;
queue[mae] = index;
while(mae != ato){
var parent = queue[mae];
mae++;
var child = Array.from(list[parent].child);
for(var i = 0; i < child.length; i++){
if(list[child[i]].color == null){
queue[ato] = child[i];
ato++;
list[child[i]].color = color;
}
}
}
}
}
|
C | #include<stdio.h>
int main(void)
{
int a,b,c;
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
if(a<b&&b<c)
printf("Yes\n");
else
printf("No\n");
return 0;
}
| C++ | #include<iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << a / b << ' '
<< a % b << ' '
<< fixed << (double) a / (double) b << endl;
} | No | Do these codes solve the same problem?
Code 1: #include<stdio.h>
int main(void)
{
int a,b,c;
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
if(a<b&&b<c)
printf("Yes\n");
else
printf("No\n");
return 0;
}
Code 2: #include<iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << a / b << ' '
<< a % b << ' '
<< fixed << (double) a / (double) b << endl;
} |
C# | using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string input1 = Console.ReadLine(); // "red blue";
string input2 = Console.ReadLine(); // "5 5";
string input3 = Console.ReadLine(); // "blue";
var S = input1.Split(' ')[0];
var T = input1.Split(' ')[1];
var A = int.Parse(input2.Split(' ')[0]);
var B = int.Parse(input2.Split(' ')[1]);
var U = input3;
Dictionary<string, int> counts = new Dictionary<string, int>();
counts.Add(S, A);
counts.Add(T, B);
counts[U]--;
Console.WriteLine($"{counts[S]} {counts[T]}");
}
} | Python | import heapq
from sys import stdin
input = stdin.readline
#入力
# s = input()
# n = int(input())
# a,b = map(int, input().split())
# a = list(map(int,input().split()))
# w = [int(input()) for i in range(n)]
# ab=[]
# for i in range(m):
# a,b = map(int, input().split())
# ab.append((a,b))
def main():
a,b = map(int, input().split())
ans = 0
while a <=b:
ans+=1
a*=2
print(ans)
if __name__ == '__main__':
main() | No | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string input1 = Console.ReadLine(); // "red blue";
string input2 = Console.ReadLine(); // "5 5";
string input3 = Console.ReadLine(); // "blue";
var S = input1.Split(' ')[0];
var T = input1.Split(' ')[1];
var A = int.Parse(input2.Split(' ')[0]);
var B = int.Parse(input2.Split(' ')[1]);
var U = input3;
Dictionary<string, int> counts = new Dictionary<string, int>();
counts.Add(S, A);
counts.Add(T, B);
counts[U]--;
Console.WriteLine($"{counts[S]} {counts[T]}");
}
}
Code 2: import heapq
from sys import stdin
input = stdin.readline
#入力
# s = input()
# n = int(input())
# a,b = map(int, input().split())
# a = list(map(int,input().split()))
# w = [int(input()) for i in range(n)]
# ab=[]
# for i in range(m):
# a,b = map(int, input().split())
# ab.append((a,b))
def main():
a,b = map(int, input().split())
ans = 0
while a <=b:
ans+=1
a*=2
print(ans)
if __name__ == '__main__':
main() |
Python | from sys import stdin
from itertools import repeat
def main():
L, n = map(int, stdin.readline().split())
a = map(int, stdin.read().split(), repeat(10, n))
sr = [0] * (n + 1)
sl = [0] * (n + 1)
for i in xrange(n):
sl[i+1] = sl[i] + a[i]
for i in xrange(n - 1, 0, -1):
sr[i-1] = sr[i] + L - a[i]
ans = 0
for i in xrange(n):
l = i
r = n - 1 - i
if l < r:
r = l + 1
else:
l = r
t = (sr[i] - sr[i+r] + sl[i] - sl[i-l]) * 2 + a[i]
if ans < t:
ans = t
for i in xrange(n - 1, -1, -1):
l = i
r = n - 1 - i
if l > r:
l = r + 1
else:
r = l
t = (sr[i] - sr[i+r] + sl[i] - sl[i-l]) * 2 + L - a[i]
if ans < t:
ans = t
print ans
main()
| Java | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov (egor@egork.net)
*/
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);
BTreeBurning solver = new BTreeBurning();
solver.solve(1, in, out);
out.close();
}
static class BTreeBurning {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long l = in.readInt();
int n = in.readInt();
int[] x = in.readIntArray(n);
long answer = 0;
for (int j = 0; j < 2; j++) {
long[] sums = ArrayUtils.partialSums(x);
for (int i = 0; i < n; i++) {
int last = (n + i) >> 1;
int forward = (n + i - 1) >> 1;
long current =
2 * (sums[forward + 1] - sums[i] + (n - forward - 1) * l - (sums[n] - sums[forward + 1]));
if (((n - i) & 1) == 0) {
current -= l - x[last];
} else {
current -= x[last];
}
answer = Math.max(answer, current);
}
ArrayUtils.reverse(x);
for (int i = 0; i < n; i++) {
x[i] = (int) (l - x[i]);
}
}
out.printLine(answer);
}
}
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 interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
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 int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
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 interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface IntCollection extends IntStream {
public int size();
}
static class ArrayUtils {
public static void reverse(int[] array) {
new IntArray(array).inPlaceReverse();
}
public static long[] partialSums(int[] array) {
long[] result = new long[array.length + 1];
for (int i = 0; i < array.length; i++) {
result[i + 1] = result[i] + array[i];
}
return result;
}
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void set(int index, int value);
public abstract void removeAt(int index);
default public void swap(int first, int second) {
if (first == second) {
return;
}
int temp = get(first);
set(first, get(second));
set(second, temp);
}
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void inPlaceReverse() {
for (int i = 0, j = size() - 1; i < j; i++, j--) {
swap(i, j);
}
}
}
static interface IntReversableCollection extends IntCollection {
}
static class IntArray extends IntAbstractStream implements IntList {
private int[] data;
public IntArray(int[] arr) {
data = arr;
}
public int size() {
return data.length;
}
public int get(int at) {
return data[at];
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int index, int value) {
data[index] = value;
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: from sys import stdin
from itertools import repeat
def main():
L, n = map(int, stdin.readline().split())
a = map(int, stdin.read().split(), repeat(10, n))
sr = [0] * (n + 1)
sl = [0] * (n + 1)
for i in xrange(n):
sl[i+1] = sl[i] + a[i]
for i in xrange(n - 1, 0, -1):
sr[i-1] = sr[i] + L - a[i]
ans = 0
for i in xrange(n):
l = i
r = n - 1 - i
if l < r:
r = l + 1
else:
l = r
t = (sr[i] - sr[i+r] + sl[i] - sl[i-l]) * 2 + a[i]
if ans < t:
ans = t
for i in xrange(n - 1, -1, -1):
l = i
r = n - 1 - i
if l > r:
l = r + 1
else:
r = l
t = (sr[i] - sr[i+r] + sl[i] - sl[i-l]) * 2 + L - a[i]
if ans < t:
ans = t
print ans
main()
Code 2: import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Egor Kulikov (egor@egork.net)
*/
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);
BTreeBurning solver = new BTreeBurning();
solver.solve(1, in, out);
out.close();
}
static class BTreeBurning {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long l = in.readInt();
int n = in.readInt();
int[] x = in.readIntArray(n);
long answer = 0;
for (int j = 0; j < 2; j++) {
long[] sums = ArrayUtils.partialSums(x);
for (int i = 0; i < n; i++) {
int last = (n + i) >> 1;
int forward = (n + i - 1) >> 1;
long current =
2 * (sums[forward + 1] - sums[i] + (n - forward - 1) * l - (sums[n] - sums[forward + 1]));
if (((n - i) & 1) == 0) {
current -= l - x[last];
} else {
current -= x[last];
}
answer = Math.max(answer, current);
}
ArrayUtils.reverse(x);
for (int i = 0; i < n; i++) {
x[i] = (int) (l - x[i]);
}
}
out.printLine(answer);
}
}
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 interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
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 int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
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 interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface IntCollection extends IntStream {
public int size();
}
static class ArrayUtils {
public static void reverse(int[] array) {
new IntArray(array).inPlaceReverse();
}
public static long[] partialSums(int[] array) {
long[] result = new long[array.length + 1];
for (int i = 0; i < array.length; i++) {
result[i + 1] = result[i] + array[i];
}
return result;
}
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void set(int index, int value);
public abstract void removeAt(int index);
default public void swap(int first, int second) {
if (first == second) {
return;
}
int temp = get(first);
set(first, get(second));
set(second, temp);
}
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void inPlaceReverse() {
for (int i = 0, j = size() - 1; i < j; i++, j--) {
swap(i, j);
}
}
}
static interface IntReversableCollection extends IntCollection {
}
static class IntArray extends IntAbstractStream implements IntList {
private int[] data;
public IntArray(int[] arr) {
data = arr;
}
public int size() {
return data.length;
}
public int get(int at) {
return data[at];
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int index, int value) {
data[index] = value;
}
}
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int mod = 1000000007;
const int INF = 1000000000;
const double EPS = 1e-9;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N, A;
cin >> N >> A;
vector<int> x(N + 1);
int K = A;
for (int i = 1; i <= N; ++i) {
cin >> x[i];
K = max(K, x[i]);
x[i] -= A;
}
K = A;
vector<vector<ll>> dp(N + 1, vector<ll>(2*K*N + 1, 0));
dp[0][K*N] = 1;
for (int j = 0; j <= N; ++j) {
for (int s = 0; s <= 2*K*N; ++s) {
if (j >= 1 && x[j] > s) dp[j][s] = dp[j-1][s];
if (j >= 1 && x[j] <= s) dp[j][s] = dp[j-1][s] + dp[j-1][s-x[j]];
}
}
cout << dp[N][K*N] - 1 << endl;
}
| Python | import math
a, b = map(int, input().split())
print(math.ceil((a+b)/2)) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int mod = 1000000007;
const int INF = 1000000000;
const double EPS = 1e-9;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N, A;
cin >> N >> A;
vector<int> x(N + 1);
int K = A;
for (int i = 1; i <= N; ++i) {
cin >> x[i];
K = max(K, x[i]);
x[i] -= A;
}
K = A;
vector<vector<ll>> dp(N + 1, vector<ll>(2*K*N + 1, 0));
dp[0][K*N] = 1;
for (int j = 0; j <= N; ++j) {
for (int s = 0; s <= 2*K*N; ++s) {
if (j >= 1 && x[j] > s) dp[j][s] = dp[j-1][s];
if (j >= 1 && x[j] <= s) dp[j][s] = dp[j-1][s] + dp[j-1][s-x[j]];
}
}
cout << dp[N][K*N] - 1 << endl;
}
Code 2: import math
a, b = map(int, input().split())
print(math.ceil((a+b)/2)) |
C++ | #include <bits/stdc++.h>
using namespace std;
int n, m;
int a[10][10];
const long mod = 2019;
int main() {
long l, r;
cin >> l >> r;
long mn = mod;
for (long i = l; i <= min(r, l + mod); ++i) {
for (long j = i + 1; j <= min(r, i + 1 + mod); ++j) {
mn = min(mn, i * j % mod);
}
}
cout << mn << endl;
} | Python | N, K = map(int, input().split())
H_list = list(map(int, input().split()))
H_list.sort()
if K >= len(H_list):
print(0)
else:
for i in range(K):
H_list[-i - 1] = 0
print(sum(H_list)) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int n, m;
int a[10][10];
const long mod = 2019;
int main() {
long l, r;
cin >> l >> r;
long mn = mod;
for (long i = l; i <= min(r, l + mod); ++i) {
for (long j = i + 1; j <= min(r, i + 1 + mod); ++j) {
mn = min(mn, i * j % mod);
}
}
cout << mn << endl;
}
Code 2: N, K = map(int, input().split())
H_list = list(map(int, input().split()))
H_list.sort()
if K >= len(H_list):
print(0)
else:
for i in range(K):
H_list[-i - 1] = 0
print(sum(H_list)) |
C++ | #include <bits/stdc++.h>
#define REP(i, e) for(int (i) = 0; (i) < (e); ++(i))
#define FOR(i, b, e) for(int (i) = (b); (i) < (e); ++(i))
#define ALL(c) (c).begin(), (c).end()
#define PRINT(x) cout << (x) << "\n"
using namespace std;
using ll = long long; using pint = pair<int, int>; using pll = pair<ll, ll>;
const long long MOD = 1000000007;
template<const long long MOD>
class Modint{
public:
Modint() : x(0) {
}
Modint(long long y) : x((y % MOD + MOD) % MOD) {
}
Modint& operator+=(const Modint& p){
if((x += p.x) >= MOD) x -= MOD;
return *this;
}
Modint& operator-=(const Modint& p){
if((x += MOD - p.x) >= MOD) x -= MOD;
return *this;
}
Modint& operator*=(const Modint& p){
x = x * p.x % MOD;
return *this;
}
Modint& operator/=(const Modint& p){
*this *= p.inverse();
return *this;
}
Modint operator-() const {
return Modint(-x);
}
Modint operator+(const Modint& p) const {
return Modint(*this) += p;
}
Modint operator-(const Modint& p) const {
return Modint(*this) -= p;
}
Modint operator*(const Modint& p) const {
return Modint(*this) *= p;
}
Modint operator/(const Modint& p) const {
return Modint(*this) /= p;
}
bool operator==(const Modint& p) const {
return x == p.x;
}
bool operator!=(const Modint& p) const {
return !(*this == p);
}
bool operator<(const Modint& p) const {
return x < p.x;
}
bool operator>(const Modint& p) const {
return x > p.x;
}
bool operator<=(const Modint& p) const {
return !(*this > p);
}
bool operator>=(const Modint& p) const {
return !(*this < p);
}
Modint inverse() const {
long long a = x, b = MOD, u = 1, v = 0;
while(b > 0){
long long t = a / b;
a -= t * b;
swap(a, b);
u -= t * v;
swap(u, v);
}
return Modint(u);
}
Modint pow(long long n) const {
Modint ret(1), mul(x);
while(n > 0){
if(n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
friend ostream &operator<<(ostream& os, const Modint& p){
return os << p.x;
}
friend istream &operator>>(istream& is, Modint& a){
long long t;
cin >> t;
a = Modint<MOD>(t);
return is;
}
explicit operator long long() const {
return x;
}
static long long get_mod(){
return MOD;
}
private:
long long x;
};
template<const long long MOD>
class Combination_Mod{
public:
Combination_Mod(long long N) : fact(N), inv(N), finv(N), N(N){
init();
}
void init(){
fact[0] = fact[1] = 1;
finv[0] = finv[1] = 1;
inv[1] = 1;
for(long long i = 2; i < N; ++i){
fact[i] = fact[i - 1] * i;
inv[i] = -inv[MOD % i] * (MOD / i);
finv[i] = finv[i - 1] * inv[i];
}
}
Modint<MOD> bin(long long n, long long r){
if(n < r || n < 0 || r < 0) return 0;
return fact[n] * finv[r] * finv[n - r];
}
Modint<MOD> perm(long long n, long long r){
return bin(n, r) * fact[r];
}
Modint<MOD> factorial(long long n){
return fact[n];
}
Modint<MOD> inverse(long long n){
return inv[n];
}
Modint<MOD> fact_inverse(long long n){
return finv[n];
}
private:
vector<Modint<MOD>> fact;
vector<Modint<MOD>> inv;
vector<Modint<MOD>> finv;
const long long N;
};
using mint = Modint<MOD>;
Combination_Mod<MOD> cm(3000);
signed main(){
ll S;
cin >> S;
mint ans = 0;
FOR(i, 1, S / 3 + 1){
ans += cm.bin(i + (S - 3 * i) - 1, S - 3 * i);
}
PRINT(ans);
return 0;
} | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define min(a, b) (((a) < (b)) ? (a) : (b)) /* 2個の値の最小値 */
/********************************************************************************************************************************/
/* main *************************************************************************************************************************/
/********************************************************************************************************************************/
int DEBUG = 0; /* デバッグプリント 提出時は0 */
int main()
{
int N;
int i,j, a,b,ba;
char s[10000][11];
int ans = 0;
scanf("%d", &N);
for (i=0; i<N; i++) {
scanf("%s", s[i]);
for(j=0; j<10; j++) {
if (s[i][j+1]==0) break;
if ((s[i][j]=='A')&&(s[i][j+1]=='B')) ans++;
}
s[i][1] = s[i][strlen(s[i])-1];
s[i][2] = 0;
}
a = b = ba = 0;
for (i=0; i<N; i++) {
if (s[i][0]=='B') {
if (s[i][1]=='A') {
ba++;
} else {
b++;
}
}
if ((s[i][1]=='A')&&(s[i][0]!='B')) a++;
}
if (DEBUG) printf("a b ba : %d %d %d\n",a,b,ba);
if (ba==0) ans += min(a,b);
if (ba!=0) {
ans += ba-1;
if (a>0) { ans++; a--; }
if (b>0) { ans++; b--; }
ans += min(a,b);
}
printf("%d\n",ans);
return 0;
}
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#define REP(i, e) for(int (i) = 0; (i) < (e); ++(i))
#define FOR(i, b, e) for(int (i) = (b); (i) < (e); ++(i))
#define ALL(c) (c).begin(), (c).end()
#define PRINT(x) cout << (x) << "\n"
using namespace std;
using ll = long long; using pint = pair<int, int>; using pll = pair<ll, ll>;
const long long MOD = 1000000007;
template<const long long MOD>
class Modint{
public:
Modint() : x(0) {
}
Modint(long long y) : x((y % MOD + MOD) % MOD) {
}
Modint& operator+=(const Modint& p){
if((x += p.x) >= MOD) x -= MOD;
return *this;
}
Modint& operator-=(const Modint& p){
if((x += MOD - p.x) >= MOD) x -= MOD;
return *this;
}
Modint& operator*=(const Modint& p){
x = x * p.x % MOD;
return *this;
}
Modint& operator/=(const Modint& p){
*this *= p.inverse();
return *this;
}
Modint operator-() const {
return Modint(-x);
}
Modint operator+(const Modint& p) const {
return Modint(*this) += p;
}
Modint operator-(const Modint& p) const {
return Modint(*this) -= p;
}
Modint operator*(const Modint& p) const {
return Modint(*this) *= p;
}
Modint operator/(const Modint& p) const {
return Modint(*this) /= p;
}
bool operator==(const Modint& p) const {
return x == p.x;
}
bool operator!=(const Modint& p) const {
return !(*this == p);
}
bool operator<(const Modint& p) const {
return x < p.x;
}
bool operator>(const Modint& p) const {
return x > p.x;
}
bool operator<=(const Modint& p) const {
return !(*this > p);
}
bool operator>=(const Modint& p) const {
return !(*this < p);
}
Modint inverse() const {
long long a = x, b = MOD, u = 1, v = 0;
while(b > 0){
long long t = a / b;
a -= t * b;
swap(a, b);
u -= t * v;
swap(u, v);
}
return Modint(u);
}
Modint pow(long long n) const {
Modint ret(1), mul(x);
while(n > 0){
if(n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
friend ostream &operator<<(ostream& os, const Modint& p){
return os << p.x;
}
friend istream &operator>>(istream& is, Modint& a){
long long t;
cin >> t;
a = Modint<MOD>(t);
return is;
}
explicit operator long long() const {
return x;
}
static long long get_mod(){
return MOD;
}
private:
long long x;
};
template<const long long MOD>
class Combination_Mod{
public:
Combination_Mod(long long N) : fact(N), inv(N), finv(N), N(N){
init();
}
void init(){
fact[0] = fact[1] = 1;
finv[0] = finv[1] = 1;
inv[1] = 1;
for(long long i = 2; i < N; ++i){
fact[i] = fact[i - 1] * i;
inv[i] = -inv[MOD % i] * (MOD / i);
finv[i] = finv[i - 1] * inv[i];
}
}
Modint<MOD> bin(long long n, long long r){
if(n < r || n < 0 || r < 0) return 0;
return fact[n] * finv[r] * finv[n - r];
}
Modint<MOD> perm(long long n, long long r){
return bin(n, r) * fact[r];
}
Modint<MOD> factorial(long long n){
return fact[n];
}
Modint<MOD> inverse(long long n){
return inv[n];
}
Modint<MOD> fact_inverse(long long n){
return finv[n];
}
private:
vector<Modint<MOD>> fact;
vector<Modint<MOD>> inv;
vector<Modint<MOD>> finv;
const long long N;
};
using mint = Modint<MOD>;
Combination_Mod<MOD> cm(3000);
signed main(){
ll S;
cin >> S;
mint ans = 0;
FOR(i, 1, S / 3 + 1){
ans += cm.bin(i + (S - 3 * i) - 1, S - 3 * i);
}
PRINT(ans);
return 0;
}
Code 2: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define min(a, b) (((a) < (b)) ? (a) : (b)) /* 2個の値の最小値 */
/********************************************************************************************************************************/
/* main *************************************************************************************************************************/
/********************************************************************************************************************************/
int DEBUG = 0; /* デバッグプリント 提出時は0 */
int main()
{
int N;
int i,j, a,b,ba;
char s[10000][11];
int ans = 0;
scanf("%d", &N);
for (i=0; i<N; i++) {
scanf("%s", s[i]);
for(j=0; j<10; j++) {
if (s[i][j+1]==0) break;
if ((s[i][j]=='A')&&(s[i][j+1]=='B')) ans++;
}
s[i][1] = s[i][strlen(s[i])-1];
s[i][2] = 0;
}
a = b = ba = 0;
for (i=0; i<N; i++) {
if (s[i][0]=='B') {
if (s[i][1]=='A') {
ba++;
} else {
b++;
}
}
if ((s[i][1]=='A')&&(s[i][0]!='B')) a++;
}
if (DEBUG) printf("a b ba : %d %d %d\n",a,b,ba);
if (ba==0) ans += min(a,b);
if (ba!=0) {
ans += ba-1;
if (a>0) { ans++; a--; }
if (b>0) { ans++; b--; }
ans += min(a,b);
}
printf("%d\n",ans);
return 0;
}
|
Python | #!/usr/bin/env python3
from math import *
import heapq
def disktra(g,s):
n=len(g)
dist = [inf]*n
dist[s] = 0
hq=[]
heapq.heappush(hq,(dist[s],s))
while hq:
cost,u =heapq.heappop(hq)
if dist[u] < cost:
continue
for v,c in g[u]:
if dist[v] <= dist[u] +c:
continue
dist[v] = dist[u] + c
heapq.heappush(hq,(dist[v],v))
return dist
while True:
n, k = map(int, input().split())
if n == 0 and k == 0:
break
G = [[]*n for i in range(n)]
used = [0]*n
E = [[float('inf')]*n for i in range(n)]
for i in range(k):
inp = tuple(map(int, input().split()))
if inp[0] == 1:
c, d, e = inp[1:]
c -= 1
d -= 1
G[c].append((d,e))
G[d].append((c,e))
# E[c][d] = min(E[c][d], e)
# E[d][c] = min(E[d][c], e)
else:
# for i in G:
# print(i)
a, b = inp[1:]
a-=1
b-=1
d=disktra(G,a)
print(-1 if d[b]==inf else d[b])
# dis = [float('inf')]*n
# dis[a] = 0
# mv = a
# for v in G[a]:
# m = float('inf')
# if not used[v]:
# if m >dis[v]:
# m = dis[v]
# mv = v
# used[mv]=1
# # print(dis)
# for i in G[mv]:
# dis[i] = min(dis[i],dis[mv]+E[mv][i])
# print(dis)
# print(-1 if dis[b] == float('inf') else dis[b])
# while True:
# n, k = map(int, input().split())
# if n == 0 and k == 0:
# break
# G = [[]*n for i in range(n)]
# used = [0]*n
# dis = [float('inf')]*n
# E = [[float('inf')]*n for i in range(n)]
# dis[0]=0
# for i in range(k):
# inp = tuple(map(int, input().split()))
# if inp[0] == 1:
# c, d, e = inp[1:]
# c -= 1
# d -= 1
# G[c].append(d)
# G[d].append(c)
# E[c][d] = min(E[c][d], e)
# E[d][c] = min(E[d][c], e)
# else:
# a, b = inp[1:]
# a-=1;b-=1
# mv=a
# for v in G[a]:
# m=float('inf')
# if not used[v]:
# if m>dis[v]:
# m=dis[v]
# mv=v
# for i in G[mv]:
# dis[i]=min(dis[i],dis[mv]+E[mv][i])
# # print(dis)
# print(-1 if dis[b]==float('inf') else dis[b])
| Java | import java.util.Scanner;
public class Main {
static int a,b;
public static void main(String args[]){
Scanner s=new Scanner(System.in);
while(true){
a=s.nextInt();
b=s.nextInt();
if(a==0)System.exit(0);
int[][] map = new int[a+1][a+1];
for(int i=1; i<=a; i++) {
for(int j=1; j<=a; j++) {
map[i][j] = 1<<25;
if(i==j)map[i][j]=0;
}
}
for(int n=0; n<b; n++) {
int c = s.nextInt();
if(c==1) {
int p = s.nextInt();
int q = s.nextInt();
int w = s.nextInt();
if(map[p][q]<=w)continue;
map[p][q] = w;
map[q][p] = w;
for(int k=1; k<=a; k++) {
for(int i=1; i<=a; i++) {
for(int j=1; j<=a; j++) {
if(map[i][j]>map[i][k]+map[k][j]) {
map[i][j]=map[i][k]+map[k][j];
}
}
}
}
} else {
int x=s.nextInt();
int y=s.nextInt();
if(map[x][y]==1<<25) {
System.out.println(-1);
} else {
System.out.println(map[x][y]);
}
}
}
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: #!/usr/bin/env python3
from math import *
import heapq
def disktra(g,s):
n=len(g)
dist = [inf]*n
dist[s] = 0
hq=[]
heapq.heappush(hq,(dist[s],s))
while hq:
cost,u =heapq.heappop(hq)
if dist[u] < cost:
continue
for v,c in g[u]:
if dist[v] <= dist[u] +c:
continue
dist[v] = dist[u] + c
heapq.heappush(hq,(dist[v],v))
return dist
while True:
n, k = map(int, input().split())
if n == 0 and k == 0:
break
G = [[]*n for i in range(n)]
used = [0]*n
E = [[float('inf')]*n for i in range(n)]
for i in range(k):
inp = tuple(map(int, input().split()))
if inp[0] == 1:
c, d, e = inp[1:]
c -= 1
d -= 1
G[c].append((d,e))
G[d].append((c,e))
# E[c][d] = min(E[c][d], e)
# E[d][c] = min(E[d][c], e)
else:
# for i in G:
# print(i)
a, b = inp[1:]
a-=1
b-=1
d=disktra(G,a)
print(-1 if d[b]==inf else d[b])
# dis = [float('inf')]*n
# dis[a] = 0
# mv = a
# for v in G[a]:
# m = float('inf')
# if not used[v]:
# if m >dis[v]:
# m = dis[v]
# mv = v
# used[mv]=1
# # print(dis)
# for i in G[mv]:
# dis[i] = min(dis[i],dis[mv]+E[mv][i])
# print(dis)
# print(-1 if dis[b] == float('inf') else dis[b])
# while True:
# n, k = map(int, input().split())
# if n == 0 and k == 0:
# break
# G = [[]*n for i in range(n)]
# used = [0]*n
# dis = [float('inf')]*n
# E = [[float('inf')]*n for i in range(n)]
# dis[0]=0
# for i in range(k):
# inp = tuple(map(int, input().split()))
# if inp[0] == 1:
# c, d, e = inp[1:]
# c -= 1
# d -= 1
# G[c].append(d)
# G[d].append(c)
# E[c][d] = min(E[c][d], e)
# E[d][c] = min(E[d][c], e)
# else:
# a, b = inp[1:]
# a-=1;b-=1
# mv=a
# for v in G[a]:
# m=float('inf')
# if not used[v]:
# if m>dis[v]:
# m=dis[v]
# mv=v
# for i in G[mv]:
# dis[i]=min(dis[i],dis[mv]+E[mv][i])
# # print(dis)
# print(-1 if dis[b]==float('inf') else dis[b])
Code 2: import java.util.Scanner;
public class Main {
static int a,b;
public static void main(String args[]){
Scanner s=new Scanner(System.in);
while(true){
a=s.nextInt();
b=s.nextInt();
if(a==0)System.exit(0);
int[][] map = new int[a+1][a+1];
for(int i=1; i<=a; i++) {
for(int j=1; j<=a; j++) {
map[i][j] = 1<<25;
if(i==j)map[i][j]=0;
}
}
for(int n=0; n<b; n++) {
int c = s.nextInt();
if(c==1) {
int p = s.nextInt();
int q = s.nextInt();
int w = s.nextInt();
if(map[p][q]<=w)continue;
map[p][q] = w;
map[q][p] = w;
for(int k=1; k<=a; k++) {
for(int i=1; i<=a; i++) {
for(int j=1; j<=a; j++) {
if(map[i][j]>map[i][k]+map[k][j]) {
map[i][j]=map[i][k]+map[k][j];
}
}
}
}
} else {
int x=s.nextInt();
int y=s.nextInt();
if(map[x][y]==1<<25) {
System.out.println(-1);
} else {
System.out.println(map[x][y]);
}
}
}
}
}
}
|
Python | a=str(input())
if a.isupper():print('A')
else:print('a') | C++ | #include<string>
#include<vector>
#include<iostream>
#include<sstream>
#include<cstdio>
#include<cstdlib>
#include<functional>
#include<algorithm>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<map>
#include<utility>
#include<cmath>
#include<ctime>
#include<complex>
using namespace std;
#define REP(i,s,e) for(int i=int(s);i<=int(e);i++)
#define rep(i,n) for(int i=0;i<int(n);i++)
int main(){
int N,K,a,b;
cin >> N >> K;
rep(i,K){
cin >> a >> b;
if(b<=a && b<=N-a){
if(b%3==0) cout << 3 << endl;
if(b%3==1) cout << 1 << endl;
if(b%3==2) cout << 2 << endl;
}
if(b>a && b<=N-a){
if(a%3==0) cout << 3 << endl;
if(a%3==1) cout << 1 << endl;
if(a%3==2) cout << 2 << endl;
}
if(b>a && b>N-a){
if((N-b+1)%3==0) cout << 3 << endl;
if((N-b+1)%3==1) cout << 1 << endl;
if((N-b+1)%3==2) cout << 2 << endl;
}
if(b<=a && b>N-a){
if((N-a+1)%3==0) cout << 3 << endl;
if((N-a+1)%3==1) cout << 1 << endl;
if((N-a+1)%3==2) cout << 2 << endl;
}
}
return 0;
} | No | Do these codes solve the same problem?
Code 1: a=str(input())
if a.isupper():print('A')
else:print('a')
Code 2: #include<string>
#include<vector>
#include<iostream>
#include<sstream>
#include<cstdio>
#include<cstdlib>
#include<functional>
#include<algorithm>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<map>
#include<utility>
#include<cmath>
#include<ctime>
#include<complex>
using namespace std;
#define REP(i,s,e) for(int i=int(s);i<=int(e);i++)
#define rep(i,n) for(int i=0;i<int(n);i++)
int main(){
int N,K,a,b;
cin >> N >> K;
rep(i,K){
cin >> a >> b;
if(b<=a && b<=N-a){
if(b%3==0) cout << 3 << endl;
if(b%3==1) cout << 1 << endl;
if(b%3==2) cout << 2 << endl;
}
if(b>a && b<=N-a){
if(a%3==0) cout << 3 << endl;
if(a%3==1) cout << 1 << endl;
if(a%3==2) cout << 2 << endl;
}
if(b>a && b>N-a){
if((N-b+1)%3==0) cout << 3 << endl;
if((N-b+1)%3==1) cout << 1 << endl;
if((N-b+1)%3==2) cout << 2 << endl;
}
if(b<=a && b>N-a){
if((N-a+1)%3==0) cout << 3 << endl;
if((N-a+1)%3==1) cout << 1 << endl;
if((N-a+1)%3==2) cout << 2 << endl;
}
}
return 0;
} |
C++ | #include <iostream>
using namespace std;
int main(){
int h,a;
cin >> h >> a;
if(h % a){
cout << h/a + 1;
return 0;
}
cout << h/a;
return 0;
}
| Go | package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
func readf(sc *bufio.Scanner) float64 {
f, err := strconv.ParseFloat(sc.Text(), 64)
if err != nil {
panic(err.Error())
}
return f
}
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
sc.Scan()
n, _ := strconv.Atoi(sc.Text())
v := make([]float64, n)
for i := range v {
sc.Scan()
v[i] = readf(sc)
}
max := 0.0
sort.Float64s(v)
for i := n - 1; i >= 0; i-- {
tmp := Alchemy(v)
if max < tmp {
max = tmp
}
}
fmt.Println(max)
}
func alchemy(x, y float64) float64 {
return (x + y) / 2
}
func Alchemy(list []float64) float64 {
for i := range list {
if i == len(list)-1 {
continue
}
list[i+1] = alchemy(list[i], list[i+1])
}
return list[len(list)-1]
}
func Permute(nums []float64) [][]float64 {
n := factorial(len(nums))
ret := make([][]float64, 0, n)
permute(nums, &ret)
return ret
}
func permute(nums []float64, ret *[][]float64) {
*ret = append(*ret, makeCopy(nums))
n := len(nums)
p := make([]float64, n+1)
for i := 0; i < n+1; i++ {
p[i] = float64(i)
}
for i := 1; i < n; {
p[i]--
j := 0
if i%2 == 1 {
j = int(p[i])
}
nums[i], nums[j] = nums[j], nums[i]
*ret = append(*ret, makeCopy(nums))
for i = 1; p[i] == 0; i++ {
p[i] = float64(i)
}
}
}
func factorial(n int) int {
ret := 1
for i := 2; i <= n; i++ {
ret *= i
}
return ret
}
func makeCopy(nums []float64) []float64 {
return append([]float64{}, nums...)
}
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int main(){
int h,a;
cin >> h >> a;
if(h % a){
cout << h/a + 1;
return 0;
}
cout << h/a;
return 0;
}
Code 2: package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
func readf(sc *bufio.Scanner) float64 {
f, err := strconv.ParseFloat(sc.Text(), 64)
if err != nil {
panic(err.Error())
}
return f
}
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
sc.Scan()
n, _ := strconv.Atoi(sc.Text())
v := make([]float64, n)
for i := range v {
sc.Scan()
v[i] = readf(sc)
}
max := 0.0
sort.Float64s(v)
for i := n - 1; i >= 0; i-- {
tmp := Alchemy(v)
if max < tmp {
max = tmp
}
}
fmt.Println(max)
}
func alchemy(x, y float64) float64 {
return (x + y) / 2
}
func Alchemy(list []float64) float64 {
for i := range list {
if i == len(list)-1 {
continue
}
list[i+1] = alchemy(list[i], list[i+1])
}
return list[len(list)-1]
}
func Permute(nums []float64) [][]float64 {
n := factorial(len(nums))
ret := make([][]float64, 0, n)
permute(nums, &ret)
return ret
}
func permute(nums []float64, ret *[][]float64) {
*ret = append(*ret, makeCopy(nums))
n := len(nums)
p := make([]float64, n+1)
for i := 0; i < n+1; i++ {
p[i] = float64(i)
}
for i := 1; i < n; {
p[i]--
j := 0
if i%2 == 1 {
j = int(p[i])
}
nums[i], nums[j] = nums[j], nums[i]
*ret = append(*ret, makeCopy(nums))
for i = 1; p[i] == 0; i++ {
p[i] = float64(i)
}
}
}
func factorial(n int) int {
ret := 1
for i := 2; i <= n; i++ {
ret *= i
}
return ret
}
func makeCopy(nums []float64) []float64 {
return append([]float64{}, nums...)
}
|
C++ | #include <cstdio>
#include <vector>
#include <queue>
using namespace std;
int f[100000];
vector <int> v[100000];
int main() {
int n, m, x, y, i;
deque <int> d;
scanf("%d %d", &n, &m);
for (i = 0; i < m; i++) {
int x, y;
scanf("%d %d", &x, &y);
x--;
y--;
v[x].push_back(y);
v[y].push_back(x);
}
x = 0;
y = v[0][0];
f[x] = f[y] = 1;
d.push_back(x);
d.push_back(y);
while (1) {
for (i = 0; i < v[x].size(); i++) {
if (f[v[x][i]] == 0) break;
}
if (i == v[x].size()) break;
x = v[x][i];
f[x] = 1;
d.push_front(x);
}
while (1) {
for (i = 0; i < v[y].size(); i++) {
if (f[v[y][i]] == 0) break;
}
if (i == v[y].size()) break;
y = v[y][i];
f[y] = 1;
d.push_back(y);
}
printf("%d\n", d.size());
for (i = 0; i < d.size(); i++) {
if (i > 0) putchar(' ');
printf("%d", d[i] + 1);
}
puts("");
return 0;
}
| Python | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys # {{{
import os
import time
import re
from pydoc import help
import string
import math
from operator import itemgetter
from collections import Counter
from collections import deque
from collections import defaultdict as dd
import fractions
from heapq import heappop, heappush, heapify
import array
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy as dcopy
import itertools
# }}}
# pre-defined{{{
sys.setrecursionlimit(10**7)
INF = 10**20
GOSA = 1.0 / 10**10
MOD = 10**9+7
ALPHABETS = [chr(i) for i in range(ord('a'), ord('z')+1)] # can also use string module
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def DP(N, M, first): return [[first] * M for n in range(N)]
def DP3(N, M, L, first): return [[[first] * L for n in range(M)] for _ in range(N)]
from inspect import currentframe
# }}}
def local_input():# {{{
from pcm.utils import set_stdin
import sys
from pathlib import Path
parentdir = Path(os.path.dirname(__file__)).parent
inputfile = parentdir.joinpath('test/sample-1.in')
if len(sys.argv) == 1:
set_stdin(inputfile)
# }}}
def solve():
N = int(input())
X = []
for i in range(N):
S,P = map(str, input().split())
P = int(P)
X.append((S,P,i))
X.sort(key=lambda x: x[1], reverse=True)
X.sort(key=lambda x: x[0])
for x in X:
print(x[2]+1)
return 0
if __name__ == "__main__":# {{{
try:
local_input()
def dump(*args):
names = {id(v):k for k,v in currentframe().f_back.f_locals.items()}
print(', '.join(names.get(id(arg),'???')+' => '+repr(arg) for arg in args), file=sys.stderr)
except:
def dump(*args):
pass
solve()
# vim: set foldmethod=marker:}}}
| No | Do these codes solve the same problem?
Code 1: #include <cstdio>
#include <vector>
#include <queue>
using namespace std;
int f[100000];
vector <int> v[100000];
int main() {
int n, m, x, y, i;
deque <int> d;
scanf("%d %d", &n, &m);
for (i = 0; i < m; i++) {
int x, y;
scanf("%d %d", &x, &y);
x--;
y--;
v[x].push_back(y);
v[y].push_back(x);
}
x = 0;
y = v[0][0];
f[x] = f[y] = 1;
d.push_back(x);
d.push_back(y);
while (1) {
for (i = 0; i < v[x].size(); i++) {
if (f[v[x][i]] == 0) break;
}
if (i == v[x].size()) break;
x = v[x][i];
f[x] = 1;
d.push_front(x);
}
while (1) {
for (i = 0; i < v[y].size(); i++) {
if (f[v[y][i]] == 0) break;
}
if (i == v[y].size()) break;
y = v[y][i];
f[y] = 1;
d.push_back(y);
}
printf("%d\n", d.size());
for (i = 0; i < d.size(); i++) {
if (i > 0) putchar(' ');
printf("%d", d[i] + 1);
}
puts("");
return 0;
}
Code 2: #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys # {{{
import os
import time
import re
from pydoc import help
import string
import math
from operator import itemgetter
from collections import Counter
from collections import deque
from collections import defaultdict as dd
import fractions
from heapq import heappop, heappush, heapify
import array
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy as dcopy
import itertools
# }}}
# pre-defined{{{
sys.setrecursionlimit(10**7)
INF = 10**20
GOSA = 1.0 / 10**10
MOD = 10**9+7
ALPHABETS = [chr(i) for i in range(ord('a'), ord('z')+1)] # can also use string module
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def DP(N, M, first): return [[first] * M for n in range(N)]
def DP3(N, M, L, first): return [[[first] * L for n in range(M)] for _ in range(N)]
from inspect import currentframe
# }}}
def local_input():# {{{
from pcm.utils import set_stdin
import sys
from pathlib import Path
parentdir = Path(os.path.dirname(__file__)).parent
inputfile = parentdir.joinpath('test/sample-1.in')
if len(sys.argv) == 1:
set_stdin(inputfile)
# }}}
def solve():
N = int(input())
X = []
for i in range(N):
S,P = map(str, input().split())
P = int(P)
X.append((S,P,i))
X.sort(key=lambda x: x[1], reverse=True)
X.sort(key=lambda x: x[0])
for x in X:
print(x[2]+1)
return 0
if __name__ == "__main__":# {{{
try:
local_input()
def dump(*args):
names = {id(v):k for k,v in currentframe().f_back.f_locals.items()}
print(', '.join(names.get(id(arg),'???')+' => '+repr(arg) for arg in args), file=sys.stderr)
except:
def dump(*args):
pass
solve()
# vim: set foldmethod=marker:}}}
|
C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.Intrinsics.X86;
using System.Text;
using static Solve.Methods;
using static Solve.Input;
using static Solve.Output;
using static System.Math;
namespace Solve
{
public partial class Solver
{
public void Main() {
var (A, B, C, K) = Long;
var ans = 0L;
var remain = K;
if (remain > 0) ans += Min(K, A);
remain -= Min(K, A);
if (remain > 0) remain -= Min(remain, B);
if (remain > 0) ans -= Min(remain, C);
print(ans);
}
const int MOD = 1_000_000_007;
}
public static class Methods
{
[MethodImpl(256)] public static bool Assert(in bool b, in string message = null) =>
b ? true : throw new Exception(message ?? "Assert failed.");
[MethodImpl(256)] public static string JoinSpace<T>(this IEnumerable<T> source) => source.Join(" ");
[MethodImpl(256)] public static string JoinEndline<T>(this IEnumerable<T> source) => source.Join("\n");
[MethodImpl(256)] public static string Join<T>(this IEnumerable<T> source, string s) => string.Join(s, source);
[MethodImpl(256)] public static string Join<T>(this IEnumerable<T> source, char c) =>
string.Join(c.ToString(), source);
public static int Gcd(int a, int b) => (int) Gcd((long) a, b);
public static long Gcd(long a, long b) {
while (true) {
if (a < b) (a, b) = (b, a);
if (a % b == 0) return b;
var x = a;
a = b;
b = x % b;
}
}
public static long Lcm(long a, long b) => a / Gcd(a, b) * b;
public static bool IsPrime(long value) {
if (value <= 1) return false;
for (long i = 2; i * i <= value; ++i) if (value % i == 0) return false;
return true;
}
public static long Pow(long a, int b) {
long res = 1;
while (b > 0) { if (b % 2 != 0) res *= a; a *= a; b >>= 1; }
return res;
}
public static int PowMod(long a, long b, int p) => (int) PowMod(a, b, (long) p);
public static long PowMod(long a, long b, long p) {
long res = 1;
while (b > 0) { if (b % 2 != 0) res = res * a % p; a = a * a % p; b >>= 1; }
return res;
}
public static IEnumerable<long> Factors(long n) {
Assert(n >= 0, "n must be greater than 0.");
for (long i = 1; i * i <= n; ++i) {
var div = DivRem(n, i, out var rem);
if (rem > 0) continue;
yield return div;
if (i != div) yield return i;
}
}
public static IEnumerable<int> Factors(int n) => Factors((long) n).Select(Convert.ToInt32);
[MethodImpl(256)] public static int DivCeil(int a, int b) => (a + b - 1) / b;
[MethodImpl(256)] public static long DivCeil(long a, long b) => (a + b - 1) / b;
public static IEnumerable<T[]> Permutations<T>(IEnumerable<T> src) {
var ret = new List<T[]>();
Search(ret, new Stack<T>(), src.ToArray());
return ret;
static void Search(ICollection<T[]> perms, Stack<T> stack, T[] a) {
int N = a.Length;
if (N == 0) perms.Add(stack.Reverse().ToArray());
else {
var b = new T[N - 1];
Array.Copy(a, 1, b, 0, N - 1);
for (int i = 0; i < a.Length; ++i) {
stack.Push(a[i]);
Search(perms, stack, b);
if (i < b.Length) b[i] = a[i];
stack.Pop();
}
}
}
}
public static long BinarySearch(long low, long high, Func<long, bool> expression) {
while (low < high) {
long middle = (high - low) / 2 + low;
if (!expression(middle))
high = middle;
else
low = middle + 1;
}
return high;
}
public static int LowerBound<T>(T[] arr, int start, int end, T value, IComparer<T> comparer) {
int low = start;
int high = end;
while (low < high) {
var mid = ((high - low) >> 1) + low;
if (comparer.Compare(arr[mid], value) < 0)
low = mid + 1;
else
high = mid;
}
return low;
}
public static int LowerBound<T>(T[] arr, T value) where T : IComparable =>
LowerBound(arr, 0, arr.Length, value, Comparer<T>.Default);
public static int UpperBound<T>(T[] arr, int start, int end, T value, IComparer<T> comparer) {
var (low, high) = (start, end);
while (low < high) {
var mid = ((high - low) >> 1) + low;
if (comparer.Compare(arr[mid], value) <= 0) low = mid + 1;
else high = mid;
}
return low;
}
public static int UpperBound<T>(T[] arr, T value) =>
UpperBound(arr, 0, arr.Length, value, Comparer<T>.Default);
[MethodImpl(256)]
public static IEnumerable<TResult> Repeat<TResult>(TResult value, int count) => Enumerable.Repeat(value, count);
[MethodImpl(256)] public static string AsString(this IEnumerable<char> source) => new string(source.ToArray());
public static IEnumerable<long> CumSum(this IEnumerable<long> source) {
long sum = 0; foreach (var item in source) yield return sum += item;
}
public static IEnumerable<int> CumSum(this IEnumerable<int> source) {
int sum = 0; foreach (var item in source) yield return sum += item;
}
[MethodImpl(256)] public static bool IsIn<T>(this T value, T l, T r) where T : IComparable<T> =>
l.CompareTo(r) > 0 ? throw new ArgumentException() : l.CompareTo(value) <= 0 && value.CompareTo(r) < 0;
[MethodImpl(256)] public static bool IsIn(this in int value, in Range range) =>
value.IsIn(range.Start.Value, range.End.Value);
[MethodImpl(256)] public static bool IsIn(this in Index value, in Range range) =>
value.IsFromEnd && value.Value.IsIn(range.Start.Value, range.End.Value);
public static IEnumerable<int> Range(int start, int end, int step = 1) {
for (var i = start; i < end; i += step) yield return i;
}
public static IEnumerable<int> Range(int end) => Range(0, end);
public static IEnumerable<int> Range(Range range, int step = 1) =>
Range(range.Start.Value, range.End.Value, step);
[MethodImpl(256)] public static T[] Sort<T>(this T[] arr) where T : IComparable<T> {
var array = arr[..]; Array.Sort(array); return array;
}
[MethodImpl(256)]
public static T[] Sort<T, U>(this T[] arr, Func<T, U> selector) where U : IComparable<U> {
var array = arr[..];
Array.Sort(array, (a, b) => selector(a).CompareTo(selector(b)));
return array;
}
[MethodImpl(256)] public static T[] SortDescending<T>(this T[] arr) where T : IComparable<T> {
var array = arr[..];
Array.Sort(array, (a, b) => b.CompareTo(a));
return array;
}
[MethodImpl(256)]
public static T[] SortDescending<T, U>(this T[] arr, Func<T, U> selector) where U : IComparable<U> {
var array = arr[..];
Array.Sort(array, (a, b) => selector(b).CompareTo(selector(a)));
return array;
}
public static T[] Unique<T>(this IEnumerable<T> arr) {
var source = arr.ToArray();
var ret = new List<T>(source.Length);
var set = new SortedSet<T>();
ret.AddRange(source.Where(val => set.Add(val)));
return ret.ToArray();
}
[MethodImpl(256)] 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(256)] 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;
}
public static T[] InitArray<T>(int n, Func<int, T> init) {
var res = new T[n];
for (int i = 0; i < n; i++) res[i] = init(i);
return res;
}
public static T[][] JaggedArray2D<T>(int a, int b, T defaultValue = default) {
var ret = new T[a][];
for (int i = 0; i < a; ++i) ret[i] = Enumerable.Repeat(defaultValue, b).ToArray();
return ret;
}
public static T[,] Array2D<T>(int a, int b, T defaultValue = default) {
var ret = new T[a, b];
for (int i = 0; i < a; ++i) for (int j = 0; j < b; ++j) ret[i, j] = defaultValue;
return ret;
}
public static T[,] To2DArray<T>(this T[][] array) {
if (!array.Any()) return new T[0, 0];
int len = array[0].Length;
if (array.Any(x => x.Length != len))
throw new ArgumentException("array の各要素の長さが異なります。", nameof(array));
var ret = new T[array.Length, len];
for (int i = 0; i < array.Length; ++i) for (int j = 0; j < len; ++j) ret[i, j] = array[i][j];
return ret;
}
[MethodImpl(256)] public static T Min<T>(params T[] col) => col.Min();
[MethodImpl(256)] public static T Max<T>(params T[] col) => col.Max();
[MethodImpl(256)] public static IEnumerable<(T, int)> WithIndex<T>(this IEnumerable<T> source) =>
source.Select((x, i) => (x, i));
[MethodImpl(256)] public static (T, U, V)[] Zip<T, U, V>(
IReadOnlyCollection<T> t,
IReadOnlyCollection<U> u,
IReadOnlyCollection<V> v
) {
Assert(t.Count == u.Count && u.Count == v.Count);
return t.Zip(u, (a, b) => (a, b))
.Zip(v, (tuple, c) => (tuple.Item1, tuple.Item2, c)).ToArray();
}
[MethodImpl(256)] public static void rep(in int start, in int end, Action<int> func) {
for (int i = start; i < end; ++i) func(i);
}
[MethodImpl(256)] public static void rep(in int end, Action<int> func) => rep(0, end, func);
[MethodImpl(256)] public static void rep1(in int end, Action<int> func) => rep(1, end + 1, func);
[MethodImpl(256)] public static void repr(in int end, Action<int> func) {
for (int i = end - 1; i >= 0; --i) func(i);
}
[MethodImpl(256)]
public static void each<T>(this IEnumerable<T> source, Action<T> func) {
foreach (var item in source) func(item);
}
[MethodImpl(256)]
public static void eachWithIndex<T>(this IEnumerable<T> source, Action<T, int> func) {
int index = 0; foreach (var item in source) func(item, index++);
}
[MethodImpl(256)] public static int bit(in int x) => 1 << x;
[MethodImpl(256)] public static long bitl(in int x) => 1L << x;
}
public static class Caluclation
{
public static int Addition(int a, int b) => a + b;
public static long Addition(long a, long b) => a + b;
public static double Addition(double a, double b) => a + b;
public static int Xor(int a, int b) => a ^ b;
public static long Xor(long a, long b) => a ^ b;
public static int Multiplication(int a, int b) => a * b;
public static long Multiplication(long a, long b) => a * b;
}
public class UnorderedMap<T, U> : Dictionary<T, U>
{
public new U this[T k] {
get =>
TryGetValue(k, out var v) ? v : base[k] = default;
set =>
base[k] = value;
}
}
public class Map<T, U> : SortedDictionary<T, U>
{
public new U this[T k] {
get =>
TryGetValue(k, out var v) ? v : base[k] = default;
set =>
base[k] = value;
}
}
public class Scanner<T>
{
public T r => next<T>();
public T next() => r;
IEnumerable<T> enumerable(int N) { for (int i = 0; i < N; ++i) yield return r; }
public T[] array(in int N) => enumerable(N).ToArray();
public List<T> list(in int N) => enumerable(N).ToList();
public T[,] array2d(in int N, in int M) => next2DArray<T>(N, M);
public T[][] listArray(in int n) {
var ret = new T[n][];
for (int i = 0; i < n; i++) ret[i] = array(next<int>());
return ret;
}
public void Deconstruct(out T _1, out T _2) => (_1, _2) = (r, r);
public void Deconstruct(out T _1, out T _2, out T _3) => (_1, _2, _3) = (r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4) =>
(_1, _2, _3, _4) = (r, r, r, r);
public void Dconstruct(out T _1, out T _2, out T _3, out T _4, out T _5) =>
(_1, _2, _3, _4, _5) = (r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6) =>
(_1, _2, _3, _4, _5, _6) = (r, r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6, out T _7) =>
(_1, _2, _3, _4, _5, _6, _7) = (r, r, r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6, out T _7, out T _8) =>
(_1, _2, _3, _4, _5, _6, _7, _8) = (r, r, r, r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6, out T _7, out T _8, out T _9) =>
(_1, _2, _3, _4, _5, _6, _7, _8, _9) = (r, r, r, r, r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6, out T _7, out T _8, out T _9, out T _10) =>
(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) =
(r, r, r, r, r, r, r, r, r, r);
public static implicit operator T(Scanner<T> sc) => sc.r;
}
public static class Input
{
const char _separator = ' ';
static readonly Queue<string> _input = new Queue<string>();
static readonly StreamReader sr =
#if FILE
new StreamReader("in.txt");
#else
new StreamReader(Console.OpenStandardInput());
#endif
public static string ReadLine => sr.ReadLine();
static string ReadStr => Read;
static int ReadInt => int.Parse(Read);
static long ReadLong => long.Parse(Read);
static ulong ReadULong => ulong.Parse(Read);
static double ReadDouble => double.Parse(Read);
static BigInteger ReadBigInteger => BigInteger.Parse(Read);
public static string Read {
get {
if (_input.Any()) return _input.Dequeue();
foreach (var val in sr.ReadLine().Split(_separator)) _input.Enqueue(val);
return _input.Dequeue();
}
}
public static string next() => Read;
public static T next<T>() =>
default(T) switch {
sbyte _ => (T) (object) (sbyte) ReadInt,
short _ => (T) (object) (short) ReadInt,
int _ => (T) (object) ReadInt,
long _ => (T) (object) ReadLong,
byte _ => (T) (object) (byte) ReadULong,
ushort _ => (T) (object) (ushort) ReadULong,
uint _ => (T) (object) (uint) ReadULong,
ulong _ => (T) (object) ReadULong,
float _ => (T) (object) (float) ReadDouble,
double _ => (T) (object) ReadDouble,
string _ => (T) (object) ReadStr,
char _ => (T) (object) ReadStr[0],
BigInteger _ => (T) (object) ReadBigInteger,
_ => typeof(T) == typeof(string)
? (T) (object) ReadStr
: throw new NotSupportedException(),
};
public static (T, U) next<T, U>() => (next<T>(), next<U>());
public static (T, U, V) next<T, U, V>() => (next<T>(), next<U>(), next<V>());
public static (T, U, V, W) next<T, U, V, W>() => (next<T>(), next<U>(), next<V>(), next<W>());
public static (T, U, V, W, X) next<T, U, V, W, X>() => (next<T>(), next<U>(), next<V>(), next<W>(), next<X>());
public static T[] nextArray<T>(in int size) {
var ret = new T[size]; for (int i = 0; i < size; ++i) ret[i] = next<T>(); return ret;
}
public static T[,] next2DArray<T>(int n, in int m) {
var ret = new T[n, m];
for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) ret[i, j] = next<T>(); return ret;
}
public static (T[], U[]) nextArray<T, U>(in int size) {
var ret1 = new T[size]; var ret2 = new U[size];
for (int i = 0; i < size; ++i) (ret1[i], ret2[i]) = next<T, U>();
return (ret1, ret2);
}
public static (T[], U[], V[]) nextArray<T, U, V>(in int size) {
var ret1 = new T[size]; var ret2 = new U[size]; var ret3 = new V[size];
for (int i = 0; i < size; ++i) (ret1[i], ret2[i], ret3[i]) = next<T, U, V>();
return (ret1, ret2, ret3);
}
}
public static class Output
{
[MethodImpl(256)] public static void print() => Console.WriteLine();
[MethodImpl(256)] public static void print(in string s, bool endline = true) {
if (endline) Console.WriteLine(s); else Console.Write(s);
}
[MethodImpl(256)] public static void print(in char s, bool endline = true) {
if (endline) Console.WriteLine(s); else Console.Write(s);
}
[MethodImpl(256)] public static void print(in int v, bool endline = true) {
if (endline) Console.WriteLine(v); else Console.Write(v);
}
[MethodImpl(256)] public static void print(in long v, bool endline = true) {
if (endline) Console.WriteLine(v); else Console.Write(v);
}
[MethodImpl(256)] public static void print(in ulong v, bool endline = true) {
if (endline) Console.WriteLine(v); else Console.Write(v);
}
[MethodImpl(256)] public static void print(in bool b) => PrintBool(b);
[MethodImpl(256)] public static void print(in object v) => Console.WriteLine(v);
[MethodImpl(256)] public static void print<T>(in IEnumerable<T> array, string separator = " ") =>
Console.WriteLine(array.Join(separator));
[MethodImpl(256)] public static void prints<T>(params T[] t) => print(t);
#if LOCAL
[MethodImpl(256)] public static void debug<T>(in T value, bool endline = true) {
if (endline) Console.WriteLine(value);else Console.Write(value);
}
#else
public static void debug(params object[] obj) { }
#endif
[MethodImpl(256)] static void PrintBool(in bool val, in string yes = null, in string no = null) =>
print(val ? yes ?? _yes : no ?? _no);
static string _yes = "Yes", _no = "No";
public static void SetYesNoString(in YesNoType t) => (_yes, _no) = YesNoString[t];
public static void SetYesNoString(in string yes, in string no) => (_yes, _no) = (yes, no);
static readonly Dictionary<YesNoType, (string yes, string no)>
YesNoString = new Dictionary<YesNoType, (string, string)> {
{YesNoType.Yes_No, ("Yes", "No")},
{YesNoType.YES_NO, ("YES", "NO")},
{YesNoType.Upper, ("YES", "NO")},
{YesNoType.yes_no, ("yes", "no")},
{YesNoType.Lower, ("yes", "no")},
{YesNoType.Possible_Impossible, ("Possible", "Impossible")},
{YesNoType.Yay, ("Yay!", ":(")},
};
public static readonly (string yes, string no) YN_Possible = ("Possible", "Impossible"),
YN_lower = ("yes", "no"), YN_upper = ("YES", "NO"), YN_Yay = ("Yay!", ":(");
public static void Yes() => print(_yes);
public static void No() => print(_no);
public static object cout { set => Console.WriteLine(value); }
#if LOCAL
public static object dout { set => Console.WriteLine(value); }
#else
public static object dout { set { } }
#endif
public static object cerr { set => Console.Error.WriteLine(value); }
public const string endl = "\n";
public enum YesNoType { Yes_No, YES_NO, Upper, yes_no, Lower, Possible_Impossible, Yay }
}
public class Program
{
public static void Main(string[] args) {
var sw = new StreamWriter(Console.OpenStandardOutput()) {AutoFlush = false};
Console.SetOut(sw);
new Solver().Main();
Console.Out.Flush();
}
}
partial class Solver
{
readonly Scanner<int> Int;
readonly Scanner<long> Long;
readonly Scanner<string> String;
public Solver() => (Int, String, Long) = (new Scanner<int>(), new Scanner<string>(), new Scanner<long>());
const int INF = 1000000010;
const long LINF = 1000000000000000100;
const double EPS = 1e-9;
public static readonly int[] dx = {-1, 0, 0, 1}, dy = {0, 1, -1, 0};
}
} | Go | /*
URL:
https://atcoder.jp/contests/abc167/tasks/abc167_b
*/
package main
import (
"bufio"
"errors"
"fmt"
"io"
"math"
"os"
"strconv"
)
/********** FAU standard libraries **********/
//fmt.Sprintf("%b\n", 255) // binary expression
/********** I/O usage **********/
//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)
//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)
/*******************************************************************/
const (
// General purpose
MOD = 1000000000 + 7
ALPHABET_NUM = 26
INF_INT64 = math.MaxInt64
INF_BIT60 = 1 << 60
INF_INT32 = math.MaxInt32
INF_BIT30 = 1 << 30
NIL = -1
// for dijkstra, prim, and so on
WHITE = 0
GRAY = 1
BLACK = 2
)
func init() {
// bufio.ScanWords <---> bufio.ScanLines
ReadString = newReadString(os.Stdin, bufio.ScanWords)
stdout = bufio.NewWriter(os.Stdout)
}
var (
a, b, c, k int
)
func main() {
a, b, c, k = ReadInt4()
if a >= k {
fmt.Println(k)
return
}
if a+b >= k {
fmt.Println(a)
return
}
tmp := k - a - b
fmt.Println(a - tmp)
}
/*******************************************************************/
/*********** I/O ***********/
var (
// ReadString returns a WORD string.
ReadString func() string
stdout *bufio.Writer
)
func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
r := bufio.NewScanner(ior)
r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
r.Split(sf)
return func() string {
if !r.Scan() {
panic("Scan failed")
}
return r.Text()
}
}
// ReadInt returns an integer.
func ReadInt() int {
return int(readInt64())
}
func ReadInt2() (int, int) {
return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}
// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
return readInt64()
}
func ReadInt64_2() (int64, int64) {
return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
return readInt64(), readInt64(), readInt64(), readInt64()
}
func readInt64() int64 {
i, err := strconv.ParseInt(ReadString(), 0, 64)
if err != nil {
panic(err.Error())
}
return i
}
// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
b := make([]int, n)
for i := 0; i < n; i++ {
b[i] = ReadInt()
}
return b
}
// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
b := make([]int64, n)
for i := 0; i < n; i++ {
b[i] = ReadInt64()
}
return b
}
// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
return float64(readFloat64())
}
func readFloat64() float64 {
f, err := strconv.ParseFloat(ReadString(), 64)
if err != nil {
panic(err.Error())
}
return f
}
// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
b := make([]float64, n)
for i := 0; i < n; i++ {
b[i] = ReadFloat64()
}
return b
}
// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
return []rune(ReadString())
}
/*********** Debugging ***********/
// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
sn := fmt.Sprintf("%b", n)
residualLength := digitsNum - len(sn)
if residualLength <= 0 {
return []rune(sn)
}
zeros := make([]rune, residualLength)
for i := 0; i < len(zeros); i++ {
zeros[i] = '0'
}
res := []rune{}
res = append(res, zeros...)
res = append(res, []rune(sn)...)
return res
}
// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
if i, err := strconv.Atoi(s); err != nil {
panic(errors.New("[argument error]: Strtoi only accepts integer string"))
} else {
return i
}
}
// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
res := []rune{}
for i := 0; i < len(A); i++ {
str := strconv.Itoa(A[i])
res = append(res, []rune(str)...)
if i != len(A)-1 {
res = append(res, ' ')
}
}
return string(res)
}
// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
res := []rune{}
for i := 0; i < len(A); i++ {
str := strconv.FormatInt(A[i], 10) // 64bit int version
res = append(res, []rune(str)...)
if i != len(A)-1 {
res = append(res, ' ')
}
}
return string(res)
}
// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
}
// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
fmt.Fprintf(stdout, format, a...)
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.Intrinsics.X86;
using System.Text;
using static Solve.Methods;
using static Solve.Input;
using static Solve.Output;
using static System.Math;
namespace Solve
{
public partial class Solver
{
public void Main() {
var (A, B, C, K) = Long;
var ans = 0L;
var remain = K;
if (remain > 0) ans += Min(K, A);
remain -= Min(K, A);
if (remain > 0) remain -= Min(remain, B);
if (remain > 0) ans -= Min(remain, C);
print(ans);
}
const int MOD = 1_000_000_007;
}
public static class Methods
{
[MethodImpl(256)] public static bool Assert(in bool b, in string message = null) =>
b ? true : throw new Exception(message ?? "Assert failed.");
[MethodImpl(256)] public static string JoinSpace<T>(this IEnumerable<T> source) => source.Join(" ");
[MethodImpl(256)] public static string JoinEndline<T>(this IEnumerable<T> source) => source.Join("\n");
[MethodImpl(256)] public static string Join<T>(this IEnumerable<T> source, string s) => string.Join(s, source);
[MethodImpl(256)] public static string Join<T>(this IEnumerable<T> source, char c) =>
string.Join(c.ToString(), source);
public static int Gcd(int a, int b) => (int) Gcd((long) a, b);
public static long Gcd(long a, long b) {
while (true) {
if (a < b) (a, b) = (b, a);
if (a % b == 0) return b;
var x = a;
a = b;
b = x % b;
}
}
public static long Lcm(long a, long b) => a / Gcd(a, b) * b;
public static bool IsPrime(long value) {
if (value <= 1) return false;
for (long i = 2; i * i <= value; ++i) if (value % i == 0) return false;
return true;
}
public static long Pow(long a, int b) {
long res = 1;
while (b > 0) { if (b % 2 != 0) res *= a; a *= a; b >>= 1; }
return res;
}
public static int PowMod(long a, long b, int p) => (int) PowMod(a, b, (long) p);
public static long PowMod(long a, long b, long p) {
long res = 1;
while (b > 0) { if (b % 2 != 0) res = res * a % p; a = a * a % p; b >>= 1; }
return res;
}
public static IEnumerable<long> Factors(long n) {
Assert(n >= 0, "n must be greater than 0.");
for (long i = 1; i * i <= n; ++i) {
var div = DivRem(n, i, out var rem);
if (rem > 0) continue;
yield return div;
if (i != div) yield return i;
}
}
public static IEnumerable<int> Factors(int n) => Factors((long) n).Select(Convert.ToInt32);
[MethodImpl(256)] public static int DivCeil(int a, int b) => (a + b - 1) / b;
[MethodImpl(256)] public static long DivCeil(long a, long b) => (a + b - 1) / b;
public static IEnumerable<T[]> Permutations<T>(IEnumerable<T> src) {
var ret = new List<T[]>();
Search(ret, new Stack<T>(), src.ToArray());
return ret;
static void Search(ICollection<T[]> perms, Stack<T> stack, T[] a) {
int N = a.Length;
if (N == 0) perms.Add(stack.Reverse().ToArray());
else {
var b = new T[N - 1];
Array.Copy(a, 1, b, 0, N - 1);
for (int i = 0; i < a.Length; ++i) {
stack.Push(a[i]);
Search(perms, stack, b);
if (i < b.Length) b[i] = a[i];
stack.Pop();
}
}
}
}
public static long BinarySearch(long low, long high, Func<long, bool> expression) {
while (low < high) {
long middle = (high - low) / 2 + low;
if (!expression(middle))
high = middle;
else
low = middle + 1;
}
return high;
}
public static int LowerBound<T>(T[] arr, int start, int end, T value, IComparer<T> comparer) {
int low = start;
int high = end;
while (low < high) {
var mid = ((high - low) >> 1) + low;
if (comparer.Compare(arr[mid], value) < 0)
low = mid + 1;
else
high = mid;
}
return low;
}
public static int LowerBound<T>(T[] arr, T value) where T : IComparable =>
LowerBound(arr, 0, arr.Length, value, Comparer<T>.Default);
public static int UpperBound<T>(T[] arr, int start, int end, T value, IComparer<T> comparer) {
var (low, high) = (start, end);
while (low < high) {
var mid = ((high - low) >> 1) + low;
if (comparer.Compare(arr[mid], value) <= 0) low = mid + 1;
else high = mid;
}
return low;
}
public static int UpperBound<T>(T[] arr, T value) =>
UpperBound(arr, 0, arr.Length, value, Comparer<T>.Default);
[MethodImpl(256)]
public static IEnumerable<TResult> Repeat<TResult>(TResult value, int count) => Enumerable.Repeat(value, count);
[MethodImpl(256)] public static string AsString(this IEnumerable<char> source) => new string(source.ToArray());
public static IEnumerable<long> CumSum(this IEnumerable<long> source) {
long sum = 0; foreach (var item in source) yield return sum += item;
}
public static IEnumerable<int> CumSum(this IEnumerable<int> source) {
int sum = 0; foreach (var item in source) yield return sum += item;
}
[MethodImpl(256)] public static bool IsIn<T>(this T value, T l, T r) where T : IComparable<T> =>
l.CompareTo(r) > 0 ? throw new ArgumentException() : l.CompareTo(value) <= 0 && value.CompareTo(r) < 0;
[MethodImpl(256)] public static bool IsIn(this in int value, in Range range) =>
value.IsIn(range.Start.Value, range.End.Value);
[MethodImpl(256)] public static bool IsIn(this in Index value, in Range range) =>
value.IsFromEnd && value.Value.IsIn(range.Start.Value, range.End.Value);
public static IEnumerable<int> Range(int start, int end, int step = 1) {
for (var i = start; i < end; i += step) yield return i;
}
public static IEnumerable<int> Range(int end) => Range(0, end);
public static IEnumerable<int> Range(Range range, int step = 1) =>
Range(range.Start.Value, range.End.Value, step);
[MethodImpl(256)] public static T[] Sort<T>(this T[] arr) where T : IComparable<T> {
var array = arr[..]; Array.Sort(array); return array;
}
[MethodImpl(256)]
public static T[] Sort<T, U>(this T[] arr, Func<T, U> selector) where U : IComparable<U> {
var array = arr[..];
Array.Sort(array, (a, b) => selector(a).CompareTo(selector(b)));
return array;
}
[MethodImpl(256)] public static T[] SortDescending<T>(this T[] arr) where T : IComparable<T> {
var array = arr[..];
Array.Sort(array, (a, b) => b.CompareTo(a));
return array;
}
[MethodImpl(256)]
public static T[] SortDescending<T, U>(this T[] arr, Func<T, U> selector) where U : IComparable<U> {
var array = arr[..];
Array.Sort(array, (a, b) => selector(b).CompareTo(selector(a)));
return array;
}
public static T[] Unique<T>(this IEnumerable<T> arr) {
var source = arr.ToArray();
var ret = new List<T>(source.Length);
var set = new SortedSet<T>();
ret.AddRange(source.Where(val => set.Add(val)));
return ret.ToArray();
}
[MethodImpl(256)] 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(256)] 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;
}
public static T[] InitArray<T>(int n, Func<int, T> init) {
var res = new T[n];
for (int i = 0; i < n; i++) res[i] = init(i);
return res;
}
public static T[][] JaggedArray2D<T>(int a, int b, T defaultValue = default) {
var ret = new T[a][];
for (int i = 0; i < a; ++i) ret[i] = Enumerable.Repeat(defaultValue, b).ToArray();
return ret;
}
public static T[,] Array2D<T>(int a, int b, T defaultValue = default) {
var ret = new T[a, b];
for (int i = 0; i < a; ++i) for (int j = 0; j < b; ++j) ret[i, j] = defaultValue;
return ret;
}
public static T[,] To2DArray<T>(this T[][] array) {
if (!array.Any()) return new T[0, 0];
int len = array[0].Length;
if (array.Any(x => x.Length != len))
throw new ArgumentException("array の各要素の長さが異なります。", nameof(array));
var ret = new T[array.Length, len];
for (int i = 0; i < array.Length; ++i) for (int j = 0; j < len; ++j) ret[i, j] = array[i][j];
return ret;
}
[MethodImpl(256)] public static T Min<T>(params T[] col) => col.Min();
[MethodImpl(256)] public static T Max<T>(params T[] col) => col.Max();
[MethodImpl(256)] public static IEnumerable<(T, int)> WithIndex<T>(this IEnumerable<T> source) =>
source.Select((x, i) => (x, i));
[MethodImpl(256)] public static (T, U, V)[] Zip<T, U, V>(
IReadOnlyCollection<T> t,
IReadOnlyCollection<U> u,
IReadOnlyCollection<V> v
) {
Assert(t.Count == u.Count && u.Count == v.Count);
return t.Zip(u, (a, b) => (a, b))
.Zip(v, (tuple, c) => (tuple.Item1, tuple.Item2, c)).ToArray();
}
[MethodImpl(256)] public static void rep(in int start, in int end, Action<int> func) {
for (int i = start; i < end; ++i) func(i);
}
[MethodImpl(256)] public static void rep(in int end, Action<int> func) => rep(0, end, func);
[MethodImpl(256)] public static void rep1(in int end, Action<int> func) => rep(1, end + 1, func);
[MethodImpl(256)] public static void repr(in int end, Action<int> func) {
for (int i = end - 1; i >= 0; --i) func(i);
}
[MethodImpl(256)]
public static void each<T>(this IEnumerable<T> source, Action<T> func) {
foreach (var item in source) func(item);
}
[MethodImpl(256)]
public static void eachWithIndex<T>(this IEnumerable<T> source, Action<T, int> func) {
int index = 0; foreach (var item in source) func(item, index++);
}
[MethodImpl(256)] public static int bit(in int x) => 1 << x;
[MethodImpl(256)] public static long bitl(in int x) => 1L << x;
}
public static class Caluclation
{
public static int Addition(int a, int b) => a + b;
public static long Addition(long a, long b) => a + b;
public static double Addition(double a, double b) => a + b;
public static int Xor(int a, int b) => a ^ b;
public static long Xor(long a, long b) => a ^ b;
public static int Multiplication(int a, int b) => a * b;
public static long Multiplication(long a, long b) => a * b;
}
public class UnorderedMap<T, U> : Dictionary<T, U>
{
public new U this[T k] {
get =>
TryGetValue(k, out var v) ? v : base[k] = default;
set =>
base[k] = value;
}
}
public class Map<T, U> : SortedDictionary<T, U>
{
public new U this[T k] {
get =>
TryGetValue(k, out var v) ? v : base[k] = default;
set =>
base[k] = value;
}
}
public class Scanner<T>
{
public T r => next<T>();
public T next() => r;
IEnumerable<T> enumerable(int N) { for (int i = 0; i < N; ++i) yield return r; }
public T[] array(in int N) => enumerable(N).ToArray();
public List<T> list(in int N) => enumerable(N).ToList();
public T[,] array2d(in int N, in int M) => next2DArray<T>(N, M);
public T[][] listArray(in int n) {
var ret = new T[n][];
for (int i = 0; i < n; i++) ret[i] = array(next<int>());
return ret;
}
public void Deconstruct(out T _1, out T _2) => (_1, _2) = (r, r);
public void Deconstruct(out T _1, out T _2, out T _3) => (_1, _2, _3) = (r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4) =>
(_1, _2, _3, _4) = (r, r, r, r);
public void Dconstruct(out T _1, out T _2, out T _3, out T _4, out T _5) =>
(_1, _2, _3, _4, _5) = (r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6) =>
(_1, _2, _3, _4, _5, _6) = (r, r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6, out T _7) =>
(_1, _2, _3, _4, _5, _6, _7) = (r, r, r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6, out T _7, out T _8) =>
(_1, _2, _3, _4, _5, _6, _7, _8) = (r, r, r, r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6, out T _7, out T _8, out T _9) =>
(_1, _2, _3, _4, _5, _6, _7, _8, _9) = (r, r, r, r, r, r, r, r, r);
public void Deconstruct(out T _1, out T _2, out T _3, out T _4, out T _5, out T _6, out T _7, out T _8, out T _9, out T _10) =>
(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) =
(r, r, r, r, r, r, r, r, r, r);
public static implicit operator T(Scanner<T> sc) => sc.r;
}
public static class Input
{
const char _separator = ' ';
static readonly Queue<string> _input = new Queue<string>();
static readonly StreamReader sr =
#if FILE
new StreamReader("in.txt");
#else
new StreamReader(Console.OpenStandardInput());
#endif
public static string ReadLine => sr.ReadLine();
static string ReadStr => Read;
static int ReadInt => int.Parse(Read);
static long ReadLong => long.Parse(Read);
static ulong ReadULong => ulong.Parse(Read);
static double ReadDouble => double.Parse(Read);
static BigInteger ReadBigInteger => BigInteger.Parse(Read);
public static string Read {
get {
if (_input.Any()) return _input.Dequeue();
foreach (var val in sr.ReadLine().Split(_separator)) _input.Enqueue(val);
return _input.Dequeue();
}
}
public static string next() => Read;
public static T next<T>() =>
default(T) switch {
sbyte _ => (T) (object) (sbyte) ReadInt,
short _ => (T) (object) (short) ReadInt,
int _ => (T) (object) ReadInt,
long _ => (T) (object) ReadLong,
byte _ => (T) (object) (byte) ReadULong,
ushort _ => (T) (object) (ushort) ReadULong,
uint _ => (T) (object) (uint) ReadULong,
ulong _ => (T) (object) ReadULong,
float _ => (T) (object) (float) ReadDouble,
double _ => (T) (object) ReadDouble,
string _ => (T) (object) ReadStr,
char _ => (T) (object) ReadStr[0],
BigInteger _ => (T) (object) ReadBigInteger,
_ => typeof(T) == typeof(string)
? (T) (object) ReadStr
: throw new NotSupportedException(),
};
public static (T, U) next<T, U>() => (next<T>(), next<U>());
public static (T, U, V) next<T, U, V>() => (next<T>(), next<U>(), next<V>());
public static (T, U, V, W) next<T, U, V, W>() => (next<T>(), next<U>(), next<V>(), next<W>());
public static (T, U, V, W, X) next<T, U, V, W, X>() => (next<T>(), next<U>(), next<V>(), next<W>(), next<X>());
public static T[] nextArray<T>(in int size) {
var ret = new T[size]; for (int i = 0; i < size; ++i) ret[i] = next<T>(); return ret;
}
public static T[,] next2DArray<T>(int n, in int m) {
var ret = new T[n, m];
for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) ret[i, j] = next<T>(); return ret;
}
public static (T[], U[]) nextArray<T, U>(in int size) {
var ret1 = new T[size]; var ret2 = new U[size];
for (int i = 0; i < size; ++i) (ret1[i], ret2[i]) = next<T, U>();
return (ret1, ret2);
}
public static (T[], U[], V[]) nextArray<T, U, V>(in int size) {
var ret1 = new T[size]; var ret2 = new U[size]; var ret3 = new V[size];
for (int i = 0; i < size; ++i) (ret1[i], ret2[i], ret3[i]) = next<T, U, V>();
return (ret1, ret2, ret3);
}
}
public static class Output
{
[MethodImpl(256)] public static void print() => Console.WriteLine();
[MethodImpl(256)] public static void print(in string s, bool endline = true) {
if (endline) Console.WriteLine(s); else Console.Write(s);
}
[MethodImpl(256)] public static void print(in char s, bool endline = true) {
if (endline) Console.WriteLine(s); else Console.Write(s);
}
[MethodImpl(256)] public static void print(in int v, bool endline = true) {
if (endline) Console.WriteLine(v); else Console.Write(v);
}
[MethodImpl(256)] public static void print(in long v, bool endline = true) {
if (endline) Console.WriteLine(v); else Console.Write(v);
}
[MethodImpl(256)] public static void print(in ulong v, bool endline = true) {
if (endline) Console.WriteLine(v); else Console.Write(v);
}
[MethodImpl(256)] public static void print(in bool b) => PrintBool(b);
[MethodImpl(256)] public static void print(in object v) => Console.WriteLine(v);
[MethodImpl(256)] public static void print<T>(in IEnumerable<T> array, string separator = " ") =>
Console.WriteLine(array.Join(separator));
[MethodImpl(256)] public static void prints<T>(params T[] t) => print(t);
#if LOCAL
[MethodImpl(256)] public static void debug<T>(in T value, bool endline = true) {
if (endline) Console.WriteLine(value);else Console.Write(value);
}
#else
public static void debug(params object[] obj) { }
#endif
[MethodImpl(256)] static void PrintBool(in bool val, in string yes = null, in string no = null) =>
print(val ? yes ?? _yes : no ?? _no);
static string _yes = "Yes", _no = "No";
public static void SetYesNoString(in YesNoType t) => (_yes, _no) = YesNoString[t];
public static void SetYesNoString(in string yes, in string no) => (_yes, _no) = (yes, no);
static readonly Dictionary<YesNoType, (string yes, string no)>
YesNoString = new Dictionary<YesNoType, (string, string)> {
{YesNoType.Yes_No, ("Yes", "No")},
{YesNoType.YES_NO, ("YES", "NO")},
{YesNoType.Upper, ("YES", "NO")},
{YesNoType.yes_no, ("yes", "no")},
{YesNoType.Lower, ("yes", "no")},
{YesNoType.Possible_Impossible, ("Possible", "Impossible")},
{YesNoType.Yay, ("Yay!", ":(")},
};
public static readonly (string yes, string no) YN_Possible = ("Possible", "Impossible"),
YN_lower = ("yes", "no"), YN_upper = ("YES", "NO"), YN_Yay = ("Yay!", ":(");
public static void Yes() => print(_yes);
public static void No() => print(_no);
public static object cout { set => Console.WriteLine(value); }
#if LOCAL
public static object dout { set => Console.WriteLine(value); }
#else
public static object dout { set { } }
#endif
public static object cerr { set => Console.Error.WriteLine(value); }
public const string endl = "\n";
public enum YesNoType { Yes_No, YES_NO, Upper, yes_no, Lower, Possible_Impossible, Yay }
}
public class Program
{
public static void Main(string[] args) {
var sw = new StreamWriter(Console.OpenStandardOutput()) {AutoFlush = false};
Console.SetOut(sw);
new Solver().Main();
Console.Out.Flush();
}
}
partial class Solver
{
readonly Scanner<int> Int;
readonly Scanner<long> Long;
readonly Scanner<string> String;
public Solver() => (Int, String, Long) = (new Scanner<int>(), new Scanner<string>(), new Scanner<long>());
const int INF = 1000000010;
const long LINF = 1000000000000000100;
const double EPS = 1e-9;
public static readonly int[] dx = {-1, 0, 0, 1}, dy = {0, 1, -1, 0};
}
}
Code 2: /*
URL:
https://atcoder.jp/contests/abc167/tasks/abc167_b
*/
package main
import (
"bufio"
"errors"
"fmt"
"io"
"math"
"os"
"strconv"
)
/********** FAU standard libraries **********/
//fmt.Sprintf("%b\n", 255) // binary expression
/********** I/O usage **********/
//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)
//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)
/*******************************************************************/
const (
// General purpose
MOD = 1000000000 + 7
ALPHABET_NUM = 26
INF_INT64 = math.MaxInt64
INF_BIT60 = 1 << 60
INF_INT32 = math.MaxInt32
INF_BIT30 = 1 << 30
NIL = -1
// for dijkstra, prim, and so on
WHITE = 0
GRAY = 1
BLACK = 2
)
func init() {
// bufio.ScanWords <---> bufio.ScanLines
ReadString = newReadString(os.Stdin, bufio.ScanWords)
stdout = bufio.NewWriter(os.Stdout)
}
var (
a, b, c, k int
)
func main() {
a, b, c, k = ReadInt4()
if a >= k {
fmt.Println(k)
return
}
if a+b >= k {
fmt.Println(a)
return
}
tmp := k - a - b
fmt.Println(a - tmp)
}
/*******************************************************************/
/*********** I/O ***********/
var (
// ReadString returns a WORD string.
ReadString func() string
stdout *bufio.Writer
)
func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
r := bufio.NewScanner(ior)
r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
r.Split(sf)
return func() string {
if !r.Scan() {
panic("Scan failed")
}
return r.Text()
}
}
// ReadInt returns an integer.
func ReadInt() int {
return int(readInt64())
}
func ReadInt2() (int, int) {
return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}
// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
return readInt64()
}
func ReadInt64_2() (int64, int64) {
return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
return readInt64(), readInt64(), readInt64(), readInt64()
}
func readInt64() int64 {
i, err := strconv.ParseInt(ReadString(), 0, 64)
if err != nil {
panic(err.Error())
}
return i
}
// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
b := make([]int, n)
for i := 0; i < n; i++ {
b[i] = ReadInt()
}
return b
}
// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
b := make([]int64, n)
for i := 0; i < n; i++ {
b[i] = ReadInt64()
}
return b
}
// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
return float64(readFloat64())
}
func readFloat64() float64 {
f, err := strconv.ParseFloat(ReadString(), 64)
if err != nil {
panic(err.Error())
}
return f
}
// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
b := make([]float64, n)
for i := 0; i < n; i++ {
b[i] = ReadFloat64()
}
return b
}
// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
return []rune(ReadString())
}
/*********** Debugging ***********/
// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
sn := fmt.Sprintf("%b", n)
residualLength := digitsNum - len(sn)
if residualLength <= 0 {
return []rune(sn)
}
zeros := make([]rune, residualLength)
for i := 0; i < len(zeros); i++ {
zeros[i] = '0'
}
res := []rune{}
res = append(res, zeros...)
res = append(res, []rune(sn)...)
return res
}
// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
if i, err := strconv.Atoi(s); err != nil {
panic(errors.New("[argument error]: Strtoi only accepts integer string"))
} else {
return i
}
}
// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
res := []rune{}
for i := 0; i < len(A); i++ {
str := strconv.Itoa(A[i])
res = append(res, []rune(str)...)
if i != len(A)-1 {
res = append(res, ' ')
}
}
return string(res)
}
// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
res := []rune{}
for i := 0; i < len(A); i++ {
str := strconv.FormatInt(A[i], 10) // 64bit int version
res = append(res, []rune(str)...)
if i != len(A)-1 {
res = append(res, ' ')
}
}
return string(res)
}
// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
}
// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
fmt.Fprintf(stdout, format, a...)
}
|
Python | S = input()
tmp = ""
tmp2 = ""
count = 0
for i in S:
tmp2 += i
if tmp2 != tmp:
tmp = tmp2
tmp2 = ""
count += 1
print(count) | Kotlin | fun main(args: Array<String>) {
val s = readLine()!!.toString()
val n = s.length
var sum = 0
var before = ""
var now = ""
var i = 0
while (i in 0 until n) {
now += s[i]
if (now != before) {
sum++
before = now
now = ""
}
i++
}
println(sum)
} | Yes | Do these codes solve the same problem?
Code 1: S = input()
tmp = ""
tmp2 = ""
count = 0
for i in S:
tmp2 += i
if tmp2 != tmp:
tmp = tmp2
tmp2 = ""
count += 1
print(count)
Code 2: fun main(args: Array<String>) {
val s = readLine()!!.toString()
val n = s.length
var sum = 0
var before = ""
var now = ""
var i = 0
while (i in 0 until n) {
now += s[i]
if (now != before) {
sum++
before = now
now = ""
}
i++
}
println(sum)
} |
C++ | #include<bits/stdc++.h>
using namespace std;
int a;
int main(){
cin>>a;
int a500=a/500,a5=(a%500)/5;
cout<<a500*1000+a5*5;
return 0;
} | Python | s = input()
c = 0
ans = []
for i in s:
if c % 2 == 0:
ans.append(i)
c+=1
print(''.join(ans)) | No | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
using namespace std;
int a;
int main(){
cin>>a;
int a500=a/500,a5=(a%500)/5;
cout<<a500*1000+a5*5;
return 0;
}
Code 2: s = input()
c = 0
ans = []
for i in s:
if c % 2 == 0:
ans.append(i)
c+=1
print(''.join(ans)) |
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define sl(x) scanf("%ld", &x)
#define ss(x) scanf("%s", x)
#define pl(x) printf("%ld\n", x)
#define INF 100000000000
#define M 1000000007
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
int main() {
long i, j;
long N;
long p[20001];
long a[20001];
long b[20001];
long step = 40000;
sl(N);
for(i=1;i<=N;i++) {
sl(p[i]);
b[N-i+1] = a[i] = i * step;
}
step = N;
for(i=1;i<=N;i++) {
a[p[i]] -= step;
step--;
}
for(i=1;i<N;i++) {
printf("%ld ", a[i]);
}
printf("%ld\n", a[i]);
for(i=1;i<N;i++) {
printf("%ld ", b[i]);
}
printf("%ld\n", b[i]);
return 0;
} | C++ | #include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> p(n);
int q;
for (int i = 0; i < n; i++) {
cin >> q;
p[q - 1] = i;
}
for (int i = 1; i <= n; i++) {
cout << (20001 * i) << (i != n ? " " : "\n");
}
for (int i = 1; i <= n; i++) {
cout << (20001 * (n - i + 1) + p[i - 1]) << (i != n ? " " : "\n");
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define sl(x) scanf("%ld", &x)
#define ss(x) scanf("%s", x)
#define pl(x) printf("%ld\n", x)
#define INF 100000000000
#define M 1000000007
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
int main() {
long i, j;
long N;
long p[20001];
long a[20001];
long b[20001];
long step = 40000;
sl(N);
for(i=1;i<=N;i++) {
sl(p[i]);
b[N-i+1] = a[i] = i * step;
}
step = N;
for(i=1;i<=N;i++) {
a[p[i]] -= step;
step--;
}
for(i=1;i<N;i++) {
printf("%ld ", a[i]);
}
printf("%ld\n", a[i]);
for(i=1;i<N;i++) {
printf("%ld ", b[i]);
}
printf("%ld\n", b[i]);
return 0;
}
Code 2: #include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> p(n);
int q;
for (int i = 0; i < n; i++) {
cin >> q;
p[q - 1] = i;
}
for (int i = 1; i <= n; i++) {
cout << (20001 * i) << (i != n ? " " : "\n");
}
for (int i = 1; i <= n; i++) {
cout << (20001 * (n - i + 1) + p[i - 1]) << (i != n ? " " : "\n");
}
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
#define all(c) (c).begin(),(c).end()
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--)
#define REP(i,m,n) for(int i=(int)(m);i<(int)(n);i++)
#define rep(i,n) REP(i,0,n)
#define iter(c) __typeof((c).begin())
#define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++)
#define pb(a) push_back(a)
#define pr(a) cout<<(a)<<endl
#define PR(a,b) cout<<(a)<<" "<<(b)<<endl
#define R cin>>
#define F first
#define S second
#define ll long long
bool check(int n,int m,int x,int y){return x>=0&&x<n&&y>=0&&y<m;}
const ll MAX=1000000007,MAXL=1LL<<60,dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
typedef pair<int,int> P;
string s[1001];
vector<int> v[1001];
void dfs(int i, int k) {
rep(j,k) cout << ".";
pr(s[i]);
rep(j,v[i].size()) dfs(v[i][j],k+1);
}
int main() {
int n;
R n;
REP(i,1,n+1) {
int x;
cin >> x >> s[i];
v[x].pb(i);
}
dfs(1,0);
return 0;
}
| Java |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO 自動生成されたメソッド・スタブ
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Submission array[] = new Submission[n];
for(int i = 0; i < n; i++){
int reply = Integer.parseInt(br.readLine());
String message = br.readLine();
Submission sub = new Submission(message);
if(reply != 0){
array[reply - 1].child.add(sub);
}
array[i] = sub;
}
printThread(array, array[0], 0);
}
static void printThread(Submission[] array, Submission sub, int depth){
for(int i = 0; i < depth; i++){
System.out.print('.');
}
System.out.println(sub.message);
for(int i = 0; i < sub.child.size() ; i++){
Submission tmp = sub.child.elementAt(i);
printThread(array, tmp, depth + 1);
}
}
}
class Submission {
Vector<Submission> child = new Vector<Submission>();
String message;
public Submission(String message) {
this.message = message;
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
#define all(c) (c).begin(),(c).end()
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--)
#define REP(i,m,n) for(int i=(int)(m);i<(int)(n);i++)
#define rep(i,n) REP(i,0,n)
#define iter(c) __typeof((c).begin())
#define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++)
#define pb(a) push_back(a)
#define pr(a) cout<<(a)<<endl
#define PR(a,b) cout<<(a)<<" "<<(b)<<endl
#define R cin>>
#define F first
#define S second
#define ll long long
bool check(int n,int m,int x,int y){return x>=0&&x<n&&y>=0&&y<m;}
const ll MAX=1000000007,MAXL=1LL<<60,dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
typedef pair<int,int> P;
string s[1001];
vector<int> v[1001];
void dfs(int i, int k) {
rep(j,k) cout << ".";
pr(s[i]);
rep(j,v[i].size()) dfs(v[i][j],k+1);
}
int main() {
int n;
R n;
REP(i,1,n+1) {
int x;
cin >> x >> s[i];
v[x].pb(i);
}
dfs(1,0);
return 0;
}
Code 2:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO 自動生成されたメソッド・スタブ
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Submission array[] = new Submission[n];
for(int i = 0; i < n; i++){
int reply = Integer.parseInt(br.readLine());
String message = br.readLine();
Submission sub = new Submission(message);
if(reply != 0){
array[reply - 1].child.add(sub);
}
array[i] = sub;
}
printThread(array, array[0], 0);
}
static void printThread(Submission[] array, Submission sub, int depth){
for(int i = 0; i < depth; i++){
System.out.print('.');
}
System.out.println(sub.message);
for(int i = 0; i < sub.child.size() ; i++){
Submission tmp = sub.child.elementAt(i);
printThread(array, tmp, depth + 1);
}
}
}
class Submission {
Vector<Submission> child = new Vector<Submission>();
String message;
public Submission(String message) {
this.message = message;
}
}
|
C | #include<stdio.h>
#include<string.h>
#define MAX(x,y) ((x>y)?x:y)
typedef struct g{
int d,s,e;
}G;
G a[12];
typedef struct p{
int x,y,z,f;
}P;
P q[50000],sq[50000],cp;
int qn,sqn;
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
char map[25][25];
int func(int d,P p){
p.x+=dx[d];p.y+=dy[d];
int m=map[p.y][p.x]-'0';
if(0<=m && m<=9 && !(p.f&(1<<m)))return m;
else return -1;
}
void func2(int f){
int i;
for(i=0;i<10;i++){
if((f>>i)&1)printf("1");
else printf("0");
}
printf("\n");
}
int main(){
int i,j,k,w,h,n,m,mt,t,ans;
char s;
while(1){
scanf("%d %d\n",&w,&h);
if(w+h==0)break;
for(i=0;i<=h+1;i++)map[i][0]=map[i][w+1]='#';
for(i=1;i<=w ;i++)map[0][i]=map[h+1][i]='#';
for(i=1;i<=h;i++){
for(j=1;j<=w;j++){
scanf("%c ",&map[i][j]);
if(map[i][j]=='P'){
q[0]=(P){j,i,0,0};
map[i][j]='.';
}
}
}
//for(i=0;i<=h+1;i++)printf("%s\n",map[i]);
mt=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&m);
scanf("%d%d%d",&a[m].d,&a[m].s,&a[m].e);
mt=MAX(mt,a[m].e);
}
qn=1;
t=1;
for(i=0;i<4;i++){
m=func(i,q[0]);
if(m!=-1 && a[m].s<=0 && 0<a[m].e){
q[0].z+=a[m].d;
q[0].f=q[0].f|(1<<m);
}
}
while(t<=mt+1){
sqn=0;
for(i=0;i<qn;i++){
//printf("%2d %2d %3d ",q[i].x,q[i].y,q[i].z);
//func2(q[i].f);
for(j=0;j<4;j++){
cp=q[i];
cp.x+=dx[j];
cp.y+=dy[j];
if(map[cp.y][cp.x]=='.'){
for(k=0;k<4;k++){
m=func(k,cp);
if(m!=-1 && a[m].s<=t && t<a[m].e){
cp.z+=a[m].d;
cp.f=cp.f|(1<<m);
}
}
for(k=0;k<sqn;k++){
//if(sq[k].x==cp.x && sq[k].y==cp.y && (sq[k].z>cp.z || sq[k].f==cp.f))break;
if(sq[k].x==cp.x && sq[k].y==cp.y){
if(cp.f>sq[k].f && !((~cp.f)&sq[k].f)){
sq[k]=cp;
break;
}
if(cp.f==sq[k].f)break;
if(cp.f<sq[k].f && !(cp.f&(~sq[k].f)))break;
}
}
if(k==sqn)sq[sqn++]=cp;
}
}
}
memcpy(q,sq,sizeof(P)*sqn);
qn=sqn;
t++;
//printf("\n");
}
ans=0;
//printf("%d\n",sqn);
for(i=0;i<qn;i++)ans=MAX(ans,q[i].z);
printf("%d\n",ans);
}
return 0;
} | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0245
{
class Program
{
const int BLANK_NUM = -1;
static readonly int[] di = new int[] { 0, -1, 0, 1 };
static readonly int[] dj = new int[] { -1, 0, 1, 0 };
class State
{
public int I { get; set; }
public int J { get; set; }
public int Time { get; set; }
public int Amount { get; set; }
public int GotItem { get; set; }
public State(int i, int j, int time, int amount, int gotItem)
{
I = i;
J = j;
Time = time;
Amount = amount;
GotItem = gotItem;
}
}
class Item
{
public int Price { get; set; }
public int Start { get; set; }
public int End { get; set; }
public Item(int price, int start, int end)
{
Price = price;
Start = start;
End = end;
}
}
static int[,] map;
static Dictionary<int, Item> Items;
static int sI, sJ;
static void Main(string[] args)
{
while (true)
{
int[] xy = RArInt();
if (xy.Sum() == 0) break;
Init(xy);
Console.WriteLine(CalcMaxAmount());
}
}
private static void Init(int[] xy)
{
map = new int[xy[1], xy[0]];
for (int i = 0; i < map.GetLength(0); i++)
{
string[] ms = RArSt();
for (int j = 0; j < map.GetLength(1); j++)
{
if (ms[j] == "P")
{
map[i, j] = BLANK_NUM;
sI = i; sJ = j;
}
else if (ms[j] == ".") map[i, j] = BLANK_NUM;
else map[i, j] = int.Parse(ms[j]);
}
}
Items = new Dictionary<int, Item>();
int n = RInt();
for (int i = 0; i < n; i++)
{
int[] vs = RArInt();
Items.Add(vs[0], new Item(vs[1], vs[2], vs[3]));
}
}
private static int CalcMaxAmount()
{
int res = 0;
int maxE = Items.Max(x => x.Value.End);
bool[,,,] visited = new bool[map.GetLength(0), map.GetLength(1), (int)Math.Pow(2, Items.Count()), maxE + 1];
Queue<State> q = new Queue<State>();
q.Enqueue(new State(sI, sJ, 0, 0, 0));
while (q.Count > 0)
{
State cur = q.Dequeue();
res = Math.Max(res, cur.Amount);
if (cur.GotItem == (int)Math.Pow(2, Items.Count()) - 1) break;
if (cur.Time >= maxE) continue;
if (visited[cur.I, cur.J, cur.GotItem, cur.Time]) continue;
visited[cur.I, cur.J, cur.GotItem, cur.Time] = true;
int nAmount = cur.Amount;
int nItems = cur.GotItem;
for (int i = 0; i < di.Length; i++)
{
int nI = cur.I + di[i];
int nJ = cur.J + dj[i];
if (IsInArea(nI, nJ) && map[nI, nJ] != BLANK_NUM && ((nItems >> map[nI, nJ]) & 1) == 0)
{
if (Items[map[nI, nJ]].Start <= cur.Time && cur.Time < Items[map[nI, nJ]].End)
{
nAmount += Items[map[nI, nJ]].Price;
nItems |= 1 << map[nI, nJ];
}
}
}
for (int i = 0; i < di.Length; i++)
{
int nI = cur.I + di[i];
int nJ = cur.J + dj[i];
if (IsInArea(nI, nJ) && map[nI, nJ] == BLANK_NUM)
{
q.Enqueue(new State(nI, nJ, cur.Time + 1, nAmount, nItems));
}
}
}
return res;
}
private static bool IsInArea(int i, int j)
{
return 0 <= i && i < map.GetLength(0) && 0 <= j && j < map.GetLength(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: #include<stdio.h>
#include<string.h>
#define MAX(x,y) ((x>y)?x:y)
typedef struct g{
int d,s,e;
}G;
G a[12];
typedef struct p{
int x,y,z,f;
}P;
P q[50000],sq[50000],cp;
int qn,sqn;
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
char map[25][25];
int func(int d,P p){
p.x+=dx[d];p.y+=dy[d];
int m=map[p.y][p.x]-'0';
if(0<=m && m<=9 && !(p.f&(1<<m)))return m;
else return -1;
}
void func2(int f){
int i;
for(i=0;i<10;i++){
if((f>>i)&1)printf("1");
else printf("0");
}
printf("\n");
}
int main(){
int i,j,k,w,h,n,m,mt,t,ans;
char s;
while(1){
scanf("%d %d\n",&w,&h);
if(w+h==0)break;
for(i=0;i<=h+1;i++)map[i][0]=map[i][w+1]='#';
for(i=1;i<=w ;i++)map[0][i]=map[h+1][i]='#';
for(i=1;i<=h;i++){
for(j=1;j<=w;j++){
scanf("%c ",&map[i][j]);
if(map[i][j]=='P'){
q[0]=(P){j,i,0,0};
map[i][j]='.';
}
}
}
//for(i=0;i<=h+1;i++)printf("%s\n",map[i]);
mt=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&m);
scanf("%d%d%d",&a[m].d,&a[m].s,&a[m].e);
mt=MAX(mt,a[m].e);
}
qn=1;
t=1;
for(i=0;i<4;i++){
m=func(i,q[0]);
if(m!=-1 && a[m].s<=0 && 0<a[m].e){
q[0].z+=a[m].d;
q[0].f=q[0].f|(1<<m);
}
}
while(t<=mt+1){
sqn=0;
for(i=0;i<qn;i++){
//printf("%2d %2d %3d ",q[i].x,q[i].y,q[i].z);
//func2(q[i].f);
for(j=0;j<4;j++){
cp=q[i];
cp.x+=dx[j];
cp.y+=dy[j];
if(map[cp.y][cp.x]=='.'){
for(k=0;k<4;k++){
m=func(k,cp);
if(m!=-1 && a[m].s<=t && t<a[m].e){
cp.z+=a[m].d;
cp.f=cp.f|(1<<m);
}
}
for(k=0;k<sqn;k++){
//if(sq[k].x==cp.x && sq[k].y==cp.y && (sq[k].z>cp.z || sq[k].f==cp.f))break;
if(sq[k].x==cp.x && sq[k].y==cp.y){
if(cp.f>sq[k].f && !((~cp.f)&sq[k].f)){
sq[k]=cp;
break;
}
if(cp.f==sq[k].f)break;
if(cp.f<sq[k].f && !(cp.f&(~sq[k].f)))break;
}
}
if(k==sqn)sq[sqn++]=cp;
}
}
}
memcpy(q,sq,sizeof(P)*sqn);
qn=sqn;
t++;
//printf("\n");
}
ans=0;
//printf("%d\n",sqn);
for(i=0;i<qn;i++)ans=MAX(ans,q[i].z);
printf("%d\n",ans);
}
return 0;
}
Code 2: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0245
{
class Program
{
const int BLANK_NUM = -1;
static readonly int[] di = new int[] { 0, -1, 0, 1 };
static readonly int[] dj = new int[] { -1, 0, 1, 0 };
class State
{
public int I { get; set; }
public int J { get; set; }
public int Time { get; set; }
public int Amount { get; set; }
public int GotItem { get; set; }
public State(int i, int j, int time, int amount, int gotItem)
{
I = i;
J = j;
Time = time;
Amount = amount;
GotItem = gotItem;
}
}
class Item
{
public int Price { get; set; }
public int Start { get; set; }
public int End { get; set; }
public Item(int price, int start, int end)
{
Price = price;
Start = start;
End = end;
}
}
static int[,] map;
static Dictionary<int, Item> Items;
static int sI, sJ;
static void Main(string[] args)
{
while (true)
{
int[] xy = RArInt();
if (xy.Sum() == 0) break;
Init(xy);
Console.WriteLine(CalcMaxAmount());
}
}
private static void Init(int[] xy)
{
map = new int[xy[1], xy[0]];
for (int i = 0; i < map.GetLength(0); i++)
{
string[] ms = RArSt();
for (int j = 0; j < map.GetLength(1); j++)
{
if (ms[j] == "P")
{
map[i, j] = BLANK_NUM;
sI = i; sJ = j;
}
else if (ms[j] == ".") map[i, j] = BLANK_NUM;
else map[i, j] = int.Parse(ms[j]);
}
}
Items = new Dictionary<int, Item>();
int n = RInt();
for (int i = 0; i < n; i++)
{
int[] vs = RArInt();
Items.Add(vs[0], new Item(vs[1], vs[2], vs[3]));
}
}
private static int CalcMaxAmount()
{
int res = 0;
int maxE = Items.Max(x => x.Value.End);
bool[,,,] visited = new bool[map.GetLength(0), map.GetLength(1), (int)Math.Pow(2, Items.Count()), maxE + 1];
Queue<State> q = new Queue<State>();
q.Enqueue(new State(sI, sJ, 0, 0, 0));
while (q.Count > 0)
{
State cur = q.Dequeue();
res = Math.Max(res, cur.Amount);
if (cur.GotItem == (int)Math.Pow(2, Items.Count()) - 1) break;
if (cur.Time >= maxE) continue;
if (visited[cur.I, cur.J, cur.GotItem, cur.Time]) continue;
visited[cur.I, cur.J, cur.GotItem, cur.Time] = true;
int nAmount = cur.Amount;
int nItems = cur.GotItem;
for (int i = 0; i < di.Length; i++)
{
int nI = cur.I + di[i];
int nJ = cur.J + dj[i];
if (IsInArea(nI, nJ) && map[nI, nJ] != BLANK_NUM && ((nItems >> map[nI, nJ]) & 1) == 0)
{
if (Items[map[nI, nJ]].Start <= cur.Time && cur.Time < Items[map[nI, nJ]].End)
{
nAmount += Items[map[nI, nJ]].Price;
nItems |= 1 << map[nI, nJ];
}
}
}
for (int i = 0; i < di.Length; i++)
{
int nI = cur.I + di[i];
int nJ = cur.J + dj[i];
if (IsInArea(nI, nJ) && map[nI, nJ] == BLANK_NUM)
{
q.Enqueue(new State(nI, nJ, cur.Time + 1, nAmount, nItems));
}
}
}
return res;
}
private static bool IsInArea(int i, int j)
{
return 0 <= i && i < map.GetLength(0) && 0 <= j && j < map.GetLength(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()); }
}
}
|
JavaScript | //Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
obj = init(inLine);
console.error("\n");
var start = Date.now();
Main();
var end = Date.now() - start;
myerr("time : " + end + "ms");
myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
return {
list : input, index : 0, max : input.length,
hasNext : function(){return (this.index < this.max);},
next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw "ArrayIndexOutOfBoundsException ‚There is no more input";}}
};
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
//Don't have to see. end------------------------------------------
function Main(){
var one = nextIntArray();
var N = one[0];
var K = one[1];
var output = 0;
for(var i = 1; i <= N; i++){
output += Math.max(0, i - K) * Math.floor(N / i) + Math.max(0, N % i - K + 1);
}
if(K == 0){
output -= N;
}
myout(output);
}
| Go | package main
import "fmt"
func main() {
var N, K int
fmt.Scan(&N, &K)
ans := 0
for b := K + 1; b <= N; b++ {
ans += (N/b)*(b-K) + relu((N%b - K + 1))
}
if K == 0 {
ans -= N
}
fmt.Println(ans)
}
func guchoku() {
var N, K int
fmt.Scan(&N, &K)
ans := 0
for i := 1; i <= N; i++ {
for j := 1; j <= N; j++ {
if j%i >= K {
ans++
}
}
}
fmt.Println(ans)
}
func relu(a int) int {
if a > 0 {
return a
}
return 0
}
| Yes | Do these codes solve the same problem?
Code 1: //Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
obj = init(inLine);
console.error("\n");
var start = Date.now();
Main();
var end = Date.now() - start;
myerr("time : " + end + "ms");
myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
return {
list : input, index : 0, max : input.length,
hasNext : function(){return (this.index < this.max);},
next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw "ArrayIndexOutOfBoundsException ‚There is no more input";}}
};
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
//Don't have to see. end------------------------------------------
function Main(){
var one = nextIntArray();
var N = one[0];
var K = one[1];
var output = 0;
for(var i = 1; i <= N; i++){
output += Math.max(0, i - K) * Math.floor(N / i) + Math.max(0, N % i - K + 1);
}
if(K == 0){
output -= N;
}
myout(output);
}
Code 2: package main
import "fmt"
func main() {
var N, K int
fmt.Scan(&N, &K)
ans := 0
for b := K + 1; b <= N; b++ {
ans += (N/b)*(b-K) + relu((N%b - K + 1))
}
if K == 0 {
ans -= N
}
fmt.Println(ans)
}
func guchoku() {
var N, K int
fmt.Scan(&N, &K)
ans := 0
for i := 1; i <= N; i++ {
for j := 1; j <= N; j++ {
if j%i >= K {
ans++
}
}
}
fmt.Println(ans)
}
func relu(a int) int {
if a > 0 {
return a
}
return 0
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.