jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
import java.util.*;
import java.util.stream.*;

public class Main{

	static Scanner s=new Scanner(System.in);
	public static void main(String[] $){
		IntSummaryStatistics o=IntStream.range(0,s.nextInt()).map(i->s.nextInt()).summaryStatistics();
		System.out.println(o.getMax()-o.getMin());
	}
}
//  [java]
import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int a = sc.nextInt();
		List<Integer> list = new ArrayList<>();
		// スペース区切りの整数の入力
		for(int i=1;i<=a;i++){
			list.add(sc.nextInt());
		}

		Optional<Integer> min = list.stream()
		.min((c, b) -> c.compareTo(b));
		Optional<Integer> max = list.stream()
		.max((c, b) -> c.compareTo(b));

		System.out.println(max.get()-min.get());
	}
}
//  [java]
import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int N = sc.nextInt();
		// スペース区切りの整数の入力
		List<Integer> list = new ArrayList<>();
		for(int i=0;i<N;i++){
			list.add(sc.nextInt());
		}
		Optional<Integer> max = list.stream().max(Comparator.naturalOrder());
		Optional<Integer> min = list.stream().min(Comparator.naturalOrder());
		
		// 出力
		System.out.println(max.get()-min.get());
	}
}
//  [cpp]
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <typeinfo>
#include <numeric>
#include <functional>
#include <unordered_map>
#include <bitset>
#include <stack>


using namespace std;
using ll = long long;
using ull = unsigned long long;

const ll INF = 1e16;
const ll MOD = 1e9 + 7;

#define REP(i, n) for(ll i = 0; i < n; i++)






void stoogesort(vector<int> &a, int l, int r){
    if(a[l] > a[r]){
        swap(a[l], a[r]);
    }
    if(r - l + 1 >= 3){
        int t = (r - l + 1) / 3;
        stoogesort(a, l, r - t);
        stoogesort(a, l + t, r);
        stoogesort(a, l, r - t);
    }
}


int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    REP(i, n){
        cin >> a[i];
    }
    REP(i, 2000){
        stoogesort(a, 0, n - 1);
        cerr << i << endl;
    }
    cout << a[n - 1] - a[0] << endl;
}
//  [cpp]
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <typeinfo>
#include <numeric>
#include <functional>
#include <unordered_map>
#include <bitset>
#include <stack>


using namespace std;
using ll = long long;
using ull = unsigned long long;

const ll INF = 1e16;
const ll MOD = 1e9 + 7;

#define REP(i, n) for(ll i = 0; i < n; i++)






void stoogesort(vector<int> &a, int l, int r){
    if(a[l] > a[r]){
        swap(a[l], a[r]);
    }
    if(r - l + 1 >= 3){
        int t = (r - l + 1) / 3;
        stoogesort(a, l, r - t);
        stoogesort(a, l + t, r);
        stoogesort(a, l, r - t);
    }
}


int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    REP(i, n){
        cin >> a[i];
    }
    REP(i, 100){
        stoogesort(a, 0, n - 1);
        cerr << i << endl;
    }
    cout << a[n - 1] - a[0] << endl;
}
//  [cpp]
#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

int main ()
{
	int n;
	cin >> n;
	int a[1000000];
	for(int i = 0; i < n; i++){
		cin >> a[i];




	}
	sort(a, a+n);
	cout << a[n-1] - a[0]<<endl;
	return 0;
}
//  [c]
#include <stdio.h>

int main()
{
  int a[100],i,d,min=1000000000,max=0;
  scanf("%d",&d);
  for(int i=1;i<=d;i++){
  scanf("%d",&a[i]);
  }
      for(i = 1;i <= d;i++){
      if(a[i]>max){
          max=a[i];
      }
  }
  for(i=1;i<=d;i++){
      if(a[i]<min){
          min=a[i];
      }
  }
  printf("%d",max-min);
    return 0;
}
//  [c]
#include <stdio.h>

int main(void){
	int N = 0,tmp_dif=0,max_dif;
	int A[100];
	scanf("%d",&N);
	for(int i = 0;i < N;i++){
		scanf("%d",&A[i]);
	}
	for(int i = 0;i < N;i++){
		for(int j = i+1;j < N;j++){
			tmp_dif = A[i] - A[j];
			if(tmp_dif<0){
				tmp_dif = tmp_dif*(-1);
			}
			if(tmp_dif>max_dif){
				max_dif = tmp_dif;
			}
		}
	}
	printf("%d\n", max_dif);
	return 0;
}
//  [c]
#include <stdio.h>

int main(void)
{
    int N;
    int num;

    int max=0;
    int min=1000000000;

    scanf("%d", &N);

    for (int i = 0; i < N; i++)
    {
        scanf("%d",&num);
        if(num>=max)max=num;
        if(num<=min)min=num;
    }

    printf("%d\n",max-min);
    return 0;
}
//  [javascript]
'use strict'

function Main(input) {
  const N = Number(input.split('\n')[0]);
  const line = input.split('\n')[1].split(' ').map(x => Number(x));

  const max = Math.max.apply(null, line);
  const min = Math.min.apply(null, line);

  console.log(max - min);

}

Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
//  [javascript]
"use strict";

process.stdin.resume();
process.stdin.setEncoding('utf8');

var g_input = '';
process.stdin.on('data', function(chunk) {
    g_input += chunk;
});

process.stdin.on('end', function() {
    Main(g_input.split(/\r?\n/));
});

function Main(input) {

    const n = parseInt(input[0], 10);
    const a = input[1].split(' ').map(function(value) { return parseInt(value, 10); });
    
    const maxA = Math.max.apply(null, a);
    const minA = Math.min.apply(null, a);

    const ans = maxA - minA;

    console.log(ans);

    return 0;
}
//  [javascript]
const fs = require("fs");

