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 <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
const ll INF64 = 1LL << 60;
const int INF32 = 1 << 29;
const int MOD = 1000000007;
const int dx[]={0,0,1,-1};
const int dy[]={1,-1,0,0};
int h, w, n;
vector<string> s;
vector< vector<int> >steps;
void bfs(vector<P> &starts){
queue<P> q;
for(auto s : starts){
q.push(s);
steps[s.first][s.second] = 0;
}
while(!q.empty()){
int y, x;
tie(y, x) = q.front(); q.pop();
for(int k = 0; k < 4; k++){
int ny = y + dy[k];
int nx = x + dx[k];
if(nx < 0 || w <= nx || ny < 0 || h <= ny) continue;
if(s[ny][nx] == '#') continue;
s[ny][nx] = '#';
steps[ny][nx] = min(steps[ny][nx], steps[y][x] + 1);
q.emplace(ny, nx);
}
}
return;
}
int main() {
#ifdef MYLOCAL
ifstream in("input.txt");
cin.rdbuf(in.rdbuf());
#endif
cin >> h >> w;
s.resize(h);
for(int i = 0;i < h; i++){
cin>>s[i];
}
steps.resize(h);
for(int i = 0;i < h; i++){
steps[i].resize(w);
}
vector<P> starts;
for(int i = 0; i < h; ++i){
for(int j = 0; j < w; ++j){
steps[i][j] = INF32;
if(s[i][j] == '#'){
starts.push_back(make_pair(i, j));
}
}
}
bfs(starts);
int ans = 0;
for(int i = 0; i < h; ++i){
for(int j = 0; j < w; ++j){
ans = max(ans, steps[i][j]);
}
}
cout << ans << endl;
return 0;
}
| Go | package main
import (
"fmt"
"strconv"
)
func main() {
var N string
fmt.Scan(&N)
A, _ := strconv.Atoi(string(N[0]))
B, _ := strconv.Atoi(string(N[1]))
C, _ := strconv.Atoi(string(N[2]))
D, _ := strconv.Atoi(string(N[3]))
op := []string{"+", "-"}
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
for k := 0; k < 2; k++ {
res := 0
if i == 0 {
res = A + B
} else {
res = A - B
}
if j == 0 {
res = res + C
} else {
res = res - C
}
if k == 0 {
res = res + D
} else {
res = res - D
}
if res == 7 {
fmt.Printf("%d%s%d%s%d%s%d%s\n", A, op[i], B, op[j], C, op[k], D, "=7")
goto END
}
}
}
}
END:
}
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
const ll INF64 = 1LL << 60;
const int INF32 = 1 << 29;
const int MOD = 1000000007;
const int dx[]={0,0,1,-1};
const int dy[]={1,-1,0,0};
int h, w, n;
vector<string> s;
vector< vector<int> >steps;
void bfs(vector<P> &starts){
queue<P> q;
for(auto s : starts){
q.push(s);
steps[s.first][s.second] = 0;
}
while(!q.empty()){
int y, x;
tie(y, x) = q.front(); q.pop();
for(int k = 0; k < 4; k++){
int ny = y + dy[k];
int nx = x + dx[k];
if(nx < 0 || w <= nx || ny < 0 || h <= ny) continue;
if(s[ny][nx] == '#') continue;
s[ny][nx] = '#';
steps[ny][nx] = min(steps[ny][nx], steps[y][x] + 1);
q.emplace(ny, nx);
}
}
return;
}
int main() {
#ifdef MYLOCAL
ifstream in("input.txt");
cin.rdbuf(in.rdbuf());
#endif
cin >> h >> w;
s.resize(h);
for(int i = 0;i < h; i++){
cin>>s[i];
}
steps.resize(h);
for(int i = 0;i < h; i++){
steps[i].resize(w);
}
vector<P> starts;
for(int i = 0; i < h; ++i){
for(int j = 0; j < w; ++j){
steps[i][j] = INF32;
if(s[i][j] == '#'){
starts.push_back(make_pair(i, j));
}
}
}
bfs(starts);
int ans = 0;
for(int i = 0; i < h; ++i){
for(int j = 0; j < w; ++j){
ans = max(ans, steps[i][j]);
}
}
cout << ans << endl;
return 0;
}
Code 2: package main
import (
"fmt"
"strconv"
)
func main() {
var N string
fmt.Scan(&N)
A, _ := strconv.Atoi(string(N[0]))
B, _ := strconv.Atoi(string(N[1]))
C, _ := strconv.Atoi(string(N[2]))
D, _ := strconv.Atoi(string(N[3]))
op := []string{"+", "-"}
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
for k := 0; k < 2; k++ {
res := 0
if i == 0 {
res = A + B
} else {
res = A - B
}
if j == 0 {
res = res + C
} else {
res = res - C
}
if k == 0 {
res = res + D
} else {
res = res - D
}
if res == 7 {
fmt.Printf("%d%s%d%s%d%s%d%s\n", A, op[i], B, op[j], C, op[k], D, "=7")
goto END
}
}
}
}
END:
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
#define _GLIBCXX_DEBUG
long long a,b;
long long calc(long long i){
long double res = floor(a*i/b) - a*floor(i/b);
return res;
}
int main() {
long long n;
cin >> a >> b >> n;
cout << calc(min(b-1,n)) << endl;
}
| Python | n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
from collections import defaultdict
d = defaultdict(int)
for ele in a:
d[ele] += 1
print(sum(sorted(d.values(), reverse=True)[k:])) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
#define _GLIBCXX_DEBUG
long long a,b;
long long calc(long long i){
long double res = floor(a*i/b) - a*floor(i/b);
return res;
}
int main() {
long long n;
cin >> a >> b >> n;
cout << calc(min(b-1,n)) << endl;
}
Code 2: n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
from collections import defaultdict
d = defaultdict(int)
for ele in a:
d[ele] += 1
print(sum(sorted(d.values(), reverse=True)[k:])) |
Python | n = int(input())
print(n**3) | C++ | // ¯\_(ツ)_/¯
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mma,ava,tune=native")
//#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define sz(a) ((int)(a).size())
#define all(a) (a).begin(),(a).end()
#define ll long long
void file(){
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
}
int tc;
const int N=2e5+5,M=2e6+5,MOD=1e9+7,OO=1e9;
int main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//file();
int D;
scanf("%d",&D);
std::vector<int> c(26);
for(int i=0;i<26;i++)scanf("%d",&c[i]);
std::vector<vector<int>> s(D,vector<int>(26));
for(int i = 0;i<D;i++){
for(int j=0;j<26;j++){
scanf("%d",&s[i][j]);
}
}
int curr = 0;
std::vector<int> a(26);
for(int i=0;i<26;i++)a[i]=i+1;
random_shuffle(all(a));
for(int i=1;i<=365;i++){
printf("%d\n",a[curr++]);
curr%=26;
}
} | No | Do these codes solve the same problem?
Code 1: n = int(input())
print(n**3)
Code 2: // ¯\_(ツ)_/¯
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mma,ava,tune=native")
//#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define sz(a) ((int)(a).size())
#define all(a) (a).begin(),(a).end()
#define ll long long
void file(){
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
}
int tc;
const int N=2e5+5,M=2e6+5,MOD=1e9+7,OO=1e9;
int main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//file();
int D;
scanf("%d",&D);
std::vector<int> c(26);
for(int i=0;i<26;i++)scanf("%d",&c[i]);
std::vector<vector<int>> s(D,vector<int>(26));
for(int i = 0;i<D;i++){
for(int j=0;j<26;j++){
scanf("%d",&s[i][j]);
}
}
int curr = 0;
std::vector<int> a(26);
for(int i=0;i<26;i++)a[i]=i+1;
random_shuffle(all(a));
for(int i=1;i<=365;i++){
printf("%d\n",a[curr++]);
curr%=26;
}
} |
Kotlin | fun main(args: Array<String>) {
val line = readLine()!!.split(' ').map { it.toInt() }
val n = line[0]
val t = line[1]
var ans = -1
var isFirst = true
for (i in (1..n)) {
val l = readLine()!!.split(' ').map { it.toInt() }
if (isFirst && l[1] <= t || l[0] < ans && l[1] <= t) {
ans = l[0]
isFirst = false
}
}
if (ans == -1) {
println("TLE")
} else {
println(ans)
}
} | Java | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni(), A = ni();
int[] x = na(n);
for(int i = 0;i < n;i++){
x[i] -= A;
}
int O = 3000;
long[][] dp = new long[n+1][6000];
dp[0][O] = 1;
for(int i = 0;i < n;i++){
for(int j = 0;j < 6000;j++){
dp[i+1][j] += dp[i][j];
int nj = j + x[i];
if(nj >= 0 && nj < 6000)dp[i+1][nj] += dp[i][j];
}
}
out.println(dp[n][O]-1);
}
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)); }
}
| No | Do these codes solve the same problem?
Code 1: fun main(args: Array<String>) {
val line = readLine()!!.split(' ').map { it.toInt() }
val n = line[0]
val t = line[1]
var ans = -1
var isFirst = true
for (i in (1..n)) {
val l = readLine()!!.split(' ').map { it.toInt() }
if (isFirst && l[1] <= t || l[0] < ans && l[1] <= t) {
ans = l[0]
isFirst = false
}
}
if (ans == -1) {
println("TLE")
} else {
println(ans)
}
}
Code 2: import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni(), A = ni();
int[] x = na(n);
for(int i = 0;i < n;i++){
x[i] -= A;
}
int O = 3000;
long[][] dp = new long[n+1][6000];
dp[0][O] = 1;
for(int i = 0;i < n;i++){
for(int j = 0;j < 6000;j++){
dp[i+1][j] += dp[i][j];
int nj = j + x[i];
if(nj >= 0 && nj < 6000)dp[i+1][nj] += dp[i][j];
}
}
out.println(dp[n][O]-1);
}
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)); }
}
|
Go | // https://atcoder.jp/contests/abc140/tasks/abc140_a
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
)
// d: debug IO. it can print debug in test.
func solve(io *Io, d *Io) {
N := io.NextInt()
res := Pow(N, 3)
io.Println(res)
}
func main() {
io := NewIo()
defer io.Flush()
solve(io, nil)
}
/* IO Helpers */
// Io combines reader, writer, & tokens as the state when processing the input
type Io struct {
reader *bufio.Reader
writer *bufio.Writer
tokens []string
nextToken int
}
// NewIo creates Io with Stdin & Stdout
func NewIo() *Io {
return &Io{
reader: bufio.NewReader(os.Stdin),
writer: bufio.NewWriter(os.Stdout),
}
}
// Flush calls the writer's Flush
func (io *Io) Flush() {
io.writer.Flush()
}
// NextLine returns the string from reader.ReadLine()
func (io *Io) NextLine() string {
if io.nextToken < len(io.tokens) {
panic("io.nextToken < len(io.tokens)")
}
var buffer bytes.Buffer
for {
line, isPrefix, err := io.reader.ReadLine()
if err != nil {
panic(err)
}
buffer.Write(line)
if !isPrefix {
break
}
}
return buffer.String()
}
// NextLines returns []string from next n lines
func (io *Io) NextLines(n int) []string {
res := make([]string, n)
for i := 0; i < n; i++ {
res[i] = io.NextLine()
}
return res
}
// Next returns the string token (partial string of the line divided by spaces)
func (io *Io) Next() string {
if io.nextToken >= len(io.tokens) {
line := io.NextLine()
io.tokens = strings.Fields(line)
io.nextToken = 0
}
res := io.tokens[io.nextToken]
io.nextToken++
return res
}
// NextStrings returns the []string from the next n tokens
func (io *Io) NextStrings(n int) []string {
res := make([]string, n)
for i := 0; i < n; i++ {
res[i] = io.Next()
}
return res
}
// NextRunes returns next string as []rune
func (io *Io) NextRunes() []rune {
return []rune(io.Next())
}
// NextInt returns the int from the next token
func (io *Io) NextInt() int {
res, err := strconv.Atoi(io.Next())
if err != nil {
panic(err)
}
return res
}
// NextInts returns the []int from the next n tokens
func (io *Io) NextInts(n int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
res[i] = io.NextInt()
}
return res
}
// NextFloat returns the float64 from the next token
func (io *Io) NextFloat() float64 {
res, err := strconv.ParseFloat(io.Next(), 64)
if err != nil {
panic(err)
}
return res
}
// NextFloats returns the []float64 from the next n tokens
func (io *Io) NextFloats(n int) []float64 {
res := make([]float64, n)
for i := 0; i < n; i++ {
res[i] = io.NextFloat()
}
return res
}
// Println prints the input to the writer in an easy-to-see form
func (io *Io) Println(a ...interface{}) {
var values []string
for i := 0; i < len(a); i++ {
values = append(values, "%v")
}
io.Printfln(strings.Join(values, " "), a...)
}
// Print calls Fprint to the writer
func (io *Io) Print(a interface{}) {
fmt.Fprint(io.writer, a)
}
// Printf calls Fprintf to the writer
func (io *Io) Printf(format string, a ...interface{}) {
fmt.Fprintf(io.writer, format, a...)
}
// Printfln calls Fprint to the writer
func (io *Io) Printfln(format string, a ...interface{}) {
fmt.Fprintf(io.writer, format+"\n", a...)
}
// PrintInts prints ints with space and new line at the end
func (io *Io) PrintInts(ints []int) {
for i, e := range ints {
io.Print(e)
if i == len(ints)-1 {
io.Println()
} else {
io.Print(" ")
}
}
}
// Debug calls Println and Flush immediately
func (io *Io) Debug(a ...interface{}) {
if io == nil {
return
}
io.Println(a...)
io.Flush()
}
// Assert checks the value equality for debug
func (io *Io) Assert(a, b interface{}) {
if io == nil {
return
}
if !reflect.DeepEqual(a, b) {
_, _, line, _ := runtime.Caller(1)
io.Debug("Diff:", line, "\na:", a, "\nb:", b)
}
}
/* Math Helpers */
// MOD is 10^9 + 7
const MOD = 1000000007
// Max of the ints
func Max(numbers ...int) int {
max := numbers[0]
for i, number := range numbers {
if i == 0 {
continue
}
if number > max {
max = number
}
}
return max
}
// Min of the ints
func Min(numbers ...int) int {
min := numbers[0]
for i, number := range numbers {
if i == 0 {
continue
}
if min > number {
min = number
}
}
return min
}
// Sum of the ints
func Sum(numbers ...int) int {
sum := 0
for _, number := range numbers {
sum += number
}
return sum
}
// Pow calculates the pow for int with O(log e)
func Pow(a, e int) int {
if a < 0 || e < 0 {
panic(fmt.Sprintf("Pow was called for a < 0 or e < 0, a: %d, e: %d", a, e))
}
if e == 0 {
return 1
}
if e%2 == 0 {
half := Pow(a, e/2)
return half * half
}
return a * Pow(a, e-1)
}
// Abs returns the absolute value of the input
func Abs(a int) int {
if a < 0 {
return -a
}
return a
}
/* Structure Helpers */
// Set is orderless List
type Set map[interface{}]struct{}
// NewSet returns empty Set
func NewSet() *Set {
return &Set{}
}
// Add the value to the set
func (set *Set) Add(value interface{}) {
(*set)[value] = struct{}{}
}
// Includes check the set has the value
func (set *Set) Includes(value interface{}) bool {
_, included := (*set)[value]
return included
}
// Remove deletes the value from the set if exists
func (set *Set) Remove(value interface{}) {
if !set.Includes(value) {
return
}
delete(*set, value)
}
// ImmutableSort returns sorted slice without mutating original one
func ImmutableSort(slice []int) []int {
res := make([]int, len(slice))
copy(res, slice)
sort.Ints(res)
return res
}
/* Util helpers */
// Ternary is like `cond ? a : b`. should assert the returned value like `Ternary(cond, a, b).(int)`
func Ternary(cond bool, a, b interface{}) interface{} {
if cond {
return a
}
return b
}
// TernaryInt uses Ternary and assert the value as int
func TernaryInt(cond bool, a, b int) int {
return Ternary(cond, a, b).(int)
}
// TernaryString uses Ternary and assert the value as string
func TernaryString(cond bool, a, b string) string {
return Ternary(cond, a, b).(string)
}
| PHP | <?php
fscanf(STDIN, "%d", $n);
echo $n**3; | Yes | Do these codes solve the same problem?
Code 1: // https://atcoder.jp/contests/abc140/tasks/abc140_a
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
)
// d: debug IO. it can print debug in test.
func solve(io *Io, d *Io) {
N := io.NextInt()
res := Pow(N, 3)
io.Println(res)
}
func main() {
io := NewIo()
defer io.Flush()
solve(io, nil)
}
/* IO Helpers */
// Io combines reader, writer, & tokens as the state when processing the input
type Io struct {
reader *bufio.Reader
writer *bufio.Writer
tokens []string
nextToken int
}
// NewIo creates Io with Stdin & Stdout
func NewIo() *Io {
return &Io{
reader: bufio.NewReader(os.Stdin),
writer: bufio.NewWriter(os.Stdout),
}
}
// Flush calls the writer's Flush
func (io *Io) Flush() {
io.writer.Flush()
}
// NextLine returns the string from reader.ReadLine()
func (io *Io) NextLine() string {
if io.nextToken < len(io.tokens) {
panic("io.nextToken < len(io.tokens)")
}
var buffer bytes.Buffer
for {
line, isPrefix, err := io.reader.ReadLine()
if err != nil {
panic(err)
}
buffer.Write(line)
if !isPrefix {
break
}
}
return buffer.String()
}
// NextLines returns []string from next n lines
func (io *Io) NextLines(n int) []string {
res := make([]string, n)
for i := 0; i < n; i++ {
res[i] = io.NextLine()
}
return res
}
// Next returns the string token (partial string of the line divided by spaces)
func (io *Io) Next() string {
if io.nextToken >= len(io.tokens) {
line := io.NextLine()
io.tokens = strings.Fields(line)
io.nextToken = 0
}
res := io.tokens[io.nextToken]
io.nextToken++
return res
}
// NextStrings returns the []string from the next n tokens
func (io *Io) NextStrings(n int) []string {
res := make([]string, n)
for i := 0; i < n; i++ {
res[i] = io.Next()
}
return res
}
// NextRunes returns next string as []rune
func (io *Io) NextRunes() []rune {
return []rune(io.Next())
}
// NextInt returns the int from the next token
func (io *Io) NextInt() int {
res, err := strconv.Atoi(io.Next())
if err != nil {
panic(err)
}
return res
}
// NextInts returns the []int from the next n tokens
func (io *Io) NextInts(n int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
res[i] = io.NextInt()
}
return res
}
// NextFloat returns the float64 from the next token
func (io *Io) NextFloat() float64 {
res, err := strconv.ParseFloat(io.Next(), 64)
if err != nil {
panic(err)
}
return res
}
// NextFloats returns the []float64 from the next n tokens
func (io *Io) NextFloats(n int) []float64 {
res := make([]float64, n)
for i := 0; i < n; i++ {
res[i] = io.NextFloat()
}
return res
}
// Println prints the input to the writer in an easy-to-see form
func (io *Io) Println(a ...interface{}) {
var values []string
for i := 0; i < len(a); i++ {
values = append(values, "%v")
}
io.Printfln(strings.Join(values, " "), a...)
}
// Print calls Fprint to the writer
func (io *Io) Print(a interface{}) {
fmt.Fprint(io.writer, a)
}
// Printf calls Fprintf to the writer
func (io *Io) Printf(format string, a ...interface{}) {
fmt.Fprintf(io.writer, format, a...)
}
// Printfln calls Fprint to the writer
func (io *Io) Printfln(format string, a ...interface{}) {
fmt.Fprintf(io.writer, format+"\n", a...)
}
// PrintInts prints ints with space and new line at the end
func (io *Io) PrintInts(ints []int) {
for i, e := range ints {
io.Print(e)
if i == len(ints)-1 {
io.Println()
} else {
io.Print(" ")
}
}
}
// Debug calls Println and Flush immediately
func (io *Io) Debug(a ...interface{}) {
if io == nil {
return
}
io.Println(a...)
io.Flush()
}
// Assert checks the value equality for debug
func (io *Io) Assert(a, b interface{}) {
if io == nil {
return
}
if !reflect.DeepEqual(a, b) {
_, _, line, _ := runtime.Caller(1)
io.Debug("Diff:", line, "\na:", a, "\nb:", b)
}
}
/* Math Helpers */
// MOD is 10^9 + 7
const MOD = 1000000007
// Max of the ints
func Max(numbers ...int) int {
max := numbers[0]
for i, number := range numbers {
if i == 0 {
continue
}
if number > max {
max = number
}
}
return max
}
// Min of the ints
func Min(numbers ...int) int {
min := numbers[0]
for i, number := range numbers {
if i == 0 {
continue
}
if min > number {
min = number
}
}
return min
}
// Sum of the ints
func Sum(numbers ...int) int {
sum := 0
for _, number := range numbers {
sum += number
}
return sum
}
// Pow calculates the pow for int with O(log e)
func Pow(a, e int) int {
if a < 0 || e < 0 {
panic(fmt.Sprintf("Pow was called for a < 0 or e < 0, a: %d, e: %d", a, e))
}
if e == 0 {
return 1
}
if e%2 == 0 {
half := Pow(a, e/2)
return half * half
}
return a * Pow(a, e-1)
}
// Abs returns the absolute value of the input
func Abs(a int) int {
if a < 0 {
return -a
}
return a
}
/* Structure Helpers */
// Set is orderless List
type Set map[interface{}]struct{}
// NewSet returns empty Set
func NewSet() *Set {
return &Set{}
}
// Add the value to the set
func (set *Set) Add(value interface{}) {
(*set)[value] = struct{}{}
}
// Includes check the set has the value
func (set *Set) Includes(value interface{}) bool {
_, included := (*set)[value]
return included
}
// Remove deletes the value from the set if exists
func (set *Set) Remove(value interface{}) {
if !set.Includes(value) {
return
}
delete(*set, value)
}
// ImmutableSort returns sorted slice without mutating original one
func ImmutableSort(slice []int) []int {
res := make([]int, len(slice))
copy(res, slice)
sort.Ints(res)
return res
}
/* Util helpers */
// Ternary is like `cond ? a : b`. should assert the returned value like `Ternary(cond, a, b).(int)`
func Ternary(cond bool, a, b interface{}) interface{} {
if cond {
return a
}
return b
}
// TernaryInt uses Ternary and assert the value as int
func TernaryInt(cond bool, a, b int) int {
return Ternary(cond, a, b).(int)
}
// TernaryString uses Ternary and assert the value as string
func TernaryString(cond bool, a, b string) string {
return Ternary(cond, a, b).(string)
}
Code 2: <?php
fscanf(STDIN, "%d", $n);
echo $n**3; |
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 Problem = Tmp.Problem;
namespace Tmp
{
using static Func;
using static Math;
using static Console;
//using GeometryLong;
class Problem : IDisposable
{
bool IsGCJ;
int Repeat;
Scanner sc;
Printer pr;
public Problem(bool isGCJ, Scanner scanner, Printer printer)
{
sc = scanner;
pr = printer;
IsGCJ = isGCJ;
if (isGCJ) Repeat = sc.Get<int>();
else Read();
}
public Problem(bool isGCJ) : this(isGCJ, new Scanner(), new Printer()) { }
public Problem(bool isGCJ, Scanner scanner) : this(isGCJ, scanner, new Printer()) { }
public Problem(bool isGCJ, Printer printer) : this(isGCJ, new Scanner(), printer) { }
public void Solve()
{
if (IsGCJ) for (var i = 0; i < Repeat; i++) { Read(); pr.Write("Case #" + (i + 1) + ": "); SolveOne(); }
else SolveOne();
}
public void Dispose()
{
sc.Dispose();
pr.Dispose();
}
public int Size => 1;
public const long Mod = 1000000007;
//public const long Mod = 924844033;
RandomSFMT rand = Program.rand;
int N, A, B;
int[] h;
void Read()
{
sc.Read(out N, out A, out B);
h = sc.ReadManyLines<int>(N);
}
void SolveOne()
{
pr.WriteLine(FirstBinary(0, Inf, OK));
}
bool OK(int n)
{
var s = 0L;
var d = A - B;
foreach (var p in h)
{
var l = p - (long)n * B;
if (l >= 0) s += (l + d - 1) / d;
if (s > n) return false;
}
return s <= n;
}
int[] SuffixArray(string S)
{
var N = S.Length;
var sa = new int[N + 1];
var r = new int[N + 1];
for (var i = 0; i <= N; i++)
{
sa[i] = i;
r[i] = i < N ? S[i] : -1;
}
var k = 1;
Comparison<int> comp = (i, j) =>
{
if (r[i] != r[j]) return r[i] - r[j];
var a = i + k <= N ? r[i + k] : -1;
var b = j + k <= N ? r[j + k] : -1;
return a - b;
};
for (; k <= N; k *= 2)
{
Array.Sort(sa, comp);
var tmp = new int[N + 1];
for (var i = 1; i <= N; i++) tmp[sa[i]] = tmp[sa[i - 1]] + (comp(sa[i - 1], sa[i]) < 0 ? 1 : 0);
r = tmp;
}
return sa;
}
}
class RangeSegmentTree
{
int N2;
int[] seg, unif;
public RangeSegmentTree(int N)
{
N2 = 1;
while (N2 < N) N2 <<= 1;
seg = new int[2 * N2 - 1];
unif = new int[2 * N2 - 1];
}
void LazyEvaluate(int node)
{
if (unif[node] == 0) return;
seg[node] += unif[node];
if (node < N2 - 1)
{
unif[2 * node + 1] += unif[node];
unif[2 * node + 2] += unif[node];
}
unif[node] = 0;
}
void Update(int node) => seg[node] = seg[2 * node + 1] + seg[2 * node + 2];
public void AddRange(int from, int to, int value) => AddRange(from, to, value, 0, 0, N2);
void AddRange(int from, int to, int value, int node, int l, int r)
{
if (from <= l && r <= to) unif[node] += value;
else if (l < to && from < r)
{
AddRange(from, to, value, 2 * node + 1, l, (l + r) >> 1);
AddRange(from, to, value, 2 * node + 2, (l + r) >> 1, r);
Update(node);
}
LazyEvaluate(node);
}
public int this[int n] { get { return Sum(n, n + 1); } set { AddRange(n, n + 1, value - this[n]); } }
public int Sum(int from, int to) => Sum(from, to, 0, 0, N2);
int Sum(int from, int to, int node, int l, int r)
{
LazyEvaluate(node);
if (to <= l || r <= from) return 0;
else if (from <= l && r <= to) return seg[node];
else return Sum(from, to, 2 * node + 1, l, (l + r) >> 1) + Sum(from, to, 2 * node + 2, (l + r) >> 1, r);
}
}
class SlideMaximum
{
long[] a;
Deque<int> deq;
public SlideMaximum(long[] x) { a = x; deq = new Deque<int>(); }
public void Add(int index)
{
while (deq.Count > 0 && a[deq.PeekBack()] <= a[index]) deq.PopBack();
deq.PushBack(index);
}
public void Remove(int index)
{
if (deq.Count > 0 && deq.PeekFront() == index) deq.PopFront();
}
public long Maximum => a[deq.PeekFront()];
}
class SegmentTreeX
{
public const long Unit = -InfL;
int N2;
long[] seg, unif;
public SegmentTreeX(int N)
{
N2 = 1;
while (N2 < N) N2 <<= 1;
seg = new long[2 * N2 - 1];
unif = new long[2 * N2 - 1];
for (var i = 0; i < 2 * N2 - 1; i++) seg[i] = unif[i] = Unit;
}
void LazyEvaluate(int node)
{
if (unif[node] != Unit)
{
seg[node] = Math.Max(seg[node], unif[node]);
if (node < N2 - 1)
{
unif[2 * node + 1] = Math.Max(unif[2 * node + 1], unif[node]);
unif[2 * node + 2] = Math.Max(unif[2 * node + 2], unif[node]);
}
unif[node] = Unit;
}
}
void Update(int node) => seg[node] = Math.Max(seg[2 * node + 1], seg[2 * node + 2]);
public void Maximize(int from, int to, long value) => Maximize(from, to, value, 0, 0, N2);
void Maximize(int from, int to, long value, int node, int l, int r)
{
if (from <= l && r <= to) unif[node] = Math.Max(unif[node], value);
else if (l < to && from < r)
{
Maximize(from, to, value, 2 * node + 1, l, (l + r) >> 1);
Maximize(from, to, value, 2 * node + 2, (l + r) >> 1, r);
Update(node);
}
LazyEvaluate(node);
}
public long this[int n] { get { return Max(n, n + 1); } set { Maximize(n, n + 1, value); } }
public long Max(int from, int to) => Max(from, to, 0, 0, N2);
long Max(int from, int to, int node, int l, int r)
{
LazyEvaluate(node);
if (to <= l || r <= from) return Unit;
else if (from <= l && r <= to) return seg[node];
else return Math.Max(Max(from, to, 2 * node + 1, l, (l + r) >> 1), Max(from, to, 2 * node + 2, (l + r) >> 1, r));
}
}
}
class Treap<T>
{
Random rand;
Comparison<T> comp;
class Node
{
public T value;
public int size;
private int priority;
public Node left, right;
public Treap<T> treap;
public Node(Treap<T> treap, T value) { this.treap = treap; this.value = value; priority = treap.rand.Next(); size = 1; }
public Node Update() { size = 1 + Size(left) + Size(right); return this; }
public static int Size(Node t) => t?.size ?? 0;
public static Node Merge(Node l, Node r)
{
if (l == null) return r;
if (r == null) return l;
if (l.priority < r.priority)
{
l.right = Merge(l.right, r);
return l.Update();
}
else
{
r.left = Merge(r.left, l);
return r.Update();
}
}
// [0,N) => [0,k) + [k,N)
public static Tuple<Node, Node> Split(Node t, int k)
{
if (t == null) return new Tuple<Node, Node>(null, null);
if (k <= Size(t.left))
{
var s = Split(t.left, k);
t.left = s.Item2;
return new Tuple<Node, Node>(s.Item1, t.Update());
}
else
{
var s = Split(t.right, k - Size(t.left) - 1);
t.right = s.Item1;
return new Tuple<Node, Node>(t.Update(), s.Item2);
}
}
// [0,k) + [k,N) => [0,k) + (new node) + [k+1,N)
public static Node Insert(Node t, int k, T val)
{
var n = new Node(t.treap, val);
var s = Split(t, k);
return Merge(Merge(s.Item1, n), s.Item2);
}
// [0,k) + k + [k+1,N) => [0,k) + [k+1,N)
public static Node Erase(Node t, int k)
{
var s1 = Split(t, k + 1);
var s2 = Split(s1.Item1, k);
return Merge(s2.Item1, s1.Item2);
}
}
}
class RMQI
{
int N2;
int[] segtree;
int[] position;
public RMQI(int N) : this(new int[N]) { }
public RMQI(int[] array)
{
N2 = 1;
while (N2 < array.Length) N2 <<= 1;
segtree = new int[2 * N2 - 1];
position = new int[2 * N2 - 1];
for (var i = 0; i < 2 * N2 - 1; i++) segtree[i] = Func.Inf;
for (var i = 0; i < array.Length; i++) { segtree[i + N2 - 1] = array[i]; position[i + N2 - 1] = i; }
for (var i = N2 - 2; i >= 0; i--) SetMin(i);
}
void SetMin(int i)
{
int l = 2 * i + 1, r = 2 * i + 2;
int a = segtree[l], b = segtree[r];
if (a <= b) { segtree[i] = a; position[i] = position[l]; }
else { segtree[i] = b; position[i] = position[r]; }
}
Tuple<int, int> Merge(Tuple<int, int> a, Tuple<int, int> b) => a.Item1 <= b.Item1 ? a : b;
public void Update(int index, int value)
{
index += N2 - 1;
segtree[index] = value;
while (index > 0) SetMin(index = (index - 1) / 2);
}
public int this[int n] { get { return Min(n, n + 1).Item1; } set { Update(n, value); } }
// min, pos
public Tuple<int, int> Min(int from, int to) => Min(from, to, 0, 0, N2);
Tuple<int, int> Min(int from, int to, int node, int l, int r)
{
if (to <= l || r <= from) return new Tuple<int, int>(Func.Inf, N2);
else if (from <= l && r <= to) return new Tuple<int, int>(segtree[node], position[node]);
else return Merge(Min(from, to, 2 * node + 1, l, (l + r) >> 1), Min(from, to, 2 * node + 2, (l + r) >> 1, r));
}
}
static class Hoge
{
public static T Peek<T>(this IEnumerable<T> set)
{
foreach (var x in set) return x;
return default(T);
}
}
interface ISegmentTree<T> where T : IComparable<T>
{
void Add(int from, int to, T value);
T Min(int from, int to);
}
class SegmentTree2 : ISegmentTree<long>
{
int N;
long[] a;
public SegmentTree2(int N) : this(new long[N]) { }
public SegmentTree2(long[] a) { N = a.Length; this.a = a.ToArray(); }
public void Add(int from, int to, long value) { for (var i = from; i < to; i++) a[i] += value; }
public long Min(int from, int to) { var s = Func.InfL; for (var i = from; i < to; i++) s = Math.Min(s, a[i]); return s; }
}
class SegmentTree3 : ISegmentTree<long>
{
public const long Unit = Func.InfL;
public readonly Func<long, long, long> Operator = Math.Min;
int N2;
long[] seg, unif;
public SegmentTree3(int N) : this(new long[N]) { }
public SegmentTree3(long[] a)
{
N2 = 1;
while (N2 < a.Length) N2 <<= 1;
seg = new long[2 * N2 - 1];
unif = new long[2 * N2 - 1];
for (var i = a.Length + N2 - 1; i < 2 * N2 - 1; i++) seg[i] = Unit;
for (var i = 0; i < a.Length; i++) seg[i + N2 - 1] = a[i];
for (var i = N2 - 2; i >= 0; i--) Update(i);
}
void LazyEvaluate(int node)
{
if (unif[node] != 0)
{
seg[node] += unif[node];
if (node < N2 - 1) { unif[2 * node + 1] += unif[node]; unif[2 * node + 2] += unif[node]; }
unif[node] = 0;
}
}
void Update(int node) => seg[node] = Operator(seg[2 * node + 1], seg[2 * node + 2]);
public void Add(int from, int to, long value) => Add(from, to, value, 0, 0, N2);
void Add(int from, int to, long value, int node, int l, int r)
{
if (from <= l && r <= to) unif[node] += value;
else if (l < to && from < r)
{
Add(from, to, value, 2 * node + 1, l, (l + r) >> 1);
Add(from, to, value, 2 * node + 2, (l + r) >> 1, r);
Update(node);
}
LazyEvaluate(node);
}
public long this[int n] { get { return Min(n, n + 1); } set { Add(n, n + 1, value - this[n]); } }
public long Min(int from, int to) => Min(from, to, 0, 0, N2);
long Min(int from, int to, int node, int l, int r)
{
LazyEvaluate(node);
if (to <= l || r <= from) return Unit;
else if (from <= l && r <= to) return seg[node];
else return Operator(Min(from, to, 2 * node + 1, l, (l + r) >> 1), Min(from, to, 2 * node + 2, (l + r) >> 1, r));
}
}
class SegmentTree : ISegmentTree<long>
{
int N2;
long[] seg, unif;
public SegmentTree(int N) : this(new long[N]) { }
public SegmentTree(long[] a)
{
N2 = 1;
while (N2 < a.Length) N2 <<= 1;
seg = new long[2 * N2 - 1];
unif = new long[2 * N2 - 1];
for (var i = a.Length + N2 - 1; i < 2 * N2 - 1; i++) seg[i] = Func.InfL;
for (var i = 0; i < a.Length; i++) seg[i + N2 - 1] = a[i];
for (var i = N2 - 2; i >= 0; i--) seg[i] = Math.Min(seg[2 * i + 1], seg[2 * i + 2]);
}
public void Add(int from, int to, long value) => Add(from, to, value, 0, 0, N2);
void Add(int from, int to, long value, int node, int l, int r)
{
if (to <= l || r <= from) return;
else if (from <= l && r <= to) unif[node] += value;
else
{
Add(from, to, value, 2 * node + 1, l, (l + r) >> 1);
Add(from, to, value, 2 * node + 2, (l + r) >> 1, r);
seg[node] = Math.Min(seg[2 * node + 1] + unif[2 * node + 1], seg[2 * node + 2] + unif[2 * node + 2]);
}
}
public long this[int n] { get { return Min(n, n + 1); } set { Add(n, n + 1, value - this[n]); } }
public long Min(int from, int to) => Min(from, to, 0, 0, N2);
long Min(int from, int to, int node, int l, int r)
{
if (to <= l || r <= from) return Func.InfL;
else if (from <= l && r <= to) return seg[node] + unif[node];
else return Math.Min(Min(from, to, 2 * node + 1, l, (l + r) >> 1), Min(from, to, 2 * node + 2, (l + r) >> 1, r)) + unif[node];
}
}
class Eq : IEqualityComparer<List<int>>
{
public bool Equals(List<int> x, List<int> y)
{
if (x == null || y == null) return x == y;
if (x.Count != y.Count) return false;
for (var i = 0; i < x.Count; i++) if (x[i] != y[i]) return false;
return true;
}
public int GetHashCode(List<int> obj)
{
var x = obj.Count.GetHashCode();
foreach (var i in obj) x ^= i.GetHashCode();
return x;
}
}
class MultiSortedSet<T> : IEnumerable<T>, ICollection<T>
{
public IComparer<T> Comparer { get; private set; }
private SortedSet<T> keys;
private Dictionary<T, int> mult;
public int Multiplicity(T item) => keys.Contains(item) ? mult[item] : 0;
public int this[T item]
{
get { return Multiplicity(item); }
set
{
Debug.Assert(value >= 0);
if (value == 0) { if (keys.Contains(item)) Remove(item); }
else
{
Count += value - mult[item];
mult[item] = value;
}
}
}
public int Count { get; private set; }
public MultiSortedSet(IComparer<T> comp)
{
keys = new SortedSet<T>(Comparer = comp);
mult = new Dictionary<T, int>();
}
public MultiSortedSet(Comparison<T> comp) : this(Comparer<T>.Create(comp)) { }
public MultiSortedSet() : this(Func.DefaultComparison<T>()) { }
public void Add(T item) => Add(item, 1);
private void Add(T item, int num)
{
Count += num;
if (!keys.Contains(item)) { keys.Add(item); mult.Add(item, num); }
else mult[item] += num;
}
public void AddRange(IEnumerable<T> list) { foreach (var x in list) Add(x); }
public bool Remove(T item)
{
if (!keys.Contains(item)) return false;
Count--;
if (mult[item] == 1) { keys.Remove(item); mult.Remove(item); }
else mult[item]--;
return true;
}
public bool Overlaps(IEnumerable<T> other) => keys.Overlaps(other);
public bool IsSupersetOf(IEnumerable<T> other) => keys.IsSupersetOf(other);
public bool IsSubsetOf(IEnumerable<T> other) => keys.IsSubsetOf(other);
public bool IsProperSubsetOf(IEnumerable<T> other) => keys.IsProperSubsetOf(other);
public bool IsProperSupersetOf(IEnumerable<T> other) => keys.IsProperSupersetOf(other);
public void ExceptWith(IEnumerable<T> other) { foreach (var x in other) if (Contains(x)) Remove(x); }
public void IntersectWith(IEnumerable<T> other)
{
var next = new MultiSortedSet<T>(Comparer);
foreach (var x in other) if (Contains(x) && !next.Contains(x)) next.Add(x, mult[x]);
keys = next.keys; mult = next.mult;
}
public void CopyTo(T[] array) => CopyTo(array, 0);
public void CopyTo(T[] array, int index) { foreach (var item in array) array[index++] = item; }
public void CopyTo(T[] array, int index, int count) { var i = 0; foreach (var item in array) { if (i++ >= count) return; array[index++] = item; } }
public bool Contains(T item) => keys.Contains(item);
public void Clear() { keys.Clear(); mult.Clear(); Count = 0; }
public IEnumerator<T> Reverse() { foreach (var x in keys.Reverse()) for (var i = 0; i < mult[x]; i++) yield return x; }
public IEnumerator<T> GetEnumerator() { foreach (var x in keys) for (var i = 0; i < mult[x]; i++) yield return x; }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public T Max => keys.Max;
public T Min => keys.Min;
public bool IsReadOnly => false;
}
class SkewHeap<T> : IEnumerable<T>
{
class Node : IEnumerable<T>
{
public Node l, r;
public T val;
public Node(T x) { l = r = null; val = x; }
public IEnumerator<T> GetEnumerator()
{
if (l != null) foreach (var x in l) yield return x;
yield return val;
if (r != null) foreach (var x in r) yield return x;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public int Count { get; private set; }
Node head;
Comparison<T> comp;
public bool IsEmpty => head != null;
public SkewHeap(Comparison<T> c) { comp = c; Count = 0; }
public SkewHeap() : this(Func.DefaultComparison<T>()) { }
public SkewHeap(IComparer<T> c) : this(Func.ToComparison(c)) { }
private SkewHeap(Comparison<T> c, Node h) : this(c) { head = h; }
public void Push(T x) { var n = new Node(x); head = Meld(head, n); Count++; }
public T Peek() => head.val;
public T Pop() { var x = head.val; head = Meld(head.l, head.r); Count--; return x; }
// a.comp must be equivalent to b.comp
// a, b will be destroyed
public static SkewHeap<T> Meld(SkewHeap<T> a, SkewHeap<T> b) => new SkewHeap<T>(a.comp, a.Meld(a.head, b.head));
public void MeldWith(SkewHeap<T> a) => head = Meld(head, a.head);
Node Meld(Node a, Node b)
{
if (a == null) return b;
else if (b == null) return a;
if (comp(a.val, b.val) > 0) Func.Swap(ref a, ref b);
a.r = Meld(a.r, b);
Func.Swap(ref a.l, ref a.r);
return a;
}
public IEnumerator<T> GetEnumerator() => head.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => (IEnumerator)GetEnumerator();
}
// [0, Size) の整数の集合を表す
class BITSet : BinaryIndexedTree
{
public BITSet(int size) : base(size) { }
public void Add(int item) => Add(item, 1);
public bool Contains(int item) => Sum(item, item + 1) > 0;
public int Count(int item) => Sum(item, item + 1);
// 順位 = item が小さい方から何番目か(0-indexed)
public int GetRank(int item) => Sum(0, item);
public void Remove(int item) => Add(item, -1);
public void RemoveAll(int item) => Add(item, -Count(item));
// 0-indexed で順位が rank のものを求める
// ない場合は Size が返る
public int GetValue(int rank) => Func.FirstBinary(0, Size, t => Sum(0, t + 1) >= rank + 1);
}
class RangeBIT
{
public int N { get; private set; }
long[,] bit;
public RangeBIT(int N) { bit = new long[2, this.N = N + 1]; }
public RangeBIT(int[] array) : this(array.Length)
{
for (var i = 1; i < N; i++) bit[0, i] = array[i - 1];
for (var i = 1; i < N - 1; i++) if (i + (i & (-i)) < N) bit[0, i + (i & (-i))] += bit[0, i];
}
public RangeBIT(long[] array) : this(array.Length)
{
for (var i = 1; i < N; i++) bit[0, i] = array[i - 1];
for (var i = 1; i < N - 1; i++) if (i + (i & (-i)) < N) bit[0, i + (i & (-i))] += bit[0, i];
}
public void Add(int from, int to, long value)
{
Add2(0, from + 1, -value * from);
Add2(1, from + 1, value);
Add2(0, to + 1, value * to);
Add2(1, to + 1, -value);
}
void Add2(int which, int i, long value) { while (i < N) { bit[which, i] += value; i += i & (-i); } }
long Sum(int to) => Sum2(0, to) + Sum2(1, to) * to;
public long Sum(int from, int to) => Sum(to) - Sum(from);
long Sum2(int which, int i) { var sum = 0L; while (i > 0) { sum += bit[which, i]; i -= i & (-i); } return sum; }
}
class RMQ
{
int N2;
int[] segtree;
public RMQ(int N) : this(new int[N]) { }
public RMQ(int[] array)
{
N2 = 1;
while (N2 < array.Length) N2 <<= 1;
segtree = new int[2 * N2 - 1];
for (var i = 0; i < 2 * N2 - 1; i++) segtree[i] = Func.Inf;
for (var i = 0; i < array.Length; i++) segtree[i + N2 - 1] = array[i];
for (var i = N2 - 2; i >= 0; i--) segtree[i] = Math.Min(segtree[2 * i + 1], segtree[2 * i + 2]);
}
public void Update(int index, int value)
{
index += N2 - 1;
segtree[index] = value;
while (index > 0)
{
index = (index - 1) / 2;
segtree[index] = Math.Min(segtree[index * 2 + 1], segtree[index * 2 + 2]);
}
}
public int this[int n] { get { return Min(n, n + 1); } set { Update(n, value); } }
public int Min(int from, int to) => Min(from, to, 0, 0, N2);
int Min(int from, int to, int node, int l, int r)
{
if (to <= l || r <= from) return Func.Inf;
else if (from <= l && r <= to) return segtree[node];
else return Math.Min(Min(from, to, 2 * node + 1, l, (l + r) >> 1), Min(from, to, 2 * node + 2, (l + r) >> 1, r));
}
}
class Program
{
public static RandomSFMT rand = new RandomSFMT();
public static bool IsJudgeMode = true;
public static bool IsGCJMode = false;
public static bool IsSolveCreated = true;
static void Main()
{
if (IsJudgeMode)
if (IsGCJMode) using (var problem = new Problem(true, new Scanner("C-large-practice.in.txt"), new Printer("output.txt"))) problem.Solve();
else using (var problem = new Problem(false, new Printer())) problem.Solve();
else
{
var num = 1;
var size = 0;
var time = 0m;
for (var tmp = 0; tmp < num; tmp++)
{
using (var P = IsSolveCreated ? new Problem(false, new Scanner("input.txt"), new Printer()) : new Problem(false))
{
size = P.Size;
time += Func.MeasureTime(() => P.Solve());
}
}
Console.WriteLine("{0}, {1}ms", size, time / num);
}
}
}
class BinaryIndexedTree3D
{
public int X { get; private set; }
public int Y { get; private set; }
public int Z { get; private set; }
int[,,] bit;
public BinaryIndexedTree3D(int X, int Y, int Z)
{
this.X = X; this.Y = Y; this.Z = Z;
bit = new int[X + 1, Y + 1, Z + 1];
}
public BinaryIndexedTree3D(int[,,] array)
: this(array.GetLength(0), array.GetLength(1), array.GetLength(2))
{
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) for (var z = 0; z < Z; z++) Add(x, y, z, array[x, y, z]);
}
public void Add(int x, int y, int z, int value)
{
for (var i = x + 1; i <= X; i += i & (-i)) for (var j = y + 1; j <= Y; j += j & (-j)) for (var k = z + 1; k <= Z; k += k & (-k)) bit[i, j, k] += value;
}
public int Sum(int x0, int y0, int z0, int x1, int y1, int z1)
=> Sum(x1, y1, z1) - Sum(x0, y1, z1) - Sum(x1, y0, z1) - Sum(x1, y1, z0) + Sum(x1, y0, z0) + Sum(x0, y1, z0) + Sum(x0, y0, z1) - Sum(x0, y0, z0);
int Sum(int x, int y, int z)
{
var sum = 0;
for (var i = x; i > 0; i -= i & (-i)) for (var j = y; j > 0; j -= j & (-j)) for (var k = y; k > 0; k -= k & (-k)) sum += bit[i, j, k];
return sum;
}
}
class BinaryIndexedTree2D
{
public int X { get; private set; }
public int Y { get; private set; }
int[,] bit;
public BinaryIndexedTree2D(int X, int Y)
{
this.X = X; this.Y = Y;
bit = new int[X + 1, Y + 1];
}
public BinaryIndexedTree2D(int[,] array)
: this(array.GetLength(0), array.GetLength(1))
{
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) Add(x, y, array[x, y]);
}
public void Add(int x, int y, int value) { for (var i = x + 1; i <= X; i += i & (-i)) for (var j = y + 1; j <= Y; j += j & (-j)) bit[i, j] += value; }
public int Sum(int x0, int y0, int x1, int y1) => Sum(x0, y0) + Sum(x1, y1) - Sum(x0, y1) - Sum(x1, y0);
int Sum(int x, int y) { var sum = 0; for (var i = x; i > 0; i -= i & (-i)) for (var j = y; j > 0; j -= j & (-j)) sum += bit[i, j]; return sum; }
}
class BinaryIndexedTree
{
public int Size { get; private set; }
int[] bit;
public BinaryIndexedTree(int size)
{
Size = size;
bit = new int[size + 1];
}
public BinaryIndexedTree(int[] array) : this(array.Length)
{
for (var i = 0; i < Size; i++) bit[i + 1] = array[i];
for (var i = 1; i < Size; i++) if (i + (i & (-i)) <= Size) bit[i + (i & (-i))] += bit[i];
}
// index is 0-indexed
public void Add(int index, int value) { for (var i = index + 1; i <= Size; i += i & (-i)) bit[i] += value; }
// from, to is 0-indexed
// from is inclusive, to is exclusive
public int Sum(int from, int to) => Sum(to) - Sum(from);
int Sum(int to) { var sum = 0; for (var i = to; i > 0; i -= i & (-i)) sum += bit[i]; return sum; }
}
class Amoeba
{
public const int Dimension = 2;
public const double Alpha = 1; // reflection
public const double Beta = 1 + 2.0 / Dimension; // expansion
public const double Gamma = 0.75 - 0.5 / Dimension; // contraction
public const double Delta = 1 - 1.0 / Dimension; // shrink
public Pair<AmoebaState, double>[] a;
public AmoebaState m;
public void Initiate()
{
Array.Sort(a, (x, y) => x.Second.CompareTo(y.Second));
m = new AmoebaState();
for (var i = 0; i < Dimension; i++) m.Add(a[i].First);
m.Multiply(1.0 / Dimension);
}
void PartialSort(int i, int j) { if (a[i].Second > a[j].Second) a.Swap(i, j); }
void Accept(AmoebaState point, double value)
{
var tmp = Func.FirstBinary(0, Dimension, x => a[x].Second >= value);
if (tmp != Dimension) m.Add((point - a[Dimension - 1].First) / Dimension);
for (var i = Dimension; i > tmp; i--) a[i] = a[i - 1];
a[tmp].First = point;
a[tmp].Second = value;
}
public void Search()
{
var r = m + Alpha * (m - a[Dimension].First);
var fr = r.Func();
if (a[0].Second <= fr && fr < a[Dimension - 1].Second) { Accept(r, fr); return; }
var diff = r - m;
if (fr < a[0].Second)
{
var e = m + Beta * diff;
var fe = e.Func();
if (fe < fr) Accept(e, fe);
else Accept(r, fr);
}
else
{
var tmp = Gamma * diff;
var o = m + tmp;
var fo = o.Func();
var i = m - tmp;
var fi = i.Func();
if (fi < fo) { o = i; fo = fi; }
if (fo < a[Dimension - 1].Second) Accept(o, fo);
else Shrink();
}
}
void Shrink()
{
var tmp = (1 - Delta) * a[0].First;
for (var i = 1; i <= Dimension; i++) { a[i].First.Multiply(Delta); a[i].First.Add(tmp); a[i].Second = a[i].First.Func(); }
Initiate();
}
}
class AmoebaState
{
public static int Dimension = 2;
public double[] vec;
public AmoebaState() { vec = new double[Dimension]; }
public AmoebaState(params double[] elements) : this() { elements.CopyTo(vec, 0); }
public double this[int n] { get { return vec[n]; } set { vec[n] = value; } }
public void Multiply(double r) { for (var i = 0; i < Dimension; i++) vec[i] *= r; }
public void Add(AmoebaState v) { for (var i = 0; i < Dimension; i++) vec[i] += v.vec[i]; }
public static AmoebaState operator +(AmoebaState p) => new AmoebaState(p.vec);
public static AmoebaState operator -(AmoebaState p) { var tmp = new AmoebaState(p.vec); tmp.Multiply(-1); return tmp; }
public static AmoebaState operator /(AmoebaState p, double r) { var tmp = new AmoebaState(p.vec); tmp.Multiply(1 / r); return tmp; }
public static AmoebaState operator *(double r, AmoebaState p) { var tmp = new AmoebaState(p.vec); tmp.Multiply(r); return tmp; }
public static AmoebaState operator *(AmoebaState p, double r) => r * p;
public static AmoebaState operator +(AmoebaState p, AmoebaState q) { var tmp = +p; tmp.Add(q); return tmp; }
public static AmoebaState operator -(AmoebaState p, AmoebaState q) { var tmp = -q; tmp.Add(p); return tmp; }
public double Func()
{
return 0;//P.Func(vec[0], vec[1]);
}
public static Problem P;
}
class BucketList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable
{
public Comparison<T> Comp { get; protected set; }
public int BucketSize = 20;
public int Count { get { var sum = 0; var bucket = Head; while (bucket != null) { sum += bucket.Count; bucket = bucket.Next; } return sum; } }
public int NumOfBucket { get; protected set; }
public Bucket<T> Head { get; protected set; }
public Bucket<T> Tail { get; protected set; }
public BucketList(IComparer<T> comp) : this(comp.ToComparison()) { }
public BucketList(Comparison<T> comp = null) { Head = null; Tail = null; NumOfBucket = 0; Comp = comp ?? Func.DefaultComparison<T>(); }
protected void AddAfter(Bucket<T> pos, Bucket<T> bucket)
{
Debug.Assert(bucket != null && bucket.Count > 0 && pos != null && pos.Parent == this && Comp(pos.Tail.Value, bucket.Head.Value) <= 0
&& (pos.Next == null || Comp(pos.Next.Head.Value, bucket.Tail.Value) >= 0));
bucket.Parent = this;
bucket.Prev = pos;
bucket.Next = pos.Next;
if (pos != Tail) pos.Next.Prev = bucket;
else Tail = bucket;
pos.Next = bucket;
NumOfBucket++;
}
protected void AddBefore(Bucket<T> pos, Bucket<T> bucket)
{
Debug.Assert(bucket != null && bucket.Count > 0 && pos != null && pos.Parent == this && Comp(pos.Head.Value, bucket.Tail.Value) >= 0
&& (pos.Prev == null || Comp(pos.Prev.Tail.Value, bucket.Head.Value) <= 0));
bucket.Parent = this;
bucket.Prev = pos.Prev;
bucket.Next = pos;
if (pos != Head) pos.Prev.Next = bucket;
else Head = bucket;
pos.Prev = bucket;
NumOfBucket++;
}
protected void AddAfter(Bucket<T> bucket, BucketNode<T> node)
{
Debug.Assert(node != null && bucket != null && bucket.Parent == this && node.Parent.Parent == this && Comp(bucket.Tail.Value, node.Value) <= 0
&& (bucket.Next == null || Comp(bucket.Next.Head.Value, node.Value) >= 0));
var tmp = new Bucket<T>(this, bucket, bucket.Next);
tmp.InitiateWith(node);
if (bucket != Tail) bucket.Next.Prev = tmp;
else Tail = tmp;
bucket.Next = tmp;
NumOfBucket++;
}
protected void AddBefore(Bucket<T> bucket, BucketNode<T> node)
{
Debug.Assert(node != null && bucket != null && bucket.Parent == this && node.Parent.Parent == this && Comp(bucket.Head.Value, node.Value) >= 0
&& (bucket.Prev == null || Comp(bucket.Prev.Tail.Value, node.Value) <= 0));
var tmp = new Bucket<T>(this, bucket.Prev, bucket);
tmp.InitiateWith(node);
if (bucket != Head) bucket.Prev.Next = tmp;
else Head = tmp;
bucket.Prev = tmp;
NumOfBucket++;
}
public void AddAfter(BucketNode<T> node, T item)
{
Debug.Assert(node != null && node.Parent.Parent == this && Comp(node.Value, item) <= 0
&& ((node.Next == null && (node.Parent.Next == null || Comp(node.Parent.Next.Head.Value, item) >= 0))
|| Comp(node.Next.Value, item) >= 0));
var bucket = node.Parent;
var tmp = new BucketNode<T>(item, bucket, node, node.Next);
if (!bucket.AddAfter(node, tmp))
{
if (node.Next == null && (bucket.Next == null || bucket.Next.Count >= BucketSize)) AddAfter(bucket, tmp);
else if (node.Next == null) AddBefore(bucket.Next.Head, item);
else
{
node.Next.Prev = tmp;
node.Next = tmp;
while (node.Next.Next != null) node = node.Next;
item = node.Next.Value;
bucket.Tail = node;
node.Next = null;
AddAfter(node, item);
}
}
}
public void AddBefore(BucketNode<T> node, T item)
{
Debug.Assert(node != null && node.Parent.Parent == this && Comp(node.Value, item) >= 0
&& ((node.Prev == null && (node.Parent.Prev == null || Comp(node.Parent.Prev.Tail.Value, item) <= 0))
|| Comp(node.Prev.Value, item) <= 0));
var bucket = node.Parent;
var tmp = new BucketNode<T>(item, bucket, node.Prev, node);
if (!bucket.AddBefore(node, tmp))
{
if (node.Prev == null && (bucket.Prev == null || bucket.Prev.Count >= BucketSize)) AddBefore(bucket, tmp);
else if (node.Prev == null) AddAfter(bucket.Prev.Tail, item);
else
{
node.Prev.Next = tmp;
node.Prev = tmp;
while (node.Prev.Prev != null) node = node.Prev;
item = node.Prev.Value;
bucket.Head = node;
node.Prev = null;
AddBefore(node, item);
}
}
}
// (node, index)
// index is the position of node in node.Parent
public Tuple<BucketNode<T>, int> UpperBound(Predicate<T> pred)
{
if (NumOfBucket == 0) return null;
if (pred(Tail.Tail.Value)) return new Tuple<BucketNode<T>, int>(Tail.Tail, Tail.Count - 1);
var bucket = Tail;
while (bucket.Prev != null && !pred(bucket.Prev.Tail.Value)) bucket = bucket.Prev;
var node = bucket.Tail;
var index = bucket.Count - 1;
while (node.Prev != null && !pred(node.Prev.Value)) { node = node.Prev; index--; }
if (node.Prev == null) return bucket.Prev == null ? null : new Tuple<BucketNode<T>, int>(bucket.Prev.Tail, bucket.Prev.Count - 1);
else return new Tuple<BucketNode<T>, int>(node.Prev, index - 1);
}
public Tuple<BucketNode<T>, int> UpperBound(T item) => LowerBound(x => Comp(x, item) <= 0);
// (node, index)
// index is the position of node in node.Parent
public Tuple<BucketNode<T>, int> LowerBound(Predicate<T> pred)
{
if (NumOfBucket == 0) return null;
if (pred(Head.Head.Value)) return new Tuple<BucketNode<T>, int>(Head.Head, 0);
var bucket = Head;
while (bucket.Next != null && !pred(bucket.Next.Head.Value)) bucket = bucket.Next;
var node = bucket.Head;
var index = 0;
while (node.Next != null && !pred(node.Next.Value)) { node = node.Next; index++; }
if (node.Next == null) return bucket.Next == null ? null : new Tuple<BucketNode<T>, int>(bucket.Next.Head, 0);
else return new Tuple<BucketNode<T>, int>(node.Next, index + 1);
}
public Tuple<BucketNode<T>, int> LowerBound(T item) => LowerBound(x => Comp(x, item) >= 0);
public void InitiateWith(Bucket<T> bucket)
{
Debug.Assert(bucket != null && bucket.Count > 0);
RemoveAll();
Head = Tail = bucket;
bucket.Parent = this;
NumOfBucket++;
}
public void InitiateWith(T item)
{
RemoveAll();
Head = Tail = new Bucket<T>(this, null, null);
Head.Head = Head.Tail = new BucketNode<T>(item, Head, null, null);
Head.Count++;
NumOfBucket++;
}
public void AddFirst(Bucket<T> bucket) { if (NumOfBucket == 0) InitiateWith(bucket); else AddBefore(Head, bucket); }
public void AddLast(Bucket<T> bucket) { if (NumOfBucket == 0) InitiateWith(bucket); else AddAfter(Tail, bucket); }
public void AddFirst(T item) { if (NumOfBucket == 0) InitiateWith(item); else AddBefore(Head.Head, item); }
public void AddLast(T item) { if (NumOfBucket == 0) InitiateWith(item); else AddAfter(Tail.Tail, item); }
public void Clear() => RemoveAll();
public void RemoveAll() { Head = Tail = null; NumOfBucket = 0; }
public void RemoveFirst() { if (NumOfBucket == 0) throw new InvalidOperationException(); else Remove(Head.Head); }
public void RemoveLast() { if (NumOfBucket == 0) throw new InvalidOperationException(); else Remove(Tail.Tail); }
// remove item and return whether item was removed or not
public bool Remove(T item) { var node = Find(item); if (node != null) Remove(node); return node != null; }
public void Remove(Bucket<T> bucket)
{
Debug.Assert(bucket != null && bucket.Parent == this);
NumOfBucket--;
if (bucket == Head && bucket == Tail) { Head = Tail = null; }
else if (bucket == Head) { Head.Next.Prev = null; Head = Head.Next; }
else if (bucket == Tail) { Tail.Prev.Next = null; Tail = Tail.Prev; }
else { bucket.Prev.Next = bucket.Next; bucket.Next.Prev = bucket.Prev; }
}
public void Remove(BucketNode<T> node) { Debug.Assert(node != null && node.Parent.Parent == this); if (!node.Parent.Remove(node)) Remove(node.Parent); }
protected void RemoveRange(Bucket<T> from, Bucket<T> to, int indexFrom = -1, int indexTo = -1)
{
Debug.Assert(from != null && to != null && from.Parent == this && to.Parent == this);
if (indexFrom < 0) indexFrom = from.Index;
if (indexTo < 0) indexTo = to.Index;
if (indexFrom == 0 && indexTo == NumOfBucket - 1) { Clear(); return; }
else if (indexFrom == 0) { Head = to.Next; Head.Prev = null; }
else if (indexTo == NumOfBucket - 1) { Tail = from.Prev; Tail.Next = null; }
else { from.Prev.Next = to.Next; to.Next.Prev = from.Prev; }
NumOfBucket -= indexTo - indexFrom + 1;
}
public void RemoveRange(BucketNode<T> from, BucketNode<T> to, int indexFrom = -1, int indexTo = -1)
{
Debug.Assert(from != null && to != null && from.Parent.Parent == this && to.Parent.Parent == this);
if (indexFrom < 0) indexFrom = from.Index;
if (indexTo < 0) indexTo = to.Index;
var bucketFrom = from.Parent;
var bucketTo = to.Parent;
if (bucketFrom == bucketTo)
{
var bucket = bucketFrom;
if (indexFrom == 0 && indexTo == bucket.Count - 1) Remove(bucket);
else bucket.RemoveRange(from, to, indexFrom, indexTo);
}
else
{
var bf = bucketFrom.Index;
var bt = bucketTo.Index;
Debug.Assert(bf < bt);
if (bt > bf + 1) RemoveRange(bucketFrom.Next, bucketTo.Prev, bf + 1, bt - 1);
if (indexFrom == 0) { Remove(bucketFrom); RemoveRange(bucketTo.Head, to, 0, indexTo); }
else if (indexTo == bucketTo.Count - 1) { Remove(bucketTo); RemoveRange(from, bucketFrom.Tail, indexFrom, bucketFrom.Count - 1); }
else
{
bucketFrom.RemoveRange(from, bucketFrom.Tail, indexFrom, bucketFrom.Count - 1);
bucketTo.RemoveRange(bucketTo.Head, to, 0, indexTo);
if (bucketFrom.Count + bucketTo.Count < BucketSize) Adjust();
}
}
}
public void Adjust()
{
var array = this.ToArray();
Clear();
var length = array.Length;
BucketSize = (int)Math.Sqrt(length + 1);
var count = (length + BucketSize - 1) / BucketSize;
for (var i = 0; i < count; i++)
{
var bucket = new Bucket<T>(this, null, null);
var lim = Math.Min(BucketSize * (i + 1), length);
for (var j = BucketSize * i; j < lim; j++) bucket.AddLast(array[j]);
AddLast(bucket);
}
}
public BucketNode<T> Find(T item) { var node = LowerBound(item); if (node == null || Comp(node.Item1.Value, item) != 0) return null; else return node.Item1; }
public BucketNode<T> FindLast(T item) { var node = UpperBound(item); if (node == null || Comp(node.Item1.Value, item) != 0) return null; else return node.Item1; }
public IEnumerator<T> GetEnumerator()
{
var bucket = Head;
while (bucket != null)
{
var node = bucket.Head;
while (node != null) { yield return node.Value; node = node.Next; }
bucket = bucket.Next;
}
}
public void Add(T item) { var ub = LowerBound(item); if (ub != null) AddBefore(ub.Item1, item); else AddLast(item); }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void CopyTo(Array array, int index) { foreach (var item in this) array.SetValue(item, index++); }
public bool IsSynchronized => false;
public object SyncRoot => this;
public bool IsReadOnly => false;
public bool Contains(T item) => Find(item) != null;
public void CopyTo(T[] array, int index) { foreach (var item in this) array[index++] = item; }
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("<Start>\n");
var node = Head;
while (node != null) { sb.Append($"{node.ToString()}\n"); node = node.Next; }
sb.Append("<end>");
return sb.ToString();
}
public bool Check()
{
if (NumOfBucket == 0) return Head == null && Tail == null;
if (Head.Prev != null || Tail.Next != null) return false;
var bucket = Head;
var c = 1;
while (bucket.Next != null)
{
if (!CheckConnection(bucket) || !CheckBucket(bucket)) return false;
bucket = bucket.Next;
c++;
}
return bucket == Tail && CheckBucket(Tail) && c == NumOfBucket;
}
bool CheckConnection(Bucket<T> bucket)
{
if (bucket.Next == null) return bucket == Tail;
else return bucket.Next.Prev == bucket && Comp(bucket.Tail.Value, bucket.Next.Head.Value) <= 0;
}
bool CheckBucket(Bucket<T> bucket) => bucket.Count > 0 && bucket.Count <= BucketSize && bucket.Parent == this;
public void Start(Func<string, T> parser, Func<T> random)
{
BucketNode<T> x = null, y = null;
var help = true;
while (true)
{
Console.Clear();
Console.WriteLine($"{Count} items, {NumOfBucket} buckets(size : {BucketSize})");
Console.WriteLine(this);
Console.WriteLine(Check() ? "OK!" : "NG!");
if (help)
{
Console.WriteLine("when val is omitted, random value will be used.");
Console.WriteLine("a val : add val");
Console.WriteLine("r val : remove val");
Console.WriteLine("j : adjust");
Console.WriteLine("c : clear");
Console.WriteLine("h : disable/enable help message");
Console.WriteLine("x : set x");
Console.WriteLine("x h : set x to head");
Console.WriteLine("x t : set x to tail");
Console.WriteLine("x n : set x to x.next");
Console.WriteLine("x p : set x to x.prev");
Console.WriteLine("x f val : set x to lower bound of val");
Console.WriteLine("y : set y");
Console.WriteLine("x : exchange x and y");
Console.WriteLine("d : remove from x to y");
Console.WriteLine("q : quit");
}
if (x != null) Console.WriteLine($"x = {x.Value} <- {x.Parent}");
if (y != null) Console.WriteLine($"y = {y.Value} <- {y.Parent}");
Console.Write("enter command > ");
var command = Console.ReadLine().Split();
if (command[0].Length > 1 && command[0][1] == 'd')
Console.WriteLine("debug...");
if (command[0].StartsWith("a")) { if (command.Length > 1) Add(parser(command[1])); else Add(random()); }
else if (command[0].StartsWith("r")) { if (command.Length > 1) Remove(parser(command[1])); else Remove(random()); }
else if (command[0].StartsWith("c")) Clear();
else if (command[0].StartsWith("j")) Adjust();
else if (command[0].StartsWith("h")) help = !help;
else if (command[0].StartsWith("x")) SetVariable(command, ref x, parser, random);
else if (command[0].StartsWith("y")) SetVariable(command, ref y, parser, random);
else if (command[0].StartsWith("e")) { var tmp = x; x = y; y = tmp; }
else if (command[0].StartsWith("d")) { RemoveRange(x, y, x.Index, y.Index); x = null; y = null; }
else if (command[0].StartsWith("q")) break;
}
}
void SetVariable(string[] command, ref BucketNode<T> x, Func<string, T> parser, Func<T> random)
{
if (command[1].StartsWith("h")) x = Head.Head;
else if (command[1].StartsWith("t")) x = Tail.Tail;
else if (command[1].StartsWith("n"))
{
if (x.Next != null) x = x.Next;
else if (x.Parent.Next != null) x = x.Parent.Next.Head;
else { Console.WriteLine("x is the last element..."); Console.ReadKey(true); }
}
else if (command[1].StartsWith("p"))
{
if (x.Prev != null) x = x.Prev;
else if (x.Parent.Prev != null) x = x.Parent.Prev.Tail;
else { Console.WriteLine("x is the first element..."); Console.ReadKey(true); }
}
else if (command[1].StartsWith("f")) { if (command.Length > 2) x = LowerBound(parser(command[2])).Item1; else x = LowerBound(random()).Item1; }
}
}
// bucket cannot be empty
class Bucket<T>
{
public BucketList<T> Parent;
public int Count;
public Bucket<T> Prev;
public Bucket<T> Next;
public BucketNode<T> Head;
public BucketNode<T> Tail;
public Bucket(BucketList<T> parent, Bucket<T> prev, Bucket<T> next) { Parent = parent; Prev = prev; Next = next; Head = null; Tail = null; }
public int Index
{
get
{
var count = 0;
var node = Parent.Head;
while (node != this) { node = node.Next; count++; }
return count;
}
}
public bool AddAfter(BucketNode<T> node, BucketNode<T> item) => AddAfter(node, item.Value);
public bool AddBefore(BucketNode<T> node, BucketNode<T> item) => AddBefore(node, item.Value);
public bool AddAfter(BucketNode<T> node, T item)
{
Debug.Assert(node != null && node.Parent == this && Parent.Comp(node.Value, item) <= 0
&& ((node.Next == null && (Next == null || Parent.Comp(Next.Head.Value, item) >= 0))
|| Parent.Comp(node.Next.Value, item) >= 0));
if (Count < Parent.BucketSize)
{
var tmp = new BucketNode<T>(item, this, node, node.Next);
if (node.Next != null) node.Next.Prev = tmp;
else Tail = tmp;
node.Next = tmp;
Count++;
return true;
}
return false;
}
public bool AddBefore(BucketNode<T> node, T item)
{
Debug.Assert(node != null && node.Parent == this && Parent.Comp(node.Value, item) >= 0
&& ((node.Prev == null && (Prev == null || Parent.Comp(Prev.Tail.Value, item) <= 0))
|| Parent.Comp(node.Prev.Value, item) <= 0));
if (Count < Parent.BucketSize)
{
var tmp = new BucketNode<T>(item, this, node.Prev, node);
if (node.Prev != null) node.Prev.Next = tmp;
else Head = tmp;
node.Prev = tmp;
Count++;
return true;
}
else return false;
}
public bool InitiateWith(BucketNode<T> node)
{
Head = Tail = node;
node.Parent = this;
node.Prev = node.Next = null;
Count++;
return true;
}
public bool InitiateWith(T item) => InitiateWith(new BucketNode<T>(item, this, null, null));
public void RemoveAll() { Head = Tail = null; Count = 0; }
public bool AddFirst(T item) { if (Count == 0) return InitiateWith(item); else return AddBefore(Head, item); }
public bool AddLast(T item) { if (Count == 0) return InitiateWith(item); else return AddAfter(Tail, item); }
public bool Remove(BucketNode<T> node)
{
Debug.Assert(node != null && node.Parent == this);
if (Count > 1)
{
Count--;
if (node == Head) { Head.Next.Prev = null; Head = Head.Next; }
else if (node == Tail) { Tail.Prev.Next = null; Tail = Tail.Prev; }
else { node.Prev.Next = node.Next; node.Next.Prev = node.Prev; }
return true;
}
else return false;
}
public bool RemoveRange(BucketNode<T> from, BucketNode<T> to, int indexFrom = -1, int indexTo = -1)
{
Debug.Assert(from != null && to != null && from.Parent == this && to.Parent == this);
if (indexFrom < 0) indexFrom = from.Index;
if (indexTo < 0) indexTo = to.Index;
if (indexTo == 0 && indexFrom == Count - 1) return false;
else if (indexFrom == 0) { Head = to.Next; Head.Prev = null; }
else if (indexTo == Count - 1) { Tail = from.Prev; Tail.Next = null; }
else { from.Prev.Next = to.Next; to.Next.Prev = from.Prev; }
Count -= indexTo - indexFrom + 1;
return true;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("[");
var node = Head;
while (node != null) { sb.Append($"{node.ToString()}, "); node = node.Next; }
if (sb.Length > 1) sb.Remove(sb.Length - 2, 2);
sb.Append("]");
return sb.ToString();
}
public bool Check()
{
if (Count == 0) return Head == null && Tail == null;
if (Head.Prev != null || Tail.Next != null) return false;
var node = Head;
var c = 1;
while (node.Next != null)
{
if (!CheckConnection(node) || !CheckNode(node)) return false;
node = node.Next;
c++;
}
return node == Tail && CheckNode(Tail) && c == Count;
}
bool CheckConnection(BucketNode<T> node)
{
if (node.Next == null) return node == Tail;
else return node.Next.Prev == node && Parent.Comp(node.Value, node.Next.Value) <= 0;
}
bool CheckNode(BucketNode<T> node) => node.Parent == this;
}
class BucketNode<T>
{
public T Value;
public Bucket<T> Parent;
public BucketNode<T> Prev;
public BucketNode<T> Next;
public BucketNode(T item, Bucket<T> parent, BucketNode<T> prev, BucketNode<T> next) { Value = item; Parent = parent; Prev = prev; Next = next; }
public int Index
{
get
{
var count = 0;
var node = Parent.Head;
while (node != this) { node = node.Next; count++; }
return count;
}
}
public override string ToString() => Value.ToString();
}
class UndirectedGraph<V, E> : DirectedGraph<V, E>
{
public UndirectedGraph(int V) : base(V) { }
public UndirectedGraph(int V, IEnumerable<EdgeInfo<E>> edges) : base(V, edges) { }
public override void AddEdge(EdgeInfo<E> edge)
{
edges.Add(edge);
edges.Add(edge.Reverse());
edgesFrom[edge.From].Add(new HalfEdgeInfo<E>(edge.To, edge.Information));
edgesFrom[edge.To].Add(new HalfEdgeInfo<E>(edge.From, edge.Information));
edgesTo[edge.To].Add(new HalfEdgeInfo<E>(edge.From, edge.Information));
edgesTo[edge.From].Add(new HalfEdgeInfo<E>(edge.To, edge.Information));
}
public bool IsConnected
{
get
{
if (numberOfNodes == 0) return true;
var used = new bool[numberOfNodes];
var queue = new Queue<int>();
queue.Enqueue(0);
while (queue.Count > 0)
{
var v = queue.Dequeue();
if (used[v]) continue;
used[v] = true;
foreach (var e in EdgesFrom(v)) queue.Enqueue(e.End);
}
return used.All(x => x);
}
}
public bool IsTree
{
get
{
if (numberOfNodes == 0) return true;
var used = new bool[numberOfNodes];
var queue = new Queue<int>();
queue.Enqueue(0);
while (queue.Count > 0)
{
var v = queue.Dequeue();
if (used[v]) return false;
used[v] = true;
foreach (var e in EdgesFrom(v)) queue.Enqueue(e.End);
}
return used.All(x => x);
}
}
public UndirectedGraph<V, E> MinimumSpanningTreePrim(int start, Func<E, int> cost)
{
var graph = new UndirectedGraph<V, E>(numberOfNodes);
nodes.CopyTo(graph.nodes, 0);
var d = Enumerable.Repeat(Func.Inf, numberOfNodes).ToArray();
var used = new bool[numberOfNodes];
var queue = new PriorityQueue<Pair<EdgeInfo<E>, int>>((x, y) => x.Second.CompareTo(y.Second), numberOfNodes);
d[start] = 0;
queue.Enqueue(new Pair<EdgeInfo<E>, int>(new EdgeInfo<E>(-1, 0, default(E)), 0));
while (queue.Count > 0)
{
var p = queue.Dequeue();
var v = p.First.To;
if (d[v] < p.Second) continue;
used[v] = true;
if (p.First.From >= 0) graph.AddEdge(v, p.First.From, p.First.Information);
foreach (var w in EdgesFrom(v))
{
if (!used[w.End] && cost(w.Information) < d[w.End])
{
d[w.End] = cost(w.Information);
queue.Enqueue(new Pair<EdgeInfo<E>, int>(new EdgeInfo<E>(v, w.End, w.Information), cost(w.Information)));
}
}
}
return graph;
}
public UndirectedGraph<V, E> MinimumSpanningTreeKruskal(Func<E, int> cost)
{
var graph = new UndirectedGraph<V, E>(numberOfNodes);
nodes.CopyTo(graph.nodes, 0);
var tree = new UnionFindTree(numberOfNodes);
edges.Sort((x, y) => cost(x.Information).CompareTo(cost(y.Information)));
foreach (var e in edges)
{
if (!tree.IsSameCategory(e.From, e.To))
{
tree.UniteCategory(e.From, e.To);
graph.AddEdge(e);
}
}
return graph;
}
public bool IsBipartite
{
get
{
var color = new int[numberOfNodes];
foreach (var v in nodes)
{
if (color[v.Code] == 0)
{
var queue = new Queue<Pair<int, int>>();
queue.Enqueue(new Pair<int, int>(v.Code, 1));
while (queue.Count > 0)
{
var w = queue.Dequeue();
if (color[w.First] != 0)
{
if (color[w.First] != w.Second) return false;
continue;
}
color[w.First] = w.Second;
foreach (var e in EdgesFrom(w.First)) queue.Enqueue(new Pair<int, int>(e.End, -w.Second));
}
}
}
return true;
}
}
public IEnumerable<NodeInfo<V>> GetArticulationPoints()
{
var visited = new bool[numberOfNodes];
var parent = new int[numberOfNodes];
var children = Enumerable.Range(0, numberOfNodes).Select(_ => new SortedSet<int>()).ToArray();
var order = new int[numberOfNodes];
var lowest = new int[numberOfNodes];
var isroot = new bool[numberOfNodes];
var count = 1;
var isarticulation = new bool[numberOfNodes];
Action<int, int> dfs = null;
dfs = (u, prev) =>
{
order[u] = count;
lowest[u] = count;
count++;
visited[u] = true;
foreach (var e in edgesFrom[u])
{
var v = e.End;
if (visited[v]) { if (v != prev) lowest[u] = Math.Min(lowest[u], order[v]); }
else
{
parent[v] = u;
if (isroot[u]) children[u].Add(v);
dfs(v, u);
lowest[u] = Math.Min(lowest[u], lowest[v]);
if (order[u] <= lowest[v]) isarticulation[u] = true;
}
}
};
for (var v = 0; v < numberOfNodes; v++)
{
if (visited[v]) continue;
count = 1; dfs(v, -1);
isroot[v] = true;
}
for (var v = 0; v < numberOfNodes; v++)
{
if (isroot[v]) { if (children[v].Count > 1) yield return nodes[v]; }
else { if (isarticulation[v]) yield return nodes[v]; }
}
}
public string ToString(Func<NodeInfo<V>, string> vertex, Func<EdgeInfo<E>, string> edge)
{
var sb = new StringBuilder();
sb.Append("graph G {\n");
foreach (var v in nodes) sb.Append($"\tv{v.Code} [label = \"{vertex(v)}\"];\n");
foreach (var e in edges) sb.Append($"\tv{e.From} -- v{e.To} [label=\"{edge(e)}\"];\n");
sb.Append("}");
return sb.ToString();
}
public override string ToString() => ToString(v => v.ToString(), e => e.ToString());
}
class NodeInfo<V> : Pair<int, V>
{
public int Code { get { return First; } set { First = value; } }
public V Information { get { return Second; } set { Second = value; } }
public NodeInfo() : base() { }
public NodeInfo(int code, V info) : base(code, info) { }
}
class HalfEdgeInfo<E> : Pair<int, E>
{
public int End { get { return First; } set { First = value; } }
public E Information { get { return Second; } set { Second = value; } }
public HalfEdgeInfo() : base() { }
public HalfEdgeInfo(int end, E info) : base(end, info) { }
}
class EdgeInfo<E> : Pair<Pair<int, int>, E>
{
public int From { get { return First.First; } set { First.First = value; } }
public int To { get { return First.Second; } set { First.Second = value; } }
public E Information { get { return Second; } set { Second = value; } }
public EdgeInfo() : base() { }
public EdgeInfo(int from, int to, E info) : base(new Pair<int, int>(from, to), info) { }
public EdgeInfo<E> Reverse() => new EdgeInfo<E>(To, From, Information);
}
class DirectedGraph<V, E> : IEnumerable<NodeInfo<V>>
{
protected int numberOfNodes;
public int NumberOfNodes => numberOfNodes;
protected NodeInfo<V>[] nodes;
protected List<EdgeInfo<E>> edges;
protected List<HalfEdgeInfo<E>>[] edgesFrom;
protected List<HalfEdgeInfo<E>>[] edgesTo;
public IEnumerable<HalfEdgeInfo<E>> EdgesFrom(int node) => edgesFrom[node];
public int InDegree(int node) => edgesTo[node].Count;
public int OutDegree(int node) => edgesFrom[node].Count;
public IEnumerable<HalfEdgeInfo<E>> EdgesTo(int node) => edgesTo[node];
public V this[int node] { get { return nodes[node].Second; } set { nodes[node].Second = value; } }
public IEnumerable<EdgeInfo<E>> Edges => edges;
public DirectedGraph(int V)
{
numberOfNodes = V;
nodes = Enumerable.Range(0, V).Select(x => new NodeInfo<V>(x, default(V))).ToArray();
edges = new List<EdgeInfo<E>>();
edgesFrom = Enumerable.Range(0, V).Select(_ => new List<HalfEdgeInfo<E>>()).ToArray();
edgesTo = Enumerable.Range(0, V).Select(_ => new List<HalfEdgeInfo<E>>()).ToArray();
}
public DirectedGraph(int V, IEnumerable<EdgeInfo<E>> edges) : this(V) { foreach (var e in edges) AddEdge(e.From, e.To, e.Information); }
public virtual void AddEdge(EdgeInfo<E> edge)
{
edges.Add(edge);
edgesFrom[edge.From].Add(new HalfEdgeInfo<E>(edge.To, edge.Information));
edgesTo[edge.To].Add(new HalfEdgeInfo<E>(edge.From, edge.Information));
}
public void AddEdge(int from, int to, E information) => AddEdge(new EdgeInfo<E>(from, to, information));
public void AddEdge(V from, V to, E information) => AddEdge(new EdgeInfo<E>(SearchNode(from).Code, SearchNode(to).Code, information));
public NodeInfo<V> SearchNode(V node) => nodes.FirstOrDefault(e => e.Information.Equals(node));
public EdgeInfo<E> SearchEdge(E edge) => edges.Find(e => e.Information.Equals(edge));
public IEnumerator<NodeInfo<V>> GetEnumerator() { foreach (var v in nodes) yield return v; }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public int[] ShortestPathLengthFrom(int from, Func<E, int> cost)
{
var d = Enumerable.Repeat(Func.Inf, numberOfNodes).ToArray();
d[from] = 0;
var update = true;
while (update)
{
update = false;
foreach (var e in edges)
{
var tmp = d[e.From] + cost(e.Information);
if (d[e.From] < Func.Inf && d[e.To] > tmp)
{
d[e.To] = tmp;
update = true;
}
}
}
return d;
}
public int[] DijkstraFrom(int from, Func<E, int> cost)
{
var d = Enumerable.Repeat(Func.Inf, numberOfNodes).ToArray();
var queue = new PriorityQueue<Pair<int, int>>((x, y) => x.Second.CompareTo(y.Second));
d[from] = 0;
queue.Enqueue(new Pair<int, int>(from, 0));
while (!queue.IsEmpty)
{
var p = queue.Dequeue();
var v = p.First;
if (d[v] < p.Second) continue;
foreach (var e in EdgesFrom(v))
{
var tmp = d[v] + cost(e.Information);
if (d[e.End] > tmp) queue.Enqueue(new Pair<int, int>(e.End, d[e.End] = tmp));
}
}
return d;
}
// cost(e)>=0
public Pair<long, int>[] DijkstraFromL(int from, Func<E, long> cost)
{
var d = new Pair<long, int>[numberOfNodes];
for (var i = 0; i < numberOfNodes; i++) d[i] = new Pair<long, int>(Func.InfL, -1);
var queue = new PriorityQueue<Tuple<int, long, int>>((x, y) => x.Item2.CompareTo(y.Item2));
d[from] = new Pair<long, int>(0, -1);
queue.Enqueue(new Tuple<int, long, int>(from, 0, -1));
while (!queue.IsEmpty)
{
var p = queue.Dequeue();
var v = p.Item1;
if (d[v].First < p.Item2) continue;
foreach (var e in edgesFrom[v])
{
var tmp = d[v].First + cost(e.Information);
if (d[e.End].First > tmp) queue.Enqueue(new Tuple<int, long, int>(e.End, d[e.End].First = tmp, d[e.End].Second = v));
}
}
return d;
}
public int[,] ShortestPathLengthEachOther(Func<E, int> cost)
{
var d = new int[numberOfNodes, numberOfNodes];
for (var v = 0; v < numberOfNodes; v++) for (var w = 0; w < numberOfNodes; w++) d[v, w] = Func.Inf;
for (var v = 0; v < numberOfNodes; v++) d[v, v] = 0;
foreach (var e in edges) if (e.From != e.To) d[e.From, e.To] = cost(e.Information);
for (var k = 0; k < numberOfNodes; k++)
for (var v = 0; v < numberOfNodes; v++)
for (var w = 0; w < numberOfNodes; w++)
d[v, w] = Math.Min(d[v, w], d[v, k] + d[k, w]);
return d;
}
public bool ContainsNegativeLoopWF(Func<E, int> cost)
{
var d = ShortestPathLengthEachOther(cost);
for (var v = 0; v < numberOfNodes; v++) if (d[v, v] < 0) return true;
return false;
}
public bool ContainsNegativeLoop(Func<E, int> cost)
{
var d = Enumerable.Repeat(0, numberOfNodes).ToArray();
for (var v = 0; v < numberOfNodes; v++)
{
foreach (var e in edges)
{
var tmp = d[e.From] + cost(e.Information);
if (d[e.To] > tmp)
{
d[e.To] = tmp;
if (v == numberOfNodes - 1) return true;
}
}
}
return false;
}
public IEnumerable<int> ReachableFrom(int from)
{
var used = new bool[numberOfNodes];
var queue = new Queue<int>();
queue.Enqueue(from);
while (queue.Count > 0)
{
var v = queue.Dequeue();
if (used[v]) continue;
used[v] = true;
foreach (var e in EdgesFrom(v)) queue.Enqueue(e.End);
}
for (var v = 0; v < numberOfNodes; v++) if (used[v]) yield return v;
}
public bool IsReachable(int from, int to)
{
var used = new bool[numberOfNodes];
var queue = new Queue<int>();
queue.Enqueue(from);
while (queue.Count > 0)
{
var v = queue.Dequeue();
if (v == to) return true;
if (used[v]) continue;
used[v] = true;
foreach (var e in EdgesFrom(v)) queue.Enqueue(e.End);
}
return false;
}
public Pair<DirectedGraph<HashSet<NodeInfo<V>>, object>, int[]> StronglyConnectedComponents()
{
var mark = new bool[numberOfNodes];
var stack = new Stack<int>();
Action<int> dfs = null;
dfs = v =>
{
mark[v] = true;
foreach (var w in edgesFrom[v]) if (!mark[w.End]) dfs(w.End);
stack.Push(v);
};
for (var v = 0; v < numberOfNodes; v++) if (!mark[v]) dfs(v);
var scc = new List<HashSet<NodeInfo<V>>>();
mark = new bool[numberOfNodes];
var which = new int[numberOfNodes];
Action<int, HashSet<NodeInfo<V>>> rdfs = null;
rdfs = (v, set) =>
{
set.Add(new NodeInfo<V>(v, nodes[v].Information));
mark[v] = true;
foreach (var w in edgesFrom[v]) if (!mark[w.End]) rdfs(w.End, set);
};
var M = 0;
while (stack.Count > 0)
{
var v = stack.Pop();
if (mark[v]) continue;
var set = new HashSet<NodeInfo<V>>();
rdfs(v, set);
scc.Add(set);
foreach (var w in set) which[w.Code] = M;
M++;
}
var graph = new UndirectedGraph<HashSet<NodeInfo<V>>, object>(M);
for (var v = 0; v < M; v++) graph[v] = scc[v];
foreach (var e in edges) if (which[e.From] != which[e.To]) graph.AddEdge(which[e.From], which[e.To], null);
return new Pair<DirectedGraph<HashSet<NodeInfo<V>>, object>, int[]>(graph, which);
}
public string ToString(Func<V, string> vertex, Func<E, string> edge)
{
var sb = new StringBuilder();
sb.Append("digraph G {\n");
foreach (var v in nodes) sb.Append($"\tv{v.Code} [label = \"{vertex(v.Information)}\"];\n");
foreach (var e in edges) sb.Append($"\tv{e.From} -> v{e.To} [label=\"{edge(e.Information)}\"];\n");
sb.Append("}");
return sb.ToString();
}
public override string ToString() => ToString(v => v.ToString(), e => e.ToString());
}
class UnionFindTree
{
int N;
int[] parent, rank, size;
public UnionFindTree(int capacity)
{
N = capacity;
parent = new int[N];
rank = new int[N];
size = new int[N];
for (var i = 0; i < N; i++) { parent[i] = i; size[i] = 1; }
}
public int GetSize(int x) => size[GetRootOf(x)];
public int GetRootOf(int x) => parent[x] == x ? x : parent[x] = GetRootOf(parent[x]);
public bool UniteCategory(int x, int y)
{
if ((x = GetRootOf(x)) == (y = GetRootOf(y))) return false;
if (rank[x] < rank[y]) { parent[x] = y; size[y] += size[x]; }
else
{
parent[y] = x; size[x] += size[y];
if (rank[x] == rank[y]) rank[x]++;
}
return true;
}
public bool IsSameCategory(int x, int y) => GetRootOf(x) == GetRootOf(y);
}
class AVLTree<T> : IEnumerable<T>, ICollection<T>, ICollection, IEnumerable
{
public class AVLNode : IEnumerable<T>
{
AVLTree<T> tree;
int height;
public int Height => height;
public int Bias => Left.height - Right.height;
public T Item;
public AVLNode Parent;
public AVLNode Left;
public AVLNode Right;
AVLNode(T x, AVLTree<T> tree) { this.tree = tree; Item = x; Left = tree.sentinel; Right = tree.sentinel; }
public AVLNode(AVLTree<T> tree) : this(default(T), tree) { height = 0; Parent = null; }
public AVLNode(T x, AVLNode parent, AVLTree<T> tree) : this(x, tree) { height = 1; Parent = parent; }
public void Adjust() => height = 1 + Math.Max(Left.height, Right.height);
public void ResetAsSentinel() { height = 0; Left = tree.sentinel; Right = tree.sentinel; }
public IEnumerator<T> GetEnumerator()
{
if (this != tree.sentinel)
{
foreach (var x in Left) yield return x;
yield return Item;
foreach (var x in Right) yield return x;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
AVLNode sentinel;
Comparison<T> comp;
Func<T, T, bool> equals;
int count;
// assumed to be comparer
// i.e. comp(x,x)=0, and comp(x,y)>0 then comp(y,x)<0, and comp(x,y)>0 & comp(y,z)>0 then comp(x,z)>0
public AVLTree(Comparison<T> comp)
{
sentinel = new AVLNode(this);
sentinel.ResetAsSentinel();
this.comp = comp ?? Func.DefaultComparison<T>();
if (typeof(T).IsValueType) equals = (x, y) => x.Equals(y);
else equals = (x, y) => ReferenceEquals(x, y);
count = 0;
}
public AVLTree(IComparer<T> comp = null) : this(comp.ToComparison()) { }
void Replace(AVLNode u, AVLNode v)
{
var parent = u.Parent;
if (parent.Left == u) parent.Left = v;
else parent.Right = v;
v.Parent = parent;
}
AVLNode RotateL(AVLNode v)
{
var u = v.Right;
Replace(v, u);
v.Right = u.Left;
u.Left.Parent = v;
u.Left = v;
v.Parent = u;
v.Adjust();
u.Adjust();
return u;
}
AVLNode RotateR(AVLNode u)
{
var v = u.Left;
Replace(u, v);
u.Left = v.Right;
v.Right.Parent = u;
v.Right = u;
u.Parent = v;
u.Adjust();
v.Adjust();
return v;
}
AVLNode RotateLR(AVLNode t) { RotateL(t.Left); return RotateR(t); }
AVLNode RotateRL(AVLNode t) { RotateR(t.Right); return RotateL(t); }
void Adjust(bool isInsertMode, AVLNode node)
{
while (node.Parent != sentinel)
{
var parent = node.Parent;
var height = parent.Height;
if ((parent.Left == node) == isInsertMode)
if (parent.Bias == 2)
if (parent.Left.Bias >= 0) parent = RotateR(parent);
else parent = RotateLR(parent);
else parent.Adjust();
else
if (parent.Bias == -2)
if (parent.Right.Bias <= 0) parent = RotateL(parent);
else parent = RotateRL(parent);
else parent.Adjust();
if (height == parent.Height) break;
node = parent;
}
}
public void Add(T item)
{
var parent = sentinel;
var pos = sentinel.Left;
var isLeft = true;
count++;
while (pos != sentinel)
if (comp(item, pos.Item) < 0) { parent = pos; pos = pos.Left; isLeft = true; }
else { parent = pos; pos = pos.Right; isLeft = false; }
if (isLeft)
{
parent.Left = new AVLNode(item, parent, this);
Adjust(true, parent.Left);
}
else
{
parent.Right = new AVLNode(item, parent, this);
Adjust(true, parent.Right);
}
}
// if equals(x,y) holds then !(comp(x,y)<0) and !(comp(x,y)>0) must hold
// i.e. equals(x,y) -> comp(x,y)=0
public bool Remove(T item, AVLNode start)
{
var pos = start;
while (pos != sentinel)
{
if (comp(item, pos.Item) < 0) pos = pos.Left;
else if (comp(item, pos.Item) > 0) pos = pos.Right;
else if (equals(pos.Item, item))
{
if (pos.Left == sentinel)
{
Replace(pos, pos.Right);
Adjust(false, pos.Right);
}
else
{
var max = Max(pos.Left);
pos.Item = max.Item;
Replace(max, max.Left);
Adjust(false, max.Left);
}
count--;
return true;
}
else return Remove(item, pos.Left) || Remove(item, pos.Right);
}
return false;
}
public bool Remove(T item) => Remove(item, sentinel.Left);
AVLNode Max(AVLNode node)
{
while (node.Right != sentinel) node = node.Right;
return node;
}
AVLNode Min(AVLNode node)
{
while (node.Left != sentinel) node = node.Left;
return node;
}
public bool Contains(T item)
{
var pos = sentinel.Left;
while (pos != sentinel)
{
if (comp(item, pos.Item) < 0) pos = pos.Left;
else if (comp(item, pos.Item) > 0) pos = pos.Right;
else return true;
}
return false;
}
public T Find(T item)
{
var pos = sentinel.Left;
while (pos != sentinel)
{
if (comp(item, pos.Item) < 0) pos = pos.Left;
else if (comp(item, pos.Item) > 0) pos = pos.Right;
else return pos.Item;
}
return default(T);
}
public AVLNode LowerBound(Predicate<T> pred) { AVLNode node; LowerBound(pred, sentinel.Left, out node); return node; }
public AVLNode UpperBound(Predicate<T> pred) { AVLNode node; UpperBound(pred, sentinel.Left, out node); return node; }
public AVLNode LowerBound(T item) => LowerBound(x => comp(x, item) >= 0);
public AVLNode UpperBound(T item) => UpperBound(x => comp(x, item) <= 0);
bool UpperBound(Predicate<T> pred, AVLNode node, out AVLNode res)
{
if (node == sentinel) { res = null; return false; }
if (pred(node.Item)) { if (!UpperBound(pred, node.Right, out res)) res = node; return true; }
else return UpperBound(pred, node.Left, out res);
}
bool LowerBound(Predicate<T> pred, AVLNode node, out AVLNode res)
{
if (node == sentinel) { res = null; return false; }
if (pred(node.Item)) { if (!LowerBound(pred, node.Left, out res)) res = node; return true; }
else return LowerBound(pred, node.Right, out res);
}
public T Min() => Min(sentinel.Left).Item;
public AVLNode MinNode() => Min(sentinel.Left);
public T Max() => Max(sentinel.Left).Item;
public AVLNode MaxNode() => Max(sentinel.Left);
public bool IsEmpty => sentinel.Left == sentinel;
public void Clear() { sentinel.Left = sentinel; count = 0; sentinel.ResetAsSentinel(); }
public IEnumerator<T> GetEnumerator() => sentinel.Left.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void CopyTo(T[] array, int arrayIndex) { foreach (var x in this) array[arrayIndex++] = x; }
public int Count => count;
public bool IsReadOnly => true;
public void CopyTo(Array array, int index) { foreach (var x in this) array.SetValue(x, index++); }
public bool IsSynchronized => false;
public object SyncRoot => this;
public override string ToString()
{
var nodes = new StringBuilder();
var edges = new StringBuilder();
ConcatSubTree(nodes, edges, sentinel.Left, "L");
return $"digraph G {{\n{nodes.ToString()}{edges.ToString()}}}";
}
void ConcatSubTree(StringBuilder nodes, StringBuilder edges, AVLNode node, string code)
{
if (node == sentinel) return;
nodes.Append($"\tv{code} [label = \"{node.Height}:{node.Item}\"];\n");
if (node.Left != sentinel) edges.Append($"\tv{code} -> v{code}L;\n");
if (node.Right != sentinel) edges.Append($"\tv{code} -> v{code}R;\n");
ConcatSubTree(nodes, edges, node.Left, $"{code}L");
ConcatSubTree(nodes, edges, node.Right, $"{code}R");
}
public bool IsBalanced() => IsBalanced(sentinel.Left);
public bool IsValidBinarySearchTree() => IsValidBinarySearchTree(sentinel.Left);
bool IsBalanced(AVLNode node) => node == sentinel || (Math.Abs(node.Bias) < 2 && IsBalanced(node.Left) && IsBalanced(node.Right));
bool IsValidBinarySearchTree(AVLNode node)
=> node == sentinel || (Small(node.Item, node.Left) && Large(node.Item, node.Right)
&& IsValidBinarySearchTree(node.Left) && IsValidBinarySearchTree(node.Right));
bool Small(T item, AVLNode node) => node == sentinel || (comp(item, node.Item) >= 0 && Small(item, node.Left) && Small(item, node.Right));
bool Large(T item, AVLNode node) => node == sentinel || (comp(item, node.Item) <= 0 && Large(item, node.Left) && Large(item, node.Right));
public static void CheckAVL(Random rand, int N)
{
Comparison<double> comp = (x, y) => x.CompareTo(y);
var avl = new AVLTree<double>(comp);
var toBeLeft = new double[N];
var toBeRemoved = new double[N];
for (var i = 0; i < N; i++) avl.Add(toBeRemoved[i] = rand.NextDouble());
for (var i = 0; i < N; i++) avl.Add(toBeLeft[i] = rand.NextDouble());
for (var i = 0; i < N; i++) Console.Write(avl.Remove(toBeRemoved[i]) ? "" : "!!!NOT REMOVED!!! => " + toBeRemoved[i] + "\n");
var insertErrors = toBeLeft.All(x => avl.Contains(x));
var deleteErrors = avl.Count == N;
//Console.WriteLine("【AVL木の構造】");
//Console.WriteLine(avl);
if (insertErrors && deleteErrors) Console.WriteLine("○\t挿入, 削除操作が正しく行われています.");
else if (insertErrors) Console.WriteLine("×\t挿入(または削除)操作に問題があります.");
else Console.WriteLine("×\t削除(または挿入)操作に問題があります.");
if (avl.IsBalanced()) Console.WriteLine("○\tAVL木は平衡条件を保っています.");
else Console.WriteLine("×\tAVL木の平衡条件が破れています.");
if (avl.IsValidBinarySearchTree()) Console.WriteLine("○\tAVL木は二分探索木になっています.");
else Console.WriteLine("×\tAVL木は二分探索木になっていません.");
Array.Sort(toBeLeft, comp);
Console.WriteLine($"最小値 : {avl.Min()} ≡ {toBeLeft.First()}");
Console.WriteLine($"最大値 : {avl.Max()} ≡ {toBeLeft.Last()}");
Console.WriteLine($"要素数 : {avl.Count} 個");
}
}
class PriorityQueue<T> : IEnumerable<T>, ICollection, IEnumerable, ICloneable
{
Comparison<T> comp;
List<T> list;
public int Count { get; private set; } = 0;
public bool IsEmpty => Count == 0;
public PriorityQueue(IEnumerable<T> source) : this((Comparison<T>)null, 0, source) { }
public PriorityQueue(int capacity = 4, IEnumerable<T> source = null) : this((Comparison<T>)null, capacity, source) { }
public PriorityQueue(IComparer<T> comp, IEnumerable<T> source) : this(comp.ToComparison(), source) { }
public PriorityQueue(IComparer<T> comp, int capacity = 4, IEnumerable<T> source = null) : this(comp.ToComparison(), source) { list.Capacity = capacity; }
public PriorityQueue(Comparison<T> comp, IEnumerable<T> source) : this(comp, 0, source) { }
public PriorityQueue(Comparison<T> comp, int capacity = 4, IEnumerable<T> source = null) { this.comp = comp ?? Func.DefaultComparison<T>(); list = new List<T>(capacity); if (source != null) foreach (var x in source) Enqueue(x); }
/// <summary>
/// add an item
/// this is an O(log n) operation
/// </summary>
/// <param name="x">item</param>
public void Enqueue(T x)
{
var pos = Count++;
list.Add(x);
while (pos > 0)
{
var p = (pos - 1) / 2;
if (comp(list[p], x) <= 0) break;
list[pos] = list[p];
pos = p;
}
list[pos] = x;
}
/// <summary>
/// return the minimum element and remove it
/// this is an O(log n) operation
/// </summary>
/// <returns>the minimum</returns>
public T Dequeue()
{
var value = list[0];
var x = list[--Count];
list.RemoveAt(Count);
if (Count == 0) return value;
var pos = 0;
while (pos * 2 + 1 < Count)
{
var a = 2 * pos + 1;
var b = 2 * pos + 2;
if (b < Count && comp(list[b], list[a]) < 0) a = b;
if (comp(list[a], x) >= 0) break;
list[pos] = list[a];
pos = a;
}
list[pos] = x;
return value;
}
/// <summary>
/// look at the minimum element
/// this is an O(1) operation
/// </summary>
/// <returns>the minimum</returns>
public T Peek() => list[0];
public IEnumerator<T> GetEnumerator() { var x = (PriorityQueue<T>)Clone(); while (x.Count > 0) yield return x.Dequeue(); }
void CopyTo(Array array, int index) { foreach (var x in this) array.SetValue(x, index++); }
public object Clone() { var x = new PriorityQueue<T>(comp, Count); x.list.AddRange(list); return x; }
public void Clear() { list = new List<T>(); Count = 0; }
public void TrimExcess() => list.TrimExcess();
/// <summary>
/// check whether item is in this queue
/// this is an O(n) operation
/// </summary>
public bool Contains(T item) => list.Contains(item);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
void ICollection.CopyTo(Array array, int index) => CopyTo(array, index);
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
}
class Deque<T>
{
T[] array;
int offset, capacity;
public int Count { get; protected set; }
public Deque(int capacity) { array = new T[this.capacity = capacity]; Count = 0; offset = 0; }
public Deque() : this(16) { }
public T this[int index] { get { return array[GetIndex(index)]; } set { array[GetIndex(index)] = value; } }
int GetIndex(int index) { var tmp = index + offset; return tmp >= capacity ? tmp - capacity : tmp; }
public T PeekFront() => array[offset];
public T PeekBack() => array[GetIndex(Count - 1)];
public void PushFront(T item)
{
if (Count == capacity) Extend();
if (--offset < 0) offset += array.Length;
array[offset] = item;
Count++;
}
public T PopFront()
{
Count--;
var tmp = array[offset++];
if (offset >= capacity) offset -= capacity;
return tmp;
}
public void PushBack(T item)
{
if (Count == capacity) Extend();
var id = (Count++) + offset;
if (id >= capacity) id -= capacity;
array[id] = item;
}
public T PopBack() => array[GetIndex(--Count)];
public void Insert(int index, T item)
{
PushFront(item);
for (var i = 0; i < index; i++) this[i] = this[i + 1];
this[index] = item;
}
public T RemoveAt(int index)
{
var tmp = this[index];
for (var i = index; i > 0; i--) this[i] = this[i - 1];
PopFront();
return tmp;
}
void Extend()
{
var newArray = new T[capacity << 1];
if (offset > capacity - Count)
{
var length = array.Length - offset;
Array.Copy(array, offset, newArray, 0, length);
Array.Copy(array, 0, newArray, length, Count - length);
}
else Array.Copy(array, offset, newArray, 0, Count);
array = newArray;
offset = 0;
capacity <<= 1;
}
}
class PairComparer<S, T> : IComparer<Pair<S, T>>
where S : IComparable<S>
where T : IComparable<T>
{
public PairComparer() { }
public int Compare(Pair<S, T> x, Pair<S, T> y)
{
var p = x.First.CompareTo(y.First);
if (p != 0) return p;
else return x.Second.CompareTo(y.Second);
}
}
class Pair<S, T>
{
public S First;
public T Second;
public Pair() { First = default(S); Second = default(T); }
public Pair(S s, T t) { First = s; Second = t; }
public override string ToString() => $"({First}, {Second})";
public override int GetHashCode() => First.GetHashCode() ^ Second.GetHashCode();
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
else if (obj == null) return false;
var tmp = obj as Pair<S, T>;
return tmp != null && First.Equals(tmp.First) && Second.Equals(tmp.Second);
}
}
class Point : Pair<int, int>
{
public int X { get { return First; } set { First = value; } }
public int Y { get { return Second; } set { Second = value; } }
public Point() : base(0, 0) { }
public Point(int x, int y) : base(x, y) { }
public IEnumerable<Point> Neighbors4()
{
yield return new Point(X - 1, Y);
yield return new Point(X, Y - 1);
yield return new Point(X, Y + 1);
yield return new Point(X + 1, Y);
}
public IEnumerable<Point> Neighbors8()
{
yield return new Point(X - 1, Y - 1);
yield return new Point(X - 1, Y);
yield return new Point(X - 1, Y + 1);
yield return new Point(X, Y - 1);
yield return new Point(X, Y + 1);
yield return new Point(X + 1, Y - 1);
yield return new Point(X + 1, Y);
yield return new Point(X + 1, Y + 1);
}
public static Point operator +(Point p) => new Point(p.X, p.Y);
public static Point operator -(Point p) => new Point(-p.X, -p.Y);
public static Point operator /(Point p, int r) => new Point(p.X / r, p.Y / r);
public static Point operator *(int r, Point p) => new Point(p.X * r, p.Y * r);
public static Point operator *(Point p, int r) => new Point(p.X * r, p.Y * r);
public static Point operator +(Point p, Point q) => new Point(p.X + q.X, p.Y + q.Y);
public static Point operator -(Point p, Point q) => new Point(p.X - q.X, p.Y - q.Y);
}
class Printer : IDisposable
{
bool isConsole;
TextWriter file;
public Printer() { file = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; isConsole = true; }
public Printer(string path) { file = new StreamWriter(path, false) { AutoFlush = false }; isConsole = false; }
public void Write<T>(T value) => file.Write(value);
public void Write(bool b) => file.Write(b ? "YES" : "NO");
public void Write(string str, params object[] args) => file.Write(str, args);
public void WriteLine() => file.WriteLine();
public void WriteLine<T>(T value) => file.WriteLine(value);
public void WriteLine(bool b) => file.WriteLine(b ? "YES" : "NO");
public void WriteLine<T>(IEnumerable<T> list) { foreach (var x in list) file.WriteLine(x); }
public void WriteLine<T>(List<T> list) { foreach (var x in list) file.WriteLine(x); }
public void WriteLine<T>(T[] list) { foreach (var x in list) file.WriteLine(x); }
public void WriteLine(string str, params object[] args) => file.WriteLine(str, args);
public void Dispose() { file.Flush(); if (!isConsole) file.Dispose(); }
}
class Scanner : IDisposable
{
bool isConsole;
TextReader file;
public Scanner() { file = Console.In; }
public Scanner(string path) { file = new StreamReader(path); isConsole = false; }
public void Dispose() { if (!isConsole) file.Dispose(); }
public T Get<T>() => (T)Convert(file.ReadLine(), Type.GetTypeCode(typeof(T)));
public int Int => Get<int>();
public uint UInt => Get<uint>();
public long Long => Get<long>();
public ulong ULong => Get<ulong>();
public double Double => Get<double>();
public decimal Decimal => Get<decimal>();
public char Char => Get<char>();
public string String => Get<string>();
public Tuple<S, T> Get<S, T>() { S s; T t; Read(out s, out t); return new Tuple<S, T>(s, t); }
public Tuple<S, T, U> Get<S, T, U>() { S s; T t; U u; Read(out s, out t, out u); return new Tuple<S, T, U>(s, t, u); }
public Tuple<S, T, U, V> Get<S, T, U, V>() { S s; T t; U u; V v; Read(out s, out t, out u, out v); return new Tuple<S, T, U, V>(s, t, u, v); }
public Tuple<S, T, U, V, W> Get<S, T, U, V, W>() { S s; T t; U u; V v; W w; Read(out s, out t, out u, out v, out w); return new Tuple<S, T, U, V, W>(s, t, u, v, w); }
public Tuple<S, T, U, V, W, X> Get<S, T, U, V, W, X>() { S s; T t; U u; V v; W w; X x; Read(out s, out t, out u, out v, out w, out x); return new Tuple<S, T, U, V, W, X>(s, t, u, v, w, x); }
public Tuple<S, T, U, V, W, X, Y> Get<S, T, U, V, W, X, Y>() { S s; T t; U u; V v; W w; X x; Y y; Read(out s, out t, out u, out v, out w, out x, out y); return new Tuple<S, T, U, V, W, X, Y>(s, t, u, v, w, x, y); }
public Tuple<S, T, U, V, W, X, Y, Z> Get<S, T, U, V, W, X, Y, Z>() { S s; T t; U u; V v; W w; X x; Y y; Z z; Read(out s, out t, out u, out v, out w, out x, out y, out z); return new Tuple<S, T, U, V, W, X, Y, Z>(s, t, u, v, w, x, y, z); }
public Pair<S, T> Pair<S, T>() { S s; T t; Read(out s, out t); return new Pair<S, T>(s, t); }
object Convert(string str, TypeCode type)
{
if (type == TypeCode.Int32) return int.Parse(str);
else if (type == TypeCode.UInt32) return uint.Parse(str);
else if (type == TypeCode.Int64) return long.Parse(str);
else if (type == TypeCode.UInt64) return ulong.Parse(str);
else if (type == TypeCode.Double) return double.Parse(str);
else if (type == TypeCode.Decimal) return decimal.Parse(str);
else if (type == TypeCode.Char) return str[0];
else if (type == TypeCode.String) return str;
else if (type == Type.GetTypeCode(typeof(Point))) { int s, t; Read(out s, out t); return new Point(s, t); }
else throw new Exception();
}
public T[] ReadMany<T>() { var type = Type.GetTypeCode(typeof(T)); return file.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries).Select(str => (T)Convert(str, type)).ToArray(); }
public T[] ReadMany<T>(int n) { var type = Type.GetTypeCode(typeof(T)); return file.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries).Take(n).Select(str => (T)Convert(str, type)).ToArray(); }
public T[] ReadManyLines<T>(int n, Func<T> selector) => Enumerable.Range(0, n).Select(_ => selector()).ToArray();
public T[] ReadManyLines<T>(int n) => Enumerable.Range(0, n).Select(_ => Get<T>()).ToArray();
public Tuple<S, T>[] ReadManyLines<S, T>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T>()).ToArray();
public Tuple<S, T, U>[] ReadManyLines<S, T, U>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U>()).ToArray();
public Tuple<S, T, U, V>[] ReadManyLines<S, T, U, V>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V>()).ToArray();
public Tuple<S, T, U, V, W>[] ReadManyLines<S, T, U, V, W>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V, W>()).ToArray();
public Tuple<S, T, U, V, W, X>[] ReadManyLines<S, T, U, V, W, X>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V, W, X>()).ToArray();
public Tuple<S, T, U, V, W, X, Y>[] ReadManyLines<S, T, U, V, W, X, Y>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V, W, X, Y>()).ToArray();
public Tuple<S, T, U, V, W, X, Y, Z>[] ReadManyLines<S, T, U, V, W, X, Y, Z>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V, W, X, Y, Z>()).ToArray();
public T[,] ReadManyManyLines<T>(int X, int Y)
{
var array = new T[X, Y];
for (var y = 0; y < Y; y++) { var tmp = ReadMany<T>(X); for (var x = 0; x < X; x++) array[x, y] = tmp[x]; }
return array;
}
public void Read<S>(out S s)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S))).ToArray();
s = (S)read[0];
}
public void Read<S, T>(out S s, out T t)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T))).ToArray();
s = (S)read[0];
t = (T)read[1];
}
public void Read<S, T, U>(out S s, out T t, out U u)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)), Type.GetTypeCode(typeof(U))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
}
public void Read<S, T, U, V>(out S s, out T t, out U u, out V v)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)), Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
}
public void Read<S, T, U, V, W>(out S s, out T t, out U u, out V v, out W w)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)),
Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V)), Type.GetTypeCode(typeof(W))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
w = (W)read[4];
}
public void Read<S, T, U, V, W, X>(out S s, out T t, out U u, out V v, out W w, out X x)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)),
Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V)), Type.GetTypeCode(typeof(W)), Type.GetTypeCode(typeof(X))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
w = (W)read[4];
x = (X)read[5];
}
public void Read<S, T, U, V, W, X, Y>(out S s, out T t, out U u, out V v, out W w, out X x, out Y y)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)),
Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V)), Type.GetTypeCode(typeof(W)), Type.GetTypeCode(typeof(X)), Type.GetTypeCode(typeof(Y))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
w = (W)read[4];
x = (X)read[5];
y = (Y)read[6];
}
public void Read<S, T, U, V, W, X, Y, Z>(out S s, out T t, out U u, out V v, out W w, out X x, out Y y, out Z z)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)),
Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V)), Type.GetTypeCode(typeof(W)),
Type.GetTypeCode(typeof(X)), Type.GetTypeCode(typeof(Y)), Type.GetTypeCode(typeof(Z))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
w = (W)read[4];
x = (X)read[5];
y = (Y)read[6];
z = (Z)read[7];
}
static char[] sep = new[] { ' ', '/' };
IEnumerable<object> ReadMulti(params TypeCode[] types)
{
var input = file.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < types.Length; i++) yield return Convert(input[i], types[i]);
}
public T[,] Board<T>(int X, int Y, Func<char, int, int, T> selector)
{
var array = new T[X, Y];
for (var y = 0; y < Y; y++)
{
var str = Get<string>();
for (var x = 0; x < X; x++) array[x, y] = selector(str[x], x, y);
}
return array;
}
}
static class Func
{
public const int Inf = 1073741789; // 2 * Inf < int.MaxValue, and Inf is a prime number
public const long InfL = 4011686018427387913L; // 2 * InfL < long.MaxValue, and InfL is a prime number
public static Comparison<T> DefaultComparison<T>() => (x, y) => Comparer<T>.Default.Compare(x, y);
public static Comparison<T> ToComparison<T>(this IComparer<T> comp) => comp == null ? DefaultComparison<T>() : (x, y) => comp.Compare(x, y);
/// <summary>
/// Find the first number x such that pred(x) is true
/// if pred(x) is false for all min<=x<max, then return max
/// in other words, pred(max) is assumed to be true
/// </summary>
/// <param name="min">inclusive lower limit</param>
/// <param name="max">exclusive upper limit</param>
/// <param name="pred">monotonous predicate, i.e. if pred(a) and a<b, then pred(b)</param>
/// <returns>first number such that satisfy pred</returns>
public static long FirstBinary(long min, long max, Predicate<long> pred)
{
while (min < max)
{
var mid = (min + max) / 2;
if (pred(mid)) max = mid;
else min = mid + 1;
}
return min;
}
/// <summary>
/// Find the first number x such that pred(x) is true
/// if pred(x) is false for all min<=x<max, then return max
/// in other words, pred(max) is assumed to be true
/// </summary>
/// <param name="min">inclusive lower limit</param>
/// <param name="max">exclusive upper limit</param>
/// <param name="pred">monotonous predicate, i.e. if pred(a) and a<b, then pred(b)</param>
/// <returns>first number such that satisfy pred</returns>
public static int FirstBinary(int min, int max, Predicate<int> pred)
{
while (min < max)
{
var mid = (min + max) / 2;
if (pred(mid)) max = mid;
else min = mid + 1;
}
return min;
}
public static Dictionary<T, S> Reverse<S, T>(this IDictionary<S, T> dict)
{
var r = new Dictionary<T, S>();
foreach (var t in dict) r.Add(t.Value, t.Key);
return r;
}
public static void Swap<T>(this IList<T> array, int i, int j) { var tmp = array[i]; array[i] = array[j]; array[j] = tmp; }
public static void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; }
public static T IndexAt<T>(this T[,] array, Pair<int, int> index) => array[index.First, index.Second];
public static bool InRegion(this Pair<int, int> p, int X, int Y) => p.InRegion(0, X, 0, Y);
public static bool InRegion(this Pair<int, int> p, int x, int X, int y, int Y) => p.First >= x && p.Second >= y && p.First < X && p.Second < Y;
/// <summary>
/// get all permutation of 0, 1, ..., n - 1
/// </summary>
/// <param name="n">length of array</param>
/// <param name="func">if you want to change the elements of the array, you must take a copy</param>
public static void Permutation(int n, Action<int[]> func)
{
var array = new int[n];
var unused = new bool[n];
for (var i = 0; i < n; i++) unused[i] = true;
Permutation(n, 0, array, unused, func);
}
static void Permutation(int n, int i, int[] array, bool[] unused, Action<int[]> func)
{
if (i == n) func(array);
else
for (var x = 0; x < n; x++)
if (unused[x])
{
array[i] = x;
unused[x] = false;
Permutation(n, i + 1, array, unused, func);
unused[x] = true;
}
}
public static long Fact(int n)
{
var fact = 1L;
for (var i = 2; i <= n; i++) fact *= i;
return fact;
}
public static Dictionary<long, int> Factorize(this long n, List<int> primes)
{
var d = new Dictionary<long, int>();
for (var j = 0; j < primes.Count; j++)
{
var i = primes[j];
if (i * i > n) break;
if (n % i == 0)
{
d.Add(i, 0);
while (n % i == 0) { n /= i; d[i]++; }
}
}
if (n > 1) d.Add(n, 1);
return d;
}
public static Dictionary<long, int> Factorize(this long n)
{
var d = new Dictionary<long, int>();
for (var i = 2L; i * i <= n; i++)
if (n % i == 0)
{
d.Add(i, 0);
while (n % i == 0) { n /= i; d[i]++; }
}
if (n > 1) d.Add(n, 1);
return d;
}
public static long LCM(long n, long m) => Math.Abs((n / GCD(n, m)) * m);
public static long Divide(long n, long m) => (n - Remainder(n, m)) / m;
public static long Remainder(long n, long m)
{
if (m == 0) throw new DivideByZeroException();
else if (m < 0) return Remainder(n, -m);
else
{
var r = n % m;
return r < 0 ? r + m : r;
}
}
public static long Recurrence(long[] coeff, long[] init, long N, long mod)
{
var K = init.Length;
if (N < 0)
{
var inv = Inverse(coeff[0], mod);
var rc = new long[K];
for (var i = 1; i < K; i++) rc[K - i] = -coeff[i] * inv % mod;
rc[0] = inv;
var ri = new long[K];
for (var i = 0; i < K; i++) ri[K - 1 - i] = init[i];
return Recurrence(rc, ri, K - 1 - N, mod);
}
var tmp = new long[K];
Recurrence(coeff, init, tmp, N, mod);
var sum = 0L;
for (var i = 0; i < K; i++) sum += init[i] * tmp[i] % mod;
sum %= mod;
if (sum < 0) sum += mod;
return sum;
}
public static void Recurrence(long[] coeff, long[] init, long[] state, long N, long mod)
{
var K = init.Length;
if (N < K) state[N] = init[N];
else if ((N & 1) == 0)
{
var tmp = new long[K][];
for (var i = 0; i < K; i++) tmp[i] = new long[K];
Recurrence(coeff, init, tmp[0], N / 2, mod);
for (var i = 1; i < K; i++) tmp[i] = Next(coeff, tmp[i - 1], mod);
for (var i = 0; i < K; i++)
{
state[i] = 0;
for (var j = 0; j < K; j++) state[i] += tmp[0][j] * tmp[j][i] % mod;
state[i] %= mod;
}
}
else if (N < 2 * K || (N & 2) == 0)
{
var tmp = new long[K];
Recurrence(coeff, init, tmp, N - 1, mod);
tmp = Next(coeff, tmp, mod);
for (var i = 0; i < K; i++) state[i] = tmp[i];
}
else
{
var tmp = new long[K];
Recurrence(coeff, init, tmp, N + 1, mod);
tmp = Prev(coeff, tmp, mod);
for (var i = 0; i < K; i++) state[i] = tmp[i];
}
}
static long[] Next(long[] coeff, long[] state, long mod)
{
var K = coeff.Length;
var tmp = new long[K];
for (var i = 0; i < K; i++) tmp[i] = coeff[i] * state[K - 1] % mod;
for (var i = 1; i < K; i++) tmp[i] = (tmp[i] + state[i - 1]) % mod;
return tmp;
}
static long[] Prev(long[] coeff, long[] state, long mod)
{
var K = coeff.Length;
var tmp = new long[K];
var inv = Inverse(coeff[0], mod);
tmp[K - 1] = state[0] * inv % mod;
for (var i = 1; i < K; i++) tmp[i - 1] = (state[i] - coeff[i] * tmp[K - 1] % mod) % mod;
return tmp;
}
// get all primes less than or equal to n
public static List<int> GetPrimes(int n)
{
if (n < 3) n = 3;
var m = (n - 1) >> 1;
var primes = new List<int>((int)(n / Math.Log(n))) { 2 };
var composites = new bool[m];
for (var p = 0; p < m; p++)
{
if (!composites[p])
{
var pnum = 2 * p + 3;
primes.Add(pnum);
for (var k = 3 * p + 3; k < m; k += pnum) composites[k] = true;
}
}
return primes;
}
/// <summary>
/// solve nx+my=1 and returns (x,y)
/// </summary>
/// <param name="n">assumed to be with m</param>
/// <param name="m">assumed to be with n</param>
/// <returns>(x,y) where nx+my=1</returns>
public static Tuple<long, long> SolveLinear(long n, long m)
{
if (n < 0) { var p = SolveLinear(-n, m); return p == null ? p : new Tuple<long, long>(-p.Item1, p.Item2); }
if (m < 0) { var p = SolveLinear(n, -m); return p == null ? p : new Tuple<long, long>(p.Item1, -p.Item2); }
if (n < m) { var p = SolveLinear(m, n); return p == null ? p : new Tuple<long, long>(p.Item2, p.Item1); }
long a = 1, b = 0, c = 0, d = 1;
while (m > 0)
{
var r = n % m;
var q = n / m;
n = m;
m = r;
var tmp = a;
a = -a * q + b;
b = tmp;
tmp = c;
c = -c * q + d;
d = tmp;
}
return n != 1 ? null : new Tuple<long, long>(d, b);
}
public static int GCD(int n, int m)
{
var a = Math.Abs(n);
var b = Math.Abs(m);
if (a < b) { var c = a; a = b; b = c; }
while (b > 0)
{
var c = a % b;
a = b;
b = c;
}
return a;
}
/*public static long GCD(long n, long m)
{
var a = Math.Abs(n);
var b = Math.Abs(m);
if (a < b) { var c = a; a = b; b = c; }
while (b > 0)
{
var c = a % b;
a = b;
b = c;
}
return a;
}*/
public static long GCD(long a, long b)
{
var n = (ulong)Math.Abs(a); var m = (ulong)Math.Abs(b);
if (n == 0) return (long)m; if (m == 0) return (long)n;
int zm = 0, zn = 0;
while ((n & 1) == 0) { n >>= 1; zn++; }
while ((m & 1) == 0) { m >>= 1; zm++; }
while (m != n)
{
if (m > n) { m -= n; while ((m & 1) == 0) m >>= 1; }
else { n -= m; while ((n & 1) == 0) n >>= 1; }
}
return (long)n << Math.Min(zm, zn);
}
public static BigInteger GCD(BigInteger a, BigInteger b) => BigInteger.GreatestCommonDivisor(a, b);
public static long Inverse(long a, long mod)
{
if (a < 0) { a %= mod; if (a < 0) a += mod; }
var t = SolveLinear(a, mod);
return t.Item1 > 0 ? t.Item1 : t.Item1 + mod;
}
public static ulong Pow(ulong a, ulong b, ulong mod)
{
var p = 1uL;
var x = a;
while (b > 0)
{
if ((b & 1) == 1) p = (p * x) % mod;
b >>= 1;
x = (x * x) % mod;
}
return p;
}
public static long Pow(long a, long b, long mod)
{
var p = 1L;
var x = a;
while (b > 0)
{
if ((b & 1) == 1) p = (p * x) % mod;
b >>= 1;
x = (x * x) % mod;
}
return p;
}
public static long Pow(long a, long b)
{
if (a == 1) return 1;
else if (a == 0) { if (b >= 0) return 0; else throw new DivideByZeroException(); }
else if (b < 0) return 0;
var p = 1L;
var x = a;
while (b > 0)
{
if ((b & 1) == 1) p *= x;
b >>= 1;
x *= x;
}
return p;
}
public static ulong Pow(ulong a, ulong b)
{
var p = 1ul;
var x = a;
while (b > 0)
{
if ((b & 1) == 1) p *= x;
b >>= 1;
x *= x;
}
return p;
}
public static long ChineseRemainder(Tuple<long, long> modRemainder1, Tuple<long, long> modRemainder2)
{
var m1 = modRemainder1.Item1;
var m2 = modRemainder2.Item1;
var a1 = modRemainder1.Item2;
var a2 = modRemainder2.Item2;
var t = SolveLinear(m1, m2);
var n1 = t.Item1;
var n2 = t.Item2;
return (m1 * n1 * a2 + m2 * n2 * a1) % (m1 * m2);
}
public static long ChineseRemainder(params Tuple<long, long>[] modRemainder)
{
if (modRemainder.Length == 0) throw new DivideByZeroException();
else if (modRemainder.Length == 1) return modRemainder[0].Item2;
else if (modRemainder.Length == 2) return ChineseRemainder(modRemainder[0], modRemainder[1]);
else
{
var tuple = new Tuple<long, long>(1, 0);
for (var i = 0; i < modRemainder.Length; i++)
{
var tmp = ChineseRemainder(tuple, modRemainder[i]);
tuple = new Tuple<long, long>(tuple.Item1 * modRemainder[i].Item1, tmp);
}
return tuple.Item2;
}
}
// forward transform -> theta= 2*PI/n
// reverse transform -> theta=-2*PI/n, and use a[i]/n instead of a
// O(n*log(n))
public static void FastFourierTransform(int n, double theta, Complex[] a)
{
for (var m = n; m >= 2; m >>= 1)
{
var mh = m >> 1;
for (var i = 0; i < mh; i++)
{
var w = Complex.Exp(i * theta * Complex.ImaginaryOne);
for (var j = i; j < n; j += m)
{
var k = j + mh;
var x = a[j] - a[k];
a[j] += a[k];
a[k] = w * x;
}
}
theta *= 2;
}
var s = 0;
for (var j = 1; j < n - 1; j++)
{
for (var k = n >> 1; k > (s ^= k); k >>= 1) ;
if (j < s) a.Swap(s, j);
}
}
// get table of Euler function
// let return value f, f[i]=phi(i) for 0<=i<=n
// nearly O(n)
public static long[] EulerFunctionTable(long n)
{
if (n < 2) n = 2;
var f = new long[n + 1];
for (var i = 0L; i <= n; i++) f[i] = i;
for (var i = 2L; i <= n; i++) if (f[i] == i) for (var j = i; j <= n; j += i) f[j] = f[j] / i * (i - 1);
return f;
}
// O(sqrt(n))
public static long EulerFunction(long n)
{
var res = n;
for (var i = 2L; i * i <= n; i++)
if (n % i == 0)
{
res = res / i * (i - 1);
do n /= i; while (n % i == 0);
}
if (n != 1) res = res / n * (n - 1);
return res;
}
// get moebius function of d s.t. 0<=d<=n
// O(n)
public static int[] MoebiusFunctionTable(long n)
{
if (n < 2) n = 2;
var f = new int[n + 1];
var p = new bool[n + 1];
for (var i = 0L; i <= n; i++) f[i] = 1;
for (var i = 2L; i <= n; i++) if (!p[i])
{
for (var j = i; j <= n; j += i) { f[j] *= -1; p[j] = true; }
for (var j = i * i; j <= n; j += i * i) f[j] = 0;
}
return f;
}
// get moebius function of d s.t. d|n
// if dict.ContainsKey(d), dict[d]!=0, otherwise moebius function of d is 0
// O(sqrt(n))
public static Dictionary<long, int> MoebiusFunctionOfDivisors(long n)
{
var ps = new List<long>();
for (var i = 2L; i * i <= n; i++)
if (n % i == 0)
{
ps.Add(i);
do n /= i; while (n % i == 0);
}
if (n != 1) ps.Add(n);
var dict = new Dictionary<long, int>();
var m = ps.Count;
for (var i = 0; i < (1 << m); i++)
{
var mu = 1;
var k = 1L;
for (var j = 0; j < m; j++) if ((i & (1 << j)) != 0) { mu *= -1; k *= ps[j]; }
dict.Add(k, mu);
}
return dict;
}
// O(sqrt(n))
public static int MoebiusFunction(long n)
{
var mu = 1;
for (var i = 2L; i * i <= n; i++)
if (n % i == 0)
{
mu *= -1;
if ((n /= i) % i == 0) return 0;
}
return n == 1 ? mu : -mu;
}
// O(sqrt(n))
public static long CarmichaelFunction(long n)
{
var lambda = 1L;
var c = 0;
while (n % 2 == 0) { n /= 2; c++; }
if (c == 2) lambda = 2; else if (c > 2) lambda = 1 << (c - 2);
for (var i = 3L; i * i <= n; i++)
if (n % i == 0)
{
var tmp = i - 1;
n /= i;
while (n % i == 0) { n /= i; tmp *= i; }
lambda = LCM(lambda, tmp);
}
if (n != 1) lambda = LCM(lambda, n - 1);
return lambda;
}
// a+bi is Gaussian prime or not
public static bool IsGaussianPrime(ulong a, ulong b)
{
if (a == 0) return b % 4 == 3 && IsPrime(b);
else if (b == 0) return a % 4 == 3 && IsPrime(a);
else return IsPrime(a * a + b * b);
}
// nearly O(200)
public static bool IsPrime(ulong n)
{
if (n <= 1 || (n > 2 && n % 2 == 0)) return false;
var test = new uint[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 111 };
var d = n - 1;
var s = 0;
while (d % 2 == 0) { ++s; d /= 2; }
Predicate<ulong> f = t =>
{
var x = Pow(t, d, n);
if (x == 1) return true;
for (var r = 0L; r < s; r++)
{
if (x == n - 1) return true;
x = (x * x) % n;
}
return false;
};
for (var i = 0; test[i] < n && test[i] != 111; i++) if (!f(test[i])) return false;
return true;
}
public static decimal MeasureTime(Action action)
{
var sw = new Stopwatch();
sw.Restart();
action();
sw.Stop();
return sw.ElapsedTicks * 1000m / Stopwatch.Frequency;
}
public static double MeasureTime2(Action action)
{
var sw = new Stopwatch();
sw.Restart();
action();
sw.Stop();
return sw.ElapsedTicks * 1000.0 / Stopwatch.Frequency;
}
static readonly double GoldenRatio = 2 / (3 + Math.Sqrt(5));
// assume f is 凹
// find c s.t. a<=c<=b and for all a<=x<=b, f(c)<=f(x)
public static double GoldenSectionSearch(double a, double b, Func<double, double> f)
{
double c = a + GoldenRatio * (b - a), d = b - GoldenRatio * (b - a);
double fc = f(c), fd = f(d);
while (d - c > 1e-9)
{
if (fc > fd)
{
a = c; c = d; d = b - GoldenRatio * (b - a);
fc = fd; fd = f(d);
}
else
{
b = d; d = c; c = a + GoldenRatio * (b - a);
fd = fc; fc = f(c);
}
}
return c;
}
// O(NW)
public static int KnapsackW(int[] w, int[] v, int W)
{
var N = w.Length;
var dp = new int[W + 1];
for (var i = 0; i < N; i++) for (var j = W; j >= w[i]; j--) dp[j] = Math.Max(dp[j], v[i] + dp[j - w[i]]);
return dp[W];
}
// O(NV)
public static int KnapsackV(int[] w, int[] v, int W)
{
var N = w.Length;
var V = v.Sum();
var dp = new int[V + 1];
for (var i = 1; i <= V; i++) dp[i] = Inf;
for (var i = 0; i < N; i++) for (var j = V; j >= v[i]; j--)
dp[j] = Math.Min(dp[j], w[i] + dp[j - v[i]]);
for (var j = V; j >= 0; j--) if (dp[j] <= W) return j;
return 0;
}
// O(N*2^(N/2))
public static long KnapsackN(long[] w, long[] v, int W)
{
var N = w.Length;
var half = N / 2;
var items = new Tuple<long, long>[N];
for (var i = 0; i < N; i++) items[i] = new Tuple<long, long>(w[i], v[i]);
Array.Sort(items, (x, y) => x.Item1.CompareTo(y.Item1));
Func<int, int, List<Pair<long, long>>> gen = (start, end) =>
{
if (start >= end) return new List<Pair<long, long>>();
var lim = 1 << (end - start);
var list = new List<Pair<long, long>>();
for (var i = 0; i < lim; i++)
{
var weight = 0L;
var value = 0L;
var tmp = i;
for (var j = start; j < end; j++)
{
if ((tmp & 1) == 1) { weight += items[j].Item1; value += items[j].Item2; }
tmp >>= 1;
}
if (weight <= W) list.Add(new Pair<long, long>(weight, value));
}
list.Sort((x, y) => { var c = x.First.CompareTo(y.First); return c == 0 ? x.Second.CompareTo(y.Second) : c; });
var n = list.Count;
if (n == 0) return list;
for (var i = list.Count - 2; i >= 0; i--) if (list[i].First == list[i + 1].First) list[i].Second = Math.Max(list[i].Second, list[i + 1].Second);
var small = new List<Pair<long, long>>();
var last = -1;
while (last + 1 < n)
{
var tmp = list[last + 1].First;
last = FirstBinary(last + 1, n, x => list[x].First > tmp) - 1;
if (small.Count == 0 || list[last].Second > small[small.Count - 1].Second) small.Add(list[last]);
}
return small;
};
var first = gen(0, half);
var second = gen(half, N);
var max = 0L;
var last2 = second.Count;
foreach (var item in first)
{
last2 = FirstBinary(0, last2, x => second[x].First > W - item.First) - 1;
if (last2 < 0) break;
if (second[last2].First <= W - item.First) SetToMax(ref max, item.Second + second[last2].Second);
last2++;
}
return max;
}
// nums[i] が counts[i] 個
// K is partial sum?
// O(NK)
public static bool PartialSum(int[] nums, int[] counts, int K)
{
var N = nums.Length;
var memo = new int[K + 1];
for (var s = 1; s <= K; s++) memo[s] = -1;
for (var n = 0; n < N; n++) for (var s = 0; s <= K; s++) memo[s] = memo[s] >= 0 ? counts[n] : s < nums[n] ? -1 : memo[s - nums[n]] - 1;
return memo[K] >= 0;
}
// O(N log(N))
public static int LongestIncreasingSubsequence(int[] a)
{
var N = a.Length;
var memo = new int[N];
memo.MemberSet(Inf);
for (var n = 0; n < N; n++)
{
var k = FirstBinary(0, N, x => a[n] <= memo[x]);
memo[k] = a[n];
}
return FirstBinary(0, N, x => memo[x] == Inf);
}
// O(nm)
public static int LongestCommonSubsequence(string s, string t)
{
var n = s.Length;
var m = t.Length;
var memo = new int[n + 1, m + 1];
for (var i = n - 1; i >= 0; i--)
for (var j = m - 1; j >= 0; j--)
if (s[i] == t[j]) memo[i, j] = memo[i + 1, j + 1] + 1;
else memo[i, j] = Math.Max(memo[i + 1, j], memo[i, j + 1]);
return memo[0, 0];
}
// the number of ways of dividing N to M numbers
// O(NM)
public static int Partition(int N, int M, int Mod)
{
var memo = new long[N + 1, M + 1];
for (var m = 0; m <= M; m++) memo[0, m] = 1;
for (var n = 1; n <= N; n++)
{
memo[n, 0] = 0;
for (var m = 1; m <= M; m++) memo[n, m] = (memo[n, m - 1] + (n - m >= 0 ? memo[n - m, m] : 0)) % Mod;
}
return (int)memo[N, M];
}
// max{f(a)+...+f(b-1) | from<=a<b<=to}
// O(to-from)
public static long MaxIntervalSum(int from, int to, Func<long, long> f)
{
long max, dp;
max = dp = f(from);
for (var i = from + 1; i < to; i++)
{
var tmp = f(i);
dp = tmp + Math.Max(0, dp);
max = Math.Max(max, dp);
}
return max;
}
public static int MaxElement<T>(this IEnumerable<T> source, Comparison<T> comp)
{
var p = source.GetEnumerator();
if (!p.MoveNext()) return -1;
var max = p.Current;
var mi = 0;
var i = 0;
while (p.MoveNext())
{
i++;
if (comp(max, p.Current) < 0) { max = p.Current; mi = i; }
}
return mi;
}
public static int MaxElement<T>(this IEnumerable<T> source) where T : IComparable<T> => source.MaxElement((x, y) => x.CompareTo(y));
public static int MinElement<T>(IEnumerable<T> source, Comparison<T> comp) => source.MaxElement((x, y) => comp(y, x));
public static int MinElement<T>(IEnumerable<T> source) where T : IComparable<T> => source.MaxElement((x, y) => y.CompareTo(x));
public static void Shuffle<T>(IList<T> source, Random rand) { for (var i = source.Count - 1; i >= 0; --i) source.Swap(i, rand.Next(0, i + 1)); }
public static void Shuffle<T>(IList<T> source, RandomSFMT rand) { for (var i = source.Count - 1; i >= 0; --i) source.Swap(i, rand.Next(0, i + 1)); }
public static char NextChar(this Random rand) => (char)(rand.Next(0, 'z' - 'a' + 1) + 'a');
public static char NextChar(this RandomSFMT rand) => (char)(rand.Next(0, 'z' - 'a' + 1) + 'a');
public static string NextString(this Random rand, int length) => new string(Enumerable.Range(0, length).Select(_ => rand.NextChar()).ToArray());
public static string NextString(this RandomSFMT rand, int length) => new string(Enumerable.Range(0, length).Select(_ => rand.NextChar()).ToArray());
public static IEnumerable<T> Rotate<T>(this IEnumerable<T> source)
{
var e = source.GetEnumerator();
if (e.MoveNext())
{
var f = e.Current;
while (e.MoveNext()) yield return e.Current;
yield return f;
}
}
public static T Apply<T>(this Func<T, T> func, T x, int n)
{
var a = x;
for (var i = 0; i < n; i++) a = func(a);
return a;
}
public static void MemberSet<T>(this T[] array, T value)
{
var X = array.Length;
for (var x = 0; x < X; x++) array[x] = value;
}
public static void MemberSet<T>(this T[,] array, T value)
{
var X = array.GetLength(0); var Y = array.GetLength(1);
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) array[x, y] = value;
}
public static void MemberSet<T>(this T[,,] array, T value)
{
var X = array.GetLength(0); var Y = array.GetLength(1); var Z = array.GetLength(2);
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) for (var z = 0; z < Z; z++) array[x, y, z] = value;
}
public static void MemberSet<T>(this T[,,,] array, T value)
{
var X = array.GetLength(0); var Y = array.GetLength(1); var Z = array.GetLength(2); var W = array.GetLength(3);
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) for (var z = 0; z < Z; z++) for (var w = 0; w < W; w++) array[x, y, z, w] = value;
}
public static string ToYesNo(this bool flag) => flag ? "YES" : "NO";
public static int SetToMin(ref int min, int other) => min = Math.Min(min, other);
public static int SetToMax(ref int max, int other) => max = Math.Max(max, other);
public static long SetToMin(ref long min, long other) => min = Math.Min(min, other);
public static long SetToMax(ref long max, long other) => max = Math.Max(max, other);
public static Tuple<SortedDictionary<int, int>, SortedDictionary<int, int>> Compress(IEnumerable<int> coord, int width, int X)
{
var tmp = new SortedSet<int>();
foreach (var x in coord)
{
for (var w = -width; w <= width; w++)
if (x + w < 0 || x + w >= X) continue;
else if (tmp.Contains(x + w)) continue;
else tmp.Add(x + w);
}
var index = 0;
var inverse = new SortedDictionary<int, int>();
var dict = new SortedDictionary<int, int>();
foreach (var pair in tmp)
{
dict.Add(pair, index);
inverse.Add(index++, pair);
}
return new Tuple<SortedDictionary<int, int>, SortedDictionary<int, int>>(dict, inverse);
}
public static int MSB(uint n)
{
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return BitCount(n) - 1;
}
public static int BitCount(uint n)
{
n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff);
return (int)((n & 0x0000ffff) + ((n >> 16) & 0x0000ffff));
}
public static int LSB(uint n)
{
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
n |= (n << 16);
return 32 - BitCount(n);
}
public static int MSB(ulong n)
{
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
n |= (n >> 32);
return BitCount(n) - 1;
}
public static int BitCount(ulong n)
{
n = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555);
n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333);
n = (n & 0x0f0f0f0f0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f0f0f0f0f);
n = (n & 0x00ff00ff00ff00ff) + ((n >> 8) & 0x00ff00ff00ff00ff);
n = (n & 0x0000ffff0000ffff) + ((n >> 16) & 0x0000ffff0000ffff);
return (int)((n & 0x00000000ffffffff) + ((n >> 32) & 0x00000000ffffffff));
}
public static int LSB(ulong n)
{
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
n |= (n << 16);
n |= (n << 32);
return 64 - BitCount(n);
}
public static int Abs(this int n) => Math.Abs(n);
public static long Abs(this long n) => Math.Abs(n);
public static double Abs(this double n) => Math.Abs(n);
public static float Abs(this float n) => Math.Abs(n);
public static decimal Abs(this decimal n) => Math.Abs(n);
public static short Abs(this short n) => Math.Abs(n);
public static sbyte Abs(this sbyte n) => Math.Abs(n);
public static int Min(params int[] nums) { var min = int.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static long Min(params long[] nums) { var min = long.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static uint Min(params uint[] nums) { var min = uint.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static ulong Min(params ulong[] nums) { var min = ulong.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static double Min(params double[] nums) { var min = double.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static decimal Min(params decimal[] nums) { var min = decimal.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static int Max(params int[] nums) { var min = int.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static long Max(params long[] nums) { var min = long.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static uint Max(params uint[] nums) { var min = uint.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static ulong Max(params ulong[] nums) { var min = ulong.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static double Max(params double[] nums) { var min = double.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static decimal Max(params decimal[] nums) { var min = decimal.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static void MultiKeySort(this string[] list) => new MultiSorter(list).QuickSort();
class MultiSorter
{
const int MIN = 0;
string[] a;
int max;
public MultiSorter(string[] l) { a = l; max = a.Max(s => s.Length); }
public void QuickSort() { if (a.Length >= 2) QuickSort(0, a.Length, 0); }
public int At(int i, int z) => z < a[i].Length ? a[i][z] : MIN;
public int At(string s, int z) => z < s.Length ? s[z] : MIN;
public void QuickSort(int l, int r, int z)
{
int w = r - l, pl = l, pm = l + w / 2, pn = r - 1, c;
if (w > 30)
{
var d = w / 8;
pl = Median(pl, pl + d, pl + 2 * d, z);
pm = Median(pm - d, pm, pm + d, z);
pn = Median(pn - 2 * d, pn - d, pn, z);
}
pm = Median(pl, pm, pn, z);
var s = a[pm]; a[pm] = a[l]; a[l] = s;
var pivot = At(l, z);
int i = l + 1, x = l + 1, j = r - 1, y = r - 1;
while (true)
{
while (i <= j && (c = At(i, z) - pivot) <= 0)
{
if (c == 0) { if (i != x) { s = a[i]; a[i] = a[x]; a[x] = s; } x++; }
i++;
}
while (i <= j && (c = At(j, z) - pivot) >= 0)
{
if (c == 0) { if (j != y) { s = a[j]; a[j] = a[y]; a[y] = s; } y--; }
j--;
}
if (i > j) break;
s = a[i]; a[i] = a[j]; a[j] = s;
i++; j--;
}
j++; y++;
var m = Min(x - l, i - x); SwapRegion(l, i - m, m);
m = Min(y - j, r - y); SwapRegion(i, r - m, m);
i += l - x;
j += r - y;
if (i - l >= 10) QuickSort(l, i, z); else InsertSort(l, i, z);
if (pivot != MIN) if (j - i >= 10) QuickSort(i, j, z + 1); else InsertSort(i, j, z + 1);
if (r - j >= 10) QuickSort(j, r, z); else InsertSort(j, r, z);
}
private void SwapRegion(int p, int q, int n)
{
string s;
while (n-- > 0) { s = a[p]; a[p++] = a[q]; a[q++] = s; }
}
private void InsertSort(int l, int r, int z)
{
string s;
for (var i = l + 1; i < r; i++)
{
var tmp = a[i];
int x = z, y = z, p, q;
s = a[i - 1];
while ((p = At(tmp, x++)) == (q = At(s, y++)) && p != MIN) ;
if (q > p)
{
var j = i;
while (true)
{
a[j] = a[j - 1];
--j;
if (j <= l) break;
x = y = z;
s = a[j - 1];
while ((p = At(tmp, x++)) == (q = At(s, y++)) && p != MIN) ;
if (q <= p) break;
}
a[j] = tmp;
}
}
}
private int Median(int a, int b, int c, int z)
{
int p = At(a, z), q = At(b, z);
if (p == q) return a;
var r = At(c, z);
if (r == p || r == q) return c;
return p < q ?
(q < r ? b : (p < r ? c : a))
: (q > r ? b : (p < r ? a : c));
}
}
}
class RandomSFMT : Random
{
int index, coin_bits, byte_pos, range, shift;
uint coin_save, byte_save, bse;
protected uint[] x = new uint[40];
static uint[] ParityData = { 0x00000001U, 0x00000000U, 0x00000000U, 0x20000000U };
public virtual void GenRandAll()
{
int a = 0, b = 28, c = 32, d = 36; uint y; var p = x;
do
{
y = p[a + 3] ^ (p[a + 3] << 24) ^ (p[a + 2] >> 8) ^ ((p[b + 3] >> 5) & 0xb5ffff7fU);
p[a + 3] = y ^ (p[c + 3] >> 8) ^ (p[d + 3] << 14);
y = p[a + 2] ^ (p[a + 2] << 24) ^ (p[a + 1] >> 8) ^ ((p[b + 2] >> 5) & 0xaff3ef3fU);
p[a + 2] = y ^ ((p[c + 2] >> 8) | (p[c + 3] << 24)) ^ (p[d + 2] << 14);
y = p[a + 1] ^ (p[a + 1] << 24) ^ (p[a] >> 8) ^ ((p[b + 1] >> 5) & 0x7fefcfffU);
p[a + 1] = y ^ ((p[c + 1] >> 8) | (p[c + 2] << 24)) ^ (p[d + 1] << 14);
y = p[a] ^ (p[a] << 24) ^ ((p[b] >> 5) & 0xf7fefffdU);
p[a] = y ^ ((p[c] >> 8) | (p[c + 1] << 24)) ^ (p[d] << 14);
c = d; d = a; a += 4; b += 4;
if (b == 40) b = 0;
} while (a != 40);
}
void PeriodCertification()
{
uint work, inner = 0; int i, j;
index = 40; range = 0; coin_bits = 0; byte_pos = 0;
for (i = 0; i < 4; i++) inner ^= x[i] & ParityData[i];
for (i = 16; i > 0; i >>= 1) inner ^= inner >> i;
inner &= 1;
if (inner == 1) return;
for (i = 0; i < 4; i++) for (j = 0, work = 1; j < 32; j++, work <<= 1) if ((work & ParityData[i]) != 0) { x[i] ^= work; return; }
}
public void InitMt(uint s)
{
unchecked
{
x[0] = s;
for (uint p = 1; p < 40; p++) x[p] = s = 1812433253 * (s ^ (s >> 30)) + p;
PeriodCertification();
}
}
public RandomSFMT(uint s) { InitMt(s); }
public void InitMtEx(uint[] init_key)
{
uint r, i, j, c, key_len = (uint)init_key.Length;
unchecked
{
for (i = 0; i < 40; i++) x[i] = 0x8b8b8b8b;
if (key_len + 1 > 40) c = key_len + 1; else c = 40;
r = x[0] ^ x[17] ^ x[39]; r = (r ^ (r >> 27)) * 1664525;
x[17] += r; r += key_len; x[22] += r; x[0] = r; c--;
for (i = 1, j = 0; j < c && j < key_len; j++)
{
r = x[i] ^ x[(i + 17) % 40] ^ x[(i + 39) % 40];
r = (r ^ (r >> 27)) * 1664525; x[(i + 17) % 40] += r;
r += init_key[j] + i; x[(i + 22) % 40] += r;
x[i] = r; i = (i + 1) % 40;
}
for (; j < c; j++)
{
r = x[i] ^ x[(i + 17) % 40] ^ x[(i + 39) % 40];
r = (r ^ (r >> 27)) * 1664525; x[(i + 17) % 40] += r; r += i;
x[(i + 22) % 40] += r; x[i] = r; i = (i + 1) % 40;
}
for (j = 0; j < 40; j++)
{
r = x[i] + x[(i + 17) % 40] + x[(i + 39) % 40];
r = (r ^ (r >> 27)) * 1566083941; x[(i + 17) % 40] ^= r;
r -= i; x[(i + 22) % 40] ^= r; x[i] = r; i = (i + 1) % 40;
}
PeriodCertification();
}
}
public RandomSFMT(uint[] init_key) { InitMtEx(init_key); }
public RandomSFMT() : this((uint)(DateTime.Now.Ticks & 0xffffffff)) { }
public uint NextMt() { if (index == 40) { GenRandAll(); index = 0; } return x[index++]; }
public int NextInt(int n) => (int)(n * (1.0 / 4294967296.0) * NextMt());
public double NextUnif() { uint z = NextMt() >> 11, y = NextMt(); return (y * 2097152.0 + z) * (1.0 / 9007199254740992.0); }
public int NextBit() { if (--coin_bits == -1) { coin_bits = 31; return (int)(coin_save = NextMt()) & 1; } else return (int)(coin_save >>= 1) & 1; }
public int NextByte() { if (--byte_pos == -1) { byte_pos = 3; return (int)(byte_save = NextMt()) & 255; } else return (int)(byte_save >>= 8) & 255; }
public override int Next(int maxValue) => Next(0, maxValue);
protected override double Sample() => NextUnif();
public override double NextDouble() => NextUnif();
public override int Next() => 1 + NextIntEx(int.MaxValue);
public override void NextBytes(byte[] buffer) { for (var i = 0; i < buffer.Length; i++) buffer[i] = (byte)NextByte(); }
public override int Next(int min, int max) => min + NextIntEx(max - min);
public int NextIntEx(int range_)
{
uint y_, base_, remain_; int shift_;
if (range_ <= 0) return 0;
if (range_ != range)
{
bse = (uint)(range = range_);
for (shift = 0; bse <= (1UL << 30); shift++) bse <<= 1;
}
while (true)
{
y_ = NextMt() >> 1;
if (y_ < bse) return (int)(y_ >> shift);
base_ = bse; shift_ = shift; y_ -= base_;
remain_ = (1U << 31) - base_;
for (; remain_ >= (uint)range_; remain_ -= base_)
{
for (; base_ > remain_; base_ >>= 1) shift_--;
if (y_ < base_) return (int)(y_ >> shift_);
else y_ -= base_;
}
}
}
}
| PHP | <?php
ini_set('error_reporting', E_ALL & ~E_NOTICE);
// define('DEBUG', true);
define('DEBUG', false);
fscanf(STDIN, "%d %d %d", $N, $A, $B);
for ($i = 0; $i < $N; $i++) {
fscanf(STDIN, "%d", $h[$i]);
}
rsort($h);
$total = array_sum($h);
$mmax = ceil($h[0] / $B);
$mmin = ceil($total / ($A + $B * ($N - 1)));
if (DEBUG) echo "mmin:{$mmin} mmax:{$mmax}\n";
$mmin--;
// exit;
$ans[$mmax] = true;
$ans[$mmin] = false;
// for ($i = $mmin; $i <= $mmax; $i++) {
// printf("%d %s\n", $i, getEnable($i));
// }
while (true) {
$mid = ceil(($mmin + $mmax) / 2);
$result = getEnable($mid);
if (DEBUG) printf("%d %d %d %s\n", $mid, $mmin, $mmax, $result);
$ans[$mid] = $result;
if ($result === false) {
if ($ans[$mid+1] === true) {
exit(($mid + 1) . "\n");
}
$mmin = $mid;
} else {
if ($ans[$mid-1] === false) {
exit($mid . "\n");
}
$mmax = $mid;
}
foreach ($ans as $key => $val) {
if (DEBUG) echo "RRR {$key} {$val}\n";
}
// sleep(1);
}
function getEnable($x) {
global $N, $A, $B, $h;
$xx = $x;
$base = $B * $x;
for ($i = 0; $i < $N; $i++) {
if ($base >= $h[$i]) {
return true;
}
$rest = $h[$i] - $base;
$need = ceil($rest / ($A - $B));
$x -= $need;
if ($x < 0) {
return false;
}
}
return true;
} | Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using Problem = Tmp.Problem;
namespace Tmp
{
using static Func;
using static Math;
using static Console;
//using GeometryLong;
class Problem : IDisposable
{
bool IsGCJ;
int Repeat;
Scanner sc;
Printer pr;
public Problem(bool isGCJ, Scanner scanner, Printer printer)
{
sc = scanner;
pr = printer;
IsGCJ = isGCJ;
if (isGCJ) Repeat = sc.Get<int>();
else Read();
}
public Problem(bool isGCJ) : this(isGCJ, new Scanner(), new Printer()) { }
public Problem(bool isGCJ, Scanner scanner) : this(isGCJ, scanner, new Printer()) { }
public Problem(bool isGCJ, Printer printer) : this(isGCJ, new Scanner(), printer) { }
public void Solve()
{
if (IsGCJ) for (var i = 0; i < Repeat; i++) { Read(); pr.Write("Case #" + (i + 1) + ": "); SolveOne(); }
else SolveOne();
}
public void Dispose()
{
sc.Dispose();
pr.Dispose();
}
public int Size => 1;
public const long Mod = 1000000007;
//public const long Mod = 924844033;
RandomSFMT rand = Program.rand;
int N, A, B;
int[] h;
void Read()
{
sc.Read(out N, out A, out B);
h = sc.ReadManyLines<int>(N);
}
void SolveOne()
{
pr.WriteLine(FirstBinary(0, Inf, OK));
}
bool OK(int n)
{
var s = 0L;
var d = A - B;
foreach (var p in h)
{
var l = p - (long)n * B;
if (l >= 0) s += (l + d - 1) / d;
if (s > n) return false;
}
return s <= n;
}
int[] SuffixArray(string S)
{
var N = S.Length;
var sa = new int[N + 1];
var r = new int[N + 1];
for (var i = 0; i <= N; i++)
{
sa[i] = i;
r[i] = i < N ? S[i] : -1;
}
var k = 1;
Comparison<int> comp = (i, j) =>
{
if (r[i] != r[j]) return r[i] - r[j];
var a = i + k <= N ? r[i + k] : -1;
var b = j + k <= N ? r[j + k] : -1;
return a - b;
};
for (; k <= N; k *= 2)
{
Array.Sort(sa, comp);
var tmp = new int[N + 1];
for (var i = 1; i <= N; i++) tmp[sa[i]] = tmp[sa[i - 1]] + (comp(sa[i - 1], sa[i]) < 0 ? 1 : 0);
r = tmp;
}
return sa;
}
}
class RangeSegmentTree
{
int N2;
int[] seg, unif;
public RangeSegmentTree(int N)
{
N2 = 1;
while (N2 < N) N2 <<= 1;
seg = new int[2 * N2 - 1];
unif = new int[2 * N2 - 1];
}
void LazyEvaluate(int node)
{
if (unif[node] == 0) return;
seg[node] += unif[node];
if (node < N2 - 1)
{
unif[2 * node + 1] += unif[node];
unif[2 * node + 2] += unif[node];
}
unif[node] = 0;
}
void Update(int node) => seg[node] = seg[2 * node + 1] + seg[2 * node + 2];
public void AddRange(int from, int to, int value) => AddRange(from, to, value, 0, 0, N2);
void AddRange(int from, int to, int value, int node, int l, int r)
{
if (from <= l && r <= to) unif[node] += value;
else if (l < to && from < r)
{
AddRange(from, to, value, 2 * node + 1, l, (l + r) >> 1);
AddRange(from, to, value, 2 * node + 2, (l + r) >> 1, r);
Update(node);
}
LazyEvaluate(node);
}
public int this[int n] { get { return Sum(n, n + 1); } set { AddRange(n, n + 1, value - this[n]); } }
public int Sum(int from, int to) => Sum(from, to, 0, 0, N2);
int Sum(int from, int to, int node, int l, int r)
{
LazyEvaluate(node);
if (to <= l || r <= from) return 0;
else if (from <= l && r <= to) return seg[node];
else return Sum(from, to, 2 * node + 1, l, (l + r) >> 1) + Sum(from, to, 2 * node + 2, (l + r) >> 1, r);
}
}
class SlideMaximum
{
long[] a;
Deque<int> deq;
public SlideMaximum(long[] x) { a = x; deq = new Deque<int>(); }
public void Add(int index)
{
while (deq.Count > 0 && a[deq.PeekBack()] <= a[index]) deq.PopBack();
deq.PushBack(index);
}
public void Remove(int index)
{
if (deq.Count > 0 && deq.PeekFront() == index) deq.PopFront();
}
public long Maximum => a[deq.PeekFront()];
}
class SegmentTreeX
{
public const long Unit = -InfL;
int N2;
long[] seg, unif;
public SegmentTreeX(int N)
{
N2 = 1;
while (N2 < N) N2 <<= 1;
seg = new long[2 * N2 - 1];
unif = new long[2 * N2 - 1];
for (var i = 0; i < 2 * N2 - 1; i++) seg[i] = unif[i] = Unit;
}
void LazyEvaluate(int node)
{
if (unif[node] != Unit)
{
seg[node] = Math.Max(seg[node], unif[node]);
if (node < N2 - 1)
{
unif[2 * node + 1] = Math.Max(unif[2 * node + 1], unif[node]);
unif[2 * node + 2] = Math.Max(unif[2 * node + 2], unif[node]);
}
unif[node] = Unit;
}
}
void Update(int node) => seg[node] = Math.Max(seg[2 * node + 1], seg[2 * node + 2]);
public void Maximize(int from, int to, long value) => Maximize(from, to, value, 0, 0, N2);
void Maximize(int from, int to, long value, int node, int l, int r)
{
if (from <= l && r <= to) unif[node] = Math.Max(unif[node], value);
else if (l < to && from < r)
{
Maximize(from, to, value, 2 * node + 1, l, (l + r) >> 1);
Maximize(from, to, value, 2 * node + 2, (l + r) >> 1, r);
Update(node);
}
LazyEvaluate(node);
}
public long this[int n] { get { return Max(n, n + 1); } set { Maximize(n, n + 1, value); } }
public long Max(int from, int to) => Max(from, to, 0, 0, N2);
long Max(int from, int to, int node, int l, int r)
{
LazyEvaluate(node);
if (to <= l || r <= from) return Unit;
else if (from <= l && r <= to) return seg[node];
else return Math.Max(Max(from, to, 2 * node + 1, l, (l + r) >> 1), Max(from, to, 2 * node + 2, (l + r) >> 1, r));
}
}
}
class Treap<T>
{
Random rand;
Comparison<T> comp;
class Node
{
public T value;
public int size;
private int priority;
public Node left, right;
public Treap<T> treap;
public Node(Treap<T> treap, T value) { this.treap = treap; this.value = value; priority = treap.rand.Next(); size = 1; }
public Node Update() { size = 1 + Size(left) + Size(right); return this; }
public static int Size(Node t) => t?.size ?? 0;
public static Node Merge(Node l, Node r)
{
if (l == null) return r;
if (r == null) return l;
if (l.priority < r.priority)
{
l.right = Merge(l.right, r);
return l.Update();
}
else
{
r.left = Merge(r.left, l);
return r.Update();
}
}
// [0,N) => [0,k) + [k,N)
public static Tuple<Node, Node> Split(Node t, int k)
{
if (t == null) return new Tuple<Node, Node>(null, null);
if (k <= Size(t.left))
{
var s = Split(t.left, k);
t.left = s.Item2;
return new Tuple<Node, Node>(s.Item1, t.Update());
}
else
{
var s = Split(t.right, k - Size(t.left) - 1);
t.right = s.Item1;
return new Tuple<Node, Node>(t.Update(), s.Item2);
}
}
// [0,k) + [k,N) => [0,k) + (new node) + [k+1,N)
public static Node Insert(Node t, int k, T val)
{
var n = new Node(t.treap, val);
var s = Split(t, k);
return Merge(Merge(s.Item1, n), s.Item2);
}
// [0,k) + k + [k+1,N) => [0,k) + [k+1,N)
public static Node Erase(Node t, int k)
{
var s1 = Split(t, k + 1);
var s2 = Split(s1.Item1, k);
return Merge(s2.Item1, s1.Item2);
}
}
}
class RMQI
{
int N2;
int[] segtree;
int[] position;
public RMQI(int N) : this(new int[N]) { }
public RMQI(int[] array)
{
N2 = 1;
while (N2 < array.Length) N2 <<= 1;
segtree = new int[2 * N2 - 1];
position = new int[2 * N2 - 1];
for (var i = 0; i < 2 * N2 - 1; i++) segtree[i] = Func.Inf;
for (var i = 0; i < array.Length; i++) { segtree[i + N2 - 1] = array[i]; position[i + N2 - 1] = i; }
for (var i = N2 - 2; i >= 0; i--) SetMin(i);
}
void SetMin(int i)
{
int l = 2 * i + 1, r = 2 * i + 2;
int a = segtree[l], b = segtree[r];
if (a <= b) { segtree[i] = a; position[i] = position[l]; }
else { segtree[i] = b; position[i] = position[r]; }
}
Tuple<int, int> Merge(Tuple<int, int> a, Tuple<int, int> b) => a.Item1 <= b.Item1 ? a : b;
public void Update(int index, int value)
{
index += N2 - 1;
segtree[index] = value;
while (index > 0) SetMin(index = (index - 1) / 2);
}
public int this[int n] { get { return Min(n, n + 1).Item1; } set { Update(n, value); } }
// min, pos
public Tuple<int, int> Min(int from, int to) => Min(from, to, 0, 0, N2);
Tuple<int, int> Min(int from, int to, int node, int l, int r)
{
if (to <= l || r <= from) return new Tuple<int, int>(Func.Inf, N2);
else if (from <= l && r <= to) return new Tuple<int, int>(segtree[node], position[node]);
else return Merge(Min(from, to, 2 * node + 1, l, (l + r) >> 1), Min(from, to, 2 * node + 2, (l + r) >> 1, r));
}
}
static class Hoge
{
public static T Peek<T>(this IEnumerable<T> set)
{
foreach (var x in set) return x;
return default(T);
}
}
interface ISegmentTree<T> where T : IComparable<T>
{
void Add(int from, int to, T value);
T Min(int from, int to);
}
class SegmentTree2 : ISegmentTree<long>
{
int N;
long[] a;
public SegmentTree2(int N) : this(new long[N]) { }
public SegmentTree2(long[] a) { N = a.Length; this.a = a.ToArray(); }
public void Add(int from, int to, long value) { for (var i = from; i < to; i++) a[i] += value; }
public long Min(int from, int to) { var s = Func.InfL; for (var i = from; i < to; i++) s = Math.Min(s, a[i]); return s; }
}
class SegmentTree3 : ISegmentTree<long>
{
public const long Unit = Func.InfL;
public readonly Func<long, long, long> Operator = Math.Min;
int N2;
long[] seg, unif;
public SegmentTree3(int N) : this(new long[N]) { }
public SegmentTree3(long[] a)
{
N2 = 1;
while (N2 < a.Length) N2 <<= 1;
seg = new long[2 * N2 - 1];
unif = new long[2 * N2 - 1];
for (var i = a.Length + N2 - 1; i < 2 * N2 - 1; i++) seg[i] = Unit;
for (var i = 0; i < a.Length; i++) seg[i + N2 - 1] = a[i];
for (var i = N2 - 2; i >= 0; i--) Update(i);
}
void LazyEvaluate(int node)
{
if (unif[node] != 0)
{
seg[node] += unif[node];
if (node < N2 - 1) { unif[2 * node + 1] += unif[node]; unif[2 * node + 2] += unif[node]; }
unif[node] = 0;
}
}
void Update(int node) => seg[node] = Operator(seg[2 * node + 1], seg[2 * node + 2]);
public void Add(int from, int to, long value) => Add(from, to, value, 0, 0, N2);
void Add(int from, int to, long value, int node, int l, int r)
{
if (from <= l && r <= to) unif[node] += value;
else if (l < to && from < r)
{
Add(from, to, value, 2 * node + 1, l, (l + r) >> 1);
Add(from, to, value, 2 * node + 2, (l + r) >> 1, r);
Update(node);
}
LazyEvaluate(node);
}
public long this[int n] { get { return Min(n, n + 1); } set { Add(n, n + 1, value - this[n]); } }
public long Min(int from, int to) => Min(from, to, 0, 0, N2);
long Min(int from, int to, int node, int l, int r)
{
LazyEvaluate(node);
if (to <= l || r <= from) return Unit;
else if (from <= l && r <= to) return seg[node];
else return Operator(Min(from, to, 2 * node + 1, l, (l + r) >> 1), Min(from, to, 2 * node + 2, (l + r) >> 1, r));
}
}
class SegmentTree : ISegmentTree<long>
{
int N2;
long[] seg, unif;
public SegmentTree(int N) : this(new long[N]) { }
public SegmentTree(long[] a)
{
N2 = 1;
while (N2 < a.Length) N2 <<= 1;
seg = new long[2 * N2 - 1];
unif = new long[2 * N2 - 1];
for (var i = a.Length + N2 - 1; i < 2 * N2 - 1; i++) seg[i] = Func.InfL;
for (var i = 0; i < a.Length; i++) seg[i + N2 - 1] = a[i];
for (var i = N2 - 2; i >= 0; i--) seg[i] = Math.Min(seg[2 * i + 1], seg[2 * i + 2]);
}
public void Add(int from, int to, long value) => Add(from, to, value, 0, 0, N2);
void Add(int from, int to, long value, int node, int l, int r)
{
if (to <= l || r <= from) return;
else if (from <= l && r <= to) unif[node] += value;
else
{
Add(from, to, value, 2 * node + 1, l, (l + r) >> 1);
Add(from, to, value, 2 * node + 2, (l + r) >> 1, r);
seg[node] = Math.Min(seg[2 * node + 1] + unif[2 * node + 1], seg[2 * node + 2] + unif[2 * node + 2]);
}
}
public long this[int n] { get { return Min(n, n + 1); } set { Add(n, n + 1, value - this[n]); } }
public long Min(int from, int to) => Min(from, to, 0, 0, N2);
long Min(int from, int to, int node, int l, int r)
{
if (to <= l || r <= from) return Func.InfL;
else if (from <= l && r <= to) return seg[node] + unif[node];
else return Math.Min(Min(from, to, 2 * node + 1, l, (l + r) >> 1), Min(from, to, 2 * node + 2, (l + r) >> 1, r)) + unif[node];
}
}
class Eq : IEqualityComparer<List<int>>
{
public bool Equals(List<int> x, List<int> y)
{
if (x == null || y == null) return x == y;
if (x.Count != y.Count) return false;
for (var i = 0; i < x.Count; i++) if (x[i] != y[i]) return false;
return true;
}
public int GetHashCode(List<int> obj)
{
var x = obj.Count.GetHashCode();
foreach (var i in obj) x ^= i.GetHashCode();
return x;
}
}
class MultiSortedSet<T> : IEnumerable<T>, ICollection<T>
{
public IComparer<T> Comparer { get; private set; }
private SortedSet<T> keys;
private Dictionary<T, int> mult;
public int Multiplicity(T item) => keys.Contains(item) ? mult[item] : 0;
public int this[T item]
{
get { return Multiplicity(item); }
set
{
Debug.Assert(value >= 0);
if (value == 0) { if (keys.Contains(item)) Remove(item); }
else
{
Count += value - mult[item];
mult[item] = value;
}
}
}
public int Count { get; private set; }
public MultiSortedSet(IComparer<T> comp)
{
keys = new SortedSet<T>(Comparer = comp);
mult = new Dictionary<T, int>();
}
public MultiSortedSet(Comparison<T> comp) : this(Comparer<T>.Create(comp)) { }
public MultiSortedSet() : this(Func.DefaultComparison<T>()) { }
public void Add(T item) => Add(item, 1);
private void Add(T item, int num)
{
Count += num;
if (!keys.Contains(item)) { keys.Add(item); mult.Add(item, num); }
else mult[item] += num;
}
public void AddRange(IEnumerable<T> list) { foreach (var x in list) Add(x); }
public bool Remove(T item)
{
if (!keys.Contains(item)) return false;
Count--;
if (mult[item] == 1) { keys.Remove(item); mult.Remove(item); }
else mult[item]--;
return true;
}
public bool Overlaps(IEnumerable<T> other) => keys.Overlaps(other);
public bool IsSupersetOf(IEnumerable<T> other) => keys.IsSupersetOf(other);
public bool IsSubsetOf(IEnumerable<T> other) => keys.IsSubsetOf(other);
public bool IsProperSubsetOf(IEnumerable<T> other) => keys.IsProperSubsetOf(other);
public bool IsProperSupersetOf(IEnumerable<T> other) => keys.IsProperSupersetOf(other);
public void ExceptWith(IEnumerable<T> other) { foreach (var x in other) if (Contains(x)) Remove(x); }
public void IntersectWith(IEnumerable<T> other)
{
var next = new MultiSortedSet<T>(Comparer);
foreach (var x in other) if (Contains(x) && !next.Contains(x)) next.Add(x, mult[x]);
keys = next.keys; mult = next.mult;
}
public void CopyTo(T[] array) => CopyTo(array, 0);
public void CopyTo(T[] array, int index) { foreach (var item in array) array[index++] = item; }
public void CopyTo(T[] array, int index, int count) { var i = 0; foreach (var item in array) { if (i++ >= count) return; array[index++] = item; } }
public bool Contains(T item) => keys.Contains(item);
public void Clear() { keys.Clear(); mult.Clear(); Count = 0; }
public IEnumerator<T> Reverse() { foreach (var x in keys.Reverse()) for (var i = 0; i < mult[x]; i++) yield return x; }
public IEnumerator<T> GetEnumerator() { foreach (var x in keys) for (var i = 0; i < mult[x]; i++) yield return x; }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public T Max => keys.Max;
public T Min => keys.Min;
public bool IsReadOnly => false;
}
class SkewHeap<T> : IEnumerable<T>
{
class Node : IEnumerable<T>
{
public Node l, r;
public T val;
public Node(T x) { l = r = null; val = x; }
public IEnumerator<T> GetEnumerator()
{
if (l != null) foreach (var x in l) yield return x;
yield return val;
if (r != null) foreach (var x in r) yield return x;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public int Count { get; private set; }
Node head;
Comparison<T> comp;
public bool IsEmpty => head != null;
public SkewHeap(Comparison<T> c) { comp = c; Count = 0; }
public SkewHeap() : this(Func.DefaultComparison<T>()) { }
public SkewHeap(IComparer<T> c) : this(Func.ToComparison(c)) { }
private SkewHeap(Comparison<T> c, Node h) : this(c) { head = h; }
public void Push(T x) { var n = new Node(x); head = Meld(head, n); Count++; }
public T Peek() => head.val;
public T Pop() { var x = head.val; head = Meld(head.l, head.r); Count--; return x; }
// a.comp must be equivalent to b.comp
// a, b will be destroyed
public static SkewHeap<T> Meld(SkewHeap<T> a, SkewHeap<T> b) => new SkewHeap<T>(a.comp, a.Meld(a.head, b.head));
public void MeldWith(SkewHeap<T> a) => head = Meld(head, a.head);
Node Meld(Node a, Node b)
{
if (a == null) return b;
else if (b == null) return a;
if (comp(a.val, b.val) > 0) Func.Swap(ref a, ref b);
a.r = Meld(a.r, b);
Func.Swap(ref a.l, ref a.r);
return a;
}
public IEnumerator<T> GetEnumerator() => head.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => (IEnumerator)GetEnumerator();
}
// [0, Size) の整数の集合を表す
class BITSet : BinaryIndexedTree
{
public BITSet(int size) : base(size) { }
public void Add(int item) => Add(item, 1);
public bool Contains(int item) => Sum(item, item + 1) > 0;
public int Count(int item) => Sum(item, item + 1);
// 順位 = item が小さい方から何番目か(0-indexed)
public int GetRank(int item) => Sum(0, item);
public void Remove(int item) => Add(item, -1);
public void RemoveAll(int item) => Add(item, -Count(item));
// 0-indexed で順位が rank のものを求める
// ない場合は Size が返る
public int GetValue(int rank) => Func.FirstBinary(0, Size, t => Sum(0, t + 1) >= rank + 1);
}
class RangeBIT
{
public int N { get; private set; }
long[,] bit;
public RangeBIT(int N) { bit = new long[2, this.N = N + 1]; }
public RangeBIT(int[] array) : this(array.Length)
{
for (var i = 1; i < N; i++) bit[0, i] = array[i - 1];
for (var i = 1; i < N - 1; i++) if (i + (i & (-i)) < N) bit[0, i + (i & (-i))] += bit[0, i];
}
public RangeBIT(long[] array) : this(array.Length)
{
for (var i = 1; i < N; i++) bit[0, i] = array[i - 1];
for (var i = 1; i < N - 1; i++) if (i + (i & (-i)) < N) bit[0, i + (i & (-i))] += bit[0, i];
}
public void Add(int from, int to, long value)
{
Add2(0, from + 1, -value * from);
Add2(1, from + 1, value);
Add2(0, to + 1, value * to);
Add2(1, to + 1, -value);
}
void Add2(int which, int i, long value) { while (i < N) { bit[which, i] += value; i += i & (-i); } }
long Sum(int to) => Sum2(0, to) + Sum2(1, to) * to;
public long Sum(int from, int to) => Sum(to) - Sum(from);
long Sum2(int which, int i) { var sum = 0L; while (i > 0) { sum += bit[which, i]; i -= i & (-i); } return sum; }
}
class RMQ
{
int N2;
int[] segtree;
public RMQ(int N) : this(new int[N]) { }
public RMQ(int[] array)
{
N2 = 1;
while (N2 < array.Length) N2 <<= 1;
segtree = new int[2 * N2 - 1];
for (var i = 0; i < 2 * N2 - 1; i++) segtree[i] = Func.Inf;
for (var i = 0; i < array.Length; i++) segtree[i + N2 - 1] = array[i];
for (var i = N2 - 2; i >= 0; i--) segtree[i] = Math.Min(segtree[2 * i + 1], segtree[2 * i + 2]);
}
public void Update(int index, int value)
{
index += N2 - 1;
segtree[index] = value;
while (index > 0)
{
index = (index - 1) / 2;
segtree[index] = Math.Min(segtree[index * 2 + 1], segtree[index * 2 + 2]);
}
}
public int this[int n] { get { return Min(n, n + 1); } set { Update(n, value); } }
public int Min(int from, int to) => Min(from, to, 0, 0, N2);
int Min(int from, int to, int node, int l, int r)
{
if (to <= l || r <= from) return Func.Inf;
else if (from <= l && r <= to) return segtree[node];
else return Math.Min(Min(from, to, 2 * node + 1, l, (l + r) >> 1), Min(from, to, 2 * node + 2, (l + r) >> 1, r));
}
}
class Program
{
public static RandomSFMT rand = new RandomSFMT();
public static bool IsJudgeMode = true;
public static bool IsGCJMode = false;
public static bool IsSolveCreated = true;
static void Main()
{
if (IsJudgeMode)
if (IsGCJMode) using (var problem = new Problem(true, new Scanner("C-large-practice.in.txt"), new Printer("output.txt"))) problem.Solve();
else using (var problem = new Problem(false, new Printer())) problem.Solve();
else
{
var num = 1;
var size = 0;
var time = 0m;
for (var tmp = 0; tmp < num; tmp++)
{
using (var P = IsSolveCreated ? new Problem(false, new Scanner("input.txt"), new Printer()) : new Problem(false))
{
size = P.Size;
time += Func.MeasureTime(() => P.Solve());
}
}
Console.WriteLine("{0}, {1}ms", size, time / num);
}
}
}
class BinaryIndexedTree3D
{
public int X { get; private set; }
public int Y { get; private set; }
public int Z { get; private set; }
int[,,] bit;
public BinaryIndexedTree3D(int X, int Y, int Z)
{
this.X = X; this.Y = Y; this.Z = Z;
bit = new int[X + 1, Y + 1, Z + 1];
}
public BinaryIndexedTree3D(int[,,] array)
: this(array.GetLength(0), array.GetLength(1), array.GetLength(2))
{
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) for (var z = 0; z < Z; z++) Add(x, y, z, array[x, y, z]);
}
public void Add(int x, int y, int z, int value)
{
for (var i = x + 1; i <= X; i += i & (-i)) for (var j = y + 1; j <= Y; j += j & (-j)) for (var k = z + 1; k <= Z; k += k & (-k)) bit[i, j, k] += value;
}
public int Sum(int x0, int y0, int z0, int x1, int y1, int z1)
=> Sum(x1, y1, z1) - Sum(x0, y1, z1) - Sum(x1, y0, z1) - Sum(x1, y1, z0) + Sum(x1, y0, z0) + Sum(x0, y1, z0) + Sum(x0, y0, z1) - Sum(x0, y0, z0);
int Sum(int x, int y, int z)
{
var sum = 0;
for (var i = x; i > 0; i -= i & (-i)) for (var j = y; j > 0; j -= j & (-j)) for (var k = y; k > 0; k -= k & (-k)) sum += bit[i, j, k];
return sum;
}
}
class BinaryIndexedTree2D
{
public int X { get; private set; }
public int Y { get; private set; }
int[,] bit;
public BinaryIndexedTree2D(int X, int Y)
{
this.X = X; this.Y = Y;
bit = new int[X + 1, Y + 1];
}
public BinaryIndexedTree2D(int[,] array)
: this(array.GetLength(0), array.GetLength(1))
{
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) Add(x, y, array[x, y]);
}
public void Add(int x, int y, int value) { for (var i = x + 1; i <= X; i += i & (-i)) for (var j = y + 1; j <= Y; j += j & (-j)) bit[i, j] += value; }
public int Sum(int x0, int y0, int x1, int y1) => Sum(x0, y0) + Sum(x1, y1) - Sum(x0, y1) - Sum(x1, y0);
int Sum(int x, int y) { var sum = 0; for (var i = x; i > 0; i -= i & (-i)) for (var j = y; j > 0; j -= j & (-j)) sum += bit[i, j]; return sum; }
}
class BinaryIndexedTree
{
public int Size { get; private set; }
int[] bit;
public BinaryIndexedTree(int size)
{
Size = size;
bit = new int[size + 1];
}
public BinaryIndexedTree(int[] array) : this(array.Length)
{
for (var i = 0; i < Size; i++) bit[i + 1] = array[i];
for (var i = 1; i < Size; i++) if (i + (i & (-i)) <= Size) bit[i + (i & (-i))] += bit[i];
}
// index is 0-indexed
public void Add(int index, int value) { for (var i = index + 1; i <= Size; i += i & (-i)) bit[i] += value; }
// from, to is 0-indexed
// from is inclusive, to is exclusive
public int Sum(int from, int to) => Sum(to) - Sum(from);
int Sum(int to) { var sum = 0; for (var i = to; i > 0; i -= i & (-i)) sum += bit[i]; return sum; }
}
class Amoeba
{
public const int Dimension = 2;
public const double Alpha = 1; // reflection
public const double Beta = 1 + 2.0 / Dimension; // expansion
public const double Gamma = 0.75 - 0.5 / Dimension; // contraction
public const double Delta = 1 - 1.0 / Dimension; // shrink
public Pair<AmoebaState, double>[] a;
public AmoebaState m;
public void Initiate()
{
Array.Sort(a, (x, y) => x.Second.CompareTo(y.Second));
m = new AmoebaState();
for (var i = 0; i < Dimension; i++) m.Add(a[i].First);
m.Multiply(1.0 / Dimension);
}
void PartialSort(int i, int j) { if (a[i].Second > a[j].Second) a.Swap(i, j); }
void Accept(AmoebaState point, double value)
{
var tmp = Func.FirstBinary(0, Dimension, x => a[x].Second >= value);
if (tmp != Dimension) m.Add((point - a[Dimension - 1].First) / Dimension);
for (var i = Dimension; i > tmp; i--) a[i] = a[i - 1];
a[tmp].First = point;
a[tmp].Second = value;
}
public void Search()
{
var r = m + Alpha * (m - a[Dimension].First);
var fr = r.Func();
if (a[0].Second <= fr && fr < a[Dimension - 1].Second) { Accept(r, fr); return; }
var diff = r - m;
if (fr < a[0].Second)
{
var e = m + Beta * diff;
var fe = e.Func();
if (fe < fr) Accept(e, fe);
else Accept(r, fr);
}
else
{
var tmp = Gamma * diff;
var o = m + tmp;
var fo = o.Func();
var i = m - tmp;
var fi = i.Func();
if (fi < fo) { o = i; fo = fi; }
if (fo < a[Dimension - 1].Second) Accept(o, fo);
else Shrink();
}
}
void Shrink()
{
var tmp = (1 - Delta) * a[0].First;
for (var i = 1; i <= Dimension; i++) { a[i].First.Multiply(Delta); a[i].First.Add(tmp); a[i].Second = a[i].First.Func(); }
Initiate();
}
}
class AmoebaState
{
public static int Dimension = 2;
public double[] vec;
public AmoebaState() { vec = new double[Dimension]; }
public AmoebaState(params double[] elements) : this() { elements.CopyTo(vec, 0); }
public double this[int n] { get { return vec[n]; } set { vec[n] = value; } }
public void Multiply(double r) { for (var i = 0; i < Dimension; i++) vec[i] *= r; }
public void Add(AmoebaState v) { for (var i = 0; i < Dimension; i++) vec[i] += v.vec[i]; }
public static AmoebaState operator +(AmoebaState p) => new AmoebaState(p.vec);
public static AmoebaState operator -(AmoebaState p) { var tmp = new AmoebaState(p.vec); tmp.Multiply(-1); return tmp; }
public static AmoebaState operator /(AmoebaState p, double r) { var tmp = new AmoebaState(p.vec); tmp.Multiply(1 / r); return tmp; }
public static AmoebaState operator *(double r, AmoebaState p) { var tmp = new AmoebaState(p.vec); tmp.Multiply(r); return tmp; }
public static AmoebaState operator *(AmoebaState p, double r) => r * p;
public static AmoebaState operator +(AmoebaState p, AmoebaState q) { var tmp = +p; tmp.Add(q); return tmp; }
public static AmoebaState operator -(AmoebaState p, AmoebaState q) { var tmp = -q; tmp.Add(p); return tmp; }
public double Func()
{
return 0;//P.Func(vec[0], vec[1]);
}
public static Problem P;
}
class BucketList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable
{
public Comparison<T> Comp { get; protected set; }
public int BucketSize = 20;
public int Count { get { var sum = 0; var bucket = Head; while (bucket != null) { sum += bucket.Count; bucket = bucket.Next; } return sum; } }
public int NumOfBucket { get; protected set; }
public Bucket<T> Head { get; protected set; }
public Bucket<T> Tail { get; protected set; }
public BucketList(IComparer<T> comp) : this(comp.ToComparison()) { }
public BucketList(Comparison<T> comp = null) { Head = null; Tail = null; NumOfBucket = 0; Comp = comp ?? Func.DefaultComparison<T>(); }
protected void AddAfter(Bucket<T> pos, Bucket<T> bucket)
{
Debug.Assert(bucket != null && bucket.Count > 0 && pos != null && pos.Parent == this && Comp(pos.Tail.Value, bucket.Head.Value) <= 0
&& (pos.Next == null || Comp(pos.Next.Head.Value, bucket.Tail.Value) >= 0));
bucket.Parent = this;
bucket.Prev = pos;
bucket.Next = pos.Next;
if (pos != Tail) pos.Next.Prev = bucket;
else Tail = bucket;
pos.Next = bucket;
NumOfBucket++;
}
protected void AddBefore(Bucket<T> pos, Bucket<T> bucket)
{
Debug.Assert(bucket != null && bucket.Count > 0 && pos != null && pos.Parent == this && Comp(pos.Head.Value, bucket.Tail.Value) >= 0
&& (pos.Prev == null || Comp(pos.Prev.Tail.Value, bucket.Head.Value) <= 0));
bucket.Parent = this;
bucket.Prev = pos.Prev;
bucket.Next = pos;
if (pos != Head) pos.Prev.Next = bucket;
else Head = bucket;
pos.Prev = bucket;
NumOfBucket++;
}
protected void AddAfter(Bucket<T> bucket, BucketNode<T> node)
{
Debug.Assert(node != null && bucket != null && bucket.Parent == this && node.Parent.Parent == this && Comp(bucket.Tail.Value, node.Value) <= 0
&& (bucket.Next == null || Comp(bucket.Next.Head.Value, node.Value) >= 0));
var tmp = new Bucket<T>(this, bucket, bucket.Next);
tmp.InitiateWith(node);
if (bucket != Tail) bucket.Next.Prev = tmp;
else Tail = tmp;
bucket.Next = tmp;
NumOfBucket++;
}
protected void AddBefore(Bucket<T> bucket, BucketNode<T> node)
{
Debug.Assert(node != null && bucket != null && bucket.Parent == this && node.Parent.Parent == this && Comp(bucket.Head.Value, node.Value) >= 0
&& (bucket.Prev == null || Comp(bucket.Prev.Tail.Value, node.Value) <= 0));
var tmp = new Bucket<T>(this, bucket.Prev, bucket);
tmp.InitiateWith(node);
if (bucket != Head) bucket.Prev.Next = tmp;
else Head = tmp;
bucket.Prev = tmp;
NumOfBucket++;
}
public void AddAfter(BucketNode<T> node, T item)
{
Debug.Assert(node != null && node.Parent.Parent == this && Comp(node.Value, item) <= 0
&& ((node.Next == null && (node.Parent.Next == null || Comp(node.Parent.Next.Head.Value, item) >= 0))
|| Comp(node.Next.Value, item) >= 0));
var bucket = node.Parent;
var tmp = new BucketNode<T>(item, bucket, node, node.Next);
if (!bucket.AddAfter(node, tmp))
{
if (node.Next == null && (bucket.Next == null || bucket.Next.Count >= BucketSize)) AddAfter(bucket, tmp);
else if (node.Next == null) AddBefore(bucket.Next.Head, item);
else
{
node.Next.Prev = tmp;
node.Next = tmp;
while (node.Next.Next != null) node = node.Next;
item = node.Next.Value;
bucket.Tail = node;
node.Next = null;
AddAfter(node, item);
}
}
}
public void AddBefore(BucketNode<T> node, T item)
{
Debug.Assert(node != null && node.Parent.Parent == this && Comp(node.Value, item) >= 0
&& ((node.Prev == null && (node.Parent.Prev == null || Comp(node.Parent.Prev.Tail.Value, item) <= 0))
|| Comp(node.Prev.Value, item) <= 0));
var bucket = node.Parent;
var tmp = new BucketNode<T>(item, bucket, node.Prev, node);
if (!bucket.AddBefore(node, tmp))
{
if (node.Prev == null && (bucket.Prev == null || bucket.Prev.Count >= BucketSize)) AddBefore(bucket, tmp);
else if (node.Prev == null) AddAfter(bucket.Prev.Tail, item);
else
{
node.Prev.Next = tmp;
node.Prev = tmp;
while (node.Prev.Prev != null) node = node.Prev;
item = node.Prev.Value;
bucket.Head = node;
node.Prev = null;
AddBefore(node, item);
}
}
}
// (node, index)
// index is the position of node in node.Parent
public Tuple<BucketNode<T>, int> UpperBound(Predicate<T> pred)
{
if (NumOfBucket == 0) return null;
if (pred(Tail.Tail.Value)) return new Tuple<BucketNode<T>, int>(Tail.Tail, Tail.Count - 1);
var bucket = Tail;
while (bucket.Prev != null && !pred(bucket.Prev.Tail.Value)) bucket = bucket.Prev;
var node = bucket.Tail;
var index = bucket.Count - 1;
while (node.Prev != null && !pred(node.Prev.Value)) { node = node.Prev; index--; }
if (node.Prev == null) return bucket.Prev == null ? null : new Tuple<BucketNode<T>, int>(bucket.Prev.Tail, bucket.Prev.Count - 1);
else return new Tuple<BucketNode<T>, int>(node.Prev, index - 1);
}
public Tuple<BucketNode<T>, int> UpperBound(T item) => LowerBound(x => Comp(x, item) <= 0);
// (node, index)
// index is the position of node in node.Parent
public Tuple<BucketNode<T>, int> LowerBound(Predicate<T> pred)
{
if (NumOfBucket == 0) return null;
if (pred(Head.Head.Value)) return new Tuple<BucketNode<T>, int>(Head.Head, 0);
var bucket = Head;
while (bucket.Next != null && !pred(bucket.Next.Head.Value)) bucket = bucket.Next;
var node = bucket.Head;
var index = 0;
while (node.Next != null && !pred(node.Next.Value)) { node = node.Next; index++; }
if (node.Next == null) return bucket.Next == null ? null : new Tuple<BucketNode<T>, int>(bucket.Next.Head, 0);
else return new Tuple<BucketNode<T>, int>(node.Next, index + 1);
}
public Tuple<BucketNode<T>, int> LowerBound(T item) => LowerBound(x => Comp(x, item) >= 0);
public void InitiateWith(Bucket<T> bucket)
{
Debug.Assert(bucket != null && bucket.Count > 0);
RemoveAll();
Head = Tail = bucket;
bucket.Parent = this;
NumOfBucket++;
}
public void InitiateWith(T item)
{
RemoveAll();
Head = Tail = new Bucket<T>(this, null, null);
Head.Head = Head.Tail = new BucketNode<T>(item, Head, null, null);
Head.Count++;
NumOfBucket++;
}
public void AddFirst(Bucket<T> bucket) { if (NumOfBucket == 0) InitiateWith(bucket); else AddBefore(Head, bucket); }
public void AddLast(Bucket<T> bucket) { if (NumOfBucket == 0) InitiateWith(bucket); else AddAfter(Tail, bucket); }
public void AddFirst(T item) { if (NumOfBucket == 0) InitiateWith(item); else AddBefore(Head.Head, item); }
public void AddLast(T item) { if (NumOfBucket == 0) InitiateWith(item); else AddAfter(Tail.Tail, item); }
public void Clear() => RemoveAll();
public void RemoveAll() { Head = Tail = null; NumOfBucket = 0; }
public void RemoveFirst() { if (NumOfBucket == 0) throw new InvalidOperationException(); else Remove(Head.Head); }
public void RemoveLast() { if (NumOfBucket == 0) throw new InvalidOperationException(); else Remove(Tail.Tail); }
// remove item and return whether item was removed or not
public bool Remove(T item) { var node = Find(item); if (node != null) Remove(node); return node != null; }
public void Remove(Bucket<T> bucket)
{
Debug.Assert(bucket != null && bucket.Parent == this);
NumOfBucket--;
if (bucket == Head && bucket == Tail) { Head = Tail = null; }
else if (bucket == Head) { Head.Next.Prev = null; Head = Head.Next; }
else if (bucket == Tail) { Tail.Prev.Next = null; Tail = Tail.Prev; }
else { bucket.Prev.Next = bucket.Next; bucket.Next.Prev = bucket.Prev; }
}
public void Remove(BucketNode<T> node) { Debug.Assert(node != null && node.Parent.Parent == this); if (!node.Parent.Remove(node)) Remove(node.Parent); }
protected void RemoveRange(Bucket<T> from, Bucket<T> to, int indexFrom = -1, int indexTo = -1)
{
Debug.Assert(from != null && to != null && from.Parent == this && to.Parent == this);
if (indexFrom < 0) indexFrom = from.Index;
if (indexTo < 0) indexTo = to.Index;
if (indexFrom == 0 && indexTo == NumOfBucket - 1) { Clear(); return; }
else if (indexFrom == 0) { Head = to.Next; Head.Prev = null; }
else if (indexTo == NumOfBucket - 1) { Tail = from.Prev; Tail.Next = null; }
else { from.Prev.Next = to.Next; to.Next.Prev = from.Prev; }
NumOfBucket -= indexTo - indexFrom + 1;
}
public void RemoveRange(BucketNode<T> from, BucketNode<T> to, int indexFrom = -1, int indexTo = -1)
{
Debug.Assert(from != null && to != null && from.Parent.Parent == this && to.Parent.Parent == this);
if (indexFrom < 0) indexFrom = from.Index;
if (indexTo < 0) indexTo = to.Index;
var bucketFrom = from.Parent;
var bucketTo = to.Parent;
if (bucketFrom == bucketTo)
{
var bucket = bucketFrom;
if (indexFrom == 0 && indexTo == bucket.Count - 1) Remove(bucket);
else bucket.RemoveRange(from, to, indexFrom, indexTo);
}
else
{
var bf = bucketFrom.Index;
var bt = bucketTo.Index;
Debug.Assert(bf < bt);
if (bt > bf + 1) RemoveRange(bucketFrom.Next, bucketTo.Prev, bf + 1, bt - 1);
if (indexFrom == 0) { Remove(bucketFrom); RemoveRange(bucketTo.Head, to, 0, indexTo); }
else if (indexTo == bucketTo.Count - 1) { Remove(bucketTo); RemoveRange(from, bucketFrom.Tail, indexFrom, bucketFrom.Count - 1); }
else
{
bucketFrom.RemoveRange(from, bucketFrom.Tail, indexFrom, bucketFrom.Count - 1);
bucketTo.RemoveRange(bucketTo.Head, to, 0, indexTo);
if (bucketFrom.Count + bucketTo.Count < BucketSize) Adjust();
}
}
}
public void Adjust()
{
var array = this.ToArray();
Clear();
var length = array.Length;
BucketSize = (int)Math.Sqrt(length + 1);
var count = (length + BucketSize - 1) / BucketSize;
for (var i = 0; i < count; i++)
{
var bucket = new Bucket<T>(this, null, null);
var lim = Math.Min(BucketSize * (i + 1), length);
for (var j = BucketSize * i; j < lim; j++) bucket.AddLast(array[j]);
AddLast(bucket);
}
}
public BucketNode<T> Find(T item) { var node = LowerBound(item); if (node == null || Comp(node.Item1.Value, item) != 0) return null; else return node.Item1; }
public BucketNode<T> FindLast(T item) { var node = UpperBound(item); if (node == null || Comp(node.Item1.Value, item) != 0) return null; else return node.Item1; }
public IEnumerator<T> GetEnumerator()
{
var bucket = Head;
while (bucket != null)
{
var node = bucket.Head;
while (node != null) { yield return node.Value; node = node.Next; }
bucket = bucket.Next;
}
}
public void Add(T item) { var ub = LowerBound(item); if (ub != null) AddBefore(ub.Item1, item); else AddLast(item); }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void CopyTo(Array array, int index) { foreach (var item in this) array.SetValue(item, index++); }
public bool IsSynchronized => false;
public object SyncRoot => this;
public bool IsReadOnly => false;
public bool Contains(T item) => Find(item) != null;
public void CopyTo(T[] array, int index) { foreach (var item in this) array[index++] = item; }
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("<Start>\n");
var node = Head;
while (node != null) { sb.Append($"{node.ToString()}\n"); node = node.Next; }
sb.Append("<end>");
return sb.ToString();
}
public bool Check()
{
if (NumOfBucket == 0) return Head == null && Tail == null;
if (Head.Prev != null || Tail.Next != null) return false;
var bucket = Head;
var c = 1;
while (bucket.Next != null)
{
if (!CheckConnection(bucket) || !CheckBucket(bucket)) return false;
bucket = bucket.Next;
c++;
}
return bucket == Tail && CheckBucket(Tail) && c == NumOfBucket;
}
bool CheckConnection(Bucket<T> bucket)
{
if (bucket.Next == null) return bucket == Tail;
else return bucket.Next.Prev == bucket && Comp(bucket.Tail.Value, bucket.Next.Head.Value) <= 0;
}
bool CheckBucket(Bucket<T> bucket) => bucket.Count > 0 && bucket.Count <= BucketSize && bucket.Parent == this;
public void Start(Func<string, T> parser, Func<T> random)
{
BucketNode<T> x = null, y = null;
var help = true;
while (true)
{
Console.Clear();
Console.WriteLine($"{Count} items, {NumOfBucket} buckets(size : {BucketSize})");
Console.WriteLine(this);
Console.WriteLine(Check() ? "OK!" : "NG!");
if (help)
{
Console.WriteLine("when val is omitted, random value will be used.");
Console.WriteLine("a val : add val");
Console.WriteLine("r val : remove val");
Console.WriteLine("j : adjust");
Console.WriteLine("c : clear");
Console.WriteLine("h : disable/enable help message");
Console.WriteLine("x : set x");
Console.WriteLine("x h : set x to head");
Console.WriteLine("x t : set x to tail");
Console.WriteLine("x n : set x to x.next");
Console.WriteLine("x p : set x to x.prev");
Console.WriteLine("x f val : set x to lower bound of val");
Console.WriteLine("y : set y");
Console.WriteLine("x : exchange x and y");
Console.WriteLine("d : remove from x to y");
Console.WriteLine("q : quit");
}
if (x != null) Console.WriteLine($"x = {x.Value} <- {x.Parent}");
if (y != null) Console.WriteLine($"y = {y.Value} <- {y.Parent}");
Console.Write("enter command > ");
var command = Console.ReadLine().Split();
if (command[0].Length > 1 && command[0][1] == 'd')
Console.WriteLine("debug...");
if (command[0].StartsWith("a")) { if (command.Length > 1) Add(parser(command[1])); else Add(random()); }
else if (command[0].StartsWith("r")) { if (command.Length > 1) Remove(parser(command[1])); else Remove(random()); }
else if (command[0].StartsWith("c")) Clear();
else if (command[0].StartsWith("j")) Adjust();
else if (command[0].StartsWith("h")) help = !help;
else if (command[0].StartsWith("x")) SetVariable(command, ref x, parser, random);
else if (command[0].StartsWith("y")) SetVariable(command, ref y, parser, random);
else if (command[0].StartsWith("e")) { var tmp = x; x = y; y = tmp; }
else if (command[0].StartsWith("d")) { RemoveRange(x, y, x.Index, y.Index); x = null; y = null; }
else if (command[0].StartsWith("q")) break;
}
}
void SetVariable(string[] command, ref BucketNode<T> x, Func<string, T> parser, Func<T> random)
{
if (command[1].StartsWith("h")) x = Head.Head;
else if (command[1].StartsWith("t")) x = Tail.Tail;
else if (command[1].StartsWith("n"))
{
if (x.Next != null) x = x.Next;
else if (x.Parent.Next != null) x = x.Parent.Next.Head;
else { Console.WriteLine("x is the last element..."); Console.ReadKey(true); }
}
else if (command[1].StartsWith("p"))
{
if (x.Prev != null) x = x.Prev;
else if (x.Parent.Prev != null) x = x.Parent.Prev.Tail;
else { Console.WriteLine("x is the first element..."); Console.ReadKey(true); }
}
else if (command[1].StartsWith("f")) { if (command.Length > 2) x = LowerBound(parser(command[2])).Item1; else x = LowerBound(random()).Item1; }
}
}
// bucket cannot be empty
class Bucket<T>
{
public BucketList<T> Parent;
public int Count;
public Bucket<T> Prev;
public Bucket<T> Next;
public BucketNode<T> Head;
public BucketNode<T> Tail;
public Bucket(BucketList<T> parent, Bucket<T> prev, Bucket<T> next) { Parent = parent; Prev = prev; Next = next; Head = null; Tail = null; }
public int Index
{
get
{
var count = 0;
var node = Parent.Head;
while (node != this) { node = node.Next; count++; }
return count;
}
}
public bool AddAfter(BucketNode<T> node, BucketNode<T> item) => AddAfter(node, item.Value);
public bool AddBefore(BucketNode<T> node, BucketNode<T> item) => AddBefore(node, item.Value);
public bool AddAfter(BucketNode<T> node, T item)
{
Debug.Assert(node != null && node.Parent == this && Parent.Comp(node.Value, item) <= 0
&& ((node.Next == null && (Next == null || Parent.Comp(Next.Head.Value, item) >= 0))
|| Parent.Comp(node.Next.Value, item) >= 0));
if (Count < Parent.BucketSize)
{
var tmp = new BucketNode<T>(item, this, node, node.Next);
if (node.Next != null) node.Next.Prev = tmp;
else Tail = tmp;
node.Next = tmp;
Count++;
return true;
}
return false;
}
public bool AddBefore(BucketNode<T> node, T item)
{
Debug.Assert(node != null && node.Parent == this && Parent.Comp(node.Value, item) >= 0
&& ((node.Prev == null && (Prev == null || Parent.Comp(Prev.Tail.Value, item) <= 0))
|| Parent.Comp(node.Prev.Value, item) <= 0));
if (Count < Parent.BucketSize)
{
var tmp = new BucketNode<T>(item, this, node.Prev, node);
if (node.Prev != null) node.Prev.Next = tmp;
else Head = tmp;
node.Prev = tmp;
Count++;
return true;
}
else return false;
}
public bool InitiateWith(BucketNode<T> node)
{
Head = Tail = node;
node.Parent = this;
node.Prev = node.Next = null;
Count++;
return true;
}
public bool InitiateWith(T item) => InitiateWith(new BucketNode<T>(item, this, null, null));
public void RemoveAll() { Head = Tail = null; Count = 0; }
public bool AddFirst(T item) { if (Count == 0) return InitiateWith(item); else return AddBefore(Head, item); }
public bool AddLast(T item) { if (Count == 0) return InitiateWith(item); else return AddAfter(Tail, item); }
public bool Remove(BucketNode<T> node)
{
Debug.Assert(node != null && node.Parent == this);
if (Count > 1)
{
Count--;
if (node == Head) { Head.Next.Prev = null; Head = Head.Next; }
else if (node == Tail) { Tail.Prev.Next = null; Tail = Tail.Prev; }
else { node.Prev.Next = node.Next; node.Next.Prev = node.Prev; }
return true;
}
else return false;
}
public bool RemoveRange(BucketNode<T> from, BucketNode<T> to, int indexFrom = -1, int indexTo = -1)
{
Debug.Assert(from != null && to != null && from.Parent == this && to.Parent == this);
if (indexFrom < 0) indexFrom = from.Index;
if (indexTo < 0) indexTo = to.Index;
if (indexTo == 0 && indexFrom == Count - 1) return false;
else if (indexFrom == 0) { Head = to.Next; Head.Prev = null; }
else if (indexTo == Count - 1) { Tail = from.Prev; Tail.Next = null; }
else { from.Prev.Next = to.Next; to.Next.Prev = from.Prev; }
Count -= indexTo - indexFrom + 1;
return true;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("[");
var node = Head;
while (node != null) { sb.Append($"{node.ToString()}, "); node = node.Next; }
if (sb.Length > 1) sb.Remove(sb.Length - 2, 2);
sb.Append("]");
return sb.ToString();
}
public bool Check()
{
if (Count == 0) return Head == null && Tail == null;
if (Head.Prev != null || Tail.Next != null) return false;
var node = Head;
var c = 1;
while (node.Next != null)
{
if (!CheckConnection(node) || !CheckNode(node)) return false;
node = node.Next;
c++;
}
return node == Tail && CheckNode(Tail) && c == Count;
}
bool CheckConnection(BucketNode<T> node)
{
if (node.Next == null) return node == Tail;
else return node.Next.Prev == node && Parent.Comp(node.Value, node.Next.Value) <= 0;
}
bool CheckNode(BucketNode<T> node) => node.Parent == this;
}
class BucketNode<T>
{
public T Value;
public Bucket<T> Parent;
public BucketNode<T> Prev;
public BucketNode<T> Next;
public BucketNode(T item, Bucket<T> parent, BucketNode<T> prev, BucketNode<T> next) { Value = item; Parent = parent; Prev = prev; Next = next; }
public int Index
{
get
{
var count = 0;
var node = Parent.Head;
while (node != this) { node = node.Next; count++; }
return count;
}
}
public override string ToString() => Value.ToString();
}
class UndirectedGraph<V, E> : DirectedGraph<V, E>
{
public UndirectedGraph(int V) : base(V) { }
public UndirectedGraph(int V, IEnumerable<EdgeInfo<E>> edges) : base(V, edges) { }
public override void AddEdge(EdgeInfo<E> edge)
{
edges.Add(edge);
edges.Add(edge.Reverse());
edgesFrom[edge.From].Add(new HalfEdgeInfo<E>(edge.To, edge.Information));
edgesFrom[edge.To].Add(new HalfEdgeInfo<E>(edge.From, edge.Information));
edgesTo[edge.To].Add(new HalfEdgeInfo<E>(edge.From, edge.Information));
edgesTo[edge.From].Add(new HalfEdgeInfo<E>(edge.To, edge.Information));
}
public bool IsConnected
{
get
{
if (numberOfNodes == 0) return true;
var used = new bool[numberOfNodes];
var queue = new Queue<int>();
queue.Enqueue(0);
while (queue.Count > 0)
{
var v = queue.Dequeue();
if (used[v]) continue;
used[v] = true;
foreach (var e in EdgesFrom(v)) queue.Enqueue(e.End);
}
return used.All(x => x);
}
}
public bool IsTree
{
get
{
if (numberOfNodes == 0) return true;
var used = new bool[numberOfNodes];
var queue = new Queue<int>();
queue.Enqueue(0);
while (queue.Count > 0)
{
var v = queue.Dequeue();
if (used[v]) return false;
used[v] = true;
foreach (var e in EdgesFrom(v)) queue.Enqueue(e.End);
}
return used.All(x => x);
}
}
public UndirectedGraph<V, E> MinimumSpanningTreePrim(int start, Func<E, int> cost)
{
var graph = new UndirectedGraph<V, E>(numberOfNodes);
nodes.CopyTo(graph.nodes, 0);
var d = Enumerable.Repeat(Func.Inf, numberOfNodes).ToArray();
var used = new bool[numberOfNodes];
var queue = new PriorityQueue<Pair<EdgeInfo<E>, int>>((x, y) => x.Second.CompareTo(y.Second), numberOfNodes);
d[start] = 0;
queue.Enqueue(new Pair<EdgeInfo<E>, int>(new EdgeInfo<E>(-1, 0, default(E)), 0));
while (queue.Count > 0)
{
var p = queue.Dequeue();
var v = p.First.To;
if (d[v] < p.Second) continue;
used[v] = true;
if (p.First.From >= 0) graph.AddEdge(v, p.First.From, p.First.Information);
foreach (var w in EdgesFrom(v))
{
if (!used[w.End] && cost(w.Information) < d[w.End])
{
d[w.End] = cost(w.Information);
queue.Enqueue(new Pair<EdgeInfo<E>, int>(new EdgeInfo<E>(v, w.End, w.Information), cost(w.Information)));
}
}
}
return graph;
}
public UndirectedGraph<V, E> MinimumSpanningTreeKruskal(Func<E, int> cost)
{
var graph = new UndirectedGraph<V, E>(numberOfNodes);
nodes.CopyTo(graph.nodes, 0);
var tree = new UnionFindTree(numberOfNodes);
edges.Sort((x, y) => cost(x.Information).CompareTo(cost(y.Information)));
foreach (var e in edges)
{
if (!tree.IsSameCategory(e.From, e.To))
{
tree.UniteCategory(e.From, e.To);
graph.AddEdge(e);
}
}
return graph;
}
public bool IsBipartite
{
get
{
var color = new int[numberOfNodes];
foreach (var v in nodes)
{
if (color[v.Code] == 0)
{
var queue = new Queue<Pair<int, int>>();
queue.Enqueue(new Pair<int, int>(v.Code, 1));
while (queue.Count > 0)
{
var w = queue.Dequeue();
if (color[w.First] != 0)
{
if (color[w.First] != w.Second) return false;
continue;
}
color[w.First] = w.Second;
foreach (var e in EdgesFrom(w.First)) queue.Enqueue(new Pair<int, int>(e.End, -w.Second));
}
}
}
return true;
}
}
public IEnumerable<NodeInfo<V>> GetArticulationPoints()
{
var visited = new bool[numberOfNodes];
var parent = new int[numberOfNodes];
var children = Enumerable.Range(0, numberOfNodes).Select(_ => new SortedSet<int>()).ToArray();
var order = new int[numberOfNodes];
var lowest = new int[numberOfNodes];
var isroot = new bool[numberOfNodes];
var count = 1;
var isarticulation = new bool[numberOfNodes];
Action<int, int> dfs = null;
dfs = (u, prev) =>
{
order[u] = count;
lowest[u] = count;
count++;
visited[u] = true;
foreach (var e in edgesFrom[u])
{
var v = e.End;
if (visited[v]) { if (v != prev) lowest[u] = Math.Min(lowest[u], order[v]); }
else
{
parent[v] = u;
if (isroot[u]) children[u].Add(v);
dfs(v, u);
lowest[u] = Math.Min(lowest[u], lowest[v]);
if (order[u] <= lowest[v]) isarticulation[u] = true;
}
}
};
for (var v = 0; v < numberOfNodes; v++)
{
if (visited[v]) continue;
count = 1; dfs(v, -1);
isroot[v] = true;
}
for (var v = 0; v < numberOfNodes; v++)
{
if (isroot[v]) { if (children[v].Count > 1) yield return nodes[v]; }
else { if (isarticulation[v]) yield return nodes[v]; }
}
}
public string ToString(Func<NodeInfo<V>, string> vertex, Func<EdgeInfo<E>, string> edge)
{
var sb = new StringBuilder();
sb.Append("graph G {\n");
foreach (var v in nodes) sb.Append($"\tv{v.Code} [label = \"{vertex(v)}\"];\n");
foreach (var e in edges) sb.Append($"\tv{e.From} -- v{e.To} [label=\"{edge(e)}\"];\n");
sb.Append("}");
return sb.ToString();
}
public override string ToString() => ToString(v => v.ToString(), e => e.ToString());
}
class NodeInfo<V> : Pair<int, V>
{
public int Code { get { return First; } set { First = value; } }
public V Information { get { return Second; } set { Second = value; } }
public NodeInfo() : base() { }
public NodeInfo(int code, V info) : base(code, info) { }
}
class HalfEdgeInfo<E> : Pair<int, E>
{
public int End { get { return First; } set { First = value; } }
public E Information { get { return Second; } set { Second = value; } }
public HalfEdgeInfo() : base() { }
public HalfEdgeInfo(int end, E info) : base(end, info) { }
}
class EdgeInfo<E> : Pair<Pair<int, int>, E>
{
public int From { get { return First.First; } set { First.First = value; } }
public int To { get { return First.Second; } set { First.Second = value; } }
public E Information { get { return Second; } set { Second = value; } }
public EdgeInfo() : base() { }
public EdgeInfo(int from, int to, E info) : base(new Pair<int, int>(from, to), info) { }
public EdgeInfo<E> Reverse() => new EdgeInfo<E>(To, From, Information);
}
class DirectedGraph<V, E> : IEnumerable<NodeInfo<V>>
{
protected int numberOfNodes;
public int NumberOfNodes => numberOfNodes;
protected NodeInfo<V>[] nodes;
protected List<EdgeInfo<E>> edges;
protected List<HalfEdgeInfo<E>>[] edgesFrom;
protected List<HalfEdgeInfo<E>>[] edgesTo;
public IEnumerable<HalfEdgeInfo<E>> EdgesFrom(int node) => edgesFrom[node];
public int InDegree(int node) => edgesTo[node].Count;
public int OutDegree(int node) => edgesFrom[node].Count;
public IEnumerable<HalfEdgeInfo<E>> EdgesTo(int node) => edgesTo[node];
public V this[int node] { get { return nodes[node].Second; } set { nodes[node].Second = value; } }
public IEnumerable<EdgeInfo<E>> Edges => edges;
public DirectedGraph(int V)
{
numberOfNodes = V;
nodes = Enumerable.Range(0, V).Select(x => new NodeInfo<V>(x, default(V))).ToArray();
edges = new List<EdgeInfo<E>>();
edgesFrom = Enumerable.Range(0, V).Select(_ => new List<HalfEdgeInfo<E>>()).ToArray();
edgesTo = Enumerable.Range(0, V).Select(_ => new List<HalfEdgeInfo<E>>()).ToArray();
}
public DirectedGraph(int V, IEnumerable<EdgeInfo<E>> edges) : this(V) { foreach (var e in edges) AddEdge(e.From, e.To, e.Information); }
public virtual void AddEdge(EdgeInfo<E> edge)
{
edges.Add(edge);
edgesFrom[edge.From].Add(new HalfEdgeInfo<E>(edge.To, edge.Information));
edgesTo[edge.To].Add(new HalfEdgeInfo<E>(edge.From, edge.Information));
}
public void AddEdge(int from, int to, E information) => AddEdge(new EdgeInfo<E>(from, to, information));
public void AddEdge(V from, V to, E information) => AddEdge(new EdgeInfo<E>(SearchNode(from).Code, SearchNode(to).Code, information));
public NodeInfo<V> SearchNode(V node) => nodes.FirstOrDefault(e => e.Information.Equals(node));
public EdgeInfo<E> SearchEdge(E edge) => edges.Find(e => e.Information.Equals(edge));
public IEnumerator<NodeInfo<V>> GetEnumerator() { foreach (var v in nodes) yield return v; }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public int[] ShortestPathLengthFrom(int from, Func<E, int> cost)
{
var d = Enumerable.Repeat(Func.Inf, numberOfNodes).ToArray();
d[from] = 0;
var update = true;
while (update)
{
update = false;
foreach (var e in edges)
{
var tmp = d[e.From] + cost(e.Information);
if (d[e.From] < Func.Inf && d[e.To] > tmp)
{
d[e.To] = tmp;
update = true;
}
}
}
return d;
}
public int[] DijkstraFrom(int from, Func<E, int> cost)
{
var d = Enumerable.Repeat(Func.Inf, numberOfNodes).ToArray();
var queue = new PriorityQueue<Pair<int, int>>((x, y) => x.Second.CompareTo(y.Second));
d[from] = 0;
queue.Enqueue(new Pair<int, int>(from, 0));
while (!queue.IsEmpty)
{
var p = queue.Dequeue();
var v = p.First;
if (d[v] < p.Second) continue;
foreach (var e in EdgesFrom(v))
{
var tmp = d[v] + cost(e.Information);
if (d[e.End] > tmp) queue.Enqueue(new Pair<int, int>(e.End, d[e.End] = tmp));
}
}
return d;
}
// cost(e)>=0
public Pair<long, int>[] DijkstraFromL(int from, Func<E, long> cost)
{
var d = new Pair<long, int>[numberOfNodes];
for (var i = 0; i < numberOfNodes; i++) d[i] = new Pair<long, int>(Func.InfL, -1);
var queue = new PriorityQueue<Tuple<int, long, int>>((x, y) => x.Item2.CompareTo(y.Item2));
d[from] = new Pair<long, int>(0, -1);
queue.Enqueue(new Tuple<int, long, int>(from, 0, -1));
while (!queue.IsEmpty)
{
var p = queue.Dequeue();
var v = p.Item1;
if (d[v].First < p.Item2) continue;
foreach (var e in edgesFrom[v])
{
var tmp = d[v].First + cost(e.Information);
if (d[e.End].First > tmp) queue.Enqueue(new Tuple<int, long, int>(e.End, d[e.End].First = tmp, d[e.End].Second = v));
}
}
return d;
}
public int[,] ShortestPathLengthEachOther(Func<E, int> cost)
{
var d = new int[numberOfNodes, numberOfNodes];
for (var v = 0; v < numberOfNodes; v++) for (var w = 0; w < numberOfNodes; w++) d[v, w] = Func.Inf;
for (var v = 0; v < numberOfNodes; v++) d[v, v] = 0;
foreach (var e in edges) if (e.From != e.To) d[e.From, e.To] = cost(e.Information);
for (var k = 0; k < numberOfNodes; k++)
for (var v = 0; v < numberOfNodes; v++)
for (var w = 0; w < numberOfNodes; w++)
d[v, w] = Math.Min(d[v, w], d[v, k] + d[k, w]);
return d;
}
public bool ContainsNegativeLoopWF(Func<E, int> cost)
{
var d = ShortestPathLengthEachOther(cost);
for (var v = 0; v < numberOfNodes; v++) if (d[v, v] < 0) return true;
return false;
}
public bool ContainsNegativeLoop(Func<E, int> cost)
{
var d = Enumerable.Repeat(0, numberOfNodes).ToArray();
for (var v = 0; v < numberOfNodes; v++)
{
foreach (var e in edges)
{
var tmp = d[e.From] + cost(e.Information);
if (d[e.To] > tmp)
{
d[e.To] = tmp;
if (v == numberOfNodes - 1) return true;
}
}
}
return false;
}
public IEnumerable<int> ReachableFrom(int from)
{
var used = new bool[numberOfNodes];
var queue = new Queue<int>();
queue.Enqueue(from);
while (queue.Count > 0)
{
var v = queue.Dequeue();
if (used[v]) continue;
used[v] = true;
foreach (var e in EdgesFrom(v)) queue.Enqueue(e.End);
}
for (var v = 0; v < numberOfNodes; v++) if (used[v]) yield return v;
}
public bool IsReachable(int from, int to)
{
var used = new bool[numberOfNodes];
var queue = new Queue<int>();
queue.Enqueue(from);
while (queue.Count > 0)
{
var v = queue.Dequeue();
if (v == to) return true;
if (used[v]) continue;
used[v] = true;
foreach (var e in EdgesFrom(v)) queue.Enqueue(e.End);
}
return false;
}
public Pair<DirectedGraph<HashSet<NodeInfo<V>>, object>, int[]> StronglyConnectedComponents()
{
var mark = new bool[numberOfNodes];
var stack = new Stack<int>();
Action<int> dfs = null;
dfs = v =>
{
mark[v] = true;
foreach (var w in edgesFrom[v]) if (!mark[w.End]) dfs(w.End);
stack.Push(v);
};
for (var v = 0; v < numberOfNodes; v++) if (!mark[v]) dfs(v);
var scc = new List<HashSet<NodeInfo<V>>>();
mark = new bool[numberOfNodes];
var which = new int[numberOfNodes];
Action<int, HashSet<NodeInfo<V>>> rdfs = null;
rdfs = (v, set) =>
{
set.Add(new NodeInfo<V>(v, nodes[v].Information));
mark[v] = true;
foreach (var w in edgesFrom[v]) if (!mark[w.End]) rdfs(w.End, set);
};
var M = 0;
while (stack.Count > 0)
{
var v = stack.Pop();
if (mark[v]) continue;
var set = new HashSet<NodeInfo<V>>();
rdfs(v, set);
scc.Add(set);
foreach (var w in set) which[w.Code] = M;
M++;
}
var graph = new UndirectedGraph<HashSet<NodeInfo<V>>, object>(M);
for (var v = 0; v < M; v++) graph[v] = scc[v];
foreach (var e in edges) if (which[e.From] != which[e.To]) graph.AddEdge(which[e.From], which[e.To], null);
return new Pair<DirectedGraph<HashSet<NodeInfo<V>>, object>, int[]>(graph, which);
}
public string ToString(Func<V, string> vertex, Func<E, string> edge)
{
var sb = new StringBuilder();
sb.Append("digraph G {\n");
foreach (var v in nodes) sb.Append($"\tv{v.Code} [label = \"{vertex(v.Information)}\"];\n");
foreach (var e in edges) sb.Append($"\tv{e.From} -> v{e.To} [label=\"{edge(e.Information)}\"];\n");
sb.Append("}");
return sb.ToString();
}
public override string ToString() => ToString(v => v.ToString(), e => e.ToString());
}
class UnionFindTree
{
int N;
int[] parent, rank, size;
public UnionFindTree(int capacity)
{
N = capacity;
parent = new int[N];
rank = new int[N];
size = new int[N];
for (var i = 0; i < N; i++) { parent[i] = i; size[i] = 1; }
}
public int GetSize(int x) => size[GetRootOf(x)];
public int GetRootOf(int x) => parent[x] == x ? x : parent[x] = GetRootOf(parent[x]);
public bool UniteCategory(int x, int y)
{
if ((x = GetRootOf(x)) == (y = GetRootOf(y))) return false;
if (rank[x] < rank[y]) { parent[x] = y; size[y] += size[x]; }
else
{
parent[y] = x; size[x] += size[y];
if (rank[x] == rank[y]) rank[x]++;
}
return true;
}
public bool IsSameCategory(int x, int y) => GetRootOf(x) == GetRootOf(y);
}
class AVLTree<T> : IEnumerable<T>, ICollection<T>, ICollection, IEnumerable
{
public class AVLNode : IEnumerable<T>
{
AVLTree<T> tree;
int height;
public int Height => height;
public int Bias => Left.height - Right.height;
public T Item;
public AVLNode Parent;
public AVLNode Left;
public AVLNode Right;
AVLNode(T x, AVLTree<T> tree) { this.tree = tree; Item = x; Left = tree.sentinel; Right = tree.sentinel; }
public AVLNode(AVLTree<T> tree) : this(default(T), tree) { height = 0; Parent = null; }
public AVLNode(T x, AVLNode parent, AVLTree<T> tree) : this(x, tree) { height = 1; Parent = parent; }
public void Adjust() => height = 1 + Math.Max(Left.height, Right.height);
public void ResetAsSentinel() { height = 0; Left = tree.sentinel; Right = tree.sentinel; }
public IEnumerator<T> GetEnumerator()
{
if (this != tree.sentinel)
{
foreach (var x in Left) yield return x;
yield return Item;
foreach (var x in Right) yield return x;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
AVLNode sentinel;
Comparison<T> comp;
Func<T, T, bool> equals;
int count;
// assumed to be comparer
// i.e. comp(x,x)=0, and comp(x,y)>0 then comp(y,x)<0, and comp(x,y)>0 & comp(y,z)>0 then comp(x,z)>0
public AVLTree(Comparison<T> comp)
{
sentinel = new AVLNode(this);
sentinel.ResetAsSentinel();
this.comp = comp ?? Func.DefaultComparison<T>();
if (typeof(T).IsValueType) equals = (x, y) => x.Equals(y);
else equals = (x, y) => ReferenceEquals(x, y);
count = 0;
}
public AVLTree(IComparer<T> comp = null) : this(comp.ToComparison()) { }
void Replace(AVLNode u, AVLNode v)
{
var parent = u.Parent;
if (parent.Left == u) parent.Left = v;
else parent.Right = v;
v.Parent = parent;
}
AVLNode RotateL(AVLNode v)
{
var u = v.Right;
Replace(v, u);
v.Right = u.Left;
u.Left.Parent = v;
u.Left = v;
v.Parent = u;
v.Adjust();
u.Adjust();
return u;
}
AVLNode RotateR(AVLNode u)
{
var v = u.Left;
Replace(u, v);
u.Left = v.Right;
v.Right.Parent = u;
v.Right = u;
u.Parent = v;
u.Adjust();
v.Adjust();
return v;
}
AVLNode RotateLR(AVLNode t) { RotateL(t.Left); return RotateR(t); }
AVLNode RotateRL(AVLNode t) { RotateR(t.Right); return RotateL(t); }
void Adjust(bool isInsertMode, AVLNode node)
{
while (node.Parent != sentinel)
{
var parent = node.Parent;
var height = parent.Height;
if ((parent.Left == node) == isInsertMode)
if (parent.Bias == 2)
if (parent.Left.Bias >= 0) parent = RotateR(parent);
else parent = RotateLR(parent);
else parent.Adjust();
else
if (parent.Bias == -2)
if (parent.Right.Bias <= 0) parent = RotateL(parent);
else parent = RotateRL(parent);
else parent.Adjust();
if (height == parent.Height) break;
node = parent;
}
}
public void Add(T item)
{
var parent = sentinel;
var pos = sentinel.Left;
var isLeft = true;
count++;
while (pos != sentinel)
if (comp(item, pos.Item) < 0) { parent = pos; pos = pos.Left; isLeft = true; }
else { parent = pos; pos = pos.Right; isLeft = false; }
if (isLeft)
{
parent.Left = new AVLNode(item, parent, this);
Adjust(true, parent.Left);
}
else
{
parent.Right = new AVLNode(item, parent, this);
Adjust(true, parent.Right);
}
}
// if equals(x,y) holds then !(comp(x,y)<0) and !(comp(x,y)>0) must hold
// i.e. equals(x,y) -> comp(x,y)=0
public bool Remove(T item, AVLNode start)
{
var pos = start;
while (pos != sentinel)
{
if (comp(item, pos.Item) < 0) pos = pos.Left;
else if (comp(item, pos.Item) > 0) pos = pos.Right;
else if (equals(pos.Item, item))
{
if (pos.Left == sentinel)
{
Replace(pos, pos.Right);
Adjust(false, pos.Right);
}
else
{
var max = Max(pos.Left);
pos.Item = max.Item;
Replace(max, max.Left);
Adjust(false, max.Left);
}
count--;
return true;
}
else return Remove(item, pos.Left) || Remove(item, pos.Right);
}
return false;
}
public bool Remove(T item) => Remove(item, sentinel.Left);
AVLNode Max(AVLNode node)
{
while (node.Right != sentinel) node = node.Right;
return node;
}
AVLNode Min(AVLNode node)
{
while (node.Left != sentinel) node = node.Left;
return node;
}
public bool Contains(T item)
{
var pos = sentinel.Left;
while (pos != sentinel)
{
if (comp(item, pos.Item) < 0) pos = pos.Left;
else if (comp(item, pos.Item) > 0) pos = pos.Right;
else return true;
}
return false;
}
public T Find(T item)
{
var pos = sentinel.Left;
while (pos != sentinel)
{
if (comp(item, pos.Item) < 0) pos = pos.Left;
else if (comp(item, pos.Item) > 0) pos = pos.Right;
else return pos.Item;
}
return default(T);
}
public AVLNode LowerBound(Predicate<T> pred) { AVLNode node; LowerBound(pred, sentinel.Left, out node); return node; }
public AVLNode UpperBound(Predicate<T> pred) { AVLNode node; UpperBound(pred, sentinel.Left, out node); return node; }
public AVLNode LowerBound(T item) => LowerBound(x => comp(x, item) >= 0);
public AVLNode UpperBound(T item) => UpperBound(x => comp(x, item) <= 0);
bool UpperBound(Predicate<T> pred, AVLNode node, out AVLNode res)
{
if (node == sentinel) { res = null; return false; }
if (pred(node.Item)) { if (!UpperBound(pred, node.Right, out res)) res = node; return true; }
else return UpperBound(pred, node.Left, out res);
}
bool LowerBound(Predicate<T> pred, AVLNode node, out AVLNode res)
{
if (node == sentinel) { res = null; return false; }
if (pred(node.Item)) { if (!LowerBound(pred, node.Left, out res)) res = node; return true; }
else return LowerBound(pred, node.Right, out res);
}
public T Min() => Min(sentinel.Left).Item;
public AVLNode MinNode() => Min(sentinel.Left);
public T Max() => Max(sentinel.Left).Item;
public AVLNode MaxNode() => Max(sentinel.Left);
public bool IsEmpty => sentinel.Left == sentinel;
public void Clear() { sentinel.Left = sentinel; count = 0; sentinel.ResetAsSentinel(); }
public IEnumerator<T> GetEnumerator() => sentinel.Left.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void CopyTo(T[] array, int arrayIndex) { foreach (var x in this) array[arrayIndex++] = x; }
public int Count => count;
public bool IsReadOnly => true;
public void CopyTo(Array array, int index) { foreach (var x in this) array.SetValue(x, index++); }
public bool IsSynchronized => false;
public object SyncRoot => this;
public override string ToString()
{
var nodes = new StringBuilder();
var edges = new StringBuilder();
ConcatSubTree(nodes, edges, sentinel.Left, "L");
return $"digraph G {{\n{nodes.ToString()}{edges.ToString()}}}";
}
void ConcatSubTree(StringBuilder nodes, StringBuilder edges, AVLNode node, string code)
{
if (node == sentinel) return;
nodes.Append($"\tv{code} [label = \"{node.Height}:{node.Item}\"];\n");
if (node.Left != sentinel) edges.Append($"\tv{code} -> v{code}L;\n");
if (node.Right != sentinel) edges.Append($"\tv{code} -> v{code}R;\n");
ConcatSubTree(nodes, edges, node.Left, $"{code}L");
ConcatSubTree(nodes, edges, node.Right, $"{code}R");
}
public bool IsBalanced() => IsBalanced(sentinel.Left);
public bool IsValidBinarySearchTree() => IsValidBinarySearchTree(sentinel.Left);
bool IsBalanced(AVLNode node) => node == sentinel || (Math.Abs(node.Bias) < 2 && IsBalanced(node.Left) && IsBalanced(node.Right));
bool IsValidBinarySearchTree(AVLNode node)
=> node == sentinel || (Small(node.Item, node.Left) && Large(node.Item, node.Right)
&& IsValidBinarySearchTree(node.Left) && IsValidBinarySearchTree(node.Right));
bool Small(T item, AVLNode node) => node == sentinel || (comp(item, node.Item) >= 0 && Small(item, node.Left) && Small(item, node.Right));
bool Large(T item, AVLNode node) => node == sentinel || (comp(item, node.Item) <= 0 && Large(item, node.Left) && Large(item, node.Right));
public static void CheckAVL(Random rand, int N)
{
Comparison<double> comp = (x, y) => x.CompareTo(y);
var avl = new AVLTree<double>(comp);
var toBeLeft = new double[N];
var toBeRemoved = new double[N];
for (var i = 0; i < N; i++) avl.Add(toBeRemoved[i] = rand.NextDouble());
for (var i = 0; i < N; i++) avl.Add(toBeLeft[i] = rand.NextDouble());
for (var i = 0; i < N; i++) Console.Write(avl.Remove(toBeRemoved[i]) ? "" : "!!!NOT REMOVED!!! => " + toBeRemoved[i] + "\n");
var insertErrors = toBeLeft.All(x => avl.Contains(x));
var deleteErrors = avl.Count == N;
//Console.WriteLine("【AVL木の構造】");
//Console.WriteLine(avl);
if (insertErrors && deleteErrors) Console.WriteLine("○\t挿入, 削除操作が正しく行われています.");
else if (insertErrors) Console.WriteLine("×\t挿入(または削除)操作に問題があります.");
else Console.WriteLine("×\t削除(または挿入)操作に問題があります.");
if (avl.IsBalanced()) Console.WriteLine("○\tAVL木は平衡条件を保っています.");
else Console.WriteLine("×\tAVL木の平衡条件が破れています.");
if (avl.IsValidBinarySearchTree()) Console.WriteLine("○\tAVL木は二分探索木になっています.");
else Console.WriteLine("×\tAVL木は二分探索木になっていません.");
Array.Sort(toBeLeft, comp);
Console.WriteLine($"最小値 : {avl.Min()} ≡ {toBeLeft.First()}");
Console.WriteLine($"最大値 : {avl.Max()} ≡ {toBeLeft.Last()}");
Console.WriteLine($"要素数 : {avl.Count} 個");
}
}
class PriorityQueue<T> : IEnumerable<T>, ICollection, IEnumerable, ICloneable
{
Comparison<T> comp;
List<T> list;
public int Count { get; private set; } = 0;
public bool IsEmpty => Count == 0;
public PriorityQueue(IEnumerable<T> source) : this((Comparison<T>)null, 0, source) { }
public PriorityQueue(int capacity = 4, IEnumerable<T> source = null) : this((Comparison<T>)null, capacity, source) { }
public PriorityQueue(IComparer<T> comp, IEnumerable<T> source) : this(comp.ToComparison(), source) { }
public PriorityQueue(IComparer<T> comp, int capacity = 4, IEnumerable<T> source = null) : this(comp.ToComparison(), source) { list.Capacity = capacity; }
public PriorityQueue(Comparison<T> comp, IEnumerable<T> source) : this(comp, 0, source) { }
public PriorityQueue(Comparison<T> comp, int capacity = 4, IEnumerable<T> source = null) { this.comp = comp ?? Func.DefaultComparison<T>(); list = new List<T>(capacity); if (source != null) foreach (var x in source) Enqueue(x); }
/// <summary>
/// add an item
/// this is an O(log n) operation
/// </summary>
/// <param name="x">item</param>
public void Enqueue(T x)
{
var pos = Count++;
list.Add(x);
while (pos > 0)
{
var p = (pos - 1) / 2;
if (comp(list[p], x) <= 0) break;
list[pos] = list[p];
pos = p;
}
list[pos] = x;
}
/// <summary>
/// return the minimum element and remove it
/// this is an O(log n) operation
/// </summary>
/// <returns>the minimum</returns>
public T Dequeue()
{
var value = list[0];
var x = list[--Count];
list.RemoveAt(Count);
if (Count == 0) return value;
var pos = 0;
while (pos * 2 + 1 < Count)
{
var a = 2 * pos + 1;
var b = 2 * pos + 2;
if (b < Count && comp(list[b], list[a]) < 0) a = b;
if (comp(list[a], x) >= 0) break;
list[pos] = list[a];
pos = a;
}
list[pos] = x;
return value;
}
/// <summary>
/// look at the minimum element
/// this is an O(1) operation
/// </summary>
/// <returns>the minimum</returns>
public T Peek() => list[0];
public IEnumerator<T> GetEnumerator() { var x = (PriorityQueue<T>)Clone(); while (x.Count > 0) yield return x.Dequeue(); }
void CopyTo(Array array, int index) { foreach (var x in this) array.SetValue(x, index++); }
public object Clone() { var x = new PriorityQueue<T>(comp, Count); x.list.AddRange(list); return x; }
public void Clear() { list = new List<T>(); Count = 0; }
public void TrimExcess() => list.TrimExcess();
/// <summary>
/// check whether item is in this queue
/// this is an O(n) operation
/// </summary>
public bool Contains(T item) => list.Contains(item);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
void ICollection.CopyTo(Array array, int index) => CopyTo(array, index);
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
}
class Deque<T>
{
T[] array;
int offset, capacity;
public int Count { get; protected set; }
public Deque(int capacity) { array = new T[this.capacity = capacity]; Count = 0; offset = 0; }
public Deque() : this(16) { }
public T this[int index] { get { return array[GetIndex(index)]; } set { array[GetIndex(index)] = value; } }
int GetIndex(int index) { var tmp = index + offset; return tmp >= capacity ? tmp - capacity : tmp; }
public T PeekFront() => array[offset];
public T PeekBack() => array[GetIndex(Count - 1)];
public void PushFront(T item)
{
if (Count == capacity) Extend();
if (--offset < 0) offset += array.Length;
array[offset] = item;
Count++;
}
public T PopFront()
{
Count--;
var tmp = array[offset++];
if (offset >= capacity) offset -= capacity;
return tmp;
}
public void PushBack(T item)
{
if (Count == capacity) Extend();
var id = (Count++) + offset;
if (id >= capacity) id -= capacity;
array[id] = item;
}
public T PopBack() => array[GetIndex(--Count)];
public void Insert(int index, T item)
{
PushFront(item);
for (var i = 0; i < index; i++) this[i] = this[i + 1];
this[index] = item;
}
public T RemoveAt(int index)
{
var tmp = this[index];
for (var i = index; i > 0; i--) this[i] = this[i - 1];
PopFront();
return tmp;
}
void Extend()
{
var newArray = new T[capacity << 1];
if (offset > capacity - Count)
{
var length = array.Length - offset;
Array.Copy(array, offset, newArray, 0, length);
Array.Copy(array, 0, newArray, length, Count - length);
}
else Array.Copy(array, offset, newArray, 0, Count);
array = newArray;
offset = 0;
capacity <<= 1;
}
}
class PairComparer<S, T> : IComparer<Pair<S, T>>
where S : IComparable<S>
where T : IComparable<T>
{
public PairComparer() { }
public int Compare(Pair<S, T> x, Pair<S, T> y)
{
var p = x.First.CompareTo(y.First);
if (p != 0) return p;
else return x.Second.CompareTo(y.Second);
}
}
class Pair<S, T>
{
public S First;
public T Second;
public Pair() { First = default(S); Second = default(T); }
public Pair(S s, T t) { First = s; Second = t; }
public override string ToString() => $"({First}, {Second})";
public override int GetHashCode() => First.GetHashCode() ^ Second.GetHashCode();
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
else if (obj == null) return false;
var tmp = obj as Pair<S, T>;
return tmp != null && First.Equals(tmp.First) && Second.Equals(tmp.Second);
}
}
class Point : Pair<int, int>
{
public int X { get { return First; } set { First = value; } }
public int Y { get { return Second; } set { Second = value; } }
public Point() : base(0, 0) { }
public Point(int x, int y) : base(x, y) { }
public IEnumerable<Point> Neighbors4()
{
yield return new Point(X - 1, Y);
yield return new Point(X, Y - 1);
yield return new Point(X, Y + 1);
yield return new Point(X + 1, Y);
}
public IEnumerable<Point> Neighbors8()
{
yield return new Point(X - 1, Y - 1);
yield return new Point(X - 1, Y);
yield return new Point(X - 1, Y + 1);
yield return new Point(X, Y - 1);
yield return new Point(X, Y + 1);
yield return new Point(X + 1, Y - 1);
yield return new Point(X + 1, Y);
yield return new Point(X + 1, Y + 1);
}
public static Point operator +(Point p) => new Point(p.X, p.Y);
public static Point operator -(Point p) => new Point(-p.X, -p.Y);
public static Point operator /(Point p, int r) => new Point(p.X / r, p.Y / r);
public static Point operator *(int r, Point p) => new Point(p.X * r, p.Y * r);
public static Point operator *(Point p, int r) => new Point(p.X * r, p.Y * r);
public static Point operator +(Point p, Point q) => new Point(p.X + q.X, p.Y + q.Y);
public static Point operator -(Point p, Point q) => new Point(p.X - q.X, p.Y - q.Y);
}
class Printer : IDisposable
{
bool isConsole;
TextWriter file;
public Printer() { file = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; isConsole = true; }
public Printer(string path) { file = new StreamWriter(path, false) { AutoFlush = false }; isConsole = false; }
public void Write<T>(T value) => file.Write(value);
public void Write(bool b) => file.Write(b ? "YES" : "NO");
public void Write(string str, params object[] args) => file.Write(str, args);
public void WriteLine() => file.WriteLine();
public void WriteLine<T>(T value) => file.WriteLine(value);
public void WriteLine(bool b) => file.WriteLine(b ? "YES" : "NO");
public void WriteLine<T>(IEnumerable<T> list) { foreach (var x in list) file.WriteLine(x); }
public void WriteLine<T>(List<T> list) { foreach (var x in list) file.WriteLine(x); }
public void WriteLine<T>(T[] list) { foreach (var x in list) file.WriteLine(x); }
public void WriteLine(string str, params object[] args) => file.WriteLine(str, args);
public void Dispose() { file.Flush(); if (!isConsole) file.Dispose(); }
}
class Scanner : IDisposable
{
bool isConsole;
TextReader file;
public Scanner() { file = Console.In; }
public Scanner(string path) { file = new StreamReader(path); isConsole = false; }
public void Dispose() { if (!isConsole) file.Dispose(); }
public T Get<T>() => (T)Convert(file.ReadLine(), Type.GetTypeCode(typeof(T)));
public int Int => Get<int>();
public uint UInt => Get<uint>();
public long Long => Get<long>();
public ulong ULong => Get<ulong>();
public double Double => Get<double>();
public decimal Decimal => Get<decimal>();
public char Char => Get<char>();
public string String => Get<string>();
public Tuple<S, T> Get<S, T>() { S s; T t; Read(out s, out t); return new Tuple<S, T>(s, t); }
public Tuple<S, T, U> Get<S, T, U>() { S s; T t; U u; Read(out s, out t, out u); return new Tuple<S, T, U>(s, t, u); }
public Tuple<S, T, U, V> Get<S, T, U, V>() { S s; T t; U u; V v; Read(out s, out t, out u, out v); return new Tuple<S, T, U, V>(s, t, u, v); }
public Tuple<S, T, U, V, W> Get<S, T, U, V, W>() { S s; T t; U u; V v; W w; Read(out s, out t, out u, out v, out w); return new Tuple<S, T, U, V, W>(s, t, u, v, w); }
public Tuple<S, T, U, V, W, X> Get<S, T, U, V, W, X>() { S s; T t; U u; V v; W w; X x; Read(out s, out t, out u, out v, out w, out x); return new Tuple<S, T, U, V, W, X>(s, t, u, v, w, x); }
public Tuple<S, T, U, V, W, X, Y> Get<S, T, U, V, W, X, Y>() { S s; T t; U u; V v; W w; X x; Y y; Read(out s, out t, out u, out v, out w, out x, out y); return new Tuple<S, T, U, V, W, X, Y>(s, t, u, v, w, x, y); }
public Tuple<S, T, U, V, W, X, Y, Z> Get<S, T, U, V, W, X, Y, Z>() { S s; T t; U u; V v; W w; X x; Y y; Z z; Read(out s, out t, out u, out v, out w, out x, out y, out z); return new Tuple<S, T, U, V, W, X, Y, Z>(s, t, u, v, w, x, y, z); }
public Pair<S, T> Pair<S, T>() { S s; T t; Read(out s, out t); return new Pair<S, T>(s, t); }
object Convert(string str, TypeCode type)
{
if (type == TypeCode.Int32) return int.Parse(str);
else if (type == TypeCode.UInt32) return uint.Parse(str);
else if (type == TypeCode.Int64) return long.Parse(str);
else if (type == TypeCode.UInt64) return ulong.Parse(str);
else if (type == TypeCode.Double) return double.Parse(str);
else if (type == TypeCode.Decimal) return decimal.Parse(str);
else if (type == TypeCode.Char) return str[0];
else if (type == TypeCode.String) return str;
else if (type == Type.GetTypeCode(typeof(Point))) { int s, t; Read(out s, out t); return new Point(s, t); }
else throw new Exception();
}
public T[] ReadMany<T>() { var type = Type.GetTypeCode(typeof(T)); return file.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries).Select(str => (T)Convert(str, type)).ToArray(); }
public T[] ReadMany<T>(int n) { var type = Type.GetTypeCode(typeof(T)); return file.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries).Take(n).Select(str => (T)Convert(str, type)).ToArray(); }
public T[] ReadManyLines<T>(int n, Func<T> selector) => Enumerable.Range(0, n).Select(_ => selector()).ToArray();
public T[] ReadManyLines<T>(int n) => Enumerable.Range(0, n).Select(_ => Get<T>()).ToArray();
public Tuple<S, T>[] ReadManyLines<S, T>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T>()).ToArray();
public Tuple<S, T, U>[] ReadManyLines<S, T, U>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U>()).ToArray();
public Tuple<S, T, U, V>[] ReadManyLines<S, T, U, V>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V>()).ToArray();
public Tuple<S, T, U, V, W>[] ReadManyLines<S, T, U, V, W>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V, W>()).ToArray();
public Tuple<S, T, U, V, W, X>[] ReadManyLines<S, T, U, V, W, X>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V, W, X>()).ToArray();
public Tuple<S, T, U, V, W, X, Y>[] ReadManyLines<S, T, U, V, W, X, Y>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V, W, X, Y>()).ToArray();
public Tuple<S, T, U, V, W, X, Y, Z>[] ReadManyLines<S, T, U, V, W, X, Y, Z>(int n) => Enumerable.Range(0, n).Select(_ => Get<S, T, U, V, W, X, Y, Z>()).ToArray();
public T[,] ReadManyManyLines<T>(int X, int Y)
{
var array = new T[X, Y];
for (var y = 0; y < Y; y++) { var tmp = ReadMany<T>(X); for (var x = 0; x < X; x++) array[x, y] = tmp[x]; }
return array;
}
public void Read<S>(out S s)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S))).ToArray();
s = (S)read[0];
}
public void Read<S, T>(out S s, out T t)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T))).ToArray();
s = (S)read[0];
t = (T)read[1];
}
public void Read<S, T, U>(out S s, out T t, out U u)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)), Type.GetTypeCode(typeof(U))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
}
public void Read<S, T, U, V>(out S s, out T t, out U u, out V v)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)), Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
}
public void Read<S, T, U, V, W>(out S s, out T t, out U u, out V v, out W w)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)),
Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V)), Type.GetTypeCode(typeof(W))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
w = (W)read[4];
}
public void Read<S, T, U, V, W, X>(out S s, out T t, out U u, out V v, out W w, out X x)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)),
Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V)), Type.GetTypeCode(typeof(W)), Type.GetTypeCode(typeof(X))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
w = (W)read[4];
x = (X)read[5];
}
public void Read<S, T, U, V, W, X, Y>(out S s, out T t, out U u, out V v, out W w, out X x, out Y y)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)),
Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V)), Type.GetTypeCode(typeof(W)), Type.GetTypeCode(typeof(X)), Type.GetTypeCode(typeof(Y))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
w = (W)read[4];
x = (X)read[5];
y = (Y)read[6];
}
public void Read<S, T, U, V, W, X, Y, Z>(out S s, out T t, out U u, out V v, out W w, out X x, out Y y, out Z z)
{
var read = ReadMulti(Type.GetTypeCode(typeof(S)), Type.GetTypeCode(typeof(T)),
Type.GetTypeCode(typeof(U)), Type.GetTypeCode(typeof(V)), Type.GetTypeCode(typeof(W)),
Type.GetTypeCode(typeof(X)), Type.GetTypeCode(typeof(Y)), Type.GetTypeCode(typeof(Z))).ToArray();
s = (S)read[0];
t = (T)read[1];
u = (U)read[2];
v = (V)read[3];
w = (W)read[4];
x = (X)read[5];
y = (Y)read[6];
z = (Z)read[7];
}
static char[] sep = new[] { ' ', '/' };
IEnumerable<object> ReadMulti(params TypeCode[] types)
{
var input = file.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < types.Length; i++) yield return Convert(input[i], types[i]);
}
public T[,] Board<T>(int X, int Y, Func<char, int, int, T> selector)
{
var array = new T[X, Y];
for (var y = 0; y < Y; y++)
{
var str = Get<string>();
for (var x = 0; x < X; x++) array[x, y] = selector(str[x], x, y);
}
return array;
}
}
static class Func
{
public const int Inf = 1073741789; // 2 * Inf < int.MaxValue, and Inf is a prime number
public const long InfL = 4011686018427387913L; // 2 * InfL < long.MaxValue, and InfL is a prime number
public static Comparison<T> DefaultComparison<T>() => (x, y) => Comparer<T>.Default.Compare(x, y);
public static Comparison<T> ToComparison<T>(this IComparer<T> comp) => comp == null ? DefaultComparison<T>() : (x, y) => comp.Compare(x, y);
/// <summary>
/// Find the first number x such that pred(x) is true
/// if pred(x) is false for all min<=x<max, then return max
/// in other words, pred(max) is assumed to be true
/// </summary>
/// <param name="min">inclusive lower limit</param>
/// <param name="max">exclusive upper limit</param>
/// <param name="pred">monotonous predicate, i.e. if pred(a) and a<b, then pred(b)</param>
/// <returns>first number such that satisfy pred</returns>
public static long FirstBinary(long min, long max, Predicate<long> pred)
{
while (min < max)
{
var mid = (min + max) / 2;
if (pred(mid)) max = mid;
else min = mid + 1;
}
return min;
}
/// <summary>
/// Find the first number x such that pred(x) is true
/// if pred(x) is false for all min<=x<max, then return max
/// in other words, pred(max) is assumed to be true
/// </summary>
/// <param name="min">inclusive lower limit</param>
/// <param name="max">exclusive upper limit</param>
/// <param name="pred">monotonous predicate, i.e. if pred(a) and a<b, then pred(b)</param>
/// <returns>first number such that satisfy pred</returns>
public static int FirstBinary(int min, int max, Predicate<int> pred)
{
while (min < max)
{
var mid = (min + max) / 2;
if (pred(mid)) max = mid;
else min = mid + 1;
}
return min;
}
public static Dictionary<T, S> Reverse<S, T>(this IDictionary<S, T> dict)
{
var r = new Dictionary<T, S>();
foreach (var t in dict) r.Add(t.Value, t.Key);
return r;
}
public static void Swap<T>(this IList<T> array, int i, int j) { var tmp = array[i]; array[i] = array[j]; array[j] = tmp; }
public static void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; }
public static T IndexAt<T>(this T[,] array, Pair<int, int> index) => array[index.First, index.Second];
public static bool InRegion(this Pair<int, int> p, int X, int Y) => p.InRegion(0, X, 0, Y);
public static bool InRegion(this Pair<int, int> p, int x, int X, int y, int Y) => p.First >= x && p.Second >= y && p.First < X && p.Second < Y;
/// <summary>
/// get all permutation of 0, 1, ..., n - 1
/// </summary>
/// <param name="n">length of array</param>
/// <param name="func">if you want to change the elements of the array, you must take a copy</param>
public static void Permutation(int n, Action<int[]> func)
{
var array = new int[n];
var unused = new bool[n];
for (var i = 0; i < n; i++) unused[i] = true;
Permutation(n, 0, array, unused, func);
}
static void Permutation(int n, int i, int[] array, bool[] unused, Action<int[]> func)
{
if (i == n) func(array);
else
for (var x = 0; x < n; x++)
if (unused[x])
{
array[i] = x;
unused[x] = false;
Permutation(n, i + 1, array, unused, func);
unused[x] = true;
}
}
public static long Fact(int n)
{
var fact = 1L;
for (var i = 2; i <= n; i++) fact *= i;
return fact;
}
public static Dictionary<long, int> Factorize(this long n, List<int> primes)
{
var d = new Dictionary<long, int>();
for (var j = 0; j < primes.Count; j++)
{
var i = primes[j];
if (i * i > n) break;
if (n % i == 0)
{
d.Add(i, 0);
while (n % i == 0) { n /= i; d[i]++; }
}
}
if (n > 1) d.Add(n, 1);
return d;
}
public static Dictionary<long, int> Factorize(this long n)
{
var d = new Dictionary<long, int>();
for (var i = 2L; i * i <= n; i++)
if (n % i == 0)
{
d.Add(i, 0);
while (n % i == 0) { n /= i; d[i]++; }
}
if (n > 1) d.Add(n, 1);
return d;
}
public static long LCM(long n, long m) => Math.Abs((n / GCD(n, m)) * m);
public static long Divide(long n, long m) => (n - Remainder(n, m)) / m;
public static long Remainder(long n, long m)
{
if (m == 0) throw new DivideByZeroException();
else if (m < 0) return Remainder(n, -m);
else
{
var r = n % m;
return r < 0 ? r + m : r;
}
}
public static long Recurrence(long[] coeff, long[] init, long N, long mod)
{
var K = init.Length;
if (N < 0)
{
var inv = Inverse(coeff[0], mod);
var rc = new long[K];
for (var i = 1; i < K; i++) rc[K - i] = -coeff[i] * inv % mod;
rc[0] = inv;
var ri = new long[K];
for (var i = 0; i < K; i++) ri[K - 1 - i] = init[i];
return Recurrence(rc, ri, K - 1 - N, mod);
}
var tmp = new long[K];
Recurrence(coeff, init, tmp, N, mod);
var sum = 0L;
for (var i = 0; i < K; i++) sum += init[i] * tmp[i] % mod;
sum %= mod;
if (sum < 0) sum += mod;
return sum;
}
public static void Recurrence(long[] coeff, long[] init, long[] state, long N, long mod)
{
var K = init.Length;
if (N < K) state[N] = init[N];
else if ((N & 1) == 0)
{
var tmp = new long[K][];
for (var i = 0; i < K; i++) tmp[i] = new long[K];
Recurrence(coeff, init, tmp[0], N / 2, mod);
for (var i = 1; i < K; i++) tmp[i] = Next(coeff, tmp[i - 1], mod);
for (var i = 0; i < K; i++)
{
state[i] = 0;
for (var j = 0; j < K; j++) state[i] += tmp[0][j] * tmp[j][i] % mod;
state[i] %= mod;
}
}
else if (N < 2 * K || (N & 2) == 0)
{
var tmp = new long[K];
Recurrence(coeff, init, tmp, N - 1, mod);
tmp = Next(coeff, tmp, mod);
for (var i = 0; i < K; i++) state[i] = tmp[i];
}
else
{
var tmp = new long[K];
Recurrence(coeff, init, tmp, N + 1, mod);
tmp = Prev(coeff, tmp, mod);
for (var i = 0; i < K; i++) state[i] = tmp[i];
}
}
static long[] Next(long[] coeff, long[] state, long mod)
{
var K = coeff.Length;
var tmp = new long[K];
for (var i = 0; i < K; i++) tmp[i] = coeff[i] * state[K - 1] % mod;
for (var i = 1; i < K; i++) tmp[i] = (tmp[i] + state[i - 1]) % mod;
return tmp;
}
static long[] Prev(long[] coeff, long[] state, long mod)
{
var K = coeff.Length;
var tmp = new long[K];
var inv = Inverse(coeff[0], mod);
tmp[K - 1] = state[0] * inv % mod;
for (var i = 1; i < K; i++) tmp[i - 1] = (state[i] - coeff[i] * tmp[K - 1] % mod) % mod;
return tmp;
}
// get all primes less than or equal to n
public static List<int> GetPrimes(int n)
{
if (n < 3) n = 3;
var m = (n - 1) >> 1;
var primes = new List<int>((int)(n / Math.Log(n))) { 2 };
var composites = new bool[m];
for (var p = 0; p < m; p++)
{
if (!composites[p])
{
var pnum = 2 * p + 3;
primes.Add(pnum);
for (var k = 3 * p + 3; k < m; k += pnum) composites[k] = true;
}
}
return primes;
}
/// <summary>
/// solve nx+my=1 and returns (x,y)
/// </summary>
/// <param name="n">assumed to be with m</param>
/// <param name="m">assumed to be with n</param>
/// <returns>(x,y) where nx+my=1</returns>
public static Tuple<long, long> SolveLinear(long n, long m)
{
if (n < 0) { var p = SolveLinear(-n, m); return p == null ? p : new Tuple<long, long>(-p.Item1, p.Item2); }
if (m < 0) { var p = SolveLinear(n, -m); return p == null ? p : new Tuple<long, long>(p.Item1, -p.Item2); }
if (n < m) { var p = SolveLinear(m, n); return p == null ? p : new Tuple<long, long>(p.Item2, p.Item1); }
long a = 1, b = 0, c = 0, d = 1;
while (m > 0)
{
var r = n % m;
var q = n / m;
n = m;
m = r;
var tmp = a;
a = -a * q + b;
b = tmp;
tmp = c;
c = -c * q + d;
d = tmp;
}
return n != 1 ? null : new Tuple<long, long>(d, b);
}
public static int GCD(int n, int m)
{
var a = Math.Abs(n);
var b = Math.Abs(m);
if (a < b) { var c = a; a = b; b = c; }
while (b > 0)
{
var c = a % b;
a = b;
b = c;
}
return a;
}
/*public static long GCD(long n, long m)
{
var a = Math.Abs(n);
var b = Math.Abs(m);
if (a < b) { var c = a; a = b; b = c; }
while (b > 0)
{
var c = a % b;
a = b;
b = c;
}
return a;
}*/
public static long GCD(long a, long b)
{
var n = (ulong)Math.Abs(a); var m = (ulong)Math.Abs(b);
if (n == 0) return (long)m; if (m == 0) return (long)n;
int zm = 0, zn = 0;
while ((n & 1) == 0) { n >>= 1; zn++; }
while ((m & 1) == 0) { m >>= 1; zm++; }
while (m != n)
{
if (m > n) { m -= n; while ((m & 1) == 0) m >>= 1; }
else { n -= m; while ((n & 1) == 0) n >>= 1; }
}
return (long)n << Math.Min(zm, zn);
}
public static BigInteger GCD(BigInteger a, BigInteger b) => BigInteger.GreatestCommonDivisor(a, b);
public static long Inverse(long a, long mod)
{
if (a < 0) { a %= mod; if (a < 0) a += mod; }
var t = SolveLinear(a, mod);
return t.Item1 > 0 ? t.Item1 : t.Item1 + mod;
}
public static ulong Pow(ulong a, ulong b, ulong mod)
{
var p = 1uL;
var x = a;
while (b > 0)
{
if ((b & 1) == 1) p = (p * x) % mod;
b >>= 1;
x = (x * x) % mod;
}
return p;
}
public static long Pow(long a, long b, long mod)
{
var p = 1L;
var x = a;
while (b > 0)
{
if ((b & 1) == 1) p = (p * x) % mod;
b >>= 1;
x = (x * x) % mod;
}
return p;
}
public static long Pow(long a, long b)
{
if (a == 1) return 1;
else if (a == 0) { if (b >= 0) return 0; else throw new DivideByZeroException(); }
else if (b < 0) return 0;
var p = 1L;
var x = a;
while (b > 0)
{
if ((b & 1) == 1) p *= x;
b >>= 1;
x *= x;
}
return p;
}
public static ulong Pow(ulong a, ulong b)
{
var p = 1ul;
var x = a;
while (b > 0)
{
if ((b & 1) == 1) p *= x;
b >>= 1;
x *= x;
}
return p;
}
public static long ChineseRemainder(Tuple<long, long> modRemainder1, Tuple<long, long> modRemainder2)
{
var m1 = modRemainder1.Item1;
var m2 = modRemainder2.Item1;
var a1 = modRemainder1.Item2;
var a2 = modRemainder2.Item2;
var t = SolveLinear(m1, m2);
var n1 = t.Item1;
var n2 = t.Item2;
return (m1 * n1 * a2 + m2 * n2 * a1) % (m1 * m2);
}
public static long ChineseRemainder(params Tuple<long, long>[] modRemainder)
{
if (modRemainder.Length == 0) throw new DivideByZeroException();
else if (modRemainder.Length == 1) return modRemainder[0].Item2;
else if (modRemainder.Length == 2) return ChineseRemainder(modRemainder[0], modRemainder[1]);
else
{
var tuple = new Tuple<long, long>(1, 0);
for (var i = 0; i < modRemainder.Length; i++)
{
var tmp = ChineseRemainder(tuple, modRemainder[i]);
tuple = new Tuple<long, long>(tuple.Item1 * modRemainder[i].Item1, tmp);
}
return tuple.Item2;
}
}
// forward transform -> theta= 2*PI/n
// reverse transform -> theta=-2*PI/n, and use a[i]/n instead of a
// O(n*log(n))
public static void FastFourierTransform(int n, double theta, Complex[] a)
{
for (var m = n; m >= 2; m >>= 1)
{
var mh = m >> 1;
for (var i = 0; i < mh; i++)
{
var w = Complex.Exp(i * theta * Complex.ImaginaryOne);
for (var j = i; j < n; j += m)
{
var k = j + mh;
var x = a[j] - a[k];
a[j] += a[k];
a[k] = w * x;
}
}
theta *= 2;
}
var s = 0;
for (var j = 1; j < n - 1; j++)
{
for (var k = n >> 1; k > (s ^= k); k >>= 1) ;
if (j < s) a.Swap(s, j);
}
}
// get table of Euler function
// let return value f, f[i]=phi(i) for 0<=i<=n
// nearly O(n)
public static long[] EulerFunctionTable(long n)
{
if (n < 2) n = 2;
var f = new long[n + 1];
for (var i = 0L; i <= n; i++) f[i] = i;
for (var i = 2L; i <= n; i++) if (f[i] == i) for (var j = i; j <= n; j += i) f[j] = f[j] / i * (i - 1);
return f;
}
// O(sqrt(n))
public static long EulerFunction(long n)
{
var res = n;
for (var i = 2L; i * i <= n; i++)
if (n % i == 0)
{
res = res / i * (i - 1);
do n /= i; while (n % i == 0);
}
if (n != 1) res = res / n * (n - 1);
return res;
}
// get moebius function of d s.t. 0<=d<=n
// O(n)
public static int[] MoebiusFunctionTable(long n)
{
if (n < 2) n = 2;
var f = new int[n + 1];
var p = new bool[n + 1];
for (var i = 0L; i <= n; i++) f[i] = 1;
for (var i = 2L; i <= n; i++) if (!p[i])
{
for (var j = i; j <= n; j += i) { f[j] *= -1; p[j] = true; }
for (var j = i * i; j <= n; j += i * i) f[j] = 0;
}
return f;
}
// get moebius function of d s.t. d|n
// if dict.ContainsKey(d), dict[d]!=0, otherwise moebius function of d is 0
// O(sqrt(n))
public static Dictionary<long, int> MoebiusFunctionOfDivisors(long n)
{
var ps = new List<long>();
for (var i = 2L; i * i <= n; i++)
if (n % i == 0)
{
ps.Add(i);
do n /= i; while (n % i == 0);
}
if (n != 1) ps.Add(n);
var dict = new Dictionary<long, int>();
var m = ps.Count;
for (var i = 0; i < (1 << m); i++)
{
var mu = 1;
var k = 1L;
for (var j = 0; j < m; j++) if ((i & (1 << j)) != 0) { mu *= -1; k *= ps[j]; }
dict.Add(k, mu);
}
return dict;
}
// O(sqrt(n))
public static int MoebiusFunction(long n)
{
var mu = 1;
for (var i = 2L; i * i <= n; i++)
if (n % i == 0)
{
mu *= -1;
if ((n /= i) % i == 0) return 0;
}
return n == 1 ? mu : -mu;
}
// O(sqrt(n))
public static long CarmichaelFunction(long n)
{
var lambda = 1L;
var c = 0;
while (n % 2 == 0) { n /= 2; c++; }
if (c == 2) lambda = 2; else if (c > 2) lambda = 1 << (c - 2);
for (var i = 3L; i * i <= n; i++)
if (n % i == 0)
{
var tmp = i - 1;
n /= i;
while (n % i == 0) { n /= i; tmp *= i; }
lambda = LCM(lambda, tmp);
}
if (n != 1) lambda = LCM(lambda, n - 1);
return lambda;
}
// a+bi is Gaussian prime or not
public static bool IsGaussianPrime(ulong a, ulong b)
{
if (a == 0) return b % 4 == 3 && IsPrime(b);
else if (b == 0) return a % 4 == 3 && IsPrime(a);
else return IsPrime(a * a + b * b);
}
// nearly O(200)
public static bool IsPrime(ulong n)
{
if (n <= 1 || (n > 2 && n % 2 == 0)) return false;
var test = new uint[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 111 };
var d = n - 1;
var s = 0;
while (d % 2 == 0) { ++s; d /= 2; }
Predicate<ulong> f = t =>
{
var x = Pow(t, d, n);
if (x == 1) return true;
for (var r = 0L; r < s; r++)
{
if (x == n - 1) return true;
x = (x * x) % n;
}
return false;
};
for (var i = 0; test[i] < n && test[i] != 111; i++) if (!f(test[i])) return false;
return true;
}
public static decimal MeasureTime(Action action)
{
var sw = new Stopwatch();
sw.Restart();
action();
sw.Stop();
return sw.ElapsedTicks * 1000m / Stopwatch.Frequency;
}
public static double MeasureTime2(Action action)
{
var sw = new Stopwatch();
sw.Restart();
action();
sw.Stop();
return sw.ElapsedTicks * 1000.0 / Stopwatch.Frequency;
}
static readonly double GoldenRatio = 2 / (3 + Math.Sqrt(5));
// assume f is 凹
// find c s.t. a<=c<=b and for all a<=x<=b, f(c)<=f(x)
public static double GoldenSectionSearch(double a, double b, Func<double, double> f)
{
double c = a + GoldenRatio * (b - a), d = b - GoldenRatio * (b - a);
double fc = f(c), fd = f(d);
while (d - c > 1e-9)
{
if (fc > fd)
{
a = c; c = d; d = b - GoldenRatio * (b - a);
fc = fd; fd = f(d);
}
else
{
b = d; d = c; c = a + GoldenRatio * (b - a);
fd = fc; fc = f(c);
}
}
return c;
}
// O(NW)
public static int KnapsackW(int[] w, int[] v, int W)
{
var N = w.Length;
var dp = new int[W + 1];
for (var i = 0; i < N; i++) for (var j = W; j >= w[i]; j--) dp[j] = Math.Max(dp[j], v[i] + dp[j - w[i]]);
return dp[W];
}
// O(NV)
public static int KnapsackV(int[] w, int[] v, int W)
{
var N = w.Length;
var V = v.Sum();
var dp = new int[V + 1];
for (var i = 1; i <= V; i++) dp[i] = Inf;
for (var i = 0; i < N; i++) for (var j = V; j >= v[i]; j--)
dp[j] = Math.Min(dp[j], w[i] + dp[j - v[i]]);
for (var j = V; j >= 0; j--) if (dp[j] <= W) return j;
return 0;
}
// O(N*2^(N/2))
public static long KnapsackN(long[] w, long[] v, int W)
{
var N = w.Length;
var half = N / 2;
var items = new Tuple<long, long>[N];
for (var i = 0; i < N; i++) items[i] = new Tuple<long, long>(w[i], v[i]);
Array.Sort(items, (x, y) => x.Item1.CompareTo(y.Item1));
Func<int, int, List<Pair<long, long>>> gen = (start, end) =>
{
if (start >= end) return new List<Pair<long, long>>();
var lim = 1 << (end - start);
var list = new List<Pair<long, long>>();
for (var i = 0; i < lim; i++)
{
var weight = 0L;
var value = 0L;
var tmp = i;
for (var j = start; j < end; j++)
{
if ((tmp & 1) == 1) { weight += items[j].Item1; value += items[j].Item2; }
tmp >>= 1;
}
if (weight <= W) list.Add(new Pair<long, long>(weight, value));
}
list.Sort((x, y) => { var c = x.First.CompareTo(y.First); return c == 0 ? x.Second.CompareTo(y.Second) : c; });
var n = list.Count;
if (n == 0) return list;
for (var i = list.Count - 2; i >= 0; i--) if (list[i].First == list[i + 1].First) list[i].Second = Math.Max(list[i].Second, list[i + 1].Second);
var small = new List<Pair<long, long>>();
var last = -1;
while (last + 1 < n)
{
var tmp = list[last + 1].First;
last = FirstBinary(last + 1, n, x => list[x].First > tmp) - 1;
if (small.Count == 0 || list[last].Second > small[small.Count - 1].Second) small.Add(list[last]);
}
return small;
};
var first = gen(0, half);
var second = gen(half, N);
var max = 0L;
var last2 = second.Count;
foreach (var item in first)
{
last2 = FirstBinary(0, last2, x => second[x].First > W - item.First) - 1;
if (last2 < 0) break;
if (second[last2].First <= W - item.First) SetToMax(ref max, item.Second + second[last2].Second);
last2++;
}
return max;
}
// nums[i] が counts[i] 個
// K is partial sum?
// O(NK)
public static bool PartialSum(int[] nums, int[] counts, int K)
{
var N = nums.Length;
var memo = new int[K + 1];
for (var s = 1; s <= K; s++) memo[s] = -1;
for (var n = 0; n < N; n++) for (var s = 0; s <= K; s++) memo[s] = memo[s] >= 0 ? counts[n] : s < nums[n] ? -1 : memo[s - nums[n]] - 1;
return memo[K] >= 0;
}
// O(N log(N))
public static int LongestIncreasingSubsequence(int[] a)
{
var N = a.Length;
var memo = new int[N];
memo.MemberSet(Inf);
for (var n = 0; n < N; n++)
{
var k = FirstBinary(0, N, x => a[n] <= memo[x]);
memo[k] = a[n];
}
return FirstBinary(0, N, x => memo[x] == Inf);
}
// O(nm)
public static int LongestCommonSubsequence(string s, string t)
{
var n = s.Length;
var m = t.Length;
var memo = new int[n + 1, m + 1];
for (var i = n - 1; i >= 0; i--)
for (var j = m - 1; j >= 0; j--)
if (s[i] == t[j]) memo[i, j] = memo[i + 1, j + 1] + 1;
else memo[i, j] = Math.Max(memo[i + 1, j], memo[i, j + 1]);
return memo[0, 0];
}
// the number of ways of dividing N to M numbers
// O(NM)
public static int Partition(int N, int M, int Mod)
{
var memo = new long[N + 1, M + 1];
for (var m = 0; m <= M; m++) memo[0, m] = 1;
for (var n = 1; n <= N; n++)
{
memo[n, 0] = 0;
for (var m = 1; m <= M; m++) memo[n, m] = (memo[n, m - 1] + (n - m >= 0 ? memo[n - m, m] : 0)) % Mod;
}
return (int)memo[N, M];
}
// max{f(a)+...+f(b-1) | from<=a<b<=to}
// O(to-from)
public static long MaxIntervalSum(int from, int to, Func<long, long> f)
{
long max, dp;
max = dp = f(from);
for (var i = from + 1; i < to; i++)
{
var tmp = f(i);
dp = tmp + Math.Max(0, dp);
max = Math.Max(max, dp);
}
return max;
}
public static int MaxElement<T>(this IEnumerable<T> source, Comparison<T> comp)
{
var p = source.GetEnumerator();
if (!p.MoveNext()) return -1;
var max = p.Current;
var mi = 0;
var i = 0;
while (p.MoveNext())
{
i++;
if (comp(max, p.Current) < 0) { max = p.Current; mi = i; }
}
return mi;
}
public static int MaxElement<T>(this IEnumerable<T> source) where T : IComparable<T> => source.MaxElement((x, y) => x.CompareTo(y));
public static int MinElement<T>(IEnumerable<T> source, Comparison<T> comp) => source.MaxElement((x, y) => comp(y, x));
public static int MinElement<T>(IEnumerable<T> source) where T : IComparable<T> => source.MaxElement((x, y) => y.CompareTo(x));
public static void Shuffle<T>(IList<T> source, Random rand) { for (var i = source.Count - 1; i >= 0; --i) source.Swap(i, rand.Next(0, i + 1)); }
public static void Shuffle<T>(IList<T> source, RandomSFMT rand) { for (var i = source.Count - 1; i >= 0; --i) source.Swap(i, rand.Next(0, i + 1)); }
public static char NextChar(this Random rand) => (char)(rand.Next(0, 'z' - 'a' + 1) + 'a');
public static char NextChar(this RandomSFMT rand) => (char)(rand.Next(0, 'z' - 'a' + 1) + 'a');
public static string NextString(this Random rand, int length) => new string(Enumerable.Range(0, length).Select(_ => rand.NextChar()).ToArray());
public static string NextString(this RandomSFMT rand, int length) => new string(Enumerable.Range(0, length).Select(_ => rand.NextChar()).ToArray());
public static IEnumerable<T> Rotate<T>(this IEnumerable<T> source)
{
var e = source.GetEnumerator();
if (e.MoveNext())
{
var f = e.Current;
while (e.MoveNext()) yield return e.Current;
yield return f;
}
}
public static T Apply<T>(this Func<T, T> func, T x, int n)
{
var a = x;
for (var i = 0; i < n; i++) a = func(a);
return a;
}
public static void MemberSet<T>(this T[] array, T value)
{
var X = array.Length;
for (var x = 0; x < X; x++) array[x] = value;
}
public static void MemberSet<T>(this T[,] array, T value)
{
var X = array.GetLength(0); var Y = array.GetLength(1);
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) array[x, y] = value;
}
public static void MemberSet<T>(this T[,,] array, T value)
{
var X = array.GetLength(0); var Y = array.GetLength(1); var Z = array.GetLength(2);
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) for (var z = 0; z < Z; z++) array[x, y, z] = value;
}
public static void MemberSet<T>(this T[,,,] array, T value)
{
var X = array.GetLength(0); var Y = array.GetLength(1); var Z = array.GetLength(2); var W = array.GetLength(3);
for (var x = 0; x < X; x++) for (var y = 0; y < Y; y++) for (var z = 0; z < Z; z++) for (var w = 0; w < W; w++) array[x, y, z, w] = value;
}
public static string ToYesNo(this bool flag) => flag ? "YES" : "NO";
public static int SetToMin(ref int min, int other) => min = Math.Min(min, other);
public static int SetToMax(ref int max, int other) => max = Math.Max(max, other);
public static long SetToMin(ref long min, long other) => min = Math.Min(min, other);
public static long SetToMax(ref long max, long other) => max = Math.Max(max, other);
public static Tuple<SortedDictionary<int, int>, SortedDictionary<int, int>> Compress(IEnumerable<int> coord, int width, int X)
{
var tmp = new SortedSet<int>();
foreach (var x in coord)
{
for (var w = -width; w <= width; w++)
if (x + w < 0 || x + w >= X) continue;
else if (tmp.Contains(x + w)) continue;
else tmp.Add(x + w);
}
var index = 0;
var inverse = new SortedDictionary<int, int>();
var dict = new SortedDictionary<int, int>();
foreach (var pair in tmp)
{
dict.Add(pair, index);
inverse.Add(index++, pair);
}
return new Tuple<SortedDictionary<int, int>, SortedDictionary<int, int>>(dict, inverse);
}
public static int MSB(uint n)
{
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return BitCount(n) - 1;
}
public static int BitCount(uint n)
{
n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff);
return (int)((n & 0x0000ffff) + ((n >> 16) & 0x0000ffff));
}
public static int LSB(uint n)
{
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
n |= (n << 16);
return 32 - BitCount(n);
}
public static int MSB(ulong n)
{
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
n |= (n >> 32);
return BitCount(n) - 1;
}
public static int BitCount(ulong n)
{
n = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555);
n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333);
n = (n & 0x0f0f0f0f0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f0f0f0f0f);
n = (n & 0x00ff00ff00ff00ff) + ((n >> 8) & 0x00ff00ff00ff00ff);
n = (n & 0x0000ffff0000ffff) + ((n >> 16) & 0x0000ffff0000ffff);
return (int)((n & 0x00000000ffffffff) + ((n >> 32) & 0x00000000ffffffff));
}
public static int LSB(ulong n)
{
n |= (n << 1);
n |= (n << 2);
n |= (n << 4);
n |= (n << 8);
n |= (n << 16);
n |= (n << 32);
return 64 - BitCount(n);
}
public static int Abs(this int n) => Math.Abs(n);
public static long Abs(this long n) => Math.Abs(n);
public static double Abs(this double n) => Math.Abs(n);
public static float Abs(this float n) => Math.Abs(n);
public static decimal Abs(this decimal n) => Math.Abs(n);
public static short Abs(this short n) => Math.Abs(n);
public static sbyte Abs(this sbyte n) => Math.Abs(n);
public static int Min(params int[] nums) { var min = int.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static long Min(params long[] nums) { var min = long.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static uint Min(params uint[] nums) { var min = uint.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static ulong Min(params ulong[] nums) { var min = ulong.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static double Min(params double[] nums) { var min = double.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static decimal Min(params decimal[] nums) { var min = decimal.MaxValue; foreach (var n in nums) min = Math.Min(min, n); return min; }
public static int Max(params int[] nums) { var min = int.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static long Max(params long[] nums) { var min = long.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static uint Max(params uint[] nums) { var min = uint.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static ulong Max(params ulong[] nums) { var min = ulong.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static double Max(params double[] nums) { var min = double.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static decimal Max(params decimal[] nums) { var min = decimal.MinValue; foreach (var n in nums) min = Math.Max(min, n); return min; }
public static void MultiKeySort(this string[] list) => new MultiSorter(list).QuickSort();
class MultiSorter
{
const int MIN = 0;
string[] a;
int max;
public MultiSorter(string[] l) { a = l; max = a.Max(s => s.Length); }
public void QuickSort() { if (a.Length >= 2) QuickSort(0, a.Length, 0); }
public int At(int i, int z) => z < a[i].Length ? a[i][z] : MIN;
public int At(string s, int z) => z < s.Length ? s[z] : MIN;
public void QuickSort(int l, int r, int z)
{
int w = r - l, pl = l, pm = l + w / 2, pn = r - 1, c;
if (w > 30)
{
var d = w / 8;
pl = Median(pl, pl + d, pl + 2 * d, z);
pm = Median(pm - d, pm, pm + d, z);
pn = Median(pn - 2 * d, pn - d, pn, z);
}
pm = Median(pl, pm, pn, z);
var s = a[pm]; a[pm] = a[l]; a[l] = s;
var pivot = At(l, z);
int i = l + 1, x = l + 1, j = r - 1, y = r - 1;
while (true)
{
while (i <= j && (c = At(i, z) - pivot) <= 0)
{
if (c == 0) { if (i != x) { s = a[i]; a[i] = a[x]; a[x] = s; } x++; }
i++;
}
while (i <= j && (c = At(j, z) - pivot) >= 0)
{
if (c == 0) { if (j != y) { s = a[j]; a[j] = a[y]; a[y] = s; } y--; }
j--;
}
if (i > j) break;
s = a[i]; a[i] = a[j]; a[j] = s;
i++; j--;
}
j++; y++;
var m = Min(x - l, i - x); SwapRegion(l, i - m, m);
m = Min(y - j, r - y); SwapRegion(i, r - m, m);
i += l - x;
j += r - y;
if (i - l >= 10) QuickSort(l, i, z); else InsertSort(l, i, z);
if (pivot != MIN) if (j - i >= 10) QuickSort(i, j, z + 1); else InsertSort(i, j, z + 1);
if (r - j >= 10) QuickSort(j, r, z); else InsertSort(j, r, z);
}
private void SwapRegion(int p, int q, int n)
{
string s;
while (n-- > 0) { s = a[p]; a[p++] = a[q]; a[q++] = s; }
}
private void InsertSort(int l, int r, int z)
{
string s;
for (var i = l + 1; i < r; i++)
{
var tmp = a[i];
int x = z, y = z, p, q;
s = a[i - 1];
while ((p = At(tmp, x++)) == (q = At(s, y++)) && p != MIN) ;
if (q > p)
{
var j = i;
while (true)
{
a[j] = a[j - 1];
--j;
if (j <= l) break;
x = y = z;
s = a[j - 1];
while ((p = At(tmp, x++)) == (q = At(s, y++)) && p != MIN) ;
if (q <= p) break;
}
a[j] = tmp;
}
}
}
private int Median(int a, int b, int c, int z)
{
int p = At(a, z), q = At(b, z);
if (p == q) return a;
var r = At(c, z);
if (r == p || r == q) return c;
return p < q ?
(q < r ? b : (p < r ? c : a))
: (q > r ? b : (p < r ? a : c));
}
}
}
class RandomSFMT : Random
{
int index, coin_bits, byte_pos, range, shift;
uint coin_save, byte_save, bse;
protected uint[] x = new uint[40];
static uint[] ParityData = { 0x00000001U, 0x00000000U, 0x00000000U, 0x20000000U };
public virtual void GenRandAll()
{
int a = 0, b = 28, c = 32, d = 36; uint y; var p = x;
do
{
y = p[a + 3] ^ (p[a + 3] << 24) ^ (p[a + 2] >> 8) ^ ((p[b + 3] >> 5) & 0xb5ffff7fU);
p[a + 3] = y ^ (p[c + 3] >> 8) ^ (p[d + 3] << 14);
y = p[a + 2] ^ (p[a + 2] << 24) ^ (p[a + 1] >> 8) ^ ((p[b + 2] >> 5) & 0xaff3ef3fU);
p[a + 2] = y ^ ((p[c + 2] >> 8) | (p[c + 3] << 24)) ^ (p[d + 2] << 14);
y = p[a + 1] ^ (p[a + 1] << 24) ^ (p[a] >> 8) ^ ((p[b + 1] >> 5) & 0x7fefcfffU);
p[a + 1] = y ^ ((p[c + 1] >> 8) | (p[c + 2] << 24)) ^ (p[d + 1] << 14);
y = p[a] ^ (p[a] << 24) ^ ((p[b] >> 5) & 0xf7fefffdU);
p[a] = y ^ ((p[c] >> 8) | (p[c + 1] << 24)) ^ (p[d] << 14);
c = d; d = a; a += 4; b += 4;
if (b == 40) b = 0;
} while (a != 40);
}
void PeriodCertification()
{
uint work, inner = 0; int i, j;
index = 40; range = 0; coin_bits = 0; byte_pos = 0;
for (i = 0; i < 4; i++) inner ^= x[i] & ParityData[i];
for (i = 16; i > 0; i >>= 1) inner ^= inner >> i;
inner &= 1;
if (inner == 1) return;
for (i = 0; i < 4; i++) for (j = 0, work = 1; j < 32; j++, work <<= 1) if ((work & ParityData[i]) != 0) { x[i] ^= work; return; }
}
public void InitMt(uint s)
{
unchecked
{
x[0] = s;
for (uint p = 1; p < 40; p++) x[p] = s = 1812433253 * (s ^ (s >> 30)) + p;
PeriodCertification();
}
}
public RandomSFMT(uint s) { InitMt(s); }
public void InitMtEx(uint[] init_key)
{
uint r, i, j, c, key_len = (uint)init_key.Length;
unchecked
{
for (i = 0; i < 40; i++) x[i] = 0x8b8b8b8b;
if (key_len + 1 > 40) c = key_len + 1; else c = 40;
r = x[0] ^ x[17] ^ x[39]; r = (r ^ (r >> 27)) * 1664525;
x[17] += r; r += key_len; x[22] += r; x[0] = r; c--;
for (i = 1, j = 0; j < c && j < key_len; j++)
{
r = x[i] ^ x[(i + 17) % 40] ^ x[(i + 39) % 40];
r = (r ^ (r >> 27)) * 1664525; x[(i + 17) % 40] += r;
r += init_key[j] + i; x[(i + 22) % 40] += r;
x[i] = r; i = (i + 1) % 40;
}
for (; j < c; j++)
{
r = x[i] ^ x[(i + 17) % 40] ^ x[(i + 39) % 40];
r = (r ^ (r >> 27)) * 1664525; x[(i + 17) % 40] += r; r += i;
x[(i + 22) % 40] += r; x[i] = r; i = (i + 1) % 40;
}
for (j = 0; j < 40; j++)
{
r = x[i] + x[(i + 17) % 40] + x[(i + 39) % 40];
r = (r ^ (r >> 27)) * 1566083941; x[(i + 17) % 40] ^= r;
r -= i; x[(i + 22) % 40] ^= r; x[i] = r; i = (i + 1) % 40;
}
PeriodCertification();
}
}
public RandomSFMT(uint[] init_key) { InitMtEx(init_key); }
public RandomSFMT() : this((uint)(DateTime.Now.Ticks & 0xffffffff)) { }
public uint NextMt() { if (index == 40) { GenRandAll(); index = 0; } return x[index++]; }
public int NextInt(int n) => (int)(n * (1.0 / 4294967296.0) * NextMt());
public double NextUnif() { uint z = NextMt() >> 11, y = NextMt(); return (y * 2097152.0 + z) * (1.0 / 9007199254740992.0); }
public int NextBit() { if (--coin_bits == -1) { coin_bits = 31; return (int)(coin_save = NextMt()) & 1; } else return (int)(coin_save >>= 1) & 1; }
public int NextByte() { if (--byte_pos == -1) { byte_pos = 3; return (int)(byte_save = NextMt()) & 255; } else return (int)(byte_save >>= 8) & 255; }
public override int Next(int maxValue) => Next(0, maxValue);
protected override double Sample() => NextUnif();
public override double NextDouble() => NextUnif();
public override int Next() => 1 + NextIntEx(int.MaxValue);
public override void NextBytes(byte[] buffer) { for (var i = 0; i < buffer.Length; i++) buffer[i] = (byte)NextByte(); }
public override int Next(int min, int max) => min + NextIntEx(max - min);
public int NextIntEx(int range_)
{
uint y_, base_, remain_; int shift_;
if (range_ <= 0) return 0;
if (range_ != range)
{
bse = (uint)(range = range_);
for (shift = 0; bse <= (1UL << 30); shift++) bse <<= 1;
}
while (true)
{
y_ = NextMt() >> 1;
if (y_ < bse) return (int)(y_ >> shift);
base_ = bse; shift_ = shift; y_ -= base_;
remain_ = (1U << 31) - base_;
for (; remain_ >= (uint)range_; remain_ -= base_)
{
for (; base_ > remain_; base_ >>= 1) shift_--;
if (y_ < base_) return (int)(y_ >> shift_);
else y_ -= base_;
}
}
}
}
Code 2: <?php
ini_set('error_reporting', E_ALL & ~E_NOTICE);
// define('DEBUG', true);
define('DEBUG', false);
fscanf(STDIN, "%d %d %d", $N, $A, $B);
for ($i = 0; $i < $N; $i++) {
fscanf(STDIN, "%d", $h[$i]);
}
rsort($h);
$total = array_sum($h);
$mmax = ceil($h[0] / $B);
$mmin = ceil($total / ($A + $B * ($N - 1)));
if (DEBUG) echo "mmin:{$mmin} mmax:{$mmax}\n";
$mmin--;
// exit;
$ans[$mmax] = true;
$ans[$mmin] = false;
// for ($i = $mmin; $i <= $mmax; $i++) {
// printf("%d %s\n", $i, getEnable($i));
// }
while (true) {
$mid = ceil(($mmin + $mmax) / 2);
$result = getEnable($mid);
if (DEBUG) printf("%d %d %d %s\n", $mid, $mmin, $mmax, $result);
$ans[$mid] = $result;
if ($result === false) {
if ($ans[$mid+1] === true) {
exit(($mid + 1) . "\n");
}
$mmin = $mid;
} else {
if ($ans[$mid-1] === false) {
exit($mid . "\n");
}
$mmax = $mid;
}
foreach ($ans as $key => $val) {
if (DEBUG) echo "RRR {$key} {$val}\n";
}
// sleep(1);
}
function getEnable($x) {
global $N, $A, $B, $h;
$xx = $x;
$base = $B * $x;
for ($i = 0; $i < $N; $i++) {
if ($base >= $h[$i]) {
return true;
}
$rest = $h[$i] - $base;
$need = ceil($rest / ($A - $B));
$x -= $need;
if ($x < 0) {
return false;
}
}
return true;
} |
C++ | #include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <stack>
#include <tuple>
#include <bitset>
#include <algorithm>
#include <functional>
#include <utility>
#include <iomanip>
#define int long long int
#define rep(i, n) for(int i = 0; i < (n); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() )
using namespace std;
typedef pair<int, int> P;
const int INF = 1e15;
const int MOD = 1e9+7;
template <typename T>
class union_find{
public:
int n;
vector<T> p, rank;
union_find(int n)
: n(n), p(n, -1), rank(n) {}
int find(int v){
if(p[v] == -1){
return v;
}
p[v] = find(p[v]);
return p[v];
}
void unite(int u, int v){
int u_root = find(u);
int v_root = find(v);
if(u_root == v_root){
return;
}
if(rank[u_root] < rank[v_root]){
swap(u_root, v_root);
}
if(rank[u_root] == rank[v_root]){
rank[u_root]++;
}
p[v_root] = u_root;
}
};
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<int> a(n);
rep(i, n) {
cin >> a[i];
}
union_find<int> uf(n);
rep(i, m){
int x, y;
cin >> x >> y;
uf.unite(x, y);
}
if(m == n - 1){
cout << 0 << endl;
return 0;
}
if(n < 2 * (n - m - 1)){
cout << "Impossible" << endl;
return 0;
}
priority_queue<P, vector<P>, greater<P>> pq;
vector<bool> used(n, false);
rep(i, n){
pq.emplace(a[i], uf.find(i));
}
int ans = 0;
int remain = 2 * (n - m - 1) - (n - m);
rep(i, n){
int cost = pq.top().first;
int v = pq.top().second;
pq.pop();
if(not used[v]){
used[v] = true;
ans += cost;
continue;
}
if(remain > 0){
ans += cost;
remain--;
}
}
cout << ans << endl;
return 0;
}
| Python | import sys
# 入力を整数に変換して受け取る
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
# 入力全てを整数に変換したものの配列を受け取る
def LI(): return list(map(int, sys.stdin.readline().split()))
# 入力全てを整数に変換して1引いたものの配列を受け取る
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SR(): return sys.stdin.readline().rstrip()
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_uppercase2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
# リストを改行区切りで出力する
p2D = lambda x: print(*x, sep="\n")
p2E = lambda x: print(''.join(x))
p2S = lambda x: print(*x, sep=" ")
n=II()
l=LI()
cnt = 0
for i in range(1, n+1):
if l[i-1] != i:
cnt+=1
if cnt == 0 or cnt == 2:
print('YES')
else:
print('NO') | No | Do these codes solve the same problem?
Code 1: #include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <stack>
#include <tuple>
#include <bitset>
#include <algorithm>
#include <functional>
#include <utility>
#include <iomanip>
#define int long long int
#define rep(i, n) for(int i = 0; i < (n); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() )
using namespace std;
typedef pair<int, int> P;
const int INF = 1e15;
const int MOD = 1e9+7;
template <typename T>
class union_find{
public:
int n;
vector<T> p, rank;
union_find(int n)
: n(n), p(n, -1), rank(n) {}
int find(int v){
if(p[v] == -1){
return v;
}
p[v] = find(p[v]);
return p[v];
}
void unite(int u, int v){
int u_root = find(u);
int v_root = find(v);
if(u_root == v_root){
return;
}
if(rank[u_root] < rank[v_root]){
swap(u_root, v_root);
}
if(rank[u_root] == rank[v_root]){
rank[u_root]++;
}
p[v_root] = u_root;
}
};
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<int> a(n);
rep(i, n) {
cin >> a[i];
}
union_find<int> uf(n);
rep(i, m){
int x, y;
cin >> x >> y;
uf.unite(x, y);
}
if(m == n - 1){
cout << 0 << endl;
return 0;
}
if(n < 2 * (n - m - 1)){
cout << "Impossible" << endl;
return 0;
}
priority_queue<P, vector<P>, greater<P>> pq;
vector<bool> used(n, false);
rep(i, n){
pq.emplace(a[i], uf.find(i));
}
int ans = 0;
int remain = 2 * (n - m - 1) - (n - m);
rep(i, n){
int cost = pq.top().first;
int v = pq.top().second;
pq.pop();
if(not used[v]){
used[v] = true;
ans += cost;
continue;
}
if(remain > 0){
ans += cost;
remain--;
}
}
cout << ans << endl;
return 0;
}
Code 2: import sys
# 入力を整数に変換して受け取る
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
# 入力全てを整数に変換したものの配列を受け取る
def LI(): return list(map(int, sys.stdin.readline().split()))
# 入力全てを整数に変換して1引いたものの配列を受け取る
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SR(): return sys.stdin.readline().rstrip()
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_uppercase2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
# リストを改行区切りで出力する
p2D = lambda x: print(*x, sep="\n")
p2E = lambda x: print(''.join(x))
p2S = lambda x: print(*x, sep=" ")
n=II()
l=LI()
cnt = 0
for i in range(1, n+1):
if l[i-1] != i:
cnt+=1
if cnt == 0 or cnt == 2:
print('YES')
else:
print('NO') |
C++ | #include<bits/stdc++.h>
using namespace std;
#define I INT32_MAX
#define IM INT_MIN
#define MOD 1000000007
#define ll long long
#define lli long long int
#define rep(i,n) for (int i = 0; i < n; i++)
#define repk(i,k,n) for (int i = k; i <= n; i++)
#define repr(i,k,n) for (int i = k; i >= n; i--)
#define all(v) (v).begin(),(v).end()
typedef vector<int> vi;
typedef set<int> si;
void solve() {
ll n, k;
cin >> n >> k;
vi arr(n + 1);
vi dp(n + 1, INT_MAX);
rep(i, n) {
cin >> arr[i];
}
dp[0] = 0;
dp[1] = abs(arr[1] - arr[0]);
for (int i = 2; i < n; ++i)
{
for (int j = i - 1, jump = 0; j >= 0 and jump < k ; j-- , jump++) {
dp[i] = min(dp[i] , dp[j] + abs(arr[i] - arr[j]));
}
}
cout << dp[n - 1] << endl;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
// cin >> t;
while (t--)
solve();
}
| C | #include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// 内部定数
#define D_GRP_MAX 200000 // 最大グループ数
// 内部構造体 - グループ情報
typedef struct Grp {
int miNo; // グループ番号
int miCnt; // 人数
} Grp;
// 内部変数
static FILE *szpFpI; // 入力
static Grp sz1Grp[D_GRP_MAX]; // グループ
// 内部変数 - テスト用
#ifdef D_TEST
static int siRes;
static FILE *szpFpA;
static int siTNo;
#endif
// 1行出力
int
fOutLine(
char *pcpLine // <I> 1行
)
{
char lc1Buf[1024];
#ifdef D_TEST
lc1Buf[0] = '\0';
fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
if (strcmp(lc1Buf, pcpLine)) {
siRes = -1;
}
#else
printf("%s", pcpLine);
#endif
return 0;
}
// 最大値 - 取得
int
fGetMaxI(
int piVal1 // <I> 値1
, int piVal2 // <I> 値2
)
{
if (piVal1 > piVal2) {
return piVal1;
}
else {
return piVal2;
}
}
// グループ番号 - 取得
int
fGNoGet(
int piNo // <I> 配列番号 0~
)
{
// グループ番号 - チェック
if (piNo == sz1Grp[piNo].miNo) {
return piNo;
}
// グループ番号 - 取得
sz1Grp[piNo].miNo = fGNoGet(sz1Grp[piNo].miNo);
return sz1Grp[piNo].miNo;
}
// 同一グループ化
int
fGrpConv(
int piNo1 // <I> 配列番号1 0~
, int piNo2 // <I> 配列番号2 0~
)
{
// グループ番号 - 取得
int liGNo1 = fGNoGet(piNo1);
int liGNo2 = fGNoGet(piNo2);
if (liGNo1 == liGNo2) {
return 0;
}
// 同一グループ化
sz1Grp[liGNo2].miNo = liGNo1;
sz1Grp[liGNo1].miCnt += sz1Grp[liGNo2].miCnt;
return sz1Grp[liGNo1].miCnt;
}
// 実行メイン
int
fMain(
)
{
int i;
char lc1Buf[1024];
// 人数・関係数 - 取得
int liHCnt, liRCnt;
fgets(lc1Buf, sizeof(lc1Buf), szpFpI);
sscanf(lc1Buf, "%d%d", &liHCnt, &liRCnt);
// グループ番号 - 初期化
for (i = 0; i < liHCnt; i++) {
sz1Grp[i].miNo = i;
sz1Grp[i].miCnt = 1;
}
// 関係 - 取得
int liMax = 1;
for (i = 0; i < liRCnt; i++) {
int liNo1, liNo2;
fgets(lc1Buf, sizeof(lc1Buf), szpFpI);
sscanf(lc1Buf, "%d%d", &liNo1, &liNo2);
int liCnt = fGrpConv(liNo1 - 1, liNo2 - 1);
liMax = fGetMaxI(liMax, liCnt);
}
return liMax;
}
// 1回実行
int
fOne(
)
{
int liRet;
char lc1Buf[1024];
// 入力 - セット
#ifdef D_TEST
sprintf(lc1Buf, ".\\Test\\T%d.txt", siTNo);
szpFpI = fopen(lc1Buf, "r");
sprintf(lc1Buf, ".\\Test\\A%d.txt", siTNo);
szpFpA = fopen(lc1Buf, "r");
siRes = 0;
#else
szpFpI = stdin;
#endif
// 実行メイン
liRet = fMain();
// 出力
sprintf(lc1Buf, "%d\n", liRet);
fOutLine(lc1Buf);
// 残データ有無
#ifdef D_TEST
lc1Buf[0] = '\0';
fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
if (strcmp(lc1Buf, "")) {
siRes = -1;
}
#endif
// テストファイルクローズ
#ifdef D_TEST
fclose(szpFpI);
fclose(szpFpA);
#endif
// テスト結果
#ifdef D_TEST
if (siRes == 0) {
printf("OK %d\n", siTNo);
}
else {
printf("NG %d\n", siTNo);
}
#endif
return 0;
}
// プログラム開始
int
main()
{
#ifdef D_TEST
int i;
for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) {
siTNo = i;
fOne();
}
#else
fOne();
#endif
return 0;
}
| No | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
using namespace std;
#define I INT32_MAX
#define IM INT_MIN
#define MOD 1000000007
#define ll long long
#define lli long long int
#define rep(i,n) for (int i = 0; i < n; i++)
#define repk(i,k,n) for (int i = k; i <= n; i++)
#define repr(i,k,n) for (int i = k; i >= n; i--)
#define all(v) (v).begin(),(v).end()
typedef vector<int> vi;
typedef set<int> si;
void solve() {
ll n, k;
cin >> n >> k;
vi arr(n + 1);
vi dp(n + 1, INT_MAX);
rep(i, n) {
cin >> arr[i];
}
dp[0] = 0;
dp[1] = abs(arr[1] - arr[0]);
for (int i = 2; i < n; ++i)
{
for (int j = i - 1, jump = 0; j >= 0 and jump < k ; j-- , jump++) {
dp[i] = min(dp[i] , dp[j] + abs(arr[i] - arr[j]));
}
}
cout << dp[n - 1] << endl;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
// cin >> t;
while (t--)
solve();
}
Code 2: #include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// 内部定数
#define D_GRP_MAX 200000 // 最大グループ数
// 内部構造体 - グループ情報
typedef struct Grp {
int miNo; // グループ番号
int miCnt; // 人数
} Grp;
// 内部変数
static FILE *szpFpI; // 入力
static Grp sz1Grp[D_GRP_MAX]; // グループ
// 内部変数 - テスト用
#ifdef D_TEST
static int siRes;
static FILE *szpFpA;
static int siTNo;
#endif
// 1行出力
int
fOutLine(
char *pcpLine // <I> 1行
)
{
char lc1Buf[1024];
#ifdef D_TEST
lc1Buf[0] = '\0';
fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
if (strcmp(lc1Buf, pcpLine)) {
siRes = -1;
}
#else
printf("%s", pcpLine);
#endif
return 0;
}
// 最大値 - 取得
int
fGetMaxI(
int piVal1 // <I> 値1
, int piVal2 // <I> 値2
)
{
if (piVal1 > piVal2) {
return piVal1;
}
else {
return piVal2;
}
}
// グループ番号 - 取得
int
fGNoGet(
int piNo // <I> 配列番号 0~
)
{
// グループ番号 - チェック
if (piNo == sz1Grp[piNo].miNo) {
return piNo;
}
// グループ番号 - 取得
sz1Grp[piNo].miNo = fGNoGet(sz1Grp[piNo].miNo);
return sz1Grp[piNo].miNo;
}
// 同一グループ化
int
fGrpConv(
int piNo1 // <I> 配列番号1 0~
, int piNo2 // <I> 配列番号2 0~
)
{
// グループ番号 - 取得
int liGNo1 = fGNoGet(piNo1);
int liGNo2 = fGNoGet(piNo2);
if (liGNo1 == liGNo2) {
return 0;
}
// 同一グループ化
sz1Grp[liGNo2].miNo = liGNo1;
sz1Grp[liGNo1].miCnt += sz1Grp[liGNo2].miCnt;
return sz1Grp[liGNo1].miCnt;
}
// 実行メイン
int
fMain(
)
{
int i;
char lc1Buf[1024];
// 人数・関係数 - 取得
int liHCnt, liRCnt;
fgets(lc1Buf, sizeof(lc1Buf), szpFpI);
sscanf(lc1Buf, "%d%d", &liHCnt, &liRCnt);
// グループ番号 - 初期化
for (i = 0; i < liHCnt; i++) {
sz1Grp[i].miNo = i;
sz1Grp[i].miCnt = 1;
}
// 関係 - 取得
int liMax = 1;
for (i = 0; i < liRCnt; i++) {
int liNo1, liNo2;
fgets(lc1Buf, sizeof(lc1Buf), szpFpI);
sscanf(lc1Buf, "%d%d", &liNo1, &liNo2);
int liCnt = fGrpConv(liNo1 - 1, liNo2 - 1);
liMax = fGetMaxI(liMax, liCnt);
}
return liMax;
}
// 1回実行
int
fOne(
)
{
int liRet;
char lc1Buf[1024];
// 入力 - セット
#ifdef D_TEST
sprintf(lc1Buf, ".\\Test\\T%d.txt", siTNo);
szpFpI = fopen(lc1Buf, "r");
sprintf(lc1Buf, ".\\Test\\A%d.txt", siTNo);
szpFpA = fopen(lc1Buf, "r");
siRes = 0;
#else
szpFpI = stdin;
#endif
// 実行メイン
liRet = fMain();
// 出力
sprintf(lc1Buf, "%d\n", liRet);
fOutLine(lc1Buf);
// 残データ有無
#ifdef D_TEST
lc1Buf[0] = '\0';
fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
if (strcmp(lc1Buf, "")) {
siRes = -1;
}
#endif
// テストファイルクローズ
#ifdef D_TEST
fclose(szpFpI);
fclose(szpFpA);
#endif
// テスト結果
#ifdef D_TEST
if (siRes == 0) {
printf("OK %d\n", siTNo);
}
else {
printf("NG %d\n", siTNo);
}
#endif
return 0;
}
// プログラム開始
int
main()
{
#ifdef D_TEST
int i;
for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) {
siTNo = i;
fOne();
}
#else
fOne();
#endif
return 0;
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
int main(){
int N;
cin >> N;
int ans = 0;
for(int i=1;i<=N;i++){
for(int x=1;x * x < i;x++){
for(int y=1;y<=x;y++){
for(int z=1;z<=y;z++){
if(x*x + y*y + z*z + x*y + y*z + z*x == i){
ans++;
if(x == y && y != z) ans += 2;
if(x != y && y == z) ans += 2;
if(x != y && y != z) ans += 5;
}
}
}
}
cout << ans << endl;
ans = 0;
}
}
| Python | A, B, N = map(int, input().split())
alpha = A // B
beta = A % B
q = min(N, B - 1)
ans = alpha * q + (beta*q//B)
print(ans) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int main(){
int N;
cin >> N;
int ans = 0;
for(int i=1;i<=N;i++){
for(int x=1;x * x < i;x++){
for(int y=1;y<=x;y++){
for(int z=1;z<=y;z++){
if(x*x + y*y + z*z + x*y + y*z + z*x == i){
ans++;
if(x == y && y != z) ans += 2;
if(x != y && y == z) ans += 2;
if(x != y && y != z) ans += 5;
}
}
}
}
cout << ans << endl;
ans = 0;
}
}
Code 2: A, B, N = map(int, input().split())
alpha = A // B
beta = A % B
q = min(N, B - 1)
ans = alpha * q + (beta*q//B)
print(ans) |
Kotlin | import java.util.*
fun main(args: Array<String>){
val cin = Scanner(System.`in`)
val n = cin.nextInt()
val a: MutableList<Int> = mutableListOf()
for (i in 0..n-1) {
a.add(cin.nextInt())
}
val a_s = a.sorted()
var now = a_s[0]
var ok = true
var count0 = -1
var val0 = -1
var count1 = -1
var val1 = -1
var p = 0
for (i in a_s) {
if (i > now) {
if (count1 >= 0) {
ok = false
break
} else if (count0 >= 0) {
count1 = p
val1 = now
} else {
count0 = p
val0 = now
}
now = i
}
p += 1
}
if (0 > count0) {
count0 = n
}
if (0 > count1) {
count1 = n - count0
}
if (!ok) {
println("No")
} else {
val k = n / 3
if (n % 3 == 0) {
if (count0 % k != 0 || count1 % k != 0) {
println("No")
} else {
if (a_s[k-1] xor a_s[2*k-1] == a_s[3*k-1]) {
println("Yes")
} else {
println("No")
}
}
} else if (n % 3 == 1) {
if (a_s[n-1] == 0) {
println("Yes")
} else {
println("No")
}
} else {
if (a_s[k] == 0 && a_s[k+1] == a_s[n-1]) {
println("Yes")
} else {
println("No")
}
}
}
} | Go | package main
import (
"fmt"
"math"
)
func main() {
var N int
fmt.Scan(&N)
a := make([]int, N)
for i := 0; i < N; i++ {
fmt.Scan(&a[i])
}
xor := 0
for i := 0; i < N; i++ {
xor ^= a[i]
}
// log.Println(xor)
if xor == 0 {
fmt.Println("Yes")
} else {
fmt.Println("No")
}
}
var dy = []int{0, 1, 0, -1}
var dx = []int{1, 0, -1, 0}
func pow(a, b int) int {
return int(math.Pow(float64(a), float64(b)))
}
func lcm(a, b int) int {
return a * b / gcd(a, b)
}
func gcd(a, b int) int {
if a < b {
a, b = b, a
}
for b != 0 {
a, b = b, a%b
}
return a
}
func max(a ...int) int {
r := a[0]
for i := 0; i < len(a); i++ {
if r < a[i] {
r = a[i]
}
}
return r
}
func min(a ...int) int {
r := a[0]
for i := 0; i < len(a); i++ {
if r > a[i] {
r = a[i]
}
}
return r
}
func sum(a []int) (r int) {
for i := range a {
r += a[i]
}
return r
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
type Pair struct {
a, b int
}
type pairs []Pair
func (p pairs) Len() int {
return len(p)
}
func (p pairs) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p pairs) Less(i, j int) bool {
if p[i].a == p[j].a {
return p[i].b < p[j].b
}
return p[i].a < p[j].a
}
| Yes | Do these codes solve the same problem?
Code 1: import java.util.*
fun main(args: Array<String>){
val cin = Scanner(System.`in`)
val n = cin.nextInt()
val a: MutableList<Int> = mutableListOf()
for (i in 0..n-1) {
a.add(cin.nextInt())
}
val a_s = a.sorted()
var now = a_s[0]
var ok = true
var count0 = -1
var val0 = -1
var count1 = -1
var val1 = -1
var p = 0
for (i in a_s) {
if (i > now) {
if (count1 >= 0) {
ok = false
break
} else if (count0 >= 0) {
count1 = p
val1 = now
} else {
count0 = p
val0 = now
}
now = i
}
p += 1
}
if (0 > count0) {
count0 = n
}
if (0 > count1) {
count1 = n - count0
}
if (!ok) {
println("No")
} else {
val k = n / 3
if (n % 3 == 0) {
if (count0 % k != 0 || count1 % k != 0) {
println("No")
} else {
if (a_s[k-1] xor a_s[2*k-1] == a_s[3*k-1]) {
println("Yes")
} else {
println("No")
}
}
} else if (n % 3 == 1) {
if (a_s[n-1] == 0) {
println("Yes")
} else {
println("No")
}
} else {
if (a_s[k] == 0 && a_s[k+1] == a_s[n-1]) {
println("Yes")
} else {
println("No")
}
}
}
}
Code 2: package main
import (
"fmt"
"math"
)
func main() {
var N int
fmt.Scan(&N)
a := make([]int, N)
for i := 0; i < N; i++ {
fmt.Scan(&a[i])
}
xor := 0
for i := 0; i < N; i++ {
xor ^= a[i]
}
// log.Println(xor)
if xor == 0 {
fmt.Println("Yes")
} else {
fmt.Println("No")
}
}
var dy = []int{0, 1, 0, -1}
var dx = []int{1, 0, -1, 0}
func pow(a, b int) int {
return int(math.Pow(float64(a), float64(b)))
}
func lcm(a, b int) int {
return a * b / gcd(a, b)
}
func gcd(a, b int) int {
if a < b {
a, b = b, a
}
for b != 0 {
a, b = b, a%b
}
return a
}
func max(a ...int) int {
r := a[0]
for i := 0; i < len(a); i++ {
if r < a[i] {
r = a[i]
}
}
return r
}
func min(a ...int) int {
r := a[0]
for i := 0; i < len(a); i++ {
if r > a[i] {
r = a[i]
}
}
return r
}
func sum(a []int) (r int) {
for i := range a {
r += a[i]
}
return r
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
type Pair struct {
a, b int
}
type pairs []Pair
func (p pairs) Len() int {
return len(p)
}
func (p pairs) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p pairs) Less(i, j int) bool {
if p[i].a == p[j].a {
return p[i].b < p[j].b
}
return p[i].a < p[j].a
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
int main(){
int W,H,x,y,r;
cin >> W >> H >> x >> y >> r;
bool judge=false;
if(x-r>=0 && x+r<=W && y-r>=0 && y+r<=H){
judge=true;
}
if(judge){
cout << "Yes" << endl;
}
else{
cout << "No" << endl;
}
}
| Java | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args){
new Thread(null, null, "Anshum Gupta", 99999999) {
public void run() {
try {
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static final long mxx = (long)(1e18+5);
static final int mxN = (int)(1e6);
static final int mxV = (int)(1e6), log = 18;
static long mod = (long)(1e9+7); //998244353;//̇
static final int INF = (int)1e9;
static boolean[][]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, k, q, p;
static char[]str;
static int[]a;
static boolean[]flipped;
public static void solve() throws Exception {
// solve the problem here
s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
// out = new PrintWriter("output.txt");
int tc = 1;//s.nextInt();
while(tc-- > 0){
int n = s.nextInt(), x = s.nextInt(), t = s.nextInt();
out.println((n + x - 1) / x * t);
}
out.flush();
out.close();
}
public static PrintWriter out;
public static MyScanner s;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
int[] nextIntArray(int n){
int[]a = new int[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextlongArray(int n) {
long[]a = new long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
Integer[] nextIntegerArray(int n){
Integer[]a = new Integer[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[]a = new Long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
char[][] next2DCharArray(int n, int m){
char[][]arr = new char[n][m];
for(int i=0; i<n; i++) {
arr[i] = this.next().toCharArray();
}
return arr;
}
ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
return adj;
}
ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
}
return adj;
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int main(){
int W,H,x,y,r;
cin >> W >> H >> x >> y >> r;
bool judge=false;
if(x-r>=0 && x+r<=W && y-r>=0 && y+r<=H){
judge=true;
}
if(judge){
cout << "Yes" << endl;
}
else{
cout << "No" << endl;
}
}
Code 2: import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args){
new Thread(null, null, "Anshum Gupta", 99999999) {
public void run() {
try {
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static final long mxx = (long)(1e18+5);
static final int mxN = (int)(1e6);
static final int mxV = (int)(1e6), log = 18;
static long mod = (long)(1e9+7); //998244353;//̇
static final int INF = (int)1e9;
static boolean[][]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, k, q, p;
static char[]str;
static int[]a;
static boolean[]flipped;
public static void solve() throws Exception {
// solve the problem here
s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
// out = new PrintWriter("output.txt");
int tc = 1;//s.nextInt();
while(tc-- > 0){
int n = s.nextInt(), x = s.nextInt(), t = s.nextInt();
out.println((n + x - 1) / x * t);
}
out.flush();
out.close();
}
public static PrintWriter out;
public static MyScanner s;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
int[] nextIntArray(int n){
int[]a = new int[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextlongArray(int n) {
long[]a = new long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
Integer[] nextIntegerArray(int n){
Integer[]a = new Integer[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[]a = new Long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
char[][] next2DCharArray(int n, int m){
char[][]arr = new char[n][m];
for(int i=0; i<n; i++) {
arr[i] = this.next().toCharArray();
}
return arr;
}
ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
return adj;
}
ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
}
return adj;
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
C++ | #include<bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = (a); i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define endl '\n'
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
const ll mod = 1000000007;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// head
const int nax = 2e5+2;
vector<ll> t(4*nax);
void update(int v, int tl, int tr, int p, ll val) {
if(tl == tr) {
t[v] = val;
} else {
int tm = (tl + tr) / 2;
if(p <= tm)
update(2*v, tl, tm, p, val);
else update(2*v+1, tm + 1, tr, p, val);
t[v] = max(t[v*2], t[v*2+1]);
}
}
ll maxi(int v, int tl, int tr, int l, int r) {
if(l > r) return 0;
if(l == tl && r == tr) {
return t[v];
} else {
int tm = (tl + tr) / 2;
return max(maxi(v*2, tl, tm, l, min(r, tm)), maxi(v*2+1, tm + 1, tr, max(l, tm + 1), r));
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vi h(n);
vll a(n);
rep(i,0,n) cin >> h[i];
rep(i,0,n) cin >> a[i];
vll dp(n + 1);
rep(i,0,n) {
// find the max value of dp[i] from [0, h[i] - 1]
ll val = maxi(1,0,n,0,h[i]-1);
//ll val = maxi(1,0,n,0,h[i]-1);
if(val + a[i] > dp[h[i]]) {
dp[h[i]] = val + a[i];
update(1,0,n,h[i],val + a[i]);
}
//dp[h[i]] = max(val + a[i], dp[h[i]]);
//dp[h[i]] = val + a[i];
/*rep(j,0,h[i]) {
dp[h[i]] = max(dp[h[i]], dp[j] + a[i]);
}*/
}
cout << t[1] << endl;
return 0;
}
| Python | num_0 = int(input())
num_1 = input()
count = 0
count_i = 0
for i in range(0,num_0):
if num_1[i] == "A":
count_i = 1
elif count_i == 1 and num_1[i] == "B":
count_i = 2
elif count_i == 2 and num_1[i] == "C":
count = count + 1
count_i = 0
else:
count_i = 0
print(count) | No | Do these codes solve the same problem?
Code 1: #include<bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = (a); i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define endl '\n'
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
const ll mod = 1000000007;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// head
const int nax = 2e5+2;
vector<ll> t(4*nax);
void update(int v, int tl, int tr, int p, ll val) {
if(tl == tr) {
t[v] = val;
} else {
int tm = (tl + tr) / 2;
if(p <= tm)
update(2*v, tl, tm, p, val);
else update(2*v+1, tm + 1, tr, p, val);
t[v] = max(t[v*2], t[v*2+1]);
}
}
ll maxi(int v, int tl, int tr, int l, int r) {
if(l > r) return 0;
if(l == tl && r == tr) {
return t[v];
} else {
int tm = (tl + tr) / 2;
return max(maxi(v*2, tl, tm, l, min(r, tm)), maxi(v*2+1, tm + 1, tr, max(l, tm + 1), r));
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vi h(n);
vll a(n);
rep(i,0,n) cin >> h[i];
rep(i,0,n) cin >> a[i];
vll dp(n + 1);
rep(i,0,n) {
// find the max value of dp[i] from [0, h[i] - 1]
ll val = maxi(1,0,n,0,h[i]-1);
//ll val = maxi(1,0,n,0,h[i]-1);
if(val + a[i] > dp[h[i]]) {
dp[h[i]] = val + a[i];
update(1,0,n,h[i],val + a[i]);
}
//dp[h[i]] = max(val + a[i], dp[h[i]]);
//dp[h[i]] = val + a[i];
/*rep(j,0,h[i]) {
dp[h[i]] = max(dp[h[i]], dp[j] + a[i]);
}*/
}
cout << t[1] << endl;
return 0;
}
Code 2: num_0 = int(input())
num_1 = input()
count = 0
count_i = 0
for i in range(0,num_0):
if num_1[i] == "A":
count_i = 1
elif count_i == 1 and num_1[i] == "B":
count_i = 2
elif count_i == 2 and num_1[i] == "C":
count = count + 1
count_i = 0
else:
count_i = 0
print(count) |
JavaScript | function Main(input) {
input = input.split("\n");
var stair_num = parseInt(input[0]);
var stair_arr = input[1].split(" ").map( v => parseInt(v,10) );
var lawest = 0;
for(var i=0; i<stair_num; i++){
if( stair_arr[i] < lawest ){ console.log("No"); return; }
if( stair_arr[i] > lawest ){
lawest = stair_arr[i]-1;
}
}
console.log("Yes");
}
Main(require("fs").readFileSync("/dev/stdin", "utf8")); | Python | import sys
S = [int(_) for _ in list(input())]
K = int(input())
t = 0
while t <= len(S) - 1:
if S[t] == 1:
t += 1
else:
break
if K <= t:
print(1)
sys.exit()
else:
print(S[t])
sys.exit()
| No | Do these codes solve the same problem?
Code 1: function Main(input) {
input = input.split("\n");
var stair_num = parseInt(input[0]);
var stair_arr = input[1].split(" ").map( v => parseInt(v,10) );
var lawest = 0;
for(var i=0; i<stair_num; i++){
if( stair_arr[i] < lawest ){ console.log("No"); return; }
if( stair_arr[i] > lawest ){
lawest = stair_arr[i]-1;
}
}
console.log("Yes");
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
Code 2: import sys
S = [int(_) for _ in list(input())]
K = int(input())
t = 0
while t <= len(S) - 1:
if S[t] == 1:
t += 1
else:
break
if K <= t:
print(1)
sys.exit()
else:
print(S[t])
sys.exit()
|
Java | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
public class Main {
static PrintWriter out;
static InputReader ir;
static void solve() {
long LO = (long) Math.pow(2L, 30), HI = LO + 100000;
long[] mods = new long[] { (long) 1e9 + 21, 2078526727L },
bases = new long[] { 3655665837329325079L, 6422997478807908741L };
String s = ir.next();
int n = s.length();
String t = ir.next();
int m = t.length();
StringBuilder sb = new StringBuilder();
RollingHash rht = new RollingHash(t, mods, bases);
while (sb.length() <= m * 2)
sb.append(s);
sb.append(s);
RollingHash rhs = new RollingHash(sb.toString(), mods, bases);
long hasht = rht.calcHash(1, m);
int[] p = new int[n];
Arrays.fill(p, -1);
long[] hashs = new long[n];
for (int i = 0; i < n; i++) {
hashs[i] = rhs.calcHash(i + 1, i + m);
}
for (int i = 0; i < n; i++) {
if (hashs[i] == hasht) {
p[i] = (i + m) % n;
}
}
// tr(p);
int[] dp = new int[n];
Arrays.fill(dp, -1);
int ma = 0;
int[] used = new int[n];
int time = 1;
for (int i = 0; i < n; i++) {
if (dp[i] >= 0 || p[i] < 0 || used[i] > 0)
continue;
dp[i] = 0;
int cur = i;
while (p[cur] >= 0) {
dp[i]++;
used[cur] = time;
cur = p[cur];
if (used[cur] == time) {
out.println(-1);
return;
}
if (dp[cur] >= 0) {
dp[i] += dp[cur];
break;
}
}
ma = Math.max(dp[i], ma);
time++;
}
// tr(dp);
out.println(ma);
}
static class RollingHash {
private String s;
private long[][] b, H;
private long[] mods, bases;
RollingHash(String s, long[] mods, long[] bases) {
this.s = s;
this.mods = mods;
this.bases = bases;
b = new long[2][0];
H = new long[2][0];
int n = s.length();
for (int j = 0; j < 1; ++j) {
long B = bases[j] % mods[j];
b[j] = new long[n + 1];
H[j] = new long[n + 1];
b[j][0] = 1;
H[j][0] = 0;
for (int i = 0; i < n; ++i) {
b[j][i + 1] = b[j][i] * B;
b[j][i + 1] %= mods[j];
H[j][i + 1] = H[j][i] * B + (int) s.charAt(i);
H[j][i + 1] %= mods[j];
}
}
}
long calcHash(int l, int r) {
long h0 = (H[0][r] - b[0][r - l + 1] * H[0][l - 1]) % mods[0];
if (h0 < 0) {
h0 += mods[0];
}
// long h1 = (H[1][r] - b[1][r - l + 1] * H[1][l - 1]) % mods[1];
// if (h1 < 0) {
// h1 += mods[1];
// }
// long hash = (h0 << 31) + h1;
// return hash;
return h0;
}
}
public static void main(String[] args) {
ir = new InputReader(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
static void tr(Object... o) {
out.println(Arrays.deepToString(o));
}
} | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.IO;
using System.Text;
using System.Diagnostics;
using static util;
using P = pair<int, int>;
using Binary = System.Func<System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.BinaryExpression>;
using Unary = System.Func<System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.UnaryExpression>;
class Program {
static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
static Scan sc = new Scan();
const int M = 1000000007;
const int M2 = 998244353;
const long LM = 1L << 60;
const double eps = 1e-11;
static void Main(string[] args)
{
var s = sc.Str;
var t = sc.Str;
var ss = new char[s.Length + t.Length + 9];
for (int i = 0; i < ss.Length; i++)
{
ss[i] = s[i % s.Length];
}
var hs = new long[ss.Length + 1];
var ht = new long[t.Length + 1];
for (int i = 0; i < ss.Length; i++)
{
hs[i + 1] = (hs[i] * 26 + ss[i] - 'a') % M;
}
for (int i = 0; i < t.Length; i++)
{
ht[i + 1] = (ht[i] * 26 + t[i] - 'a') % M;
}
ok = new bool[s.Length];
long p = pow(26, t.Length);
for (int i = 0; i < s.Length; i++)
{
long hss = (hs[i + t.Length] - hs[i] * p % M + M) % M;
long htt = ht[t.Length];
if (hss == htt) {
ok[i] = true;
}
}
cnt = new int[s.Length];
for (int i = 0; i < s.Length; i++)
{
cnt[i] = -1;
}
vis = new bool[s.Length];
tl = t.Length;
sl = s.Length;
int ans = 0;
for (int i = 0; i < s.Length; i++)
{
ans = Math.Max(ans, dfs(i));
}
Prt(ans >= M ? -1 : ans);
sw.Flush();
}
static int[] cnt;
static bool[] ok, vis;
static int tl, sl;
static int dfs(int p) {
if (!ok[p]) return cnt[p] = 0;
if (cnt[p] != -1) return cnt[p];
if (vis[p]) return M;
vis[p] = true;
return cnt[p] = dfs((p + tl) % sl) + 1;
}
static long pow(long a, long b) {
if (b == 0) return 1;
var t = pow(a, b / 2);
if ((b & 1) == 0) return t * t % M;
return t * t % M * a % M;
}
static void DBG(string a) => Console.WriteLine(a);
static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
static void DBG(params object[] a) => DBG(string.Join(" ", a));
static void Prt(string a) => sw.WriteLine(a);
static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
static void Prt(params object[] a) => Prt(string.Join(" ", a));
}
class pair<T, U> : IComparable<pair<T, U>> {
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; }
public static bool operator>(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) > 0;
public static bool operator<(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) < 0;
public static bool operator>=(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) >= 0;
public static bool operator<=(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) <= 0;
}
static class util {
public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
public static T sq<T>(T a) => Operator<T>.Multiply(a, a);
public static T Max<T>(params T[] a) => a.Max();
public static T Min<T>(params T[] a) => a.Min();
public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
static readonly int[] dd = { 0, 1, 0, -1 };
static readonly string dstring = "RDLU";
public static P[] adjacents(this P p) => adjacents(p.v1, p.v2);
public static P[] adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w);
public static pair<P, char>[] adjacents_with_str(int i, int j)
=> Enumerable.Range(0, dd.Length).Select(k => new pair<P, char>(new P(i + dd[k], j + dd[k ^ 1]), dstring[k])).ToArray();
public static pair<P, char>[] adjacents_with_str(int i, int j, int h, int w)
=> Enumerable.Range(0, dd.Length).Select(k => new pair<P, char>(new P(i + dd[k], j + dd[k ^ 1]), dstring[k]))
.Where(p => inside(p.v1.v1, p.v1.v2, h, w)).ToArray();
public static P[] adjacents(int i, int j)
=> Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).ToArray();
public static P[] adjacents(int i, int j, int h, int w)
=> Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).Where(p => inside(p.v1, p.v2, h, w)).ToArray();
public static void Assert(bool cond) { if (!cond) throw new Exception(); }
public static Dictionary<T, int> compress<T>(this IEnumerable<T> a)
=> a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i);
public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.Aggregate(Enumerable.Union));
public static 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;
}
}
static class Operator<T> {
static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x");
static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y");
public static readonly Func<T, T, T> Add = Lambda(Expression.Add);
public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract);
public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply);
public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide);
public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus);
public static readonly Func<T, T> Negate = Lambda(Expression.Negate);
public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile();
public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile();
}
class Scan {
StreamReader sr;
public Scan() { sr = new StreamReader(Console.OpenStandardInput()); }
public Scan(string path) { sr = new StreamReader(path); }
public int Int => int.Parse(Str);
public long Long => long.Parse(Str);
public double Double => double.Parse(Str);
public string Str => sr.ReadLine().Trim();
public pair<T, U> Pair<T, U>() {
T a; U b;
Multi(out a, out b);
return new pair<T, U>(a, b);
}
public P P => Pair<int, int>();
public int[] IntArr => StrArr.Select(int.Parse).ToArray();
public long[] LongArr => StrArr.Select(long.Parse).ToArray();
public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
bool eq<T, U>() => typeof(T).Equals(typeof(U));
T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
: eq<T, long>() ? ct<T, long>(long.Parse(s))
: eq<T, double>() ? ct<T, double>(double.Parse(s))
: eq<T, char>() ? ct<T, char>(s[0])
: ct<T, string>(s);
public void Multi<T>(out T a) => a = cv<T>(Str);
public void Multi<T, U>(out T a, out U b)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); }
public void Multi<T, U, V>(out T a, out U b, out V c)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); }
public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); }
public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); }
}
| Yes | Do these codes solve the same problem?
Code 1: import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
public class Main {
static PrintWriter out;
static InputReader ir;
static void solve() {
long LO = (long) Math.pow(2L, 30), HI = LO + 100000;
long[] mods = new long[] { (long) 1e9 + 21, 2078526727L },
bases = new long[] { 3655665837329325079L, 6422997478807908741L };
String s = ir.next();
int n = s.length();
String t = ir.next();
int m = t.length();
StringBuilder sb = new StringBuilder();
RollingHash rht = new RollingHash(t, mods, bases);
while (sb.length() <= m * 2)
sb.append(s);
sb.append(s);
RollingHash rhs = new RollingHash(sb.toString(), mods, bases);
long hasht = rht.calcHash(1, m);
int[] p = new int[n];
Arrays.fill(p, -1);
long[] hashs = new long[n];
for (int i = 0; i < n; i++) {
hashs[i] = rhs.calcHash(i + 1, i + m);
}
for (int i = 0; i < n; i++) {
if (hashs[i] == hasht) {
p[i] = (i + m) % n;
}
}
// tr(p);
int[] dp = new int[n];
Arrays.fill(dp, -1);
int ma = 0;
int[] used = new int[n];
int time = 1;
for (int i = 0; i < n; i++) {
if (dp[i] >= 0 || p[i] < 0 || used[i] > 0)
continue;
dp[i] = 0;
int cur = i;
while (p[cur] >= 0) {
dp[i]++;
used[cur] = time;
cur = p[cur];
if (used[cur] == time) {
out.println(-1);
return;
}
if (dp[cur] >= 0) {
dp[i] += dp[cur];
break;
}
}
ma = Math.max(dp[i], ma);
time++;
}
// tr(dp);
out.println(ma);
}
static class RollingHash {
private String s;
private long[][] b, H;
private long[] mods, bases;
RollingHash(String s, long[] mods, long[] bases) {
this.s = s;
this.mods = mods;
this.bases = bases;
b = new long[2][0];
H = new long[2][0];
int n = s.length();
for (int j = 0; j < 1; ++j) {
long B = bases[j] % mods[j];
b[j] = new long[n + 1];
H[j] = new long[n + 1];
b[j][0] = 1;
H[j][0] = 0;
for (int i = 0; i < n; ++i) {
b[j][i + 1] = b[j][i] * B;
b[j][i + 1] %= mods[j];
H[j][i + 1] = H[j][i] * B + (int) s.charAt(i);
H[j][i + 1] %= mods[j];
}
}
}
long calcHash(int l, int r) {
long h0 = (H[0][r] - b[0][r - l + 1] * H[0][l - 1]) % mods[0];
if (h0 < 0) {
h0 += mods[0];
}
// long h1 = (H[1][r] - b[1][r - l + 1] * H[1][l - 1]) % mods[1];
// if (h1 < 0) {
// h1 += mods[1];
// }
// long hash = (h0 << 31) + h1;
// return hash;
return h0;
}
}
public static void main(String[] args) {
ir = new InputReader(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
static void tr(Object... o) {
out.println(Arrays.deepToString(o));
}
}
Code 2: using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.IO;
using System.Text;
using System.Diagnostics;
using static util;
using P = pair<int, int>;
using Binary = System.Func<System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.BinaryExpression>;
using Unary = System.Func<System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.UnaryExpression>;
class Program {
static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
static Scan sc = new Scan();
const int M = 1000000007;
const int M2 = 998244353;
const long LM = 1L << 60;
const double eps = 1e-11;
static void Main(string[] args)
{
var s = sc.Str;
var t = sc.Str;
var ss = new char[s.Length + t.Length + 9];
for (int i = 0; i < ss.Length; i++)
{
ss[i] = s[i % s.Length];
}
var hs = new long[ss.Length + 1];
var ht = new long[t.Length + 1];
for (int i = 0; i < ss.Length; i++)
{
hs[i + 1] = (hs[i] * 26 + ss[i] - 'a') % M;
}
for (int i = 0; i < t.Length; i++)
{
ht[i + 1] = (ht[i] * 26 + t[i] - 'a') % M;
}
ok = new bool[s.Length];
long p = pow(26, t.Length);
for (int i = 0; i < s.Length; i++)
{
long hss = (hs[i + t.Length] - hs[i] * p % M + M) % M;
long htt = ht[t.Length];
if (hss == htt) {
ok[i] = true;
}
}
cnt = new int[s.Length];
for (int i = 0; i < s.Length; i++)
{
cnt[i] = -1;
}
vis = new bool[s.Length];
tl = t.Length;
sl = s.Length;
int ans = 0;
for (int i = 0; i < s.Length; i++)
{
ans = Math.Max(ans, dfs(i));
}
Prt(ans >= M ? -1 : ans);
sw.Flush();
}
static int[] cnt;
static bool[] ok, vis;
static int tl, sl;
static int dfs(int p) {
if (!ok[p]) return cnt[p] = 0;
if (cnt[p] != -1) return cnt[p];
if (vis[p]) return M;
vis[p] = true;
return cnt[p] = dfs((p + tl) % sl) + 1;
}
static long pow(long a, long b) {
if (b == 0) return 1;
var t = pow(a, b / 2);
if ((b & 1) == 0) return t * t % M;
return t * t % M * a % M;
}
static void DBG(string a) => Console.WriteLine(a);
static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
static void DBG(params object[] a) => DBG(string.Join(" ", a));
static void Prt(string a) => sw.WriteLine(a);
static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
static void Prt(params object[] a) => Prt(string.Join(" ", a));
}
class pair<T, U> : IComparable<pair<T, U>> {
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; }
public static bool operator>(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) > 0;
public static bool operator<(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) < 0;
public static bool operator>=(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) >= 0;
public static bool operator<=(pair<T, U> a, pair<T, U> b) => a.CompareTo(b) <= 0;
}
static class util {
public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
public static T sq<T>(T a) => Operator<T>.Multiply(a, a);
public static T Max<T>(params T[] a) => a.Max();
public static T Min<T>(params T[] a) => a.Min();
public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
static readonly int[] dd = { 0, 1, 0, -1 };
static readonly string dstring = "RDLU";
public static P[] adjacents(this P p) => adjacents(p.v1, p.v2);
public static P[] adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w);
public static pair<P, char>[] adjacents_with_str(int i, int j)
=> Enumerable.Range(0, dd.Length).Select(k => new pair<P, char>(new P(i + dd[k], j + dd[k ^ 1]), dstring[k])).ToArray();
public static pair<P, char>[] adjacents_with_str(int i, int j, int h, int w)
=> Enumerable.Range(0, dd.Length).Select(k => new pair<P, char>(new P(i + dd[k], j + dd[k ^ 1]), dstring[k]))
.Where(p => inside(p.v1.v1, p.v1.v2, h, w)).ToArray();
public static P[] adjacents(int i, int j)
=> Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).ToArray();
public static P[] adjacents(int i, int j, int h, int w)
=> Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).Where(p => inside(p.v1, p.v2, h, w)).ToArray();
public static void Assert(bool cond) { if (!cond) throw new Exception(); }
public static Dictionary<T, int> compress<T>(this IEnumerable<T> a)
=> a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i);
public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.Aggregate(Enumerable.Union));
public static 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;
}
}
static class Operator<T> {
static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x");
static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y");
public static readonly Func<T, T, T> Add = Lambda(Expression.Add);
public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract);
public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply);
public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide);
public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus);
public static readonly Func<T, T> Negate = Lambda(Expression.Negate);
public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile();
public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile();
}
class Scan {
StreamReader sr;
public Scan() { sr = new StreamReader(Console.OpenStandardInput()); }
public Scan(string path) { sr = new StreamReader(path); }
public int Int => int.Parse(Str);
public long Long => long.Parse(Str);
public double Double => double.Parse(Str);
public string Str => sr.ReadLine().Trim();
public pair<T, U> Pair<T, U>() {
T a; U b;
Multi(out a, out b);
return new pair<T, U>(a, b);
}
public P P => Pair<int, int>();
public int[] IntArr => StrArr.Select(int.Parse).ToArray();
public long[] LongArr => StrArr.Select(long.Parse).ToArray();
public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
bool eq<T, U>() => typeof(T).Equals(typeof(U));
T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
: eq<T, long>() ? ct<T, long>(long.Parse(s))
: eq<T, double>() ? ct<T, double>(double.Parse(s))
: eq<T, char>() ? ct<T, char>(s[0])
: ct<T, string>(s);
public void Multi<T>(out T a) => a = cv<T>(Str);
public void Multi<T, U>(out T a, out U b)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); }
public void Multi<T, U, V>(out T a, out U b, out V c)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); }
public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); }
public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); }
}
|
C++ | #include <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<ll> vll;
typedef pair<int,int> pint;
#define DE 1
#define FI first
#define SE second
#define PB push_back
#define MP make_pair
#define ALL(s) (s).begin(),(s).end()
#define REP(i,n) for (int i = 0; i < (int)(n); ++i)
#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 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) {s<<"{ ";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) {s<<"{ ";for(__typeof__(P.begin()) it=P.begin();it!=P.end();++it){if(it!=P.begin())s<<", ";s<<'<'<<it->first<<"->"<<it->second<<'>';}return s<<" }"<<endl;}
string str;
bool solve() {
stack<char> st;
int n = str.size();
for (int i = 0; i < 10000; ++i) st.push(-1);
for (int i = 0; i < n; ++i) {
char c = str[i];
if (c != 'w') st.push(c);
else {
if (st.top() == 'e') st.pop();
else return false;
if (st.top() == 'm') st.pop();
else return false;
if (st.top() == -1 && i != n-1) return false;
}
}
if (st.top() == -1) return true;
else return false;
}
int main() {
while (cin >> str) {
bool res = solve();
if (res) cout << "Cat" << endl;
else cout << "Rabbit" << endl;
}
return 0;
}
| Python | import sys
sys.setrecursionlimit(10**5)
def LI(): return [int(x) for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LI_(): return [-1*int(x) for x in input().split()]
def II(): return int(input())
def IF(): return float(input())
def LM(func,n): return [[func(x) for x in input().split()]for i in range(n)]
mod = 1000000007
inf = float('INF')
def isCat(S):
#print(S)
if len(S) == 0:
return True
if S[0] != "m" or S[-1] != "w":
return False
c = 0
i=0
for i in range(1,len(S)-1):
if S[i] == 'm':
c += 1
elif S[i] == 'w':
c -= 1
if c ==0:
break
if S[1] == 'e':
i = 0
return S[i+1] == 'e' and isCat(S[1:i+1]) and isCat(S[i+2:-1])
if(isCat(input())):
print("Cat")
else:
print("Rabbit")
| 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<ll> vll;
typedef pair<int,int> pint;
#define DE 1
#define FI first
#define SE second
#define PB push_back
#define MP make_pair
#define ALL(s) (s).begin(),(s).end()
#define REP(i,n) for (int i = 0; i < (int)(n); ++i)
#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 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) {s<<"{ ";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) {s<<"{ ";for(__typeof__(P.begin()) it=P.begin();it!=P.end();++it){if(it!=P.begin())s<<", ";s<<'<'<<it->first<<"->"<<it->second<<'>';}return s<<" }"<<endl;}
string str;
bool solve() {
stack<char> st;
int n = str.size();
for (int i = 0; i < 10000; ++i) st.push(-1);
for (int i = 0; i < n; ++i) {
char c = str[i];
if (c != 'w') st.push(c);
else {
if (st.top() == 'e') st.pop();
else return false;
if (st.top() == 'm') st.pop();
else return false;
if (st.top() == -1 && i != n-1) return false;
}
}
if (st.top() == -1) return true;
else return false;
}
int main() {
while (cin >> str) {
bool res = solve();
if (res) cout << "Cat" << endl;
else cout << "Rabbit" << endl;
}
return 0;
}
Code 2: import sys
sys.setrecursionlimit(10**5)
def LI(): return [int(x) for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LI_(): return [-1*int(x) for x in input().split()]
def II(): return int(input())
def IF(): return float(input())
def LM(func,n): return [[func(x) for x in input().split()]for i in range(n)]
mod = 1000000007
inf = float('INF')
def isCat(S):
#print(S)
if len(S) == 0:
return True
if S[0] != "m" or S[-1] != "w":
return False
c = 0
i=0
for i in range(1,len(S)-1):
if S[i] == 'm':
c += 1
elif S[i] == 'w':
c -= 1
if c ==0:
break
if S[1] == 'e':
i = 0
return S[i+1] == 'e' and isCat(S[1:i+1]) and isCat(S[i+2:-1])
if(isCat(input())):
print("Cat")
else:
print("Rabbit")
|
C++ | #include<iostream>
#include<cmath>
using namespace std;
int main(){
int cnt=0, x, n, i, j;
bool flg;
double rootx;
int rootintx;
cin>>n;
for(i=0;i<n;i++){
flg = true;
cin>>x;
if(x==2){
cnt++;
continue;
}
if(x<2 || !(x%2)){
continue;
}
rootx = sqrt(x);
rootx = ceil(rootx);
rootintx = int(rootx);
for(j=2;j<=rootintx;j++){
if(!(x%j)){
flg=false;
break;
}
}
if(flg)cnt++;
}
cout<<cnt<<endl;
return 0;
} | Python | n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
x=sum(a);c=0
for i in a:
if i*4*m>=x:
c+=1
if c>=m:
print("Yes")
else:
print("No") | No | Do these codes solve the same problem?
Code 1: #include<iostream>
#include<cmath>
using namespace std;
int main(){
int cnt=0, x, n, i, j;
bool flg;
double rootx;
int rootintx;
cin>>n;
for(i=0;i<n;i++){
flg = true;
cin>>x;
if(x==2){
cnt++;
continue;
}
if(x<2 || !(x%2)){
continue;
}
rootx = sqrt(x);
rootx = ceil(rootx);
rootintx = int(rootx);
for(j=2;j<=rootintx;j++){
if(!(x%j)){
flg=false;
break;
}
}
if(flg)cnt++;
}
cout<<cnt<<endl;
return 0;
}
Code 2: n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
x=sum(a);c=0
for i in a:
if i*4*m>=x:
c+=1
if c>=m:
print("Yes")
else:
print("No") |
C++ | #include <iostream>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <numeric>
#include <algorithm>
#include <tuple>
#include <math.h>
#include <iomanip>
typedef long long ll;
using namespace std;
int main(){
string s;
cin >> s;
int ctr=0;
for(auto ss : s){
ctr += (ss=='o');
}
ctr += (15 - s.size());
string ret[] = {"NO", "YES"};
cout << ret[(ctr>=8)] << endl;
return 0;
}
| Python | N=int(input())
S,T=map(str, input().split())
ans = ""
for i in range(N):
ans = ans + S[i] + T[i]
print(ans) | No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <numeric>
#include <algorithm>
#include <tuple>
#include <math.h>
#include <iomanip>
typedef long long ll;
using namespace std;
int main(){
string s;
cin >> s;
int ctr=0;
for(auto ss : s){
ctr += (ss=='o');
}
ctr += (15 - s.size());
string ret[] = {"NO", "YES"};
cout << ret[(ctr>=8)] << endl;
return 0;
}
Code 2: N=int(input())
S,T=map(str, input().split())
ans = ""
for i in range(N):
ans = ans + S[i] + T[i]
print(ans) |
Java | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int Y = sc.nextInt();
for (int i=0;i<=N&&i*10000<=Y;i++ ) {
int now = Y -i *10000;
for (int j=0;j+i<=N &&j*5000<=now;j++) {
int temp = now -j *5000;
if (temp %1000==0 &&j+i+temp/1000==N) {
System.out.println(i+" "+j+" "+temp/1000);
return ;
}
}
}
System.out.println("-1 -1 -1");
}
} | C++ | #include<bits/stdc++.h>
using namespace std;
using ll = long long;
struct point {
int x,y;
};
int main(void){
int N,M;
cin>>N>>M;
vector<point> st(N),cp(M);
for (int i=0;i<N;i++){
cin>>st[i].x>>st[i].y;
}
for (int i=0;i<M;i++){
cin>>cp[i].x>>cp[i].y;
}
vector<int> ans(N);
for (int i=0;i<N;i++){
ll min = 1e9;
for (int j=M-1;j>=0;j--){
ll dist = abs(st[i].x-cp[j].x) + abs(st[i].y-cp[j].y);
if (min>=dist) {
min = dist;
ans[i]=j+1;
}
}
cout<<ans[i]<<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 = sc.nextInt();
int Y = sc.nextInt();
for (int i=0;i<=N&&i*10000<=Y;i++ ) {
int now = Y -i *10000;
for (int j=0;j+i<=N &&j*5000<=now;j++) {
int temp = now -j *5000;
if (temp %1000==0 &&j+i+temp/1000==N) {
System.out.println(i+" "+j+" "+temp/1000);
return ;
}
}
}
System.out.println("-1 -1 -1");
}
}
Code 2: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
struct point {
int x,y;
};
int main(void){
int N,M;
cin>>N>>M;
vector<point> st(N),cp(M);
for (int i=0;i<N;i++){
cin>>st[i].x>>st[i].y;
}
for (int i=0;i<M;i++){
cin>>cp[i].x>>cp[i].y;
}
vector<int> ans(N);
for (int i=0;i<N;i++){
ll min = 1e9;
for (int j=M-1;j>=0;j--){
ll dist = abs(st[i].x-cp[j].x) + abs(st[i].y-cp[j].y);
if (min>=dist) {
min = dist;
ans[i]=j+1;
}
}
cout<<ans[i]<<endl;
}
return 0;
} |
Java | import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(s.replace(",", " "));
}
} | C++ | #include <bits/stdc++.h>
#define endl '\n'
#define int long long
#define lint long long
#define pii pair<int,int>
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
#define SZ(v) ((int)v.size())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define MINF(a) memset(a,0x3f,sizeof(a))
#define POW(n) (1LL<<(n))
#define POPCNT(n) (__builtin_popcount(n))
#define IN(i,a,b) (a <= i && i <= b)
using namespace std;
template <typename T> inline bool CHMIN(T& a,T b) { if(a>b) { a=b; return 1; } return 0; }
template <typename T> inline bool CHMAX(T& a,T b) { if(a<b) { a=b; return 1; } return 0; }
template <typename T> inline void SORT(T& a) { sort(ALL(a)); }
template <typename T> inline void REV(T& a) { reverse(ALL(a)); }
template <typename T> inline void UNI(T& a) { sort(ALL(a)); a.erase(unique(ALL(a)),a.end()); }
template <typename T> inline T LB(vector<T>& v, T a) { return *lower_bound(ALL(v),a); }
template <typename T> inline int LBP(vector<T>& v, T a) { return lower_bound(ALL(v),a) - v.begin(); }
template <typename T> inline T UB(vector<T>& v, T a) { return *upper_bound(ALL(v),a); }
template <typename T> inline int UBP(vector<T>& v, T a) { return upper_bound(ALL(v),a) - v.begin(); }
template <typename T1, typename T2> ostream& operator<< (ostream& os, const pair<T1,T2>& p) { os << p.first << " " << p.second; return os; }
template <typename T1, typename T2> istream& operator>> (istream& is, pair<T1,T2>& p) { is >> p.first >> p.second; return is; }
template <typename T> ostream& operator<< (ostream& os, const vector<T>& v) { REP(i,v.size()) { if (i) os << " "; os << v[i]; } return os; }
template <typename T> istream& operator>> (istream& is, vector<T>& v) { for(T& in : v) is >> in; return is; }
template <typename T = int> vector<T> make_v(size_t a) { return vector<T>(a); }
template <typename T, typename... Ts> auto make_v(size_t a, Ts... ts) { return vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...)); }
template <typename T, typename V> typename enable_if<is_class<T>::value == 0>::type fill_v(T &t, const V &v) { t = v; }
template <typename T, typename V> typename enable_if<is_class<T>::value != 0>::type fill_v(T &t, const V &v) { for(auto &e : t) fill_v(e,v); }
const lint MOD = 1000000007;
const lint INF = 0x3f3f3f3f3f3f3f3f;
const double EPS = 1e-10;
void _main() {
int n;
cin >> n;
vector<int> a(n);
cin >> a;
int ans = INF;
// 最初が正
int sum = (a[0] <= 0 ? 1 : a[0]);
int tmp = (a[0] <= 0 ? abs(a[0]) + 1 : 0);
for (int i = 1; i < n; ++i) {
sum += a[i];
if (i & 1) {
if (sum < 0) continue;
tmp += abs(sum) + 1;
sum = -1;
} else {
if (sum > 0) continue;
tmp += abs(sum) + 1;
sum = 1;
}
}
CHMIN(ans, tmp);
// 最初が負
sum = (a[0] >= 0 ? -1 : a[0]);
tmp = (a[0] >= 0 ? abs(a[0] + 1) : 0);
for (int i = 1; i < n; ++i) {
sum += a[i];
if (i & 1) {
if (sum > 0) continue;
tmp += abs(sum) + 1;
sum = 1;
} else {
if (sum < 0) continue;
tmp += abs(sum) + 1;
sum = -1;
}
}
CHMIN(ans, tmp);
cout << ans << endl;
}
signed main(signed argc, char **argv) {
if (argc > 1) {
if (strchr(argv[1], 'i'))
freopen("input.txt", "r", stdin);
if (strchr(argv[1], 'o'))
freopen("output.txt", "w", stdout);
}
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
_main();
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);
String s = sc.next();
System.out.println(s.replace(",", " "));
}
}
Code 2: #include <bits/stdc++.h>
#define endl '\n'
#define int long long
#define lint long long
#define pii pair<int,int>
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
#define SZ(v) ((int)v.size())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define MINF(a) memset(a,0x3f,sizeof(a))
#define POW(n) (1LL<<(n))
#define POPCNT(n) (__builtin_popcount(n))
#define IN(i,a,b) (a <= i && i <= b)
using namespace std;
template <typename T> inline bool CHMIN(T& a,T b) { if(a>b) { a=b; return 1; } return 0; }
template <typename T> inline bool CHMAX(T& a,T b) { if(a<b) { a=b; return 1; } return 0; }
template <typename T> inline void SORT(T& a) { sort(ALL(a)); }
template <typename T> inline void REV(T& a) { reverse(ALL(a)); }
template <typename T> inline void UNI(T& a) { sort(ALL(a)); a.erase(unique(ALL(a)),a.end()); }
template <typename T> inline T LB(vector<T>& v, T a) { return *lower_bound(ALL(v),a); }
template <typename T> inline int LBP(vector<T>& v, T a) { return lower_bound(ALL(v),a) - v.begin(); }
template <typename T> inline T UB(vector<T>& v, T a) { return *upper_bound(ALL(v),a); }
template <typename T> inline int UBP(vector<T>& v, T a) { return upper_bound(ALL(v),a) - v.begin(); }
template <typename T1, typename T2> ostream& operator<< (ostream& os, const pair<T1,T2>& p) { os << p.first << " " << p.second; return os; }
template <typename T1, typename T2> istream& operator>> (istream& is, pair<T1,T2>& p) { is >> p.first >> p.second; return is; }
template <typename T> ostream& operator<< (ostream& os, const vector<T>& v) { REP(i,v.size()) { if (i) os << " "; os << v[i]; } return os; }
template <typename T> istream& operator>> (istream& is, vector<T>& v) { for(T& in : v) is >> in; return is; }
template <typename T = int> vector<T> make_v(size_t a) { return vector<T>(a); }
template <typename T, typename... Ts> auto make_v(size_t a, Ts... ts) { return vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...)); }
template <typename T, typename V> typename enable_if<is_class<T>::value == 0>::type fill_v(T &t, const V &v) { t = v; }
template <typename T, typename V> typename enable_if<is_class<T>::value != 0>::type fill_v(T &t, const V &v) { for(auto &e : t) fill_v(e,v); }
const lint MOD = 1000000007;
const lint INF = 0x3f3f3f3f3f3f3f3f;
const double EPS = 1e-10;
void _main() {
int n;
cin >> n;
vector<int> a(n);
cin >> a;
int ans = INF;
// 最初が正
int sum = (a[0] <= 0 ? 1 : a[0]);
int tmp = (a[0] <= 0 ? abs(a[0]) + 1 : 0);
for (int i = 1; i < n; ++i) {
sum += a[i];
if (i & 1) {
if (sum < 0) continue;
tmp += abs(sum) + 1;
sum = -1;
} else {
if (sum > 0) continue;
tmp += abs(sum) + 1;
sum = 1;
}
}
CHMIN(ans, tmp);
// 最初が負
sum = (a[0] >= 0 ? -1 : a[0]);
tmp = (a[0] >= 0 ? abs(a[0] + 1) : 0);
for (int i = 1; i < n; ++i) {
sum += a[i];
if (i & 1) {
if (sum > 0) continue;
tmp += abs(sum) + 1;
sum = 1;
} else {
if (sum < 0) continue;
tmp += abs(sum) + 1;
sum = -1;
}
}
CHMIN(ans, tmp);
cout << ans << endl;
}
signed main(signed argc, char **argv) {
if (argc > 1) {
if (strchr(argv[1], 'i'))
freopen("input.txt", "r", stdin);
if (strchr(argv[1], 'o'))
freopen("output.txt", "w", stdout);
}
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
_main();
return 0;
} |
C | /*
AOJ 2208
Title:The Melancholy of Thomas Right
@kankichi573
*/
#include <stdio.h>
int count(int array[],int n,int x)
{
int i,ret;
for(i=0,ret=0;i<n;i++)
ret += (array[i]==x)?1:0;
return(ret);
}
void dump(int row[],int col[],int nrow,int ncol)
{
int i;
for(i=0;i<nrow;i++)
printf("%d|",row[i]);
printf("\n");
for(i=0;i<ncol;i++)
printf("%d|",col[i]);
printf("\n");
}
int check(int row[],int col[],int nrow,int ncol)
{
int i,ac1,ac2,zc1,zc2;
if(nrow==0 && ncol==0)
return(-1);
else if(nrow==0 || ncol==0)
return(0);
//dump(row,col,nrow,ncol);
zc1=count(row,nrow,0);
zc2=count(col,ncol,0);
ac1= count(row,nrow,ncol);
ac2= count(col,ncol,nrow);
//printf("zcac=%d %d %d %d\n",zc1,zc2,ac1,ac2);
if(zc1||zc2)
{
if((zc2 && ac1)||(zc1 && ac2))
return(0);
else
return(check(row+zc1,col+zc2,nrow-zc1,ncol-zc2));
}
else
{
if(ac1==nrow && ac2==ncol)
return(-1);
if(ac1==0 && ac2==0)
return(0);
for(i=0;i<nrow;i++)
row[i] -= ac2;
for(i=0;i<ncol;i++)
col[i] -= ac1;
return(check(row,col,nrow-ac1,ncol-ac2));
}
}
int comp(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
main()
{
int i,gs,rs;
int N,gyo[10000],retu[10000];
while(scanf("%d",&N) && N)
{
for(gs=0,i=0;i<N;i++)
{
scanf("%d",&gyo[i]);
gs += gyo[i];
}
for(rs=0,i=0;i<N;i++)
{
scanf("%d",&retu[i]);
rs += retu[i];
}
qsort(gyo ,N,sizeof(int),comp);
qsort(retu,N,sizeof(int),comp);
if((rs==gs) && check(gyo,retu,N,N))
printf("Yes\n");
else
printf("No\n");
}
return(0);
} | C++ | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
using ll = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b)a=b;};
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b)a=b;};
signed main(){
cin.tie(0);
ios::sync_with_stdio(0);
Int n;
while(cin>>n,n){
vector<Int> as(n),bs(n);
for(Int i=0;i<n;i++) cin>>as[i];
for(Int i=0;i<n;i++) cin>>bs[i];
priority_queue<Int, vector<Int>, greater<Int> > pq;
for(Int a:as) pq.emplace(a);
Int add=0;
while(!pq.empty()&&(pq.top()+add==0)) pq.pop();
sort(bs.rbegin(),bs.rend());
Int flg=1;
for(Int i=0;i<n;i++){
//cout<<pq.size()<<" "<<bs[i]<<endl;
if((Int)pq.size()!=bs[i]){
flg=0;
break;
}
add--;
while(!pq.empty()&&(pq.top()+add==0)) pq.pop();
}
flg&=!!pq.empty();
cout<<(flg?"Yes":"No")<<endl;
}
return 0;
}
| Yes | Do these codes solve the same problem?
Code 1: /*
AOJ 2208
Title:The Melancholy of Thomas Right
@kankichi573
*/
#include <stdio.h>
int count(int array[],int n,int x)
{
int i,ret;
for(i=0,ret=0;i<n;i++)
ret += (array[i]==x)?1:0;
return(ret);
}
void dump(int row[],int col[],int nrow,int ncol)
{
int i;
for(i=0;i<nrow;i++)
printf("%d|",row[i]);
printf("\n");
for(i=0;i<ncol;i++)
printf("%d|",col[i]);
printf("\n");
}
int check(int row[],int col[],int nrow,int ncol)
{
int i,ac1,ac2,zc1,zc2;
if(nrow==0 && ncol==0)
return(-1);
else if(nrow==0 || ncol==0)
return(0);
//dump(row,col,nrow,ncol);
zc1=count(row,nrow,0);
zc2=count(col,ncol,0);
ac1= count(row,nrow,ncol);
ac2= count(col,ncol,nrow);
//printf("zcac=%d %d %d %d\n",zc1,zc2,ac1,ac2);
if(zc1||zc2)
{
if((zc2 && ac1)||(zc1 && ac2))
return(0);
else
return(check(row+zc1,col+zc2,nrow-zc1,ncol-zc2));
}
else
{
if(ac1==nrow && ac2==ncol)
return(-1);
if(ac1==0 && ac2==0)
return(0);
for(i=0;i<nrow;i++)
row[i] -= ac2;
for(i=0;i<ncol;i++)
col[i] -= ac1;
return(check(row,col,nrow-ac1,ncol-ac2));
}
}
int comp(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
main()
{
int i,gs,rs;
int N,gyo[10000],retu[10000];
while(scanf("%d",&N) && N)
{
for(gs=0,i=0;i<N;i++)
{
scanf("%d",&gyo[i]);
gs += gyo[i];
}
for(rs=0,i=0;i<N;i++)
{
scanf("%d",&retu[i]);
rs += retu[i];
}
qsort(gyo ,N,sizeof(int),comp);
qsort(retu,N,sizeof(int),comp);
if((rs==gs) && check(gyo,retu,N,N))
printf("Yes\n");
else
printf("No\n");
}
return(0);
}
Code 2: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
using ll = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b)a=b;};
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b)a=b;};
signed main(){
cin.tie(0);
ios::sync_with_stdio(0);
Int n;
while(cin>>n,n){
vector<Int> as(n),bs(n);
for(Int i=0;i<n;i++) cin>>as[i];
for(Int i=0;i<n;i++) cin>>bs[i];
priority_queue<Int, vector<Int>, greater<Int> > pq;
for(Int a:as) pq.emplace(a);
Int add=0;
while(!pq.empty()&&(pq.top()+add==0)) pq.pop();
sort(bs.rbegin(),bs.rend());
Int flg=1;
for(Int i=0;i<n;i++){
//cout<<pq.size()<<" "<<bs[i]<<endl;
if((Int)pq.size()!=bs[i]){
flg=0;
break;
}
add--;
while(!pq.empty()&&(pq.top()+add==0)) pq.pop();
}
flg&=!!pq.empty();
cout<<(flg?"Yes":"No")<<endl;
}
return 0;
}
|
C++ | #include <bits/stdc++.h>
using namespace std;
int main() {
int N,R;
cin >> N >> R;
int answer;
if(N >= 10){
answer = R;
}else{
answer = R + 100 * (10-N);
}
cout << answer;
} | Java | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
static final long mod=1000000007;
public static void main(String[] args) throws Exception, IOException{
Reader sc = new Reader(System.in);
PrintWriter out=new PrintWriter(System.out);
// int n=sc.nextInt();
// char c[][] = new char[h][w];
// char c[]=sc.nextString().toCharArray();
// for(int i=0; i<n; i++) {d[i]=sc.nextInt();}
int n=sc.nextInt();
// int k=sc.nextInt();
// int a[]=new int[n];
// int max=5000;
long s=0,ans=0;
for (int i=0; true; i++) {
s+=i+1;
if(n<=s){ans=i+1;break;}
}
out.println(ans);
out.flush();
}
static void db(Object... os){
System.err.println(Arrays.deepToString(os));
}
}
class P implements Comparable<P>{
int id, d;
P(int id, int d) {
this.id=id;
this.d=d;
}
public int compareTo(P p){
return d-p.d; //des
}
}
class Reader
{
private BufferedReader x;
private StringTokenizer st;
public Reader(InputStream in)
{
x = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String nextString() throws IOException
{
while( st==null || !st.hasMoreTokens() )
st = new StringTokenizer(x.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
} | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int main() {
int N,R;
cin >> N >> R;
int answer;
if(N >= 10){
answer = R;
}else{
answer = R + 100 * (10-N);
}
cout << answer;
}
Code 2: import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
static final long mod=1000000007;
public static void main(String[] args) throws Exception, IOException{
Reader sc = new Reader(System.in);
PrintWriter out=new PrintWriter(System.out);
// int n=sc.nextInt();
// char c[][] = new char[h][w];
// char c[]=sc.nextString().toCharArray();
// for(int i=0; i<n; i++) {d[i]=sc.nextInt();}
int n=sc.nextInt();
// int k=sc.nextInt();
// int a[]=new int[n];
// int max=5000;
long s=0,ans=0;
for (int i=0; true; i++) {
s+=i+1;
if(n<=s){ans=i+1;break;}
}
out.println(ans);
out.flush();
}
static void db(Object... os){
System.err.println(Arrays.deepToString(os));
}
}
class P implements Comparable<P>{
int id, d;
P(int id, int d) {
this.id=id;
this.d=d;
}
public int compareTo(P p){
return d-p.d; //des
}
}
class Reader
{
private BufferedReader x;
private StringTokenizer st;
public Reader(InputStream in)
{
x = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String nextString() throws IOException
{
while( st==null || !st.hasMoreTokens() )
st = new StringTokenizer(x.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
} |
C++ | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ll n,m;
while(cin >> n >> m && n) {
double x=(1+n)*n/2,y=n;
ll a[m];
for(int i=0; i<m; i++)cin >> a[i];
for(int t=1; t<(1<<m); t++) {
ll z=1;
for(int i=0; i<m; i++) {
if(t&(1<<i)) z=z/__gcd(z,a[i])*a[i];
}
ll b=n/z;
z=(z+b*z)*b/2;
if(__builtin_popcount(t)%2) {
x-=z;
y-=b;
} else {
x+=z;
y+=b;
}
}
if(!y) x=0,y=1;
printf("%.10f\n",x/y);
}
return 0;
}
| C# | using System;
public class hello
{
public static void Main()
{
while (true)
{
string[] line = Console.ReadLine().Trim().Split(' ');
var n = int.Parse(line[0]);
var m = int.Parse(line[1]);
if (n == 0 && m == 0) break;
line = Console.ReadLine().Trim().Split(' ');
var p = Array.ConvertAll(line, int.Parse);
Array.Sort(p);
Console.WriteLine(p[0] == 1? 0:n/2d);
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ll n,m;
while(cin >> n >> m && n) {
double x=(1+n)*n/2,y=n;
ll a[m];
for(int i=0; i<m; i++)cin >> a[i];
for(int t=1; t<(1<<m); t++) {
ll z=1;
for(int i=0; i<m; i++) {
if(t&(1<<i)) z=z/__gcd(z,a[i])*a[i];
}
ll b=n/z;
z=(z+b*z)*b/2;
if(__builtin_popcount(t)%2) {
x-=z;
y-=b;
} else {
x+=z;
y+=b;
}
}
if(!y) x=0,y=1;
printf("%.10f\n",x/y);
}
return 0;
}
Code 2: using System;
public class hello
{
public static void Main()
{
while (true)
{
string[] line = Console.ReadLine().Trim().Split(' ');
var n = int.Parse(line[0]);
var m = int.Parse(line[1]);
if (n == 0 && m == 0) break;
line = Console.ReadLine().Trim().Split(' ');
var p = Array.ConvertAll(line, int.Parse);
Array.Sort(p);
Console.WriteLine(p[0] == 1? 0:n/2d);
}
}
}
|
Python | n=int(input())
masu=input().split(" ")
cnt=0
ans=0
for i in masu:
if i=="1":
cnt+=1
ans=max(ans,cnt)
else:cnt=0
print(ans+1)
| PHP | <?php
fscanf(STDIN, "%d", $N);
$board_values = array_map("intval", explode(" ", trim(fgets(STDIN))));
$max = 0;
$tmp = 0;
$prev = $board_values[0];
if ($prev == 1) {
$tmp++;
}
for ($i = 1; $i < count($board_values); ++$i) {
if ($prev != 1) {
$tmp = 0;
}
if ($board_values[$i] == 1) {
++$tmp;
}
if ($max < $tmp) $max = $tmp;
$prev = $board_values[$i];
}
echo $max+1, "\n";
| Yes | Do these codes solve the same problem?
Code 1: n=int(input())
masu=input().split(" ")
cnt=0
ans=0
for i in masu:
if i=="1":
cnt+=1
ans=max(ans,cnt)
else:cnt=0
print(ans+1)
Code 2: <?php
fscanf(STDIN, "%d", $N);
$board_values = array_map("intval", explode(" ", trim(fgets(STDIN))));
$max = 0;
$tmp = 0;
$prev = $board_values[0];
if ($prev == 1) {
$tmp++;
}
for ($i = 1; $i < count($board_values); ++$i) {
if ($prev != 1) {
$tmp = 0;
}
if ($board_values[$i] == 1) {
++$tmp;
}
if ($max < $tmp) $max = $tmp;
$prev = $board_values[$i];
}
echo $max+1, "\n";
|
C | #include <stdio.h>
int main()
{
int card[205];
int work[205];
int n;
int m;
int k;
scanf("%d", &n);
scanf("%d", &m);
for (int i = 0; i < 2 * n; i++) {
card[i] = i + 1;
}
for (int i = 0; i < m; i++) {
scanf("%d", &k);
if (k == 0) {
int idx = 0;
for (int j = 0; j < n; j = j + 1) {
work[idx] = card[j];
work[idx + 1] = card[j + n];
idx = idx + 2;
}
} else {
int idx = 0;
for (int j = k; j < 2 * n; j = j + 1) {
work[idx] = card[j];
idx++;
}
for (int j = 0; j < k; j++) {
work[idx] = card[j];
idx++;
}
}
for (int j = 0; j < 2 * n; j++) {
card[j] = work[j];
}
}
for (int i = 0; i < 2 * n; i++) {
printf("%d\n", card[i]);
}
return 0;
}
| Python | riffle = lambda half, x: [j for i in zip(x[:half], x[half:]) for j in i]
cut = lambda index, x: x[index:] + x[:index]
cards = [str(x) for x in range(1, int(input())*2 + 1)]
half = int(len(cards) / 2)
for _ in range(int(input())):
order = int(input())
if order == 0:
cards = riffle(half, cards)
else:
cards = cut(order, cards)
print("\n".join(cards)) | Yes | Do these codes solve the same problem?
Code 1: #include <stdio.h>
int main()
{
int card[205];
int work[205];
int n;
int m;
int k;
scanf("%d", &n);
scanf("%d", &m);
for (int i = 0; i < 2 * n; i++) {
card[i] = i + 1;
}
for (int i = 0; i < m; i++) {
scanf("%d", &k);
if (k == 0) {
int idx = 0;
for (int j = 0; j < n; j = j + 1) {
work[idx] = card[j];
work[idx + 1] = card[j + n];
idx = idx + 2;
}
} else {
int idx = 0;
for (int j = k; j < 2 * n; j = j + 1) {
work[idx] = card[j];
idx++;
}
for (int j = 0; j < k; j++) {
work[idx] = card[j];
idx++;
}
}
for (int j = 0; j < 2 * n; j++) {
card[j] = work[j];
}
}
for (int i = 0; i < 2 * n; i++) {
printf("%d\n", card[i]);
}
return 0;
}
Code 2: riffle = lambda half, x: [j for i in zip(x[:half], x[half:]) for j in i]
cut = lambda index, x: x[index:] + x[:index]
cards = [str(x) for x in range(1, int(input())*2 + 1)]
half = int(len(cards) / 2)
for _ in range(int(input())):
order = int(input())
if order == 0:
cards = riffle(half, cards)
else:
cards = cut(order, cards)
print("\n".join(cards)) |
C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.IO;
using static util;
using P = pair<int, int>;
using Binary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.BinaryExpression>;
using Unary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.UnaryExpression>;
class Program
{
static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
static Scan sc = new Scan();
const int M = 1000000007;
const int M2 = 998244353;
const long LM = (long)1e18;
const double eps = 1e-11;
static readonly int[] dd = { 0, 1, 0, -1, 0 };
const string dstring = "RDLU";
static void Main()
{
int n, w;
sc.Multi(out n, out w);
var dp = new long[100010];
for (int i = 0; i < 100010; i++)
{
dp[i] = LM;
}
dp[0] = 0;
for (int i = 0; i < n; i++)
{
int u, v;
sc.Multi(out u, out v);
for (int j = 100009; j >= v; j--)
{
dp[j] = Math.Min(dp[j], dp[j - v] + u);
}
}
for (int i = 100009; i >= 0 ; i--)
{
if (dp[i] <= w) {
Prt(i);
break;
}
}
sw.Flush();
}
static void DBG(string a) => Console.WriteLine(a);
static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
static void DBG(params object[] a) => DBG(string.Join(" ", a));
static void Prt(string a) => sw.WriteLine(a);
static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
static void Prt(params object[] a) => Prt(string.Join(" ", a));
}
class pair<T, U> : IComparable<pair<T, U>>
{
public T v1;
public U v2;
public pair(T v1, U v2) {
this.v1 = v1;
this.v2 = v2;
}
public int CompareTo(pair<T, U> a) {
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 pair<T, T> make_pair<T>(this IList<T> l) => make_pair(l[0], l[1]);
public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
public static T sq<T>(T a) => Operator<T>.Multiply(a, a);
public static T Max<T>(params T[] a) => a.Max();
public static T Min<T>(params T[] a) => a.Min();
public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
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;
}
}
static class Operator<T>
{
static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x");
static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y");
public static readonly Func<T, T, T> Add = Lambda(Expression.Add);
public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract);
public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply);
public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide);
public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus);
public static readonly Func<T, T> Negate = Lambda(Expression.Negate);
public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile();
public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile();
}
class Scan
{
public int Int => int.Parse(Str);
public long Long => long.Parse(Str);
public double Double => double.Parse(Str);
public string Str => Console.ReadLine().Trim();
public pair<T, U> Pair<T, U>() where T : IComparable<T> where U : IComparable<U> {
T a; U b;
Multi(out a, out b);
return new pair<T, U>(a, b);
}
public P P {
get {
int a, b;
Multi(out a, out b);
return new P(a, b);
}
}
public int[] IntArr => StrArr.Select(int.Parse).ToArray();
public long[] LongArr => StrArr.Select(long.Parse).ToArray();
public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
bool eq<T, U>() => typeof(T).Equals(typeof(U));
T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
: eq<T, long>() ? ct<T, long>(long.Parse(s))
: eq<T, double>() ? ct<T, double>(double.Parse(s))
: eq<T, char>() ? ct<T, char>(s[0])
: ct<T, string>(s);
public void Multi<T>(out T a) => a = cv<T>(Str);
public void Multi<T, U>(out T a, out U b)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); }
public void Multi<T, U, V>(out T a, out U b, out V c)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); }
public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); }
public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); }
public void Multi<T, U, V, W, X, Y>(out T a, out U b, out V c, out W d, out X e, out Y f)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); f = cv<Y>(ar[5]); }
}
| TypeScript | 'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf8');
// Your code here!
const max = (a)=>{
let i = a.length;
let max=-Infinity;
while (i--) {
if (a[i] > max)max = a[i];
}
return max;
}
const min = (a)=>{
let i = a.length;
let max=Infinity;
while (i--) {
if (a[i] < max)max = a[i];
}
return max;
}
const Main = (p)=>{
p = p.split("\n");//2 or more
//let N = parseInt(p[0]);//N
const N = parseInt(p[0].split(" ")[0]);//N M
const W = parseInt(p[0].split(" ")[1]);//N M
//let h = (p[1].split(" ").map(Number));//a1 a2 a3...
let w = new Array(N);
let v = new Array(N);
//let c=new Array(N);
//let z=new Array(N);
for(let i=0;i<N;i++){
let h = (p[i+1].split(" ").map(Number));
w[i]=h[0];
v[i]=h[1];
}
const maxv=100000;
let m = new Array(N+1);
//console.log(N,W,w,v);return;
m[0]=new Array(maxv+1).fill(Infinity);
m[0][0]=0;
for(let i=0;i<=N;i++){
m[i+1]=m[i].concat();
for(let j=0;j<=maxv;j++){
if(j-v[i]>=0){
//console.log(m[i][j-w[i]]+v[i],m[i][j])
m[i+1][j]=Math.min(m[i][j-v[i]]+w[i],m[i][j]);
}
}
//console.log(i,m[i])
}
//console.log(m[N][maxv-1]);
let i=maxv;
while(m[N][i--]>W);//console.log(m[N][i--]);
console.log(i+1);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.IO;
using static util;
using P = pair<int, int>;
using Binary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.BinaryExpression>;
using Unary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.UnaryExpression>;
class Program
{
static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
static Scan sc = new Scan();
const int M = 1000000007;
const int M2 = 998244353;
const long LM = (long)1e18;
const double eps = 1e-11;
static readonly int[] dd = { 0, 1, 0, -1, 0 };
const string dstring = "RDLU";
static void Main()
{
int n, w;
sc.Multi(out n, out w);
var dp = new long[100010];
for (int i = 0; i < 100010; i++)
{
dp[i] = LM;
}
dp[0] = 0;
for (int i = 0; i < n; i++)
{
int u, v;
sc.Multi(out u, out v);
for (int j = 100009; j >= v; j--)
{
dp[j] = Math.Min(dp[j], dp[j - v] + u);
}
}
for (int i = 100009; i >= 0 ; i--)
{
if (dp[i] <= w) {
Prt(i);
break;
}
}
sw.Flush();
}
static void DBG(string a) => Console.WriteLine(a);
static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
static void DBG(params object[] a) => DBG(string.Join(" ", a));
static void Prt(string a) => sw.WriteLine(a);
static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
static void Prt(params object[] a) => Prt(string.Join(" ", a));
}
class pair<T, U> : IComparable<pair<T, U>>
{
public T v1;
public U v2;
public pair(T v1, U v2) {
this.v1 = v1;
this.v2 = v2;
}
public int CompareTo(pair<T, U> a) {
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 pair<T, T> make_pair<T>(this IList<T> l) => make_pair(l[0], l[1]);
public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
public static T sq<T>(T a) => Operator<T>.Multiply(a, a);
public static T Max<T>(params T[] a) => a.Max();
public static T Min<T>(params T[] a) => a.Min();
public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
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;
}
}
static class Operator<T>
{
static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x");
static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y");
public static readonly Func<T, T, T> Add = Lambda(Expression.Add);
public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract);
public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply);
public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide);
public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus);
public static readonly Func<T, T> Negate = Lambda(Expression.Negate);
public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile();
public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile();
}
class Scan
{
public int Int => int.Parse(Str);
public long Long => long.Parse(Str);
public double Double => double.Parse(Str);
public string Str => Console.ReadLine().Trim();
public pair<T, U> Pair<T, U>() where T : IComparable<T> where U : IComparable<U> {
T a; U b;
Multi(out a, out b);
return new pair<T, U>(a, b);
}
public P P {
get {
int a, b;
Multi(out a, out b);
return new P(a, b);
}
}
public int[] IntArr => StrArr.Select(int.Parse).ToArray();
public long[] LongArr => StrArr.Select(long.Parse).ToArray();
public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
bool eq<T, U>() => typeof(T).Equals(typeof(U));
T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
: eq<T, long>() ? ct<T, long>(long.Parse(s))
: eq<T, double>() ? ct<T, double>(double.Parse(s))
: eq<T, char>() ? ct<T, char>(s[0])
: ct<T, string>(s);
public void Multi<T>(out T a) => a = cv<T>(Str);
public void Multi<T, U>(out T a, out U b)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); }
public void Multi<T, U, V>(out T a, out U b, out V c)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); }
public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); }
public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); }
public void Multi<T, U, V, W, X, Y>(out T a, out U b, out V c, out W d, out X e, out Y f)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); f = cv<Y>(ar[5]); }
}
Code 2: 'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf8');
// Your code here!
const max = (a)=>{
let i = a.length;
let max=-Infinity;
while (i--) {
if (a[i] > max)max = a[i];
}
return max;
}
const min = (a)=>{
let i = a.length;
let max=Infinity;
while (i--) {
if (a[i] < max)max = a[i];
}
return max;
}
const Main = (p)=>{
p = p.split("\n");//2 or more
//let N = parseInt(p[0]);//N
const N = parseInt(p[0].split(" ")[0]);//N M
const W = parseInt(p[0].split(" ")[1]);//N M
//let h = (p[1].split(" ").map(Number));//a1 a2 a3...
let w = new Array(N);
let v = new Array(N);
//let c=new Array(N);
//let z=new Array(N);
for(let i=0;i<N;i++){
let h = (p[i+1].split(" ").map(Number));
w[i]=h[0];
v[i]=h[1];
}
const maxv=100000;
let m = new Array(N+1);
//console.log(N,W,w,v);return;
m[0]=new Array(maxv+1).fill(Infinity);
m[0][0]=0;
for(let i=0;i<=N;i++){
m[i+1]=m[i].concat();
for(let j=0;j<=maxv;j++){
if(j-v[i]>=0){
//console.log(m[i][j-w[i]]+v[i],m[i][j])
m[i+1][j]=Math.min(m[i][j-v[i]]+w[i],m[i][j]);
}
}
//console.log(i,m[i])
}
//console.log(m[N][maxv-1]);
let i=maxv;
while(m[N][i--]>W);//console.log(m[N][i--]);
console.log(i+1);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
|
C++ | #include <bits/stdc++.h>
#define int long long
using namespace std;
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s;
cin >> s;
if (s == "ABC") cout << "ARC";
else cout << "ABC";
return 0;
}
| Python | H,A=map(int,input().split())
ans=0
while H>0 :
H-=A
ans+=1
print(ans) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#define int long long
using namespace std;
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s;
cin >> s;
if (s == "ABC") cout << "ARC";
else cout << "ABC";
return 0;
}
Code 2: H,A=map(int,input().split())
ans=0
while H>0 :
H-=A
ans+=1
print(ans) |
C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ITP2_6_D
{
public class Program
{
public static void Main(string[] args)
{
int n = ReadInt();
int[] line = ReadIntAr();
Comparer comparer;
int q = ReadInt();
for (int i = 0 ; i < q ; i++)
{
int k = ReadInt();
comparer = new Comparer(line, k);
Console.WriteLine("{0} {1}",BinarySearch(0, n - 1, comparer), BinarySearch2(0, n - 1, comparer));
}
}
class Comparer : IComparer<int>
{
private int[] array;
private int k;
public Comparer(int[] array, int k)
{
this.array = array;
this.k = k;
}
public int Compare(int x, int y)
{
return array[x].CompareTo(k);
}
}
/// <summary>
/// 二分探索
/// -始点から終点までの整数列の中から、比較関数を満たす値を二分探索する
/// 値が見つからない場合は、条件を満たす最小の数を返す
/// </summary>
/// <param name="left">始点</param>
/// <param name="right">終点</param>
/// <param name="comparer">比較関数</param>
/// <returns></returns>
public static int BinarySearch(int left, int right, IComparer<int> comparer)
{
int lo = left;
int hi = right;
while (lo <= hi)
{
int i = GetMedian(lo, hi);
int c = comparer.Compare(i, 0);//yはダミーとして0固定
if (c < 0) lo = i + 1;
else hi = i - 1;
}
return lo;
}
public static int BinarySearch2(int left, int right, IComparer<int> comparer)
{
int lo = left;
int hi = right;
while (lo <= hi)
{
int i = GetMedian(lo, hi);
int c = comparer.Compare(i, 0);//yはダミーとして0固定
if (c <= 0) lo = i + 1;
else hi = i - 1;
}
return lo;
}
private static int GetMedian(int low, int hi) { return low + ((hi - low) >> 1); }
static string ReadSt() { return Console.ReadLine(); }
static int ReadInt() { return int.Parse(Console.ReadLine()); }
static long ReadLong() { return long.Parse(Console.ReadLine()); }
static double ReadDouble() { return double.Parse(Console.ReadLine()); }
static string[] ReadStAr(char sep = ' ') { return Console.ReadLine().Split(sep); }
static int[] ReadIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); }
static long[] ReadLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); }
static double[] ReadDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); }
static string WriteAr(int[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
static string WriteAr(double[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
static string WriteAr(long[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
}
}
| Go | package main
import (
"fmt"
"os"
"io"
"bufio"
"bytes"
"strings"
"strconv"
// "sort"
)
// 長い入力を読む
func ReadLongLines(times int) ([]string, error) {
result := make([]string, times)
reader := bufio.NewReader(os.Stdin)
buffer := bytes.NewBuffer(make([]byte, 0))
readBytes := int64(2)
for i := 0; i < times; i++ {
for {
readBuf, isPrefix, err := reader.ReadLine()
// fmt.Printf("Reader.Read: %d\n", len(readBuf))
readBytes += int64(len(readBuf) + 1)
if err != nil {
if err == io.EOF {
fmt.Println("EOF")
break
} else {
return result, err
}
}
_, err = buffer.Write(readBuf)
if err != nil {
return result, err
}
// end of line
if !isPrefix {
result[i] = buffer.String()
buffer.Reset()
// reader = bufio.NewReader(os.Stdin)
break
}
}
}
// 先読みしてしまうようなので、戻しておく
os.Stdin.Seek(-int64(reader.Buffered()), os.SEEK_CUR)
return result, nil
}
// 出力 for 競プロ
type Console struct {
writer *bufio.Writer
}
func NewConsole() Console {
return Console{ bufio.NewWriter(os.Stdout) }
}
func (this *Console) Printf(format string, a ...interface{}) {
fmt.Fprintf(this.writer, format, a...)
}
func (this *Console) Println(s string) {
fmt.Fprintln(this.writer, s)
}
func (this *Console) Close() {
this.Flush()
}
func (this Console) Flush() {
this.writer.Flush()
}
// sort 済み配列から list[i] < n となる最初の要素のインデックスを返す。なければ n
func LowerBound(list []int, key int) int {
return LowerBoundProc(list, key, -1, len(list))
}
func LowerBoundProc(list []int, key int, begin int, end int) int {
mid := (end - begin) / 2 + begin
if (end - begin) == 1 {
return end
}
if list[mid] < key {
return LowerBoundProc(list, key, mid, end)
} else {
return LowerBoundProc(list, key, begin, mid)
}
}
func UpperBound(list []int, key int) int {
return UpperBoundProc(list, key, -1, len(list))
}
func UpperBoundProc(list []int, key int, begin int, end int) int {
mid := (end - begin) / 2 + begin
// fmt.Printf("key: %d = %d %d %d\n", key, begin, mid, end)
if 1 == end - begin {
return end
}
if list[mid] <= key {
// fmt.Println("key is large")
return UpperBoundProc(list, key, mid, end)
} else {
return UpperBoundProc(list, key, begin, mid)
}
}
func PrintList(list []int) {
con := NewConsole()
defer con.Flush()
for i := range list {
if i == 0 {
con.Printf("%d", list[i])
} else {
con.Printf(" %d", list[i])
}
}
con.Println("")
}
func main() {
con := NewConsole()
defer con.Flush()
// create list
var n int
fmt.Scanf("%d", &n)
list := make([]int, n)
lines, _ := ReadLongLines(1)
elements := strings.Split(lines[0], " ")
for i := range elements{
x, _ := strconv.Atoi(elements[i])
list[i] = x
}
var q int
fmt.Scanf("%d", &q)
lines, _ = ReadLongLines(q)
for i := range lines {
x, _ := strconv.Atoi(lines[i])
lb := LowerBound(list, x)
ub := UpperBound(list, x)
con.Printf("%d %d\n", lb, ub)
}
}
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ITP2_6_D
{
public class Program
{
public static void Main(string[] args)
{
int n = ReadInt();
int[] line = ReadIntAr();
Comparer comparer;
int q = ReadInt();
for (int i = 0 ; i < q ; i++)
{
int k = ReadInt();
comparer = new Comparer(line, k);
Console.WriteLine("{0} {1}",BinarySearch(0, n - 1, comparer), BinarySearch2(0, n - 1, comparer));
}
}
class Comparer : IComparer<int>
{
private int[] array;
private int k;
public Comparer(int[] array, int k)
{
this.array = array;
this.k = k;
}
public int Compare(int x, int y)
{
return array[x].CompareTo(k);
}
}
/// <summary>
/// 二分探索
/// -始点から終点までの整数列の中から、比較関数を満たす値を二分探索する
/// 値が見つからない場合は、条件を満たす最小の数を返す
/// </summary>
/// <param name="left">始点</param>
/// <param name="right">終点</param>
/// <param name="comparer">比較関数</param>
/// <returns></returns>
public static int BinarySearch(int left, int right, IComparer<int> comparer)
{
int lo = left;
int hi = right;
while (lo <= hi)
{
int i = GetMedian(lo, hi);
int c = comparer.Compare(i, 0);//yはダミーとして0固定
if (c < 0) lo = i + 1;
else hi = i - 1;
}
return lo;
}
public static int BinarySearch2(int left, int right, IComparer<int> comparer)
{
int lo = left;
int hi = right;
while (lo <= hi)
{
int i = GetMedian(lo, hi);
int c = comparer.Compare(i, 0);//yはダミーとして0固定
if (c <= 0) lo = i + 1;
else hi = i - 1;
}
return lo;
}
private static int GetMedian(int low, int hi) { return low + ((hi - low) >> 1); }
static string ReadSt() { return Console.ReadLine(); }
static int ReadInt() { return int.Parse(Console.ReadLine()); }
static long ReadLong() { return long.Parse(Console.ReadLine()); }
static double ReadDouble() { return double.Parse(Console.ReadLine()); }
static string[] ReadStAr(char sep = ' ') { return Console.ReadLine().Split(sep); }
static int[] ReadIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); }
static long[] ReadLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); }
static double[] ReadDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); }
static string WriteAr(int[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
static string WriteAr(double[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
static string WriteAr(long[] array, string sep = " ") { return String.Join(sep, array.Select(x => x.ToString()).ToArray()); }
}
}
Code 2: package main
import (
"fmt"
"os"
"io"
"bufio"
"bytes"
"strings"
"strconv"
// "sort"
)
// 長い入力を読む
func ReadLongLines(times int) ([]string, error) {
result := make([]string, times)
reader := bufio.NewReader(os.Stdin)
buffer := bytes.NewBuffer(make([]byte, 0))
readBytes := int64(2)
for i := 0; i < times; i++ {
for {
readBuf, isPrefix, err := reader.ReadLine()
// fmt.Printf("Reader.Read: %d\n", len(readBuf))
readBytes += int64(len(readBuf) + 1)
if err != nil {
if err == io.EOF {
fmt.Println("EOF")
break
} else {
return result, err
}
}
_, err = buffer.Write(readBuf)
if err != nil {
return result, err
}
// end of line
if !isPrefix {
result[i] = buffer.String()
buffer.Reset()
// reader = bufio.NewReader(os.Stdin)
break
}
}
}
// 先読みしてしまうようなので、戻しておく
os.Stdin.Seek(-int64(reader.Buffered()), os.SEEK_CUR)
return result, nil
}
// 出力 for 競プロ
type Console struct {
writer *bufio.Writer
}
func NewConsole() Console {
return Console{ bufio.NewWriter(os.Stdout) }
}
func (this *Console) Printf(format string, a ...interface{}) {
fmt.Fprintf(this.writer, format, a...)
}
func (this *Console) Println(s string) {
fmt.Fprintln(this.writer, s)
}
func (this *Console) Close() {
this.Flush()
}
func (this Console) Flush() {
this.writer.Flush()
}
// sort 済み配列から list[i] < n となる最初の要素のインデックスを返す。なければ n
func LowerBound(list []int, key int) int {
return LowerBoundProc(list, key, -1, len(list))
}
func LowerBoundProc(list []int, key int, begin int, end int) int {
mid := (end - begin) / 2 + begin
if (end - begin) == 1 {
return end
}
if list[mid] < key {
return LowerBoundProc(list, key, mid, end)
} else {
return LowerBoundProc(list, key, begin, mid)
}
}
func UpperBound(list []int, key int) int {
return UpperBoundProc(list, key, -1, len(list))
}
func UpperBoundProc(list []int, key int, begin int, end int) int {
mid := (end - begin) / 2 + begin
// fmt.Printf("key: %d = %d %d %d\n", key, begin, mid, end)
if 1 == end - begin {
return end
}
if list[mid] <= key {
// fmt.Println("key is large")
return UpperBoundProc(list, key, mid, end)
} else {
return UpperBoundProc(list, key, begin, mid)
}
}
func PrintList(list []int) {
con := NewConsole()
defer con.Flush()
for i := range list {
if i == 0 {
con.Printf("%d", list[i])
} else {
con.Printf(" %d", list[i])
}
}
con.Println("")
}
func main() {
con := NewConsole()
defer con.Flush()
// create list
var n int
fmt.Scanf("%d", &n)
list := make([]int, n)
lines, _ := ReadLongLines(1)
elements := strings.Split(lines[0], " ")
for i := range elements{
x, _ := strconv.Atoi(elements[i])
list[i] = x
}
var q int
fmt.Scanf("%d", &q)
lines, _ = ReadLongLines(q)
for i := range lines {
x, _ := strconv.Atoi(lines[i])
lb := LowerBound(list, x)
ub := UpperBound(list, x)
con.Printf("%d %d\n", lb, ub)
}
}
|
JavaScript | let main = (standardInput) => {
let lengthList = standardInput.split(" ");
let input = Number.parseInt(lengthList[0]);
function fib(n) {
let first = 1,
second = 1,
result = 0;
if (n === 0 || n === 1) {
return 1;
} else {
for (let i = 1; i < n; i++) {
result = first + second;
first = second;
second = result;
}
return result;
}
}
console.log(fib(input));
};
main(require("fs").readFileSync("/dev/stdin", "UTF-8"));
| Kotlin | fun main(args: Array<String>) {
val n = readLine()?.toInt() ?: return
val fibonacci = Fibonacci()
println(fibonacci.getFibonacci(n))
}
class Fibonacci {
private val fibonacciMemo = mutableMapOf(0 to 1, 1 to 1)
fun getFibonacci(n: Int): Int {
return if (fibonacciMemo[n] != null) {
fibonacciMemo[n]!!
} else {
fibonacciMemo[n] = getFibonacci(n - 2) + getFibonacci(n - 1)
fibonacciMemo[n]!!
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: let main = (standardInput) => {
let lengthList = standardInput.split(" ");
let input = Number.parseInt(lengthList[0]);
function fib(n) {
let first = 1,
second = 1,
result = 0;
if (n === 0 || n === 1) {
return 1;
} else {
for (let i = 1; i < n; i++) {
result = first + second;
first = second;
second = result;
}
return result;
}
}
console.log(fib(input));
};
main(require("fs").readFileSync("/dev/stdin", "UTF-8"));
Code 2: fun main(args: Array<String>) {
val n = readLine()?.toInt() ?: return
val fibonacci = Fibonacci()
println(fibonacci.getFibonacci(n))
}
class Fibonacci {
private val fibonacciMemo = mutableMapOf(0 to 1, 1 to 1)
fun getFibonacci(n: Int): Int {
return if (fibonacciMemo[n] != null) {
fibonacciMemo[n]!!
} else {
fibonacciMemo[n] = getFibonacci(n - 2) + getFibonacci(n - 1)
fibonacciMemo[n]!!
}
}
}
|
Kotlin | var black = 0L
var white = 0L
val map = mutableListOf<MutableList<Char>>()
fun main(args: Array<String>) {
val (h, w) = readLine()!!.split(' ').map(String::toInt)
map.add(Array(w + 2) { 'X' }.toMutableList())
(1..h).forEach {
val element = readLine()!!.toCharArray().toMutableList()
element.add(0, 'X')
element.add(element.size, 'X')
map.add(element)
}
map.add(Array(w + 2) { 'X' }.toMutableList())
var ans = 0L
for (r in 1..h) {
for (c in 1..w) {
black = 0L
white = 0L
check(r, c)
ans += black * white
}
}
println(ans)
}
fun check(r: Int, c: Int) {
val current = map[r][c]
when (current) {
'X' -> return
'#' -> {
black++
map[r][c] = 'X'
}
'.' -> {
white++
map[r][c] = 'X'
}
}
if (map[r - 1][c] != current) check(r - 1, c)
if (map[r][c - 1] != current) check(r, c - 1)
if (map[r + 1][c] != current) check(r + 1, c)
if (map[r][c + 1] != current) check(r, c + 1)
} | PHP | <?php
$input = explode(' ', trim(fgets(STDIN)));
$h = (int)$input[0];
$w = (int)$input[1];
$graph = [];
for ($i=1; $i <= $h; $i++) {
$input = trim(fgets(STDIN));
for ($j=1; $j <= $w; $j++) {
$graph[$i][$j] = [
'color' => $input[$j-1],
'check' => false
];
}
}
$sum = 0;
for ($i=1; $i <= $h; $i++) {
for ($j=1; $j <= $w; $j++) {
if ($graph[$i][$j]['check'] === false) {
$result = dfs($i, $j);
$sum += $result['#'] * $result['.'];
}
}
}
echo $sum;
function dfs($i, $j){
global $graph;
$count = ['#'=>0, '.'=>0];
$cur_c = $graph[$i][$j]['color'];
$count[$cur_c] = 1;
$graph[$i][$j]['check'] = true;
$cand = [];
if (isset($graph[$i][$j-1])) {
$cand[] = [$i, $j-1];
}
if (isset($graph[$i][$j+1])) {
$cand[] = [$i, $j+1];
}
if (isset($graph[$i+1][$j])) {
$cand[] =[$i+1, $j];
}
if (isset($graph[$i-1][$j])) {
$cand[] = [$i-1, $j];
}
foreach ($cand as $val) {
if ($graph[$val[0]][$val[1]]['color'] !== $cur_c && $graph[$val[0]][$val[1]]['check'] === false) {
$result = dfs($val[0], $val[1]);
$count['#'] += $result['#'];
$count['.'] += $result['.'];
}
}
return $count;
} | Yes | Do these codes solve the same problem?
Code 1: var black = 0L
var white = 0L
val map = mutableListOf<MutableList<Char>>()
fun main(args: Array<String>) {
val (h, w) = readLine()!!.split(' ').map(String::toInt)
map.add(Array(w + 2) { 'X' }.toMutableList())
(1..h).forEach {
val element = readLine()!!.toCharArray().toMutableList()
element.add(0, 'X')
element.add(element.size, 'X')
map.add(element)
}
map.add(Array(w + 2) { 'X' }.toMutableList())
var ans = 0L
for (r in 1..h) {
for (c in 1..w) {
black = 0L
white = 0L
check(r, c)
ans += black * white
}
}
println(ans)
}
fun check(r: Int, c: Int) {
val current = map[r][c]
when (current) {
'X' -> return
'#' -> {
black++
map[r][c] = 'X'
}
'.' -> {
white++
map[r][c] = 'X'
}
}
if (map[r - 1][c] != current) check(r - 1, c)
if (map[r][c - 1] != current) check(r, c - 1)
if (map[r + 1][c] != current) check(r + 1, c)
if (map[r][c + 1] != current) check(r, c + 1)
}
Code 2: <?php
$input = explode(' ', trim(fgets(STDIN)));
$h = (int)$input[0];
$w = (int)$input[1];
$graph = [];
for ($i=1; $i <= $h; $i++) {
$input = trim(fgets(STDIN));
for ($j=1; $j <= $w; $j++) {
$graph[$i][$j] = [
'color' => $input[$j-1],
'check' => false
];
}
}
$sum = 0;
for ($i=1; $i <= $h; $i++) {
for ($j=1; $j <= $w; $j++) {
if ($graph[$i][$j]['check'] === false) {
$result = dfs($i, $j);
$sum += $result['#'] * $result['.'];
}
}
}
echo $sum;
function dfs($i, $j){
global $graph;
$count = ['#'=>0, '.'=>0];
$cur_c = $graph[$i][$j]['color'];
$count[$cur_c] = 1;
$graph[$i][$j]['check'] = true;
$cand = [];
if (isset($graph[$i][$j-1])) {
$cand[] = [$i, $j-1];
}
if (isset($graph[$i][$j+1])) {
$cand[] = [$i, $j+1];
}
if (isset($graph[$i+1][$j])) {
$cand[] =[$i+1, $j];
}
if (isset($graph[$i-1][$j])) {
$cand[] = [$i-1, $j];
}
foreach ($cand as $val) {
if ($graph[$val[0]][$val[1]]['color'] !== $cur_c && $graph[$val[0]][$val[1]]['check'] === false) {
$result = dfs($val[0], $val[1]);
$count['#'] += $result['#'];
$count['.'] += $result['.'];
}
}
return $count;
} |
Python | s = list(input())
print(s[0]+str(len(s)-2)+s[-1])
| C++ | #include<bits/stdc++.h>
#define ll long long int
using namespace std;
const ll mod=1000000007;
const ll inf=1e18;
int main(){
ll n,m;
cin >> n >> m;
ll l=1,r=n;
for(int i=0;i<m;i++){
ll L,R;
cin >> L >> R;
if(l<L)l=L;
if(R<r)r=R;
}
if(r>=l)cout << r-l+1 << endl;
else cout << 0 << endl;
} | No | Do these codes solve the same problem?
Code 1: s = list(input())
print(s[0]+str(len(s)-2)+s[-1])
Code 2: #include<bits/stdc++.h>
#define ll long long int
using namespace std;
const ll mod=1000000007;
const ll inf=1e18;
int main(){
ll n,m;
cin >> n >> m;
ll l=1,r=n;
for(int i=0;i<m;i++){
ll L,R;
cin >> L >> R;
if(l<L)l=L;
if(R<r)r=R;
}
if(r>=l)cout << r-l+1 << endl;
else cout << 0 << endl;
} |
C# | using System;
public class hello
{
public static void Main()
{
while (true)
{
var s = Console.ReadLine().Trim();
if (s == "END OF INPUT") break;
string[] s2 = s.Split(' ');
foreach (var x in s2)
Console.Write(x.Length);
Console.WriteLine();
}
}
}
| PHP | <?php
$str;
while(1) {
$a = trim(fgets(STDIN));
if ($a == "END OF INPUT") break;
$b = explode(" ", $a);
foreach ($b as $i) {
echo strlen($i);
}
echo PHP_EOL;
}
?>
| Yes | Do these codes solve the same problem?
Code 1: using System;
public class hello
{
public static void Main()
{
while (true)
{
var s = Console.ReadLine().Trim();
if (s == "END OF INPUT") break;
string[] s2 = s.Split(' ');
foreach (var x in s2)
Console.Write(x.Length);
Console.WriteLine();
}
}
}
Code 2: <?php
$str;
while(1) {
$a = trim(fgets(STDIN));
if ($a == "END OF INPUT") break;
$b = explode(" ", $a);
foreach ($b as $i) {
echo strlen($i);
}
echo PHP_EOL;
}
?>
|
C | #include <stdio.h>
int main(void)
{
int p[3],j[2],ans,minp,minj,i;
scanf("%d", &p[0]);
minp=p[0];
for(i=1;i<3;i++){
scanf("%d", &p[i]);
if(p[i]<minp) minp=p[i];
}
scanf("%d", &j[0]);
minj=j[0];
scanf("%d", &j[1]);
if(j[1]<minj) minj=j[1];
printf("%d\n", minp+minj-50);
return 0;
}
| C++ | #include <iostream>
#include <algorithm>
using namespace std;
int main() {
int menu[5], sum;
for(int i=0; i<5; i++) {
cin >> menu[i];
}
sum = *min_element(menu, menu+3);
sum+= *min_element(menu+3, menu+5);
sum-= 50;
cout << sum << endl;
return 0;
}
| Yes | Do these codes solve the same problem?
Code 1: #include <stdio.h>
int main(void)
{
int p[3],j[2],ans,minp,minj,i;
scanf("%d", &p[0]);
minp=p[0];
for(i=1;i<3;i++){
scanf("%d", &p[i]);
if(p[i]<minp) minp=p[i];
}
scanf("%d", &j[0]);
minj=j[0];
scanf("%d", &j[1]);
if(j[1]<minj) minj=j[1];
printf("%d\n", minp+minj-50);
return 0;
}
Code 2: #include <iostream>
#include <algorithm>
using namespace std;
int main() {
int menu[5], sum;
for(int i=0; i<5; i++) {
cin >> menu[i];
}
sum = *min_element(menu, menu+3);
sum+= *min_element(menu+3, menu+5);
sum-= 50;
cout << sum << endl;
return 0;
}
|
C++ | #include <iostream>
#include <cstdio>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#ifdef ENABLE_LL
#define int long long
#endif
#ifdef ENABLE_LL
#define I "%lld"
#define II "%lld%lld"
#define III "%lld%lld%lld"
#define IIII "%lld%lld%lld%lld"
#define IN "%lld\n"
#define IIN "%lld%lld\n"
#define IIIN "%lld%lld%lld\n"
#define IIIIN "%lld%lld%lld%lld\n"
#else
#define I "%d"
#define II "%d%d"
#define III "%d%d%d"
#define IIII "%d%d%d%d"
#define IN "%d\n"
#define IIN "%d%d\n"
#define IIIN "%d%d%d\n"
#define IIIIN "%d%d%d%d\n"
#endif
#ifdef __LOCALE__
#define see(a) std::cout << #a << "=" << a << std::endl
#define ses(a) std::cout << #a << "=" << a << " "
#else
#define see(a) //std::cout << #a << "=" << a << std::endl
#define ses(a)
#endif
#define repe(a,b) for (int a=0;a<(int)b.size();a++)
#define rep(i,n) for (int i=0;i<n;i++)
#define repa(i,n) for (int i=1;i<=n;i++)
#define repi(i,a,b) for (int i=a;i<=b;i++)
#define repb(i,a,b) for (int i=a;i>=b;i--)
typedef pair < int , int > pr; typedef pair < pr , int > prr;
#define L first
#define R second
template <class T> inline bool checkMin(T& a , T b) { return (a > b ? a=b,1 : 0); }
template <class T> inline bool checkMax(T& a , T b) { return (a < b ? a=b,1 : 0); }
class Scanner{ private: istream& ist;public: Scanner(istream& in):ist(in){} string next(){ string r; ist >> r; return r; } string nextLine(){ string r; getline(ist,r); return r; } int nextInt(){ int r; ist >> r; return r; } double nextDouble(){ double r; ist >> r; return r; } char nextChar(){ char r; ist>>r; return r;} }; Scanner sc(cin);
void ALERT(bool judgememt, const char* phrase) { if (judgememt) { puts(phrase); throw "ALERT"; } }
bool alert(bool judgememt, const char* phrase) { if (judgememt) puts("phrase"); return judgememt; }
const int N = 200005;
int a[N], b[N];
int n;
void init() {
scanf(I,&n);
rep (i,n) scanf(II,&a[i],&b[i]);
sort(a, a+n); sort(b, b+n);
}
double getMedian(int* a) {
if (n&1) return a[n/2];
else return (a[n/2] + a[n/2-1]) / 2.0;
}
void solve() {
if (n&1) printf(IN,(int)( getMedian(b) - getMedian(a) + 1) );
else printf(IN,(int)((getMedian(b) - getMedian(a))* 2 + 1));
}
#ifdef ENABLE_LL
#undef int
#endif
int main(){
#ifndef CUSTOM_MAIN
#ifdef MULTIPLE_TEST_CASES_WITH_T
int T; scanf("%d",&T); while(T--) {init(); solve();}
#else
#ifdef MULTIPLE_TEST_CASES_WITHOUT_T
while(1) {try{init(); } catch(bool t){return 0;} solve(); }
#else
init(); solve();
#endif
#endif
#endif
return 0;
}
| Python | N, K = map(int,input().split())
S = input()
print(S[0:K-1]+S[K-1].lower()+S[K:]) | No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <cstdio>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#ifdef ENABLE_LL
#define int long long
#endif
#ifdef ENABLE_LL
#define I "%lld"
#define II "%lld%lld"
#define III "%lld%lld%lld"
#define IIII "%lld%lld%lld%lld"
#define IN "%lld\n"
#define IIN "%lld%lld\n"
#define IIIN "%lld%lld%lld\n"
#define IIIIN "%lld%lld%lld%lld\n"
#else
#define I "%d"
#define II "%d%d"
#define III "%d%d%d"
#define IIII "%d%d%d%d"
#define IN "%d\n"
#define IIN "%d%d\n"
#define IIIN "%d%d%d\n"
#define IIIIN "%d%d%d%d\n"
#endif
#ifdef __LOCALE__
#define see(a) std::cout << #a << "=" << a << std::endl
#define ses(a) std::cout << #a << "=" << a << " "
#else
#define see(a) //std::cout << #a << "=" << a << std::endl
#define ses(a)
#endif
#define repe(a,b) for (int a=0;a<(int)b.size();a++)
#define rep(i,n) for (int i=0;i<n;i++)
#define repa(i,n) for (int i=1;i<=n;i++)
#define repi(i,a,b) for (int i=a;i<=b;i++)
#define repb(i,a,b) for (int i=a;i>=b;i--)
typedef pair < int , int > pr; typedef pair < pr , int > prr;
#define L first
#define R second
template <class T> inline bool checkMin(T& a , T b) { return (a > b ? a=b,1 : 0); }
template <class T> inline bool checkMax(T& a , T b) { return (a < b ? a=b,1 : 0); }
class Scanner{ private: istream& ist;public: Scanner(istream& in):ist(in){} string next(){ string r; ist >> r; return r; } string nextLine(){ string r; getline(ist,r); return r; } int nextInt(){ int r; ist >> r; return r; } double nextDouble(){ double r; ist >> r; return r; } char nextChar(){ char r; ist>>r; return r;} }; Scanner sc(cin);
void ALERT(bool judgememt, const char* phrase) { if (judgememt) { puts(phrase); throw "ALERT"; } }
bool alert(bool judgememt, const char* phrase) { if (judgememt) puts("phrase"); return judgememt; }
const int N = 200005;
int a[N], b[N];
int n;
void init() {
scanf(I,&n);
rep (i,n) scanf(II,&a[i],&b[i]);
sort(a, a+n); sort(b, b+n);
}
double getMedian(int* a) {
if (n&1) return a[n/2];
else return (a[n/2] + a[n/2-1]) / 2.0;
}
void solve() {
if (n&1) printf(IN,(int)( getMedian(b) - getMedian(a) + 1) );
else printf(IN,(int)((getMedian(b) - getMedian(a))* 2 + 1));
}
#ifdef ENABLE_LL
#undef int
#endif
int main(){
#ifndef CUSTOM_MAIN
#ifdef MULTIPLE_TEST_CASES_WITH_T
int T; scanf("%d",&T); while(T--) {init(); solve();}
#else
#ifdef MULTIPLE_TEST_CASES_WITHOUT_T
while(1) {try{init(); } catch(bool t){return 0;} solve(); }
#else
init(); solve();
#endif
#endif
#endif
return 0;
}
Code 2: N, K = map(int,input().split())
S = input()
print(S[0:K-1]+S[K-1].lower()+S[K:]) |
C | #include <stdio.h>
int main(void)
{
double weight;
while(scanf("%lf", &weight)!=EOF) {
if(weight>91.00) printf("heavy\n");
else if(weight>81.00) printf("light heavy\n");
else if(weight>75.00) printf("middle\n");
else if(weight>69.00) printf("light middle\n");
else if(weight>64.00) printf("welter\n");
else if(weight>60.00) printf("light welter\n");
else if(weight>57.00) printf("light\n");
else if(weight>54.00) printf("feather\n");
else if(weight>51.00) printf("bantam\n");
else if(weight>48.00) printf("fly\n");
else printf("light fly\n");
}
return 0;
}
| Java | import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextDouble()){
double n = sc.nextDouble();
if(n <= 48.0){
System.out.println("light fly");
}else if(n <= 51.0){
System.out.println("fly");
}else if(n <= 54.0){
System.out.println("bantam");
}else if(n <= 57.0){
System.out.println("feather");
}else if(n <= 60.0){
System.out.println("light");
}else if(n <= 64.0){
System.out.println("light welter");
}else if(n <= 69.0){
System.out.println("welter");
}else if(n <= 75.0){
System.out.println("light middle");
}else if(n <= 81.0){
System.out.println("middle");
}else if(n <= 91.0){
System.out.println("light heavy");
}else{
System.out.println("heavy");
}
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <stdio.h>
int main(void)
{
double weight;
while(scanf("%lf", &weight)!=EOF) {
if(weight>91.00) printf("heavy\n");
else if(weight>81.00) printf("light heavy\n");
else if(weight>75.00) printf("middle\n");
else if(weight>69.00) printf("light middle\n");
else if(weight>64.00) printf("welter\n");
else if(weight>60.00) printf("light welter\n");
else if(weight>57.00) printf("light\n");
else if(weight>54.00) printf("feather\n");
else if(weight>51.00) printf("bantam\n");
else if(weight>48.00) printf("fly\n");
else printf("light fly\n");
}
return 0;
}
Code 2: import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextDouble()){
double n = sc.nextDouble();
if(n <= 48.0){
System.out.println("light fly");
}else if(n <= 51.0){
System.out.println("fly");
}else if(n <= 54.0){
System.out.println("bantam");
}else if(n <= 57.0){
System.out.println("feather");
}else if(n <= 60.0){
System.out.println("light");
}else if(n <= 64.0){
System.out.println("light welter");
}else if(n <= 69.0){
System.out.println("welter");
}else if(n <= 75.0){
System.out.println("light middle");
}else if(n <= 81.0){
System.out.println("middle");
}else if(n <= 91.0){
System.out.println("light heavy");
}else{
System.out.println("heavy");
}
}
}
}
|
C | #include <stdio.h>
#include <string.h>
typedef struct WORDBOOK {
char word[5000][21];
int count[5000];
int wordcount;
} WORDBOOK;
WORDBOOK wordbook[26];
void init_words(WORDBOOK *words);
void sort_dictionary(WORDBOOK *words, int j);
void display_word(WORDBOOK *words, int num);
int main(void)
{
char sentence[1050];
char tmp[21];
char *p;
char initial[2];
char temp;
int line_num;
int i, j, k, m;
int num;
int flag;
for (i = 0; i < 26; i++) { /* wordbook讒矩菴薙・n繧貞・縺ヲ0縺ォ蛻晄悄蛹・*/
wordbook[i].wordcount = 0;
}
while (1) {
scanf("%d", &line_num); /* 陦梧焚蜈・蜉・*/
if (line_num == 0) {
break;
}
scanf("%c", &temp); /* Enter遨コ隱ュ縺ソ */
init_words(wordbook);
for (i = 0; i < 26; i++) { /* wordbook讒矩菴薙・n繧貞・縺ヲ0縺ォ蛻晄悄蛹・*/
wordbook[i].wordcount = 0;
}
for (i = 0; i < line_num; i++) {
fgets(sentence, sizeof(sentence), stdin); /* 譁・ォ蜈・蜉・*/
p = sentence;
while (*p != '\n') {
if (*p == ' ') {
p++;
}
num = *p;
num -= 97;
k = 0;
while ('a' <= *p && *p <= 'z') {
tmp[k] = *p;
k++;
p++;
}
tmp[k] = '\0';
flag = 0;
for (m = 0; m < wordbook[num].wordcount; m++) {
if (strcmp(wordbook[num].word[m], tmp) == 0) {
wordbook[num].count[m]++;
flag = 1;
break;
}
}
if (flag == 0) {
strcpy(wordbook[num].word[wordbook[num].wordcount], tmp);
wordbook[num].count[wordbook[num].wordcount] = 1;
wordbook[num].wordcount++;
}
}
}
for (j = 0; j < 26; j++) {
if (wordbook[j].wordcount > 1) {
sort_dictionary(wordbook, j);
}
}
scanf("%s", initial);
num = initial[0];
num -= 97;
if (wordbook[num].wordcount == 0) {
printf("NA\n");
} else {
display_word(wordbook, num);
}
}
return (0);
}
void init_words(WORDBOOK *words)
{
int i, j;
for (i = 0; i < 26; i++) {
for (j = 0; j < 5000; j++) {
words[i].word[j][0] = '\0';
wordbook[i].count[j] = 0;
}
}
}
/* 蜊倩ェ槭r霎樊嶌鬆・↓繧ス繝シ繝・*/
void sort_dictionary(WORDBOOK *words, int j)
{
int k, l;
int flag;
int temp;
char tmp[1050];
for (k = 0; k <= words[j].wordcount - 2; k++) {
flag = 0;
for (l = k + 1; l <= words[j].wordcount - 1; l++) {
/* 蜃コ迴セ蝗樊焚縺悟、壹>蜊倩ェ槭r髯埼・た繝シ繝・*/
if (wordbook[j].count[k] < wordbook[j].count[l]) {
flag = 1;
temp = wordbook[j].count[k];
wordbook[j].count[k] = wordbook[j].count[l];
wordbook[j].count[l] = temp;
strcpy(tmp, words[j].word[k]);
strcpy(words[j].word[k], words[j].word[l]);
strcpy(words[j].word[l], tmp);
}
/* 蜃コ迴セ蝗樊焚縺悟酔縺伜腰隱槭r霎樊嶌蠑城・コ上〒荳ヲ縺ウ譖ソ縺医k */
if (wordbook[j].count[k] == wordbook[j].count[l]) {
if (strcmp(wordbook[j].word[k], wordbook[j].word[l]) > 0) {
flag = 1;
strcpy(tmp, words[j].word[k]);
strcpy(words[j].word[k], words[j].word[l]);
strcpy(words[j].word[l], tmp);
}
}
}
if (flag == 0) {
// break;
}
}
}
/* 謖・ョ壹&繧後◆鬆ュ譁・ュ励・蜊倩ェ槭r陦ィ遉コ */
void display_word(WORDBOOK *words, int num)
{
int i;
int count;
count = 0;
for (i = 0; i < words[num].wordcount; i++) {
if (i != 0) {
printf(" ");
}
printf("%s", words[num].word[i]);
count++;
if (count == 5) {
break;
}
}
#if 0
count = 0;
for (i = 0; i <= words[num].wordcount; i++) {
if (words[num].word[i][0] != '0') {
printf("%s", words[num].word[i]);
if (i == words[num].wordcount - 1) {
break;
}
printf(" ");
count++;
}
if (count == 5) {
break;
}
}
#endif
printf("\n");
}
| Java | import java.util.*;
public class Main {
Scanner in = new Scanner(System.in);
public static void main(String[] args) {
new Main();
}
public Main() {
while(true){
int n = Integer.parseInt(in.nextLine());
if(n==0)break;
new AOJ0242().doIt(n);
}
}
class AOJ0242{
void doIt(int n){
HashMap<String,KeepString> map = new HashMap<String,KeepString>();
for(int i=0;i<n;i++){
String[] a = in.nextLine().split(" ");
for(int s=0;s<a.length;s++){
if(!map.containsKey(a[s]))map.put(a[s],new KeepString(a[s]));
map.get(a[s]).cnt++;
}
}
ArrayList<KeepString> list = new ArrayList<KeepString>();
for(String str: map.keySet())list.add(map.get(str));
Collections.sort(list);
// for(int i=0;i<list.size();i++)System.out.println(list.get(i));//deba
char[] target = in.nextLine().toCharArray();
String result = "";
int cnt = 0;
for(int i=0;i<list.size();i++)if(list.get(i).word.charAt(0)==target[0]){
if(result.length()>0)result+=" ";
result+=list.get(i).word;
cnt++;
if(cnt>4)break;
}
if(result!="")System.out.println(result);
else System.out.println("NA");
}
class KeepString implements Comparable<KeepString>{
int cnt;
String word;
public KeepString(String word) {
cnt = 0;
this.word = word;
}
public int compareTo(KeepString o) {
if(this.cnt>o.cnt)return -1;
else if(this.cnt<o.cnt)return 1;
else if(this.word.compareTo(o.word)>0)return 1;
else return -1;
}
public String toString(){
return this.word+" "+cnt;
}
}
}
} | Yes | Do these codes solve the same problem?
Code 1: #include <stdio.h>
#include <string.h>
typedef struct WORDBOOK {
char word[5000][21];
int count[5000];
int wordcount;
} WORDBOOK;
WORDBOOK wordbook[26];
void init_words(WORDBOOK *words);
void sort_dictionary(WORDBOOK *words, int j);
void display_word(WORDBOOK *words, int num);
int main(void)
{
char sentence[1050];
char tmp[21];
char *p;
char initial[2];
char temp;
int line_num;
int i, j, k, m;
int num;
int flag;
for (i = 0; i < 26; i++) { /* wordbook讒矩菴薙・n繧貞・縺ヲ0縺ォ蛻晄悄蛹・*/
wordbook[i].wordcount = 0;
}
while (1) {
scanf("%d", &line_num); /* 陦梧焚蜈・蜉・*/
if (line_num == 0) {
break;
}
scanf("%c", &temp); /* Enter遨コ隱ュ縺ソ */
init_words(wordbook);
for (i = 0; i < 26; i++) { /* wordbook讒矩菴薙・n繧貞・縺ヲ0縺ォ蛻晄悄蛹・*/
wordbook[i].wordcount = 0;
}
for (i = 0; i < line_num; i++) {
fgets(sentence, sizeof(sentence), stdin); /* 譁・ォ蜈・蜉・*/
p = sentence;
while (*p != '\n') {
if (*p == ' ') {
p++;
}
num = *p;
num -= 97;
k = 0;
while ('a' <= *p && *p <= 'z') {
tmp[k] = *p;
k++;
p++;
}
tmp[k] = '\0';
flag = 0;
for (m = 0; m < wordbook[num].wordcount; m++) {
if (strcmp(wordbook[num].word[m], tmp) == 0) {
wordbook[num].count[m]++;
flag = 1;
break;
}
}
if (flag == 0) {
strcpy(wordbook[num].word[wordbook[num].wordcount], tmp);
wordbook[num].count[wordbook[num].wordcount] = 1;
wordbook[num].wordcount++;
}
}
}
for (j = 0; j < 26; j++) {
if (wordbook[j].wordcount > 1) {
sort_dictionary(wordbook, j);
}
}
scanf("%s", initial);
num = initial[0];
num -= 97;
if (wordbook[num].wordcount == 0) {
printf("NA\n");
} else {
display_word(wordbook, num);
}
}
return (0);
}
void init_words(WORDBOOK *words)
{
int i, j;
for (i = 0; i < 26; i++) {
for (j = 0; j < 5000; j++) {
words[i].word[j][0] = '\0';
wordbook[i].count[j] = 0;
}
}
}
/* 蜊倩ェ槭r霎樊嶌鬆・↓繧ス繝シ繝・*/
void sort_dictionary(WORDBOOK *words, int j)
{
int k, l;
int flag;
int temp;
char tmp[1050];
for (k = 0; k <= words[j].wordcount - 2; k++) {
flag = 0;
for (l = k + 1; l <= words[j].wordcount - 1; l++) {
/* 蜃コ迴セ蝗樊焚縺悟、壹>蜊倩ェ槭r髯埼・た繝シ繝・*/
if (wordbook[j].count[k] < wordbook[j].count[l]) {
flag = 1;
temp = wordbook[j].count[k];
wordbook[j].count[k] = wordbook[j].count[l];
wordbook[j].count[l] = temp;
strcpy(tmp, words[j].word[k]);
strcpy(words[j].word[k], words[j].word[l]);
strcpy(words[j].word[l], tmp);
}
/* 蜃コ迴セ蝗樊焚縺悟酔縺伜腰隱槭r霎樊嶌蠑城・コ上〒荳ヲ縺ウ譖ソ縺医k */
if (wordbook[j].count[k] == wordbook[j].count[l]) {
if (strcmp(wordbook[j].word[k], wordbook[j].word[l]) > 0) {
flag = 1;
strcpy(tmp, words[j].word[k]);
strcpy(words[j].word[k], words[j].word[l]);
strcpy(words[j].word[l], tmp);
}
}
}
if (flag == 0) {
// break;
}
}
}
/* 謖・ョ壹&繧後◆鬆ュ譁・ュ励・蜊倩ェ槭r陦ィ遉コ */
void display_word(WORDBOOK *words, int num)
{
int i;
int count;
count = 0;
for (i = 0; i < words[num].wordcount; i++) {
if (i != 0) {
printf(" ");
}
printf("%s", words[num].word[i]);
count++;
if (count == 5) {
break;
}
}
#if 0
count = 0;
for (i = 0; i <= words[num].wordcount; i++) {
if (words[num].word[i][0] != '0') {
printf("%s", words[num].word[i]);
if (i == words[num].wordcount - 1) {
break;
}
printf(" ");
count++;
}
if (count == 5) {
break;
}
}
#endif
printf("\n");
}
Code 2: import java.util.*;
public class Main {
Scanner in = new Scanner(System.in);
public static void main(String[] args) {
new Main();
}
public Main() {
while(true){
int n = Integer.parseInt(in.nextLine());
if(n==0)break;
new AOJ0242().doIt(n);
}
}
class AOJ0242{
void doIt(int n){
HashMap<String,KeepString> map = new HashMap<String,KeepString>();
for(int i=0;i<n;i++){
String[] a = in.nextLine().split(" ");
for(int s=0;s<a.length;s++){
if(!map.containsKey(a[s]))map.put(a[s],new KeepString(a[s]));
map.get(a[s]).cnt++;
}
}
ArrayList<KeepString> list = new ArrayList<KeepString>();
for(String str: map.keySet())list.add(map.get(str));
Collections.sort(list);
// for(int i=0;i<list.size();i++)System.out.println(list.get(i));//deba
char[] target = in.nextLine().toCharArray();
String result = "";
int cnt = 0;
for(int i=0;i<list.size();i++)if(list.get(i).word.charAt(0)==target[0]){
if(result.length()>0)result+=" ";
result+=list.get(i).word;
cnt++;
if(cnt>4)break;
}
if(result!="")System.out.println(result);
else System.out.println("NA");
}
class KeepString implements Comparable<KeepString>{
int cnt;
String word;
public KeepString(String word) {
cnt = 0;
this.word = word;
}
public int compareTo(KeepString o) {
if(this.cnt>o.cnt)return -1;
else if(this.cnt<o.cnt)return 1;
else if(this.word.compareTo(o.word)>0)return 1;
else return -1;
}
public String toString(){
return this.word+" "+cnt;
}
}
}
} |
Java | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.Reader;
import java.io.InputStreamReader;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyInput in = new MyInput(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FRemovingRobots solver = new FRemovingRobots();
solver.solve(1, in, out);
out.close();
}
static class FRemovingRobots {
static final int mod = 998244353;
public void solve(int testNumber, MyInput in, PrintWriter out) {
int n = in.nextInt();
TreeMap<Integer, Integer> mp = new TreeMap<>();
int[][] robots = new int[n][];
for (int i = 0; i < n; i++) {
robots[i] = in.nextIntArray(2);
}
Arrays.sort(robots, Comparator.comparingInt(r -> r[0]));
for (int i = 0; i < n; i++) {
mp.put(robots[i][0], i);
}
long[] dp = new long[n + 1];
dp[n] = 1;
Seg2 seg = new Seg2(n);
for (int i = 0; i < n; i++) {
seg.update(i, i);
}
for (int i = n - 1; i >= 0; i--) {
int j = seg.get(i, mp.lowerEntry(robots[i][0] + robots[i][1]).getValue() + 1);
seg.update(i, j);
dp[i] = (dp[i + 1] + dp[j + 1]) % mod;
}
out.println(dp[0]);
}
class Seg2 {
final int n;
final int[] seg;
public Seg2(final int n) {
this.n = Integer.highestOneBit(n) << 1;
seg = new int[this.n << 1];
}
int get(int l, int r) {
return get(l, r, 0, 0, n);
}
int get(int l, int r, int k, int curL, int curR) {
if (curR <= l || curL >= r) {
return 0;
}
if (l <= curL && curR <= r) {
return seg[k];
}
final int curM = (curL + curR) / 2;
return Math.max(
get(l, r, 2 * k + 1, curL, curM),
get(l, r, 2 * k + 2, curM, curR));
}
void update(int i, int v) {
i += n - 1;
seg[i] = v;
while (i != 0) {
i = (i - 1) / 2;
seg[i] = Math.max(seg[2 * i + 1], seg[2 * i + 2]);
}
}
}
}
static class MyInput {
private final BufferedReader in;
private static int pos;
private static int readLen;
private static final char[] buffer = new char[1024 * 8];
private static char[] str = new char[500 * 8 * 2];
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
private static boolean[] isLineSep = new boolean[256];
static {
for (int i = 0; i < 10; i++) {
isDigit['0' + i] = true;
}
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
isLineSep['\r'] = isLineSep['\n'] = true;
}
public MyInput(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public int read() {
if (pos >= readLen) {
pos = 0;
try {
readLen = in.read(buffer);
} catch (IOException e) {
throw new RuntimeException();
}
if (readLen <= 0) {
throw new MyInput.EndOfFileRuntimeException();
}
}
return buffer[pos++];
}
public int nextInt() {
int len = 0;
str[len++] = nextChar();
len = reads(len, isSpace);
int i = 0;
int ret = 0;
if (str[0] == '-') {
i = 1;
}
for (; i < len; i++) ret = ret * 10 + str[i] - '0';
if (str[0] == '-') {
ret = -ret;
}
return ret;
}
public char nextChar() {
while (true) {
final int c = read();
if (!isSpace[c]) {
return (char) c;
}
}
}
int reads(int len, boolean[] accept) {
try {
while (true) {
final int c = read();
if (accept[c]) {
break;
}
if (str.length == len) {
char[] rep = new char[str.length * 3 / 2];
System.arraycopy(str, 0, rep, 0, str.length);
str = rep;
}
str[len++] = (char) c;
}
} catch (MyInput.EndOfFileRuntimeException e) {
}
return len;
}
public int[] nextIntArray(final int n) {
final int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
static class EndOfFileRuntimeException extends RuntimeException {
}
}
}
| PHP | <?php
fscanf(STDIN, "%d", $N);
$xSortList = [];
// データを入れていく
for($i = 0; $i < $N; $i++) {
fscanf(STDIN, "%d %d", $X, $D);
$xSortList[] = [
"x" => $X,
"d" => $D,
];
}
// ソート
usort($xSortList, function($a, $b) {
return($a["x"] <=> $b["x"]);
});
// 検索用
function getIdx(&$list, $sIdx, $eIdx, $maxX) {
$idx = 0;
while($sIdx <= $eIdx) {
// 真ん中
$idx = intval(($eIdx + $sIdx) / 2);
if($list[$idx]["x"] == $maxX) {
return($idx);
}
if($list[$idx]["x"] > $maxX) {
$eIdx = $idx - 1;
}
else {
$sIdx = $idx + 1;
}
}
return($sIdx);
}
// ループ(範囲を求める)
for($i = $N - 1; $i >= 0; $i--) {
//==================================================================
// 影響範囲計算
//==================================================================
$xSortList[$i]["r"] = $i;
$maxX = $xSortList[$i]["x"] + $xSortList[$i]["d"];
$idx = max(0, min($N - 1, getIdx($xSortList, 0, $N - 1, $maxX)));
if($xSortList[$idx]["x"] >= $maxX) {
$idx = max(0, $idx - 1);
}
for($n = $i + 1; $n <= $idx; $n++) {
$xSortList[$i]["r"] = max($xSortList[$i]["r"], $xSortList[$n]["r"]);
$n = $xSortList[$i]["r"];
}
//==================================================================
// パターン計算
//==================================================================
$onNextIdx = $xSortList[$i]["r"] + 1;
$offNextIdx = $i + 1;
// ONのときよう
$on = 1;
if($onNextIdx < $N) {
$on = $xSortList[$onNextIdx]["a"];
}
// OFFのとき
$off = 1;
if($offNextIdx < $N) {
$off = $xSortList[$offNextIdx]["a"];
}
$xSortList[$i]["a"] = ($on + $off) % 998244353;
}
echo "{$xSortList[0]["a"]}\n";
| Yes | Do these codes solve the same problem?
Code 1: import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.Reader;
import java.io.InputStreamReader;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyInput in = new MyInput(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FRemovingRobots solver = new FRemovingRobots();
solver.solve(1, in, out);
out.close();
}
static class FRemovingRobots {
static final int mod = 998244353;
public void solve(int testNumber, MyInput in, PrintWriter out) {
int n = in.nextInt();
TreeMap<Integer, Integer> mp = new TreeMap<>();
int[][] robots = new int[n][];
for (int i = 0; i < n; i++) {
robots[i] = in.nextIntArray(2);
}
Arrays.sort(robots, Comparator.comparingInt(r -> r[0]));
for (int i = 0; i < n; i++) {
mp.put(robots[i][0], i);
}
long[] dp = new long[n + 1];
dp[n] = 1;
Seg2 seg = new Seg2(n);
for (int i = 0; i < n; i++) {
seg.update(i, i);
}
for (int i = n - 1; i >= 0; i--) {
int j = seg.get(i, mp.lowerEntry(robots[i][0] + robots[i][1]).getValue() + 1);
seg.update(i, j);
dp[i] = (dp[i + 1] + dp[j + 1]) % mod;
}
out.println(dp[0]);
}
class Seg2 {
final int n;
final int[] seg;
public Seg2(final int n) {
this.n = Integer.highestOneBit(n) << 1;
seg = new int[this.n << 1];
}
int get(int l, int r) {
return get(l, r, 0, 0, n);
}
int get(int l, int r, int k, int curL, int curR) {
if (curR <= l || curL >= r) {
return 0;
}
if (l <= curL && curR <= r) {
return seg[k];
}
final int curM = (curL + curR) / 2;
return Math.max(
get(l, r, 2 * k + 1, curL, curM),
get(l, r, 2 * k + 2, curM, curR));
}
void update(int i, int v) {
i += n - 1;
seg[i] = v;
while (i != 0) {
i = (i - 1) / 2;
seg[i] = Math.max(seg[2 * i + 1], seg[2 * i + 2]);
}
}
}
}
static class MyInput {
private final BufferedReader in;
private static int pos;
private static int readLen;
private static final char[] buffer = new char[1024 * 8];
private static char[] str = new char[500 * 8 * 2];
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
private static boolean[] isLineSep = new boolean[256];
static {
for (int i = 0; i < 10; i++) {
isDigit['0' + i] = true;
}
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
isLineSep['\r'] = isLineSep['\n'] = true;
}
public MyInput(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public int read() {
if (pos >= readLen) {
pos = 0;
try {
readLen = in.read(buffer);
} catch (IOException e) {
throw new RuntimeException();
}
if (readLen <= 0) {
throw new MyInput.EndOfFileRuntimeException();
}
}
return buffer[pos++];
}
public int nextInt() {
int len = 0;
str[len++] = nextChar();
len = reads(len, isSpace);
int i = 0;
int ret = 0;
if (str[0] == '-') {
i = 1;
}
for (; i < len; i++) ret = ret * 10 + str[i] - '0';
if (str[0] == '-') {
ret = -ret;
}
return ret;
}
public char nextChar() {
while (true) {
final int c = read();
if (!isSpace[c]) {
return (char) c;
}
}
}
int reads(int len, boolean[] accept) {
try {
while (true) {
final int c = read();
if (accept[c]) {
break;
}
if (str.length == len) {
char[] rep = new char[str.length * 3 / 2];
System.arraycopy(str, 0, rep, 0, str.length);
str = rep;
}
str[len++] = (char) c;
}
} catch (MyInput.EndOfFileRuntimeException e) {
}
return len;
}
public int[] nextIntArray(final int n) {
final int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
static class EndOfFileRuntimeException extends RuntimeException {
}
}
}
Code 2: <?php
fscanf(STDIN, "%d", $N);
$xSortList = [];
// データを入れていく
for($i = 0; $i < $N; $i++) {
fscanf(STDIN, "%d %d", $X, $D);
$xSortList[] = [
"x" => $X,
"d" => $D,
];
}
// ソート
usort($xSortList, function($a, $b) {
return($a["x"] <=> $b["x"]);
});
// 検索用
function getIdx(&$list, $sIdx, $eIdx, $maxX) {
$idx = 0;
while($sIdx <= $eIdx) {
// 真ん中
$idx = intval(($eIdx + $sIdx) / 2);
if($list[$idx]["x"] == $maxX) {
return($idx);
}
if($list[$idx]["x"] > $maxX) {
$eIdx = $idx - 1;
}
else {
$sIdx = $idx + 1;
}
}
return($sIdx);
}
// ループ(範囲を求める)
for($i = $N - 1; $i >= 0; $i--) {
//==================================================================
// 影響範囲計算
//==================================================================
$xSortList[$i]["r"] = $i;
$maxX = $xSortList[$i]["x"] + $xSortList[$i]["d"];
$idx = max(0, min($N - 1, getIdx($xSortList, 0, $N - 1, $maxX)));
if($xSortList[$idx]["x"] >= $maxX) {
$idx = max(0, $idx - 1);
}
for($n = $i + 1; $n <= $idx; $n++) {
$xSortList[$i]["r"] = max($xSortList[$i]["r"], $xSortList[$n]["r"]);
$n = $xSortList[$i]["r"];
}
//==================================================================
// パターン計算
//==================================================================
$onNextIdx = $xSortList[$i]["r"] + 1;
$offNextIdx = $i + 1;
// ONのときよう
$on = 1;
if($onNextIdx < $N) {
$on = $xSortList[$onNextIdx]["a"];
}
// OFFのとき
$off = 1;
if($offNextIdx < $N) {
$off = $xSortList[$offNextIdx]["a"];
}
$xSortList[$i]["a"] = ($on + $off) % 998244353;
}
echo "{$xSortList[0]["a"]}\n";
|
C++ | #include <bits/stdc++.h>
using namespace std;
int n,m,i,a,b,ans,q;
vector <int> wektor[100003];
int dp[100003];
bool visited[100003];
int licz(int x)
{
if(dp[x]!=0){
return dp[x];
}
for(auto i : wektor[x]){
dp[x]=max(dp[x], licz(i)+1);
}
return dp[x];
}
int main()
{
ios_base::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
for(i=0;i<m;i++)
{
cin >> a >> b;
wektor[b].push_back(a);
}
for(i=1;i<=n;i++)
{
if(!visited[i]){
licz(i);
}
ans = max(ans, dp[i]);
}
cout << ans;
return 0;
}
| Python | N = int(input())
table = [ list(map(int,input().split())) for i in range(N)]
dp = [[0 for i in range(3)] for j in range(N)]
for i in range(3):
dp[0][i] = table[0][i]
for i in range(1,N):
dp[i][0] = max(dp[i-1][1],dp[i-1][2]) + table[i][0]
dp[i][1] = max(dp[i-1][2],dp[i-1][0]) + table[i][1]
dp[i][2] = max(dp[i-1][1],dp[i-1][0]) + table[i][2]
print(max(dp[N-1][0],dp[N-1][1],dp[N-1][2]))
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int n,m,i,a,b,ans,q;
vector <int> wektor[100003];
int dp[100003];
bool visited[100003];
int licz(int x)
{
if(dp[x]!=0){
return dp[x];
}
for(auto i : wektor[x]){
dp[x]=max(dp[x], licz(i)+1);
}
return dp[x];
}
int main()
{
ios_base::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
for(i=0;i<m;i++)
{
cin >> a >> b;
wektor[b].push_back(a);
}
for(i=1;i<=n;i++)
{
if(!visited[i]){
licz(i);
}
ans = max(ans, dp[i]);
}
cout << ans;
return 0;
}
Code 2: N = int(input())
table = [ list(map(int,input().split())) for i in range(N)]
dp = [[0 for i in range(3)] for j in range(N)]
for i in range(3):
dp[0][i] = table[0][i]
for i in range(1,N):
dp[i][0] = max(dp[i-1][1],dp[i-1][2]) + table[i][0]
dp[i][1] = max(dp[i-1][2],dp[i-1][0]) + table[i][1]
dp[i][2] = max(dp[i-1][1],dp[i-1][0]) + table[i][2]
print(max(dp[N-1][0],dp[N-1][1],dp[N-1][2]))
|
Python | def main():
D, T, S= map(int, input().split())
if D <= T * S:
return "Yes"
else:
return "No"
if __name__ == '__main__':
print(main())
| C++ | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
main(){
int x;cin>>x;
int lcm = (x*360)/__gcd(x,360);
cout<<lcm/x;
} | No | Do these codes solve the same problem?
Code 1: def main():
D, T, S= map(int, input().split())
if D <= T * S:
return "Yes"
else:
return "No"
if __name__ == '__main__':
print(main())
Code 2: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
main(){
int x;cin>>x;
int lcm = (x*360)/__gcd(x,360);
cout<<lcm/x;
} |
Python | N = int(input())
L = list(map(int, input().split()))
max = 0
l = 0
for i in range(N):
if L[i]>max:
max=L[i]
l += L[i]
if max<l-max:
print("Yes")
else:
print("No")
| C++ | #include<iostream>
#include<vector>
#include<cmath>
using namespace std;
signed main(){
int N, Z, W, ans = (1<<30);
vector<int> a;
cin>>N>>Z>>W;
a.resize(N);
for(int i = 0; i < N; i++){
cin>>a[i];
}
ans = abs(a.back() - W);
if(a.size() >= 2) ans = max(ans, (int)abs(a.back() - a[a.size()-2]));
cout<<ans<<endl;
return 0;
} | No | Do these codes solve the same problem?
Code 1: N = int(input())
L = list(map(int, input().split()))
max = 0
l = 0
for i in range(N):
if L[i]>max:
max=L[i]
l += L[i]
if max<l-max:
print("Yes")
else:
print("No")
Code 2: #include<iostream>
#include<vector>
#include<cmath>
using namespace std;
signed main(){
int N, Z, W, ans = (1<<30);
vector<int> a;
cin>>N>>Z>>W;
a.resize(N);
for(int i = 0; i < N; i++){
cin>>a[i];
}
ans = abs(a.back() - W);
if(a.size() >= 2) ans = max(ans, (int)abs(a.back() - a[a.size()-2]));
cout<<ans<<endl;
return 0;
} |
C++ | #include <iostream>
#include <set>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
using namespace std;
typedef pair<int,int>P;
#define X first
#define Y second
int mp[5010][5010];
set<int>xs;
set<int>ys;
int xl[5010];
int yl[5010];
int x_find(int n){
int le=0,ri=5009;
while(le!=ri){
int p=(le+ri)/2;
if(xl[p]==n)return p;
if(xl[p]<n)le=p+1;
else ri=p-1;
}
return le;
}
int y_find(int n){
int le=0,ri=5009;
while(le!=ri){
int p=(le+ri)/2;
if(yl[p]==n)return p;
if(yl[p]<n)le=p+1;
else ri=p-1;
}
return le;
}
int x_find2(int n){
int le=0,ri=5005,p=2502;
while(le<ri){
if(xl[p]==n)return p;
if(xl[p]<n)le=p+1;
else ri=p-1;
p=(le+ri)/2;
}
if(xl[p]==n)return p;
while(xl[p]>n)p--;
while(xl[p+1]<n)p++;
return p;
}
int y_find2(int n){
int le=0,ri=5005,p=2502;
while(le<ri){
if(yl[p]==n)return p;
if(yl[p]<n)le=p+1;
else ri=p-1;
p=(le+ri)/2;
}
if(yl[p]==n)return p;
while(yl[p]>n)p--;
while(yl[p+1]<n)p++;
return p;
}
int x_find3(int n){
int le=0,ri=5005,p=2502;
while(le<ri){
if(xl[p]==n)return p;
if(xl[p]<n)le=p+1;
else ri=p-1;
p=(le+ri)/2;
}
if(xl[p]==n)return p;
while(xl[p]<n)p++;
while(xl[p-1]>n)p--;
return p;
}
int y_find3(int n){
int le=0,ri=5005,p=2502;
while(le<ri){
if(yl[p]==n)return p;
if(yl[p]<n)le=p+1;
else ri=p-1;
p=(le+ri)/2;
}
if(yl[p]==n)return p;
while(yl[p]<n)p++;
while(yl[p-1]>n)p--;
return p;
}
int main(){
int n,m;
cin>>n>>m;
vector<P>V;
xs.insert(-1100000000);
ys.insert(-1100000000);
xs.insert(-1100000001);
ys.insert(-1100000001);
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
V.push_back(P(x,y));
xs.insert(x);
ys.insert(y);
}
for(int i=1100000000;xs.size()<5010;i++){
xs.insert(i);
}
for(int i=1100000000;ys.size()<5010;i++){
ys.insert(i);
}
set<int>::iterator it = xs.begin();
for( int i=0;it != xs.end(); i++){
xl[i]=*it;
++it;
}
set<int>::iterator it2 = ys.begin();
for( int i=0;it2 != ys.end(); i++){
yl[i]=*it2;
++it2;
}
for(int i=0;i<n;i++){
mp[x_find(V[i].X)][y_find(V[i].Y)]++;
}
for(int j=0;j<5010;j++){
for(int i=1;i<5010;i++){
mp[i][j]+=mp[i-1][j];
}
}
for(int j=0;j<5010;j++){
for(int i=1;i<5010;i++){
mp[i][j]+=mp[i][j-1];
}
}
for(int i=0;i<m;i++){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
x1=x_find3(x1);
y1=y_find3(y1);
x2=x_find2(x2);
y2=y_find2(y2);
cout<<mp[x2][y2]-mp[x2][y1-1]-mp[x1-1][y2]+mp[x1-1][y1-1]<<endl;
//cout<<mp[x2][y2]<<" "<<mp[x2][y1]<<" "<<mp[x1][y2]<<" "<<mp[x1][y1]<<endl;
//cout<<mp[x2][y2]-mp[x2][y1]-mp[x1][y2]+mp[x1][y1]<<endl;
}
return 0;
}
| Java | import java.io.IOException;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
public class Main{
static Scanner scn = new Scanner(System.in);
static FastScanner sc = new FastScanner();
static PrintWriter ot = new PrintWriter(System.out);
static Random rand = new Random();
static int mod = 1000000007;
static long modmod = (long)mod * mod;
static long inf = (long)1e17;
static int[] dx = {0,1,0,-1};
static int[] dy = {1,0,-1,0};
static int[] dx8 = {-1,-1,-1,0,0,1,1,1};
static int[] dy8 = {-1,0,1,-1,1,-1,0,1};
static char[] dc = {'R','D','L','U'};
static BiFunction<Integer,Integer,Integer> fmax = (a,b)-> {return Math.max(a,b);};
static BiFunction<Integer,Integer,Integer> fmin = (a,b)-> {return Math.min(a,b);};
static BiFunction<Integer,Integer,Integer> fsum = (a,b)-> {return a+b;};
static BiFunction<Long,Long,Long> fmaxl = (a,b)-> {return Math.max(a,b);};
static BiFunction<Long,Long,Long> fminl = (a,b)-> {return Math.min(a,b);};
static BiFunction<Long,Long,Long> fsuml = (a,b)-> {return a+b;};
static BiFunction<Integer,Integer,Integer> fadd = fsum;
static BiFunction<Integer,Integer,Integer> fupd = (a,b)-> {return b;};
static BiFunction<Long,Long,Long> faddl = fsuml;
static BiFunction<Long,Long,Long> fupdl = (a,b)-> {return b;};
static String sp = " ";
static int N;
static int M;
public static void main(String[] args) {
//AOJ2426 Treasure Hunt
//author:Suunn
//幾何らしくないと思う 座標圧縮と累積和で丁寧に実装
int N = sc.nextInt();
int M = sc.nextInt();
int[] x = new int[N];
int[] y = new int[N];
sc.nextIntses(N,x,y);
TreeSet<Integer> xlist = new TreeSet<Integer>();
TreeSet<Integer> ylist = new TreeSet<Integer>();
for(int i=0;i<N;i++) {
xlist.add(x[i]);
ylist.add(y[i]);
}
xlist.add(-mod);
xlist.add(mod);
ylist.add(-mod);
ylist.add(mod);
TreeMap<Integer,Integer> xmap = new TreeMap<Integer,Integer>();
TreeMap<Integer,Integer> ymap = new TreeMap<Integer,Integer>();
int xidx = 1;
for(int e:xlist) {
xmap.put(e,xidx);
xidx += 2;
}
int yidx = 1;
for(int e:ylist) {
ymap.put(e,yidx);
yidx += 2;
}
int[][] a = new int[xidx+1][yidx+1];
for(int i=0;i<N;i++) {
int X = xmap.get(x[i]);
int Y = ymap.get(y[i]);
a[X][Y]++;
}
for(int i=0;i<=xidx;i++) {
for(int j=0;j<=yidx;j++) {
if(i==0&&j==0)continue;
else if(i==0)a[i][j] += a[i][j-1];
else if(j==0)a[i][j] += a[i-1][j];
else a[i][j] += a[i][j-1]+a[i-1][j]-a[i-1][j-1];
}
}
for(int i=0;i<M;i++) {
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
int X1 = xmap.get(xlist.ceiling(x1))-1;
int Y1 = ymap.get(ylist.ceiling(y1))-1;
int X2 = xmap.get(xlist.floor(x2));
int Y2 = ymap.get(ylist.floor(y2));
ot.println(a[X2][Y2]-a[X1][Y2]-a[X2][Y1]+a[X1][Y1]);
}
ot.flush();
}
}
class FastScanner {
private final java.io.InputStream in = System.in;
private final byte[] b = new byte[1024];
private int p = 0;
private int bl = 0;
private boolean hNB() {
if (p<bl) {
return true;
}else{
p = 0;
try {
bl = in.read(b);
} catch (IOException e) {
e.printStackTrace();
}
if (bl<=0) {
return false;
}
}
return true;
}
private int rB() { if (hNB()) return b[p++]; else return -1;}
private static boolean iPC(int c) { return 33 <= c && c <= 126;}
private void sU() { while(hNB() && !iPC(b[p])) p++;}
public boolean hN() { sU(); return hNB();}
public String next() {
if (!hN()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = rB();
while(iPC(b)) {
sb.appendCodePoint(b);
b = rB();
}
return sb.toString();
}
public char nextChar() {
return next().charAt(0);
}
public long nextLong() {
if (!hN()) throw new NoSuchElementException();
long n = 0;
boolean m = false;
int b = rB();
if (b=='-') {
m=true;
b=rB();
}
if (b<'0'||'9'<b) {
throw new NumberFormatException();
}
while(true){
if ('0'<=b&&b<='9') {
n *= 10;
n += b - '0';
}else if(b == -1||!iPC(b)){
return (m?-n:n);
}else{
throw new NumberFormatException();
}
b = rB();
}
}
public int nextInt() {
if (!hN()) throw new NoSuchElementException();
long n = 0;
boolean m = false;
int b = rB();
if (b == '-') {
m = true;
b = rB();
}
if (b<'0'||'9'<b) {
throw new NumberFormatException();
}
while(true){
if ('0'<=b&&b<='9') {
n *= 10;
n += b-'0';
}else if(b==-1||!iPC(b)){
return (int) (m?-n:n);
}else{
throw new NumberFormatException();
}
b = rB();
}
}
public int[] nextInts(int n) {
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = nextInt();
}
return a;
}
public int[] nextInts(int n,int s) {
int[] a = new int[n+s];
for(int i=s;i<n+s;i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongs(int n, int s) {
long[] a = new long[n+s];
for(int i=s;i<n+s;i++) {
a[i] = nextLong();
}
return a;
}
public long[] nextLongs(int n) {
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = nextLong();
}
return a;
}
public int[][] nextIntses(int n,int m){
int[][] a = new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j] = nextInt();
}
}
return a;
}
public String[] nexts(int n) {
String[] a = new String[n];
for(int i=0;i<n;i++) {
a[i] = next();
}
return a;
}
void nextIntses(int n,int[] ...m) {
int l = m[0].length;
for(int i=0;i<l;i++) {
for(int j=0;j<m.length;j++) {
m[j][i] = nextInt();
}
}
}
void nextLongses(int n,long[] ...m) {
int l = m[0].length;
for(int i=0;i<l;i++) {
for(int j=0;j<m.length;j++) {
m[j][i] = nextLong();
}
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <set>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
using namespace std;
typedef pair<int,int>P;
#define X first
#define Y second
int mp[5010][5010];
set<int>xs;
set<int>ys;
int xl[5010];
int yl[5010];
int x_find(int n){
int le=0,ri=5009;
while(le!=ri){
int p=(le+ri)/2;
if(xl[p]==n)return p;
if(xl[p]<n)le=p+1;
else ri=p-1;
}
return le;
}
int y_find(int n){
int le=0,ri=5009;
while(le!=ri){
int p=(le+ri)/2;
if(yl[p]==n)return p;
if(yl[p]<n)le=p+1;
else ri=p-1;
}
return le;
}
int x_find2(int n){
int le=0,ri=5005,p=2502;
while(le<ri){
if(xl[p]==n)return p;
if(xl[p]<n)le=p+1;
else ri=p-1;
p=(le+ri)/2;
}
if(xl[p]==n)return p;
while(xl[p]>n)p--;
while(xl[p+1]<n)p++;
return p;
}
int y_find2(int n){
int le=0,ri=5005,p=2502;
while(le<ri){
if(yl[p]==n)return p;
if(yl[p]<n)le=p+1;
else ri=p-1;
p=(le+ri)/2;
}
if(yl[p]==n)return p;
while(yl[p]>n)p--;
while(yl[p+1]<n)p++;
return p;
}
int x_find3(int n){
int le=0,ri=5005,p=2502;
while(le<ri){
if(xl[p]==n)return p;
if(xl[p]<n)le=p+1;
else ri=p-1;
p=(le+ri)/2;
}
if(xl[p]==n)return p;
while(xl[p]<n)p++;
while(xl[p-1]>n)p--;
return p;
}
int y_find3(int n){
int le=0,ri=5005,p=2502;
while(le<ri){
if(yl[p]==n)return p;
if(yl[p]<n)le=p+1;
else ri=p-1;
p=(le+ri)/2;
}
if(yl[p]==n)return p;
while(yl[p]<n)p++;
while(yl[p-1]>n)p--;
return p;
}
int main(){
int n,m;
cin>>n>>m;
vector<P>V;
xs.insert(-1100000000);
ys.insert(-1100000000);
xs.insert(-1100000001);
ys.insert(-1100000001);
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
V.push_back(P(x,y));
xs.insert(x);
ys.insert(y);
}
for(int i=1100000000;xs.size()<5010;i++){
xs.insert(i);
}
for(int i=1100000000;ys.size()<5010;i++){
ys.insert(i);
}
set<int>::iterator it = xs.begin();
for( int i=0;it != xs.end(); i++){
xl[i]=*it;
++it;
}
set<int>::iterator it2 = ys.begin();
for( int i=0;it2 != ys.end(); i++){
yl[i]=*it2;
++it2;
}
for(int i=0;i<n;i++){
mp[x_find(V[i].X)][y_find(V[i].Y)]++;
}
for(int j=0;j<5010;j++){
for(int i=1;i<5010;i++){
mp[i][j]+=mp[i-1][j];
}
}
for(int j=0;j<5010;j++){
for(int i=1;i<5010;i++){
mp[i][j]+=mp[i][j-1];
}
}
for(int i=0;i<m;i++){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
x1=x_find3(x1);
y1=y_find3(y1);
x2=x_find2(x2);
y2=y_find2(y2);
cout<<mp[x2][y2]-mp[x2][y1-1]-mp[x1-1][y2]+mp[x1-1][y1-1]<<endl;
//cout<<mp[x2][y2]<<" "<<mp[x2][y1]<<" "<<mp[x1][y2]<<" "<<mp[x1][y1]<<endl;
//cout<<mp[x2][y2]-mp[x2][y1]-mp[x1][y2]+mp[x1][y1]<<endl;
}
return 0;
}
Code 2: import java.io.IOException;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
public class Main{
static Scanner scn = new Scanner(System.in);
static FastScanner sc = new FastScanner();
static PrintWriter ot = new PrintWriter(System.out);
static Random rand = new Random();
static int mod = 1000000007;
static long modmod = (long)mod * mod;
static long inf = (long)1e17;
static int[] dx = {0,1,0,-1};
static int[] dy = {1,0,-1,0};
static int[] dx8 = {-1,-1,-1,0,0,1,1,1};
static int[] dy8 = {-1,0,1,-1,1,-1,0,1};
static char[] dc = {'R','D','L','U'};
static BiFunction<Integer,Integer,Integer> fmax = (a,b)-> {return Math.max(a,b);};
static BiFunction<Integer,Integer,Integer> fmin = (a,b)-> {return Math.min(a,b);};
static BiFunction<Integer,Integer,Integer> fsum = (a,b)-> {return a+b;};
static BiFunction<Long,Long,Long> fmaxl = (a,b)-> {return Math.max(a,b);};
static BiFunction<Long,Long,Long> fminl = (a,b)-> {return Math.min(a,b);};
static BiFunction<Long,Long,Long> fsuml = (a,b)-> {return a+b;};
static BiFunction<Integer,Integer,Integer> fadd = fsum;
static BiFunction<Integer,Integer,Integer> fupd = (a,b)-> {return b;};
static BiFunction<Long,Long,Long> faddl = fsuml;
static BiFunction<Long,Long,Long> fupdl = (a,b)-> {return b;};
static String sp = " ";
static int N;
static int M;
public static void main(String[] args) {
//AOJ2426 Treasure Hunt
//author:Suunn
//幾何らしくないと思う 座標圧縮と累積和で丁寧に実装
int N = sc.nextInt();
int M = sc.nextInt();
int[] x = new int[N];
int[] y = new int[N];
sc.nextIntses(N,x,y);
TreeSet<Integer> xlist = new TreeSet<Integer>();
TreeSet<Integer> ylist = new TreeSet<Integer>();
for(int i=0;i<N;i++) {
xlist.add(x[i]);
ylist.add(y[i]);
}
xlist.add(-mod);
xlist.add(mod);
ylist.add(-mod);
ylist.add(mod);
TreeMap<Integer,Integer> xmap = new TreeMap<Integer,Integer>();
TreeMap<Integer,Integer> ymap = new TreeMap<Integer,Integer>();
int xidx = 1;
for(int e:xlist) {
xmap.put(e,xidx);
xidx += 2;
}
int yidx = 1;
for(int e:ylist) {
ymap.put(e,yidx);
yidx += 2;
}
int[][] a = new int[xidx+1][yidx+1];
for(int i=0;i<N;i++) {
int X = xmap.get(x[i]);
int Y = ymap.get(y[i]);
a[X][Y]++;
}
for(int i=0;i<=xidx;i++) {
for(int j=0;j<=yidx;j++) {
if(i==0&&j==0)continue;
else if(i==0)a[i][j] += a[i][j-1];
else if(j==0)a[i][j] += a[i-1][j];
else a[i][j] += a[i][j-1]+a[i-1][j]-a[i-1][j-1];
}
}
for(int i=0;i<M;i++) {
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
int X1 = xmap.get(xlist.ceiling(x1))-1;
int Y1 = ymap.get(ylist.ceiling(y1))-1;
int X2 = xmap.get(xlist.floor(x2));
int Y2 = ymap.get(ylist.floor(y2));
ot.println(a[X2][Y2]-a[X1][Y2]-a[X2][Y1]+a[X1][Y1]);
}
ot.flush();
}
}
class FastScanner {
private final java.io.InputStream in = System.in;
private final byte[] b = new byte[1024];
private int p = 0;
private int bl = 0;
private boolean hNB() {
if (p<bl) {
return true;
}else{
p = 0;
try {
bl = in.read(b);
} catch (IOException e) {
e.printStackTrace();
}
if (bl<=0) {
return false;
}
}
return true;
}
private int rB() { if (hNB()) return b[p++]; else return -1;}
private static boolean iPC(int c) { return 33 <= c && c <= 126;}
private void sU() { while(hNB() && !iPC(b[p])) p++;}
public boolean hN() { sU(); return hNB();}
public String next() {
if (!hN()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = rB();
while(iPC(b)) {
sb.appendCodePoint(b);
b = rB();
}
return sb.toString();
}
public char nextChar() {
return next().charAt(0);
}
public long nextLong() {
if (!hN()) throw new NoSuchElementException();
long n = 0;
boolean m = false;
int b = rB();
if (b=='-') {
m=true;
b=rB();
}
if (b<'0'||'9'<b) {
throw new NumberFormatException();
}
while(true){
if ('0'<=b&&b<='9') {
n *= 10;
n += b - '0';
}else if(b == -1||!iPC(b)){
return (m?-n:n);
}else{
throw new NumberFormatException();
}
b = rB();
}
}
public int nextInt() {
if (!hN()) throw new NoSuchElementException();
long n = 0;
boolean m = false;
int b = rB();
if (b == '-') {
m = true;
b = rB();
}
if (b<'0'||'9'<b) {
throw new NumberFormatException();
}
while(true){
if ('0'<=b&&b<='9') {
n *= 10;
n += b-'0';
}else if(b==-1||!iPC(b)){
return (int) (m?-n:n);
}else{
throw new NumberFormatException();
}
b = rB();
}
}
public int[] nextInts(int n) {
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = nextInt();
}
return a;
}
public int[] nextInts(int n,int s) {
int[] a = new int[n+s];
for(int i=s;i<n+s;i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongs(int n, int s) {
long[] a = new long[n+s];
for(int i=s;i<n+s;i++) {
a[i] = nextLong();
}
return a;
}
public long[] nextLongs(int n) {
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = nextLong();
}
return a;
}
public int[][] nextIntses(int n,int m){
int[][] a = new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j] = nextInt();
}
}
return a;
}
public String[] nexts(int n) {
String[] a = new String[n];
for(int i=0;i<n;i++) {
a[i] = next();
}
return a;
}
void nextIntses(int n,int[] ...m) {
int l = m[0].length;
for(int i=0;i<l;i++) {
for(int j=0;j<m.length;j++) {
m[j][i] = nextInt();
}
}
}
void nextLongses(int n,long[] ...m) {
int l = m[0].length;
for(int i=0;i<l;i++) {
for(int j=0;j<m.length;j++) {
m[j][i] = nextLong();
}
}
}
}
|
Python | N = int(input())
def divisor(n):
cd = []
i = 1
while i*i <= n:
if n%i==0:
cd.append(i)
if i != n//i:
cd.append(n//i)
i+=1
return cd
cd = divisor(N)
ans = len(str(cd[-1]))
print(ans)
| C++ | #include<stdio.h>
int main()
{
int n,x,max=-1,i,s=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
if(x>max)
max=x;
s+=x;
}
printf("%d",s-max/2);
} | No | Do these codes solve the same problem?
Code 1: N = int(input())
def divisor(n):
cd = []
i = 1
while i*i <= n:
if n%i==0:
cd.append(i)
if i != n//i:
cd.append(n//i)
i+=1
return cd
cd = divisor(N)
ans = len(str(cd[-1]))
print(ans)
Code 2: #include<stdio.h>
int main()
{
int n,x,max=-1,i,s=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
if(x>max)
max=x;
s+=x;
}
printf("%d",s-max/2);
} |
C++ | #include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
constexpr ll INF = 1e18;
int main(void) {
int N;
cin >> N;
vector<int> P(N), Q(N);
for (int i = 0; i < N; ++i) {
cin >> P[i];
}
for (int i = 0; i < N; ++i) {
cin >> Q[i];
}
vector<int> v(N);
iota(v.begin(), v.end(), 1);
int a, b;
int i = 0;
do {
if (v == P) a = i;
if (v == Q) b = i;
i++;
} while(next_permutation(v.begin(), v.end()));
cout << abs(a-b) << endl;
return 0;
}
| Python | import sys, math
def input():
return sys.stdin.readline()[:-1]
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial
from fractions import gcd
e = enumerate
sys.setrecursionlimit(10**7)
H, N = map(int, input().split())
A = list(map(int, input().split()))
if H<=sum(A):
print('Yes')
else:
print('No')
| No | Do these codes solve the same problem?
Code 1: #include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
constexpr ll INF = 1e18;
int main(void) {
int N;
cin >> N;
vector<int> P(N), Q(N);
for (int i = 0; i < N; ++i) {
cin >> P[i];
}
for (int i = 0; i < N; ++i) {
cin >> Q[i];
}
vector<int> v(N);
iota(v.begin(), v.end(), 1);
int a, b;
int i = 0;
do {
if (v == P) a = i;
if (v == Q) b = i;
i++;
} while(next_permutation(v.begin(), v.end()));
cout << abs(a-b) << endl;
return 0;
}
Code 2: import sys, math
def input():
return sys.stdin.readline()[:-1]
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial
from fractions import gcd
e = enumerate
sys.setrecursionlimit(10**7)
H, N = map(int, input().split())
A = list(map(int, input().split()))
if H<=sum(A):
print('Yes')
else:
print('No')
|
Python | a, b = map(int, input().split())
print(-(-(a+b) // 2)) | C++ | #include<bits/stdc++.h>
using namespace std;
#define ar array
#define ll long long int
const ll mod = 1e9 + 7;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t = 1;
// cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) cin >> x;
ll st = 0;
int maxm = a[0];
for (int i = 1; i < n; ++i) {
if (a[i] < maxm) {
st += 1LL * (maxm - a[i]);
}
maxm = max(maxm, a[i]);
}
cout << st;
}
return 0;
} | No | Do these codes solve the same problem?
Code 1: a, b = map(int, input().split())
print(-(-(a+b) // 2))
Code 2: #include<bits/stdc++.h>
using namespace std;
#define ar array
#define ll long long int
const ll mod = 1e9 + 7;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t = 1;
// cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) cin >> x;
ll st = 0;
int maxm = a[0];
for (int i = 1; i < n; ++i) {
if (a[i] < maxm) {
st += 1LL * (maxm - a[i]);
}
maxm = max(maxm, a[i]);
}
cout << st;
}
return 0;
} |
C++ | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <algorithm>
#include <utility>
#include <functional>
#include <cstring>
#include <queue>
#include <stack>
#include <math.h>
#include <iterator>
#include <vector>
#include <string>
#include <set>
#include <math.h>
#include <iostream>
#include <random>
#include<map>
#include <iomanip>
#include <time.h>
#include <stdlib.h>
#include <list>
#include <typeinfo>
#include <list>
#include <set>
#include <cassert>
#include<fstream>
#include <unordered_map>
#include <cstdlib>
using namespace std;
#define Ma_PI 3.141592653589793
#define eps 0.00000001
#define LONG_INF 3000000000000000000
#define GOLD 1.61803398874989484820458
#define MAX_MOD 1000000007
#define REP(i,n) for(long long i = 0;i < n;++i)
#define seg_size 524288
int main() {
string s;
cin >> s;
if (s[1] == s[2] && (s[0] == s[1] || s[2] == s[3])) {
cout << "Yes" << endl;
}
else cout << "No" << endl;
} | C | #include <stdio.h>
#include <stdlib.h>
int main()
{
int i, I, x = 0, y, z, a;
long long t[10000] = {0};
char n[10000] = {"s"};
for(I = 0 ; I < 10000 ; I++)
{
n[I] = 's';
}
while(scanf("%s", n))
{
if(n[0] == '0')
{
break;
}
for(i = 0 ; ; i++)
{
if(n[i] == 's')
{
for(I = 0 ; I < 10000 ; I++)
{
n[I] = 's';
}
break;
}
y = n[i];
t[x] += y;
t[x] -= 48;
}
x++;
}
for(i = 0 ; i < x ; i++)
{
printf("%lld\n", t[i]+48);
}
return 0;
}
| No | Do these codes solve the same problem?
Code 1: #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <algorithm>
#include <utility>
#include <functional>
#include <cstring>
#include <queue>
#include <stack>
#include <math.h>
#include <iterator>
#include <vector>
#include <string>
#include <set>
#include <math.h>
#include <iostream>
#include <random>
#include<map>
#include <iomanip>
#include <time.h>
#include <stdlib.h>
#include <list>
#include <typeinfo>
#include <list>
#include <set>
#include <cassert>
#include<fstream>
#include <unordered_map>
#include <cstdlib>
using namespace std;
#define Ma_PI 3.141592653589793
#define eps 0.00000001
#define LONG_INF 3000000000000000000
#define GOLD 1.61803398874989484820458
#define MAX_MOD 1000000007
#define REP(i,n) for(long long i = 0;i < n;++i)
#define seg_size 524288
int main() {
string s;
cin >> s;
if (s[1] == s[2] && (s[0] == s[1] || s[2] == s[3])) {
cout << "Yes" << endl;
}
else cout << "No" << endl;
}
Code 2: #include <stdio.h>
#include <stdlib.h>
int main()
{
int i, I, x = 0, y, z, a;
long long t[10000] = {0};
char n[10000] = {"s"};
for(I = 0 ; I < 10000 ; I++)
{
n[I] = 's';
}
while(scanf("%s", n))
{
if(n[0] == '0')
{
break;
}
for(i = 0 ; ; i++)
{
if(n[i] == 's')
{
for(I = 0 ; I < 10000 ; I++)
{
n[I] = 's';
}
break;
}
y = n[i];
t[x] += y;
t[x] -= 48;
}
x++;
}
for(i = 0 ; i < x ; i++)
{
printf("%lld\n", t[i]+48);
}
return 0;
}
|
C++ | // hloya template v24
// ░░░░░░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░░░░░
// ░░░░░░█░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░█░░░░░
// ░░░░░░█░█░▀░░░░░▀░░▀░░░░█░█░░░░░
// ░░░░░░█░█░░░░░░░░▄▀▀▄░▀░█░█▄▀▀▄░
// █▀▀█▄░█░█░░▀░░░░░█░░░▀▄▄█▄▀░░░█░
// ▀▄▄░▀██░█▄░▀░░░▄▄▀░░░░░░░░░░░░▀▄
// ░░▀█▄▄█░█░░░░▄░░█░░░▄█░░░▄░▄█░░█
// ░░░░░▀█░▀▄▀░░░░░█░██░▄░░▄░░▄░███
// ░░░░░▄█▄░░▀▀▀▀▀▀▀▀▄░░▀▀▀▀▀▀▀░▄▀░
// ░░░░█░░▄█▀█▀▀█▀▀▀▀▀▀█▀▀█▀█▀▀█░░░
// ░░░░▀▀▀▀░░▀▀▀░░░░░░░░▀▀▀░░▀▀░░░░
#include <bits/stdc++.h>
#include <valarray>
using namespace std;
bool dbg = 0;
clock_t start_time = clock();
#define current_time fixed<<setprecision(6)<<(ld)(clock()-start_time)/CLOCKS_PER_SEC
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define ll long long
#define ld long double
#define pii pair<int,int>
#define umap unordered_map<int, int>
#define files1 freopen("input.txt","r",stdin)
#define files2 freopen("paths.out","w",stdout)
#define files files1;files2
#define fast_io ios_base::sync_with_stdio(0);cin.tie(0)
#define endl '\n'
#define ln(i,n) " \n"[(i) == (n) - 1]
void bad(string mes = "Impossible"){cout << mes;exit(0);}
void bad(int mes){cout << mes;exit(0);}
template<typename T>
string bin(T x, int st = 2){
string ans = "";
while (x > 0){
ans += char('0' + x % st);
x /= st;
}
reverse(ans.begin(), ans.end());
return ans.empty() ? "0" : ans;
}
template<typename T>
void amax(T& x, T y) {
x = max(x, y);
}
template<typename T>
void amin(T& x, T y) {
x = min(x, y);
}
template<typename T>
T input(){
T ans = 0, m = 1;
char c = ' ';
while (!((c >= '0' && c <= '9') || c == '-')) {
c = getchar();
}
if (c == '-')
m = -1, c = getchar();
while (c >= '0' && c <= '9'){
ans = ans * 10 + (c - '0'), c = getchar();
}
return ans * m;
}
template<typename T> void read(T& a) { a = input<T>(); }
template<typename T> void read(T& a, T& b) { read(a), read(b); }
template<typename T> void read(T& a, T& b, T& c) { read(a, b), read(c); }
template<typename T> void read(T& a, T& b, T& c, T& d) { read(a, b), read(c, d); }
const int inf = 2e9 + 20;
const short short_inf = 3e4 + 20;
const long double eps = 1e-12;
const int maxn = 1e5 + 12, base = 1e9 + 7;
const ll llinf = 2e18 + 5;
template<typename T>
T binpow(T n, T s)
{
if (s <= 0)
return 1LL;
if (s % 2 == 0){
T b = binpow(n, s / 2);
return ( 1LL * b * b ) % base;
} else {
return (1LL* binpow(n, s - 1) * n) % base;
}
}
ll n, m;
bool can(ll x) {
if (m < 2ll * x) return 0;
ll ms = m - 2ll * x;
ll ns = n + ms / 2;
if (ns >= x)
return 1;
return 0;
}
int main() {
// files1;
cin >> n >> m;
ll l = 0, r = (ll)1e13;
while (r - l > 1) {
ll c = (l + r) >> 1;
if (can(c))
l = c;
else
r = c;
}
if (can(r))
cout << r;
else
cout << l;
return 0;
} | Python | from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, acos, asin, atan, sqrt, tan, cos, pi
from operator import mul
from functools import reduce
from pprint import pprint
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 998244353
s = S()
D = defaultdict(int)
for i in s:
D[i]+=1
ans = len(s) * (len(s) - 1) // 2
for j in D.values():
ans -= j * (j - 1) // 2
print(ans + 1)
| No | Do these codes solve the same problem?
Code 1: // hloya template v24
// ░░░░░░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░░░░░
// ░░░░░░█░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░█░░░░░
// ░░░░░░█░█░▀░░░░░▀░░▀░░░░█░█░░░░░
// ░░░░░░█░█░░░░░░░░▄▀▀▄░▀░█░█▄▀▀▄░
// █▀▀█▄░█░█░░▀░░░░░█░░░▀▄▄█▄▀░░░█░
// ▀▄▄░▀██░█▄░▀░░░▄▄▀░░░░░░░░░░░░▀▄
// ░░▀█▄▄█░█░░░░▄░░█░░░▄█░░░▄░▄█░░█
// ░░░░░▀█░▀▄▀░░░░░█░██░▄░░▄░░▄░███
// ░░░░░▄█▄░░▀▀▀▀▀▀▀▀▄░░▀▀▀▀▀▀▀░▄▀░
// ░░░░█░░▄█▀█▀▀█▀▀▀▀▀▀█▀▀█▀█▀▀█░░░
// ░░░░▀▀▀▀░░▀▀▀░░░░░░░░▀▀▀░░▀▀░░░░
#include <bits/stdc++.h>
#include <valarray>
using namespace std;
bool dbg = 0;
clock_t start_time = clock();
#define current_time fixed<<setprecision(6)<<(ld)(clock()-start_time)/CLOCKS_PER_SEC
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define ll long long
#define ld long double
#define pii pair<int,int>
#define umap unordered_map<int, int>
#define files1 freopen("input.txt","r",stdin)
#define files2 freopen("paths.out","w",stdout)
#define files files1;files2
#define fast_io ios_base::sync_with_stdio(0);cin.tie(0)
#define endl '\n'
#define ln(i,n) " \n"[(i) == (n) - 1]
void bad(string mes = "Impossible"){cout << mes;exit(0);}
void bad(int mes){cout << mes;exit(0);}
template<typename T>
string bin(T x, int st = 2){
string ans = "";
while (x > 0){
ans += char('0' + x % st);
x /= st;
}
reverse(ans.begin(), ans.end());
return ans.empty() ? "0" : ans;
}
template<typename T>
void amax(T& x, T y) {
x = max(x, y);
}
template<typename T>
void amin(T& x, T y) {
x = min(x, y);
}
template<typename T>
T input(){
T ans = 0, m = 1;
char c = ' ';
while (!((c >= '0' && c <= '9') || c == '-')) {
c = getchar();
}
if (c == '-')
m = -1, c = getchar();
while (c >= '0' && c <= '9'){
ans = ans * 10 + (c - '0'), c = getchar();
}
return ans * m;
}
template<typename T> void read(T& a) { a = input<T>(); }
template<typename T> void read(T& a, T& b) { read(a), read(b); }
template<typename T> void read(T& a, T& b, T& c) { read(a, b), read(c); }
template<typename T> void read(T& a, T& b, T& c, T& d) { read(a, b), read(c, d); }
const int inf = 2e9 + 20;
const short short_inf = 3e4 + 20;
const long double eps = 1e-12;
const int maxn = 1e5 + 12, base = 1e9 + 7;
const ll llinf = 2e18 + 5;
template<typename T>
T binpow(T n, T s)
{
if (s <= 0)
return 1LL;
if (s % 2 == 0){
T b = binpow(n, s / 2);
return ( 1LL * b * b ) % base;
} else {
return (1LL* binpow(n, s - 1) * n) % base;
}
}
ll n, m;
bool can(ll x) {
if (m < 2ll * x) return 0;
ll ms = m - 2ll * x;
ll ns = n + ms / 2;
if (ns >= x)
return 1;
return 0;
}
int main() {
// files1;
cin >> n >> m;
ll l = 0, r = (ll)1e13;
while (r - l > 1) {
ll c = (l + r) >> 1;
if (can(c))
l = c;
else
r = c;
}
if (can(r))
cout << r;
else
cout << l;
return 0;
}
Code 2: from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, acos, asin, atan, sqrt, tan, cos, pi
from operator import mul
from functools import reduce
from pprint import pprint
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 998244353
s = S()
D = defaultdict(int)
for i in s:
D[i]+=1
ans = len(s) * (len(s) - 1) // 2
for j in D.values():
ans -= j * (j - 1) // 2
print(ans + 1)
|
C++ | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF 1e18+5
vector<int> w(1009);
vector<int> s(1009);
vector<int> v(1009);
vector< int > dp(20009);
bool comp(int a, int b){
return s[a] + w[a] > s[b] + w[b];
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> elements(n);
for(int i = 0; i < n; i++){
elements[i] = i;
cin >> w[i] >> s[i] >> v[i];
}
sort(elements.begin(), elements.end(), comp);
for(int j = 0; j < n; j++){
int i = elements[j];
for(int k = w[i]; k < 20009; k++){
dp[min(k-w[i],s[i])] = max(dp[min(k-w[i], s[i])], dp[k]+v[i]);
}
}
int ans = 0;
for(int i = 0; i < 10009; i++){
ans = max(ans, dp[i]);
}
cout << ans << endl;
}
| Python | N = int(input())
if N%1000 == 0:
print(0)
else:
print(1000-N%1000)
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF 1e18+5
vector<int> w(1009);
vector<int> s(1009);
vector<int> v(1009);
vector< int > dp(20009);
bool comp(int a, int b){
return s[a] + w[a] > s[b] + w[b];
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> elements(n);
for(int i = 0; i < n; i++){
elements[i] = i;
cin >> w[i] >> s[i] >> v[i];
}
sort(elements.begin(), elements.end(), comp);
for(int j = 0; j < n; j++){
int i = elements[j];
for(int k = w[i]; k < 20009; k++){
dp[min(k-w[i],s[i])] = max(dp[min(k-w[i], s[i])], dp[k]+v[i]);
}
}
int ans = 0;
for(int i = 0; i < 10009; i++){
ans = max(ans, dp[i]);
}
cout << ans << endl;
}
Code 2: N = int(input())
if N%1000 == 0:
print(0)
else:
print(1000-N%1000)
|
C++ | #include <bits/stdc++.h>
using namespace std;
char a[200010];
int ans, sst;
int main(){
scanf("%s", a);
int le = strlen(a);
for(int i = 0; i < le; ++i){
if(*(a + i) == 'S'){
sst++;
}else{
if(sst != 0){
sst--;
}else{
ans++;
}
}
}
printf("%d\n", sst + ans);
return 0;
}
| C | // ABC 155-B
// 2020.2.16 bal4u
#include <stdio.h>
int main()
{
int N, A;
scanf("%d", &N);
while (N--) {
scanf("%d", &A);
if (A & 1) continue;
if (A % 3 && A % 5) {
puts("DENIED");
return 0;
}
}
puts("APPROVED");
return 0;
}
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
char a[200010];
int ans, sst;
int main(){
scanf("%s", a);
int le = strlen(a);
for(int i = 0; i < le; ++i){
if(*(a + i) == 'S'){
sst++;
}else{
if(sst != 0){
sst--;
}else{
ans++;
}
}
}
printf("%d\n", sst + ans);
return 0;
}
Code 2: // ABC 155-B
// 2020.2.16 bal4u
#include <stdio.h>
int main()
{
int N, A;
scanf("%d", &N);
while (N--) {
scanf("%d", &A);
if (A & 1) continue;
if (A % 3 && A % 5) {
puts("DENIED");
return 0;
}
}
puts("APPROVED");
return 0;
}
|
Python | #!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = I()
return l
def LIR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LI()
return l
def SR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = S()
return l
def LSR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LS()
return l
sys.setrecursionlimit(1000000)
mod = 1000000007
#A
def A():
n,k = LI()
print(n%k)
return
#B
def B():
n = I()
return
#C
def C():
n = I()
return
#D
def D():
n = I()
return
#E
def E():
n = I()
return
#F
def F():
n = I()
return
#G
def G():
n = I()
return
#H
def H():
n = I()
return
#I
def I_():
n = I()
return
#J
def J():
n = I()
return
#Solve
if __name__ == "__main__":
A()
| Kotlin | fun main(args: Array<String>) {
val (n, k) = readLine()!!.split(" ").map { it.toInt() }
println(
if (k==1) 0
else n-k
)
} | Yes | Do these codes solve the same problem?
Code 1: #!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = I()
return l
def LIR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LI()
return l
def SR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = S()
return l
def LSR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LS()
return l
sys.setrecursionlimit(1000000)
mod = 1000000007
#A
def A():
n,k = LI()
print(n%k)
return
#B
def B():
n = I()
return
#C
def C():
n = I()
return
#D
def D():
n = I()
return
#E
def E():
n = I()
return
#F
def F():
n = I()
return
#G
def G():
n = I()
return
#H
def H():
n = I()
return
#I
def I_():
n = I()
return
#J
def J():
n = I()
return
#Solve
if __name__ == "__main__":
A()
Code 2: fun main(args: Array<String>) {
val (n, k) = readLine()!!.split(" ").map { it.toInt() }
println(
if (k==1) 0
else n-k
)
} |
C | #include<stdio.h>
int main(void){
char st[40];
scanf("%s",st);
printf("%c%c%c",st[0],st[1],st[2]);
return 0;
}
| C++ | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <map>
#include <set>
#include <bitset>
#include <functional>
using namespace std;
typedef long long ll;
struct edge {
bool used;
int to, d, rev;
};
ll INI = 1e18;
ll d[100003];
vector<edge> edg[100003];
bool vis[100003];
bool func(int pos, ll dis) {
if (vis[pos]) return d[pos] == dis;
vis[pos] = true;
d[pos] = dis;
bool ret = true;
for (int i = 0; i < (int)edg[pos].size(); ++i) {
edge &e = edg[pos][i];
if (e.used) continue;
e.used = true;
edg[e.to][e.rev].used = true;
ret &= func(e.to, dis + e.d);
}
return ret;
}
int main() {
int n, m; cin >> n >> m;
for (int i = 0; i < m; ++i) {
int l, r, d; cin >> l >> r >> d;
--l; --r;
edg[l].push_back({ false, r, d, edg[r].size() });
edg[r].push_back({ false, l, -d, edg[l].size() - 1 });
}
bool ans = true;
for (int i = 0; i < n; ++i) {
if (vis[i]) continue;
ans &= func(i, 0);
}
cout << (ans ? "Yes" : "No") << endl;
return 0;
} | No | Do these codes solve the same problem?
Code 1: #include<stdio.h>
int main(void){
char st[40];
scanf("%s",st);
printf("%c%c%c",st[0],st[1],st[2]);
return 0;
}
Code 2: #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <map>
#include <set>
#include <bitset>
#include <functional>
using namespace std;
typedef long long ll;
struct edge {
bool used;
int to, d, rev;
};
ll INI = 1e18;
ll d[100003];
vector<edge> edg[100003];
bool vis[100003];
bool func(int pos, ll dis) {
if (vis[pos]) return d[pos] == dis;
vis[pos] = true;
d[pos] = dis;
bool ret = true;
for (int i = 0; i < (int)edg[pos].size(); ++i) {
edge &e = edg[pos][i];
if (e.used) continue;
e.used = true;
edg[e.to][e.rev].used = true;
ret &= func(e.to, dis + e.d);
}
return ret;
}
int main() {
int n, m; cin >> n >> m;
for (int i = 0; i < m; ++i) {
int l, r, d; cin >> l >> r >> d;
--l; --r;
edg[l].push_back({ false, r, d, edg[r].size() });
edg[r].push_back({ false, l, -d, edg[l].size() - 1 });
}
bool ans = true;
for (int i = 0; i < n; ++i) {
if (vis[i]) continue;
ans &= func(i, 0);
}
cout << (ans ? "Yes" : "No") << endl;
return 0;
} |
C++ | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P2;
int dx[8]={1,1,1,0,-1,-1,-1,0},dy[8]={-1,0,1,1,1,0,-1,-1};
bool check(int n, int m, int x, int y) {
if(x<0 || x>=n || y<0 || y>=m) return false;
return true;
}
const double EPS = 1e-10;
const double INF = 1e12;
typedef complex<double> P;
namespace std {
bool operator < (const P& a, const P& b) {
return real(a) != real(b) ? real(a) < real(b) : imag(a) < imag(b);
}
}
double cross(const P& a, const P& b) {
return imag(conj(a)*b);
}
double dot(const P& a, const P& b) {
return real(conj(a)*b);
}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > EPS) return +1;
if (cross(b, c) < -EPS) return -1;
if (dot(b, c) < -EPS) return +2;
if (norm(b) < norm(c)) return -2;
return 0;
}
vector<P> convex_hull(vector<P> p) {
int n = p.size(), k = 0;
sort(p.begin(), p.end());
vector<P> q(2*n);
for(int i = 0; i < n; q[k++] = p[i++])
while(k >= 2 && ccw(q[k-2], q[k-1], p[i]) <= 0) --k;
for(int i = n-2, t = k+1; i >= 0; q[k++] = p[i--])
while(k >= t && ccw(q[k-2], q[k-1], p[i]) <= 0) --k;
q.resize(k-1);
return q;
}
double porigon_area(vector<P> p) {
double area=0;
for(int i=0; i<(int)p.size(); i++) area+=cross(p[i],p[(i+1)%p.size()]);
return area;
}
int main() {
bool f=false;
int n;
string t;
while(1) {
cin >> n;
if(n==0) break;
getline(cin,t);
char s[n][100];
fill(s[0],s[n],' ');
for(int i=0; i<n; i++) {
getline(cin,t);
for(int j=0; j<t.size(); j++) s[i][j]=t[j];
}
map<int,int> m;
m.clear();
bool d[n][100];
memset(d,false,sizeof(d));
for(int i=0; i<n; i++) {
for(int j=0; j<100; j++) {
if(d[i][j] || s[i][j]==' ') continue;
d[i][j]=true;
vector<P2> v;
v.push_back(P2(i,j));
queue<P2> que;
que.push(P2(i,j));
int k=0;
while(!que.empty()) {
P2 p=que.front();que.pop();
int nx=p.first,ny=p.second;
for(int l=0; l<8; l++) {
int x=nx+dx[(l+k)%8],y=ny+dy[(l+k)%8];
if(check(n,100,x,y) && !d[x][y] && s[x][y]=='*') {
k=(l+k)%8;
d[x][y]=true;
v.push_back(P2(x,y));
que.push(P2(x,y));
break;
}
}
}
vector<P> p;
for(int l=0; l<v.size(); l++) p.push_back(P(v[l].first,v[l].second));
p=convex_hull(p);
P q=p[0];
p[0]=P(0,0);
p[1]=P(p[1].real()-q.real()+1,p[1].imag()-q.imag());
p[2]=P(p[2].real()-q.real()+1,p[2].imag()-q.imag()+1);
p[3]=P(p[3].real()-q.real(),p[3].imag()-q.imag()+1);
m[(int)porigon_area(p)/2]++;
}
}
if(f) cout << "----------" << endl;
for(map<int,int>::iterator it=m.begin(); it!=m.end(); it++) cout << it->first << " " << it->second << endl;
f=true;
}
return 0;
}
| Java | import java.awt.geom.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
new Main();
}
Main(){
new AOJ1211();
}
class AOJ1211{
AOJ1211(){
int cnt=0;
while(true){
N=sc.nextInt();
if(N==0) break;
if(cnt>0) System.out.println("----------");
solve();
++cnt;
}
}
int N;
final int vx[]={-1,0,1,1,1,0,-1,-1},vy[]={1,1,1,0,-1,-1,-1,0};
final int offsetx[]={-1,-1,0,0},offsety[]={0,1,1,0};
void solve(){
StringBuilder[] str=new StringBuilder[N];
sc.nextLine();
for(int i=0; i<N; ++i) str[i]=new StringBuilder(sc.nextLine());
TreeMap<Integer,Integer> ans=new TreeMap<Integer,Integer>();
ArrayList<Point2D> ps = new ArrayList<Point2D>(4);
for(int y=0; y<N; ++y){
for(int x=0; x<str[y].length(); ++x){
if(str[y].charAt(x)=='*'){
int xx=x, yy=y;
for(int i=0; i<4; ++i){
ps.add(new Point2D.Double(xx+offsetx[i],yy+offsety[i]));
str[yy].setCharAt(xx, '.');
int v=0;
while(!(0<=yy+vy[v]&&yy+vy[v]<N&&0<=xx+vx[v]&&xx+vx[v]<str[yy+vy[v]].length()) || str[yy+vy[v]].charAt(xx+vx[v])!='*') ++v;
// System.out.println("V"+v+" "+xx+","+yy+" "+str[yy].charAt(xx)+" "+str[yy+vy[v]].charAt(xx+vx[v]));
while(0<=yy+vy[v]&&yy+vy[v]<N&&0<=xx+vx[v]&&xx+vx[v]<str[yy+vy[v]].length() && str[yy+vy[v]].charAt(xx+vx[v])=='*'){
xx+=vx[v]; yy+=vy[v];
str[yy].setCharAt(xx, '.');
}
}
// System.out.println(ps);
// System.out.println(area(ps));
int area=(int)area(ps);
if(ans.containsKey(area)) ans.put(area, ans.get(area)+1);
else ans.put(area, 1);
ps.clear();
}
}
}
for(Map.Entry<Integer, Integer> e:ans.entrySet()){
System.out.println(e.getKey()+" "+e.getValue());
}
}
double cross(Point2D p1,Point2D p2){
return p1.getX()*p2.getY() - p2.getX()*p1.getY();
}
double area(ArrayList<Point2D> points){
double ret=0.0;
for(int i=0; i<points.size(); ++i){
Point2D p1=points.get(i), p2=points.get((i+1)%points.size());
ret+=cross(p1, p2);
}
return Math.abs(ret)/2.0;
}
}
} | Yes | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P2;
int dx[8]={1,1,1,0,-1,-1,-1,0},dy[8]={-1,0,1,1,1,0,-1,-1};
bool check(int n, int m, int x, int y) {
if(x<0 || x>=n || y<0 || y>=m) return false;
return true;
}
const double EPS = 1e-10;
const double INF = 1e12;
typedef complex<double> P;
namespace std {
bool operator < (const P& a, const P& b) {
return real(a) != real(b) ? real(a) < real(b) : imag(a) < imag(b);
}
}
double cross(const P& a, const P& b) {
return imag(conj(a)*b);
}
double dot(const P& a, const P& b) {
return real(conj(a)*b);
}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > EPS) return +1;
if (cross(b, c) < -EPS) return -1;
if (dot(b, c) < -EPS) return +2;
if (norm(b) < norm(c)) return -2;
return 0;
}
vector<P> convex_hull(vector<P> p) {
int n = p.size(), k = 0;
sort(p.begin(), p.end());
vector<P> q(2*n);
for(int i = 0; i < n; q[k++] = p[i++])
while(k >= 2 && ccw(q[k-2], q[k-1], p[i]) <= 0) --k;
for(int i = n-2, t = k+1; i >= 0; q[k++] = p[i--])
while(k >= t && ccw(q[k-2], q[k-1], p[i]) <= 0) --k;
q.resize(k-1);
return q;
}
double porigon_area(vector<P> p) {
double area=0;
for(int i=0; i<(int)p.size(); i++) area+=cross(p[i],p[(i+1)%p.size()]);
return area;
}
int main() {
bool f=false;
int n;
string t;
while(1) {
cin >> n;
if(n==0) break;
getline(cin,t);
char s[n][100];
fill(s[0],s[n],' ');
for(int i=0; i<n; i++) {
getline(cin,t);
for(int j=0; j<t.size(); j++) s[i][j]=t[j];
}
map<int,int> m;
m.clear();
bool d[n][100];
memset(d,false,sizeof(d));
for(int i=0; i<n; i++) {
for(int j=0; j<100; j++) {
if(d[i][j] || s[i][j]==' ') continue;
d[i][j]=true;
vector<P2> v;
v.push_back(P2(i,j));
queue<P2> que;
que.push(P2(i,j));
int k=0;
while(!que.empty()) {
P2 p=que.front();que.pop();
int nx=p.first,ny=p.second;
for(int l=0; l<8; l++) {
int x=nx+dx[(l+k)%8],y=ny+dy[(l+k)%8];
if(check(n,100,x,y) && !d[x][y] && s[x][y]=='*') {
k=(l+k)%8;
d[x][y]=true;
v.push_back(P2(x,y));
que.push(P2(x,y));
break;
}
}
}
vector<P> p;
for(int l=0; l<v.size(); l++) p.push_back(P(v[l].first,v[l].second));
p=convex_hull(p);
P q=p[0];
p[0]=P(0,0);
p[1]=P(p[1].real()-q.real()+1,p[1].imag()-q.imag());
p[2]=P(p[2].real()-q.real()+1,p[2].imag()-q.imag()+1);
p[3]=P(p[3].real()-q.real(),p[3].imag()-q.imag()+1);
m[(int)porigon_area(p)/2]++;
}
}
if(f) cout << "----------" << endl;
for(map<int,int>::iterator it=m.begin(); it!=m.end(); it++) cout << it->first << " " << it->second << endl;
f=true;
}
return 0;
}
Code 2: import java.awt.geom.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
new Main();
}
Main(){
new AOJ1211();
}
class AOJ1211{
AOJ1211(){
int cnt=0;
while(true){
N=sc.nextInt();
if(N==0) break;
if(cnt>0) System.out.println("----------");
solve();
++cnt;
}
}
int N;
final int vx[]={-1,0,1,1,1,0,-1,-1},vy[]={1,1,1,0,-1,-1,-1,0};
final int offsetx[]={-1,-1,0,0},offsety[]={0,1,1,0};
void solve(){
StringBuilder[] str=new StringBuilder[N];
sc.nextLine();
for(int i=0; i<N; ++i) str[i]=new StringBuilder(sc.nextLine());
TreeMap<Integer,Integer> ans=new TreeMap<Integer,Integer>();
ArrayList<Point2D> ps = new ArrayList<Point2D>(4);
for(int y=0; y<N; ++y){
for(int x=0; x<str[y].length(); ++x){
if(str[y].charAt(x)=='*'){
int xx=x, yy=y;
for(int i=0; i<4; ++i){
ps.add(new Point2D.Double(xx+offsetx[i],yy+offsety[i]));
str[yy].setCharAt(xx, '.');
int v=0;
while(!(0<=yy+vy[v]&&yy+vy[v]<N&&0<=xx+vx[v]&&xx+vx[v]<str[yy+vy[v]].length()) || str[yy+vy[v]].charAt(xx+vx[v])!='*') ++v;
// System.out.println("V"+v+" "+xx+","+yy+" "+str[yy].charAt(xx)+" "+str[yy+vy[v]].charAt(xx+vx[v]));
while(0<=yy+vy[v]&&yy+vy[v]<N&&0<=xx+vx[v]&&xx+vx[v]<str[yy+vy[v]].length() && str[yy+vy[v]].charAt(xx+vx[v])=='*'){
xx+=vx[v]; yy+=vy[v];
str[yy].setCharAt(xx, '.');
}
}
// System.out.println(ps);
// System.out.println(area(ps));
int area=(int)area(ps);
if(ans.containsKey(area)) ans.put(area, ans.get(area)+1);
else ans.put(area, 1);
ps.clear();
}
}
}
for(Map.Entry<Integer, Integer> e:ans.entrySet()){
System.out.println(e.getKey()+" "+e.getValue());
}
}
double cross(Point2D p1,Point2D p2){
return p1.getX()*p2.getY() - p2.getX()*p1.getY();
}
double area(ArrayList<Point2D> points){
double ret=0.0;
for(int i=0; i<points.size(); ++i){
Point2D p1=points.get(i), p2=points.get((i+1)%points.size());
ret+=cross(p1, p2);
}
return Math.abs(ret)/2.0;
}
}
} |
Python | def make_ps(n):
nums = [True] * n
nums[0] = nums[1] = False
p = 2
sqrt = n ** 0.5
while p < sqrt:
for i in range(2 * p, n, p):
nums[i] = False
while True:
p += 1
if nums[p]:
break
return [i for i in range(n) if nums[i]]
ps = make_ps(105000)
while True:
n = int(input())
if not n:
break
print(sum(ps[:n])) | C++ | #include <iostream>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <bitset>
#include <algorithm>
#include <cmath>
#include <tuple>
#include <climits>
#include <stdlib.h>
#include <queue>
#include <stack>
#define mp make_pair
#define pb push_back
#define forn(n) for(long long i=0;i<n;++i)
#define ll long long
#define ull unsigned long long
#define mod 1000000007
typedef long double ld;
using namespace std;
vector<ll> sieve(ll n)
{
vector<ll> a(n+1,0);
for(ll i=3;i<=n;i+=2)
a[i]=1;
for(ll i=3;i<=n;i+=2)
{
if(a[i]==1)
{
for(ll j=i*2;j<=n;j+=i)
a[j]=0;
}
}
a[2]=1;
a[1]=a[0]=0;
return a;
}
ll reverse(ll n)
{
ll s=0;
while(n>0)
{
ll t=n%10;
s=s*10+t;
n/=10;
}
return s;
}
int count_setbits(int N)
{ int cnt=0;
while(N>0)
{
cnt+=(N&1);
N=N>>1;
}
return cnt;
}
ll power(ll x, ll y)
{
int res = 1; // Initialize result
x = x % mod; // Update x if it is more than or
// equal to p
if (x == 0) return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % mod;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % mod;
}
return res;
}
void BellmanFord(vector< vector<ll> > &graph, int V, int E, int src)
{
// Initialize distance of all vertices as infinite.
int dis[V];
for (int i = 0; i < V; i++)
dis[i] = INT_MAX;
// initialize distance of source as 0
dis[src] = 0;
// Relax all edges |V| - 1 times. A simple
// shortest path from src to any other
// vertex can have at-most |V| - 1 edges
for (int i = 0; i < V - 1; i++) {
for (int j = 0; j < E; j++) {
if (dis[graph[j][0]] + graph[j][2] <
dis[graph[j][1]])
dis[graph[j][1]] =
dis[graph[j][0]] + graph[j][2];
}
}
// check for negative-weight cycles.
// The above step guarantees shortest
// distances if graph doesn't contain
// negative weight cycle. If we get a
// shorter path, then there is a cycle.
for (int i = 0; i < E; i++) {
int x = graph[i][0];
int y = graph[i][1];
int weight = graph[i][2];
if (dis[x] != INT_MAX &&
dis[x] + weight < dis[y])
cout << "Graph contains negative"
" weight cycle"
<< endl;
}
}
/*
to find the farthest node from root using dfs and its distance from root, we have to just
change the dfs function a bit
void dfs(ll node,ll dis)
{
vis[node]=true;
// for any processing of the node, like printing it, please do it here
if(dis>maxd)
{
maxd=dis;maxnode=node;
}
for(ll i=0;i<adj[node].size();i++)
{
ll child=adj[node][i];
if(!vis[child])
dfs(child,dis+1);
}
}
*/
bool vis[1000001];
ll dist[1000001];
int color[1000001];
vector<ll> adj[1000001];
vector<ll> edges;
ll maxd,maxnode;
void dfs(ll node)
{
stack<ll> s;
vis[node]=true;
s.push(node);
// for any processing of the node, like printing it, please do it here
dist[node]=0;
while(!s.empty())
{
ll curr=s.top();
s.pop();
for(ll i:adj[curr])
{
if(!vis[i])
{
s.push(i);
vis[i]=1;
dist[i]=dist[curr]+1;
}
}
}
}
void bfs(ll node)
{
queue<ll> q;
q.push(node);
vis[node]=1;
dist[node]=0;
while(!q.empty())
{
ll curr=q.front();
q.pop();
for(ll i:adj[curr])
{
if(vis[i]==0)
{
q.push(i);
dist[i]=dist[curr]+1;
vis[i]=1;
}
}
}
}
bool dfs_bipartite_check(ll node,int c)
{
vis[node]=1;
color[node]=c;
for(ll i:adj[node])
{
if(vis[i]==0)
{
if(dfs_bipartite_check(i,c^1)==false)
return false;
}
else
{
if(color[node]==color[i])
return false;
}
}
return true;
}
ll subsize[1000001];
ll subtree_size(ll node)
{
vis[node]=1;
ll curr_size=1;
for(ll i=0;i<adj[node].size();i++)
{
ll child=adj[node][i];
if(vis[child]==0)
{
curr_size+=subtree_size(child); // dfs call when child is not visited
}
}
subsize[node]=curr_size; // update size of subtree of the current node
return curr_size; // return size of subtree of the current node
}
bool cycle_detect(ll node,ll parent)
{
vis[node]=1;
for(ll child:adj[node])
{
if(vis[child]==0) { // if not visited, make dfs call, and return true if dfs returns true
if(cycle_detect(child,node))
return true;
}
else
{
if(child!=parent) // check if visited child is parent of current node or ancestor of current node
return true; // returns true if child is ancestor and not parent of current node
}
}
return false;
}
// for graph questions having multiple test cases, dont forget to clear adjacency list and clear visited array
/* Just add these lines in each testcases
for(ll i=1;i<=nodes;i++)
adj[i].clear(),vis[i]=0;
*/
int main()
{
string a,b;
cin>>a>>b;
ll cnt=0;
for(ll i=0;i<a.size();i++)
if(a[i]!=b[i])
cnt++;
cout<<cnt<<"\n";
}
| No | Do these codes solve the same problem?
Code 1: def make_ps(n):
nums = [True] * n
nums[0] = nums[1] = False
p = 2
sqrt = n ** 0.5
while p < sqrt:
for i in range(2 * p, n, p):
nums[i] = False
while True:
p += 1
if nums[p]:
break
return [i for i in range(n) if nums[i]]
ps = make_ps(105000)
while True:
n = int(input())
if not n:
break
print(sum(ps[:n]))
Code 2: #include <iostream>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <bitset>
#include <algorithm>
#include <cmath>
#include <tuple>
#include <climits>
#include <stdlib.h>
#include <queue>
#include <stack>
#define mp make_pair
#define pb push_back
#define forn(n) for(long long i=0;i<n;++i)
#define ll long long
#define ull unsigned long long
#define mod 1000000007
typedef long double ld;
using namespace std;
vector<ll> sieve(ll n)
{
vector<ll> a(n+1,0);
for(ll i=3;i<=n;i+=2)
a[i]=1;
for(ll i=3;i<=n;i+=2)
{
if(a[i]==1)
{
for(ll j=i*2;j<=n;j+=i)
a[j]=0;
}
}
a[2]=1;
a[1]=a[0]=0;
return a;
}
ll reverse(ll n)
{
ll s=0;
while(n>0)
{
ll t=n%10;
s=s*10+t;
n/=10;
}
return s;
}
int count_setbits(int N)
{ int cnt=0;
while(N>0)
{
cnt+=(N&1);
N=N>>1;
}
return cnt;
}
ll power(ll x, ll y)
{
int res = 1; // Initialize result
x = x % mod; // Update x if it is more than or
// equal to p
if (x == 0) return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % mod;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % mod;
}
return res;
}
void BellmanFord(vector< vector<ll> > &graph, int V, int E, int src)
{
// Initialize distance of all vertices as infinite.
int dis[V];
for (int i = 0; i < V; i++)
dis[i] = INT_MAX;
// initialize distance of source as 0
dis[src] = 0;
// Relax all edges |V| - 1 times. A simple
// shortest path from src to any other
// vertex can have at-most |V| - 1 edges
for (int i = 0; i < V - 1; i++) {
for (int j = 0; j < E; j++) {
if (dis[graph[j][0]] + graph[j][2] <
dis[graph[j][1]])
dis[graph[j][1]] =
dis[graph[j][0]] + graph[j][2];
}
}
// check for negative-weight cycles.
// The above step guarantees shortest
// distances if graph doesn't contain
// negative weight cycle. If we get a
// shorter path, then there is a cycle.
for (int i = 0; i < E; i++) {
int x = graph[i][0];
int y = graph[i][1];
int weight = graph[i][2];
if (dis[x] != INT_MAX &&
dis[x] + weight < dis[y])
cout << "Graph contains negative"
" weight cycle"
<< endl;
}
}
/*
to find the farthest node from root using dfs and its distance from root, we have to just
change the dfs function a bit
void dfs(ll node,ll dis)
{
vis[node]=true;
// for any processing of the node, like printing it, please do it here
if(dis>maxd)
{
maxd=dis;maxnode=node;
}
for(ll i=0;i<adj[node].size();i++)
{
ll child=adj[node][i];
if(!vis[child])
dfs(child,dis+1);
}
}
*/
bool vis[1000001];
ll dist[1000001];
int color[1000001];
vector<ll> adj[1000001];
vector<ll> edges;
ll maxd,maxnode;
void dfs(ll node)
{
stack<ll> s;
vis[node]=true;
s.push(node);
// for any processing of the node, like printing it, please do it here
dist[node]=0;
while(!s.empty())
{
ll curr=s.top();
s.pop();
for(ll i:adj[curr])
{
if(!vis[i])
{
s.push(i);
vis[i]=1;
dist[i]=dist[curr]+1;
}
}
}
}
void bfs(ll node)
{
queue<ll> q;
q.push(node);
vis[node]=1;
dist[node]=0;
while(!q.empty())
{
ll curr=q.front();
q.pop();
for(ll i:adj[curr])
{
if(vis[i]==0)
{
q.push(i);
dist[i]=dist[curr]+1;
vis[i]=1;
}
}
}
}
bool dfs_bipartite_check(ll node,int c)
{
vis[node]=1;
color[node]=c;
for(ll i:adj[node])
{
if(vis[i]==0)
{
if(dfs_bipartite_check(i,c^1)==false)
return false;
}
else
{
if(color[node]==color[i])
return false;
}
}
return true;
}
ll subsize[1000001];
ll subtree_size(ll node)
{
vis[node]=1;
ll curr_size=1;
for(ll i=0;i<adj[node].size();i++)
{
ll child=adj[node][i];
if(vis[child]==0)
{
curr_size+=subtree_size(child); // dfs call when child is not visited
}
}
subsize[node]=curr_size; // update size of subtree of the current node
return curr_size; // return size of subtree of the current node
}
bool cycle_detect(ll node,ll parent)
{
vis[node]=1;
for(ll child:adj[node])
{
if(vis[child]==0) { // if not visited, make dfs call, and return true if dfs returns true
if(cycle_detect(child,node))
return true;
}
else
{
if(child!=parent) // check if visited child is parent of current node or ancestor of current node
return true; // returns true if child is ancestor and not parent of current node
}
}
return false;
}
// for graph questions having multiple test cases, dont forget to clear adjacency list and clear visited array
/* Just add these lines in each testcases
for(ll i=1;i<=nodes;i++)
adj[i].clear(),vis[i]=0;
*/
int main()
{
string a,b;
cin>>a>>b;
ll cnt=0;
for(ll i=0;i<a.size();i++)
if(a[i]!=b[i])
cnt++;
cout<<cnt<<"\n";
}
|
C# | using System;
class Program
{
static void Main(string[] args)
{
// スペース区切りの整数の入力
var input = Console.ReadLine().Split(' ');
var a = int.Parse(input[0]);
var b = int.Parse(input[1]);
var max=Math.Max(a,b);
var min=Math.Min(a,b);
if(max>min){
Console.WriteLine(max*2-1);
}
else{
Console.WriteLine(max*2);
}
}
}
| C++ | #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, x;
scanf("%d %d %d", &a, &b, &x);
if(x >= a && x <= a+b) {
printf("YES\n");
} else {
printf("NO\n");
}
} | No | Do these codes solve the same problem?
Code 1: using System;
class Program
{
static void Main(string[] args)
{
// スペース区切りの整数の入力
var input = Console.ReadLine().Split(' ');
var a = int.Parse(input[0]);
var b = int.Parse(input[1]);
var max=Math.Max(a,b);
var min=Math.Min(a,b);
if(max>min){
Console.WriteLine(max*2-1);
}
else{
Console.WriteLine(max*2);
}
}
}
Code 2: #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, x;
scanf("%d %d %d", &a, &b, &x);
if(x >= a && x <= a+b) {
printf("YES\n");
} else {
printf("NO\n");
}
} |
C++ | #include <bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
cout<<max(max(a+b,a-b),a*b)<<endl;
return 0;
} | Python | from fractions import gcd
N = int(input())
A = list(map(int,input().split()))
if N == 2:
ans = max(A)
else:
GCDF, GCDB = [0]*N, [0]*N
GCDF[1],GCDB[-2] = A[0], A[N-1]
for i in range(2, N):
GCDF[i] = gcd(GCDF[i-1],A[i-1])
GCDB[-(i+1)] = gcd(GCDB[-i], A[-i])
GCDm = [0]*N
GCDm[0] = GCDB[0]
GCDm[N-1] = GCDF[N-1]
for i in range(1, N-1):
GCDm[i] = gcd(GCDF[i],GCDB[i])
ans = max(GCDm)
print(ans)
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
cout<<max(max(a+b,a-b),a*b)<<endl;
return 0;
}
Code 2: from fractions import gcd
N = int(input())
A = list(map(int,input().split()))
if N == 2:
ans = max(A)
else:
GCDF, GCDB = [0]*N, [0]*N
GCDF[1],GCDB[-2] = A[0], A[N-1]
for i in range(2, N):
GCDF[i] = gcd(GCDF[i-1],A[i-1])
GCDB[-(i+1)] = gcd(GCDB[-i], A[-i])
GCDm = [0]*N
GCDm[0] = GCDB[0]
GCDm[N-1] = GCDF[N-1]
for i in range(1, N-1):
GCDm[i] = gcd(GCDF[i],GCDB[i])
ans = max(GCDm)
print(ans)
|
Java | import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import static java.lang.Math.E;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.atan;
import static java.lang.Math.cos;
import static java.lang.Math.exp;
import static java.lang.Math.hypot;
import static java.lang.Math.log;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.TEN;
import static java.math.BigInteger.ZERO;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
import static java.util.Comparator.reverseOrder;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
public class Main {
public static void main(String[] args) {
FastScanner fsc = new FastScanner();
char[] s = fsc.next().toCharArray();
int q = fsc.nextInt();
ArrayDeque<Character> ans = new ArrayDeque<>();
for (char c : s) {
ans.addLast(c);
}
boolean rev = false;
while (q-- > 0) {
int t = fsc.nextInt();
if (t == 1) {
rev = !rev;
} else {
int f = fsc.nextInt();
char c = fsc.next().charAt(0);
if (f == 1) {
if (rev) {
ans.addLast(c);
} else {
ans.addFirst(c);
}
} else {
if (rev) {
ans.addFirst(c);
} else {
ans.addLast(c);
}
}
}
}
StringBuilder sb = new StringBuilder();
while (ans.size() > 0) {
if (rev) {
sb.append(ans.pollLast());
} else {
sb.append(ans.pollFirst());
}
}
System.out.println(sb);
}
}
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());
}
}
| TypeScript | import * as fs from "fs";
interface FlipQuery {
type: "flip";
}
interface AddQuery {
type: "add";
to: "start" | "end";
char: string
}
type Query = FlipQuery | AddQuery;
const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const s = input[0];
const q = +input[1];
const queries = [];
for (let i = 0; i < q; i++) {
const query = input[i + 2].split(" ");
if (query[0] === "1") {
queries.push({ type: "flip" });
} else {
if (query[1] === "1") {
queries.push({ type: "add", to: "start", char: query[2] });
} else {
queries.push({ type: "add", to: "end", char: query[2] });
}
}
}
queries.reverse()
let strs: [string, string] = ["", ""];
let flip_count = 0;
for (const query of queries) {
if (query.type === "flip") {
flip_count++;
continue;
}
else if (query.type === "add") {
// add
const to = (query as AddQuery).to;
const char = (query as AddQuery).char;
const reversed = flip_count % 2 === 1;
let to_start = to === "start";
if (reversed) to_start = !to_start;
strs[to_start ? 0 : 1] += char;
}
}
let result = strs[0];
if (flip_count % 2 === 1) {
result += s.split("").reverse().join("");
} else {
result += s;
}
result += strs[1].split("").reverse().join("");
console.log(result);
| Yes | Do these codes solve the same problem?
Code 1: import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import static java.lang.Math.E;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.atan;
import static java.lang.Math.cos;
import static java.lang.Math.exp;
import static java.lang.Math.hypot;
import static java.lang.Math.log;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.TEN;
import static java.math.BigInteger.ZERO;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
import static java.util.Comparator.reverseOrder;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
public class Main {
public static void main(String[] args) {
FastScanner fsc = new FastScanner();
char[] s = fsc.next().toCharArray();
int q = fsc.nextInt();
ArrayDeque<Character> ans = new ArrayDeque<>();
for (char c : s) {
ans.addLast(c);
}
boolean rev = false;
while (q-- > 0) {
int t = fsc.nextInt();
if (t == 1) {
rev = !rev;
} else {
int f = fsc.nextInt();
char c = fsc.next().charAt(0);
if (f == 1) {
if (rev) {
ans.addLast(c);
} else {
ans.addFirst(c);
}
} else {
if (rev) {
ans.addFirst(c);
} else {
ans.addLast(c);
}
}
}
}
StringBuilder sb = new StringBuilder();
while (ans.size() > 0) {
if (rev) {
sb.append(ans.pollLast());
} else {
sb.append(ans.pollFirst());
}
}
System.out.println(sb);
}
}
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());
}
}
Code 2: import * as fs from "fs";
interface FlipQuery {
type: "flip";
}
interface AddQuery {
type: "add";
to: "start" | "end";
char: string
}
type Query = FlipQuery | AddQuery;
const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const s = input[0];
const q = +input[1];
const queries = [];
for (let i = 0; i < q; i++) {
const query = input[i + 2].split(" ");
if (query[0] === "1") {
queries.push({ type: "flip" });
} else {
if (query[1] === "1") {
queries.push({ type: "add", to: "start", char: query[2] });
} else {
queries.push({ type: "add", to: "end", char: query[2] });
}
}
}
queries.reverse()
let strs: [string, string] = ["", ""];
let flip_count = 0;
for (const query of queries) {
if (query.type === "flip") {
flip_count++;
continue;
}
else if (query.type === "add") {
// add
const to = (query as AddQuery).to;
const char = (query as AddQuery).char;
const reversed = flip_count % 2 === 1;
let to_start = to === "start";
if (reversed) to_start = !to_start;
strs[to_start ? 0 : 1] += char;
}
}
let result = strs[0];
if (flip_count % 2 === 1) {
result += s.split("").reverse().join("");
} else {
result += s;
}
result += strs[1].split("").reverse().join("");
console.log(result);
|
C++ | #include <bits/stdc++.h>
#define ll long long
using namespace std;
#define inf 0x3f3f3f3f
#define MAXN 1019191130
int main(){
ll n , W; cin >> n >> W;
ll w[101] , v[101] , dp[100001];
for(int i = 0 ; i <= 100000; ++i) dp[i] = inf;
for(int i = 0 ; i < n ; ++i)
cin >> w[i] >> v[i];
dp[0] = 0;
for(int i = 0 ; i < n ; ++i){
for(int j = 100000 ; j >= v[i] ; j--){
dp[j] = min(dp[j] , dp[j - v[i]] + w[i]);
}
}
int j = 100001;
while(j-- && dp[j] > W);
cout<< j <<endl;
} | Python |
A = [input() for i in range(3)]
B =A[0]+A[1]+A[2]
B
print('{}'.format(B[0]+B[4]+B[8]))
| No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#define ll long long
using namespace std;
#define inf 0x3f3f3f3f
#define MAXN 1019191130
int main(){
ll n , W; cin >> n >> W;
ll w[101] , v[101] , dp[100001];
for(int i = 0 ; i <= 100000; ++i) dp[i] = inf;
for(int i = 0 ; i < n ; ++i)
cin >> w[i] >> v[i];
dp[0] = 0;
for(int i = 0 ; i < n ; ++i){
for(int j = 100000 ; j >= v[i] ; j--){
dp[j] = min(dp[j] , dp[j - v[i]] + w[i]);
}
}
int j = 100001;
while(j-- && dp[j] > W);
cout<< j <<endl;
}
Code 2:
A = [input() for i in range(3)]
B =A[0]+A[1]+A[2]
B
print('{}'.format(B[0]+B[4]+B[8]))
|
Python | N = int(input())
p = list(map(int, input().split()))
check = 0
for i in range(N):
if i+1 != p[i]:
check += 1
print("YES" if check <= 2 else "NO") | Java | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
BRedOrBlue solver = new BRedOrBlue();
solver.solve(1, in, out);
out.close();
}
static class BRedOrBlue {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
String s = in.readString();
int r = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'R') r++;
}
out.printLine(r > n - r ? "Yes" : "No");
}
}
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 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 String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 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 print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| No | Do these codes solve the same problem?
Code 1: N = int(input())
p = list(map(int, input().split()))
check = 0
for i in range(N):
if i+1 != p[i]:
check += 1
print("YES" if check <= 2 else "NO")
Code 2: import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
BRedOrBlue solver = new BRedOrBlue();
solver.solve(1, in, out);
out.close();
}
static class BRedOrBlue {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
String s = in.readString();
int r = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'R') r++;
}
out.printLine(r > n - r ? "Yes" : "No");
}
}
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 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 String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 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 print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
|
Python | S = input()[::-1]
cnt = [0] * 2019
cnt[0] = 1
total = 0
x = 1
ans = 0
for a in S:
total += int(a) * x
total %= 2019
cnt[total] += 1
x = x*10
x %= 2019
for i in range(2019):
ans += cnt[i]*(cnt[i]-1)//2
print(ans)
| C++ | #include"bits/stdc++.h"
using namespace std;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define rep3(i,m,n) for(int (i)=m;(i)<=(n);(i)++)
#define rep3rev(i,m,n) for(int (i)=m;(i)>=(n);(i)--)
#define all(a) (a.begin()),(a.end())
#define rall(a) (a.rbegin()),(a.rend())
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef pair<int, int> pii;
int n, m, q;
vi a, b, c, d;
vi A;
ll mx = 0;
void dfs(int depth = 0, int parnum = 1){
if(depth == n) {
ll tot = 0;
rep(i,q){
if(A[b[i]] - A[a[i]] == c[i]) tot += d[i];
}
mx = max(mx, tot);
}
else{
rep3(i, parnum, m){
A[depth] = i;
dfs(depth + 1, i);
}
}
}
void Main(){
cin >> n >> m >> q;
a.resize(q);
b.resize(q);
c.resize(q);
d.resize(q);
A.resize(n);
rep(i,q){
cin >> a[i] >> b[i] >> c[i] >> d[i];
a[i]--; b[i]--;
}
dfs();
cout << mx << endl;
return;
}
int main(){
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
cout << fixed << setprecision(15);
Main();
return 0;
} | No | Do these codes solve the same problem?
Code 1: S = input()[::-1]
cnt = [0] * 2019
cnt[0] = 1
total = 0
x = 1
ans = 0
for a in S:
total += int(a) * x
total %= 2019
cnt[total] += 1
x = x*10
x %= 2019
for i in range(2019):
ans += cnt[i]*(cnt[i]-1)//2
print(ans)
Code 2: #include"bits/stdc++.h"
using namespace std;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define rep3(i,m,n) for(int (i)=m;(i)<=(n);(i)++)
#define rep3rev(i,m,n) for(int (i)=m;(i)>=(n);(i)--)
#define all(a) (a.begin()),(a.end())
#define rall(a) (a.rbegin()),(a.rend())
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef pair<int, int> pii;
int n, m, q;
vi a, b, c, d;
vi A;
ll mx = 0;
void dfs(int depth = 0, int parnum = 1){
if(depth == n) {
ll tot = 0;
rep(i,q){
if(A[b[i]] - A[a[i]] == c[i]) tot += d[i];
}
mx = max(mx, tot);
}
else{
rep3(i, parnum, m){
A[depth] = i;
dfs(depth + 1, i);
}
}
}
void Main(){
cin >> n >> m >> q;
a.resize(q);
b.resize(q);
c.resize(q);
d.resize(q);
A.resize(n);
rep(i,q){
cin >> a[i] >> b[i] >> c[i] >> d[i];
a[i]--; b[i]--;
}
dfs();
cout << mx << endl;
return;
}
int main(){
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
cout << fixed << setprecision(15);
Main();
return 0;
} |
C++ | #include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <functional>
#include <cmath>
#include <unordered_map>
#define REP(i, n) for (int i = 0; i < n; i++)
#define ll long long int
using namespace std;
int main()
{
int a, b, k;
cin >> a >> b >> k;
int list[100] = {};
REP(i, 100)
{
if (a % (i + 1) == 0 && b % (i + 1) == 0)
{
list[i] = 1;
}
}
int count = 0;
int ans = 0;
for (int i = 99; i >= 0; i--)
{
if (list[i] == 1)
{
count++;
}
ans = i + 1;
if (count == k)
{
break;
}
}
cout << ans << endl;
} | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Numerics;
using System.Threading;
using static System.Math;
using static System.Array;
using static AtCoder.IO_ShortCut;
using static AtCoder.Tool;
using static AtCoder.ModInt;
namespace AtCoder
{
class AC
{
const int MOD = 1000000007;
//const int MOD = 998244353;
const int INF = int.MaxValue / 2;
const long SINF = long.MaxValue / 2;
const double EPS = 1e-8;
static readonly int[] dI = { 0, 1, 0, -1, 1, -1, -1, 1 };
static readonly int[] dJ = { 1, 0, -1, 0, 1, 1, -1, -1 };
static List<List<int>> G = new List<List<int>>();
//static List<List<Edge>> G = new List<List<Edge>>();
//static List<Edge> E = new List<Edge>();
static void Main(string[] args)
{
var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw);
/*var th = new Thread(Run, 1 << 26);
th.Start();
th.Join();*/
Run();
Console.Out.Flush();
}
static void Run()
{
int t = 1;
for (var _ = 0; _ < t; _++) Solve();
}
static void Solve()
{
int N;
long K;
Input(out N, out K);
var A = ConvertAll(_ReadSplitInt, x => x - 1);
var nxt = new int[63, N];
for (var i = 0; i < N; i++) nxt[0, i] = A[i];
for(var i = 1; i < 63; i++)
{
for(var j = 0; j < N; j++)
{
nxt[i, j] = nxt[i - 1, nxt[i - 1, j]];
}
}
int cur = 0;
for(var i = 62; i >= 0; i--)
{
if (Bit(K, i))
{
cur = nxt[i, cur];
}
}
OutL(++cur);
}
public struct Edge
{
public int from;
public int to;
public long dist;
public Edge(int t, long c)
{
from = -1;
to = t;
dist = c;
}
public Edge(int f, int t, long c)
{
from = f;
to = t;
dist = c;
}
}
}
struct ModInt
{
public long value;
private const int MOD = 1000000007;
//private const int MOD = 998244353;
public ModInt(long value) { this.value = value; }
public static implicit operator ModInt(long a)
{
var ret = a % MOD;
return new ModInt(ret < 0 ? (ret + MOD) : ret);
}
public static ModInt operator +(ModInt a, ModInt b) => (a.value + b.value);
public static ModInt operator -(ModInt a, ModInt b) => (a.value - b.value);
public static ModInt operator *(ModInt a, ModInt b) => (a.value * b.value);
public static ModInt operator /(ModInt a, ModInt b) => a * Modpow(b, MOD - 2);
public static ModInt operator <<(ModInt a, int n) => (a.value << n);
public static ModInt operator >>(ModInt a, int n) => (a.value >> n);
public static ModInt operator ++(ModInt a) => a.value + 1;
public static ModInt operator --(ModInt a) => a.value - 1;
public static ModInt Modpow(ModInt a, long n)
{
var k = a;
ModInt ret = 1;
while (n > 0)
{
if ((n & 1) != 0) ret *= k;
k *= k;
n >>= 1;
}
return ret;
}
private static readonly List<long> Factorials = new List<long>() { 1 };
public static ModInt Fac(long n)
{
for (var i = Factorials.Count(); i <= n; i++)
{
Factorials.Add((Factorials[i - 1] * i) % MOD);
}
return Factorials[(int)n];
}
public static ModInt nCr(long n, long r)
{
return n < r ? 0 : Fac(n) / (Fac(r) * Fac(n - r));
}
public static explicit operator int(ModInt a) => (int)a.value;
}
static class IO_ShortCut
{
public static string[] _ReadSplit => Console.ReadLine().Split();
public static int[] _ReadSplitInt => ConvertAll(Console.ReadLine().Split(), int.Parse);
public static long[] _ReadSplitLong => ConvertAll(Console.ReadLine().Split(), long.Parse);
public static double[] _ReadSplit_Double => ConvertAll(Console.ReadLine().Split(), double.Parse);
public static string Str => Console.ReadLine();
public static int Int => int.Parse(Console.ReadLine());
public static long Long => long.Parse(Console.ReadLine());
public static double Double => double.Parse(Console.ReadLine());
public static T Conv<T>(string input)
{
if (typeof(T).Equals(typeof(ModInt)))
{
return (T)(dynamic)(long.Parse(input));
}
return (T)Convert.ChangeType(input, typeof(T));
}
public static void Input<T>(out T a) => a = Conv<T>(Console.ReadLine());
public static void Input<T, U>(out T a, out U b)
{ var q = _ReadSplit; a = Conv<T>(q[0]); b = Conv<U>(q[1]); }
public static void Input<T, U, V>(out T a, out U b, out V c)
{ var q = _ReadSplit; a = Conv<T>(q[0]); b = Conv<U>(q[1]); c = Conv<V>(q[2]); }
public static void Input<T, U, V, W>(out T a, out U b, out V c, out W d)
{ var q = _ReadSplit; a = Conv<T>(q[0]); b = Conv<U>(q[1]); c = Conv<V>(q[2]); d = Conv<W>(q[3]); }
public static void Input<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
{ var q = _ReadSplit; a = Conv<T>(q[0]); b = Conv<U>(q[1]); c = Conv<V>(q[2]); d = Conv<W>(q[3]); e = Conv<X>(q[4]); }
public static void OutL(object s) => Console.WriteLine(s);
public static void Out_Sep<T>(IEnumerable<T> s) => Console.WriteLine(string.Join(" ", s));
public static void Out_Sep<T>(IEnumerable<T> s, string sep) => Console.WriteLine(string.Join($"{sep}", s));
public static void Out_Sep(params object[] s) => Console.WriteLine(string.Join(" ", s));
public static void Out_One(object s) => Console.Write($"{s} ");
public static void Out_One(object s, string sep) => Console.Write($"{s}{sep}");
public static void Endl() => Console.WriteLine();
}
public static class Tool
{
static public void Initialize<T>(ref T[] array, T initialvalue)
{
array = ConvertAll(array, x => initialvalue);
}
static public void Swap<T>(ref T a, ref T b)
{
T keep = a;
a = b;
b = keep;
}
static public void Display<T>(T[,] array2d, int n, int m)
{
for (var i = 0; i < n; i++)
{
for (var j = 0; j < m; j++)
{
Console.Write($"{array2d[i, j]} ");
}
Console.WriteLine();
}
}
static public long Gcd(long a, long b)
{
if (a == 0 || b == 0) return Max(a, b);
return a % b == 0 ? b : Gcd(b, a % b);
}
static public long LPow(int a, int b) => (long)Pow(a, b);
static public bool Bit(long x, int dig) => ((1L << dig) & x) != 0;
static public int Sig(long a) => a == 0 ? 0 : (int)(a / Abs(a));
}
}
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <functional>
#include <cmath>
#include <unordered_map>
#define REP(i, n) for (int i = 0; i < n; i++)
#define ll long long int
using namespace std;
int main()
{
int a, b, k;
cin >> a >> b >> k;
int list[100] = {};
REP(i, 100)
{
if (a % (i + 1) == 0 && b % (i + 1) == 0)
{
list[i] = 1;
}
}
int count = 0;
int ans = 0;
for (int i = 99; i >= 0; i--)
{
if (list[i] == 1)
{
count++;
}
ans = i + 1;
if (count == k)
{
break;
}
}
cout << ans << endl;
}
Code 2: using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Numerics;
using System.Threading;
using static System.Math;
using static System.Array;
using static AtCoder.IO_ShortCut;
using static AtCoder.Tool;
using static AtCoder.ModInt;
namespace AtCoder
{
class AC
{
const int MOD = 1000000007;
//const int MOD = 998244353;
const int INF = int.MaxValue / 2;
const long SINF = long.MaxValue / 2;
const double EPS = 1e-8;
static readonly int[] dI = { 0, 1, 0, -1, 1, -1, -1, 1 };
static readonly int[] dJ = { 1, 0, -1, 0, 1, 1, -1, -1 };
static List<List<int>> G = new List<List<int>>();
//static List<List<Edge>> G = new List<List<Edge>>();
//static List<Edge> E = new List<Edge>();
static void Main(string[] args)
{
var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw);
/*var th = new Thread(Run, 1 << 26);
th.Start();
th.Join();*/
Run();
Console.Out.Flush();
}
static void Run()
{
int t = 1;
for (var _ = 0; _ < t; _++) Solve();
}
static void Solve()
{
int N;
long K;
Input(out N, out K);
var A = ConvertAll(_ReadSplitInt, x => x - 1);
var nxt = new int[63, N];
for (var i = 0; i < N; i++) nxt[0, i] = A[i];
for(var i = 1; i < 63; i++)
{
for(var j = 0; j < N; j++)
{
nxt[i, j] = nxt[i - 1, nxt[i - 1, j]];
}
}
int cur = 0;
for(var i = 62; i >= 0; i--)
{
if (Bit(K, i))
{
cur = nxt[i, cur];
}
}
OutL(++cur);
}
public struct Edge
{
public int from;
public int to;
public long dist;
public Edge(int t, long c)
{
from = -1;
to = t;
dist = c;
}
public Edge(int f, int t, long c)
{
from = f;
to = t;
dist = c;
}
}
}
struct ModInt
{
public long value;
private const int MOD = 1000000007;
//private const int MOD = 998244353;
public ModInt(long value) { this.value = value; }
public static implicit operator ModInt(long a)
{
var ret = a % MOD;
return new ModInt(ret < 0 ? (ret + MOD) : ret);
}
public static ModInt operator +(ModInt a, ModInt b) => (a.value + b.value);
public static ModInt operator -(ModInt a, ModInt b) => (a.value - b.value);
public static ModInt operator *(ModInt a, ModInt b) => (a.value * b.value);
public static ModInt operator /(ModInt a, ModInt b) => a * Modpow(b, MOD - 2);
public static ModInt operator <<(ModInt a, int n) => (a.value << n);
public static ModInt operator >>(ModInt a, int n) => (a.value >> n);
public static ModInt operator ++(ModInt a) => a.value + 1;
public static ModInt operator --(ModInt a) => a.value - 1;
public static ModInt Modpow(ModInt a, long n)
{
var k = a;
ModInt ret = 1;
while (n > 0)
{
if ((n & 1) != 0) ret *= k;
k *= k;
n >>= 1;
}
return ret;
}
private static readonly List<long> Factorials = new List<long>() { 1 };
public static ModInt Fac(long n)
{
for (var i = Factorials.Count(); i <= n; i++)
{
Factorials.Add((Factorials[i - 1] * i) % MOD);
}
return Factorials[(int)n];
}
public static ModInt nCr(long n, long r)
{
return n < r ? 0 : Fac(n) / (Fac(r) * Fac(n - r));
}
public static explicit operator int(ModInt a) => (int)a.value;
}
static class IO_ShortCut
{
public static string[] _ReadSplit => Console.ReadLine().Split();
public static int[] _ReadSplitInt => ConvertAll(Console.ReadLine().Split(), int.Parse);
public static long[] _ReadSplitLong => ConvertAll(Console.ReadLine().Split(), long.Parse);
public static double[] _ReadSplit_Double => ConvertAll(Console.ReadLine().Split(), double.Parse);
public static string Str => Console.ReadLine();
public static int Int => int.Parse(Console.ReadLine());
public static long Long => long.Parse(Console.ReadLine());
public static double Double => double.Parse(Console.ReadLine());
public static T Conv<T>(string input)
{
if (typeof(T).Equals(typeof(ModInt)))
{
return (T)(dynamic)(long.Parse(input));
}
return (T)Convert.ChangeType(input, typeof(T));
}
public static void Input<T>(out T a) => a = Conv<T>(Console.ReadLine());
public static void Input<T, U>(out T a, out U b)
{ var q = _ReadSplit; a = Conv<T>(q[0]); b = Conv<U>(q[1]); }
public static void Input<T, U, V>(out T a, out U b, out V c)
{ var q = _ReadSplit; a = Conv<T>(q[0]); b = Conv<U>(q[1]); c = Conv<V>(q[2]); }
public static void Input<T, U, V, W>(out T a, out U b, out V c, out W d)
{ var q = _ReadSplit; a = Conv<T>(q[0]); b = Conv<U>(q[1]); c = Conv<V>(q[2]); d = Conv<W>(q[3]); }
public static void Input<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
{ var q = _ReadSplit; a = Conv<T>(q[0]); b = Conv<U>(q[1]); c = Conv<V>(q[2]); d = Conv<W>(q[3]); e = Conv<X>(q[4]); }
public static void OutL(object s) => Console.WriteLine(s);
public static void Out_Sep<T>(IEnumerable<T> s) => Console.WriteLine(string.Join(" ", s));
public static void Out_Sep<T>(IEnumerable<T> s, string sep) => Console.WriteLine(string.Join($"{sep}", s));
public static void Out_Sep(params object[] s) => Console.WriteLine(string.Join(" ", s));
public static void Out_One(object s) => Console.Write($"{s} ");
public static void Out_One(object s, string sep) => Console.Write($"{s}{sep}");
public static void Endl() => Console.WriteLine();
}
public static class Tool
{
static public void Initialize<T>(ref T[] array, T initialvalue)
{
array = ConvertAll(array, x => initialvalue);
}
static public void Swap<T>(ref T a, ref T b)
{
T keep = a;
a = b;
b = keep;
}
static public void Display<T>(T[,] array2d, int n, int m)
{
for (var i = 0; i < n; i++)
{
for (var j = 0; j < m; j++)
{
Console.Write($"{array2d[i, j]} ");
}
Console.WriteLine();
}
}
static public long Gcd(long a, long b)
{
if (a == 0 || b == 0) return Max(a, b);
return a % b == 0 ? b : Gcd(b, a % b);
}
static public long LPow(int a, int b) => (long)Pow(a, b);
static public bool Bit(long x, int dig) => ((1L << dig) & x) != 0;
static public int Sig(long a) => a == 0 ? 0 : (int)(a / Abs(a));
}
}
|
C++ | #include <iostream>
using namespace std;
int main() {
while (true) {
int n, m;
cin >> n >> m;
if (n == 0 && m == 0) {
break;
}
bool* player = new bool [n];
for (int i = 0; i < n; i++) {
player[i] = true;
}
int retireNum = 0, count = 0, i = 0;
while (retireNum < n - 1) {
if (player[i]) {
count++;
if (count == m) {
player[i] = false;
retireNum++;
count = 0;
}
}
i++;
if (i >= n) {
i = i % n;
}
}
for (int i = 0; i < n; i++) {
if (player[i]) {
cout << i + 1 << endl;
}
}
delete[] player;
}
} | Kotlin | import java.util.*
class ModInt {
var v: Long
private set
constructor(v: Int){
this.v = v.toLong() % MOD
}
constructor(v: Long){
this.v = v % MOD
}
override fun toString() = v.toString()
override fun equals(other: Any?): Boolean {
return if (other is ModInt) v == other.v else false
}
override fun hashCode() = 31*17 + v.hashCode()
operator fun unaryPlus() = this
operator fun unaryMinus() = ModInt(MOD-this.v)
private operator fun plus(o: Long) = ModInt(this.v + o)
operator fun plus(o: ModInt) = this.plus(o.v)
operator fun plus(o: Int) = this.plus(o.toLong())
private operator fun minus(o: Long) = this.plus(-o)
operator fun minus(o: ModInt) = this.plus(-o)
operator fun minus(o: Int) = this.plus(-o)
private operator fun times(o: Long) = ModInt(this.v*o)
operator fun times(o: ModInt) = this.times(o.v)
operator fun times(o: Int) = this.times(o.toLong())
private operator fun div(o: Long) = this.times(pow(o, MOD-2))
operator fun div(o: ModInt) = this.div(o.v)
operator fun div(o: Int) = this.div(o.toLong())
operator fun inc() = this.plus(1)
operator fun dec() = this.minus(1)
companion object{
const val MOD = 1000000007
private fun pow(b:Long, e: Int): ModInt{
if (b==1L) return ModInt(1)
var ans = 1L
var b = b; var e = e
while (e!=0){
if (e%2==1) ans = (ans*b)%MOD
b = (b*b)%MOD
e /= 2
}
return ModInt(ans)
}
fun pow(b: Int, e: Int): ModInt = pow(b.toLong(), e)
fun pow(b: ModInt, e: Int): ModInt = pow(b.v, e)
}
}
val fctrls = mutableListOf<ModInt>()
fun main(args: Array<String>) {
val scn = Scanner(System.`in`)
val n = scn.nextInt()
val k = scn.nextInt()
val arr = IntArray(n){scn.nextInt()}
arr.sort()
var ans = ModInt(0)
for (i in 0..n-k) ans -= comb(n-i-1, k-1)*arr[i]
for (i in k-1 until n) ans += comb(i, k-1)*arr[i]
print(ans)
}
fun factorial(n: Int): ModInt{
if (n in fctrls.indices) return fctrls[n]
else if (fctrls.size==0) fctrls.add(ModInt(1))
for (i in fctrls.size..n){
fctrls.add(fctrls[i-1]*i)
}
return fctrls[n]
}
fun comb(n: Int, k: Int): ModInt = factorial(n)/(factorial(k)* factorial(n-k))
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int main() {
while (true) {
int n, m;
cin >> n >> m;
if (n == 0 && m == 0) {
break;
}
bool* player = new bool [n];
for (int i = 0; i < n; i++) {
player[i] = true;
}
int retireNum = 0, count = 0, i = 0;
while (retireNum < n - 1) {
if (player[i]) {
count++;
if (count == m) {
player[i] = false;
retireNum++;
count = 0;
}
}
i++;
if (i >= n) {
i = i % n;
}
}
for (int i = 0; i < n; i++) {
if (player[i]) {
cout << i + 1 << endl;
}
}
delete[] player;
}
}
Code 2: import java.util.*
class ModInt {
var v: Long
private set
constructor(v: Int){
this.v = v.toLong() % MOD
}
constructor(v: Long){
this.v = v % MOD
}
override fun toString() = v.toString()
override fun equals(other: Any?): Boolean {
return if (other is ModInt) v == other.v else false
}
override fun hashCode() = 31*17 + v.hashCode()
operator fun unaryPlus() = this
operator fun unaryMinus() = ModInt(MOD-this.v)
private operator fun plus(o: Long) = ModInt(this.v + o)
operator fun plus(o: ModInt) = this.plus(o.v)
operator fun plus(o: Int) = this.plus(o.toLong())
private operator fun minus(o: Long) = this.plus(-o)
operator fun minus(o: ModInt) = this.plus(-o)
operator fun minus(o: Int) = this.plus(-o)
private operator fun times(o: Long) = ModInt(this.v*o)
operator fun times(o: ModInt) = this.times(o.v)
operator fun times(o: Int) = this.times(o.toLong())
private operator fun div(o: Long) = this.times(pow(o, MOD-2))
operator fun div(o: ModInt) = this.div(o.v)
operator fun div(o: Int) = this.div(o.toLong())
operator fun inc() = this.plus(1)
operator fun dec() = this.minus(1)
companion object{
const val MOD = 1000000007
private fun pow(b:Long, e: Int): ModInt{
if (b==1L) return ModInt(1)
var ans = 1L
var b = b; var e = e
while (e!=0){
if (e%2==1) ans = (ans*b)%MOD
b = (b*b)%MOD
e /= 2
}
return ModInt(ans)
}
fun pow(b: Int, e: Int): ModInt = pow(b.toLong(), e)
fun pow(b: ModInt, e: Int): ModInt = pow(b.v, e)
}
}
val fctrls = mutableListOf<ModInt>()
fun main(args: Array<String>) {
val scn = Scanner(System.`in`)
val n = scn.nextInt()
val k = scn.nextInt()
val arr = IntArray(n){scn.nextInt()}
arr.sort()
var ans = ModInt(0)
for (i in 0..n-k) ans -= comb(n-i-1, k-1)*arr[i]
for (i in k-1 until n) ans += comb(i, k-1)*arr[i]
print(ans)
}
fun factorial(n: Int): ModInt{
if (n in fctrls.indices) return fctrls[n]
else if (fctrls.size==0) fctrls.add(ModInt(1))
for (i in fctrls.size..n){
fctrls.add(fctrls[i-1]*i)
}
return fctrls[n]
}
fun comb(n: Int, k: Int): ModInt = factorial(n)/(factorial(k)* factorial(n-k))
|
C++ | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
main() {
vector<int> xs(3);
for(auto& x:xs) cin>>x;
sort(xs.begin(), xs.end());
cout<< (xs[0]*xs[1])/2 <<endl;
} | Java | import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int K = in.nextInt(), X = in.nextInt();
int min = Math.max(-1000000, X - K + 1);
for (int i = min; i < Math.min(1000001, X + K); i++) {
if(i != min) {
System.out.print(" ");
}
System.out.print(i);
}
System.out.println();
}
}
| No | Do these codes solve the same problem?
Code 1: #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
main() {
vector<int> xs(3);
for(auto& x:xs) cin>>x;
sort(xs.begin(), xs.end());
cout<< (xs[0]*xs[1])/2 <<endl;
}
Code 2: import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int K = in.nextInt(), X = in.nextInt();
int min = Math.max(-1000000, X - K + 1);
for (int i = min; i < Math.min(1000001, X + K); i++) {
if(i != min) {
System.out.print(" ");
}
System.out.print(i);
}
System.out.println();
}
}
|
Python | def solve():
can_positive = False
if len(P) > 0:
if k < n: can_positive = True
else: can_positive = len(M)%2 == 0
else: can_positive = k%2 == 0
if can_positive:
P.sort()
M.sort(reverse=True)
a = [P.pop()] if k%2 else [1]
while len(P) >= 2: a.append(P.pop() * P.pop())
while len(M) >= 2: a.append(M.pop() * M.pop())
return a[:1] + sorted(a[1:], reverse=True)[:(k-k%2)//2]
else: return sorted(P+M, key=lambda x:abs(x))[:k]
n, k = map(int, input().split())
P, M = [], []
for a in map(int, input().split()):
if a < 0: M.append(a)
else: P.append(a)
ans, MOD = 1, 10**9 + 7
for a in solve(): ans *= a; ans %= MOD
ans += MOD; ans %= MOD
print(ans)
| Java | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int k = in.nextInt();
Dijkstra dijkstra = new Dijkstra(k);
for (int i = 0; i < k; i++) {
dijkstra.addDirectedEdge(i, (i + 1) % k, 1);
dijkstra.addDirectedEdge(i, i * 10 % k, 0);
}
long[] dist = dijkstra.getDist(1);
out.println(dist[0] + 1);
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tok;
public String nextString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine(), " ");
} catch (IOException e) {
throw new InputMismatchException();
}
}
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public InputReader(InputStream inputStream) {
in = new BufferedReader(new InputStreamReader(inputStream));
tok = new StringTokenizer("");
}
}
static class Dijkstra {
int n;
ArrayList<Pair>[] G;
private long INF = Long.MAX_VALUE / 3;
public Dijkstra(int n) {
this.n = n;
G = new ArrayList[n];
for (int i = 0; i < n; i++) {
G[i] = new ArrayList<>();
}
}
public void addDirectedEdge(int from, int to, int cost) {
G[from].add(new Pair(to, cost));
}
public long[] getDist(int s) {
PriorityQueue<Pair> Q = new PriorityQueue<>();
Q.add(new Pair(s, 0));
long[] dist = new long[n];
Arrays.fill(dist, INF);
boolean[] used = new boolean[n];
while (!Q.isEmpty()) {
Pair p = Q.poll();
if (used[p.x]) continue;
used[p.x] = true;
dist[p.x] = p.y;
for (Pair edge : G[p.x]) {
Q.add(new Pair(edge.x, p.y + edge.y));
}
}
return dist;
}
class Pair implements Comparable<Pair> {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair p) {
return Long.compare(y, p.y);
}
}
}
}
| No | Do these codes solve the same problem?
Code 1: def solve():
can_positive = False
if len(P) > 0:
if k < n: can_positive = True
else: can_positive = len(M)%2 == 0
else: can_positive = k%2 == 0
if can_positive:
P.sort()
M.sort(reverse=True)
a = [P.pop()] if k%2 else [1]
while len(P) >= 2: a.append(P.pop() * P.pop())
while len(M) >= 2: a.append(M.pop() * M.pop())
return a[:1] + sorted(a[1:], reverse=True)[:(k-k%2)//2]
else: return sorted(P+M, key=lambda x:abs(x))[:k]
n, k = map(int, input().split())
P, M = [], []
for a in map(int, input().split()):
if a < 0: M.append(a)
else: P.append(a)
ans, MOD = 1, 10**9 + 7
for a in solve(): ans *= a; ans %= MOD
ans += MOD; ans %= MOD
print(ans)
Code 2: import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int k = in.nextInt();
Dijkstra dijkstra = new Dijkstra(k);
for (int i = 0; i < k; i++) {
dijkstra.addDirectedEdge(i, (i + 1) % k, 1);
dijkstra.addDirectedEdge(i, i * 10 % k, 0);
}
long[] dist = dijkstra.getDist(1);
out.println(dist[0] + 1);
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tok;
public String nextString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine(), " ");
} catch (IOException e) {
throw new InputMismatchException();
}
}
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public InputReader(InputStream inputStream) {
in = new BufferedReader(new InputStreamReader(inputStream));
tok = new StringTokenizer("");
}
}
static class Dijkstra {
int n;
ArrayList<Pair>[] G;
private long INF = Long.MAX_VALUE / 3;
public Dijkstra(int n) {
this.n = n;
G = new ArrayList[n];
for (int i = 0; i < n; i++) {
G[i] = new ArrayList<>();
}
}
public void addDirectedEdge(int from, int to, int cost) {
G[from].add(new Pair(to, cost));
}
public long[] getDist(int s) {
PriorityQueue<Pair> Q = new PriorityQueue<>();
Q.add(new Pair(s, 0));
long[] dist = new long[n];
Arrays.fill(dist, INF);
boolean[] used = new boolean[n];
while (!Q.isEmpty()) {
Pair p = Q.poll();
if (used[p.x]) continue;
used[p.x] = true;
dist[p.x] = p.y;
for (Pair edge : G[p.x]) {
Q.add(new Pair(edge.x, p.y + edge.y));
}
}
return dist;
}
class Pair implements Comparable<Pair> {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair p) {
return Long.compare(y, p.y);
}
}
}
}
|
Python | s = input().split(',')
for a in s:
print(a, end=' ')
| Go | package main
import (
"bufio"
"fmt"
"os"
)
var sc = bufio.NewScanner(os.Stdin)
func main() {
sc.Scan()
t := sc.Text()
r := []rune(t)
fmt.Printf("2018%s\n", string(r[4:]))
}
| No | Do these codes solve the same problem?
Code 1: s = input().split(',')
for a in s:
print(a, end=' ')
Code 2: package main
import (
"bufio"
"fmt"
"os"
)
var sc = bufio.NewScanner(os.Stdin)
func main() {
sc.Scan()
t := sc.Text()
r := []rune(t)
fmt.Printf("2018%s\n", string(r[4:]))
}
|
Python | from collections import deque
import sys
sys.setrecursionlimit(10**7)
N = int(input())
P = list(map(int,input().split()))
Q = [-1]*N
for i,p in enumerate(P):
Q[p-1] = i
S = ''
a = 1
def rec(l,r):
global S,a
if l==r:
return
while l < r:
ai = Q[a-1]
if ai >= r:
print(':(')
exit()
a += 1
S += '('
rec(l,ai)
S += ')'
l = ai + 1
rec(0,N)
print(S)
| Java |
import java.util.ArrayDeque;
public class Main {
private static void solve() {
int n = ni();
int[] p = na(n);
ArrayDeque<Integer> q = new ArrayDeque<>();
StringBuilder sb = new StringBuilder();
int now = 1;
for (int v : p) {
for (; now <= v; now ++) {
sb.append("(");
q.addLast(now);
}
sb.append(")");
if (q.pollLast() != v) {
System.out.println(":(");
return;
}
}
System.out.println(sb);
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String debug = args.length > 0 ? args[0] : null;
if (debug != null) {
try {
is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
solve();
out.flush();
tr((System.currentTimeMillis() - start) + "ms");
}
}, "", 64000000).start();
}
private static java.io.InputStream is = System.in;
private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
private static java.util.StringTokenizer tokenizer = null;
private static java.io.BufferedReader reader;
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private static double nd() {
return Double.parseDouble(next());
}
private static long nl() {
return Long.parseLong(next());
}
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 char[] ns() {
return next().toCharArray();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int[][] ntable(int n, int m) {
int[][] table = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[i][j] = ni();
}
}
return table;
}
private static int[][] nlist(int n, int m) {
int[][] table = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[j][i] = ni();
}
}
return table;
}
private static int ni() {
return Integer.parseInt(next());
}
private static void tr(Object... o) {
if (is != System.in)
System.out.println(java.util.Arrays.deepToString(o));
}
}
| Yes | Do these codes solve the same problem?
Code 1: from collections import deque
import sys
sys.setrecursionlimit(10**7)
N = int(input())
P = list(map(int,input().split()))
Q = [-1]*N
for i,p in enumerate(P):
Q[p-1] = i
S = ''
a = 1
def rec(l,r):
global S,a
if l==r:
return
while l < r:
ai = Q[a-1]
if ai >= r:
print(':(')
exit()
a += 1
S += '('
rec(l,ai)
S += ')'
l = ai + 1
rec(0,N)
print(S)
Code 2:
import java.util.ArrayDeque;
public class Main {
private static void solve() {
int n = ni();
int[] p = na(n);
ArrayDeque<Integer> q = new ArrayDeque<>();
StringBuilder sb = new StringBuilder();
int now = 1;
for (int v : p) {
for (; now <= v; now ++) {
sb.append("(");
q.addLast(now);
}
sb.append(")");
if (q.pollLast() != v) {
System.out.println(":(");
return;
}
}
System.out.println(sb);
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String debug = args.length > 0 ? args[0] : null;
if (debug != null) {
try {
is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
solve();
out.flush();
tr((System.currentTimeMillis() - start) + "ms");
}
}, "", 64000000).start();
}
private static java.io.InputStream is = System.in;
private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
private static java.util.StringTokenizer tokenizer = null;
private static java.io.BufferedReader reader;
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private static double nd() {
return Double.parseDouble(next());
}
private static long nl() {
return Long.parseLong(next());
}
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 char[] ns() {
return next().toCharArray();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int[][] ntable(int n, int m) {
int[][] table = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[i][j] = ni();
}
}
return table;
}
private static int[][] nlist(int n, int m) {
int[][] table = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[j][i] = ni();
}
}
return table;
}
private static int ni() {
return Integer.parseInt(next());
}
private static void tr(Object... o) {
if (is != System.in)
System.out.println(java.util.Arrays.deepToString(o));
}
}
|
JavaScript | //添字付mergeSort
'use strict'
function mergeSort(arr){
var groups=[[]];
var n=0;
for(let i=0;i<arr.length;i++){
groups[n].push([arr[i],i]);
if(arr[i]>arr[i+1]){
n++;
groups[n]=[];
}
}
while(groups.length>1){//大
let newGroups=[];
while(groups.length>=2){//中
let g1=groups.pop();
g1.push([Infinity]);
let g2=groups.pop();
g2.push([Infinity]);
let merged=[];
let j=0,k=0;
while(j<g1.length-1||k<g2.length-1){//小
if(g1[j][0]<g2[k][0]){
merged[j+k]=g1[j];
j++;
}else{
merged[j+k]=g2[k];
k++;
}
}//小了
newGroups.push(merged);
}//中了
if(groups.length)
newGroups.push(groups[0]);
groups=newGroups;
}//大了
var result=groups[0];
return result;
}
function Main(input){
input=input.trim().split(/\s+/).map(x=>x-0);
var N=input.shift();
var sorted=mergeSort(input);
var L=sorted[N/2-1][0];
var H=sorted[N/2][0];
var ans=[];
for(let i=0;i<N/2;i++){
let ID=sorted[i][1];
ans[ID]=H;
}
for(let i=N/2;i<N;i++){
let ID=sorted[i][1];
ans[ID]=L;
}
console.log(ans.join('\n'));
}
Main(require('fs').readFileSync('/dev/stdin','utf8')); | C++ | #include <stdio.h>
int main(){
for(int i = 0; i < 2000000; ++i) putchar('(');
int a, b, c, d;
while(1){
scanf("%d%d%d%d", &a, &b, &c, &d);
if(a == 0){ break; }
printf("%d+%d+%d+%d\n", a, b, c, d);
}
} | No | Do these codes solve the same problem?
Code 1: //添字付mergeSort
'use strict'
function mergeSort(arr){
var groups=[[]];
var n=0;
for(let i=0;i<arr.length;i++){
groups[n].push([arr[i],i]);
if(arr[i]>arr[i+1]){
n++;
groups[n]=[];
}
}
while(groups.length>1){//大
let newGroups=[];
while(groups.length>=2){//中
let g1=groups.pop();
g1.push([Infinity]);
let g2=groups.pop();
g2.push([Infinity]);
let merged=[];
let j=0,k=0;
while(j<g1.length-1||k<g2.length-1){//小
if(g1[j][0]<g2[k][0]){
merged[j+k]=g1[j];
j++;
}else{
merged[j+k]=g2[k];
k++;
}
}//小了
newGroups.push(merged);
}//中了
if(groups.length)
newGroups.push(groups[0]);
groups=newGroups;
}//大了
var result=groups[0];
return result;
}
function Main(input){
input=input.trim().split(/\s+/).map(x=>x-0);
var N=input.shift();
var sorted=mergeSort(input);
var L=sorted[N/2-1][0];
var H=sorted[N/2][0];
var ans=[];
for(let i=0;i<N/2;i++){
let ID=sorted[i][1];
ans[ID]=H;
}
for(let i=N/2;i<N;i++){
let ID=sorted[i][1];
ans[ID]=L;
}
console.log(ans.join('\n'));
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));
Code 2: #include <stdio.h>
int main(){
for(int i = 0; i < 2000000; ++i) putchar('(');
int a, b, c, d;
while(1){
scanf("%d%d%d%d", &a, &b, &c, &d);
if(a == 0){ break; }
printf("%d+%d+%d+%d\n", a, b, c, d);
}
} |
C++ | #include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx")
#define all(x) (x).begin(),(x).end()
#define rep(i,n) for(int (i)=0;i<(n);i++)
#define rrep(i,n) for(int (i)=1;i<=(n);i++)
#define REP(i,m,n) for(int (i)=(m);(i)<(n);(i)++)
#define MOD 1000000007
#define INF 1e18
#define int long long
#define endl "\n"
#define yorn(f) puts((f)?"Yes":"No")
#define YORN(f) puts((f)?"YES":"NO")
typedef long long ll;
typedef pair<int, int> P;
int gcd(int a,int b){return b?gcd(b,a%b):a;};
int lcm(int a,int b){return a/gcd(a,b)*b;};
int mod(int a,int b){return (a+b-1)/b;};
template<typename A, size_t N, typename T>
void Fill(A(&array)[N],const T &val){std::fill((T*)array,(T*)(array+N),val);}
template<class T>inline bool chmax(T& a,T b){if(a<b){a=b;return true;}return false;};
template<class T>inline bool chmin(T& a,T b){if(a>b){a=b;return true;}return false;};
signed main() {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(false);
//cout << fixed << setprecision(15);
string s, t;
cin >> s >> t;
int ans = 0;
rep(i, s.size()) {
if(s[i] != t[i]) ans++;
}
cout << ans << endl;
return 0;
} | Python | a, b, c, x, y = map(int, input().split())
ans1 = a * x + b * y
ans2 = min(x, y) * 2 * c + [a, b][max(x, y) == y] * abs(x - y)
ans3 = max(x, y) * 2 * c
print(min(ans1, ans2, ans3)) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx")
#define all(x) (x).begin(),(x).end()
#define rep(i,n) for(int (i)=0;i<(n);i++)
#define rrep(i,n) for(int (i)=1;i<=(n);i++)
#define REP(i,m,n) for(int (i)=(m);(i)<(n);(i)++)
#define MOD 1000000007
#define INF 1e18
#define int long long
#define endl "\n"
#define yorn(f) puts((f)?"Yes":"No")
#define YORN(f) puts((f)?"YES":"NO")
typedef long long ll;
typedef pair<int, int> P;
int gcd(int a,int b){return b?gcd(b,a%b):a;};
int lcm(int a,int b){return a/gcd(a,b)*b;};
int mod(int a,int b){return (a+b-1)/b;};
template<typename A, size_t N, typename T>
void Fill(A(&array)[N],const T &val){std::fill((T*)array,(T*)(array+N),val);}
template<class T>inline bool chmax(T& a,T b){if(a<b){a=b;return true;}return false;};
template<class T>inline bool chmin(T& a,T b){if(a>b){a=b;return true;}return false;};
signed main() {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(false);
//cout << fixed << setprecision(15);
string s, t;
cin >> s >> t;
int ans = 0;
rep(i, s.size()) {
if(s[i] != t[i]) ans++;
}
cout << ans << endl;
return 0;
}
Code 2: a, b, c, x, y = map(int, input().split())
ans1 = a * x + b * y
ans2 = min(x, y) * 2 * c + [a, b][max(x, y) == y] * abs(x - y)
ans3 = max(x, y) * 2 * c
print(min(ans1, ans2, ans3)) |
C++ | #include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int W, H, N, Q;
cin >> W >> H >> N;
vector<int> cx = { 0, W }, cy = { 0, H };
vector<int> ax(N), ay(N), bx(N), by(N);
for (int i = 0; i < N; ++i) {
cin >> ax[i] >> ay[i] >> bx[i] >> by[i];
cx.push_back(ax[i]);
cy.push_back(ay[i]);
cx.push_back(bx[i]);
cy.push_back(by[i]);
}
sort(cx.begin(), cx.end());
cx.erase(unique(cx.begin(), cx.end()), cx.end());
sort(cy.begin(), cy.end());
cy.erase(unique(cy.begin(), cy.end()), cy.end());
W = cx.size() - 1;
H = cy.size() - 1;
vector<vector<bool> > vertline(W + 1, vector<bool>(H)), horzline(W, vector<bool>(W + 1));
for (int i = 0; i < N; ++i) {
ax[i] = lower_bound(cx.begin(), cx.end(), ax[i]) - cx.begin();
ay[i] = lower_bound(cy.begin(), cy.end(), ay[i]) - cy.begin();
bx[i] = lower_bound(cx.begin(), cx.end(), bx[i]) - cx.begin();
by[i] = lower_bound(cy.begin(), cy.end(), by[i]) - cy.begin();
if (ax[i] > bx[i]) swap(ax[i], bx[i]);
if (ay[i] > by[i]) swap(ay[i], by[i]);
if (ax[i] == bx[i]) {
for (int j = ay[i]; j < by[i]; ++j) {
horzline[ax[i]][j] = true;
}
}
if (ay[i] == by[i]) {
for (int j = ax[i]; j < bx[i]; ++j) {
vertline[j][ay[i]] = true;
}
}
}
cin >> Q;
while (Q--) {
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
sx = lower_bound(cx.begin(), cx.end(), sx) - cx.begin() - 1;
sy = lower_bound(cy.begin(), cy.end(), sy) - cy.begin() - 1;
gx = lower_bound(cx.begin(), cx.end(), gx) - cx.begin() - 1;
gy = lower_bound(cy.begin(), cy.end(), gy) - cy.begin() - 1;
vector<vector<int> > d(W, vector<int>(H, -1));
d[sx][sy] = 0;
deque<pair<int, int> > que;
que.push_back(make_pair(sx, sy));
while (!que.empty()) {
pair<int, int> u = que.front(); que.pop_front();
int cur = d[u.first][u.second];
if (u.first >= 1 && (d[u.first - 1][u.second] == -1 || d[u.first - 1][u.second] == cur + 1)) {
if (horzline[u.first][u.second] && d[u.first - 1][u.second] == -1) {
d[u.first - 1][u.second] = cur + 1;
que.push_back(make_pair(u.first - 1, u.second));
}
if (!horzline[u.first][u.second]) {
d[u.first - 1][u.second] = cur;
que.push_front(make_pair(u.first - 1, u.second));
}
}
if (u.first < W - 1 && (d[u.first + 1][u.second] == -1 || d[u.first + 1][u.second] == cur + 1)) {
if (horzline[u.first + 1][u.second] && d[u.first + 1][u.second] == -1) {
d[u.first + 1][u.second] = cur + 1;
que.push_back(make_pair(u.first + 1, u.second));
}
if (!horzline[u.first + 1][u.second]) {
d[u.first + 1][u.second] = cur;
que.push_front(make_pair(u.first + 1, u.second));
}
}
if (u.second >= 1 && (d[u.first][u.second - 1] == -1 || d[u.first][u.second - 1] == cur + 1)) {
if (vertline[u.first][u.second] && d[u.first][u.second - 1] == -1) {
d[u.first][u.second - 1] = cur + 1;
que.push_back(make_pair(u.first, u.second - 1));
}
if (!vertline[u.first][u.second]) {
d[u.first][u.second - 1] = cur;
que.push_front(make_pair(u.first, u.second - 1));
}
}
if (u.second < H - 1 && (d[u.first][u.second + 1] == -1 || d[u.first][u.second + 1] == cur + 1)) {
if (vertline[u.first][u.second + 1] && d[u.first][u.second + 1] == -1) {
d[u.first][u.second + 1] = cur + 1;
que.push_back(make_pair(u.first, u.second + 1));
}
if (!vertline[u.first][u.second + 1]) {
d[u.first][u.second + 1] = cur;
que.push_front(make_pair(u.first, u.second + 1));
}
}
}
cout << d[gx][gy] << endl;
}
return 0;
}
| Python | from collections import defaultdict, deque
from bisect import bisect
W, H, M = map(int, input().split())
L = [list(map(int, input().split())) for i in range(M)]
XS = set([0, W])
YS = set([0, H])
for px, py, qx, qy in L:
XS.add(px); XS.add(qx)
YS.add(py); YS.add(qy)
X0 = sorted(XS)
Y0 = sorted(YS)
def convert(X0):
mp = {}
prv = -1
cur = 0
for x in X0:
mp[x] = cur
cur += 2
prv = x
cur -= 1
return mp, cur
XM, X = convert(X0)
YM, Y = convert(Y0)
C = [[0]*X for i in range(Y)]
D = [[-1]*X for i in range(Y)]
for i in range(Y):
C[i][0] = C[i][X-1] = 1
for i in range(X):
C[0][i] = C[Y-1][i] = 1
for px, py, qx, qy in L:
if px == qx:
if not py < qy:
py, qy = qy, py
x0 = XM[px]
y0 = YM[py]; y1 = YM[qy]
for i in range(y0, y1+1):
C[i][x0] = 1
else:
if not px < qx:
px, qx = qx, px
x0 = XM[px]; x1 = XM[qx]
y0 = YM[py]
for i in range(x0, x1+1):
C[y0][i] = 1
dd = ((-1, 0), (0, -1), (1, 0), (0, 1))
que = deque()
cur = 0
for i in range(Y):
for j in range(X):
if C[i][j] or D[i][j] != -1:
continue
D[i][j] = cur
que.append((j, i))
while que:
x, y = que.popleft()
for dx, dy in dd:
nx = x + dx; ny = y + dy
if C[ny][nx] or D[ny][nx] != -1:
continue
D[ny][nx] = cur
que.append((nx, ny))
cur += 1
N = cur
INF = 10**9
G = [[] for i in range(N)]
for i in range(1, Y-1):
for j in range(1, X-1):
a = D[i-1][j]; b = D[i+1][j]
if a != -1 != b != a:
G[a].append(b)
G[b].append(a)
a = D[i][j-1]; b = D[i][j+1]
if a != -1 != b != a:
G[a].append(b)
G[b].append(a)
Q = int(input())
for i in range(Q):
sx, sy, gx, gy = map(int, input().split())
x0 = (bisect(X0, sx)-1)*2+1; y0 = (bisect(Y0, sy-1)-1)*2+1
x1 = (bisect(X0, gx)-1)*2+1; y1 = (bisect(Y0, gy)-1)*2+1
assert D[y0][x0] != -1 and D[y1][x1] != -1
s = D[y0][x0]; t = D[y1][x1]
que = deque([s])
U = [-1]*N
U[s] = 0
while que:
v = que.popleft()
d = U[v]
for w in G[v]:
if U[w] != -1:
continue
U[w] = d+1
que.append(w)
print(U[t])
| Yes | Do these codes solve the same problem?
Code 1: #include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int W, H, N, Q;
cin >> W >> H >> N;
vector<int> cx = { 0, W }, cy = { 0, H };
vector<int> ax(N), ay(N), bx(N), by(N);
for (int i = 0; i < N; ++i) {
cin >> ax[i] >> ay[i] >> bx[i] >> by[i];
cx.push_back(ax[i]);
cy.push_back(ay[i]);
cx.push_back(bx[i]);
cy.push_back(by[i]);
}
sort(cx.begin(), cx.end());
cx.erase(unique(cx.begin(), cx.end()), cx.end());
sort(cy.begin(), cy.end());
cy.erase(unique(cy.begin(), cy.end()), cy.end());
W = cx.size() - 1;
H = cy.size() - 1;
vector<vector<bool> > vertline(W + 1, vector<bool>(H)), horzline(W, vector<bool>(W + 1));
for (int i = 0; i < N; ++i) {
ax[i] = lower_bound(cx.begin(), cx.end(), ax[i]) - cx.begin();
ay[i] = lower_bound(cy.begin(), cy.end(), ay[i]) - cy.begin();
bx[i] = lower_bound(cx.begin(), cx.end(), bx[i]) - cx.begin();
by[i] = lower_bound(cy.begin(), cy.end(), by[i]) - cy.begin();
if (ax[i] > bx[i]) swap(ax[i], bx[i]);
if (ay[i] > by[i]) swap(ay[i], by[i]);
if (ax[i] == bx[i]) {
for (int j = ay[i]; j < by[i]; ++j) {
horzline[ax[i]][j] = true;
}
}
if (ay[i] == by[i]) {
for (int j = ax[i]; j < bx[i]; ++j) {
vertline[j][ay[i]] = true;
}
}
}
cin >> Q;
while (Q--) {
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
sx = lower_bound(cx.begin(), cx.end(), sx) - cx.begin() - 1;
sy = lower_bound(cy.begin(), cy.end(), sy) - cy.begin() - 1;
gx = lower_bound(cx.begin(), cx.end(), gx) - cx.begin() - 1;
gy = lower_bound(cy.begin(), cy.end(), gy) - cy.begin() - 1;
vector<vector<int> > d(W, vector<int>(H, -1));
d[sx][sy] = 0;
deque<pair<int, int> > que;
que.push_back(make_pair(sx, sy));
while (!que.empty()) {
pair<int, int> u = que.front(); que.pop_front();
int cur = d[u.first][u.second];
if (u.first >= 1 && (d[u.first - 1][u.second] == -1 || d[u.first - 1][u.second] == cur + 1)) {
if (horzline[u.first][u.second] && d[u.first - 1][u.second] == -1) {
d[u.first - 1][u.second] = cur + 1;
que.push_back(make_pair(u.first - 1, u.second));
}
if (!horzline[u.first][u.second]) {
d[u.first - 1][u.second] = cur;
que.push_front(make_pair(u.first - 1, u.second));
}
}
if (u.first < W - 1 && (d[u.first + 1][u.second] == -1 || d[u.first + 1][u.second] == cur + 1)) {
if (horzline[u.first + 1][u.second] && d[u.first + 1][u.second] == -1) {
d[u.first + 1][u.second] = cur + 1;
que.push_back(make_pair(u.first + 1, u.second));
}
if (!horzline[u.first + 1][u.second]) {
d[u.first + 1][u.second] = cur;
que.push_front(make_pair(u.first + 1, u.second));
}
}
if (u.second >= 1 && (d[u.first][u.second - 1] == -1 || d[u.first][u.second - 1] == cur + 1)) {
if (vertline[u.first][u.second] && d[u.first][u.second - 1] == -1) {
d[u.first][u.second - 1] = cur + 1;
que.push_back(make_pair(u.first, u.second - 1));
}
if (!vertline[u.first][u.second]) {
d[u.first][u.second - 1] = cur;
que.push_front(make_pair(u.first, u.second - 1));
}
}
if (u.second < H - 1 && (d[u.first][u.second + 1] == -1 || d[u.first][u.second + 1] == cur + 1)) {
if (vertline[u.first][u.second + 1] && d[u.first][u.second + 1] == -1) {
d[u.first][u.second + 1] = cur + 1;
que.push_back(make_pair(u.first, u.second + 1));
}
if (!vertline[u.first][u.second + 1]) {
d[u.first][u.second + 1] = cur;
que.push_front(make_pair(u.first, u.second + 1));
}
}
}
cout << d[gx][gy] << endl;
}
return 0;
}
Code 2: from collections import defaultdict, deque
from bisect import bisect
W, H, M = map(int, input().split())
L = [list(map(int, input().split())) for i in range(M)]
XS = set([0, W])
YS = set([0, H])
for px, py, qx, qy in L:
XS.add(px); XS.add(qx)
YS.add(py); YS.add(qy)
X0 = sorted(XS)
Y0 = sorted(YS)
def convert(X0):
mp = {}
prv = -1
cur = 0
for x in X0:
mp[x] = cur
cur += 2
prv = x
cur -= 1
return mp, cur
XM, X = convert(X0)
YM, Y = convert(Y0)
C = [[0]*X for i in range(Y)]
D = [[-1]*X for i in range(Y)]
for i in range(Y):
C[i][0] = C[i][X-1] = 1
for i in range(X):
C[0][i] = C[Y-1][i] = 1
for px, py, qx, qy in L:
if px == qx:
if not py < qy:
py, qy = qy, py
x0 = XM[px]
y0 = YM[py]; y1 = YM[qy]
for i in range(y0, y1+1):
C[i][x0] = 1
else:
if not px < qx:
px, qx = qx, px
x0 = XM[px]; x1 = XM[qx]
y0 = YM[py]
for i in range(x0, x1+1):
C[y0][i] = 1
dd = ((-1, 0), (0, -1), (1, 0), (0, 1))
que = deque()
cur = 0
for i in range(Y):
for j in range(X):
if C[i][j] or D[i][j] != -1:
continue
D[i][j] = cur
que.append((j, i))
while que:
x, y = que.popleft()
for dx, dy in dd:
nx = x + dx; ny = y + dy
if C[ny][nx] or D[ny][nx] != -1:
continue
D[ny][nx] = cur
que.append((nx, ny))
cur += 1
N = cur
INF = 10**9
G = [[] for i in range(N)]
for i in range(1, Y-1):
for j in range(1, X-1):
a = D[i-1][j]; b = D[i+1][j]
if a != -1 != b != a:
G[a].append(b)
G[b].append(a)
a = D[i][j-1]; b = D[i][j+1]
if a != -1 != b != a:
G[a].append(b)
G[b].append(a)
Q = int(input())
for i in range(Q):
sx, sy, gx, gy = map(int, input().split())
x0 = (bisect(X0, sx)-1)*2+1; y0 = (bisect(Y0, sy-1)-1)*2+1
x1 = (bisect(X0, gx)-1)*2+1; y1 = (bisect(Y0, gy)-1)*2+1
assert D[y0][x0] != -1 and D[y1][x1] != -1
s = D[y0][x0]; t = D[y1][x1]
que = deque([s])
U = [-1]*N
U[s] = 0
while que:
v = que.popleft()
d = U[v]
for w in G[v]:
if U[w] != -1:
continue
U[w] = d+1
que.append(w)
print(U[t])
|
JavaScript | var code = require('fs').readFileSync('/dev/stdin','utf8').trim()
var prePattern = code[0]
var sNum = 0
var bNum = 0
var total = 0
if(code[0] === '>') {
code = '<' + code
}
for(var i=0;i<code.length;) {
for(;i<code.length;i++) {
if(code[i] !== '<') break
sNum += 1
}
for(;i<code.length;i++) {
if(code[i] !== '>') break
bNum += 1
}
if(sNum > bNum) {
for(var j=0;j<=sNum;j++) total += j
for(var j=0;j<bNum;j++) total += j
} else {
for(var j=0;j<sNum;j++) total += j
for(var j=0;j<=bNum;j++) total += j
}
sNum = 0
bNum = 0
}
console.log(total)
| Kotlin | fun main(args: Array<String>) {
val s = readLine()!!
val n = s.length + 1
val ansArray = Array(n) { 0L }
var cur = 2L
var j = 1
if (s.first() == '<') {
ansArray[0] = 0
ansArray[1] = 1
cur = 2L
j = 1
while (true) {
if (j >= s.length || s[j] != '<') break
ansArray[j + 1] = Math.max(cur, ansArray[j + 1])
j++
cur++
}
}
if (s.last() == '>') {
ansArray[n - 1] = Math.max(0,ansArray[n - 1])
ansArray[n - 2] = Math.max(1,ansArray[n - 2])
cur = 2L
j = s.length - 2
while (true) {
if (j < 0 || s[j] != '>') break
ansArray[j] = Math.max(cur, ansArray[j])
j--
cur++
}
}
for (i in 0..(s.length - 2)) {
if (s[i] == '>' && s[i + 1] == '<') {
ansArray[i] = Math.max(1, ansArray[i])
ansArray[i + 1] = Math.max(0, ansArray[i + 1])
ansArray[i + 2] = Math.max(1, ansArray[i + 2])
cur = 2L
j = i - 1
while (true) {
if (j < 0 || s[j] != '>') break
ansArray[j] = Math.max(cur, ansArray[j])
j--
cur++
}
cur = 2L
j = i + 2
while (true) {
if (j >= s.length || s[j] != '<') break
ansArray[j + 1] = Math.max(cur, ansArray[j + 1])
j++
cur++
}
}
}
println(ansArray.sum())
} | Yes | Do these codes solve the same problem?
Code 1: var code = require('fs').readFileSync('/dev/stdin','utf8').trim()
var prePattern = code[0]
var sNum = 0
var bNum = 0
var total = 0
if(code[0] === '>') {
code = '<' + code
}
for(var i=0;i<code.length;) {
for(;i<code.length;i++) {
if(code[i] !== '<') break
sNum += 1
}
for(;i<code.length;i++) {
if(code[i] !== '>') break
bNum += 1
}
if(sNum > bNum) {
for(var j=0;j<=sNum;j++) total += j
for(var j=0;j<bNum;j++) total += j
} else {
for(var j=0;j<sNum;j++) total += j
for(var j=0;j<=bNum;j++) total += j
}
sNum = 0
bNum = 0
}
console.log(total)
Code 2: fun main(args: Array<String>) {
val s = readLine()!!
val n = s.length + 1
val ansArray = Array(n) { 0L }
var cur = 2L
var j = 1
if (s.first() == '<') {
ansArray[0] = 0
ansArray[1] = 1
cur = 2L
j = 1
while (true) {
if (j >= s.length || s[j] != '<') break
ansArray[j + 1] = Math.max(cur, ansArray[j + 1])
j++
cur++
}
}
if (s.last() == '>') {
ansArray[n - 1] = Math.max(0,ansArray[n - 1])
ansArray[n - 2] = Math.max(1,ansArray[n - 2])
cur = 2L
j = s.length - 2
while (true) {
if (j < 0 || s[j] != '>') break
ansArray[j] = Math.max(cur, ansArray[j])
j--
cur++
}
}
for (i in 0..(s.length - 2)) {
if (s[i] == '>' && s[i + 1] == '<') {
ansArray[i] = Math.max(1, ansArray[i])
ansArray[i + 1] = Math.max(0, ansArray[i + 1])
ansArray[i + 2] = Math.max(1, ansArray[i + 2])
cur = 2L
j = i - 1
while (true) {
if (j < 0 || s[j] != '>') break
ansArray[j] = Math.max(cur, ansArray[j])
j--
cur++
}
cur = 2L
j = i + 2
while (true) {
if (j >= s.length || s[j] != '<') break
ansArray[j + 1] = Math.max(cur, ansArray[j + 1])
j++
cur++
}
}
}
println(ansArray.sum())
} |
Python | n=int(input())
print(n//2+n%2) | C++ | /*
题意是求一个序列中"所有子序列的中位数"所组成的序列的中位数
看题解了,完全不会。https://www.cnblogs.com/quzhizhou/p/9535597.html
首先我们先二分最后序列的中位数。设tot为中位数 >= mid的区间个数,若中位数序列的中位数 >= mid,
则有tot >= n(n+1)/4。
我们另外构造一个序列b[i], 当a[i]>=mid时b[i]=1, 否则bi=-1.
那么若区间[l, r]的中位数 >= mid, 则b[l]+...+b[r] >= 0.
于是我们求出序列b[i]的前缀和序列sum[i],那么问题就变成了求满足l <= r且sum[r]-sum[l-1]>=0的数对(l,r)数量(0<=l,r<=n),
这个问题可以用与求逆序对数量相似的方法解决. 树状数组即可.
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int NN = 110000;
int a[NN], l, r, n, mid, ans;
int s[NN * 2];
//树状数组,注意,[-n-1, n], 为了让每一个存的值都是>0, 都加上n即可(因为树状数组不能从0开始)
//所以开双倍空间给数组
int lowbit(int x){
return x & (-x);
}
void add1(int x, int k){
while (x <= n * 2){
s[x] += k;
x += lowbit(x);
}
}
int getsum(int x){
int sum = 0;
while (x > 0){
sum += s[x];
x -= lowbit(x);
}
return sum;
}
int check(int mid){
memset(s, 0, sizeof(s)); //树状数组清0
//for(int i=1;i<=2*n;i++)s[i]=0;
//与求逆序对的方法相同
add1(n, 1); //因为在每个数的基础上都加了n,所以这句话相当于在和等于0的点+1
int sum = 0;
ll tmp = 0; //注意,tmp也不必须是ll,算清楚,以后要是不仔细想一律给ll
for (int i=1; i<=n; i++){
if (a[i] >= mid) sum++;
else sum--;
tmp += getsum(sum + n);
add1(sum + n, 1);
}
long long nn = ((long long) n) * (n + 1) / 4; //注意!nn必须给long long, 右边的long long也必须打!!!!!!!不然wa!!!!
if (tmp >= nn) return true;
else return false;
}
int main(){
//freopen("atcoderarc101d.in", "r", stdin);
scanf("%d", &n);
l = 0x7fffffff; r = 0;
for (int i=1; i<=n; i++){
scanf("%d", &a[i]);
if (a[i] >= r) r = a[i];
if (a[i] <= l) l = a[i];
}
//printf("%d %d\n", l, r);
while (l <= r){
mid = (l + r) / 2;
if (check(mid)){
ans = mid;
l = mid + 1;
} else r = mid-1;
}
printf("%d", ans);
return 0;
} | No | Do these codes solve the same problem?
Code 1: n=int(input())
print(n//2+n%2)
Code 2: /*
题意是求一个序列中"所有子序列的中位数"所组成的序列的中位数
看题解了,完全不会。https://www.cnblogs.com/quzhizhou/p/9535597.html
首先我们先二分最后序列的中位数。设tot为中位数 >= mid的区间个数,若中位数序列的中位数 >= mid,
则有tot >= n(n+1)/4。
我们另外构造一个序列b[i], 当a[i]>=mid时b[i]=1, 否则bi=-1.
那么若区间[l, r]的中位数 >= mid, 则b[l]+...+b[r] >= 0.
于是我们求出序列b[i]的前缀和序列sum[i],那么问题就变成了求满足l <= r且sum[r]-sum[l-1]>=0的数对(l,r)数量(0<=l,r<=n),
这个问题可以用与求逆序对数量相似的方法解决. 树状数组即可.
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int NN = 110000;
int a[NN], l, r, n, mid, ans;
int s[NN * 2];
//树状数组,注意,[-n-1, n], 为了让每一个存的值都是>0, 都加上n即可(因为树状数组不能从0开始)
//所以开双倍空间给数组
int lowbit(int x){
return x & (-x);
}
void add1(int x, int k){
while (x <= n * 2){
s[x] += k;
x += lowbit(x);
}
}
int getsum(int x){
int sum = 0;
while (x > 0){
sum += s[x];
x -= lowbit(x);
}
return sum;
}
int check(int mid){
memset(s, 0, sizeof(s)); //树状数组清0
//for(int i=1;i<=2*n;i++)s[i]=0;
//与求逆序对的方法相同
add1(n, 1); //因为在每个数的基础上都加了n,所以这句话相当于在和等于0的点+1
int sum = 0;
ll tmp = 0; //注意,tmp也不必须是ll,算清楚,以后要是不仔细想一律给ll
for (int i=1; i<=n; i++){
if (a[i] >= mid) sum++;
else sum--;
tmp += getsum(sum + n);
add1(sum + n, 1);
}
long long nn = ((long long) n) * (n + 1) / 4; //注意!nn必须给long long, 右边的long long也必须打!!!!!!!不然wa!!!!
if (tmp >= nn) return true;
else return false;
}
int main(){
//freopen("atcoderarc101d.in", "r", stdin);
scanf("%d", &n);
l = 0x7fffffff; r = 0;
for (int i=1; i<=n; i++){
scanf("%d", &a[i]);
if (a[i] >= r) r = a[i];
if (a[i] <= l) l = a[i];
}
//printf("%d %d\n", l, r);
while (l <= r){
mid = (l + r) / 2;
if (check(mid)){
ans = mid;
l = mid + 1;
} else r = mid-1;
}
printf("%d", ans);
return 0;
} |
C++ | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using pi = pair<int,int>;
#define mp make_pair
#define pb push_back
#define rsz resize
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
void setIO(string name = ""){
freopen((name+".in").c_str(), "r", stdin);
freopen((name+".out").c_str(), "w", stdout);
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
// setIO();
int cnt = 0;
int n; long double d;
cin >> n >> d;
for(int i{}; i<n; i++){
long double x,y; cin >> x >> y;
if(sqrt((x*x)+(y*y))<=d){
cnt++;
}
}
cout << cnt << "\n";
}
| Python | import sys
input=sys.stdin.readline
N,D=map(int,input().split())
X = (N//(2*D+1))
Y = (N%(2*D+1))
ans = X if Y==0 else X+1
print(ans) | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using pi = pair<int,int>;
#define mp make_pair
#define pb push_back
#define rsz resize
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
void setIO(string name = ""){
freopen((name+".in").c_str(), "r", stdin);
freopen((name+".out").c_str(), "w", stdout);
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
// setIO();
int cnt = 0;
int n; long double d;
cin >> n >> d;
for(int i{}; i<n; i++){
long double x,y; cin >> x >> y;
if(sqrt((x*x)+(y*y))<=d){
cnt++;
}
}
cout << cnt << "\n";
}
Code 2: import sys
input=sys.stdin.readline
N,D=map(int,input().split())
X = (N//(2*D+1))
Y = (N%(2*D+1))
ans = X if Y==0 else X+1
print(ans) |
Python | N, M = map(int, input().split())
D = [[0]*(N+1) for i in range(M)]
cnts = [0]*M
for i in range(N):
v = int(input())
cnts[v-1] += 1
D[v-1][i+1] = 1
for i in range(M):
d = D[i]
for j in range(1, N+1):
d[j] += d[j-1]
memo = [None]*(2**M)
memo[2**M-1] = 0
def dfs(state, idx):
if memo[state] is not None:
return memo[state]
res = N
for i in range(M):
if state & (1 << i) == 0:
need = cnts[i] - (D[i][cnts[i] + idx] - D[i][idx])
res = min(res, need + dfs(state | (1 << i), idx + cnts[i]))
memo[state] = res
return res
print(dfs(0, 0)) | Java | import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static final int BIG_NUM = 2000000000;
public static final int MOD = 1000000007;
public static final long HUGE_NUM = 99999999999999999L;
public static final double EPS = 0.000000001;
public static final int SIZE = 21;
@SuppressWarnings("unchecked")
public static void main(String[] args) {
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int POW[] = new int[SIZE];
POW[0] = 1;
for(int i = 1; i < SIZE; i++){
POW[i] = POW[i-1]*2;
}
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
//種類の個数を記録
int table[] = new int[M];
for(int i = 0; i < table.length; i++){
table[i] = 0;
}
//移動するぬいぐるみの個数を求めるための累積和テーブル
int ruisekiwa[][] = new int[M][N];
for(int row = 0; row < M; row++){
for(int col = 0; col < N; col++){
ruisekiwa[row][col] = 0;
}
}
int tmp;
for(int i = 0; i < N; i++){
tmp = scanner.nextInt();
tmp--;
table[tmp]++;
ruisekiwa[tmp][i] += 1;
}
for(int row = 0; row < M; row++){
for(int col = 1; col < N; col++){
ruisekiwa[row][col] += ruisekiwa[row][col-1];
}
}
int dp[] = new int[POW[M]];
dp[0] = 0;
for(int state = 1; state < POW[M]; state++){
dp[state] = BIG_NUM;
}
int left,right;
int tmp_sum,next_state,add,loc;
for(int state = 0; state < POW[M]-1; state++){
tmp_sum = 0;
//配置済のぬいぐるみの個数を求める
for(int loop = 0; loop < M; loop++){
if((state & POW[loop]) != 0){
tmp_sum += table[loop];
}
}
left = tmp_sum;
for(int loop = 0; loop < M; loop++){
if((state & POW[loop]) == 0){ //次に置くぬいぐるみ
right = tmp_sum+table[loop]-1;
//範囲より左
if(left == 0){
add = 0;
}else{
add = ruisekiwa[loop][left-1];
}
//範囲より右
add += (ruisekiwa[loop][N-1]-ruisekiwa[loop][right]);
next_state = state+POW[loop];
dp[next_state] = Math.min(dp[next_state],dp[state]+add);
}
}
}
System.out.println(dp[POW[M]-1]);
}
}
class UTIL{
//String→intへ変換
public static int getNUM(String tmp_str){
return Integer.parseInt(tmp_str);
}
//文字が半角数字か判定する関数
public static boolean isNumber(String tmp_str){
if(tmp_str == null || tmp_str.length() == 0){
return false;
}
Pattern pattern = Pattern.compile("\\A[0-9]+\\z");
Matcher matcher = pattern.matcher(tmp_str);
return matcher.matches();
}
}
| Yes | Do these codes solve the same problem?
Code 1: N, M = map(int, input().split())
D = [[0]*(N+1) for i in range(M)]
cnts = [0]*M
for i in range(N):
v = int(input())
cnts[v-1] += 1
D[v-1][i+1] = 1
for i in range(M):
d = D[i]
for j in range(1, N+1):
d[j] += d[j-1]
memo = [None]*(2**M)
memo[2**M-1] = 0
def dfs(state, idx):
if memo[state] is not None:
return memo[state]
res = N
for i in range(M):
if state & (1 << i) == 0:
need = cnts[i] - (D[i][cnts[i] + idx] - D[i][idx])
res = min(res, need + dfs(state | (1 << i), idx + cnts[i]))
memo[state] = res
return res
print(dfs(0, 0))
Code 2: import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static final int BIG_NUM = 2000000000;
public static final int MOD = 1000000007;
public static final long HUGE_NUM = 99999999999999999L;
public static final double EPS = 0.000000001;
public static final int SIZE = 21;
@SuppressWarnings("unchecked")
public static void main(String[] args) {
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int POW[] = new int[SIZE];
POW[0] = 1;
for(int i = 1; i < SIZE; i++){
POW[i] = POW[i-1]*2;
}
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
//種類の個数を記録
int table[] = new int[M];
for(int i = 0; i < table.length; i++){
table[i] = 0;
}
//移動するぬいぐるみの個数を求めるための累積和テーブル
int ruisekiwa[][] = new int[M][N];
for(int row = 0; row < M; row++){
for(int col = 0; col < N; col++){
ruisekiwa[row][col] = 0;
}
}
int tmp;
for(int i = 0; i < N; i++){
tmp = scanner.nextInt();
tmp--;
table[tmp]++;
ruisekiwa[tmp][i] += 1;
}
for(int row = 0; row < M; row++){
for(int col = 1; col < N; col++){
ruisekiwa[row][col] += ruisekiwa[row][col-1];
}
}
int dp[] = new int[POW[M]];
dp[0] = 0;
for(int state = 1; state < POW[M]; state++){
dp[state] = BIG_NUM;
}
int left,right;
int tmp_sum,next_state,add,loc;
for(int state = 0; state < POW[M]-1; state++){
tmp_sum = 0;
//配置済のぬいぐるみの個数を求める
for(int loop = 0; loop < M; loop++){
if((state & POW[loop]) != 0){
tmp_sum += table[loop];
}
}
left = tmp_sum;
for(int loop = 0; loop < M; loop++){
if((state & POW[loop]) == 0){ //次に置くぬいぐるみ
right = tmp_sum+table[loop]-1;
//範囲より左
if(left == 0){
add = 0;
}else{
add = ruisekiwa[loop][left-1];
}
//範囲より右
add += (ruisekiwa[loop][N-1]-ruisekiwa[loop][right]);
next_state = state+POW[loop];
dp[next_state] = Math.min(dp[next_state],dp[state]+add);
}
}
}
System.out.println(dp[POW[M]-1]);
}
}
class UTIL{
//String→intへ変換
public static int getNUM(String tmp_str){
return Integer.parseInt(tmp_str);
}
//文字が半角数字か判定する関数
public static boolean isNumber(String tmp_str){
if(tmp_str == null || tmp_str.length() == 0){
return false;
}
Pattern pattern = Pattern.compile("\\A[0-9]+\\z");
Matcher matcher = pattern.matcher(tmp_str);
return matcher.matches();
}
}
|
Python | n=int(input())
b=list(map(int,input().split()))
a=[float('Inf')]*n
for i,num in enumerate(b):
if n>i:
a[i]=min(a[i],num)
a[i+1]=num
print(sum(a)) | 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.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author osiruko
*/
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);
CDivideTheProblems solver = new CDivideTheProblems();
solver.solve(1, in, out);
out.close();
}
static class CDivideTheProblems {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int a[] = in.readIntArray(n);
Arrays.sort(a);
out.printLine(Math.abs(a[n / 2] - a[n / 2 - 1]));
}
}
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 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(int i) {
writer.println(i);
}
}
}
| No | Do these codes solve the same problem?
Code 1: n=int(input())
b=list(map(int,input().split()))
a=[float('Inf')]*n
for i,num in enumerate(b):
if n>i:
a[i]=min(a[i],num)
a[i+1]=num
print(sum(a))
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.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author osiruko
*/
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);
CDivideTheProblems solver = new CDivideTheProblems();
solver.solve(1, in, out);
out.close();
}
static class CDivideTheProblems {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int a[] = in.readIntArray(n);
Arrays.sort(a);
out.printLine(Math.abs(a[n / 2] - a[n / 2 - 1]));
}
}
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 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(int i) {
writer.println(i);
}
}
}
|
C++ | #include <bits/stdc++.h>
#define f(i,j,k) for(int i=j;i<k;i++)
using namespace std;
int main(){
long long n,v,ans=0;
map <long long,long long> b;
cin>>n>>v;
long long a[4][n];
f(i,0,4){
f(j,0,n){
cin>>a[i][j];
}
}
f(i,0,n){
f(j,0,n){
b[a[0][i]+a[1][j]]++;
}
}
f(i,0,n){
f(j,0,n){
ans+=b[v-a[2][i]-a[3][j]];
}
}
cout<<ans<<endl;
return 0;
}
| C# | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Linq;
class Program
{
static void Main()
{
int[] inputs = Console.ReadLine().Split().Select(int.Parse).ToArray();
Array.Sort(inputs);
long ans = inputs[0] * inputs[1] / 2;
Console.WriteLine(ans);
}
} | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
#define f(i,j,k) for(int i=j;i<k;i++)
using namespace std;
int main(){
long long n,v,ans=0;
map <long long,long long> b;
cin>>n>>v;
long long a[4][n];
f(i,0,4){
f(j,0,n){
cin>>a[i][j];
}
}
f(i,0,n){
f(j,0,n){
b[a[0][i]+a[1][j]]++;
}
}
f(i,0,n){
f(j,0,n){
ans+=b[v-a[2][i]-a[3][j]];
}
}
cout<<ans<<endl;
return 0;
}
Code 2: using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Linq;
class Program
{
static void Main()
{
int[] inputs = Console.ReadLine().Split().Select(int.Parse).ToArray();
Array.Sort(inputs);
long ans = inputs[0] * inputs[1] / 2;
Console.WriteLine(ans);
}
} |
Java | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author osiruko
*/
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);
CDiceAndCoin solver = new CDiceAndCoin();
solver.solve(1, in, out);
out.close();
}
static class CDiceAndCoin {
public void solve(int testNumber, InputReader in, OutputWriter out) {
float n = in.readInt();
int k = in.readInt();
int count = 0;
double sum = 0.0;
for (int i = 1; i < n + 1; i++) {
for (int j = i; j < k; j += j) {
count++;
}
sum += (1.0 / n) * Math.pow(0.5, count);
count = 0;
}
out.printLine(sum);
}
}
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 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 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 print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Python | import itertools
N = int(input())
S = input()
S = [int(x) for x in S]
left_index = [[-1] * (N+1) for _ in range(10)]
for i,x in enumerate(S,1):
for j in range(10):
left_index[j][i] = left_index[j][i-1]
left_index[x][i] = i
answer = 0
for a,b,c in itertools.product(range(10),repeat=3):
i = N
bl = True
for x in [a,b,c]:
i = left_index[x][i] - 1
if i < -1:
bl = False
break
if bl:
answer += 1
print(answer) | No | Do these codes solve the same problem?
Code 1: import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author osiruko
*/
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);
CDiceAndCoin solver = new CDiceAndCoin();
solver.solve(1, in, out);
out.close();
}
static class CDiceAndCoin {
public void solve(int testNumber, InputReader in, OutputWriter out) {
float n = in.readInt();
int k = in.readInt();
int count = 0;
double sum = 0.0;
for (int i = 1; i < n + 1; i++) {
for (int j = i; j < k; j += j) {
count++;
}
sum += (1.0 / n) * Math.pow(0.5, count);
count = 0;
}
out.printLine(sum);
}
}
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 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 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 print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
Code 2: import itertools
N = int(input())
S = input()
S = [int(x) for x in S]
left_index = [[-1] * (N+1) for _ in range(10)]
for i,x in enumerate(S,1):
for j in range(10):
left_index[j][i] = left_index[j][i-1]
left_index[x][i] = i
answer = 0
for a,b,c in itertools.product(range(10),repeat=3):
i = N
bl = True
for x in [a,b,c]:
i = left_index[x][i] - 1
if i < -1:
bl = False
break
if bl:
answer += 1
print(answer) |
JavaScript | "use strict";
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function main(input) {
var lines = input.split('\n');
var N = parseInt(lines[0]);
var hsTmp = splitNum(lines[1]).slice(0, N);
var hhs = [hsTmp];
var res = 0;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = range(0, 101)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var h = _step.value;
var newHhs = [];
for (var _i = 0; _i < hhs.length; _i++) {
var hs = hhs[_i];
var l = hs.length;
var last = 0;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = range(0, l)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var i = _step2.value;
if (hs[i] === h) {
// split here
if (last < i) {
newHhs.push(hs.slice(last, i));
}
last = i + 1;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
if (last < l) {
newHhs.push(hs.slice(last));
}
if (h > 0) res++;
}
hhs = newHhs;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
console.log(res);
}
var P = 1e9 + 7;
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
function splitNum(line) {
return (Array.isArray(line) ? line : line.split(/\s+/)).map(function (n) {
return parseInt(n);
});
}
/**
* Iterates over integers in [start, end).
*/
function* range(start, end) {
for (var i = start; i < end; i++) {
yield i;
}
}
/**
* Iterates over integers in [end, start) in desc order.
*/
function* rangeRev(start, end) {
for (var i = start - 1; i >= end; i--) {
yield i;
}
}
/**
* Runs a recursive function expressed as a generator function.
*/
function runRecursive(func) {
// 最終結果を受け取るオブジェクトを用意
var rootCaller = {
lastReturnValue: null
}; // 自前のコールスタックを用意
var callStack = []; // 最初の関数呼び出しを追加
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
callStack.push({
iterator: func.apply(void 0, args),
lastReturnValue: null,
caller: rootCaller
});
while (callStack.length > 0) {
var stackFrame = callStack[callStack.length - 1];
var iterator = stackFrame.iterator,
lastReturnValue = stackFrame.lastReturnValue,
caller = stackFrame.caller; // 関数の実行を再開
var _iterator$next = iterator.next(lastReturnValue),
value = _iterator$next.value,
done = _iterator$next.done;
if (done) {
// 関数がreturnしたので親に返り値を記録
caller.lastReturnValue = value;
callStack.pop();
} else {
// 関数がyieldした(valueは再帰呼び出しの引数リスト)
callStack.push({
iterator: func.apply(void 0, _toConsumableArray(value)),
lastReturnValue: null,
caller: stackFrame
});
}
}
return rootCaller.lastReturnValue;
}
| C# | using System;
using System.Collections.Generic;
using System.Text;
namespace AtTest.ABC116
{
class C
{
static void Main(string[] args)
{
Method(args);
Console.ReadLine();
}
static void Method(string[] args)
{
int n = ReadInt();
int[] hs = ReadInts();
int cnt = 0;
int remain = n;
while (remain > 0)
{
remain = 0;
bool removing = false;
for (int i = 0; i < n; i++)
{
if (hs[i] > 0)
{
if (!removing)
{
removing = true;
cnt++;
}
hs[i]--;
remain++;
}
else
{
removing = false;
}
}
}
Console.WriteLine(cnt);
}
private static string Read() { return Console.ReadLine(); }
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: "use strict";
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function main(input) {
var lines = input.split('\n');
var N = parseInt(lines[0]);
var hsTmp = splitNum(lines[1]).slice(0, N);
var hhs = [hsTmp];
var res = 0;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = range(0, 101)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var h = _step.value;
var newHhs = [];
for (var _i = 0; _i < hhs.length; _i++) {
var hs = hhs[_i];
var l = hs.length;
var last = 0;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = range(0, l)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var i = _step2.value;
if (hs[i] === h) {
// split here
if (last < i) {
newHhs.push(hs.slice(last, i));
}
last = i + 1;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
if (last < l) {
newHhs.push(hs.slice(last));
}
if (h > 0) res++;
}
hhs = newHhs;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
console.log(res);
}
var P = 1e9 + 7;
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
function splitNum(line) {
return (Array.isArray(line) ? line : line.split(/\s+/)).map(function (n) {
return parseInt(n);
});
}
/**
* Iterates over integers in [start, end).
*/
function* range(start, end) {
for (var i = start; i < end; i++) {
yield i;
}
}
/**
* Iterates over integers in [end, start) in desc order.
*/
function* rangeRev(start, end) {
for (var i = start - 1; i >= end; i--) {
yield i;
}
}
/**
* Runs a recursive function expressed as a generator function.
*/
function runRecursive(func) {
// 最終結果を受け取るオブジェクトを用意
var rootCaller = {
lastReturnValue: null
}; // 自前のコールスタックを用意
var callStack = []; // 最初の関数呼び出しを追加
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
callStack.push({
iterator: func.apply(void 0, args),
lastReturnValue: null,
caller: rootCaller
});
while (callStack.length > 0) {
var stackFrame = callStack[callStack.length - 1];
var iterator = stackFrame.iterator,
lastReturnValue = stackFrame.lastReturnValue,
caller = stackFrame.caller; // 関数の実行を再開
var _iterator$next = iterator.next(lastReturnValue),
value = _iterator$next.value,
done = _iterator$next.done;
if (done) {
// 関数がreturnしたので親に返り値を記録
caller.lastReturnValue = value;
callStack.pop();
} else {
// 関数がyieldした(valueは再帰呼び出しの引数リスト)
callStack.push({
iterator: func.apply(void 0, _toConsumableArray(value)),
lastReturnValue: null,
caller: stackFrame
});
}
}
return rootCaller.lastReturnValue;
}
Code 2: using System;
using System.Collections.Generic;
using System.Text;
namespace AtTest.ABC116
{
class C
{
static void Main(string[] args)
{
Method(args);
Console.ReadLine();
}
static void Method(string[] args)
{
int n = ReadInt();
int[] hs = ReadInts();
int cnt = 0;
int remain = n;
while (remain > 0)
{
remain = 0;
bool removing = false;
for (int i = 0; i < n; i++)
{
if (hs[i] > 0)
{
if (!removing)
{
removing = true;
cnt++;
}
hs[i]--;
remain++;
}
else
{
removing = false;
}
}
}
Console.WriteLine(cnt);
}
private static string Read() { return Console.ReadLine(); }
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 <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for(int i=0; i<n; i++) {
int nx=0,ny=0,max=0,ax=0,ay=0;
while(1) {
int x,y,z;
cin >> x >> y;
if(x==0 && y==0) break;
nx+=x;
ny+=y;
z=nx*nx+ny*ny;
if(z>=max) {
if(z==max) {
if(nx>ax) {
max=z;
ax=nx;
ay=ny;
}
} else {
max=z;
ax=nx;
ay=ny;
}
}
}
cout << ax << " " << ay << endl;
}
return 0;
}
| Java | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int z=0;z<n;z++){
int maxx = 0;
int maxy = 0;
int prex = 0;
int prey = 0;
double d = 0;
int x, y;
while(true){
x = sc.nextInt();
y = sc.nextInt();
if(x==0 && y==0) break;
x += prex;
y += prey;
if(d<Math.sqrt(x*x+y*y) || (d==Math.sqrt(x*x+y*y) && x>maxx)){
d = Math.sqrt(x*x+y*y);
maxx = x;
maxy = y;
}
prex = x;
prey = y;
}
System.out.println(maxx + " " + maxy);
}
}
} | Yes | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for(int i=0; i<n; i++) {
int nx=0,ny=0,max=0,ax=0,ay=0;
while(1) {
int x,y,z;
cin >> x >> y;
if(x==0 && y==0) break;
nx+=x;
ny+=y;
z=nx*nx+ny*ny;
if(z>=max) {
if(z==max) {
if(nx>ax) {
max=z;
ax=nx;
ay=ny;
}
} else {
max=z;
ax=nx;
ay=ny;
}
}
}
cout << ax << " " << ay << endl;
}
return 0;
}
Code 2: import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int z=0;z<n;z++){
int maxx = 0;
int maxy = 0;
int prex = 0;
int prey = 0;
double d = 0;
int x, y;
while(true){
x = sc.nextInt();
y = sc.nextInt();
if(x==0 && y==0) break;
x += prex;
y += prey;
if(d<Math.sqrt(x*x+y*y) || (d==Math.sqrt(x*x+y*y) && x>maxx)){
d = Math.sqrt(x*x+y*y);
maxx = x;
maxy = y;
}
prex = x;
prey = y;
}
System.out.println(maxx + " " + maxy);
}
}
} |
C++ | #include <bits/stdc++.h>
using namespace std;
int main() {
bool p[100001];
int c[100001], q, l, r;
for (int i = 0; i < 100001; i++)
{
p[i] = false;
c[i] = 0;
}
for (int i = 2; i < 100001; i++)
{
if (p[i] == false)
for (int j = i * 2; j < 100001; j += i) p[j] = true;
}
for (int i = 3; i < 100001; i++)
if (p[i] == false && p[(i + 1) / 2] == false) c[i]++;
for (int i = 3; i < 100001; i++) c[i] += c[i - 1];
cin >> q;
for (int i = 0; i < q; i++)
{
cin >> l >> r;
cout << c[r] - c[l - 1] << endl;
}
} | Python | from sys import stdin
#, setrecursionlimit, stdout
#setrecursionlimit(1000000)
#from collections import deque
#from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline().rstrip()
def lsi(): return list(si())
#mod=1000000007
res=['Yes', 'No']
############# CODE STARTS HERE #############
test_case=1
while test_case:
test_case-=1
cnt=[0]*100005
n=ii()
a=li()
for i in a:
cnt[i]+=1
s=sum(a)
for _ in range(ii()):
x, y=mi()
s+=(y-x)*cnt[x]
print(s)
cnt[y]+=cnt[x]
cnt[x]=0 | No | Do these codes solve the same problem?
Code 1: #include <bits/stdc++.h>
using namespace std;
int main() {
bool p[100001];
int c[100001], q, l, r;
for (int i = 0; i < 100001; i++)
{
p[i] = false;
c[i] = 0;
}
for (int i = 2; i < 100001; i++)
{
if (p[i] == false)
for (int j = i * 2; j < 100001; j += i) p[j] = true;
}
for (int i = 3; i < 100001; i++)
if (p[i] == false && p[(i + 1) / 2] == false) c[i]++;
for (int i = 3; i < 100001; i++) c[i] += c[i - 1];
cin >> q;
for (int i = 0; i < q; i++)
{
cin >> l >> r;
cout << c[r] - c[l - 1] << endl;
}
}
Code 2: from sys import stdin
#, setrecursionlimit, stdout
#setrecursionlimit(1000000)
#from collections import deque
#from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline().rstrip()
def lsi(): return list(si())
#mod=1000000007
res=['Yes', 'No']
############# CODE STARTS HERE #############
test_case=1
while test_case:
test_case-=1
cnt=[0]*100005
n=ii()
a=li()
for i in a:
cnt[i]+=1
s=sum(a)
for _ in range(ii()):
x, y=mi()
s+=(y-x)*cnt[x]
print(s)
cnt[y]+=cnt[x]
cnt[x]=0 |
C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.IO;
using System.Text;
using System.Diagnostics;
using static util;
using P = pair<int, int>;
using Binary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.BinaryExpression>;
using Unary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.UnaryExpression>;
class Program
{
static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
static Scan sc = new Scan();
const int M = 1000000007;
// const int M = 998244353;
const long LM = (long)1e18;
const double eps = 1e-11;
static readonly int[] dd = { 0, 1, 0, -1, 0 };
static void Main()
{
int n, h;
sc.Multi(out n, out h);
var s = new int[n];
var t = new int[n];
for (int i = 0; i < n; i++)
{
sc.Multi(out s[i], out t[i]);
}
int ma = s.Max();
Array.Sort(t);
int sum = 0;
for (int i = n - 1; i >= 0 ; i--)
{
if (t[i] > ma) {
sum += t[i];
if (sum >= h) {
DBG(n - i);
return;
}
}
else {
DBG(n - i - 1 + (h - sum + ma - 1) / ma);
return;
}
}
DBG(n + (h - sum + ma - 1) / ma);
sw.Flush();
}
static void DBG(string a) => Console.WriteLine(a);
static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
static void DBG(params object[] a) => DBG(string.Join(" ", a));
static void Prt(string a) => sw.WriteLine(a);
static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
static void Prt(params object[] a) => Prt(string.Join(" ", a));
}
class pair<T, U> : IComparable<pair<T, U>> where T : IComparable<T> where U : IComparable<U>
{
public T v1;
public U v2;
public pair(T v1, U v2) {
this.v1 = v1;
this.v2 = v2;
}
public int CompareTo(pair<T, U> a) => v1.CompareTo(a.v1) != 0 ? v1.CompareTo(a.v1) : v2.CompareTo(a.v2);
public override string ToString() => v1 + " " + v2;
}
static class util
{
public static pair<T, T> make_pair<T>(this IList<T> l) where T : IComparable<T> => make_pair(l[0], l[1]);
public static pair<T, U> make_pair<T, U>(T v1, U v2) where T : IComparable<T> where U : IComparable<U> => new pair<T, U>(v1, v2);
public static T sqr<T>(T a) => Operator<T>.Multiply(a, a);
public static T Max<T>(params T[] a) => a.Max();
public static T Min<T>(params T[] a) => a.Min();
public static void swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; }
public static void swap<T>(this IList<T> a, int i, int j) { var t = a[i]; a[i] = a[j]; a[j] = t; }
public static T[] copy<T>(this IList<T> a) {
var ret = new T[a.Count];
for (int i = 0; i < a.Count; i++) ret[i] = a[i];
return ret;
}
}
static class Operator<T>
{
static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x");
static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y");
public static readonly Func<T, T, T> Add = Lambda(Expression.Add);
public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract);
public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply);
public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide);
public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus);
public static readonly Func<T, T> Negate = Lambda(Expression.Negate);
public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile();
public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile();
}
class Scan
{
public int Int => int.Parse(Str);
public long Long => long.Parse(Str);
public double Double => double.Parse(Str);
public string Str => Console.ReadLine().Trim();
public pair<T, U> Pair<T, U>() where T : IComparable<T> where U : IComparable<U>
{ T a; U b; Multi(out a, out b); return make_pair(a, b); }
public int[] IntArr => StrArr.Select(int.Parse).ToArray();
public long[] LongArr => StrArr.Select(long.Parse).ToArray();
public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
public string[] StrArr => Str.Split(new []{' '}, System.StringSplitOptions.RemoveEmptyEntries);
bool eq<T, U>() => typeof(T).Equals(typeof(U));
T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
: eq<T, long>() ? ct<T, long>(long.Parse(s))
: eq<T, double>() ? ct<T, double>(double.Parse(s))
: eq<T, char>() ? ct<T, char>(s[0])
: ct<T, string>(s);
public void Multi<T>(out T a) => a = cv<T>(Str);
public void Multi<T, U>(out T a, out U b)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); }
public void Multi<T, U, V>(out T a, out U b, out V c)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); }
public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); }
public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); }
public void Multi<T, U, V, W, X, Y>(out T a, out U b, out V c, out W d, out X e, out Y f)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); f = cv<Y>(ar[5]); }
}
static class mymath
{
public static long Mod = 1000000007;
public static bool isprime(long a) {
if (a < 2) return false;
for (long i = 2; i * i <= a; i++) if (a % i == 0) return false;
return true;
}
public static bool[] sieve(int n) {
var p = new bool[n + 1];
for (int i = 2; i <= n; i++) p[i] = true;
for (int i = 2; i * i <= n; i++) if (p[i]) for (int j = i * i; j <= n; j += i) p[j] = false;
return p;
}
public static List<int> getprimes(int n) {
var prs = new List<int>();
var p = sieve(n);
for (int i = 2; i <= n; i++) if (p[i]) prs.Add(i);
return prs;
}
public static long[][] E(int n) {
var ret = new long[n][];
for (int i = 0; i < n; i++) { ret[i] = new long[n]; ret[i][i] = 1; }
return ret;
}
public static double[][] dE(int n) {
var ret = new double[n][];
for (int i = 0; i < n; i++) { ret[i] = new double[n]; ret[i][i] = 1; }
return ret;
}
public static long[][] pow(long[][] A, long n) {
if (n == 0) return E(A.Length);
var t = pow(A, n / 2);
if ((n & 1) == 0) return mul(t, t);
return mul(mul(t, t), A);
}
public static double[][] pow(double[][] A, long n) {
if (n == 0) return dE(A.Length);
var t = pow(A, n / 2);
if ((n & 1) == 0) return mul(t, t);
return mul(mul(t, t), A);
}
public static double dot(double[] x, double[] y) {
int n = x.Length;
double ret = 0;
for (int i = 0; i < n; i++) ret += x[i] * y[i];
return ret;
}
public static double _dot(double[] x, double[] y) {
int n = x.Length;
double ret = 0, r = 0;
for (int i = 0; i < n; i++) {
double s = ret + (x[i] * y[i] + r);
r = (x[i] * y[i] + r) - (s - ret);
ret = s;
}
return ret;
}
public static long dot(long[] x, long[] y) {
int n = x.Length;
long ret = 0;
for (int i = 0; i < n; i++) ret = (ret + x[i] * y[i]) % Mod;
return ret;
}
public static T[][] trans<T>(T[][] A) {
int n = A[0].Length, m = A.Length;
var ret = new T[n][];
for (int i = 0; i < n; i++) { ret[i] = new T[m]; for (int j = 0; j < m; j++) ret[i][j] = A[j][i]; }
return ret;
}
public static double[] mul(double a, double[] x) {
int n = x.Length;
var ret = new double[n];
for (int i = 0; i < n; i++) ret[i] = a * x[i];
return ret;
}
public static long[] mul(long a, long[] x) {
int n = x.Length;
var ret = new long[n];
for (int i = 0; i < n; i++) ret[i] = a * x[i] % Mod;
return ret;
}
public static double[] mul(double[][] A, double[] x) {
int n = A.Length;
var ret = new double[n];
for (int i = 0; i < n; i++) ret[i] = dot(x, A[i]);
return ret;
}
public static long[] mul(long[][] A, long[] x) {
int n = A.Length;
var ret = new long[n];
for (int i = 0; i < n; i++) ret[i] = dot(x, A[i]);
return ret;
}
public static double[][] mul(double a, double[][] A) {
int n = A.Length;
var ret = new double[n][];
for (int i = 0; i < n; i++) ret[i] = mul(a, A[i]);
return ret;
}
public static long[][] mul(long a, long[][] A) {
int n = A.Length;
var ret = new long[n][];
for (int i = 0; i < n; i++) ret[i] = mul(a, A[i]);
return ret;
}
public static double[][] mul(double[][] A, double[][] B) {
int n = A.Length;
var Bt = trans(B);
var ret = new double[n][];
for (int i = 0; i < n; i++) ret[i] = mul(Bt, A[i]);
return ret;
}
public static long[][] mul(long[][] A, long[][] B) {
int n = A.Length;
var Bt = trans(B);
var ret = new long[n][];
for (int i = 0; i < n; i++) ret[i] = mul(Bt, A[i]);
return ret;
}
public static long[] add(long[] x, long[] y) {
int n = x.Length;
var ret = new long[n];
for (int i = 0; i < n; i++) ret[i] = (x[i] + y[i]) % Mod;
return ret;
}
public static long[][] add(long[][] A, long[][] B) {
int n = A.Length;
var ret = new long[n][];
for (int i = 0; i < n; i++) ret[i] = add(A[i], B[i]);
return ret;
}
public static long pow(long a, long b) {
if (a >= Mod) return pow(a % Mod, b);
if (a == 0) return 0;
if (b == 0) return 1;
var t = pow(a, b / 2);
if ((b & 1) == 0) return t * t % Mod;
return t * t % Mod * a % Mod;
}
public static long inv(long a) => pow(a, Mod - 2);
public static long gcd(long a, long b) {
while (b > 0) { var t = a % b; a = b; b = t; } return a;
}
// a x + b y = gcd(a, b)
public static long extgcd(long a, long b, out long x, out long y) {
long g = a; x = 1; y = 0;
if (b > 0) { g = extgcd(b, a % b, out y, out x); y -= a / b * x; }
return g;
}
public static long lcm(long a, long b) => a / gcd(a, b) * b;
static long[] facts;
public static long[] setfacts(int n) {
facts = new long[n + 1];
facts[0] = 1;
for (int i = 0; i < n; i++) facts[i + 1] = facts[i] * (i + 1) % Mod;
return facts;
}
public static long comb(int n, int r) {
if (n < 0 || r < 0 || r > n) return 0;
if (n - r < r) r = n - r;
if (r == 0) return 1;
if (r == 1) return n;
if (facts != null && facts.Length > n) return facts[n] * inv(facts[r]) % Mod * inv(facts[n - r]) % Mod;
int[] numer = new int[r], denom = new int[r];
for (int k = 0; k < r; k++) { numer[k] = n - r + k + 1; denom[k] = k + 1; }
for (int p = 2; p <= r; p++) {
int piv = denom[p - 1];
if (piv > 1) {
int ofst = (n - r) % p;
for (int k = p - 1; k < r; k += p) { numer[k - ofst] /= piv; denom[k] /= piv; }
}
}
long ret = 1;
for (int k = 0; k < r; k++) if (numer[k] > 1) ret = ret * numer[k] % Mod;
return ret;
}
public static long[][] getcombs(int n) {
var ret = new long[n + 1][];
for (int i = 0; i <= n; i++) {
ret[i] = new long[i + 1];
ret[i][0] = ret[i][i] = 1;
for (int j = 1; j < i; j++) ret[i][j] = (ret[i - 1][j - 1] + ret[i - 1][j]) % Mod;
}
return ret;
}
// nC0, nC2, ..., nCn
public static long[] getcomb(int n) {
var ret = new long[n + 1];
ret[0] = 1;
for (int i = 0; i < n; i++) ret[i + 1] = ret[i] * (n - i) % Mod * inv(i + 1) % Mod;
return ret;
}
}
| PHP | <?php
//error_reporting(0);
//$A = explode(" ",trim(fgets(STDIN)));
list($N,$H) = explode(" ",trim(fgets(STDIN)));
//$N=trim(fgets(STDIN));
for($i=0;$i<$N;$i++) {
list($s[],$t[])=explode(" ",trim(fgets(STDIN)));
}
$smax = max($s);
rsort($t);
$ans = $H;
for($k=0;$k<=$N;$k++) {
if ($k > 0) $H -= $t[$k-1];
$cnt=0;
if ($H>0) $cnt=ceil($H/$smax);
$ans = min($ans,$k+$cnt);
}
printf("%d\n",$ans);
| Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.IO;
using System.Text;
using System.Diagnostics;
using static util;
using P = pair<int, int>;
using Binary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.ParameterExpression,
System.Linq.Expressions.BinaryExpression>;
using Unary = System.Func<System.Linq.Expressions.ParameterExpression, System.Linq.Expressions.UnaryExpression>;
class Program
{
static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
static Scan sc = new Scan();
const int M = 1000000007;
// const int M = 998244353;
const long LM = (long)1e18;
const double eps = 1e-11;
static readonly int[] dd = { 0, 1, 0, -1, 0 };
static void Main()
{
int n, h;
sc.Multi(out n, out h);
var s = new int[n];
var t = new int[n];
for (int i = 0; i < n; i++)
{
sc.Multi(out s[i], out t[i]);
}
int ma = s.Max();
Array.Sort(t);
int sum = 0;
for (int i = n - 1; i >= 0 ; i--)
{
if (t[i] > ma) {
sum += t[i];
if (sum >= h) {
DBG(n - i);
return;
}
}
else {
DBG(n - i - 1 + (h - sum + ma - 1) / ma);
return;
}
}
DBG(n + (h - sum + ma - 1) / ma);
sw.Flush();
}
static void DBG(string a) => Console.WriteLine(a);
static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
static void DBG(params object[] a) => DBG(string.Join(" ", a));
static void Prt(string a) => sw.WriteLine(a);
static void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
static void Prt(params object[] a) => Prt(string.Join(" ", a));
}
class pair<T, U> : IComparable<pair<T, U>> where T : IComparable<T> where U : IComparable<U>
{
public T v1;
public U v2;
public pair(T v1, U v2) {
this.v1 = v1;
this.v2 = v2;
}
public int CompareTo(pair<T, U> a) => v1.CompareTo(a.v1) != 0 ? v1.CompareTo(a.v1) : v2.CompareTo(a.v2);
public override string ToString() => v1 + " " + v2;
}
static class util
{
public static pair<T, T> make_pair<T>(this IList<T> l) where T : IComparable<T> => make_pair(l[0], l[1]);
public static pair<T, U> make_pair<T, U>(T v1, U v2) where T : IComparable<T> where U : IComparable<U> => new pair<T, U>(v1, v2);
public static T sqr<T>(T a) => Operator<T>.Multiply(a, a);
public static T Max<T>(params T[] a) => a.Max();
public static T Min<T>(params T[] a) => a.Min();
public static void swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; }
public static void swap<T>(this IList<T> a, int i, int j) { var t = a[i]; a[i] = a[j]; a[j] = t; }
public static T[] copy<T>(this IList<T> a) {
var ret = new T[a.Count];
for (int i = 0; i < a.Count; i++) ret[i] = a[i];
return ret;
}
}
static class Operator<T>
{
static readonly ParameterExpression x = Expression.Parameter(typeof(T), "x");
static readonly ParameterExpression y = Expression.Parameter(typeof(T), "y");
public static readonly Func<T, T, T> Add = Lambda(Expression.Add);
public static readonly Func<T, T, T> Subtract = Lambda(Expression.Subtract);
public static readonly Func<T, T, T> Multiply = Lambda(Expression.Multiply);
public static readonly Func<T, T, T> Divide = Lambda(Expression.Divide);
public static readonly Func<T, T> Plus = Lambda(Expression.UnaryPlus);
public static readonly Func<T, T> Negate = Lambda(Expression.Negate);
public static Func<T, T, T> Lambda(Binary op) => Expression.Lambda<Func<T, T, T>>(op(x, y), x, y).Compile();
public static Func<T, T> Lambda(Unary op) => Expression.Lambda<Func<T, T>>(op(x), x).Compile();
}
class Scan
{
public int Int => int.Parse(Str);
public long Long => long.Parse(Str);
public double Double => double.Parse(Str);
public string Str => Console.ReadLine().Trim();
public pair<T, U> Pair<T, U>() where T : IComparable<T> where U : IComparable<U>
{ T a; U b; Multi(out a, out b); return make_pair(a, b); }
public int[] IntArr => StrArr.Select(int.Parse).ToArray();
public long[] LongArr => StrArr.Select(long.Parse).ToArray();
public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
public string[] StrArr => Str.Split(new []{' '}, System.StringSplitOptions.RemoveEmptyEntries);
bool eq<T, U>() => typeof(T).Equals(typeof(U));
T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
: eq<T, long>() ? ct<T, long>(long.Parse(s))
: eq<T, double>() ? ct<T, double>(double.Parse(s))
: eq<T, char>() ? ct<T, char>(s[0])
: ct<T, string>(s);
public void Multi<T>(out T a) => a = cv<T>(Str);
public void Multi<T, U>(out T a, out U b)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); }
public void Multi<T, U, V>(out T a, out U b, out V c)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); }
public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); }
public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); }
public void Multi<T, U, V, W, X, Y>(out T a, out U b, out V c, out W d, out X e, out Y f)
{ var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); f = cv<Y>(ar[5]); }
}
static class mymath
{
public static long Mod = 1000000007;
public static bool isprime(long a) {
if (a < 2) return false;
for (long i = 2; i * i <= a; i++) if (a % i == 0) return false;
return true;
}
public static bool[] sieve(int n) {
var p = new bool[n + 1];
for (int i = 2; i <= n; i++) p[i] = true;
for (int i = 2; i * i <= n; i++) if (p[i]) for (int j = i * i; j <= n; j += i) p[j] = false;
return p;
}
public static List<int> getprimes(int n) {
var prs = new List<int>();
var p = sieve(n);
for (int i = 2; i <= n; i++) if (p[i]) prs.Add(i);
return prs;
}
public static long[][] E(int n) {
var ret = new long[n][];
for (int i = 0; i < n; i++) { ret[i] = new long[n]; ret[i][i] = 1; }
return ret;
}
public static double[][] dE(int n) {
var ret = new double[n][];
for (int i = 0; i < n; i++) { ret[i] = new double[n]; ret[i][i] = 1; }
return ret;
}
public static long[][] pow(long[][] A, long n) {
if (n == 0) return E(A.Length);
var t = pow(A, n / 2);
if ((n & 1) == 0) return mul(t, t);
return mul(mul(t, t), A);
}
public static double[][] pow(double[][] A, long n) {
if (n == 0) return dE(A.Length);
var t = pow(A, n / 2);
if ((n & 1) == 0) return mul(t, t);
return mul(mul(t, t), A);
}
public static double dot(double[] x, double[] y) {
int n = x.Length;
double ret = 0;
for (int i = 0; i < n; i++) ret += x[i] * y[i];
return ret;
}
public static double _dot(double[] x, double[] y) {
int n = x.Length;
double ret = 0, r = 0;
for (int i = 0; i < n; i++) {
double s = ret + (x[i] * y[i] + r);
r = (x[i] * y[i] + r) - (s - ret);
ret = s;
}
return ret;
}
public static long dot(long[] x, long[] y) {
int n = x.Length;
long ret = 0;
for (int i = 0; i < n; i++) ret = (ret + x[i] * y[i]) % Mod;
return ret;
}
public static T[][] trans<T>(T[][] A) {
int n = A[0].Length, m = A.Length;
var ret = new T[n][];
for (int i = 0; i < n; i++) { ret[i] = new T[m]; for (int j = 0; j < m; j++) ret[i][j] = A[j][i]; }
return ret;
}
public static double[] mul(double a, double[] x) {
int n = x.Length;
var ret = new double[n];
for (int i = 0; i < n; i++) ret[i] = a * x[i];
return ret;
}
public static long[] mul(long a, long[] x) {
int n = x.Length;
var ret = new long[n];
for (int i = 0; i < n; i++) ret[i] = a * x[i] % Mod;
return ret;
}
public static double[] mul(double[][] A, double[] x) {
int n = A.Length;
var ret = new double[n];
for (int i = 0; i < n; i++) ret[i] = dot(x, A[i]);
return ret;
}
public static long[] mul(long[][] A, long[] x) {
int n = A.Length;
var ret = new long[n];
for (int i = 0; i < n; i++) ret[i] = dot(x, A[i]);
return ret;
}
public static double[][] mul(double a, double[][] A) {
int n = A.Length;
var ret = new double[n][];
for (int i = 0; i < n; i++) ret[i] = mul(a, A[i]);
return ret;
}
public static long[][] mul(long a, long[][] A) {
int n = A.Length;
var ret = new long[n][];
for (int i = 0; i < n; i++) ret[i] = mul(a, A[i]);
return ret;
}
public static double[][] mul(double[][] A, double[][] B) {
int n = A.Length;
var Bt = trans(B);
var ret = new double[n][];
for (int i = 0; i < n; i++) ret[i] = mul(Bt, A[i]);
return ret;
}
public static long[][] mul(long[][] A, long[][] B) {
int n = A.Length;
var Bt = trans(B);
var ret = new long[n][];
for (int i = 0; i < n; i++) ret[i] = mul(Bt, A[i]);
return ret;
}
public static long[] add(long[] x, long[] y) {
int n = x.Length;
var ret = new long[n];
for (int i = 0; i < n; i++) ret[i] = (x[i] + y[i]) % Mod;
return ret;
}
public static long[][] add(long[][] A, long[][] B) {
int n = A.Length;
var ret = new long[n][];
for (int i = 0; i < n; i++) ret[i] = add(A[i], B[i]);
return ret;
}
public static long pow(long a, long b) {
if (a >= Mod) return pow(a % Mod, b);
if (a == 0) return 0;
if (b == 0) return 1;
var t = pow(a, b / 2);
if ((b & 1) == 0) return t * t % Mod;
return t * t % Mod * a % Mod;
}
public static long inv(long a) => pow(a, Mod - 2);
public static long gcd(long a, long b) {
while (b > 0) { var t = a % b; a = b; b = t; } return a;
}
// a x + b y = gcd(a, b)
public static long extgcd(long a, long b, out long x, out long y) {
long g = a; x = 1; y = 0;
if (b > 0) { g = extgcd(b, a % b, out y, out x); y -= a / b * x; }
return g;
}
public static long lcm(long a, long b) => a / gcd(a, b) * b;
static long[] facts;
public static long[] setfacts(int n) {
facts = new long[n + 1];
facts[0] = 1;
for (int i = 0; i < n; i++) facts[i + 1] = facts[i] * (i + 1) % Mod;
return facts;
}
public static long comb(int n, int r) {
if (n < 0 || r < 0 || r > n) return 0;
if (n - r < r) r = n - r;
if (r == 0) return 1;
if (r == 1) return n;
if (facts != null && facts.Length > n) return facts[n] * inv(facts[r]) % Mod * inv(facts[n - r]) % Mod;
int[] numer = new int[r], denom = new int[r];
for (int k = 0; k < r; k++) { numer[k] = n - r + k + 1; denom[k] = k + 1; }
for (int p = 2; p <= r; p++) {
int piv = denom[p - 1];
if (piv > 1) {
int ofst = (n - r) % p;
for (int k = p - 1; k < r; k += p) { numer[k - ofst] /= piv; denom[k] /= piv; }
}
}
long ret = 1;
for (int k = 0; k < r; k++) if (numer[k] > 1) ret = ret * numer[k] % Mod;
return ret;
}
public static long[][] getcombs(int n) {
var ret = new long[n + 1][];
for (int i = 0; i <= n; i++) {
ret[i] = new long[i + 1];
ret[i][0] = ret[i][i] = 1;
for (int j = 1; j < i; j++) ret[i][j] = (ret[i - 1][j - 1] + ret[i - 1][j]) % Mod;
}
return ret;
}
// nC0, nC2, ..., nCn
public static long[] getcomb(int n) {
var ret = new long[n + 1];
ret[0] = 1;
for (int i = 0; i < n; i++) ret[i + 1] = ret[i] * (n - i) % Mod * inv(i + 1) % Mod;
return ret;
}
}
Code 2: <?php
//error_reporting(0);
//$A = explode(" ",trim(fgets(STDIN)));
list($N,$H) = explode(" ",trim(fgets(STDIN)));
//$N=trim(fgets(STDIN));
for($i=0;$i<$N;$i++) {
list($s[],$t[])=explode(" ",trim(fgets(STDIN)));
}
$smax = max($s);
rsort($t);
$ans = $H;
for($k=0;$k<=$N;$k++) {
if ($k > 0) $H -= $t[$k-1];
$cnt=0;
if ($H>0) $cnt=ceil($H/$smax);
$ans = min($ans,$k+$cnt);
}
printf("%d\n",$ans);
|
C++ | #include <iostream>
using namespace std;
int main(void){
long long x, y;
cin >> x >> y;
if(abs(x-y) <= 1){
cout << "Brown" << endl;
}else{
cout << "Alice" << endl;
}
return 0;
} | Python | x=int(input())
if x==0:
print(1)
elif x==1:
print(0) | No | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int main(void){
long long x, y;
cin >> x >> y;
if(abs(x-y) <= 1){
cout << "Brown" << endl;
}else{
cout << "Alice" << endl;
}
return 0;
}
Code 2: x=int(input())
if x==0:
print(1)
elif x==1:
print(0) |
JavaScript | "use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextssort(n,a){return a?cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>b-a):cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>a-b);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}
var streams=[];function print(s){streams.push(s);}
var mod = 1e9+7;
function mul(){for(var a=arguments,r=a[0],i=a.length;--i;)r=((r>>16)*a[i]%mod*65536+(r&65535)*a[i])%mod;return r;}
var fac=[],finv=[],invs=[],pow2=[];
function fset(n){
fac.length=n+1,fac[0]=fac[1]=1;
for(var i=2;i<=n;)fac[i]=mul(fac[i-1],i++);
finv.length=n+1,finv[0]=finv[1]=1,finv[n]=inv(fac[n]);
for(i=n;2<i;)finv[i-1]=mul(finv[i],i--);
//invs.length=n+1,invs[0]=invs[1]=1;
//for(i=2;i<=n;)invs[i]=mul(fac[i-1],finv[i++]);
//pow2.length=n+1,pow2[0]=1;
//for(i=1;i<=n;i++)pow2[i]=pow2[i-1]*2%mod;
}
function inv(b){for(var a=mod,u=0,v=1,t;b;v=t)t=a/b|0,a-=t*b,u-=t*v,t=a,a=b,b=t,t=u,u=v;u%=mod;return u<0?u+mod:u;}
function pow(a,n){for(var r=1;n;a=mul(a,a),n>>=1)if(n&1)r=mul(a,r);return r;}
function ncr(n,r){return mul(fac[n],finv[r],finv[n-r]);}
function npr(n,r){return mul(fac[n],finv[n-r]);}
function mput(n){return (n%mod+mod)%mod;}
var myOut = main();
if(myOut !== undefined)console.log(String(myOut));
if(streams.length)console.log(streams.join("\n"));
function main(){
var n = next();
var ans = pow(10,n);
ans -= pow(9,n);
ans -= pow(9,n);
ans += pow(8,n);
return mput(ans);
} | PHP | <?php
[$N] = fscanf(STDIN, "%d");
$ans = 1;
const MOD = 1000000007;
for($i=0;$i<$N;$i++){
$ans *= 10;
$ans %= MOD;
}
$hiku = 1;
$tasu = 1;
for($i=0;$i<$N;$i++){
$hiku *= 9;
$tasu *= 8;
$hiku %= MOD;
$tasu %= MOD;
}
$ans -= ($hiku + $hiku - $tasu) % MOD;
$ans = (int)gmp_mod($ans, MOD);
echo $ans; | Yes | Do these codes solve the same problem?
Code 1: "use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextssort(n,a){return a?cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>b-a):cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>a-b);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}
var streams=[];function print(s){streams.push(s);}
var mod = 1e9+7;
function mul(){for(var a=arguments,r=a[0],i=a.length;--i;)r=((r>>16)*a[i]%mod*65536+(r&65535)*a[i])%mod;return r;}
var fac=[],finv=[],invs=[],pow2=[];
function fset(n){
fac.length=n+1,fac[0]=fac[1]=1;
for(var i=2;i<=n;)fac[i]=mul(fac[i-1],i++);
finv.length=n+1,finv[0]=finv[1]=1,finv[n]=inv(fac[n]);
for(i=n;2<i;)finv[i-1]=mul(finv[i],i--);
//invs.length=n+1,invs[0]=invs[1]=1;
//for(i=2;i<=n;)invs[i]=mul(fac[i-1],finv[i++]);
//pow2.length=n+1,pow2[0]=1;
//for(i=1;i<=n;i++)pow2[i]=pow2[i-1]*2%mod;
}
function inv(b){for(var a=mod,u=0,v=1,t;b;v=t)t=a/b|0,a-=t*b,u-=t*v,t=a,a=b,b=t,t=u,u=v;u%=mod;return u<0?u+mod:u;}
function pow(a,n){for(var r=1;n;a=mul(a,a),n>>=1)if(n&1)r=mul(a,r);return r;}
function ncr(n,r){return mul(fac[n],finv[r],finv[n-r]);}
function npr(n,r){return mul(fac[n],finv[n-r]);}
function mput(n){return (n%mod+mod)%mod;}
var myOut = main();
if(myOut !== undefined)console.log(String(myOut));
if(streams.length)console.log(streams.join("\n"));
function main(){
var n = next();
var ans = pow(10,n);
ans -= pow(9,n);
ans -= pow(9,n);
ans += pow(8,n);
return mput(ans);
}
Code 2: <?php
[$N] = fscanf(STDIN, "%d");
$ans = 1;
const MOD = 1000000007;
for($i=0;$i<$N;$i++){
$ans *= 10;
$ans %= MOD;
}
$hiku = 1;
$tasu = 1;
for($i=0;$i<$N;$i++){
$hiku *= 9;
$tasu *= 8;
$hiku %= MOD;
$tasu %= MOD;
}
$ans -= ($hiku + $hiku - $tasu) % MOD;
$ans = (int)gmp_mod($ans, MOD);
echo $ans; |
JavaScript | var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
while(true){
var mn=arr.shift();
if(mn=="0 0")break;
mn=mn.split(" ").map(Number);
var m=mn[0];
var n=mn[1];
var ary=[];
for(var i=0;i<18;i++)ary[i]=0;
ary[0]=m;
for(var j=1;j<n;j++){
var plus=[];
for(var i=0;i<18;i++)plus[i]=0;
ary.forEach(function(v,i){
var k=v*m;
if(k>=10000){
ary[i]=k%10000;
plus[i+1]+=Math.floor(k/10000);
}else{
ary[i]=k;
}
});
ary.forEach(function(v,i){
var k=ary[i]+plus[i];
if(k>=10000){
ary[i]=k%10000;
ary[i+1]+=Math.floor(k/10000);
}else{
ary[i]=k;
}
});
}
var us=["","Man","Oku","Cho","Kei","Gai","Jo","Jou","Ko","Kan","Sei","Sai","Gok","Ggs","Asg","Nyt","Fks","Mts"];
var str="";
ary.forEach(function(v,i){
if(v!=0)str=v+us[i]+str;
});
if(str=="")str=0;
console.log(str);
} | C# | using System.Numerics;
using System;
public class Hello
{
public static void Main()
{
var a = new string[] { "", "Man", "Oku", "Cho", "Kei", "Gai", "Jo", "Jou", "Ko", "Kan", "Sei", "Sai", "Gok", "Ggs", "Asg", "Nyt", "Fks", "Mts" };
while (true)
{
string[] line = Console.ReadLine().Trim().Split(' ');
var m = int.Parse(line[0]);
var n = int.Parse(line[1]);
if (m == 0 && n == 0) break;
var s = BigInteger.Pow(m, n).ToString();
getAns(a, s);
}
}
static void getAns(string[] a, string s)
{
var c1 = s.Length / 4;
var c2 = s.Length % 4;
var ans = "";
if (c2 > 0) ans = s.Substring(0, c2) + a[c1];
for (int i = 0; i < c1; i++)
{
var w = int.Parse(s.Substring(c2 + 4 * i, 4));
if (w != 0) ans += w.ToString()+ a[c1 - i - 1];
}
Console.WriteLine(ans);
}
}
| Yes | Do these codes solve the same problem?
Code 1: var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
while(true){
var mn=arr.shift();
if(mn=="0 0")break;
mn=mn.split(" ").map(Number);
var m=mn[0];
var n=mn[1];
var ary=[];
for(var i=0;i<18;i++)ary[i]=0;
ary[0]=m;
for(var j=1;j<n;j++){
var plus=[];
for(var i=0;i<18;i++)plus[i]=0;
ary.forEach(function(v,i){
var k=v*m;
if(k>=10000){
ary[i]=k%10000;
plus[i+1]+=Math.floor(k/10000);
}else{
ary[i]=k;
}
});
ary.forEach(function(v,i){
var k=ary[i]+plus[i];
if(k>=10000){
ary[i]=k%10000;
ary[i+1]+=Math.floor(k/10000);
}else{
ary[i]=k;
}
});
}
var us=["","Man","Oku","Cho","Kei","Gai","Jo","Jou","Ko","Kan","Sei","Sai","Gok","Ggs","Asg","Nyt","Fks","Mts"];
var str="";
ary.forEach(function(v,i){
if(v!=0)str=v+us[i]+str;
});
if(str=="")str=0;
console.log(str);
}
Code 2: using System.Numerics;
using System;
public class Hello
{
public static void Main()
{
var a = new string[] { "", "Man", "Oku", "Cho", "Kei", "Gai", "Jo", "Jou", "Ko", "Kan", "Sei", "Sai", "Gok", "Ggs", "Asg", "Nyt", "Fks", "Mts" };
while (true)
{
string[] line = Console.ReadLine().Trim().Split(' ');
var m = int.Parse(line[0]);
var n = int.Parse(line[1]);
if (m == 0 && n == 0) break;
var s = BigInteger.Pow(m, n).ToString();
getAns(a, s);
}
}
static void getAns(string[] a, string s)
{
var c1 = s.Length / 4;
var c2 = s.Length % 4;
var ans = "";
if (c2 > 0) ans = s.Substring(0, c2) + a[c1];
for (int i = 0; i < c1; i++)
{
var w = int.Parse(s.Substring(c2 + 4 * i, 4));
if (w != 0) ans += w.ToString()+ a[c1 - i - 1];
}
Console.WriteLine(ans);
}
}
|
C++ | #include <iostream>
#include <map>
#define For(i,x,y) for(register int i=(x); i<=(y); i++)
using namespace std;
map<string,int>ma;
int main()
{
ios::sync_with_stdio(false);
int n,ans=0;
cin>>n;
For(i,1,n)
{
string s;
cin>>s;
if(!ma.count(s))
{
ma[s]=1;
ans++;
}
}
cout<<ans<<endl;
return 0;
}
| Python | n = int(input())
ttl = n
ans = []
memo = -2
memo2 = 1
while(abs(ttl)>0):
if ttl%memo != 0:
ttl -= memo2
ans.append(1)
else:
ans.append(0)
memo *= (-2)
memo2 *= (-2)
if n == 0:
print(0)
else:
for i in range(1,len(ans)+1):
print(ans[-i],end = "")
print() | No | Do these codes solve the same problem?
Code 1: #include <iostream>
#include <map>
#define For(i,x,y) for(register int i=(x); i<=(y); i++)
using namespace std;
map<string,int>ma;
int main()
{
ios::sync_with_stdio(false);
int n,ans=0;
cin>>n;
For(i,1,n)
{
string s;
cin>>s;
if(!ma.count(s))
{
ma[s]=1;
ans++;
}
}
cout<<ans<<endl;
return 0;
}
Code 2: n = int(input())
ttl = n
ans = []
memo = -2
memo2 = 1
while(abs(ttl)>0):
if ttl%memo != 0:
ttl -= memo2
ans.append(1)
else:
ans.append(0)
memo *= (-2)
memo2 *= (-2)
if n == 0:
print(0)
else:
for i in range(1,len(ans)+1):
print(ans[-i],end = "")
print() |
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()
{
int n = int.Parse(Console.ReadLine());
for (int i = 0; i <= n; i++)
{
if (n == i * 108 / 100)
{
Console.WriteLine(i);
return;
}
}
Console.WriteLine(":(");
}
} | TypeScript | const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))}
const main=()=>{
let n=tn()
let a=floor(n*0.92)
for(let i=a;floor(i*1.08)<=n;i++){
if(floor(i*1.08)==n){
to(floor(i))
return
}
}
to(':(')
}
main() | Yes | Do these codes solve the same problem?
Code 1: using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Math;
public static class P
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
for (int i = 0; i <= n; i++)
{
if (n == i * 108 / 100)
{
Console.WriteLine(i);
return;
}
}
Console.WriteLine(":(");
}
}
Code 2: const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))}
const main=()=>{
let n=tn()
let a=floor(n*0.92)
for(let i=a;floor(i*1.08)<=n;i++){
if(floor(i*1.08)==n){
to(floor(i))
return
}
}
to(':(')
}
main() |
C++ | #include<iostream>
#include<cstdio>
#include<map>
#include<queue>
using namespace std;
class wormcheck{
public:
string Worm;
int Val;
wormcheck(string W,int V){
Worm=W;
Val=V;
}
};
int main(){
string worm;
while(cin>>worm){
if(worm=="0")break;
queue<wormcheck> que;
que.push(wormcheck(worm,0));
map<string,int> visit;
while(1){
if(que.empty()){cout<<"NA"<<endl;break;}
wormcheck w = que.front();
que.pop();
if(visit[w.Worm]==1)continue;
visit[w.Worm]=1;
for(int i=1;i<w.Worm.size();i++){
if(w.Worm[i]!=w.Worm[i-1]){
goto Skip;
}
}
//printf("%s %d",w.Worm,w.Val);
cout<<w.Val<<endl;
break;
Skip:;
string subWorm = w.Worm;
for(int i=1;i<w.Worm.size();i++){
if(subWorm[i]!=subWorm[i-1]){
if(subWorm[i]!='b'&&subWorm[i-1]!='b'){
subWorm[i]='b';
subWorm[i-1]='b';
}
else if(subWorm[i]!='g'&&subWorm[i-1]!='g'){
subWorm[i]='g';
subWorm[i-1]='g';
}
else if(subWorm[i]!='r'&&subWorm[i-1]!='r'){
subWorm[i]='r';
subWorm[i-1]='r';
}
que.push(wormcheck(subWorm,w.Val+1));
subWorm=w.Worm;
}
}
}
}
return 0;
} | Python | n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(n):
ans += 1 / a[i]
print(1 / ans) | No | Do these codes solve the same problem?
Code 1: #include<iostream>
#include<cstdio>
#include<map>
#include<queue>
using namespace std;
class wormcheck{
public:
string Worm;
int Val;
wormcheck(string W,int V){
Worm=W;
Val=V;
}
};
int main(){
string worm;
while(cin>>worm){
if(worm=="0")break;
queue<wormcheck> que;
que.push(wormcheck(worm,0));
map<string,int> visit;
while(1){
if(que.empty()){cout<<"NA"<<endl;break;}
wormcheck w = que.front();
que.pop();
if(visit[w.Worm]==1)continue;
visit[w.Worm]=1;
for(int i=1;i<w.Worm.size();i++){
if(w.Worm[i]!=w.Worm[i-1]){
goto Skip;
}
}
//printf("%s %d",w.Worm,w.Val);
cout<<w.Val<<endl;
break;
Skip:;
string subWorm = w.Worm;
for(int i=1;i<w.Worm.size();i++){
if(subWorm[i]!=subWorm[i-1]){
if(subWorm[i]!='b'&&subWorm[i-1]!='b'){
subWorm[i]='b';
subWorm[i-1]='b';
}
else if(subWorm[i]!='g'&&subWorm[i-1]!='g'){
subWorm[i]='g';
subWorm[i-1]='g';
}
else if(subWorm[i]!='r'&&subWorm[i-1]!='r'){
subWorm[i]='r';
subWorm[i-1]='r';
}
que.push(wormcheck(subWorm,w.Val+1));
subWorm=w.Worm;
}
}
}
}
return 0;
}
Code 2: n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(n):
ans += 1 / a[i]
print(1 / ans) |
Java |
public class Main {
private static void solve() {
char[] s = ns();
int a = Integer.parseInt("" + s[0] + s[1]);
int b = Integer.parseInt("" + s[2] + s[3]);
if (1 <= a && a <= 12 && 1 <= b && b <= 12) {
System.out.println("AMBIGUOUS");
} else if (1 <= a && a <= 12) {
System.out.println("MMYY");
} else if (1 <= b && b <= 12) {
System.out.println("YYMM");
} else {
System.out.println("NA");
}
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String debug = args.length > 0 ? args[0] : null;
if (debug != null) {
try {
is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
solve();
out.flush();
tr((System.currentTimeMillis() - start) + "ms");
}
}, "", 64000000).start();
}
private static java.io.InputStream is = System.in;
private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
private static java.util.StringTokenizer tokenizer = null;
private static java.io.BufferedReader reader;
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private static double nd() {
return Double.parseDouble(next());
}
private static long nl() {
return Long.parseLong(next());
}
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 char[] ns() {
return next().toCharArray();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int[][] ntable(int n, int m) {
int[][] table = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[i][j] = ni();
}
}
return table;
}
private static int[][] nlist(int n, int m) {
int[][] table = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[j][i] = ni();
}
}
return table;
}
private static int ni() {
return Integer.parseInt(next());
}
private static void tr(Object... o) {
if (is != System.in)
System.out.println(java.util.Arrays.deepToString(o));
}
}
| C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using static System.Math;
using static Func;
class Z { static void Main() => new K(); }
class K
{
int F => int.Parse(Str);
long FL => long.Parse(Str);
int[] G => Strs.Select(int.Parse).ToArray();
uint[] GU => Strs.Select(uint.Parse).ToArray();
decimal[] GD => Strs.Select(decimal.Parse).ToArray();
long[] GL => Strs.Select(long.Parse).ToArray();
string Str => ReadLine();
string[] Strs => Str.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
static T[] ConstantArray<T>(int n, T val) { var a = new T[n]; for (var i = 0; i < n; i++) a[i] = val; return a; }
static T[] MakeArray<T>(int n, Func<int, T> f) { var a = new T[n]; for (var i = 0; i < n; i++) a[i] = f(i); return a; }
static T[] Recurse<T>(int n, T a0, Func<int, T, T> f) { var a = new T[n]; a[0] = a0; for (var i = 1; i < n; i++) a[i] = f(i, a[i - 1]); return a; }
static T[] Accumulate<T>(IList<T> a, T zero, Func<T, T, T> f) { var s = new T[a.Count + 1]; s[0] = zero; for (var i = 0; i < a.Count; i++) s[i + 1] = f(s[i], a[i]); return s; }
static ulong One(int k) => 1ul << k;
static ulong All(int k) => One(k) - 1;
static bool Has(ulong s, int k) => (s & One(k)) != 0;
const int MOD = 1000000007;
public K()
{
SetOut(new StreamWriter(OpenStandardOutput()) { AutoFlush = false });
Solve();
Out.Flush();
}
void Solve()
{
var S = Str;
var a = int.Parse(S.Substring(0, 2));
var b = int.Parse(S.Substring(2, 2));
var f = 1 <= a && a <= 12;
var g = 1 <= b && b <= 12;
WriteLine(f && g ? "AMBIGUOUS" : !f && !g ? "NA" : f ? "MMYY" : "YYMM");
}
}
static class Func { }
| Yes | Do these codes solve the same problem?
Code 1:
public class Main {
private static void solve() {
char[] s = ns();
int a = Integer.parseInt("" + s[0] + s[1]);
int b = Integer.parseInt("" + s[2] + s[3]);
if (1 <= a && a <= 12 && 1 <= b && b <= 12) {
System.out.println("AMBIGUOUS");
} else if (1 <= a && a <= 12) {
System.out.println("MMYY");
} else if (1 <= b && b <= 12) {
System.out.println("YYMM");
} else {
System.out.println("NA");
}
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String debug = args.length > 0 ? args[0] : null;
if (debug != null) {
try {
is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
solve();
out.flush();
tr((System.currentTimeMillis() - start) + "ms");
}
}, "", 64000000).start();
}
private static java.io.InputStream is = System.in;
private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
private static java.util.StringTokenizer tokenizer = null;
private static java.io.BufferedReader reader;
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private static double nd() {
return Double.parseDouble(next());
}
private static long nl() {
return Long.parseLong(next());
}
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 char[] ns() {
return next().toCharArray();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int[][] ntable(int n, int m) {
int[][] table = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[i][j] = ni();
}
}
return table;
}
private static int[][] nlist(int n, int m) {
int[][] table = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[j][i] = ni();
}
}
return table;
}
private static int ni() {
return Integer.parseInt(next());
}
private static void tr(Object... o) {
if (is != System.in)
System.out.println(java.util.Arrays.deepToString(o));
}
}
Code 2: using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using static System.Math;
using static Func;
class Z { static void Main() => new K(); }
class K
{
int F => int.Parse(Str);
long FL => long.Parse(Str);
int[] G => Strs.Select(int.Parse).ToArray();
uint[] GU => Strs.Select(uint.Parse).ToArray();
decimal[] GD => Strs.Select(decimal.Parse).ToArray();
long[] GL => Strs.Select(long.Parse).ToArray();
string Str => ReadLine();
string[] Strs => Str.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
static T[] ConstantArray<T>(int n, T val) { var a = new T[n]; for (var i = 0; i < n; i++) a[i] = val; return a; }
static T[] MakeArray<T>(int n, Func<int, T> f) { var a = new T[n]; for (var i = 0; i < n; i++) a[i] = f(i); return a; }
static T[] Recurse<T>(int n, T a0, Func<int, T, T> f) { var a = new T[n]; a[0] = a0; for (var i = 1; i < n; i++) a[i] = f(i, a[i - 1]); return a; }
static T[] Accumulate<T>(IList<T> a, T zero, Func<T, T, T> f) { var s = new T[a.Count + 1]; s[0] = zero; for (var i = 0; i < a.Count; i++) s[i + 1] = f(s[i], a[i]); return s; }
static ulong One(int k) => 1ul << k;
static ulong All(int k) => One(k) - 1;
static bool Has(ulong s, int k) => (s & One(k)) != 0;
const int MOD = 1000000007;
public K()
{
SetOut(new StreamWriter(OpenStandardOutput()) { AutoFlush = false });
Solve();
Out.Flush();
}
void Solve()
{
var S = Str;
var a = int.Parse(S.Substring(0, 2));
var b = int.Parse(S.Substring(2, 2));
var f = 1 <= a && a <= 12;
var g = 1 <= b && b <= 12;
WriteLine(f && g ? "AMBIGUOUS" : !f && !g ? "NA" : f ? "MMYY" : "YYMM");
}
}
static class Func { }
|
Python | s=list(input())
t=list(input())
ls=len(s)
lt=len(t)
if ls<lt:
print("UNRESTORABLE")
exit()
for i in range(ls-lt,-1,-1):
for j in range(i,i+lt):
if s[j]==t[j-i] or s[j]=="?":
continue
else:
break
else:
for k in range(i,i+lt):
s[k]=t[k-i]
for l in range(ls):
if s[l]=="?":
s[l]="a"
print(*s,sep="")
exit()
else:
print("UNRESTORABLE")
| C++ | #include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <iostream>
#include <istream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <tuple>
#include <iomanip>
#include <climits>
#include <fstream>
#include <random>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define revrep(i, n) for(int i = (n)-1; i >= 0; i--)
#define pb push_back
#define f first
#define s second
#define chmin(x, y) x = min(x, y);
#define chmax(x, y) x = max(x, y);
#define sz(x) ((int)(x).size())
//const ll INFL = LLONG_MAX;//10^18 = 2^60
const ll INFL = 1LL<<60;
//const int INF = INT_MAX;
const int INF = 1 << 30;//10^9
//const ll MOD = 1000000007;
//const ll MOD = 998244353;
const ll MOD = 1000003;
double EPS = 1e-10;
vector<ll> dy = {0, 1, 0, -1, 1, 1, -1, -1, 0};
vector<ll> dx = {1, 0, -1, 0, 1, -1, 1, -1, 0};
void pres(double A){printf("%.12lf\n", A);}
void BinarySay(ll x, ll y = 60){rep(i, y) cout << (x>>(y-1-i) & 1); cout << endl;}
ll cnt_bit(ll x){return __builtin_popcountll(x);}
ll pow_long(ll x, ll k){
ll res = 1;
while(k > 0){
if(k % 2) res *= x;
x *= x; k /= 2;
}
return res;
}
ll pow_mod(ll x, ll k){
x %= MOD;
ll res = 1;
while(k > 0){
if(k % 2){
res *= x; res %= MOD;
}
x *= x; x %= MOD;
k /= 2;
}
return res;
}
ll inverse(ll x){return pow_mod(x, MOD - 2);};
ll gcd(ll a, ll b){
if(b == 0) return a;
return gcd(b, a % b);
}
ll lcm(ll x, ll y){
ll res = x / gcd(x, y);
res *= y;
return res;
};
void solve(){
while(true){
int n, m;
cin >> n >> m;
if(n == 0 && m == 0) return;
vector<int> s(n), t(m);
rep(i, n) cin >> s[i];
rep(i, m) cin >> t[i];
int S = 0, T = 0;
rep(i, n) S += s[i];
rep(i, m) T += t[i];
pair<int, pair<int, int>> ans = {INF, {INF, INF}};
rep(i, n)rep(j, m){
if(S - s[i] + t[j] == T - t[j] + s[i]){
ans = min(ans, {s[i] + t[j], {s[i], t[j]}});
}
}
if(ans.f == INF) cout << -1 << endl;
else cout << ans.s.f << " " << ans.s.s << endl;
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
solve();
}
| No | Do these codes solve the same problem?
Code 1: s=list(input())
t=list(input())
ls=len(s)
lt=len(t)
if ls<lt:
print("UNRESTORABLE")
exit()
for i in range(ls-lt,-1,-1):
for j in range(i,i+lt):
if s[j]==t[j-i] or s[j]=="?":
continue
else:
break
else:
for k in range(i,i+lt):
s[k]=t[k-i]
for l in range(ls):
if s[l]=="?":
s[l]="a"
print(*s,sep="")
exit()
else:
print("UNRESTORABLE")
Code 2: #include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <iostream>
#include <istream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <tuple>
#include <iomanip>
#include <climits>
#include <fstream>
#include <random>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define revrep(i, n) for(int i = (n)-1; i >= 0; i--)
#define pb push_back
#define f first
#define s second
#define chmin(x, y) x = min(x, y);
#define chmax(x, y) x = max(x, y);
#define sz(x) ((int)(x).size())
//const ll INFL = LLONG_MAX;//10^18 = 2^60
const ll INFL = 1LL<<60;
//const int INF = INT_MAX;
const int INF = 1 << 30;//10^9
//const ll MOD = 1000000007;
//const ll MOD = 998244353;
const ll MOD = 1000003;
double EPS = 1e-10;
vector<ll> dy = {0, 1, 0, -1, 1, 1, -1, -1, 0};
vector<ll> dx = {1, 0, -1, 0, 1, -1, 1, -1, 0};
void pres(double A){printf("%.12lf\n", A);}
void BinarySay(ll x, ll y = 60){rep(i, y) cout << (x>>(y-1-i) & 1); cout << endl;}
ll cnt_bit(ll x){return __builtin_popcountll(x);}
ll pow_long(ll x, ll k){
ll res = 1;
while(k > 0){
if(k % 2) res *= x;
x *= x; k /= 2;
}
return res;
}
ll pow_mod(ll x, ll k){
x %= MOD;
ll res = 1;
while(k > 0){
if(k % 2){
res *= x; res %= MOD;
}
x *= x; x %= MOD;
k /= 2;
}
return res;
}
ll inverse(ll x){return pow_mod(x, MOD - 2);};
ll gcd(ll a, ll b){
if(b == 0) return a;
return gcd(b, a % b);
}
ll lcm(ll x, ll y){
ll res = x / gcd(x, y);
res *= y;
return res;
};
void solve(){
while(true){
int n, m;
cin >> n >> m;
if(n == 0 && m == 0) return;
vector<int> s(n), t(m);
rep(i, n) cin >> s[i];
rep(i, m) cin >> t[i];
int S = 0, T = 0;
rep(i, n) S += s[i];
rep(i, m) T += t[i];
pair<int, pair<int, int>> ans = {INF, {INF, INF}};
rep(i, n)rep(j, m){
if(S - s[i] + t[j] == T - t[j] + s[i]){
ans = min(ans, {s[i] + t[j], {s[i], t[j]}});
}
}
if(ans.f == INF) cout << -1 << endl;
else cout << ans.s.f << " " << ans.s.s << endl;
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
solve();
}
|
Java | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni();
int K = ni();
int[] a = na(n);
int mod = 1000000007;
long[] dp = new long[K+1];
dp[0] = 1;
for(int i = 0;i < n;i++){
for(int j = K-a[i]-1;j >= 0;j--) {
dp[j+a[i]+1] += mod-dp[j];
}
for(int j = 0;j <= K;j++){
if(j > 0)dp[j] += dp[j-1];
dp[j] %= mod;
}
}
out.println(dp[K]);
}
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)); }
}
| C++ | #include <bits/stdc++.h>
using namespace std;
//関数
int ksum(int X){
int ks=0;
while(X>0){
ks+=X%10;
X-=X%10;
X/=10;
}
return ks;
}
//main関数
int main() {
//入力
int N;
cin>>N;
//計算
int result =1000000;
for(int A=1;A<N;A++){
result=min(ksum(A)+ksum(N-A),result);
//cout <<A<<" "<<N-A<<" "<<ksum(A)+ksum(N-A)<<endl;
}
//出力
cout <<result<<endl;
} | No | Do these codes solve the same problem?
Code 1: import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni();
int K = ni();
int[] a = na(n);
int mod = 1000000007;
long[] dp = new long[K+1];
dp[0] = 1;
for(int i = 0;i < n;i++){
for(int j = K-a[i]-1;j >= 0;j--) {
dp[j+a[i]+1] += mod-dp[j];
}
for(int j = 0;j <= K;j++){
if(j > 0)dp[j] += dp[j-1];
dp[j] %= mod;
}
}
out.println(dp[K]);
}
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: #include <bits/stdc++.h>
using namespace std;
//関数
int ksum(int X){
int ks=0;
while(X>0){
ks+=X%10;
X-=X%10;
X/=10;
}
return ks;
}
//main関数
int main() {
//入力
int N;
cin>>N;
//計算
int result =1000000;
for(int A=1;A<N;A++){
result=min(ksum(A)+ksum(N-A),result);
//cout <<A<<" "<<N-A<<" "<<ksum(A)+ksum(N-A)<<endl;
}
//出力
cout <<result<<endl;
} |
C++ | //Code by 27.
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<fstream>
#include<stdlib.h>
#include<set>
#include<climits>
#include<cmath>
#include<memory.h>
#include<sstream>
#include<time.h>
#include <iomanip>
using namespace std;
const unsigned long long BIGEST=1000000000000000000+1000000000000000000;
const long long BIGER=1000000000000000000;
const int BIG=1000000000;
const int MOD=19260817;
/*
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo^ =ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\` ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo, =/ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo` \ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooo[o\oo\oo` , ,o\o/\\ooo`ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooo//\ \. =\ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo\` ,\`,ooo/]`* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo/oo` .\ooo\[ ,/\ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\^ =\\o/ ,ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo =/` =^ =oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo^ oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/ .oo/` =ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo^o=` ,\oooo/o^ ]^ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.]o/\oooooooo,.//ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo^ [oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo ,/ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/` ,\/oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\//oooooooooooooo, =^/oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo/`,`o\/ooooooooooooo` \/ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooo/\\ ,,\/\oooooooo\^ ,\oooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooo/^ `oooooooooo^ \ooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooo\\/ /\\ooooooooooo^ ,o\=ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooo` /oooooooooooooooo^ ,,^ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooo/ooo/ =o\ooooooooooooooooo` ^ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooo/ ,\oooooooooooooooo^\ ,ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooo` ,\[]/oooooooooooooo ,/ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooo/\ ]` ,`\oooooooooooooo^ oooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooo\` \o\o \ooooooooooooooo =\oooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooo/o=` /o/oooo^ \/\ooooooooooo ,ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/o ooooooooo\o/ ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/\ .o\ooooooo/ ooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo` \/ooo\o/ ooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\/ \ooo^^ ,ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo^ ./\/ oooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\/` . ,oo^ooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooo. ,ooooooooooooooo ooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooo^ `/oooooooooooo/^ oooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooo/\oo`` \/[ooo[ooooo^ ooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooo\, =. .[[[ ,\ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooo/o/o. oooo\o` \o/\ooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooo/o. ]oooooooo\ ,ooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooo` =ooooooooooooo` ,oo/\ \ooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooo =oooooooooooooooooo/oooooooooooo\/. `ooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooo^^ ,ooooooooooooooooooooooooooooooooooo\ ,ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooo\ `,/ooooooooooooooooooooooooooooooooooooo/^ o]o/ooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
*/
long long a[100001];
int main()
{
long long n;
scanf("%lld",&n);
for(long long i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
}
sort(a+1,a+1+n);
long long mn=BIG;
int t;
for(int i=0;i<n;i++)
{
if(abs(a[n]/2-(a[n]-a[i]))<=mn)
{
t=i;
mn=abs(a[n]/2-(a[n]-a[i]));
}
}
cout<<a[n]<<" "<<a[t];
return 0;
} | Java |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[N];
for(int i = 0; i < N; i++) arr[i] = sc.nextInt();
int res = Integer.MAX_VALUE;
int tmp = Integer.MAX_VALUE;
for(int i = 0; i + (k - 1)< N; i++) {
int l = arr[i];
int r = arr[i+k-1];
tmp = Math.min(Math.abs(l) + Math.abs(l-r), Math.abs(r) + Math.abs(l-r));
res = Math.min(tmp, res);
}
System.out.println(res);
}
}
| No | Do these codes solve the same problem?
Code 1: //Code by 27.
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<fstream>
#include<stdlib.h>
#include<set>
#include<climits>
#include<cmath>
#include<memory.h>
#include<sstream>
#include<time.h>
#include <iomanip>
using namespace std;
const unsigned long long BIGEST=1000000000000000000+1000000000000000000;
const long long BIGER=1000000000000000000;
const int BIG=1000000000;
const int MOD=19260817;
/*
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo^ =ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\` ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo, =/ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo` \ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooo[o\oo\oo` , ,o\o/\\ooo`ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooo//\ \. =\ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo\` ,\`,ooo/]`* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo/oo` .\ooo\[ ,/\ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\^ =\\o/ ,ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo =/` =^ =oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo^ oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/ .oo/` =ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo^o=` ,\oooo/o^ ]^ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.]o/\oooooooo,.//ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo^ [oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo ,/ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/` ,\/oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\//oooooooooooooo, =^/oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo/`,`o\/ooooooooooooo` \/ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooo/\\ ,,\/\oooooooo\^ ,\oooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooo/^ `oooooooooo^ \ooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooo\\/ /\\ooooooooooo^ ,o\=ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooo` /oooooooooooooooo^ ,,^ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooo/ooo/ =o\ooooooooooooooooo` ^ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooo/ ,\oooooooooooooooo^\ ,ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooo` ,\[]/oooooooooooooo ,/ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooo/\ ]` ,`\oooooooooooooo^ oooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooo\` \o\o \ooooooooooooooo =\oooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooo/o=` /o/oooo^ \/\ooooooooooo ,ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/o ooooooooo\o/ ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/\ .o\ooooooo/ ooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo` \/ooo\o/ ooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\/ \ooo^^ ,ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo^ ./\/ oooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\/` . ,oo^ooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooo. ,ooooooooooooooo ooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooo^ `/oooooooooooo/^ oooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooo/\oo`` \/[ooo[ooooo^ ooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooo\, =. .[[[ ,\ooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooo/o/o. oooo\o` \o/\ooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooo/o. ]oooooooo\ ,ooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooo` =ooooooooooooo` ,oo/\ \ooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooo =oooooooooooooooooo/oooooooooooo\/. `ooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooo^^ ,ooooooooooooooooooooooooooooooooooo\ ,ooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooo\ `,/ooooooooooooooooooooooooooooooooooooo/^ o]o/ooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
*/
long long a[100001];
int main()
{
long long n;
scanf("%lld",&n);
for(long long i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
}
sort(a+1,a+1+n);
long long mn=BIG;
int t;
for(int i=0;i<n;i++)
{
if(abs(a[n]/2-(a[n]-a[i]))<=mn)
{
t=i;
mn=abs(a[n]/2-(a[n]-a[i]));
}
}
cout<<a[n]<<" "<<a[t];
return 0;
}
Code 2:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[N];
for(int i = 0; i < N; i++) arr[i] = sc.nextInt();
int res = Integer.MAX_VALUE;
int tmp = Integer.MAX_VALUE;
for(int i = 0; i + (k - 1)< N; i++) {
int l = arr[i];
int r = arr[i+k-1];
tmp = Math.min(Math.abs(l) + Math.abs(l-r), Math.abs(r) + Math.abs(l-r));
res = Math.min(tmp, res);
}
System.out.println(res);
}
}
|
Python | import sys
stdin = sys.stdin
ni = lambda: int(ns()) #int
na = lambda: list(map(int, stdin.readline().split())) #int,list
ns = lambda: stdin.readline().rstrip() # str
n=ni()
b=na()
ans=[]
def solve(li):
for i in range(1,len(li)+1):
if li[len(li)-i]==len(li)-i+1:
a=li.pop(len(li)-i)
ans.append(a)
return solve(li)
solve(b)
if len(ans)==n:
for i in range(n):
print(ans[n-i-1])
else:
print(-1) | C++ | #include <bits/stdc++.h>
#define fst(t) std::get<0>(t)
#define snd(t) std::get<1>(t)
#define thd(t) std::get<2>(t)
#define unless(p) if(!(p))
#define until(p) while(!(p))
using ll = std::int64_t;
using P = std::tuple<int,int>;
int N;
std::string S;
int main(){
std::cin.tie(nullptr);
std::ios::sync_with_stdio(false);
std::cin >> N >> S;
ll res = 1ll * std::count(S.begin(), S.end(), 'R') * std::count(S.begin(), S.end(), 'G') * std::count(S.begin(), S.end(), 'B');
for(int i=0;i<N;++i){
for(int l=1;i+l*2<N;++l){
int j = i + l, k = j + l;
if(S[i] != S[j] && S[j] != S[k] && S[k] != S[i]){
res -= 1;
}
}
}
std::cout << res << std::endl;
}
| No | Do these codes solve the same problem?
Code 1: import sys
stdin = sys.stdin
ni = lambda: int(ns()) #int
na = lambda: list(map(int, stdin.readline().split())) #int,list
ns = lambda: stdin.readline().rstrip() # str
n=ni()
b=na()
ans=[]
def solve(li):
for i in range(1,len(li)+1):
if li[len(li)-i]==len(li)-i+1:
a=li.pop(len(li)-i)
ans.append(a)
return solve(li)
solve(b)
if len(ans)==n:
for i in range(n):
print(ans[n-i-1])
else:
print(-1)
Code 2: #include <bits/stdc++.h>
#define fst(t) std::get<0>(t)
#define snd(t) std::get<1>(t)
#define thd(t) std::get<2>(t)
#define unless(p) if(!(p))
#define until(p) while(!(p))
using ll = std::int64_t;
using P = std::tuple<int,int>;
int N;
std::string S;
int main(){
std::cin.tie(nullptr);
std::ios::sync_with_stdio(false);
std::cin >> N >> S;
ll res = 1ll * std::count(S.begin(), S.end(), 'R') * std::count(S.begin(), S.end(), 'G') * std::count(S.begin(), S.end(), 'B');
for(int i=0;i<N;++i){
for(int l=1;i+l*2<N;++l){
int j = i + l, k = j + l;
if(S[i] != S[j] && S[j] != S[k] && S[k] != S[i]){
res -= 1;
}
}
}
std::cout << res << std::endl;
}
|
Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
var tree map[int]map[int]int64
var color []int
func main() {
var n int = NextInt()
tree = make(map[int]map[int]int64)
color = make([]int,n)
for i:=0;i<n;i++ {
tree[i] = map[int]int64{}
color[i] = -1
}
for i:=0;i<n-1;i++ {
var u,v,w int = NextInts()
tree[u-1][v-1] = int64(w)
tree[v-1][u-1] = int64(w)
}
dfs(0,-1,0)
for i:=0;i<n;i++ { fmt.Println(color[i]) }
}
func dfs(v,p int,d int64) {
color[v] = int(d%2)
for u,w := range tree[v] {
if u == p { continue }
dfs(u,v,d+w)
}
}
var reader = bufio.NewReaderSize(os.Stdin,1000000)
func NextLine() string {
var line,buffer []byte
var isPrefix bool = true
var err error
for ;isPrefix; {
line,isPrefix,err = reader.ReadLine()
if err != nil { panic(err) }
buffer = append(buffer,line...)
}
return string(buffer)
}
func NextInt() int {
var x int
x,_ = strconv.Atoi(NextLine())
return x
}
func NextInts() (int,int,int) {
var x,y,z int
var s []string = strings.Split(NextLine()," ")
x,_ = strconv.Atoi(s[0])
y,_ = strconv.Atoi(s[1])
z,_ = strconv.Atoi(s[2])
return x,y,z
} | PHP | <?php
$n = trim(fgets(STDIN));
for($i = 0; $i < $n-1; $i++){
list($from, $to, $length) = explode(" ", trim(fgets(STDIN)));
$connect[$from][$to] = $length;
$connect[$to][$from] = $length;
}
for($i = 1; $i <= $n; $i++){
$map[$i] = false;
}
dfs(1, 0);
for($i = 1; $i <= $n; $i++){
echo $map[$i]."\n";
}
function dfs($from, $color){
global $map;
global $connect;
$map[$from] = $color;
foreach($connect[$from] as $to => $length){
if($map[$to] === false){
if($length % 2 == 1){
dfs($to, 1 - $color);
}else{
dfs($to, $color);
}
}
}
}
| Yes | Do these codes solve the same problem?
Code 1: package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
var tree map[int]map[int]int64
var color []int
func main() {
var n int = NextInt()
tree = make(map[int]map[int]int64)
color = make([]int,n)
for i:=0;i<n;i++ {
tree[i] = map[int]int64{}
color[i] = -1
}
for i:=0;i<n-1;i++ {
var u,v,w int = NextInts()
tree[u-1][v-1] = int64(w)
tree[v-1][u-1] = int64(w)
}
dfs(0,-1,0)
for i:=0;i<n;i++ { fmt.Println(color[i]) }
}
func dfs(v,p int,d int64) {
color[v] = int(d%2)
for u,w := range tree[v] {
if u == p { continue }
dfs(u,v,d+w)
}
}
var reader = bufio.NewReaderSize(os.Stdin,1000000)
func NextLine() string {
var line,buffer []byte
var isPrefix bool = true
var err error
for ;isPrefix; {
line,isPrefix,err = reader.ReadLine()
if err != nil { panic(err) }
buffer = append(buffer,line...)
}
return string(buffer)
}
func NextInt() int {
var x int
x,_ = strconv.Atoi(NextLine())
return x
}
func NextInts() (int,int,int) {
var x,y,z int
var s []string = strings.Split(NextLine()," ")
x,_ = strconv.Atoi(s[0])
y,_ = strconv.Atoi(s[1])
z,_ = strconv.Atoi(s[2])
return x,y,z
}
Code 2: <?php
$n = trim(fgets(STDIN));
for($i = 0; $i < $n-1; $i++){
list($from, $to, $length) = explode(" ", trim(fgets(STDIN)));
$connect[$from][$to] = $length;
$connect[$to][$from] = $length;
}
for($i = 1; $i <= $n; $i++){
$map[$i] = false;
}
dfs(1, 0);
for($i = 1; $i <= $n; $i++){
echo $map[$i]."\n";
}
function dfs($from, $color){
global $map;
global $connect;
$map[$from] = $color;
foreach($connect[$from] as $to => $length){
if($map[$to] === false){
if($length % 2 == 1){
dfs($to, 1 - $color);
}else{
dfs($to, $color);
}
}
}
}
|
Python | # 石の番号は0-initial
N=int(input())
S=input()
# 0~iまでの石を白'.',i+1~N-1までの石を黒'#'にする必要がある
L=[0] # iより左の黒石の個数
for i in range(N):
L.append(L[-1]+int(S[i]=='#'))
R=[0] # i-1より右(i以右)の白石の個数(右から数えて後で反転させる)
for i in range(N-1,-1,-1):
R.append(R[-1]+int(S[i]=='.'))
R=R[::-1]
ans=min([L[i]+R[i] for i in range(N+1)])
print(ans) | C++ | #include <bits/stdc++.h>
using namespace std;
#define int long long
signed main()
{
string a, b;
cin >> a >> b;
int n = a.size();
int ans = 0;
for (int i = 0; i < n; i++)
ans += a[i] != b[i];
cout << ans << endl;
} | No | Do these codes solve the same problem?
Code 1: # 石の番号は0-initial
N=int(input())
S=input()
# 0~iまでの石を白'.',i+1~N-1までの石を黒'#'にする必要がある
L=[0] # iより左の黒石の個数
for i in range(N):
L.append(L[-1]+int(S[i]=='#'))
R=[0] # i-1より右(i以右)の白石の個数(右から数えて後で反転させる)
for i in range(N-1,-1,-1):
R.append(R[-1]+int(S[i]=='.'))
R=R[::-1]
ans=min([L[i]+R[i] for i in range(N+1)])
print(ans)
Code 2: #include <bits/stdc++.h>
using namespace std;
#define int long long
signed main()
{
string a, b;
cin >> a >> b;
int n = a.size();
int ans = 0;
for (int i = 0; i < n; i++)
ans += a[i] != b[i];
cout << ans << endl;
} |
C++ | #include<iostream>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
if(a<=0&&b>=0){
cout<<"Zero"<<endl;
}
else if(a>0&&b>0){
cout<<"Positive"<<endl;
}
else if(a<0&&b<0&&(b-a)%2==0){
cout<<"Negative"<<endl;
}
else{
cout<<"Positive"<<endl;
}
return 0;
} | Python | #-*-coding:utf-8-*-
import sys
input=sys.stdin.readline
def main():
numbers=[]
a,b = map(int,input().split())
numbers=list(range(a,b+1))
count=0
for number in numbers:
if str(number)[0]==str(number)[-1] and str(number)[1]== str(number)[3]:
count+=1
print(count)
if __name__=="__main__":
main() | No | Do these codes solve the same problem?
Code 1: #include<iostream>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
if(a<=0&&b>=0){
cout<<"Zero"<<endl;
}
else if(a>0&&b>0){
cout<<"Positive"<<endl;
}
else if(a<0&&b<0&&(b-a)%2==0){
cout<<"Negative"<<endl;
}
else{
cout<<"Positive"<<endl;
}
return 0;
}
Code 2: #-*-coding:utf-8-*-
import sys
input=sys.stdin.readline
def main():
numbers=[]
a,b = map(int,input().split())
numbers=list(range(a,b+1))
count=0
for number in numbers:
if str(number)[0]==str(number)[-1] and str(number)[1]== str(number)[3]:
count+=1
print(count)
if __name__=="__main__":
main() |
C | // AOJ 2664: Shopping
// 2017.12.3 bal4u@uu
#include <stdio.h>
#include <string.h>
#define HASHSIZ 15013
typedef struct { char *s; int id, w; } HASH;
HASH hash[HASHSIZ+2], *hashend = hash + HASHSIZ; // Hash table
void insert(char *s, int w, int id)
{
HASH *tp = hash + (101 * *s + 103 * *(s+w-1) + 107 * w) % HASHSIZ;
while (tp->s != NULL) {
if (tp->w == w && memcmp(tp->s, s, w) == 0) return;
if (++tp == hashend) tp = hash;
}
tp->s = s, tp->id = id, tp->w = w;
}
int lookup(char *s, int w)
{
HASH *tp = hash + (101 * *s + 103 * *(s+w-1) + 107 * w) % HASHSIZ;
while (tp->s != NULL) {
if (tp->w == w && memcmp(tp->s, s, w) == 0) break;
if (++tp == hashend) tp = hash;
}
return tp->id;
}
#define MAX 5002
/* UNION-FIND library */
int p[MAX], rank[MAX];
void make_set(int x) { p[x] = x, rank[x] = 0; }
void link(int x, int y) {
if (rank[x] > rank[y]) p[y] = x;
else { p[x] = y; if (rank[x] == rank[y]) rank[y] = rank[y] + 1; }
}
int find_set(int x) { if (x != p[x]) p[x] = find_set(p[x]); return p[x]; }
void union_set(int x, int y) { link(find_set(x), find_set(y)); }
int x[MAX];
char s[MAX][20];
char buf[30], *bp;
int getint()
{
int n = 0;
while (*bp >= '0') n = (n<<3) + (n<<1) + (*bp++ & 0xf);
return n;
}
int main()
{
int n, m, i, j, ans;
char *q;
fgets(bp=buf, 10, stdin), n = getint();
for (i = 0; i < n; i++) p[i] = i;
for (i = 0; i < n; i++) {
fgets(bp=s[i], 20, stdin);
q = bp; while (*bp >= 'a') bp++;
insert(q, bp-q, i);
bp++, x[i] = getint();
}
fgets(bp=buf, 10, stdin), m = getint();
while (m--) {
fgets(bp=buf, 30, stdin);
q = bp; while (*bp >= 'a') bp++;
i = lookup(q, bp-q);
q = ++bp; while (*bp >= 'a') bp++;
j = lookup(q, bp-q);
union_set(i, j);
}
for (i = 0; i < n; i++) {
j = find_set(i);
if (x[i] < x[j]) x[j] = x[i];
}
for (ans = 0, i = 0; i < n; i++) ans += x[p[i]];
printf("%d\n", ans);
return 0;
} | C++ | #include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)
#define all(c) c.begin(),c.end()
#define pb push_back
#define fs first
#define sc second
#define show(x) cout << #x << " = " << x << endl
#define chmin(x,y) x=min(x,y)
#define chmax(x,y) x=max(x,y)
using namespace std;
int N,x[5000],M;
map<string,int> msi;
int par[5000],mn[5000],n[5000];
void init(int N){rep(i,N) par[i]=i,mn[i]=x[i],n[i]=1;}
int find(int x){
if(x==par[x]) return x;
return par[x]=find(par[x]);
}
void unite(int x,int y){
x=find(x),y=find(y);
if(x==y) return;
par[x]=y;
mn[y]=min(mn[x],mn[y]);
n[y]+=n[x];
}
int main(){
cin>>N;
rep(i,N){
string s;
cin>>s>>x[i];
msi[s]=i;
}
init(N);
cin>>M;
rep(i,M){
string a,b;
cin>>a>>b;
int p=msi[a],q=msi[b];
unite(p,q);
}
int ans=0;
rep(i,N) if(find(i)==i) ans+=mn[i]*n[i];
cout<<ans<<endl;
} | Yes | Do these codes solve the same problem?
Code 1: // AOJ 2664: Shopping
// 2017.12.3 bal4u@uu
#include <stdio.h>
#include <string.h>
#define HASHSIZ 15013
typedef struct { char *s; int id, w; } HASH;
HASH hash[HASHSIZ+2], *hashend = hash + HASHSIZ; // Hash table
void insert(char *s, int w, int id)
{
HASH *tp = hash + (101 * *s + 103 * *(s+w-1) + 107 * w) % HASHSIZ;
while (tp->s != NULL) {
if (tp->w == w && memcmp(tp->s, s, w) == 0) return;
if (++tp == hashend) tp = hash;
}
tp->s = s, tp->id = id, tp->w = w;
}
int lookup(char *s, int w)
{
HASH *tp = hash + (101 * *s + 103 * *(s+w-1) + 107 * w) % HASHSIZ;
while (tp->s != NULL) {
if (tp->w == w && memcmp(tp->s, s, w) == 0) break;
if (++tp == hashend) tp = hash;
}
return tp->id;
}
#define MAX 5002
/* UNION-FIND library */
int p[MAX], rank[MAX];
void make_set(int x) { p[x] = x, rank[x] = 0; }
void link(int x, int y) {
if (rank[x] > rank[y]) p[y] = x;
else { p[x] = y; if (rank[x] == rank[y]) rank[y] = rank[y] + 1; }
}
int find_set(int x) { if (x != p[x]) p[x] = find_set(p[x]); return p[x]; }
void union_set(int x, int y) { link(find_set(x), find_set(y)); }
int x[MAX];
char s[MAX][20];
char buf[30], *bp;
int getint()
{
int n = 0;
while (*bp >= '0') n = (n<<3) + (n<<1) + (*bp++ & 0xf);
return n;
}
int main()
{
int n, m, i, j, ans;
char *q;
fgets(bp=buf, 10, stdin), n = getint();
for (i = 0; i < n; i++) p[i] = i;
for (i = 0; i < n; i++) {
fgets(bp=s[i], 20, stdin);
q = bp; while (*bp >= 'a') bp++;
insert(q, bp-q, i);
bp++, x[i] = getint();
}
fgets(bp=buf, 10, stdin), m = getint();
while (m--) {
fgets(bp=buf, 30, stdin);
q = bp; while (*bp >= 'a') bp++;
i = lookup(q, bp-q);
q = ++bp; while (*bp >= 'a') bp++;
j = lookup(q, bp-q);
union_set(i, j);
}
for (i = 0; i < n; i++) {
j = find_set(i);
if (x[i] < x[j]) x[j] = x[i];
}
for (ans = 0, i = 0; i < n; i++) ans += x[p[i]];
printf("%d\n", ans);
return 0;
}
Code 2: #include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)
#define all(c) c.begin(),c.end()
#define pb push_back
#define fs first
#define sc second
#define show(x) cout << #x << " = " << x << endl
#define chmin(x,y) x=min(x,y)
#define chmax(x,y) x=max(x,y)
using namespace std;
int N,x[5000],M;
map<string,int> msi;
int par[5000],mn[5000],n[5000];
void init(int N){rep(i,N) par[i]=i,mn[i]=x[i],n[i]=1;}
int find(int x){
if(x==par[x]) return x;
return par[x]=find(par[x]);
}
void unite(int x,int y){
x=find(x),y=find(y);
if(x==y) return;
par[x]=y;
mn[y]=min(mn[x],mn[y]);
n[y]+=n[x];
}
int main(){
cin>>N;
rep(i,N){
string s;
cin>>s>>x[i];
msi[s]=i;
}
init(N);
cin>>M;
rep(i,M){
string a,b;
cin>>a>>b;
int p=msi[a],q=msi[b];
unite(p,q);
}
int ans=0;
rep(i,N) if(find(i)==i) ans+=mn[i]*n[i];
cout<<ans<<endl;
} |
Python | x=input()
a=input()
b=input()
x=int(x)
a=int(a)
b=int(b)
x=(x-a)%b
print (x)
| Java | import java.util.*;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int d = scan.nextInt();
if(a * b < c * d){
System.out.println(c * d);
}else{
System.out.println(a * b);
}
}
} | No | Do these codes solve the same problem?
Code 1: x=input()
a=input()
b=input()
x=int(x)
a=int(a)
b=int(b)
x=(x-a)%b
print (x)
Code 2: import java.util.*;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int d = scan.nextInt();
if(a * b < c * d){
System.out.println(c * d);
}else{
System.out.println(a * b);
}
}
} |
C++ | #include<iostream>
#include<string>
using namespace std;
int main(void){
int n,y;
string str,ans;
string s="abcdefghijklmnopqrstuvwxyz";
cin >> n;
getline(cin,str);
for(int i=0;i<n;i++){
getline(cin,str);
for(int a=0;a<=100;a++){
for(int b=0;b<=100;b++){
ans.clear();
for(int i=0;i<str.size();i++){
if(str[i]==' '){
ans+=' ';
continue;
}
for(int j=0;;j++){
if(str[i]==s[j]){
y=j;
break;
}
}
ans+=s[((a*y)+b)%26];
}
if(ans.find("that")==-1 && ans.find("this")==-1) continue;
cout << ans << endl;
goto lbl;
}
}
lbl:;
}
}
| Java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class Main {
public static String encodeByAffin(int a, int b, String str) {
StringBuilder sb = new StringBuilder();
int l = str.length();
for (int i = 0 ; i < l ; i++) {
char c = str.charAt(i);
if (c == ' ') sb.append(' ');
else {
char cp = (char) ((a*(c-97)+b)%26 + 97);
sb.append(cp);
}
}
return sb.toString();
}
public static String decodeAffin(int a, int b, String crypt) {
char[] table = new char[123];
for (int i = 97 ; i < 123 ; i++) {
table[(char) ((a*(i-97)+b)%26 + 97)] = (char) i;
}
int l = crypt.length();
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < l ; i++) {
char c = crypt.charAt(i);
if (c == ' ') sb.append(' ');
else sb.append(table[c]);
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Main m = new Main();
List<Integer> alphas = Arrays.asList(1,3,5,7,9,11,15,17,19,21,23,25);
List<Integer> betas = Arrays.asList(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);
int N = Integer.parseInt(br.readLine());
for (int i = 0 ; i < N ; i++) {
String crypt = br.readLine();
int alpha = 0, beta = 0;
LOOP: for (int a : alphas) {
for (int b : betas) {
String THIS = encodeByAffin(a, b, "this");
String THAT = encodeByAffin(a, b, "that");
if (crypt.contains(THIS) || crypt.contains(THAT)) {
//System.out.println("a:"+a+" b:"+b);
alpha = a; beta = b;
break LOOP;
}
}
}
System.out.println(decodeAffin(alpha, beta, crypt));
}
}
} | Yes | Do these codes solve the same problem?
Code 1: #include<iostream>
#include<string>
using namespace std;
int main(void){
int n,y;
string str,ans;
string s="abcdefghijklmnopqrstuvwxyz";
cin >> n;
getline(cin,str);
for(int i=0;i<n;i++){
getline(cin,str);
for(int a=0;a<=100;a++){
for(int b=0;b<=100;b++){
ans.clear();
for(int i=0;i<str.size();i++){
if(str[i]==' '){
ans+=' ';
continue;
}
for(int j=0;;j++){
if(str[i]==s[j]){
y=j;
break;
}
}
ans+=s[((a*y)+b)%26];
}
if(ans.find("that")==-1 && ans.find("this")==-1) continue;
cout << ans << endl;
goto lbl;
}
}
lbl:;
}
}
Code 2: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class Main {
public static String encodeByAffin(int a, int b, String str) {
StringBuilder sb = new StringBuilder();
int l = str.length();
for (int i = 0 ; i < l ; i++) {
char c = str.charAt(i);
if (c == ' ') sb.append(' ');
else {
char cp = (char) ((a*(c-97)+b)%26 + 97);
sb.append(cp);
}
}
return sb.toString();
}
public static String decodeAffin(int a, int b, String crypt) {
char[] table = new char[123];
for (int i = 97 ; i < 123 ; i++) {
table[(char) ((a*(i-97)+b)%26 + 97)] = (char) i;
}
int l = crypt.length();
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < l ; i++) {
char c = crypt.charAt(i);
if (c == ' ') sb.append(' ');
else sb.append(table[c]);
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Main m = new Main();
List<Integer> alphas = Arrays.asList(1,3,5,7,9,11,15,17,19,21,23,25);
List<Integer> betas = Arrays.asList(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);
int N = Integer.parseInt(br.readLine());
for (int i = 0 ; i < N ; i++) {
String crypt = br.readLine();
int alpha = 0, beta = 0;
LOOP: for (int a : alphas) {
for (int b : betas) {
String THIS = encodeByAffin(a, b, "this");
String THAT = encodeByAffin(a, b, "that");
if (crypt.contains(THIS) || crypt.contains(THAT)) {
//System.out.println("a:"+a+" b:"+b);
alpha = a; beta = b;
break LOOP;
}
}
}
System.out.println(decodeAffin(alpha, beta, crypt));
}
}
} |
Python | a,b,c = input().split()
print('A'+b[0] +'C')
| C++ | #include <bits/stdc++.h>
int main()
{
int N, X, T;
std::cin >> N >> X >> T;
int ans;
ans = (N/X)*T;
if((N/X)*X != N)
{
ans+=T;
}
std::cout << ans << std::endl;
} | No | Do these codes solve the same problem?
Code 1: a,b,c = input().split()
print('A'+b[0] +'C')
Code 2: #include <bits/stdc++.h>
int main()
{
int N, X, T;
std::cin >> N >> X >> T;
int ans;
ans = (N/X)*T;
if((N/X)*X != N)
{
ans+=T;
}
std::cout << ans << std::endl;
} |
C++ | #include <iostream>
using namespace std;
int main(int argc, char const* argv[])
{
int n, m;
int a[100][100] = {{}}, b[100] = {};
int answer[100] = {};
cin >> n >> m;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
cin >> a[i][j];
}
}
for (int i=0; i<m; i++) {
cin >> b[i];
}
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
answer[i] += a[i][j] * b[j];
}
}
for (int i=0; i<n; i++) {
cout << answer[i] << endl;
}
return 0;
}
| Java | import java.util.*;
//update 2020/1/1 23:01
public class Main{
static Scanner sc = new Scanner(System.in);
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
int n = nextInt();
int m = nextInt();
int[] a = new int[n];
int sum = 0;
for(int i=0;i<n;i++){
a[i] = nextInt();
sum += a[i];
}
Arrays.sort(a);
for(int i=0;i<n/2;i++){
int tmp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = tmp;
}
if(a[m-1]*4*m>=sum){
System.out.println("Yes");
}
else{
System.out.println("No");
}
//System.out.println();
}
/*
static String toSmall(String s){
char c = s.charAt(0);
//if(Character.isUpperCase(c)){
if(c<=90){
c += 32;
}
return String.valueOf(c);
}
static String toBig(String s){
char c = s.charAt(0);
//if(Character.isLowerCase(c)){
if(c>=97){
c -= 32;
}
return String.valueOf(c);
}
*/
static String toSmall(String s){
return s.toLowerCase();
}
static String toBig(String s){
return s.toUpperCase();
}
static String next(){
return sc.next();
}
static int nextInt(){
return Integer.parseInt(sc.next());
}
static long nextLong(){
return Long.parseLong(sc.next());
}
static double nextDouble(){
return Double.parseDouble(sc.next());
}
static String[] splitString(String s){
return s.split("");
}
static char[] splitChar(String s){
return s.toCharArray();
}
static int charToInt(char a){
return a - 48;
}
////////////////////////////////////////////
public static int max(int[] a){
int lng = a.length;
int max = a[0];
for(int i=1;i<lng;i++){
max = Math.max(max,a[i]);
}
return max;
}
public static long max(long[] a){
int lng = a.length;
long max = a[0];
for(int i=1;i<lng;i++){
max = Math.max(max,a[i]);
}
return max;
}
////////////////////////////////////////////
////////////////////////////////////////////
public static int min(int[] a){
int lng = a.length;
int min = a[0];
for(int i=1;i<lng;i++){
min = Math.min(min,a[i]);
}
return min;
}
public static long min(long[] a){
int lng = a.length;
long min = a[0];
for(int i=1;i<lng;i++){
min = Math.min(min,a[i]);
}
return min;
}
////////////////////////////////////////////
}
| No | Do these codes solve the same problem?
Code 1: #include <iostream>
using namespace std;
int main(int argc, char const* argv[])
{
int n, m;
int a[100][100] = {{}}, b[100] = {};
int answer[100] = {};
cin >> n >> m;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
cin >> a[i][j];
}
}
for (int i=0; i<m; i++) {
cin >> b[i];
}
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
answer[i] += a[i][j] * b[j];
}
}
for (int i=0; i<n; i++) {
cout << answer[i] << endl;
}
return 0;
}
Code 2: import java.util.*;
//update 2020/1/1 23:01
public class Main{
static Scanner sc = new Scanner(System.in);
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
int n = nextInt();
int m = nextInt();
int[] a = new int[n];
int sum = 0;
for(int i=0;i<n;i++){
a[i] = nextInt();
sum += a[i];
}
Arrays.sort(a);
for(int i=0;i<n/2;i++){
int tmp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = tmp;
}
if(a[m-1]*4*m>=sum){
System.out.println("Yes");
}
else{
System.out.println("No");
}
//System.out.println();
}
/*
static String toSmall(String s){
char c = s.charAt(0);
//if(Character.isUpperCase(c)){
if(c<=90){
c += 32;
}
return String.valueOf(c);
}
static String toBig(String s){
char c = s.charAt(0);
//if(Character.isLowerCase(c)){
if(c>=97){
c -= 32;
}
return String.valueOf(c);
}
*/
static String toSmall(String s){
return s.toLowerCase();
}
static String toBig(String s){
return s.toUpperCase();
}
static String next(){
return sc.next();
}
static int nextInt(){
return Integer.parseInt(sc.next());
}
static long nextLong(){
return Long.parseLong(sc.next());
}
static double nextDouble(){
return Double.parseDouble(sc.next());
}
static String[] splitString(String s){
return s.split("");
}
static char[] splitChar(String s){
return s.toCharArray();
}
static int charToInt(char a){
return a - 48;
}
////////////////////////////////////////////
public static int max(int[] a){
int lng = a.length;
int max = a[0];
for(int i=1;i<lng;i++){
max = Math.max(max,a[i]);
}
return max;
}
public static long max(long[] a){
int lng = a.length;
long max = a[0];
for(int i=1;i<lng;i++){
max = Math.max(max,a[i]);
}
return max;
}
////////////////////////////////////////////
////////////////////////////////////////////
public static int min(int[] a){
int lng = a.length;
int min = a[0];
for(int i=1;i<lng;i++){
min = Math.min(min,a[i]);
}
return min;
}
public static long min(long[] a){
int lng = a.length;
long min = a[0];
for(int i=1;i<lng;i++){
min = Math.min(min,a[i]);
}
return min;
}
////////////////////////////////////////////
}
|
JavaScript | "use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}
var mod = 998244353;
function mul(){for(var a=arguments,r=a[0],i=a.length;--i;)r=((r>>16)*a[i]%mod*65536+(r&65535)*a[i])%mod;return r;}
var fac=[],finv=[],invs=[],pow2=[];
function fset(n){
fac.length=n+1,fac[0]=fac[1]=1;
for(var i=2;i<=n;)fac[i]=mul(fac[i-1],i++);
finv.length=n+1,finv[0]=finv[1]=1,finv[n]=inv(fac[n]);
for(i=n;2<i;)finv[i-1]=mul(finv[i],i--);
//invs.length=n+1,invs[0]=invs[1]=1;
//for(i=2;i<=n;)invs[i]=mul(fac[i-1],finv[i++]);
//pow2.length=n+1,pow2[0]=1;
//for(i=1;i<=n;i++)pow2[i]=pow2[i-1]*2%mod;
}
function inv(b){for(var a=mod,u=0,v=1,t;b;v=t)t=a/b|0,a-=t*b,u-=t*v,t=a,a=b,b=t,t=u,u=v;u%=mod;return u<0?u+mod:u;}
function pow(a,n){for(var r=1;n;a=mul(a,a),n>>=1)if(n&1)r=mul(a,r);return r;}
function ncr(n,r){return mul(fac[n],finv[r],finv[n-r]);}
function npr(n,r){return mul(fac[n],finv[n-r]);}
function mput(n){return (n%mod+mod)%mod;}
var myOut = main();
if(myOut !== undefined)console.log(myOut);
function main(){
var [a,b,c,d] = nexts(4);
var dp = xArray(0,c+1,d+1);
dp[a][b] = 1;
for(var y = a; y <= c; y++){
for(var x = b; x <= d; x++){
dp[y][x] += dp[y-1][x] * x + dp[y][x-1] * y - mul(dp[y-1][x-1], y-1, x-1);
dp[y][x] %= mod;
}
}
return mput(dp[c][d]);
} | Kotlin |
import java.util.*
fun main() {
val sc = Scanner(System.`in`)
val mod = 998244353.toLong()
val a = sc.nextInt()
val b = sc.nextInt()
val c = sc.nextInt()
val d = sc.nextInt()
val dp = Array(c+1){LongArray(d+1){-1L} }
fun solve(r:Int, c:Int): Long {
if(r < a || c < b)
return 0L
if(r==a && c == b) {
return 1L
}
if(dp[r][c] != -1L) {
return dp[r][c]
}
// column 붙인 경우
var cnt = 0L
cnt += solve(r-1, c) * c
cnt %= mod
cnt += solve(r, c - 1) * r
cnt %= mod
var x = ((r-1) * (c-1)).toLong()
x *= solve(r - 1, c - 1)
x %= mod
cnt = cnt - x + mod
cnt %= mod
dp[r][c] = cnt
return cnt
}
print(solve(c, d))
//println(".")
//[a,b] -> [c,d]
//
} | Yes | Do these codes solve the same problem?
Code 1: "use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}
var mod = 998244353;
function mul(){for(var a=arguments,r=a[0],i=a.length;--i;)r=((r>>16)*a[i]%mod*65536+(r&65535)*a[i])%mod;return r;}
var fac=[],finv=[],invs=[],pow2=[];
function fset(n){
fac.length=n+1,fac[0]=fac[1]=1;
for(var i=2;i<=n;)fac[i]=mul(fac[i-1],i++);
finv.length=n+1,finv[0]=finv[1]=1,finv[n]=inv(fac[n]);
for(i=n;2<i;)finv[i-1]=mul(finv[i],i--);
//invs.length=n+1,invs[0]=invs[1]=1;
//for(i=2;i<=n;)invs[i]=mul(fac[i-1],finv[i++]);
//pow2.length=n+1,pow2[0]=1;
//for(i=1;i<=n;i++)pow2[i]=pow2[i-1]*2%mod;
}
function inv(b){for(var a=mod,u=0,v=1,t;b;v=t)t=a/b|0,a-=t*b,u-=t*v,t=a,a=b,b=t,t=u,u=v;u%=mod;return u<0?u+mod:u;}
function pow(a,n){for(var r=1;n;a=mul(a,a),n>>=1)if(n&1)r=mul(a,r);return r;}
function ncr(n,r){return mul(fac[n],finv[r],finv[n-r]);}
function npr(n,r){return mul(fac[n],finv[n-r]);}
function mput(n){return (n%mod+mod)%mod;}
var myOut = main();
if(myOut !== undefined)console.log(myOut);
function main(){
var [a,b,c,d] = nexts(4);
var dp = xArray(0,c+1,d+1);
dp[a][b] = 1;
for(var y = a; y <= c; y++){
for(var x = b; x <= d; x++){
dp[y][x] += dp[y-1][x] * x + dp[y][x-1] * y - mul(dp[y-1][x-1], y-1, x-1);
dp[y][x] %= mod;
}
}
return mput(dp[c][d]);
}
Code 2:
import java.util.*
fun main() {
val sc = Scanner(System.`in`)
val mod = 998244353.toLong()
val a = sc.nextInt()
val b = sc.nextInt()
val c = sc.nextInt()
val d = sc.nextInt()
val dp = Array(c+1){LongArray(d+1){-1L} }
fun solve(r:Int, c:Int): Long {
if(r < a || c < b)
return 0L
if(r==a && c == b) {
return 1L
}
if(dp[r][c] != -1L) {
return dp[r][c]
}
// column 붙인 경우
var cnt = 0L
cnt += solve(r-1, c) * c
cnt %= mod
cnt += solve(r, c - 1) * r
cnt %= mod
var x = ((r-1) * (c-1)).toLong()
x *= solve(r - 1, c - 1)
x %= mod
cnt = cnt - x + mod
cnt %= mod
dp[r][c] = cnt
return cnt
}
print(solve(c, d))
//println(".")
//[a,b] -> [c,d]
//
} |
Kotlin | fun main(args: Array<String>) {
val sc = java.util.Scanner(System.`in`)
val N = sc.nextInt()
val A = arrayOf(0) + Array(N) { sc.nextInt() } + arrayOf(0)
val d = (0..(A.count() - 2)).map { i ->
val d = A[i] - A[i + 1]
if (d > 0) d else -d
}
val sum = d.sum()
for (i in 0..(N-1)) {
println(sum - d[i] - d[i + 1] + Math.abs(A[i] - A[i + 2]))
}
}
| Go | ///
// File: c.go
// Author: ymiyamoto
//
// Created on Sun Mar 25 21:07:39 2018
//
package main
import (
"fmt"
)
var N int
func diff(a, b int) int {
if a < b {
return b - a
}
return a - b
}
func main() {
fmt.Scan(&N)
arr := make([]int, N+2)
prev := 0
total := 0
for i := 1; i <= N; i++ {
fmt.Scan(&arr[i])
total += diff(prev, arr[i])
prev = arr[i]
}
total += diff(0, prev)
prev = 0
for i := 1; i <= N; i++ {
var d int
if prev < arr[i] {
if arr[i] < arr[i+1] {
d = 0
} else {
d = -diff(arr[i], arr[i+1]) - diff(prev, arr[i]) + diff(prev, arr[i+1])
}
} else {
if arr[i] < arr[i+1] {
d = -diff(arr[i], arr[i+1]) - diff(prev, arr[i]) + diff(prev, arr[i+1])
} else {
d = 0
}
}
fmt.Println(total + d)
prev = arr[i]
}
}
| Yes | Do these codes solve the same problem?
Code 1: fun main(args: Array<String>) {
val sc = java.util.Scanner(System.`in`)
val N = sc.nextInt()
val A = arrayOf(0) + Array(N) { sc.nextInt() } + arrayOf(0)
val d = (0..(A.count() - 2)).map { i ->
val d = A[i] - A[i + 1]
if (d > 0) d else -d
}
val sum = d.sum()
for (i in 0..(N-1)) {
println(sum - d[i] - d[i + 1] + Math.abs(A[i] - A[i + 2]))
}
}
Code 2: ///
// File: c.go
// Author: ymiyamoto
//
// Created on Sun Mar 25 21:07:39 2018
//
package main
import (
"fmt"
)
var N int
func diff(a, b int) int {
if a < b {
return b - a
}
return a - b
}
func main() {
fmt.Scan(&N)
arr := make([]int, N+2)
prev := 0
total := 0
for i := 1; i <= N; i++ {
fmt.Scan(&arr[i])
total += diff(prev, arr[i])
prev = arr[i]
}
total += diff(0, prev)
prev = 0
for i := 1; i <= N; i++ {
var d int
if prev < arr[i] {
if arr[i] < arr[i+1] {
d = 0
} else {
d = -diff(arr[i], arr[i+1]) - diff(prev, arr[i]) + diff(prev, arr[i+1])
}
} else {
if arr[i] < arr[i+1] {
d = -diff(arr[i], arr[i+1]) - diff(prev, arr[i]) + diff(prev, arr[i+1])
} else {
d = 0
}
}
fmt.Println(total + d)
prev = arr[i]
}
}
|
C | #include <stdio.h>
int main(){
int an,bn,i,j,count=0;
scanf("%d",&an);
int A[an+1];
for(i=0;i<an;i++)
scanf("%d",&A[i]);
scanf("%d",&bn);
int B[bn+1];
for(i=0;i<bn;i++)
scanf("%d",&B[i]);
//search
for(i=0;i<bn;i++){
j=0;
A[an]=B[i];
while(A[j]!=B[i])
j++;
if(j!=an)count++;
//printf("j=%d\n",j);
}
printf("%d\n",count);
return 0;
} | C++ | #include <bits/stdc++.h>
using namespace std;
int main(){
int sum5=0, sum7=0;
for(int i=0; i<3; i++){
int a;
cin >> a;
if(a == 5){
sum5++;
}
if(a == 7){
sum7++;
}
}
if(sum5 == 2 && sum7 == 1){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
return 0;
}
| No | Do these codes solve the same problem?
Code 1: #include <stdio.h>
int main(){
int an,bn,i,j,count=0;
scanf("%d",&an);
int A[an+1];
for(i=0;i<an;i++)
scanf("%d",&A[i]);
scanf("%d",&bn);
int B[bn+1];
for(i=0;i<bn;i++)
scanf("%d",&B[i]);
//search
for(i=0;i<bn;i++){
j=0;
A[an]=B[i];
while(A[j]!=B[i])
j++;
if(j!=an)count++;
//printf("j=%d\n",j);
}
printf("%d\n",count);
return 0;
}
Code 2: #include <bits/stdc++.h>
using namespace std;
int main(){
int sum5=0, sum7=0;
for(int i=0; i<3; i++){
int a;
cin >> a;
if(a == 5){
sum5++;
}
if(a == 7){
sum7++;
}
}
if(sum5 == 2 && sum7 == 1){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
return 0;
}
|
Python | n = int(input())
ss = set()
for i in range(n):
temp = input()
if temp in ss:
next
else:
ss.add(temp)
print(len(ss))
| C++ | #include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
#include<bits/stdc++.h>
#define int long long
#define x first
#define y second
#define all(aaa) (aaa).begin(),(aaa).end()
#define REP(i,sss,eee) for(int i=sss;i<=eee;++i)
#define pb push_back
#define pii pair<int,int>
#define vi vector<int>
#define speed ios_base::sync_with_stdio(0);cin.tie(0);
#define N 1000000007
#define inf 1000000000000000000
using namespace __gnu_pbds;
using namespace std;
template <class T>
T MAX(T a, T b){return ((a>b)?a:b);}
template <class T>
T MIN(T a, T b){return ((a<b)?a:b);}
template <class T>
T MOD(T a){return ((a>=0)?a:(-1*a));}
template <class T>
void SWAP(T &a,T &b){T temp=a;a=b;b=temp;}
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
inline int ex(int a, int b){
if(b==0||a==1){return 1;}
if(a==0||b==1){return a;}
int tmp=ex(a,(b/2));
if(b%2){return ((((tmp*tmp)%N)*a)%N);}
else{return ((tmp*tmp)%N);}
}
inline int inv(int k){
if(k==1){return 1;}
else{return ex(k,N-2);}
}
/*****************default********************/
int solve()
{
string str;cin>>str;
int zro=0,one=0,n=str.length();
for(auto it:str)
{
if(it=='0'){++zro;}
else{++one;}
}
cout<<(n-MAX(zro,one)+MIN(zro,one))<<"\n";
}
signed main(){
speed
int tt=1;
//cin>>tt;
while(tt--)
{
solve();
}
return 0;
} | No | Do these codes solve the same problem?
Code 1: n = int(input())
ss = set()
for i in range(n):
temp = input()
if temp in ss:
next
else:
ss.add(temp)
print(len(ss))
Code 2: #include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
#include<bits/stdc++.h>
#define int long long
#define x first
#define y second
#define all(aaa) (aaa).begin(),(aaa).end()
#define REP(i,sss,eee) for(int i=sss;i<=eee;++i)
#define pb push_back
#define pii pair<int,int>
#define vi vector<int>
#define speed ios_base::sync_with_stdio(0);cin.tie(0);
#define N 1000000007
#define inf 1000000000000000000
using namespace __gnu_pbds;
using namespace std;
template <class T>
T MAX(T a, T b){return ((a>b)?a:b);}
template <class T>
T MIN(T a, T b){return ((a<b)?a:b);}
template <class T>
T MOD(T a){return ((a>=0)?a:(-1*a));}
template <class T>
void SWAP(T &a,T &b){T temp=a;a=b;b=temp;}
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
inline int ex(int a, int b){
if(b==0||a==1){return 1;}
if(a==0||b==1){return a;}
int tmp=ex(a,(b/2));
if(b%2){return ((((tmp*tmp)%N)*a)%N);}
else{return ((tmp*tmp)%N);}
}
inline int inv(int k){
if(k==1){return 1;}
else{return ex(k,N-2);}
}
/*****************default********************/
int solve()
{
string str;cin>>str;
int zro=0,one=0,n=str.length();
for(auto it:str)
{
if(it=='0'){++zro;}
else{++one;}
}
cout<<(n-MAX(zro,one)+MIN(zro,one))<<"\n";
}
signed main(){
speed
int tt=1;
//cin>>tt;
while(tt--)
{
solve();
}
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.