function Main(input){
  input = input.split("\n");
  var numArray = input[1].split(" ");
  var max = Math.max.apply(null, numArray);
  var min = Math.min.apply(null, numArray);
  console.log(Math.abs(max - min));
}
Main(fs.readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	// Code for B - Maximum Difference
	var N int
	fmt.Scanf("%d", &N)
	A := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d", &A[i])
	}

	sort.Sort(sort.IntSlice(A))

	fmt.Println(A[N-1] - A[0])
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func Scan() string {
	sc.Scan()
	return sc.Text()
}

func iScan() int {
	n, _ := strconv.Atoi(Scan())
	return n
}

func fScan() float64 {
	n, _ := strconv.ParseFloat(Scan(), 64)
	return n
}
func stringToInt(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
func SScan(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = Scan()
	}
	return a
}
func iSScan(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = iScan()
	}
	return a
}
func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}
func larger(a, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}
func smaller(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}
func max(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x > a[i] {
			x = a[i]
		}
	}
	return x
}
func sum(a []int) int {
	x := 0
	for _, v := range a {
		x += v
	}
	return x
}

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	n := iScan()
	a := iSScan(n)
	fmt.Println(max(a) - min(a))
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := range a {
		fmt.Scan(&a[i])
	}
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	fmt.Println(a[0] - a[n-1])
}
//  [ruby]
require 'prime'
require 'set'
require 'tsort'
include Math
ALP = ('a'..'z').to_a
INF = 0xffffffffffffffff
def max(a,b);              a > b ? a : b                              end
def min(a,b);              a < b ?  a : b                             end
def swap(a,b);             a, b = b, a                                end
def gif;                   gets.to_i                                  end
def gff;                   gets.to_f                                  end
def gsf;                   gets.chomp                                 end
def gi;                    gets.split.map(&:to_i)                     end
def gf;                    gets.split.map(&:to_f)                     end
def gs;                    gets.chomp.split.map(&:to_s)               end
def gc;                    gets.chomp.split('')                       end
def pr(num);               num.prime_division                         end
def pr?(num);              Prime.prime?(num)                          end
def digit(num);            num.to_s.length                            end
def array(s,ini=nil);      Array.new(s){ini}                          end
def darray(s1,s2,ini=nil); Array.new(s1){Array.new(s2){ini}}          end
def rep(num);              num.times{|i|yield(i)}                     end
def repl(st,en,n=1);       st.step(en,n){|i|yield(i)}                 end

n=gif
a=gi

puts (a.max - a.min).abs
//  [ruby]
_,*a=`dd`.split.map(&:to_i)
p a.max-a.min
//  [ruby]
N = gets.to_i
input = gets.chomp.split.map(&:to_i)
min = 10 ** 9 
max = 0

input.each do |num|
  min = [min,num].min
  max = [max,num].max
end

puts max - min
//  [rust]
#![allow(unused, non_snake_case, dead_code, non_upper_case_globals)]
use {
    proconio::{marker::*, *},
    std::{cmp::*, collections::*, mem::*},
};

#[fastout]
fn main() {
    input! {//
        n:usize,
       mut a:[i64;n],
    }
    a.sort();
    println!("{}", a[n - 1] - a[0]);
}
//  [rust]
#![allow(non_snake_case)]
use proconio::input;
// use std::collections::HashMap;

fn main() {
    input! {
        N: usize,
        mut As: [i64; N],
    }

    As.sort();

    let ans = As[N - 1] - As[0];

    println!("{}", ans);
}
//  [rust]
#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_imports)]

use text_io::*;
use proconio::*;
use itertools::Itertools;

const U_INF: usize = 1 << 60;
const I_INF: isize = 1 << 60;

fn main() {
    input! {
        n:usize,
        a:[usize;n],
    }
    
    println!("{}", a.iter().max().unwrap() - a.iter().min().unwrap());
}
//  [swift]
import Foundation
let N=Int(readLine()!)!
var strA=readLine()!.componentsSeparatedByString(" ")
var A=[Int]()
for i in strA{
  A.append(Int(i)!)
}
let max=A.maxElement()
let min=A.minElement()
print(max!-min!)
//  [swift]
import Foundation
func readInts() -> [Int] { readLine()!.split(separator: " ").map { Int($0)! } }

_ = readLine()
let ai = readInts().sorted()
print(abs(ai.last!-ai.first!))
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const A = input[1].map(Number);

  A.sort((a, b) => a - b);

  return A[A.length - 1] - A[0];
};

console.log(main(read()));
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}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[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;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 main=()=>{
  let n=tn()
  let a=tnn(n)
  let ans=0
  for(let i=0;i<a.length-1;i++){
    for(let j=i;j<a.length;j++){
      ans=max(ans,abs(a[i]-a[j]))
    }
  }
  to(ans)
}
main()
//  [typescript]
'use strict';

const receive = require('fs')
  .readFileSync('/dev/stdin', 'utf8')
  .split(/\n/);

const main = input => {
  const N = input[0];
  const A = input[1].split(/ /).map(x => Number(x));
  const max = Math.max(...A);
  const min = Math.min(...A);
  const ans = max - min;
  console.log(ans);
};

main(receive);
//  [python]
import sys
input=sys.stdin.readline

def main():
    n = int(input())
    
    A = [0]*n
    B = [0]*n
    C = [0]*n
    
    a,b,c = map(int,input().split())
    A[0] = a
    B[0] = b
    C[0] = c
    
    for i in range(1,n):
        a,b,c = map(int,input().split())
        A[i] = max(B[i-1]+a, C[i-1]+a)
        B[i] = max(A[i-1]+b, C[i-1]+b)
        C[i] = max(A[i-1]+c, B[i-1]+c)
    
    print(max(A[n-1], B[n-1], C[n-1]))
    
if __name__ == '__main__':
    main()
//  [python]
from sys import stdin
input = stdin.buffer.readline

def main():
    n = int(input())

    dp = [0, 0, 0]
    for _ in range(n):
        a, b, c = map(int, input().split())
        dp = [max(dp[1], dp[2]) + a,
            max(dp[2], dp[0]) + b,
            max(dp[0], dp[1]) + c]

    print(max(dp))

main()
//  [python]
from sys import stdin,stdout

n = int(stdin.readline())
ls = list()
dp1 = [0] * n
dp2 = [0] * n
dp3 = [0] * n
for i in range(n):
	a, b, c = map(int, stdin.readline().split())
	if i == 0:
		dp1[0] = a
		dp2[0] = b
		dp3[0] = c
	else:
		dp1[i] = max(dp2[i - 1], dp3[i - 1]) + a
		dp2[i] = max(dp1[i - 1], dp3[i - 1]) + b
		dp3[i] = max(dp1[i - 1], dp2[i - 1]) + c
print(max(dp1[n - 1], dp2[n - 1], dp3[n - 1]))
//  [python]
import numpy as np
n = int(input())
ary = [list(map(int,input().split())) for _ in range(n)]
ary = np.array(ary)
dp = np.zeros((n,3))
dp[0] = ary[0]
for i in range(n-1):
    for j in range(3):
        for k in range(3):
            if k == j:continue
            check = dp[i][j] + ary[i+1][k]
            if check > dp[i+1][k]:
                dp[i+1][k] = check
print(int(max(dp[n-1])))
//  [python]
N = int(input())
act = [list(map(int, input().split())) for _ in range(N)]

import numpy as np
act = np.array(act)
act = np.concatenate([[[0]*3], act])  # 0日目は0にする

# DPテーブル
dp = np.zeros([N+1, 3], dtype='int')

for i in range(1, N+1):  # 1日目からN日目までの幸福度を順番に計算する
    for j in range(3):  # i日目は海か山か家を選択する
        for k in range(3):  # i日目にjの活動をする場合、i-1日目はj以外の活動
            if k == j:
                continue
            dp[i][j] = max(dp[i][j], dp[i-1][k] + act[i][j])
            
print(np.max(dp[-1]))
//  [python]
import sys
import itertools
from operator import itemgetter #sortedの対象を決めたい
from fractions import gcd #最大公約数
from math import ceil, floor, sqrt, isinf #小数点切り上げ、切り捨て、平方根
from copy import deepcopy #参照で影響されないコピー
from collections import Counter, deque #要素ごとの出現回数、双方向アクセス可能データ型
import heapq
import numpy as np
from functools import reduce
sys.setrecursionlimit(200000)

input = sys.stdin.readline
# template

def retmax(a, b):
    if a > b:
        return a
    else:
        return b

def main():
    n = int(input())
    a = [list(map(int, input().split())) for _ in range(n)]

    dp = np.zeros([3, n+1])

    for i, a_l in enumerate(a):
        for j in range(3):
            for k in range(3):
                if j != k:
                    dp[k, i+1] = max(dp[k, i+1], dp[j, i] + a_l[k])

    print(int(np.max(dp[:, n], axis=0)))


if __name__ == "__main__":
    main()
//  [java]
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;

/**
 * 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;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task
    {
        public void solve(int testNumber, Scanner in, PrintWriter out)
        {
            int N = in.nextInt();
            int activities[][] = new int[N][3];
            Map<Key, Integer> memo = new HashMap<>();
            for (int i = 0; i < N; i++)
            {
                activities[i] = CPUtils.readIntArray(3, in);
            }
            out.println(solve(N, 0, '0', activities, memo));
        }

        private int solve(int n, int day, char prev, int[][] activities, Map<Key, Integer> memo)
        {
            if (day == n) return 0;

            int score = -1;
            char activity = '0';
            char choices[] = {'A', 'B', 'C'};
            for (int i = 0; i < 3; i++)
            {
                if (prev != choices[i])
                {
                    int choiceScore;
                    Key key = new Key(day, choices[i]);
                    choiceScore = memo.containsKey(key) ? memo.get(key) :
                                  solve(n, day + 1, choices[i], activities, memo) + activities[day][i];
                    if (choiceScore > score)
                    {
                        score = choiceScore;
                        activity = choices[i];
                    }
                }
            }
            memo.put(new Key(day, activity), score);
            return score;
        }

    }

    static class Key
    {
        int day;
        char activity;

        Key(int day, char activity)
        {
            this.day = day;
            this.activity = activity;
        }

        public boolean equals(Object o)
        {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Key key = (Key) o;
            return day == key.day && activity == key.activity;
        }

        public int hashCode()
        {
            return Objects.hash(day, activity);
        }

    }

    static class CPUtils
    {
        public static int[] readIntArray(int size, Scanner in)
        {
            int[] array = new int[size];
            for (int i = 0; i < size; i++)
            {
                array[i] = in.nextInt();
            }
            return array;
        }

    }
}
//  [java]
/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Main
{
  HashMap<String, Integer> map 
            = new HashMap<>(); 
  	
	public static void main (String[] args) throws java.lang.Exception
	{
      	FastReader s = new FastReader();
		int  n = s.nextInt();
      	
		int arr[][] = new int[n][3];
		for(int i=0;i<n;i++)
          for(int j=0;j<3;j++)
		arr[i][j]= s.nextInt();
		Main ob = new Main();
		int ans = ob.getH(n-1,arr,1,1,1);
      	System.out.println(ans);
	}
  int maxim (int x, int y, int z){
  int m = Math.max(x,y);
    return Math.max(m,z);
  }
  int getH(int n,int arr[][], int a, int b, int c){
    int res=0;
    String key = ""+Integer.toString(n)+Integer.toString(a)+Integer.toString(b)+Integer.toString(c);
  	if(n==0){
      res=maxim(a*arr[0][0],b*arr[0][1],c*arr[0][2]);
      map.put(key ,res);
    return map.get(key);
  }
    if(map.containsKey(key)) return map.get(key);
    res=maxim(a==1?(arr[n][0]+getH(n-1,arr,0,1,1)):0,
                b==1?(arr[n][1]+getH(n-1,arr,1,0,1)):0,
                c==1?(arr[n][2]+getH(n-1,arr,1,1,0)):0);
    
    map.put(key ,res);
    return map.get(key);
  }


  static class FastReader 
    { 
        BufferedReader br; 
        StringTokenizer st; 
  
        public FastReader() 
        { 
            br = new BufferedReader(new
                     InputStreamReader(System.in)); 
        } 
  
        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()); 
        } 
  
        String nextLine() 
        { 
            String str = ""; 
            try
            { 
                str = br.readLine(); 
            } 
            catch (IOException e) 
            { 
                e.printStackTrace(); 
            } 
            return str; 
        } 
    } 
}
//  [java]
//package atcoderdp;

import java.util.*;

class Main {
    static HashMap<String, Integer> states;

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int a[][] = new int[n][3];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                a[i][j] = s.nextInt();
            }
        }
        states = new HashMap<>();
        int res = Math.max(Math.max(find(a, n,  0, 0), find(a, n,  0, 1)), find(a, n,  0, 2));
        System.out.println(res);
    }

    public static int find(int a[][], int n,  int start, int index) {
        String state = index + " " + start;
        if (states.containsKey(state))
            return states.get(state);
        if (start == n-1) {
            //System.out.println(a[start][index]);
            return a[start][index];
        }

        else {
            int val1 = find(a, n,  start + 1, (index + 1) % 3);
            int val2 = find(a, n,  start + 1, (index + 2) % 3);
            // System.out.println(val1+" "+val2);
            int val = Math.max(val1 + a[start][index], val2 + a[start][index]);
            states.put(state, val);
            return val;
        }
    }
}
/*150 150
90 90
150 90
150 150
90 150
150 150
150 150
150 150
150 150
150*/
/*150 150
90 90
150 90
120 120
150 150
120 150
150 150
150 150
180 180
150 180
120 120
150 150
120 150
180 150
150 150
180 180
150 180
210 210
150 150
210 150
180 210
210*/
//  [cpp]
#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint();
	int dp0 = 0;
	int dp1 = 0;
	int dp2 = 0;

	rep(i, N) {
		int kari1 = max(dp0, dp1) + getint();
		int kari2 = max(dp1, dp2) + getint();
		dp1 = max(dp2, dp0) + getint();
		dp2 = kari1;
		dp0 = kari2;
	}

	printf("%d", max(dp0, max(dp1, dp2)));

	Would you please return 0;
}
//  [cpp]
/*
 ╔═══╦═══╦═══╗
 ║╔═╗║╔══╩╗╔╗║
 ║║░║║╚══╗║║║║
 ║║░║║╔══╝║║║║
 ║╚═╝║╚══╦╝╚╝║
 ╚══╗╠═══╩═══╝
 ░░░╚╝░░░░░░░░
 */

#include <bits/stdc++.h>
#define ll					long long
#define MOD					1000000007
#define MAX					1e9
#define MIN                 -1e9
#define PI					acos(-1.0)
#define vi					vector<int>
#define vii					vector<vi>
#define vll					vector<ll>
#define mid(s,e)			(s+(e-s)/2)
#define clz(n)				__builtin_clzll(n))

using namespace std;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
template<typename T>
void printVec(const T &v, char sep=' ') {for (auto &i: v) cout << i << sep;}
template<typename T>
void printVecPair(const T &v, char sep=' ') {for (auto &i: v) cout << i.first <<" " << i.second<< sep;}


#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

int main() {
	ios::sync_with_stdio(false);
 	cin.tie(0);
	int n;
	cin>>n;
	vii dp(2,vi(3));
	for(int i=0;i<n;i++) {
			int c[3];
			for(int j=0;j<3;cin>>c[j++]);
			for(int j=0;j<3;j++) {
					for(int k=0;k<3;k++) {
							if(j!=k) {
									dp[i&1][j] = max(dp[(i+1)&1][k] + c[j],dp[i&1][j]);

							}
					}
			}
			debug(dp);
			
	}
	cout<<max({dp[(n-1)&1][0], dp[(n-1)&1][1], dp[(n-1)&1][2]});
	return 0;
}
//  [cpp]
/*
 ╔═══╦═══╦═══╗
 ║╔═╗║╔══╩╗╔╗║
 ║║░║║╚══╗║║║║
 ║║░║║╔══╝║║║║
 ║╚═╝║╚══╦╝╚╝║
 ╚══╗╠═══╩═══╝
 ░░░╚╝░░░░░░░░
 */

#include <bits/stdc++.h>
#define ll					long long
#define MOD					1000000007
#define MAX					1e9
#define MIN                 -1e9
#define PI					acos(-1.0)
#define vi					vector<int>
#define vii					vector<vi>
#define vll					vector<ll>
#define mid(s,e)			(s+(e-s)/2)
#define clz(n)				__builtin_clzll(n))

using namespace std;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
template<typename T>
void printVec(const T &v, char sep=' ') {for (auto &i: v) cout << i << sep;}
template<typename T>
void printVecPair(const T &v, char sep=' ') {for (auto &i: v) cout << i.first <<" " << i.second<< sep;}


#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

int main() {
	ios::sync_with_stdio(false);
 	cin.tie(0);
	int n;
	cin>>n;
	vii dp(2,vi(3));
	for(int i=0;i<n;i++) {
			int c[3];
			for(int j=0;j<3;cin>>c[j++]);
			for(int j=0;j<3;j++) {
					for(int k=0;k<3;k++) {
							if(j!=k) {
									dp[i%2][j] = max(dp[(i+1)%2][k] + c[j],dp[i%2][j]);

							}
					}
			}
			debug(dp);
			
	}
	cout<<max({dp[(n-1)%2][0], dp[(n-1)%2][1], dp[(n-1)%2][2]});
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>                 // [PRIMES]               1777 ~2^10.80
using namespace std;                     //                       10333 ~2^13.33
using ll = long long;                    // seq 1 128 | factor   100333 ~2^16.61
using ld = long double;                  //   | grep -v ' .* '  1300111 ~2^20.31
using vl = vector<ll>;                   //                    10300777 ~2^23.30
using vvl = vector<vl>;                  //                   100400999 ~2^26.58
using pll = pair<ll,ll>;                 //                  1300400999 ~2^30.28
using vpll = vector<pll>;                //                 10200500333 ~2^33.25
using vb = vector<bool>;                 //                100200400777 ~2^36.54
using vs = vector<string>;               //               1200300700111 ~2^40.13
const ll oo = 0x3f3f3f3f3f3f3f3fLL;      //              10200300500777 ~2^43.21
const ld eps = 1e-9;                     //             100200300400777 ~2^46.51
#define sz(c) ll((c).size())             //            1200300400600999 ~2^50.09
#define all(c) begin(c),end(c)           //           10200300400600111 ~2^53.18
#define mp make_pair                     //          100200300400600333 ~2^56.48
#define mt make_tuple                    //         1200300400500800999 ~2^60.06
#define pb push_back
#define eb emplace_back
#define xx first
#define yy second
#define FOR(i,a,b) for(ll i=(a); i<(b); i++)
#define FORD(i,a,b) for(ll i=ll(b)-1;i>=(a);i--)
#define TR(X) ({if(1) cerr << "TR: " << (#X) << " = " << (X) << endl; })

int main(){
	cin.sync_with_stdio(0);
	cin.tie(0);

	ll n; cin >> n;
	vvl acts(n+1, vl(3));
	FOR(i,0,n) cin >> acts[i+1][0] >> acts[i+1][1] >> acts[i+1][2];

	vvl dp(n+1, vl(3, 0));
	FOR(i,1,n+1) {
		TR(i);
		vl prev = dp[i-1];
		dp[i][0] = max(prev[1], prev[2]) + acts[i][0];
		dp[i][1] = max(prev[0], prev[2]) + acts[i][1];
		dp[i][2] = max(prev[0], prev[1]) + acts[i][2];
		TR(dp[i][0]);
		TR(dp[i][1]);
		TR(dp[i][2]);
	}

	cout << *max_element(all(dp[n])) << "\n";

	return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

long dp[100005][3],ans;

long max(long a,long b);

int main(void){
  int N,a[100005],b[100005],c[100005],i;
  char str[1000],*p;
  
  fgets(str,sizeof(str),stdin);
  N=atoi(str);
  
  for(i=1;i<N+1;i++){
    fgets(str,sizeof(str),stdin);
    p=strtok(str," \n");
    a[i]=atoi(p);
    p=strtok(NULL," \n");
    b[i]=atoi(p);
    p=strtok(NULL," \n");
    c[i]=atoi(p);
  }
  
  for(i=1,a[0]=0,b[0]=0,c[0]=0;i<N+2;i++){
    dp[i][0]=max(dp[i-1][1]+b[i-1],dp[i-1][2]+c[i-1]);
    dp[i][1]=max(dp[i-1][0]+a[i-1],dp[i-1][2]+c[i-1]);
    dp[i][2]=max(dp[i-1][1]+b[i-1],dp[i-1][0]+a[i-1]);
  }
  
  ans=dp[N+1][0];
  for(i=1;i<3;i++){
    if(dp[N+1][i]>ans){
      ans=dp[N+1][i];
    }
  }
  
  printf("%ld\n",ans);
  
 return 0;
}

long max(long a,long b){
  if(a>=b){
    return a;
  }else{
    return b;
  }
}
//  [c]
#include<stdio.h>
int max(int a, int b)
{
	if (a > b)return a;
	else return b;
}
int main()
{
	int n;
	scanf("%d", &n);
	int a, b, c;
	int i;
	int a1, a2, b1, b2, c1, c2;
	a1 = a2 = b1 = b2 = c1 = c2 = 0;
	for (i = 0; i < n; i++)
	{
		scanf("%d %d %d", &a, &b, &c);
		a2 = a + max(b1, c1);
		b2 = b + max(a1, c1);
		c2 = c + max(a1, b1);
		a1 = a2;
		b1 = b2;
		c1 = c2;
	}
	printf("%d\n", max(a1, max(b1, c1)));
	return 0;
}
//  [c]
#include<stdio.h>
int m[100000][3];
int h[100000][3];
int n;
int min(int i,int j)
{
    return i>j?i:j;
}
int f(int j,int i)
{
    int k;
    if(n==j)
        return 0;
    if(m[j][i]!=-1)
        return m[j][i];
    int ans=0;
    for(k=0;k<3;k++)
    {
        if(k==i)
            continue;
        ans=min(ans,h[j][i]+f(j+1,k));
    }
    m[j][i]=ans;
    return ans;
}
int main()
{
     int i,j,l=0;
     scanf("%d",&n);
     for(i=0;i<n;i++)
     {
         for(j=0;j<3;j++)
            {
                scanf("%d",&h[i][j]);
            }
     }
     for(i=0;i<n;i++)
     {
         for(j=0;j<3;j++)
            m[i][j]=-1;
     }
     for(i=0;i<3;i++)
     {
         l=l>f(0,i)?l:f(0,i);

     }
     printf("%d",l);
    return 0;
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>
#define rep(i,l,r) for(int i=l;i<r;i++)

typedef long long ll;

ll max(ll a, ll b) { return a > b ? a : b; }

int main() {
    ll n, a[3][100001];
    scanf("%lld", &n);
    rep(i, 0, n) {
        rep(j, 0, 3) {
            scanf("%lld", &a[j][i]);
        }
    }
    ll dp[3][100001];
    rep(i, 0, 3) dp[i][0] = a[i][0];
    rep(i, 1, n) {
        rep(j, 0, 3) {
            dp[j][i] = max(dp[(j + 1) % 3][i - 1] + a[j][i], dp[(j + 2) % 3][i - 1] + a[j][i]);
        }
    }
    ll ans = max(dp[0][n - 1], max(dp[1][n - 1], dp[2][n - 1]));
    
    printf("%lld", ans);
    return 0;
}
//  [c]
#include<stdio.h>
int a[100001][3],x[100001][3];
int main()
{
	int n;
	int i,j,k,max=-1;
	scanf("%d",&n);
	for(i=0;i<n;i++){
		for(j=0;j<3;j++){
			scanf("%d",&a[i][j]);
			x[i][j]=0;
			x[0][i]=a[0][i];
		}
	}
	for(i=0;i<n;i++){
		for(j=0;j<3;j++){
			for(k=0;k<3;k++){
				if(j!=k&&i<n&&a[i+1][k]+x[i][j]>x[i+1][k]){
					x[i+1][k]=x[i][j]+a[i+1][k];
				}
			}
		}
	}
	for(i=0;i<3;i++){
		if(max<x[n-1][i]) max=x[n-1][i];
	}
	printf("%d\n",max);
	return 0;
}
//  [javascript]
'use strict'
const lines = require('fs').readFileSync(0, 'utf8').split('\n')
const N = parseInt(lines[0], 10)
const dp = {a:[],b:[],c:[]}
for (let i=1;i <= N;i++) {
  const abc = lines[i].split(' ')
  dp.a[i-1] = parseInt(abc[0], 10) + (i>1 ? Math.max(dp.b[i-2], dp.c[i-2]) : 0)
  dp.b[i-1] = parseInt(abc[1], 10) + (i>1 ? Math.max(dp.a[i-2], dp.c[i-2]) : 0)
  dp.c[i-1] = parseInt(abc[2], 10) + (i>1 ? Math.max(dp.b[i-2], dp.a[i-2]) : 0)
}
console.log(Math.max(dp.a[N-1], dp.b[N-1], dp.c[N-1]))
//  [javascript]


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var a = new Array(N);
  var b = new Array(N);
  var c = new Array(N);
  var maxs = new Array(3);
  for(var i=0;i<3;i++){
    var maxsub=new Array(N).fill(0);
    maxs[i]=maxsub;
  }
  for(var i=0;i<N;i++){
    var tmp = input[i+1].split(" ");
    a[i]=parseInt(tmp[0]);
    b[i]=parseInt(tmp[1]);
    c[i]=parseInt(tmp[2]);
    for(var j=0;j<3;j++){
      if(i==0){
        maxs[j][i]=parseInt(tmp[j]);
      }else{
        if(j==0){
          maxs[1][i]=Math.max(maxs[1][i],maxs[0][i-1]+b[i]);
          maxs[2][i]=Math.max(maxs[2][i],maxs[0][i-1]+c[i]);
        }else if(j==1){
          maxs[0][i]=Math.max(maxs[0][i],maxs[1][i-1]+a[i]);
          maxs[2][i]=Math.max(maxs[2][i],maxs[1][i-1]+c[i]);
        }else{
          maxs[0][i]=Math.max(maxs[0][i],maxs[2][i-1]+a[i]);
          maxs[1][i]=Math.max(maxs[1][i],maxs[2][i-1]+b[i]);
        }
      }
    }
  }
  var ans = Math.max(maxs[0][N-1],maxs[1][N-1],maxs[2][N-1]);
  console.log('%s', ans);
  return ans;
}
// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));

console.log(main());
function main(){
  var n = o.a();
  var a = o.m(n);
  var dp = [[0,0,0]];
  for(var i = 1; i <= n; i++){
    dp[i] = [];
    var t = a[i-1];
    dp[i][0] = t[0] + Math.max(dp[i-1][1], dp[i-1][2]);
    dp[i][1] = t[1] + Math.max(dp[i-1][0], dp[i-1][2]);
    dp[i][2] = t[2] + Math.max(dp[i-1][0], dp[i-1][1]);
  }
  return Math.max(...dp[n]);
}
//  [javascript]
'use strict'
function main(input) {
  const tmp = Array.from(input.split('\n'));
  const N = parseInt(tmp.shift(), 10);

  let a = [];
  let b = [];
  let c = [];
  for (let abc of tmp) {
    abc = abc.split(' ').map((elem) => parseInt(elem, 10));
    a.push(abc[0]);
    b.push(abc[1]);
    c.push(abc[2]);
  }

  let dp = new Array(N + 1);
  for (let i = 0; i <= N; i++) {
    dp[i] = new Array(3).fill(0);
  }
  const happiestValDay1 = [a[0], b[0], c[0]].reduce((max, elem) => Math.max(max, elem));

  dp[1][0] = happiestValDay1;
  dp[1][1] = happiestValDay1;
  dp[1][2] = happiestValDay1;
  for (let day = 2; day <= N; day++) {
    dp[day][0] = Math.max(dp[day][0], dp[day - 1][1] + b[day - 1]);
    dp[day][0] = Math.max(dp[day][0], dp[day - 1][2] + c[day - 1]);

    dp[day][1] = Math.max(dp[day][1], dp[day - 1][0] + a[day - 1]);
    dp[day][1] = Math.max(dp[day][1], dp[day - 1][2] + c[day - 1]);

    dp[day][2] = Math.max(dp[day][2], dp[day - 1][0] + a[day - 1]);
    dp[day][2] = Math.max(dp[day][2], dp[day - 1][1] + b[day - 1]);
  }
  const answer = [dp[N][0], dp[N][1], dp[N][2]].reduce((max, elem) => Math.max(max, elem));
  console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
'use strict'

const main = input => {
	const args = input.split('\n').map(arg => arg.split(' '))
	const n = parseInt(args[0][0], 10)
	const t = args.slice(1, n + 1)
	const dp = new Array(n + 1)

	for (let i = 0; i < dp.length; i++) {
		dp[i] = new Array(3).fill(0)
	}

	for (let i = 0; i < n; i++) {
		const a = t[i].map(arg => parseInt(arg, 10))

		for (let j = 0; j < 3; j++) {
			for (let k = 0; k < 3; k++) {
				if (j === k) continue
				dp[i + 1][j] = Math.max(dp[i + 1][j], dp[i][k] + a[j])
			}
		}
	}

	let max = 0

	for (let i = 0; i < 3; i++) {
		max = Math.max(max, dp[n][i])
	}

	console.log(max)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
)

var sc = bufio.NewScanner(os.Stdin)

type triple struct {
	a, b, c int
}

func ri() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func max(a []int) int {
	x := a[0]
	for _, v := range a {
		if v > x {
			x = v
		}
	}
	return x
}

func main() {
	sc.Split(bufio.ScanWords)
	n := ri()
	h := triple{a: 0, b: 0, c: 0}
	for i := 0; i < n; i++ {
		x, y, z := ri(), ri(), ri()
		var today triple
		today.a = x + larger(h.b, h.c)
		today.b = y + larger(h.c, h.a)
		today.c = z + larger(h.a, h.b)
		h = today
	}
	fmt.Println(max([]int{h.a, h.b, h.c}))
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	n := nextInt()
	a := make([]int, n)
	b := make([]int, n)
	c := make([]int, n)

	for i := 0; i < n; i++ {
		a[i] = nextInt()
		b[i] = nextInt()
		c[i] = nextInt()
	}

	dp := make([][3]int, n)
	dp[0][0] = a[0]
	dp[0][1] = b[0]
	dp[0][2] = c[0]
	for i := 1; i < n; i++ {
		dp[i][0] = max(dp[i-1][1]+a[i], dp[i-1][2]+a[i])
		dp[i][1] = max(dp[i-1][0]+b[i], dp[i-1][2]+b[i])
		dp[i][2] = max(dp[i-1][0]+c[i], dp[i-1][1]+c[i])
	}

	fmt.Println(max(dp[n-1][0], max(dp[n-1][1], dp[n-1][2])))
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// ---- readfunc
func scanInit() {
	const cap = 200 * 1024 // Default=64
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)

func oneInt() int {
	var a int
	fmt.Scan(&a)
	return a
}

func oneInt64() int64 {
	var a int64
	fmt.Scan(&a)
	return a
}

func oneStr() string {
	var a string
	fmt.Scan(&a)
	return a
}

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func scanNums() (nums []int) {
	s := nextLine()
	numStr := strings.Split(s, " ")

	for _, n := range numStr {
		i, _ := strconv.Atoi(n)
		nums = append(nums, i)
	}
	return nums
}

func scanStrings() (strs []string) {
	s := nextLine()
	list := strings.Split(s, " ")
	strs = append(strs, list...)
	return strs
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func sortAsc(a []int) []int {
	sort.Ints(a)
	return a
}

func sortDesc(a []int) []int {
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	return a
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int) int {
	if a == 0 && b == 0 {
		return 0
	}
	return a * b / gcd(a, b)
}

func permutation(n int, k int) int {
	v := 1
	if 0 < k && k <= n {
		for i := 0; i < k; i++ {
			v *= (n - i)
		}
	} else if k > n {
		v = 0
	}
	return v
}

func factorial(n int) int {
	return permutation(n, n-1)
}

func combination(n int, k int) int {
	return permutation(n, k) / factorial(k)
}

func homogeneous(n int, k int) int {
	return combination(n+k-1, k)
}

type key struct {
	k1, k2 int
}

var table map[key]int

func main() {
	N := oneInt()
	activity := make(map[key]int)
	table = make(map[key]int)

	for index := 0; index < N; index++ {
		activity[key{index, 0}] = oneInt()
		activity[key{index, 1}] = oneInt()
		activity[key{index, 2}] = oneInt()
	}

	for day := 0; day < N; day++ {
		for k := 0; k < 3; k++ {
			for j := 0; j < 3; j++ {
				if k == j {
					continue
				}
				table[key{day + 1, j}] = max(table[key{day + 1, j}], table[key{day, k}]+activity[key{day, j}])
			}
		}
	}

	res := max(table[key{N, 0}], table[key{N, 1}], table[key{N, 2}])
	fmt.Print(res)
}
//  [go]
package main

import "fmt"
var N int
var A [][]int
var dp [][]int

func max(a, b int) int {
	if a > b { return a }
	return b
}

func min(a, b int) int {
	if a < b { return a }
	return b
}

func abs(a int) int {
	if a < 0 { return -a }
	return a
}

func main() {
	_,e := fmt.Scanf("%d", &N)
	if e != nil { return }
	A = make([][]int, N)
	for i:=0; i<N; i++ {
		A[i] = make([]int, 3)
		for j:=0; j<3; j++ {
			_,e = fmt.Scanf("%d", &A[i][j])
			if e != nil { return }
		}
	}
	for i:=1; i<N; i++ {
		for j:=0; j<3; j++ {
			A[i][j] += max(A[i-1][(j+1)%3], A[i-1][(j+2)%3])
		}
	}
	res := -(1<<31-1)-1
	for i:=0; i<3; i++ {
		if A[N-1][i] > res { res = A[N-1][i]}
	}
	fmt.Println(res)
}
//  [go]
package main

import "fmt"

func min(x, y int) int {
	if x > y {
		return y
	} else {
		return x
	}
}

func max(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func maxs(xs []int) int {
	var ans int
	for _, x := range xs {
		if ans < x {
			ans = x
		}
	}
	return ans
}

func abs(x int) int {
	if x < 0 {
		return -x
	} else {
		return x
	}
}

func main() {
	var n int
	fmt.Scanf("%d", &n)

	a := make([]int, n)
	b := make([]int, n)
	c := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d %d %d", &a[i], &b[i], &c[i])
	}

	dp := make([][]int, n)
	for i := 0; i < n; i++ {
		dp[i] = make([]int, 3)
	}
	dp[0] = []int{a[0], b[0], c[0]}

	for i := 1; i < n; i++ {
		// aを選んだ場合
		dp[i][0] = max(dp[i][0], dp[i-1][1]+a[i]) // 1つ前でbを選んだ場合
		dp[i][0] = max(dp[i][0], dp[i-1][2]+a[i]) // 1つ前でcを選んだ場合
		// bを選んだ場合
		dp[i][1] = max(dp[i][1], dp[i-1][0]+b[i]) // 1つ前でaを選んだ場合
		dp[i][1] = max(dp[i][1], dp[i-1][2]+b[i]) // 1つ前でcを選んだ場合
		// cを選んだ場合
		dp[i][2] = max(dp[i][2], dp[i-1][0]+c[i]) // 1つ前でaを選んだ場合
		dp[i][2] = max(dp[i][2], dp[i-1][1]+c[i]) // 1つ前でbを選んだ場合
	}

	fmt.Println(maxs(dp[len(dp)-1]))
}
//  [ruby]
N = gets.to_i
dp = Array.new(N + 1){[0,0,0]}
(1 .. N).each do |n|
  a,b,c = gets.split.map(&:to_i)
  dp[n][0] = [dp[n - 1][1] + a, dp[n - 1][2] + a].max
  dp[n][1] = [dp[n - 1][2] + b, dp[n - 1][0] + b].max
  dp[n][2] = [dp[n - 1][0] + c, dp[n - 1][1] + c].max
end
puts dp[N].max
//  [ruby]
N = gets.to_i
dpa = Array.new(N + 1, 0)
dpb = Array.new(N + 1, 0)
dpc = Array.new(N + 1, 0)
N.times do |i|
  a, b, c = gets.split.map(&:to_i)
  dpa[i+1] = dpb[i] + a > dpc[i] + a ? dpb[i] + a : dpc[i] + a
  dpb[i+1] = dpa[i] + b > dpc[i] + b ? dpa[i] + b : dpc[i] + b
  dpc[i+1] = dpa[i] + c > dpb[i] + c ? dpa[i] + c : dpb[i] + c
end
puts [dpa[N], dpb[N], dpc[N]].max
//  [ruby]
n = gets.to_i
dp = Array.new(n) { Array.new(3) }
dp[0][0], dp[0][1], dp[0][2] = gets.split.map(&:to_i)

(n - 1).times do |i|
  a, b, c = gets.split.map(&:to_i)
  dp[i + 1][0] = [dp[i][1], dp[i][2]].max + a
  dp[i + 1][1] = [dp[i][0], dp[i][2]].max + b
  dp[i + 1][2] = [dp[i][0], dp[i][1]].max + c
end

puts dp[n - 1].max
//  [ruby]
n = gets.to_i
a = []
n.times do |i|
  a[i] = gets.chomp.split.map(&:to_i)
end

dp = Array.new(1000001).map{Array.new(4, 0)}
n.times do |i|
  3.times do |j|
    3.times do |k|
      next if j == k
      dp[i + 1][k] = [dp[i + 1][k], dp[i][j] + a[i][k]].max
    end
  end
end

puts dp[n].max
//  [ruby]
gets;a=[0]*3;
$<.map{|s|
	b=[0]*3;
	3.times{|i|3.times{|j|b[j]=[b[j],i!=j ?a[i]+s.split[j].to_i: 0].max}}
	a=b
}
p a.max
//  [ruby]
gets;a=c=[0]*3;$<.map{|s|b=*c;3.times{|i|3.times{|j|b[j]=[b[j],i!=j ?a[i]+s.split[j].to_i: 0].max}};a=b};p a.max
//  [rust]
use std::cmp::max;

fn read<T: std::str::FromStr>(
    stdin_lock: &mut std::io::StdinLock,
    buf: &mut Vec<u8>,
    delimiter: u8,
) -> T {
    buf.clear();
    let l = std::io::BufRead::read_until(stdin_lock, delimiter, buf).unwrap();
    buf.truncate(l - 1); // remove delimiter
    let s = unsafe { std::str::from_utf8_unchecked(&buf) };
    s.parse().unwrap_or_else(|_| panic!("read"))
}

fn main() {
    let stdin = std::io::stdin();
    let mut stdin_lock = stdin.lock();
    let mut buf: Vec<u8> = Vec::new();
    let n: usize = read(&mut stdin_lock, &mut buf, b'\n');
    let mut p = (0i32, 0i32, 0i32);
    for _ in 0..n {
        let pa = p.0;
        let pb = p.1;
        let pc = p.2;
        let a: i32 = read(&mut stdin_lock, &mut buf, b' ');
        let b: i32 = read(&mut stdin_lock, &mut buf, b' ');
        let c: i32 = read(&mut stdin_lock, &mut buf, b'\n');
        p.0 = a + max(pb, pc);
        p.1 = b + max(pa, pc);
        p.2 = c + max(pa, pb);
    }
    println!("{}", max(max(p.0, p.1), p.2));
}
//  [rust]
use std::io;
use std::str::FromStr;
use std::collections::HashMap;

fn input<T:FromStr>() -> T {
    let mut line: String = String::new();
    io::stdin().read_line(&mut line);
    line.trim().parse().ok().unwrap()
}

fn input_vec() -> Vec<u64> {
    let mut line: String = String::new();
    io::stdin().read_line(&mut line);
    line.split_whitespace().map(|s| s.parse().unwrap()).collect()
}

fn dp(i: usize, yesterday: usize, happiness_vec: &Vec<Vec<u64>>, cache: &mut HashMap<usize, u64>) -> u64 {
    if i == happiness_vec.len() {
        return 0;
    }

    if cache.contains_key(&(i * 10 + yesterday)) {
        return *cache.get(&(i * 10 + yesterday)).unwrap();
    }

    let mut max = 0u64;
    for j in 0..3usize {
        if j == yesterday {
            continue;
        }
        let res = dp(i+1, j, happiness_vec, cache) + happiness_vec[i][j];
        if res > max {
            max = res;
        }
    }
    cache.insert(i * 10 + yesterday, max);
    max
}

fn main() {
    let n: u64 = input();
    let mut happiness_vec: Vec<Vec<u64>> = Vec::new();
    let mut cache: HashMap<usize, u64> = HashMap::new();
    for _ in 0..n {
        let happiness = input_vec();
        happiness_vec.push(happiness);
    }
    println!("{}", dp(0, 10, &happiness_vec, &mut cache));
}