#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb emplace_back
typedef pair<int,int> pi;

int h, w, ans, dist[1005][1005], dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};
char grid[1005][1005];
queue<pi> q;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cin >> h >> w;
	memset(dist, -1, sizeof dist);
	for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) {
		cin >> grid[i][j];
		if (grid[i][j] == '#') {
			q.emplace(i, j);
			dist[i][j] = 0;
		}
	}
	while (q.size()) {
		int x = q.front().first, y = q.front().second;
		q.pop();
		// cout << x << ' ' << y << '\n';
		for (int i = 0; i < 4; ++i) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue;
			if (dist[nx][ny] != -1) continue;
			dist[nx][ny] = dist[x][y] + 1;
			q.emplace(nx, ny);
		}
	}
	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			if (grid[i][j] == '.') ans = max(ans, dist[i][j]);
		}
	}
	cout << ans;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

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

  int h,w;
  cin >> h >> w;
  vector<string> a(h);
  for(int i=0;i<h;i++) cin >> a[i];

  vector<vector<int>> d(h,vector<int>(w,-1));
  vector<pair<int,int>> que;

  for(int i=0;i<h;i++){
   for(int j=0;j<w;j++){
    if(a[i][j]=='#') que.emplace_back(i,j), d[i][j]=0;
   }
  }

  for(int i=0;i<que.size();i++){
    for(int dx=-1;dx<=1;dx++){
     for(int dy=-1;dy<=1;dy++){
      if(dx*dx+dy*dy==1){
       int x=que[i].first+dx,y=que[i].second+dy;
        if(0<=x&&x<h&&0<=y&&y<w&&d[x][y]==-1){
        que.emplace_back(x,y);
        d[x][y]=d[que[i].first][que[i].second]+1;
      }
      }
     }
  }
  }
  cout << d[que.back().first][que.back().second] << endl;
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


#include <bits/stdc++.h>
using namespace std;

int main()
{
    int H, W;
    cin >> H >> W;
    map<pair<int, int>, int> data;
    queue<pair<int, int>> que;

    vector<pair<int, int>> diff;
    diff.emplace_back(0,1);
    diff.emplace_back(1,0);
    diff.emplace_back(0,-1);
    diff.emplace_back(-1,0);

    for(int i=0; i<H; i++)
    {
        for(int j=0; j<W; j++)
        {
            char temp;
            cin >> temp;
            if(temp == '#')
            {
                // 黒マスは0以上(初期値: 0)
                data[make_pair(i, j)] = 0;
                que.emplace(i, j);
            }
            else
            {
                // 白マスは-1
                data[make_pair(i, j)] = -1;
            }
        }
    }

    while(!que.empty())
    {
        auto cur = que.front();
        que.pop();

        // 現在のカーソル位置の上下左右を新たにカーソル位置とする
        for(auto it=diff.begin(); it!=diff.end(); it++)
        {
            // 境界値チェック
            int nx = cur.first + it->first;
            int ny = cur.second + it->second;
            if(nx < 0 || nx >=H || ny < 0 || ny >= W)
                continue;

            if(data.at(make_pair(nx, ny)) == -1)
            {
                data.at(make_pair(nx, ny)) = data.at(make_pair(cur.first, cur.second))++;
                que.emplace(nx, ny);
            }
        }
    }

    int max = 0;
    for(auto it : data)
    {
        if(max < it.second)
            max = it.second;
    }

    cout << max << endl;

    return 0;
}


#include "bits/stdc++.h"

using namespace std;
using ll = long long int;
using ullong = unsigned long long;
#define rep(i,n) for(int i = 0; i < n; i++)
#define FOR(i, a, b)  for(int i = (a); i < (b) ; i++)
#define pb push_back
#define SORT(v,n) sort(v, v+n)
#define ALL(x) (x).begin(),(x).end()
#define debug(x) cerr << #x << ": " << x << '\n'
#define int ll
const int INF = 1e9;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;
typedef pair<int, int> Vec2;
const int dx[8] = { 1, 0, -1, 0, 1, -1, -1, 1 };
const int dy[8] = { 0, 1, 0, -1, 1, 1, -1, -1 };

int h, w;
int d[1000][1000];
vector<string> grid(1000);

void printd() {
	cout << endl;
	rep(i, h) {
		rep(j, w) {
			cout << d[j][i];
		}
		cout << endl;
	}
	cout << endl;
}

void bfs(int x, int y) {
	queue<Vec2> Q;
	Q.push({ x,y });
	d[x][y] = 0;
	while (!Q.empty()) {
		int x = Q.front().first;
		int y = Q.front().second;
		Q.pop();
		rep(i, 4) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			if (nx >= 0 and nx < w and ny >= 0 and ny < h) {
				if(d[x][y] + 1 < d[nx][ny]) {
				//if(d[x][y] == INF){
					Q.push({ nx,ny });
					d[nx][ny] = d[x][y] + 1;
				}
			}
		}
	}
}

signed main() {
	ios::sync_with_stdio(false);
	cin >> h >> w;
	vector<Vec2> vec;
	rep(i, h) {
		cin >> grid[i];
	}
	rep(i, 1000) {
		rep(j, 1000)
			d[i][j] = INF;
	}

	rep(i, h) {
		rep(j, w) {
			if (grid[i][j] == '#') {
				bfs(j, i);
				//printd();
			}
		}
	}

	int ans = 0;
	rep(i, h) {
		rep(j, w) {
			ans = max(ans, d[j][i]);
		}
	}
	cout << ans << endl;
	return 0;
}


#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <set>
#include <string>
#include <map>
#include <cmath>
#include <cstring>

#define fi first
#define se second
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define rrep(i,n) for (int i = 1; i < (n); ++i)
#define drep(i,n) for (int i = (n)-1; i >= 0; --i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
#define all(x) (x).begin(), (x).end()
#define maxs(x,y) (x = max(x,y))
#define mins(x,y) (x = min(x,y))
#define pb push_back
#define sz(x) (int)(x).size()
#define PQ(T) priority_queue<T, v(T), greater<T> >

#define v(T) vector<T>
#define vv(T) v(v(T))

using namespace std;
typedef long long ll;
typedef unsigned uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<P> vp;

const ll LINF = 1001002003004005006ll;
const int INF = 1001001001;

const int mod = 1000000007;

char field[1010][1010];
bool visited[1010][1010];
int H, W;

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

queue<P> que;
int ans;

void bfs() {
    while(true) {
        queue<P> tmp;
        while(!que.empty()) {
            P p = que.front(); que.pop();
            int x = p.fi;
            int y = p.se;
            visited[y][x] = true;
            rep(i, 4) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if (nx>=0 && nx<W && ny>=0 && ny<H && field[ny][nx]=='.' && !visited[ny][nx]) {
                    tmp.push(P(nx,ny));
                }
            }
        }
        if (tmp.empty()) break;
        ans++;
        que = tmp;
    }
}

int main() {
    cin >> H >> W;
    rep(y,H)rep(x,W) cin >> field[y][x];

    rep(y,H)rep(x,W) if (field[y][x] == '#') que.push(P(x,y));
    ans = 0;
    bfs();
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define REP(i,n) for(int i = 0; i < n; i++)
#define PER(i,n) for(int i = n-1; i >= 0; i--)
#define FOR(i,l,r) for(int i = l; i <= r; i++)
#define ROF(i,l,r) for(int i = r; i >= l; i--)
#define DEBUG(x) cout << #x << "=" << x << endl;
#define SHOW1(A,n) { REP(i,n) cout<<A[i]<<(i==n-1?'\n':' '); }
#define SHOW2(A,m,n) { REP(j,m) SHOW1(A[j],n) }
#define pb push_back
#define fi first
#define se second
#define ALL(x) x.begin(),x.end()
#define SZ(x) (int)((x).size())
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> pii;
typedef pair<LL, LL> pll;
const int INF = 0x3f3f3f3f, MOD = 998244353;
const double PI = acos(-1), EPS = 1e-15;
const int MAXN = 1e3+9, MAXM = 2e5+9;

int m,n,vis[MAXN][MAXN];
char s[MAXN][MAXN];
const int r[]={0,0,1,-1};
const int c[]={1,-1,0,0};
#define vld(i,j) (0<=i&&i<m&&0<=j&&j<n)
struct node { int x,y,t; };
int bfs()
{
    memset(vis,0,sizeof(vis));
    queue<node> Q;
    REP(i,m)REP(j,n) if (s[i][j]=='#') Q.push({i,j,0}), vis[i][j]=1;
    int ans=0;
    while (!Q.empty()) {
        node now=Q.front(); Q.pop();
        int x=now.x,y=now.y,t=now.t;
        ans=max(ans,t);
        REP(i,4) {
            int xx=x+r[i], yy=y+c[i];
            if (vld(xx,yy) && !vis[xx][yy]) {
                vis[xx][yy]=1;
                Q.push({xx,yy,t+1});
            }
        }
    }
    return ans;
}

int main()
{
#ifdef LOCAL
    //freopen("i.txt", "r", stdin);
    //freopen("o.txt", "w", stdout);
#endif //LOCAL

    while (cin>>m>>n) {
        REP(i,m) scanf("%s", s[i]);
        cout<<bfs()<<endl;
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int N, M;
int MAX = 1000;
vector<vector<int>>  D(MAX, vector<int>(MAX));
vector<vector<char>> S(MAX, vector<char>(MAX));
vector<int> dx = { 0, 1,  0, -1 };
vector<int> dy = { 1, 0, -1,  0 };
queue<pair<int, int>> Q;

int main() {
	cin >> N >> M;
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < M; j++) {
			cin >> S.at(i).at(j);
			if (S.at(i).at(j) == '#') {
				Q.push({ i,j });
			}
		}
	}

	int ans = 0;
	while (!Q.empty()) {
		int x, y;
		tie(x, y) = Q.front();
		Q.pop();
		int d = D.at(x).at(y);
		ans = d;
		for (int k = 0; k < 4; k++) {
			int px = x + dx.at(k);
			int py = y + dy.at(k);
			if (px < 0 || px >= N || py < 0 || py >= M) continue;
			if (S.at(px).at(py) == '.') {
				Q.push({ px,py });
				S.at(px).at(py) = '#';
				D.at(px).at(py) = d + 1;
			}
		}
	}

	cout << ans << endl;
	return 0;
}


#include<iostream>
#include<vector>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
#define MAX 1000000000
int dis[1050][1050];

/*黒マスの位置*/
typedef struct position {
 int y;
 int x;
}position_ ;

int H,W;
int dy[4]={0, 1,-1,0};
int dx[4]={-1,0,0,1};
int ans=0;

int main(void){
 string A[1050];
 queue<position_> Q;
 int cnt=0;
 cin>>H>>W;

 for(int i=0; i<H; i++)cin>>A[i];

 position_ B;
 for(int i=0; i<H; i++)
  for(int j=0; j<W; j++){
   if(A[i][j]=='#'){
    B.x=j;
    B.y=i;
    Q.push(B);
    dis[i][j]=0;
   }
   else{
    dis[i][j]=MAX;
   }
  }

 position_ C;
 while(Q.empty()!=true){
  B=Q.front();
  Q.pop();
  for(int i=0; i<4; i++){
   if(0<=dx[i]+B.x && dx[i]+B.x<W && 0<=dy[i]+B.y && dy[i]+B.y<H){
    if(dis[dy[i]+B.y][dx[i]+B.x]==MAX){
     dis[dy[i]+B.y][dx[i]+B.x]=dis[B.y][B.x]+1;
     C.x=B.x+dx[i];
     C.y=B.y+dy[i];
     Q.push(C);
     ans=max(ans,dis[dy[i]+B.y][dx[i]+B.x]);
    }
   }
  }
 }
 cout<<ans<<endl;
 return 0;
}


#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdalign>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif
#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>
#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif
#define y0 qvya13579
#define y1 qvyb24680
#define j0 qvja13579
#define j1 qvjb24680
#define next qvne13579xt
#define prev qvpr13579ev
#define INF 1000000007
#define MOD 1000000007
#define PI acos(-1.0)
#define endl "\n"
#define IOS cin.tie(0);ios::sync_with_stdio(false)
#define M_P make_pair
#define PU_B push_back
#define PU_F push_front
#define PO_B pop_back
#define PO_F pop_front
#define U_B upper_bound
#define L_B lower_bound
#define B_S binary_search
#define PR_Q priority_queue
#define FIR first
#define SEC second
#if __cplusplus < 201103L
#define stoi(argument_string) atoi((argument_string).c_str())
#endif
#define REP(i,n) for(int i=0;i<(int)(n);++i)
#define REP_R(i,n) for(int i=((int)(n)-1);i>=0;--i)
#define FOR(i,m,n) for(int i=((int)(m));i<(int)(n);++i)
#define FOR_R(i,m,n) for(int i=((int)(m)-1);i>=(int)(n);--i)
#define ALL(v) (v).begin(),(v).end()
#define RALL(v) (v).rbegin(),(v).rend()
#define SIZ(x) ((int)(x).size())
#define COUT(x) cout<<(x)<<endl
#define CIN(x) cin>>(x)
#define CIN2(x,y) cin>>(x)>>(y)
#define CIN3(x,y,z) cin>>(x)>>(y)>>(z)
#define CIN4(x,y,z,w) cin>>(x)>>(y)>>(z)>>(w)
#define SCAND(x) scanf("%d",&(x))
#define SCAND2(x,y) scanf("%d%d",&(x),&(y))
#define SCAND3(x,y,z) scanf("%d%d%d",&(x),&(y),&(z))
#define SCAND4(x,y,z,w) scanf("%d%d%d%d",&(x),&(y),&(z),&(w))
#define SCANLLD(x) scanf("%lld",&(x))
#define SCANLLD2(x,y) scanf("%lld%lld",&(x),&(y))
#define SCANLLD3(x,y,z) scanf("%lld%lld%lld",&(x),&(y),&(z))
#define SCANLLD4(x,y,z,w) scanf("%lld%lld%lld%lld",&(x),&(y),&(z),&(w))
#define PRINTD(x) printf("%d\n",(x))
#define PRINTLLD(x) printf("%lld\n",(x))
typedef long long int lli;
using namespace std;

bool compare_by_2nd(pair<int,int> a, pair<int,int> b)
{
  if( a.second != b.second )
    {
      return a.second < b.second;
    }
  else
    {
      return a.first < b.first;
    }

}

int ctoi(char c)
{
  if( c >= '0' and c <= '9' )
    {
      return (int)(c-'0');
    }

  return -1;
}

int alphabet_pos(char c)
{
  if( c >= 'a' and c <= 'z' )
    {
      return (int)(c-'a');
    }

  return -1;
}

int alphabet_pos_capital(char c)
{
  if( c >= 'A' and c <= 'Z' )
    {
      return (int)(c-'A');
    }

  return -1;
}

vector<string> split(string str, char ch)
{
  int first = 0;
  int last = str.find_first_of(ch);

  if(last == string::npos)
    {
      last = SIZ(str);
    }

  vector<string> result;

  while( first < SIZ(str) )
    {
      string Ssubstr(str, first, last - first);
      result.push_back(Ssubstr);
      first = last + 1;
      last = str.find_first_of(ch, first);

      if(last == string::npos)
	{
	  last = SIZ(str);
	}
    }

  return result;
}

int gcd( int a , int b ) // assuming a,b >= 1
{
  if( a < b )
    {
      return gcd( b , a );

    }

  if( a % b == 0 )
    {
      return b;

    }

  return gcd( b , a % b );

}

int lcm( int a , int b ) // assuming a,b >= 1
{
  return  a * b / gcd( a , b );

}

/*------------------ the end of the template -----------------------*/

void bfs( vector<vector<int> >& m , deque<pair<int,int> >& q , int H, int W )
{
  int dx[4] = {0,1,0,-1};
  int dy[4] = {1,0,-1,0};

  while( SIZ(q) > 0 )
    {
      pair<int,int> temp = q.front();
      q.pop_front();

      REP(i,4)
	{
	  int y = temp.first + dy[i];
	  int x = temp.second + dx[i];

	  if( 0 <= y and y < H and 0 <= x and x < W )
	    {
	      if( m[y][x] == -1  )
		{
		  m[y][x] = m[temp.first][temp.second] + 1;

		  q.push_back(make_pair(y,x));

		}

	    }

	}

    }

}

int main()
{
  IOS; /* making cin faster */
  int H,W;
  CIN2(H,W);

  string S;
  vector<vector<int> > m(H,vector<int>(W,-1));

  deque<pair<int,int> > q;

  REP(i,H)
    {
      CIN(S);

      REP(j,W)
	{
	  if( S[j] == '#' )
	    {
	      m[i][j] = 0;
	      q.push_back(make_pair(i,j));
	    }

	}

    }

  bfs(  m , q , H, W );

  int mx = 0;

  REP(i,H)
    {
      REP(j,W)
	{
	  mx = max(mx,m[i][j]);

	}
    }

  PRINTD(mx);

}


#include <iostream>
#include <algorithm>
#include <vector>
#include<cmath>
#include<numeric>

using namespace std;

int main() {
	int H, W;
	cin >> H >> W;
	vector<vector<char>> A(H, vector<char>(W));
//	vector<vector<int>> Memo(H, vector<int>(W));

	vector<vector<int>> black(2, vector<int>(H * W));
	vector<vector<int>> white(2, vector<int>(H * W));

	int k = 0;
	int s = 0;
	int maxtime = 0;

	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {

			scanf("%c", &A[i][j]);

			//			cin >> A[i][j];
			if (A[i][j] == '#') {
				black[0][k] = i;
				black[1][k] = j;
				k++;
			}
			else {
				white[0][s] = i;
				white[1][s] = j;
				s++;
			}
		}
	}

	for (int i = 0; i < s; i++) {

		int minDis = H * W;

		for (int j = 0; j < k; j++) {

			minDis = min(minDis, abs(black[0][j] - white[0][i]) + abs(black[1][j] - white[1][i]));

		}

		maxtime = max(maxtime, minDis);
//		cout << maxtime;
	}
/*	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (A[i][j] == '#') {
			}
			else {
				int minDis = H * W;
				int dis;
				for (int m = 0; m < k; m++) {
					dis = abs(black[0][m] - i) + abs(black[1][m] - j);
					minDis = min(minDis, dis);
				}
			maxtime = max(maxtime, minDis);
			}
		}
	}
*/
	cout << maxtime;

	return 0;
}


#include <bits/stdc++.h>
using namespace std;

using ll = long long;
const int INF = 1<<29;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;
#ifdef LOCAL_ENV
	#define debug(var) std::cout<<#var" = "<<var<<std::endl
#else
	#define debug(var)
#endif
#define p(var)  std::cout<<var<<std::endl
#define PI (acos(-1))
#define rep(i, n)   for(int i=0, i##_length=(n); i< i##_length; ++i)
#define repeq(i, n) for(int i=1, i##_length=(n); i<=i##_length; ++i)
#define all(a) (a).begin(), (a).end()
#define pb push_back
inline double isnatural(double a) { return a>=0 && ceil(a)==floor(a); }
template<typename T> inline T gcd(T a, T b) { return b ? gcd(b,a%b) : a; }
template<typename T> inline T lcm(T a, T b) { return a / gcd(a,  b) * b; }
template<typename T1, typename T2>inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }
template<typename T1, typename T2>inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }
template<typename T1, typename T2> ostream& operator<<(ostream& s, const pair<T1, T2>& p) {return s << "(" << p.first << ", " << p.second << ")";}
template<typename T> ostream& operator<<(ostream& s, const vector<T>& v) {
	for (int i = 0, len = v.size(); i < len; ++i){
		s << v[i]; if (i < len - 1) s << "\t";
	}
	return s;
}
template<typename T> ostream& operator<<(ostream& s, const vector< vector<T> >& vv) {
	for (int i = 0, len = vv.size(); i < len; ++i){
		s << vv[i] << endl;
	}
	return s;
}
template<typename T1, typename T2> ostream& operator<<(ostream& s, const map<T1, T2>& m) {
	s << "{" << endl;
	for (typeof(m.begin()) itr = m.begin(); itr != m.end(); ++itr){
		s << "\t" << (*itr).first << " : " << (*itr).second << endl;
	}
	s << "}" << endl;
	return s;
}

/*-----8<-----8<-----*/

int H,W;
vector<vector<int>> dis;
vector<int> hh(2,-1),ww(2,-1);
void update(int h,int w){
	int t;
	{
		int i=0;
		int j=0;
		t=abs(i-h)+abs(j-w);
		chmin(dis[i][j],t);
		i=H-1;
		t=abs(i-h)+abs(j-w);
		chmin(dis[i][j],t);
	}
	{
		int i=0;
		int j=W-1;
		t=abs(i-h)+abs(j-w);
		chmin(dis[i][j],t);
		i=H-1;
		t=abs(i-h)+abs(j-w);
		chmin(dis[i][j],t);
	}

	debug(dis);
	rep(i,2){
		if(hh[i]==-1)continue;
		rep(j,2){
			if(ww[j]==-1)continue;
			t=abs(hh[i]-h)+abs(ww[j]-w);
			chmin(dis[hh[i]][ww[j]],t);
		}
	}
}
int main() {

	cin >> H >> W;

	if(H%2==0){
		hh[0]=H/2-1;
		hh[1]=H/2;
	}else{
		hh[0]=(H-1)/2;
	}
	if(W%2==0){
		ww[0]=W/2-1;
		ww[1]=W/2;
	}else{
		ww[0]=(W-1)/2;
	}

	vector<string> a(H,"");
	dis=vector<vector<int>>(H,vector<int>(W,INF));
	rep(i,H){
		cin >> a[i];
	}

	rep(i,H){
		rep(j,W){
			if(a[i][j]=='#')update(i,j);
		}
	}

	int maxval=0;
	{
		int i=0;
		int j=0;
		chmax(maxval,dis[i][j]);
		j=W-1;
		chmax(maxval,dis[i][j]);
	}
	{
		int i=H-1;
		int j=0;
		chmax(maxval,dis[i][j]);
		j=W-1;
		chmax(maxval,dis[i][j]);
	}
	rep(i,2){
		if(hh[i]==-1)continue;
		rep(j,2){
			if(ww[j]==-1)continue;
			chmax(maxval,dis[hh[i]][ww[j]]);
		}
	}

	p(maxval);
	return 0;
}


#include <bits/stdc++.h>
#include <climits>
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define srep(i, begin, end) for (__typeof(end) i = begin; i != end; i++)
#define si(x) int x = scanInt();
#define sll(x) LL x = scanLong();
#define sci(x) int x; scanf("%d", &x);
#define scll(x) LL x; scanf("%lld", &x);
#define pi(x) printf("%d ", x)
#define pll(x) printf("%lld ", x)
#define nl printf("\n")
#define clr(a) memset(a, 0, sizeof(a))
#define PB push_back
#define MP make_pair
using namespace std;
typedef unsigned int UI; // 32 bit integer
typedef long int LI; // 32 bit integer
typedef unsigned long int ULI; // 32 bit unsigned integer
typedef long long int LL; // 64 bit integer
typedef unsigned long long int ULL; // 64 bit unsigned integer
typedef long double LD;
typedef vector<int> VI;
typedef vector<LL> VLL;
typedef deque<int> DI;
typedef deque<LL> DLL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const LL MOD = 1e9+7;

/* Fast I/O */
inline int scanInt() {
	int n = 0;
	char ch = getchar();
	int sign = 1;
	while(ch < '0' || ch > '9') {
		if(ch == '-')	sign = -1;
		ch = getchar();
	}
	while(ch >= '0' && ch <= '9') {
		n = (n<<1)+(n<<3)+(int)(ch-'0');
		ch = getchar();
	}
	return n*sign;
}

inline LL scanLong() {
	LL n = 0;
	char ch = getchar();
	LL sign = 1;
	while(ch < '0' || ch > '9') {
		if(ch == '-')	sign = -1;
		ch = getchar();
	}
	while(ch >= '0' && ch <= '9') {
		n = (n<<1)+(n<<3)+(LL)(ch-'0');
		ch = getchar();
	}
	return n*sign;
}

const LL MAXN = 1e6+10;
LL N, M;
string grid[MAXN];
LL dist[MAXN];
deque<LL> Q;

LL getIndex(LL i, LL j) { return (i*M + j + 1); }

int main() {
	N = scanLong(); M = scanLong();
	rep(i, 0, N)	cin >> grid[i];
	rep(i, 0, (LL)MAXN)	dist[i] = LONG_MAX;
	rep(i, 0, N) {
		rep(j, 0, M) {
			if(grid[i][j] == '#')	Q.push_back(getIndex(i, j));
		}
	}
	rep(it, Q.begin(), Q.end())	dist[*it] = 0;

	while(!Q.empty()) {
		LL curr = Q.front(); Q.pop_front();
		LL col = (curr - 1) % M;
		LL row = (curr - col - 1) / M;
		if(row > 0 && grid[row-1][col] == '.') {
			grid[row-1][col] = '#';
			Q.push_back(getIndex(row-1, col));
			dist[getIndex(row-1, col)] = dist[curr] + 1;
		}
		if(row+1 < N && grid[row+1][col] == '.') {
			grid[row+1][col] = '#';
			Q.push_back(getIndex(row+1, col));
			dist[getIndex(row+1, col)] = dist[curr] + 1;
		}
		if(col > 0 && grid[row][col-1] == '.') {
			grid[row][col-1] = '#';
			Q.push_back(getIndex(row, col-1));
			dist[getIndex(row, col-1)] = dist[curr] + 1;
		}
		if(col+1 < M && grid[row][col+1] == '.') {
			grid[row][col+1] = '#';
			Q.push_back(getIndex(row, col+1));
			dist[getIndex(row, col+1)] = dist[curr] + 1;
		}
	}
	LL ans = 0;
	rep(i, 0, N) {
		rep(j, 0, M) {
			ans = max(ans, dist[getIndex(i, j)]);
		}
	}
	pll(ans); nl;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll allg[1000000];

ll gcd(ll a, ll b){
    while(b != 0){
        ll tmp = b;
        b = a % b;
        a = tmp;
    }
    return a;
}

void allg_setter(vector<ll> &array,int n){
    allg[0] = array.at(0);
    //cout << allg[0] << " ";
    for(int i=1;i<n;i++){
        allg[i] = gcd(allg[i-1],array.at(i));
        //cout << allg[i] << " ";
    }
    //cout << endl;
}

ll maxg(vector<ll> &array,int n){
    if(n == 2){
        return max(gcd(array.at(0),array.at(1)),max(gcd(array.at(1),array.at(2)),gcd(array.at(0),array.at(2))));
    }
    ll g1 = gcd(maxg(array,n-1),array.at(n));
    //cout << g1 << " " << allg[n-1] << endl;
    return max(g1,allg[n-1]);
}

int main(){
    int n;
    cin >> n;
    vector<ll> array(n);
    for(int i=0;i<n;i++) cin >> array.at(i);

    allg_setter(array,n);
    if(n == 2){
        cout <<  max(array.at(0),array.at(1)) << endl;
    }
    cout << maxg(array,n-1) << endl;
    /*for(int i=0;i<n;i++){
        cout << allg[i] << " ";
    }*/
}

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


#include <bits/stdc++.h>

#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl "\n"

using namespace std;
using ll = long long;

const ll MOD = 1000000007LL; // = 10^9 + 7
const double PI = 3.14159265358979;

// 最大公約数 : 3,4 ->  1
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }

void solve()
{
  int n;
  cin >> n;
  vector<int> a(n);
  cin >> a[0] >> a[1];
  if (n == 2)
  {
    cout << max(a[0], a[1]);
    return;
  }

  cin >> a[2];
  int gcd0 = gcd(a[1], a[2]);
  int gcd1 = gcd(a[0], a[2]);
  int gcd2 = gcd(a[0], a[1]);

  int now_gcd = max({gcd0, gcd1, gcd2});
  int may_waste_gcd = min({gcd0, gcd1, gcd2});

  for(int i = 3; i < n; ++i)
  {
    cin >> a[i];
    if (a[i] % now_gcd == 0) continue;

    int tmp_gcd = gcd(a[i], now_gcd);
    now_gcd = max(tmp_gcd, may_waste_gcd);
    may_waste_gcd = min(tmp_gcd, may_waste_gcd);
  }
  cout << now_gcd;
}

int main()
{
  fastio;
  solve();

  return 0;
}


#include<bits/stdc++.h>
#include<string.h>
#define pb push_back
#define all(v) v.begin(),v.end()
#define see(x) cout<<#x<<" : "<<(x)<<endl;
#define ya cout<<"YES"<<endl;
#define no cout<<"NO"<<endl;
#define ff first
#define sc second
typedef long long ll;
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL),cout.tie(NULL);
    //freopen("test.txt","r",stdin);
    ll n,ind=0,i,j,ans=0,ev=0,od=0;
    cin>>n;
    vector<ll>v(n);
    for(auto &ii:v)cin>>ii;
    ll l[n+2];
    ll r[n+2];
    l[0]=r[n+1]=0;
    for(i=1;i<=n;i++)
    {
        l[i]=__gcd(l[i-1],v[i-1]);
    }
    for(i=n-1;i>=0;i--)
    {
        r[i+1]=__gcd(r[i+2],v[i]);
    }
    ans=1;
    for(i=1;i<=n;i++)
    {
        ans=max(__gcd(l[i-1],r[i+1]),ans);
    }
    cout<<ans<<endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n;
    cin >> n;

    vector<int> numVec;
    int minNum = 1000000000;
    for (int i = 0; i < n; ++i)
    {
        int input;
        cin >> input;
        numVec.push_back(input);
        minNum = min(minNum, input);
    }

    int gcd = 1;
    for (int singleGcd = minNum; singleGcd > 0; --singleGcd)
    {
        int multiplesCount = 0;

        for (const int &singleNum : numVec)
        {
            if (singleNum % singleGcd == 0)
            {
                ++multiplesCount;
            }
        }

        if (multiplesCount >= n - 1)
        {
            gcd = singleGcd;
            break;
        }
    }

    cout << gcd << endl;
}


#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int calc_Greatest_common_divisor(int n, int m)
{
  while (n % m != 0)
  {
    int temp = m;
    m = n % m;
    n = temp;
  }
  return m;
}

void GCDonBlackboard()
{
  int n;
  cin >> n;
  vector<int> a(n);

  for (int i = 0; i < n; i++)
  {
    cin >> a[i];
  }
  sort(a.begin(), a.end());

  int max = 0;
  for (int i = 0; i < a.size(); i++)
  {
    for (int j = i+1; j < a.size(); j++)
      if (max < calc_Greatest_common_divisor(a[i], a[j])) max = calc_Greatest_common_divisor(a[i], a[j]);
  }
  cout << max << endl;
  return;
}

int main()
{
  GCDonBlackboard();
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
typedef long long ll;
typedef pair<int,int> P;
ll gcd(ll a, ll b) {
    if(a%b == 0) return b;
    else return gcd(b,a%b);
}
int main(void) {
    int n; cin >> n;
    vector<ll> a(n);
    rep(i, n) cin >> a[i];
    int cand1 = a[0], cand2 = a[1];
    for(int i=2;i<n;i++) {
        cand1 = gcd(cand1, a[i]);
        cand2 = gcd(cand2, a[i]);
    }
    cout << max(cand1, cand2);
}


#include <bits/stdc++.h>
using namespace std;

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

int main() {
  int n; cin >> n;

  int ans = 0;

  vector<int> a(n);
  for(int i = 0; i < n; i++){
    int temp; cin >> temp;
      a.at(i) = temp;
  }

  vector<int> l(n + 2, 0), r(n + 2, 0);

  for(int i = 1; i <= n; i++){
    l.at(i) = gcd(a.at(i - 1), l.at(i - 1));
  }
  for(int i = n; i > 0; i--){
    r.at(i) = gcd(a.at(i - 1), r.at(i + 1));
  }

  for(int i = 0; i < n; i++){
    ans = max(ans, gcd(l.at(i), r.at(i + 2)));
  }

  cout << ans << endl;

}


#include <bits/stdc++.h>

#define rep(i, x, n) for (int i = x; i < n; i++)
typedef long long ll;

const int INF = 1e9 + 7;

using namespace std;

ll gcd(ll n, ll k)
{
    if (k == 0)
	return n;
    ll mod = n % k;
    return gcd(k, mod);
}

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

    vector<int> a(n);
    rep (i, 0, n)
	cin >> a[i];

    int l_gcd[n + 1];
    int r_gcd[n + 1];
    l_gcd[0] = 0;
    r_gcd[n] = 0;

    rep (i, 1, n) {
	l_gcd[i] = gcd(l_gcd[i - 1], a[i - 1]);
	r_gcd[n - i] = gcd(r_gcd[n - i + 1], a[n - i]);
    }

    int res = 0;
    rep (i, 0, n)
	res = max(res, (int)gcd(l_gcd[i], r_gcd[i + 1]));

    cout << res << endl;

    return 0;
}


#include<iostream>
#include<vector>
#include<numeric>

using namespace std;

int gcd(int a, int b)
{
	while(b) {
		int t = a % b;
		a = b;
		b = t;
	}

	return a;
}

int max(int *m, int n)
{

	int max = 0;

	for (int i = 0; i < n; i++) {
		if (m[i] > max) {
			max = m[i];
		}
	}

	return max;
}

int main()
{
	int n, a;
	vector<int> A;

	int *L, *R, *M;

  	cin >> n;
  	for (int i = 0; i < n; i++) {
  		cin >> a;
  		A.push_back(a);
  	}

  	 L = new int[(n+1)];
  	 R = new int[(n+1) + 1];
  	 M = new int[(n+1)];
  	 L[0] = R[n+1] = 0;

  	for (int i = 0; i < n; i++) {
  		L[i+1] = gcd(L[i], A[i]);
  	}

  	 for (int i = n; i > 0; i--) {
  		R[i] = (gcd(R[i+1], A[i]));
  	}

  	 for (int i = 0; i < n; i++) {
  		M[i] = (gcd(L[i], R[i+1]));
  	}

	cout << max(M, n);

    return 0;
}


#include <iostream>
#include <cmath>
#include <string>
#include <cstring>
#include <utility>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#define debug(x) cerr << #x << ':' << x << endl
#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
using namespace std;
typedef long long ll;

int gcd(int a, int b) {
    if(a<b) int tmp=a, a=b, b=tmp;
    if(b==0) return a;
    return gcd(b, a%b);
}

int main(){
    int n;
    cin >> n;
    int A[n];
    REP(i, n) cin >> A[i];

    int l_gcd[n+1], r_gcd[n+1];
    for(int i=0; i<=n; i++){
        if(i==0) l_gcd[i]=0;
        else l_gcd[i] = gcd(l_gcd[i-1], A[i-1]);
    }
    for(int i=n; 0<=i; i--){
        if(i==n) r_gcd[i]=0;
        else r_gcd[i] = gcd(r_gcd[i+1], A[i]);
    }

    int ma=-1;
    for(int i=0; i<=n-1; i++)
        ma = max(ma,gcd(l_gcd[i], r_gcd[i+1]));
    cout << ma << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>

using namespace std;

#define PB push_back
#define ALL(v) (v).begin(), (v).end()
#define SZ size()
#define FOR(i, a, b) for(int (i) = (a); (i) < (b); (i)++)
#define REP(i, n) FOR((i), 0, (n))
#define GET(a) cin >> (a)
#define GET2(a, b) cin >> (a) >> (b)
#define GET3(a, b, c) cin >> (a) >> (b) >> (c)
#define SHOW(v) cout << (v) << endl
#define SHOW2(a, b) cout << (a) << " " << (b) << endl
#define SHOW3(a, b, c) cout << (a) << " " << (b) << " " << (c) << endl
#define MOD 1000000007
template<class T> void GETV(T &v) { REP(i, v.size()) { GET(v[i]); } }
template<class T> void SHOWV(T &v) { REP(i, v.size()) { SHOW(v[i]); } }

typedef long long ll;

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

int main() {
	int n;
	cin >> n;

	vector<int> v(n);

	for(int i = 0; i < n; i++) {
		cin >> v[i];
	}

	int max = gcd(v[0], v[1]);
	for(int i = 2; i < n; i++) {
		max = gcd(max, v[i]);
	}

	int index1 = 0;
	int index2 = 0;
	int tmp = v[0];
	for(int i = 0; i < n; i++) {
		tmp = gcd(tmp, v[i]);
		if(tmp == max) {
			index1 = i - 1;
			index2 = i;
			break;
		}
	}

	int ans1 = 0;
	int ans2 = 0;
	for(int i = 0; i < n; i++) {
		if(i != index1) {
			if(ans1 == 0) {
				ans1 = v[i];
			}
			else {
				ans1 = gcd(ans1, v[i]);
			}
		}
		if(i != index2) {
			if(ans2 == 0) {
				ans2 = v[i];
			}
			else {
				ans2 = gcd(ans2, v[i]);
			}
		}
	}

	cout << (ans1 > ans2 ? ans1 : ans2) << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    ll n;
    vector<ll> odd, even;

    cin >> n;
    for(int i = 0; i < n; i++){
        int x;
        cin >> x;
        if(x % 2 == 0) even.push_back(x);
        else odd.push_back(x);
    }

    int el = even.size(), ol = odd.size();
    ll ans;

    if(el == n && n == 2){
        ans = max(even[0], even[1]);
    }
    else if(ol == n && n == 2){
        ans = max(odd[0], odd[1]);
    }
    else if(n == 2){
        ans = max(odd[0], even[0]);
    }
    else if(el == n){
        ans = even[0];
        for(int i = 1; i < n; i++)
             ans = __gcd(ans, even[i]);
    }
    else if(ol == n){
        ans = odd[0];
        int cnt = 0;
        ll pre = ans;
        for(int i = 1; i < n; i++){
            ans = __gcd(ans, odd[i]);
            if(ans == 1){
                cnt++;
                if(cnt <= 1) ans = pre;
            }
            pre = ans;
        }
    }
    else if(el == 1){
        ans = odd[0];
        for(int i = 1; i < ol; i++){
            ans = __gcd(ans, odd[i]);
        }
    }
    else if(ol == 1){
        ans = even[0];
        ll pre = ans;
        int cnt = 0;
        for(int i = 1; i < el; i++){
            ans = __gcd(ans, even[i]);
            if(ans == 1){
                cnt++;
                if(cnt <= 1){
                    ans = pre;
                }
            }
            pre = ans;
        }
    }
    else{
        ans = 1;
    }

    cout << ans << endl;

    return 0;
}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<bits/stdc++.h>
#include<cmath>
using namespace std;

int main(){
  int N;
  cin>>N;
  vector<int> A;
  for(int i=0; i<N; ++i){
    int a;
    cin>>a;
    A.push_back(a);
  }

  sort(A.begin(),A.end());

  int ans=0;
  for(int i=A[1]; i>0; --i){
    int count=0;
    if((A[0]%i==0)||(A[1]%i==0)){
      for(int j=0; j<N; ++j){
        if(A[j]%i==0) count++;
      }
      if(count>=N-1){
        ans=i;
        break;
      }
    }
  }

  cout<<ans<<endl;
}


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
using ll = long long;

int gcd(int n, int m) {
    if (n < m) swap(n, m);
    while (m != 0) {
        int r = n % m;
        n = m;
        m = r;
    }
    return n;
}

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

    int n;
    cin >> n;

    vector<int> a(n), b(n + 1), c(n + 1);
    int r = 0;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        r = gcd(r, a[i]);
        b[i + 1] = r;
    }

    r = 0;
    for (int i = n - 1; i >= 0; i--) {
        r = gcd(r, a[i]);
        c[i] = r;
    }

    r = 0;
    for (int i = 0; i < n; i++) {
        r = max(r, gcd(b[i], c[i + 1]));
    }

    //a[0]を書き換えるなら、a[1]~a[n-1]のgcdでOK
    //a[0]を書き換えないなら、

    cout << r << endl;

    return 0;
}


/*#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <array>
#include <vector>
#include <deque>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
*/

#include <bits/stdc++.h>
using namespace std;

#define int long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define FOR(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define SORT(c) sort((c).begin(),(c).end())

typedef long long ll;
const ll INF = 1LL<<60;
const ll mod = 1e9 + 7;
const int MAX_N = 5e5 + 5;
int dx[] = { -1,0,1,0 }, dy[] = { 0,1,0,-1 };
vector<ll> prime;

ll inv[MAX_N], fac[MAX_N];

template <class T = ll> T in() { T x; cin >> x; return (x); }
inline ll GCD(ll a, ll b) { ll c; while (b != 0) { c = a % b; a = b; b = c; }return a; }
inline ll LCM(ll a, ll b) { return a * b / GCD(a, b); }
inline ll POW(ll a, ll b) { ll c = 1; while (b > 0) { if (b & 1) { c = a * c%mod; }a = a * a%mod; b >>= 1LL; }return c; }
inline void _nCr() { fac[0] = 1; for (int i = 1LL; i < MAX_N; i++) { fac[i] = fac[i - 1] * i%mod; }for (int i = 0; i < MAX_N; i++) { inv[i] = POW(fac[i], mod - 2); } }
inline ll nCr(ll n, ll r) { return (fac[n] * inv[r] % mod)*inv[n - r] % mod; }
inline void PRI(ll n) { bool a[n + 1]; for (int i = 0; i < n + 1; i++) { a[i] = 1; }for (int i = 2; i < n + 1; i++) { if (a[i]) { prime.pb(i); ll b = i; while (b <= n) { a[b] = 0; b += i; } } } }

typedef pair<int, pair<int, int>> edge;

class UnionFind {
private:
	vector<int> par;
public:
	UnionFind(int N) { par = vector<int>(N, -1LL); }
	int find(int x);
	ll size(int x);
	void unite(int x, int y);
	bool same(int x, int y);
};

class Kruskal {
private:
	UnionFind *uf;
	vector<edge> e;
public:
	vector<edge> mst;
	Kruskal(int N) { uf = new UnionFind(N); }
	void add(int x, int y, ll z);
	void run();
};

//----UnionFind-------------------------------
int UnionFind::find(int x) {
	if (par[x] < 0) return x;
	else return par[x] = find(par[x]);
}

ll UnionFind::size(int x) {
	return -par[find(x)];
}

void UnionFind::unite(int x, int y) {
	x = find(x);
	y = find(y);

	//大きい方に小さい方をくっ付ける
	if (size(x) < size(y)) swap(x, y);
	par[x] += par[y];
	par[y] = x;
}

bool UnionFind::same(int x, int y) {
	x = find(x);
	y = find(y);
	return x == y;
}

//----Kruskal-------------------------------
void Kruskal::add(int x, int y, ll z) {
	//x < y
	if (x > y) swap(x, y);
	e.push_back({ z,{x,y} });
}

void Kruskal::run() {
	sort(e.begin(), e.end());
	e.erase(unique(e.begin(), e.end()), e.end());
	for (auto x : e) {
		if (uf->same(x.second.first, x.second.second)) {
			continue;
		}
		else {
			mst.push_back(x);
			uf->unite(x.second.first, x.second.second);
		}
	}
}

signed main() {
	int n;
	cin >> n;
	int a[n];
	REP (i,n) {cin >> a[i];}
	int gr[n],gl[n];
	gr[1] = a[0];
	gl[n-2] = a[n-1];
	FOR (i,2,n) {
		gr[i] = GCD(gr[i-1],a[i-1]);
		gl[n-i-1] = GCD(gl[n-i],a[n-i]);
	}
	gr[0] = gl[0];
	gl[n-1] = gr[n-1];
	int ans = 0;
	REP (i,n) {
		ans = max(ans,GCD(gr[i],gl[i]));
	}
	cout << ans << endl;
}


#include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;

int MOD = 998244353;

int main(void){

    int N;
    cin >> N;

    int a[N];
    int sum=0;
    long long all=1;
    for(int i=0;i<N;i++){
        cin >> a[i];
        sum += a[i];
        all = (3*all) % MOD;
    }

    long long dp1[N+1][sum+1], dp2[N+1][sum+1];
    memset(dp1, 0, sizeof(dp1));
    memset(dp2, 0, sizeof(dp2));
    dp1[0][0] = dp2[0][0] = 1;

    for(int i=0;i<N;i++){
        for(int j=0;j<=sum;j++){
            if( a[i] <= j ){
                dp1[i+1][j] = (dp1[i][j-a[i]] + 2*dp1[i][j]) % MOD;
                dp2[i+1][j] = (dp2[i][j-a[i]] + dp2[i][j]) % MOD;
            }
            else{
                dp1[i+1][j] = 2*dp1[i][j] % MOD;
                dp2[i+1][j] = dp2[i][j] % MOD;
            }
        }
    }

    long long p1=0;
    for(int i=(sum+1)/2;i<=sum;i++){
        p1 = (p1 + dp1[N][i]) % MOD;
    }
    p1 = 3*p1 % MOD;

    long long p2=0;
    if(sum%2 == 0){
        p2 = dp2[N][sum/2];
    }
    p2 = 3*p2 % MOD;

    long long p3=0;

    long long ans = (all - p1 + p2 - p3) % MOD;

    while (ans < 0) {
        ans += MOD;
    }
    cout << ans << endl;
}

Score : 600 points

Problem Statement

You are given N integers. The i-th integer is a_i.
Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:

Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.

Constraints

3 \leq N \leq 300

1 \leq a_i \leq 300(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.

Sample Input 1

4
1
1
1
2

Sample Output 1

18

We can only paint the integers so that the lengths of the sides of the triangle will be 1, 2 and 2, and there are 18 such ways.

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

20
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9
3
2
3
8
4

Sample Output 3

563038556


#include <bits/stdc++.h>
using namespace std;

int main() {
  int A,B,C;
  cin >> A >> B >> C;
  if(A*C<=B){
    cout << C << endl;
  }else{
    cout << B/A << endl;
  }
}

Score : 100 points

Problem Statement

Takahashi likes the sound when he buys a drink from a vending machine.

That sound can be heard by spending A yen (the currency of Japan) each time.

Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times Takahashi will hear his favorite sound.

Sample Input 1

2 11 4

Sample Output 1

4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


#include<bits/stdc++.h>
#include<stdlib.h>
using namespace std;
int main(){
    int a,b,c;
    cin>>a>>b>>c;
    if(b/a>c) cout<<c;
    else cout<<b/a;
}


#include <iostream>
using namespace std;

int main(){
    int a,b,c;
    cin >> a >> b >> c;
    int n = b/a;
    if(n < c){
        cout << n << "\n";
    }else{
        cout << c << "\n";
    }
}


#include <bits/stdc++.h>

using namespace std;

int main(){
	int A, B, C;
	cin >> A >> B >> C;

	if(A * C > B){
		cout << B / A << endl;
	}else{
		cout << C << endl;
	}

	return 0;

}


#include <bits/stdc++.h>
using namespace std;

int n;
int h[100005];
long long dp[100005];

int main()
{
  	cin >> n;
  	for (int i = 1; i <= n; ++ i) {
      	cin >> h[i];
    }

  	dp[1] = 0;
  	dp[2] = abs(h[2] - h[1]);
  	for (int i = 3; i <= n; ++ i) {
      	dp[i] = min(dp[i - 1] + abs(h[i] - h[i - 1]), dp[i - 2] + abs(h[i] - h[i - 2]));
    }

  	cout << dp[n];
}

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path 1 → 2 → 4, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path 1 → 3 → 5 → 6, the total cost incurred would be |30 - 60| + |60 - 60| + |60 - 50| = 40.


/* Author- Abhijeet Trigunait */

#include<bits/stdc++.h>
#define lld long long int
#define F first
#define S second
#define P pair<int,int>
#define pb push_back
#define mod 1e9+7
#define setbits(x) __builtin_popcountll(x)
#define zerobits(x) __builtin_ctzll(x)
#define gcd(x,y) __gcd(x,y)
#define endl '\n'

using namespace std;

lld dp[100010]={0};

namespace MinCost{
	lld getMin(lld *arr,lld n){
        dp[0]=arr[0];
        dp[1]=abs(arr[1]-arr[0]);
        dp[2]=abs(arr[2]-arr[0]);
        for(lld i=3;i<n;++i){
        	lld op1=dp[i-1]+abs(arr[i]-arr[i-1]);
        	lld op2=dp[i-2]+abs(arr[i]-arr[i-2]);
        	dp[i]=min(op1,op2);
        }
        return dp[n-1];
	}
}

int main(){

 	lld n;
 	cin>>n;
 	lld arr[n];
 	for(lld i=0;i<n;++i)cin>>arr[i];
 	cout<<MinCost::getMin(arr,n);
}


#include <bits/stdc++.h>
#define ll long long
#define fastIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
const int N = 105 , W = 5 + 1e5;
int n , w , its[N] , wie[W];
ll dp[N][W];
ll calc(int p , int c){
	if (p == n){
		if (c <= w) return 0;
		else return -1e9;}
	if (c > w) return -1e9;
	if (dp[p][c] != -1) return dp[p][c];
	ll tk = calc(p + 1 , c + wie[p]) + its[p];
	ll ntk = calc(p + 1 , c);
	return dp[p][c] = max(tk , ntk);
}
int main() { fastIO
    cin >> n >> w;
    memset(dp , -1 , sizeof dp);
    for (int i = 0 ; i < n ; i++) cin >> wie[i] >> its[i];
    cout << calc(0 , 0) << endl;
}


#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <cstring>
using namespace std;

void solve(){
  int n;
  cin >> n;
  int a[n];
  for(int i=0; i<n ; i++){
    cin>>a[i];
  }
  int dp[n];
  dp[0] = 0;
  dp[1] = abs(a[1]-a[0]);
  for(int i=2; i<n; i++){
    dp[i] = min(dp[i-1] + abs(a[i]-a[i-1]), dp[i-2] + abs(a[i]-a[i-2]));
  }
  cout << dp[n-1]<<"\n";
}

int main(){
  int t=1;
  // cin>>t;
  while(t--){
    solve();
  }
 return 0;
}


// Author :: <Hitesh_Saini>
#include<bits/stdc++.h>

#define __speed() ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define dbg(x) cout << "--- " << #x << " = " << x << " ---\n";
#define findmax(v) *max_element(v.begin(), v.end())
#define _sum(a) accumulate(a.begin(), a.end(), 0)
#define tt int t;for(cin>>t; t--; )
#define f0(i, n) for(i = 0; i < int(n); i++)
#define f1(i, n) for(i = 1; i<= int(n); i++)
#define all(x) x.begin(), x.end()
#define EB emplace_back
#define PB push_back
#define F first
#define S second
#define endl "\n"

using namespace std;
using mii = map<int, int>;
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
const int mod = 1e9+7,mxN = 1e6+5;

template<typename... Args>void print(Args... args){((cout << args << " "), ...);cout << endl;}
ll mod_pow(ll x, ll y){ll res = 1;x = x % mod;while(y>0){if(y&1)res = (res*x) % mod; y = y>>1;x = (x*x) % mod; }return res; }ll mod_inv ( ll n ){ll ans = mod_pow ( n , mod - 2 ) ;return ans ;}ll mul(ll a, ll b){a%=mod, b%=mod;return (a*b)%mod;}ll sub(ll a,ll b){a%=mod, b%=mod;return (a-b+mod)%mod;}ll add(ll a, ll b){a%=mod, b%=mod;return (a+b)%mod;}
bool _prime(ll n){if(n<2)return 0;if(n<4)return 1;if(n%2==0||n%3==0)return 0;for(ll i=5;i*i<=n;i+=6)if(n%i==0||n%(i+2)==0)return 0;return 1;}

/* #include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define iset tree<ll , null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define iof order_of_key
#define findat find_by_order */

int n, cache[mxN], A[mxN];
int f(int pos){
	if(pos<=0)
		return 0;
	if(pos==1)
		return abs(A[0]-A[1]);
	if(cache[pos]!=-1)
		return cache[pos];
	return cache[pos]=min(abs(A[pos]-A[pos-2])+f(pos-2), abs(A[pos]-A[pos-1])+f(pos-1));
}

void solve(){//D
	cin >> n;
	int i;
	memset(cache, -1, sizeof(cache));
	f0(i, n)
		cin >> A[i];
	print(f(n-1));
}

int main(){
	#ifndef ONLINE_JUDGE
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
	#endif
    __speed();
    solve();
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

int main()
{
    ios_base::sync_with_stdio(0);
    int n;
    cin>>n;
    vector<int> arr(n);
    int i;
    for(i=0;i<n;++i){
        cin>>arr[i];
    }
    vector<int> dp(n);
    dp[0]=0;
    dp[1]=abs(arr[1]-arr[0]);
    for(i=2;i<n;++i){
        dp[i] = min(dp[i-1]+abs(arr[i]-arr[i-1]),dp[i-2]+abs(arr[i]-arr[i-2]));
    }
    cout<<dp[n-1];
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;

const int MOD = 1000000007;
const char NL = '\n';

void solve()
{
    int n; cin >> n;
    vector<int> v;
    for (int i = 0; i < n; ++i) {
        int h; cin >> h;
        v.push_back(h);
    }
    vector<int> dp(n, 0);
    dp[1] = abs(v[1] - v[0]);
    for (int i = 2; i < n; ++i) {
        dp[i] = min(dp[i - 1] + abs(v[i] - v[i - 1]), dp[i - 2] + abs(v[i] - v[i - 2]));
    }
    cout << dp[n - 1] << NL;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define pob pop_back
#define bs binary_search
#define mp make_pair
#define F first
#define S second
#define It iterator
#define tol(s) transform(s.begin(),s.end(),s.begin(),::tolower);
#define tou(s) transform(s.begin(),s.end(),s.begin(),::toupper);
#define rint register int
#define en "\n"
#define br break
#define con continue
#define fri(n) for(register int i=0;i<n;i++)
#define frj(n) for(register int j=0;j<n;j++)
#define T(i) int i=1;cin>>i;while(i--)
#define fast ios_base::sync_with_stdio(0);cin.tie();cout.tie();
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
typedef vector<pi>vii;
typedef map<int,int> mi;
typedef set<int> S;
typedef list<int> L;
typedef stack<int> St;
typedef queue<int> Qu;
typedef deque<int> Dq;
typedef map<string,int> msi;
typedef map<pi,int> mpi;
typedef map<int,vii> mivi;
typedef map<pi,vi> mpivi;
int cost(int a[],int n,int ans[])
{
    if(ans[n-2]==-1)ans[n-2]=cost(a,n-2,ans);
    if(ans[n-1]==-1)ans[n-1]=cost(a,n-1,ans);
    return min(abs(a[n]-a[n-2])+ans[n-2],abs(a[n]-a[n-1])+ans[n-1]);
}
void solve()
{
    int n;cin>>n;
    int a[n+1]={};fri(n)cin>>a[i+1];
    int ans[n+1]={};fri(n+1)ans[i]=-1;
    ans[2]=abs(a[2]-a[1]);
    ans[1]=0;
    cout<<cost(a,n,ans);
}
int main()
{
    fast;
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    //T(t)
    {
        solve();
    }
}


//Author: nimishkhurana
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(i=a;i<b;i++)
#define rrep(i,b,a) for(i=b;i>=a;i--)
#define ld long double
#define ll long long
#define umapi unordered_map<int,int>
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vi vector<int>
#define vl vector<ll>
#define vii vector<pii>
#define vll vector<pll>
#define pb push_back
#define mk make_pair
#define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define INF 1000000000
template <typename T>
ostream& operator << (ostream& stream, const pair<T,T> &p) {
    return stream<<"("<<p.first<<","<<p.second<<") ";
}

int n;
const int mxn = 1e5;
int h[mxn];
int dp[mxn];

int solve(int i){
    if(i==n-1) return 0;
    if(dp[i]!=-1) return dp[i];
    if(i+1 == n-1)
        return dp[i] = abs(h[i+1] - h[i]);

    return dp[i] = min(abs(h[i+1] - h[i]) + solve(i+1), abs(h[i+2] - h[i]) + solve(i+2));
}

int solve_iterative(){
    int dp0 = 0;
    int dp1 = abs(h[1] - h[0]);

    for(int i = 2; i < n; i++){
        int temp = dp0;
        dp0 = dp1;
        dp1 = min(abs(h[i] - h[i-1]) + dp1, abs(h[i-2] - h[i]) + temp);
    }
    return dp1;
}

int main(){
    fastIO
    // #ifndef ONLINE_JUDGE
    //     freopen("input.txt", "r", stdin);
    //     freopen("output.txt", "w", stdout);
    // #endif
    memset(dp, -1, sizeof(dp));

    cin>>n;
    for(int i = 0; i < n; i++) cin>>h[i];

    cout<<solve_iterative();

    return 0;
}


#include <bits/stdc++.h>
#define fastIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

typedef long long int ll;

using namespace std;
int n;

int main()
{
	cin>>n;
	int h[n+1];

	for(int i=1;i<=n;i++) cin>>h[i];

	int cost[n+1];

	for(int i=0;i<=n;i++)
	{
		if((i==0)||(i==1)) cost[i]=0;
			else if(i==2) cost[i]=h[2]-h[1];
				else
				{
					cost[i]=min((cost[i-1]+abs(h[i]-h[i-1])),(cost[i-2]+abs(h[i]-h[i-2])));
				}
	}
	cout<<cost[n];
}


#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define all(x) x.begin(), x.end()
typedef pair<int,int> pii;
typedef pair <long long,long long> pll;
typedef long long ll;
typedef long double ld;
const ll mod = 1e9+7;
int main(){
    ios_base::sync_with_stdio(false); cin.tie(NULL);
    int N;
    cin>>N;
    vector <int> v(N);
    for(int &x : v)
		cin>>x;

	vector <int> cost(N);
	cost[0] = 0; cost[1] = abs(v[1] - v[0]);
	for(int i = 2; i < N ; i++ )
		cost[i] = min(cost[i-1] + abs(v[i] - v[i-1]),cost[i-2] + abs(v[i] - v[i-2]) );

	cout<<cost[N-1];
    return 0;
}


#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
#include<string>
#include<climits>
#include<unordered_map>
#include<set>
#define loopi(x,y) for(int i = x;i<(y);i++)
#define loopj(x,y) for(int j = x;j<(y);j++)

#define newline cout<<"\n";
#define ll long long int
using namespace std;
#define mod  1000000007

int cost[1000000];

int jump(vector<int> & ht, int i, int n)
{
	if (i >= n - 1)
	{
		return 0;
	}
	int a = INT_MAX, b = INT_MAX;

	if (i + 1 < n)
	{
		if (cost[i + 1] == -1)
		{
			cost[i + 1] = jump(ht, i + 1, n);
		}
		a = abs(ht[i + 1] - ht[i]) + cost[i + 1];
	}
	if (i + 2 < n)
	{
		if (cost[i + 2] == -1)
		{
			cost[i + 2] = jump(ht, i + 2, n);
		}
		b = abs(ht[i + 2] - ht[i]) + cost[i + 2];
	}
	return cost[i] = min(a, b);
}

int main() {

	ios_base :: sync_with_stdio(false);
	cin.tie(NULL);

// #ifndef ONLINE_JUDGE
// 	freopen("input.txt", "r", stdin);
// 	freopen("output.txt", "w", stdout);
// #endif

	int n;
	cin >> n;

	vector<int> ht(n);

	loopi(0, n)
	{
		cin >> ht[i];
		cost[i] = -1;
	}

	cout << jump(ht, 0, n);

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    vector<int> hs(n);
    for(int i=0; i<n; i++) cin >> hs.at(i);
    vector<ll> node(n, static_cast<ll>(1e18));
    node.at(0) = 0;
    for(int i=0; i<n; i++)
    {
        if(i+1 < n)
        {
            ll nc = node.at(i) + abs(hs.at(i) - hs.at(i+1));
            node.at(i+1) = min(node.at(i+1), nc);
        }
        if(i+2 < n)
        {
            ll nc = node.at(i) + abs(hs.at(i) - hs.at(i+2));
            node.at(i+2) = min(node.at(i+2), nc);
        }
    }
    cout << node.back() << '\n';

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<long long> vll;
typedef vector<int> vi;
typedef pair<int, int> pi;

#define pb push_back

#define rep(i, l, n) for (int i = (l); i < n; i++)
#define rep_cs(i, l, n) for (int i = (l); i <= n; i++)

#define rep_d(j, n) for (int j = n; j >= 0; j--)
#define rep_d_op(j, n, a) for (int j = n; j >= a; j--)

template <class T>
inline bool chmax(T &a, T b)
{
    if (a < b)
    {
        a = b;
        return 1;
    }
    return 0;
}
template <class T>
inline bool chmin(T &a, T b)
{
    if (a > b)
    {
        a = b;
        return 1;
    }
    return 0;
}

const int MOD = 1000000007;

const vector<int> dx = {1, 0};
const vector<int> dy = {0, 1};
const ll INF = 1LL << 60;

// int max = *std::max_element(vec.begin(), vec.end());
// int sum = accumulate(list, list + size, 0);

int GCD(int a, int b) { return b ? GCD(b, a % b) : a; }

using Graph = vector<vector<int>>;

Graph G;

vector<bool> seen;
void dfs(const Graph &G, int v)
{
    seen[v] = true;

    for (auto next_v : G[v])
    {
        if (seen[next_v])
            continue;
        dfs(G, next_v);
    }
}

int main()
{
    ll n;
    cin >> n;
    vll h(n);
    rep(i, 0, n) cin >> h[i];

    ll dp[100010];
    rep(i, 0, 100010)
    {
        dp[i] = INF;
    }

    dp[0] = 0;

    rep(i, 0, n)
    {
        chmin(dp[i + 1], dp[i] + abs(h[i] - h[i + 1]));
        chmin(dp[i + 2], dp[i] + abs(h[i] - h[i + 2]));
    }

    cout << dp[n - 1] << endl;
}


#include<iostream>
#include<vector>
#include<algorithm>
#include<iomanip>

using namespace std;

#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define ALL(a) (a).begin(),(a).end()
#define PI 3.141592653589793238
#define INF 1050000000

using vi = vector<int>;

int dp[110000];

int dfs(int k,int N,vi h)
{
	if (k >=N)return INF;
	if (k == N - 1)return 0;

	if (dp[k] != -1)return dp[k];

	int step1 = dfs(k+ 1, N, h) + abs(h[k + 1] - h[k]);
	int step2 = dfs(k + 2, N, h) + abs(h[k + 2] - h[k]);

	return dp[k] = min(step1, step2);
}

int main() {

	int N;

	cin >> N;

	vi h(N+1);

	REP(i, N) {
		cin >> h[i];
	}

	REP(i, 110000) {
		dp[i] = -1;
	}

	cout << dfs(0,N,h) << endl;

	return 0;
}


#include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef pair <ll,ll> P;
#define REP(i, n) for(int i = 0; i < (int)(n); i++)
#define REPR(i, n) for(int i = n-1; i >= 0; i--)
#define FOR(i, n, m) for(int i = n; i < (int)(m); i++)
#define PRINT(x) cout << x << endl
#define ALL(v) v.begin(), v.end()

ll gcd(ll a, ll b) { return b ? gcd(b,a%b) : a;}
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }

ll MOD = 1000000007;

int main()
{
    ll N;
    cin >> N;
    vector<ll> A(N);
    REP(i, N) cin >> A[i];
    vector<ll> dp(N);
    dp[1] = abs(dp[1] - dp[0]);
    FOR(i, 2, N) {
        dp[i] = min(dp[i-1] + abs(A[i] - A[i-1]), dp[i-2] + abs(A[i] - A[i-2]));
    }
    PRINT(dp.back());
    return 0;
}


#include <bits/stdc++.h>
#define rep(i, n, m) for (int i = (int)(n); i < (int)(m); i++)
#define repr(i, n, m) for (int i = (int)(n) - 1; i >= (int)(m); i--)
using namespace std;
using ll = int64_t;
const int MOD = 1000000007; // 10^9+7

int main() {
    int n;
    cin >> n;
    vector<int> h(n);
    rep(i, 0, n) cin >> h[i];

    vector<int> dp(n);
    dp[0] = 0;
    dp[1] = abs(h[0] - h[1]);

    rep(i, 2, n)
    {
        dp[i] = min(dp[i - 1] + abs(h[i - 1] - h[i]), dp[i - 2] + abs(h[i] - h[i - 2]));
    }

    cout << dp[n - 1] << endl;
}


#include <bits/stdc++.h>
using namespace std;

#define FASTIO  ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define ll long long int
#define ld long double
#define vll vector<ll>
#define pl pair<ll,ll>
#define vl(p) vector<p>
#define W while
#define For(i,s,x) for(i=s;i<x;i++)
#define Fore(i,s,x) for(i=s;i<=x;i++)
#define FOR(i,x) for(i=0;i<x;i++)
#define Rof(i,s,x) for(i=s;i>=x;i--)
#define all(v) v.begin(),v.end()
#define it(r,v) for(auto r=v.begin();r!=v.end();r++)
#define pb push_back
#define in insert
#define sz size()
#define F first
#define S second
#define nl cout<<"\n"
#define pr(a) cout<<a<<" "
#define pr2(a,b) cout<<a<<" "<<b<<"\n"
#define pr3(a,b,c) cout<<a<<" "<<b<<" "<<c<<"\n"
#define mod 1000000007

// ll ans(ll n, ll b[], ll c[], ll i, ll an) {
//     while()
// }

int main() {
	FASTIO;
    ll t=1, i ,j, k, l;
    // cin>>t;
    W(t--) {
        ll n=4;
        cin>>n;
        ll a[n];
        FOR(i,n) cin>>a[i];
        ll b[n], c[n];
        FOR(i,n-1) b[i]=abs(a[i+1]-a[i]);
        FOR(i,n-2) c[i]=abs(a[i+2]-a[i]);
        if(n==2) { pr(a[1]-a[0]); continue; }
        ll ans1=b[0], ans2=c[0];
        i=1;
        while(i<n-1) {
            if(i==n-3) ans1+=c[i], i+=2;
            else if(i==n-2||b[i]<c[i]) ans1+=b[i], i+=1;
            else ans1+=c[i], i+=2;
        }
        i=2;
        while(i<n-1) {
            if(i==n-3) ans1+=c[i], i+=2;
            else if(i==n-2||b[i]<c[i]) ans2+=b[i], i+=1;
            else ans2+=c[i], i+=2;
        }
        pr(min(ans1,ans2));
        nl;
    }
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define endl '\n'
#define inf 0x3f3f3f3f+1

ll n, w;
//c[i] -> weight of i-th item
//v[i] -> val of i-th item
ll c[102], v[102];
ll dp[103][100005];

//dp[a][b] -> minimum weight to achieve val=b, using itens 1 to a

ll peso(int i, int val){
  //no item is required to achieve val<=0, so minimum weight is 0
  if(val<=0) return 0;
  //with zero itens,  it is impossible to achieve any val, so minimum weight is inf
  if(i==0) return inf;
  //dp memo
  if(dp[i][val]!=-1) return dp[i][val];
  //choose whether to pick an item or not
  return dp[i][val]=min(peso(i-1, val), peso(i-1, val-v[i]) + c[i]);
}

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

  cin >> n >> w;
  for(int i=1; i<=n; i++) cin >> c[i] >> v[i];

  for(int i=1; i<=n; i++){
    for(int j=1; j<=100000; j++){
      dp[i][j]=-1;
    }
  }

  //find max val whose minimum weight required is less than or equal to capacity
  for(int val=100000; val>=0; val--) {
    if(peso(n, val)<=w){
      cout << val << endl;
      break;
    }
  }

/*
  for(int i=1; i<=n; i++){
    for(int j=1; j<=17; j++){
      if(dp[i][j]==inf) cout << "inf" << "\t";
      else cout <<  dp[i][j] << "\t";
    }
    cout << endl;
  }
  */
}


#include<stdio.h>
#include<unordered_map>
#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	int a[n];
	for(int i=0; i<n; i++) cin>>a[i];
	int dp[n];
	dp[0]=0;
	dp[1]=fabs(a[1]-a[0]);
	for(int i=2; i<n; i++)
	{
		dp[i]=min( dp[i-1]+fabs(a[i]-a[i-1]), dp[i-2]+fabs(a[i]-a[i-2])    );
	}
	cout<<dp[n-1]<<endl;
}


#include <bits/stdc++.h>
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"

const int INF=1e5+5;

int32_t main()
{
	IOS;
    int n;
    scanf("%d", &n);
    vector<int> h(n);
    for(int& x : h) {
        scanf("%d", &x);
    }
    vector<int> dp(n, INF);
    dp[0] = 0;
    for(int i = 0; i < n; ++i) {
        for(int j : {i + 1, i + 2}) {
            if(j < n) {
                dp[j] = min(dp[j], dp[i] + abs(h[i] - h[j]));
            }
        }
    }

    printf("%d\n", dp[n-1]);

	return 0;
}


#include<iostream>
#include<algorithm>
#include<string.h>
#include<set>
#include<climits>
using namespace std;
int n;
long long res[100005 ];
long long arr[100005 ];

long long dfs(long long  p, long long m) {
	if (p >= n)
		return LONG_MAX;
	if (p == n - 1)
		return m;
	return res[p] = min(dfs(p + 1, m+abs(arr[p]-arr[p+1]) ), dfs(p + 2, m+abs(arr[p]-arr[p+2])));
}

int main() {
	cin >> n;
	memset(res, -1,n+1);

	for (int i = 0; i < n; i++)
		cin >> arr[i];
	cout << dfs(0,0);

    return 0;
}


// dp_a.cc
#include <bits/stdc++.h>
using namespace std;

const int INF = 1e9 + 5;

int main() {
	int n;
	scanf("%d", &n);

	vector<int> h(n);
	for (int& x : h)
		scanf("%d", &x);

	vector<int> dp(n, INF);
	dp[0] = 0;

	for (int i = 0; i < n; i++) {
		for (int j : {i + 1, i + 2}) {
			if (j < n) {
				dp[j] = min(dp[j], dp[i] + abs(h[i] - h[j]));
			}
		}
	}
	printf("%d\n", dp.back());
}


#include <iostream>
#include <cmath>

using namespace std;

int main() {
	int *arr, n, result = 0;
	cin >> n;
	arr = new int[n];

	for ( int i=0; i<n; i++ )
		cin >> arr[i];
	for ( int i=n-1; i>0; i-- ) {
		int c1, c2;
		c1 = abs ( arr[i] - arr[i-1] );
		c2 = abs ( arr[i] - arr[i-2] );

		if ( c1 < c2 ) {
			result = result + c1;
		}
		else if ( c1 >= c2 ) {
			result = result + c2;
			i--;
		}
	}

	cout << result << endl;

	return 0;
}


#include<iostream>
#include<vector>

using namespace std;
int dp[100050]={};
int num(int a){
    if(a<0)return -a;
    else return a;
}
int min1(int a,int b){
    if(a<b)return a;
    else return b;
}
int main(){
    int n;
    cin>>n;
    vector<int> h(n+5);
    for(int i=1;i<=n;i++){
        cin>>h[i];
    }
    dp[1]=0;
    dp[2]=num(h[1]-h[0]);
    for(int i=3;i<=n;i++){
        dp[i]=min1(dp[i-1]+num(h[i]-h[i-1]),dp[i-2]+num(h[i]-h[i-2]));
    }
    cout<<dp[n]<<endl;
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define gg(x) getInt(&x)
using namespace std;
typedef long long ll;
inline void getInt(int* p);
const int maxn=1000010;
const int inf=0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
ll n;
ll dp[maxn];
ll a[maxn];
int main()
{
    gbtb;
    cin>>n;
    repd(i,1,n)
    {
        cin>>a[i];
    }
    dp[1]=0;
    dp[0]=0;
    dp[2]=abs(a[2]-a[1]);
    repd(i,3,n)
    {
        dp[i]=min(dp[i-2]+abs(a[i]-a[i-2]),dp[i-1]+abs(a[i]-a[i-1]));

    }
    cout<<dp[n];
    return 0;
}

inline void getInt(int* p) {
    char ch;
    do {
        ch = getchar();
    } while (ch == ' ' || ch == '\n');
    if (ch == '-') {
        *p = -(getchar() - '0');
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 - ch + '0';
        }
    }
    else {
        *p = ch - '0';
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 + ch - '0';
        }
    }
}


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

#ifdef RED
  mt19937 rnd(228);
#else
  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

const int N = (int)1e6 + 5;
const int inf = (int)1e9 + 7;

int n;
int a[N];
int dp[N];

int main() {
#ifdef RED
  freopen("a.in", "r", stdin);
#endif
  ios_base :: sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
    dp[i] = inf;
  }
  dp[1] = 0;
  dp[2] = abs(a[2] - a[1]);
  for (int i = 3; i <= n; ++i) {
    dp[i] = min(dp[i - 1] + abs(a[i] - a[i - 1]), dp[i - 2] + abs(a[i] - a[i - 2]));
  }
  cout << dp[n] << "\n";
  return 0;
}


/* _  */

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <functional>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <sstream> //stringstream
#include <cstring> // getline
#include <cmath>
#include <unordered_set>
#include <limits>
#include <unordered_map>

#define go(i,init ,n) for(int  i=init ;i<n ;i++)
#define X first
#define Y second
#define ll long long
#define ALL arr.begin() ,arr.end()
#define IO ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define FI freopen("input.txt", "r", stdin);
#define FO freopen("output.txt", "w", stdout);
#define OO 1000000000000
#define oo 1e9
#define N 200100

using namespace std;

ll int MOD = 1e9 + 7;
ll int memo[100005];
ll int prime[1000000];
ll int fac[N], ifac[N];
ll int inv[N];
vector<ll int>primes;

ll int gcd(ll int a, ll int b){ if (b == 0) return a; return gcd(b, a%b); }
bool IsPrime(ll int x){ if (x == 1) return false; for (ll int i = 2; i*i <= x; i++){ if (x%i == 0) return false; } return true; }
void seive(ll int n){ prime[0] = prime[1] = 1; for (ll int i = 2; i*i <= n; i++) if (!prime[i]){ for (ll int j = i*i; j <= n; j += i) prime[j] = 1;} }
bool sortMa7boub(const pair<int, int> &a, const pair<int, int> &b) { if (a.first == b.first) return (a.second < b.second); return(a.first >b.first); }
bool IsVowel(char c){ return(c == 'a' || c == 'e' || c == 'i' || c == 'u' || c == 'o'||c=='y' || c == 'A' || c == 'E' || c == 'I' || c == 'U' || c == 'O'||c=='Y'); }
bool IsEqual(string s1, string s2){ if (s1.length() != s2.length())return 0; go(i, 0, s1.length()) if (s1[i] != s2[i])return 0; return 1; }
ll int  powMod(ll int  base, ll int  pw) { ll int ret = 1; while (pw) { if (pw & 1) ret = (ret * base) % MOD; base = (base * base) % MOD; pw >>= 1; }return ret; }

/*should use makeFact before useing C or P */
void makeFact(){ fac[0] = ifac[0] = 1; for (ll int i = 1; i<N; i++) { fac[i] = (fac[i - 1] * i) % MOD; ifac[i] = powMod (fac[i], MOD - 2); } }
inline void Init(){ inv[1] = 1; for (int i = 2; i < N; ++i) inv[i] = inv[MOD % i] * (MOD - MOD / i) % MOD;}
ll int  C(ll int  a, ll int  b) { if (a < b) return 0; return (((fac[a] * ifac[b]) % MOD) * ifac[a - b]) % MOD; }
ll int P(ll int a, ll int b){ if (a < b) return 0; return(fac[a] * ifac[a - b]) % MOD; }

int a = -1;

string AL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
vector<ll int>vec; ll int n, m;

bool isValid(int i) { return i >= 0 && i < n; }

ll int mini(int indx )
{

	ll int &ret = memo[indx];

	if (indx == n-1)
		return 0;

	if (~ret)
		return ret;

	ll int a = OO, b = OO;

		a = mini(indx + 1) + abs(vec[indx] - vec[indx + 1]);

	if (isValid(indx+2))
		b = mini(indx + 2) + abs(vec[indx] - vec[indx + 2]);

	return ret =  min(a, b);
}

int main()
{
	IO;
	/*freopen("txt.in", "r", stdin);
	freopen("txt.out","w",stdout);*/

	cin >> n;
	vec.resize(n);
	go(i, 0, n)
		cin >> vec[i];

	memset(memo, -1, sizeof memo);
	ll int ans = mini(0);

	cout << ans << endl;
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>

using namespace std;

vector<pair<int, int> > lista;
int dp[105][100005];
int n, c;

int transforma(int a, int b){
    double v = a / (double)b;
    int r = (v * 100000);

    return r;
}

int solve(int pos, int total){
    if(total > 100000) return -1e7;
    if(pos >= lista.size()) return 0;
    int &d = dp[pos][total];
    if(d != -1) return d;
    int res = max(solve(pos + 1, total), solve(pos + 1, total + lista[pos].second) + lista[pos].first);

    return d = res;
}

int main(){
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    cin >> n >> c;
    for(int i = 0; i < n; i++){
        int w, v; cin >> w >> v;
        if(w > c) continue;
        lista.push_back({v, transforma(w, c)});
        // cout << lista[i].first << " " << lista[i].second << endl;
    }
    memset(dp, -1, sizeof dp);
    cout << solve(0, 0) << endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
  int n;
  cin>>n;
  int x[n];
  int dp[n];
  for(int i=0;i<n;i++)
  dp[i]=1000000;
  for(int i=0;i<n;i++)
    cin>>x[i];
  dp[0]=0;
  for(int i=0;i<n;i++)
  {
    if(i+1<n)
      dp[i+1]=min(dp[i+1],dp[i]+abs(x[i]-x[i+1]));
    if(i+2<n)
      dp[i+2]=min(dp[i+2],dp[i]+abs(x[i]-x[i+2]));
  }
  cout<<dp[n-1];
}


#include <iostream>
using namespace std;

int abs(int a,int b){
	if (a>b) return a-b;
	return b-a;
}

int min(int a,int b){
	if (a>b) return b;
	return a;
}

int main(){
	int n,i;
	cin>>n;
	int h[n],dp[n];
	for(i=0;i<n;i++)cin>>h[i];
	dp[0]=0;
	dp[1]=abs(h[0],h[1]);
	dp[2]=abs(h[0],h[2]);
	for(i=3;i<n;i++){
		dp[i]=min(dp[i-1]+abs(h[i],h[i-1]),dp[i-2]+abs(h[i],h[i-2]));
		//cout<<"ok"<<endl;
	}
	cout<<dp[n-1]<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
  int N;
  cin >> N;
  vector<int> h(N);
  for(int i = 0; i < N; i++) cin >> h[i];
  vector<int> DP(N, 0);
  DP[1] = abs(h[1] - h[0]);
  int cost1, cost2;
  for(int i = 2; i < N; i++) {
    cost1 = abs(h[i] - h[i - 1]);
    cost2 = abs(h[i] - h[i - 2]);
    if(DP[i - 1] + cost1 <= DP[i - 2] + cost2) DP[i] = DP[i - 1] + cost1;
    else DP[i] = DP[i - 2] + cost2;
  }
  cout << DP[N - 1] << endl;
}


#include <bits/stdc++.h>

typedef long long ll;

using namespace std;

#define swap(a, b)    do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while(0)
#define repd(i, a, b) for(typeof(b) i = a; i < (b); ++i)
#define rep(i, n)     repd(i, 0, n)
#define dump(x)       cerr << #x << " = " << (x) << endl
#define debug(x)      cerr << "L" << __LINE__ << ": " << #x << " = " << (x) << endl
#define YesNo(x)      cout << ((x) ? "Yes" : "No") << endl
#define YESNO(x)      cout << ((x) ? "YES" : "NO") << endl
#define absi(x)       ( ((x) >= 0) ? (x) : (-(x)) )

int main(int argc, const char* argv[]) {
	ll n;
	cin >> n;
	vector<ll> h(n);
	rep(i, n) cin >> h[i];

	vector<ll> dp(n);
	dp[0] = 0;
	dp[1] = absi(h[0] - h[1]);

	repd(i, 2, n) {
		dp[i] = min(dp[i-2] + absi(h[i] - h[i-2]), dp[i-1] + absi(h[i] - h[i-1]));
	}

	cout << dp.back() << endl;

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

struct state {
    int idx;
    int64_t cost;
};

int main(int argc, char *argv[]) {
    int N;
    cin >> N;

    vector<int> arr;
    int cur;
    for (int i = 0; i < N; i++) {
        cin >> cur;
        arr.push_back(cur);
    }

    stack<state> st;
    state root = {0};
    st.push(root);

    vector<int64_t> dp(N, INT64_MAX);
    int64_t ans = INT_MAX;

    while (!st.empty()) {
        state cur_state = st.top();
        st.pop();

        if (cur_state.cost > 0 && cur_state.idx < N) {  // メモ化
            dp[cur_state.idx] = min(cur_state.cost, dp[cur_state.idx]);
        }

        if (cur_state.idx == N - 1 && cur_state.cost <= ans) {
            ans = cur_state.cost;
        }

        //  i + [12] へジャンプ
        for (int j = 1; j <= 2; j++) {
            int cur_idx = cur_state.idx;
            int next_idx = cur_state.idx + j;

            //  但し、ジャンプ先がゴールなら、ジャンプしない
            if (next_idx >= N) {
                next_idx = N - 1;
            }

            if (cur_idx != N - 1) {
                state newstate = cur_state;
                newstate.idx = next_idx;
                newstate.cost += abs(arr[cur_idx] - arr[next_idx]);
                st.push(newstate);
            }
        }
    }

    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ll n,i;
    cin >> n;
    ll a[n],dp[n];
    for(i=0;i<n;i++)
    cin >> a[i];
    dp[0]=0;
    dp[1]=abs(a[1]-a[0]);
    for(i=2;i<n;i++)
    dp[i]=min(dp[i-1]+abs(a[i]-a[i-1]),dp[i-2]+abs(a[i]-a[i-2]));
    cout << dp[n-1] << endl;
    return 0;
}


//in progress
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define fr(i,a,b) for(int i = (int)(a); i <= (int)(b); i++)
#define forn(i,n) for(int i =0; i < (int)(n); i++)
#define rfr(i,a,b) for(int i = (int)(a); i >= (int)(b); i--)
#define PI 3.14159265
int n,a[100010];
int recur(int ind)
{
  if(ind>=n-1)
  return 0;
  else if(ind==n-2)
  return abs(a[n-1]-a[n-2]);
  return min(recur(ind+1)+abs(a[ind+1]-a[ind]),recur(ind+2)+abs(a[ind+2]-a[ind]));
}
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  //freopen("a.in", "r", stdin);
  //freopen("a.out", "w", stdout);
  cin>>n;
  for(int i=0;i<n;i++)
  cin>>a[i];
  cout<<recur(0)<<"\n";
  return 0;
}


#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<vector>
#include<cstdio>
#include<cmath>
#include<map>
#include<set>
using namespace std;
int n,a[100005],dp[100005];
int main()
{
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	    scanf("%d",&a[i]);
	if(n==1)
	{
		cout<<0;
		return 0;
	}
	dp[0]=0,dp[1]=abs(a[0]-a[1]);
	for(int i=2;i<n;i++)
	    dp[i]=min(dp[i-1]+abs(a[i]-a[i-1]),dp[i-2]+abs(a[i]-a[i-2]));
	cout<<dp[n-1];
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

vector<long long>v;
long long mn = 10000000007;

void dp (long long stop, long long sum)
{
    if(stop<0) return;
    if(stop==0) {mn = min(mn,sum); return;}
    dp(stop-1,sum+abs(v[stop]-v[stop-1]));
    dp(stop-2,sum+abs(v[stop]-v[stop-2]));
}

int main ()
{
    long long x,n;
    cin>>n;

    while(n--) cin>>x,v.push_back(x);
    dp(v.size()-1,0);
    cout<<mn;

}


#include <bits/stdc++.h>
using namespace std;

int main(){
  int N;
  cin >>N;
  int h[N];
  for(int i=0;i<N;i++){
    cin >> h[i];
  }
  int a[N+1];
  a[0] = 0;
  a[1] = 20000;
  for(int i=0;i<N-1;i++){
    a[i+1] = min(a[i+1],a[i]+abs(h[i+1]-h[i]));
    a[i+2] = a[i] + abs(h[i+2]-h[i]);
  }
  cout << a[N-1] << endl;
}


#include <bits/stdc++.h>

#define REP(i ,n) for(int i=0 ;i < n; i++)
#define REPB(i ,n) for(int i=n; i >= 0; i--)
#define FOR(i ,m ,n) for(int i=m; i < n; i++)
#define FORB(i, m, n) for(int i=m; i>= m; i--)
#define ll long long
#define pb push_back
#define popb pop_back
using namespace std;
const int MAX_N = 10000;
const int MAX_H = 10000;
const int INF = 1000000;

int n;
long h[MAX_H + 2];
long dp[MAX_N + 3];

long dprec(int i){
  long res;
  if(dp[i] != -1){
      return dp[i];
      }
      if(i < 2){
        res = 0;
      }else{
        res = min(
        dprec(i - 1) + abs(h[i] - h[i - 1]),
        dprec(i - 2) + abs(h[i] - h[i - 2])
        );
        }
      return dp[i] = res;
  }
void solve(){
    memset(dp, -1, sizeof(dp));
    cout << dprec(n+1) << endl;
  }

int main(){
  cin >> n;
  REP(c, n){
      cin >> h[c + 2];
    }
    REP(p, 2) h[p] = h[2];
    solve();
//REP(a, (n+2)) cout << dp[a] << " ";
}


#include <bits/stdc++.h>
#include<string>
using namespace std;

typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<string>vst;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<pii> vii;
typedef vector<pll> vll;

#define fastio ios_base::sync_with_stdio(false);cin.tie(0)
#define all(ct) ct.begin() , ct.end()
#define endl "\n"
#define fr(i,a) for(auto i:a)
#define f(i,a,b) for(int i=a;i<b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define pb push_back
#define in(d,v) d.find(v)!=d.end()
#define mp make_pair
#define size1(a) int(a.size())
#define FOR(n) for(int i= 0;i<n;i++)
#define FORR(n) for(ll i= 0;i<n;i++)

// adjacency list graph input

// vector<vector<int> > adj(n, vector<int>());
// for (size_t i = 0; i < m; i++) {
// 	int x, y;
// 	cin >> x >> y;
// 	adj[x - 1].push_back(y - 1);

//}

int main() {
	fastio;

	int  n , k;
	cin >> n >> k;

	vi h(n , 0 );
	for (int i = 0 ; i < n ; i++) {
		cin >> h[i];
	}
	vi dp ( n , INT_MAX);
	dp[0] = 0  ;
	for (int i = 1 ; i < n ; i ++) {

		for (int j =  1; j <= k  ; j++ ) {
			if ((i - j) < 0 ) break ;
			dp[i] = min ( dp[i] , dp[i - j] + abs(h[i] - h [i - j]));

		}

	}
	cout << dp[n - 1];
	return 0;

}

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 100

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

5 3
10 30 40 50 20

Sample Output 1

30

If we follow the path 1 → 2 → 5, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

3 1
10 20 10

Sample Output 2

20

If we follow the path 1 → 2 → 3, the total cost incurred would be |10 - 20| + |20 - 10| = 20.

Sample Input 3

2 100
10 10

Sample Output 3

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 4

10 4
40 10 20 70 80 10 20 70 80 60

Sample Output 4

40

If we follow the path 1 → 4 → 8 → 10, the total cost incurred would be |40 - 70| + |70 - 70| + |70 - 60| = 40.


#include<bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
#define all(x) (x).begin(), (x).end()
#define endl "\n"
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define ar array
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
const ll mod = 1e9 + 7;
const ll inf = 2e9 + 5;
double PI = 3.14159265358979323846;

const int N = 1e5 + 5;
vi dp(N, inf);

void solve() {

    int n;
    cin >> n;
    int k;
    cin >> k;
    int h[n + 1];
    for (int i = 1; i <= n; i++) {
        cin >> h[i];
    }

    dp[1] = 0;

    for (int i = 2; i <= n; i++) {
        for (int j = 1; j <= k and i - j; j++) {
            dp[i] = min(dp[i], dp[i - j] + (abs(h[i] - h[i - j])));
        }
    }
    cout << dp[n] << endl;

}

int32_t main()
{
    IOS
    // int T; cin >> T; while (T--)
    solve();
    return 0;
}


#include <iostream>
using namespace std;

int frog2(int n, int k, int* h){
    int dp[n] = {};
    dp[1] = abs(h[1]-h[0]);

    for(int i = 2; i < n; i++){
        int mi = 100000;
        int val;
        for(int j = i-1; j >= i-k && j >= 0; j--){

            val = min(mi, dp[j]+abs(h[i]-h[j]));
            mi = val;

        }
        dp[i] = val;
    }
    return dp[n-1];
}

int main() {
	int n,k; cin >> n >> k;
	int h[n] = {};
	for(int i = 0; i<n; i++) cin >> h[i];
 	cout << frog2(n,k,h);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int dp[100'000+5];      /// dp[i] = min cost to get from 0 to i

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

    int n, k;
    cin>>n;
    vector<int> input(n);
    for(int i = 0; i<n; i++)
        cin>>input[i];

    dp[0] = 0;
    for(int i = 1; i<n; i++){
        dp[i] = 2'000'000'000;
        for(int j = 1; j<=k; j++){
            if(i-j >= 0)
                dp[i] = min(dp[i], dp[i-k] + abs(input[i] - input[k]) );
        }
    }

    cout<<dp[n-1]<<endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

using ll = long long;

int main(){

    ll n, k; cin >> n >> k;
    ll arr[n];
    ll dp[n + 25] = {0};
    for(ll i = 0; i < n; ++i){
        cin >> arr[i];
    }
    for(ll i = k + 1; i < n; ++i){
        dp[i] = 2e9;
    }
    for(ll i = 1; i <= k; ++i){
        dp[i] = abs(arr[i] - arr[0]);
    }
    for(ll i = k; i < n; ++i){
        for(ll j = i - k; j < i; ++j){
            dp[i] = min(dp[j] + abs(arr[j] - arr[i]), dp[i]);
        }
    }
    cout << dp[n - 1];
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

int main() {
	int n;
	cin>>n;
	vector<int> h(n+1);
	for(int i=1; i<=n; i++) cin>>h[i];

	vector<int> dp(n+1, 0);
	dp[1] = 0;
	dp[2] = dp[0] + abs(h[1] - h[2]);
	for(int i=3; i<=n; i++) {
		dp[i] = min(dp[i-1] + abs(h[i] - h[i-1]), dp[i-2] + abs(h[i] - h[i-2]));
	}
	cout<<dp[n];
	return 0;

}


#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
const int N=1e9+7;
#define infi 1e18
int32_t main()
{
	IOS;
    int n,k;
    cin>>n>>k;
    int h[n+1];
    int dp[n+1];
    for(int i=1;i<=n;i++)
    {
        cin>>h[i];
        dp[i]=infi;
    }
    dp[1]=0;
    for(int i=2;i<=n;i++)
    {
      for(int j=max((int)1,i-k);j<i;j++)
      {
          dp[i] = min(dp[i],abs(h[i]-h[j])+dp[j]);
      }
    }
    cout<<dp[n];
}


#include<bits/stdc++.h>
using namespace std;
//int mincoins(int ar[],int n,int k,int dp[]){
//	for(int i=1;i<=k;i++){
//		 dp[i] = INT_MAX;
//			for(int op=0;op<n;op++){
//				if(i-ar[op]>=0)
//				dp[i]= min(dp[i-ar[op]]+1,dp[i]);
//
//			}
//
//	}
//		if(dp[k]==INT_MAX){
//		return -1;
//	}
//return dp[k];
//}
int mincost(int ar[],int n,int k){
	int dp[n+1]={0};
	if(n==0){
		return 0;
	}
	if(n==1){
		dp[1]=0;
	}

	for(int i=2;i<=n;i++){

		dp[i]=INT_MAX;

		if(i-1>=1)
		dp[i] = min(dp[i-1]+abs(ar[i]-ar[i-1]),dp[i]);

		}

return dp[n];
}
int main(){
	int n,p,k;
	cin>>n>>p>>k;
	int ar[n];
	for(int i=1;i<=n;i++){
		cin>>ar[i];
	}
	int maxdif=0;
	for(int i=1;i<n;i++){
		if(ar[i+1]-ar[i]>maxdif){
			maxdif = ar[i+1]-ar[i];
		}
	}
	cout<<maxdif<<endl;
	cout<<mincost(ar,n,k)<<endl;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;
typedef pair<ll, ll> pll;

#define FOR(i, n, m) for(ll (i)=(m);(i)<(n);++(i))
#define REP(i, n) FOR(i,n,0)
#define OF64 std::setprecision(10)

const ll MOD = 1000000007;
const ll INF = (ll) 1e15;

ll H[100005];
ll dp[100005];

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    ll N, K;
    cin >> N >> K;
    REP(i, N) {
        cin >> H[i];
    }
    REP(i, N) {
        dp[i] = INF;
    }
    dp[0] = 0;
    REP(i, N) {
        REP(j, K) {
            ll nxt = i + j + 1;
            if (nxt >= N)
                break;
            dp[nxt] = std::min(dp[nxt], dp[i] + abs(H[nxt] - H[i]));
        }
    }
    cout << dp[N - 1] << endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
const long long inf=1e9;
#define int long long
int32_t main()
{
	int n,k;
  cin>>n>>k;
  int arr[n+1];
  for(int i=1;i<=n;i++)cin>>arr[i];

  int dp[n+1];
 // memset(dp,inf,sizeof(dp));
  dp[1]=0;
  for(int i=2;i<=n;i++){
      dp[i]=inf;
    for(int j=i-1;j>0 && (i-j)<=k;j--){
      	int ans=abs(arr[i]-arr[j])+dp[j];
      	dp[i]=min(dp[i],ans);
    }
  }
  cout<<dp[n];
  return 0;
}


#include <assert.h>
#include <bits/stdc++.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <bitset>
#include <fstream>
#include <unordered_map>
#include <iostream>
#include <list>
#include <set>
#include <stack>
#include <string>
#include <vector>

using namespace std;

typedef string str;
typedef long long ll;
typedef long double ld;
typedef complex<ld> cd;
typedef long long ll;
typedef pair<int, int> pi;
typedef vector<int> vi;

#define mp make_pair
#define pb push_back
#define sz(x) (int)x.size()
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound
#define trav(a, x) for (auto &a : x)
#define F0R(i, a) for (int i = 0; i < (a); i++)
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define FORd(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define F0Rd(i, a) for (int i = (a)-1; i >= 0; i--)
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define PRINT_ARRAY(a, N)        \
  F0R(z, N) cout << a[z] << " "; \
  cout << "\n"

const int MOD = 1000000007;  // 998244353
const ll INF = 1e18;
const ld PI = 4 * atan((ld)1);

ll N, K, C[100005];
ll best[100005];
int main() {
		ios_base::sync_with_stdio(false);
		cin.tie(NULL);
		cout.tie(NULL);
		cin >> N >> K;
		F0R(i, N) cin >> C[i + 1];

		for (int i = 1; i <= N; i++) best[i] = INF;

		best[1] = 0;
		for (int i = 1; i <= N; i++) {
				for (int j = 1; j <= K; j++) best[i + j] = MIN(best[i + j], best[i] + abs(C[i + j] - C[i]));
		}
		cout << best[N] << endl;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

#define FOR(a, b, i) for(int i=a; i<b; i++)
#define RFOR(a, b, i) for(int i=a; i>=b; i--)
#define PB push_back
#define MP make_pair
#define MOD 1e9+7
#define newline cout<<"\n"

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    int n, k; cin>>n>>k;
    vector<int> h(n);
    FOR(0, n, i) cin>>h[i];

    vector<int> dp(n, 1e4+5);
    dp[0] = 0;

    FOR(0, n-1, i)
    {
        FOR(i+1, min(i+k+1, n), j)
        {
            dp[j] = min(dp[j], dp[i]+abs(h[i]-h[j]));
        }
    }
    cout<<dp[n-1];
    newline;

    return 0;
}


//       Author: Mostafa Mounir Shehab

#include <bits/stdc++.h>
using namespace std;

#define PI  3.14159265  // PI = acos(-1)
#define EPS (1e-10)
#define endl "\n"
#define SZ(v) (int)(v.size())
typedef long long ll;
typedef long double ld;
//template <class Type>

void Fast(){
	std::ios_base::sync_with_stdio(0);
	cin.tie(NULL); cout.tie(NULL); cerr.tie(NULL);
}

inline int D(){
	int t;
	scanf("%d",&t);
	return t;
}
inline ll llD(){
	ll t;
	scanf("%lld",&t);
	return t;
}

ll MOD=1e9 + 7;
const int N=1e6 + 5;
ll arr[N];
ll dp[N];
ll OO=1e12;

ll n,m,k,cnt,SU,idx,len,MN,MX;
ll l,r,mid;
ll a,b,c,d,s;

ll Solve(int idx){

	ll &ret=dp[idx];
	if(~ret)
		return ret;

	if(idx >= n)
		return ret = 0;

	ret=OO;
	for(int i=1;i<=k;++i)
		ret = min(ret , abs(arr[idx] - arr[idx+i]) + Solve(idx+i));

	return ret;
}

int main(){
	cin>>n>>k;
	for(int i=1;i<=n;++i)
		cin>>arr[i];

	memset(dp,-1,sizeof dp);

	cout<<Solve(1)<<endl;

}


#include <bits/stdc++.h>
using namespace std;

int main() {
  int N,K;
  cin>>N>>K;
  vector<int> h(N);
  for(int i=0;i<N;i++) cin>>h[i];
  if(K>=N){
    cout<<abs(h[N-1]-h[0])<<endl;
    return 0;
  }
  vector<long> c(N);

  for(int i=1;i<N;i++){
    int m=1234567890;
    int idx=-1;
    for(int j=max(0,i-K);j<i;j++){
      int cost=abs(h[i]-h[j]);
      if(cost<m){
        m=cost;
        idx=j;

      }
    }
    c[i]=c[idx]+m;
  }

  //for(int i=0;i<N;i++) cout<<c[i]<<endl;
  cout<<c[N-1]<<endl;

  }


#include <bits/stdc++.h>
using namespace std;

int main() {
  int n,k;

  cin >> n >> k;

  vector<int> h(n,0);
  vector<int> dp(n,1e5);

  for(int i=0;i<n;i++) {
    cin >> h[i];
  }

  dp[0] = 0;

  for(int i=0;i<n;i++) {
    for(int j=0;j<k+1;j++) {
      if(i+j<=n) {
        dp[i+j] = min(dp[i+j], dp[i] + abs(h[i] - h[i+j]));
        //        cout << dp[i] << endl;
      }
      else continue;
    }
  }

  // for(int i=0;i<n;i++) {
  //   cout << dp[i] << endl;
  // }

  cout << dp[n-1] << endl;

  return 0;
}


#include "bits/stdc++.h"
#pragma GCC optimize("Ofast")

// Begin Header {{{
using namespace std;

#ifndef DEBUG
#define dump(...)
#endif

#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define rep(i, n) for (intmax_t i = 0, i##_limit = (n); i < i##_limit; ++i)
#define reps(i, b, e) for (intmax_t i = (b), i##_limit = (e); i <= i##_limit; ++i)
#define repr(i, b, e) for (intmax_t i = (b), i##_limit = (e); i >= i##_limit; --i)
#define var(Type, ...) Type __VA_ARGS__; input(__VA_ARGS__)

constexpr size_t operator""_zu(unsigned long long value) { return value; };
constexpr intmax_t operator""_jd(unsigned long long value) { return value; };
constexpr uintmax_t operator""_ju(unsigned long long value) { return value; };

constexpr int INF = 0x3f3f3f3f;
constexpr intmax_t LINF = 0x3f3f3f3f3f3f3f3f_jd;

namespace moke {

    template <class T> using MaxHeap = priority_queue<T, vector<T>, less<T>>;
    template <class T> using MinHeap = priority_queue<T, vector<T>, greater<T>>;

    inline void input() {}
    template <class Head, class... Tail> inline void input(Head&& head, Tail&&... tail) {
        cin >> head;
        input(forward<Tail>(tail)...);
    }

    template <class T> inline void input(vector<T> &vec) {
        for (auto &e: vec) {
            cin >> e;
        }
    }

    template <class T> inline void input(vector<vector<T>> &mat) {
        for (auto &vec: mat) {
            input(vec);
        }
    }

    inline void print() { cout << "\n"; }
    template <class Head, class... Tail> inline void print(Head&& head, Tail&&... tail) {
        static constexpr const char *delim[] = {"", " "};
        cout << head << delim[sizeof...(tail)];
        print(forward<Tail>(tail)...);
    }

    template <class T> inline ostream& operator<<(ostream &strm, const vector<T> &vec) {
        static constexpr const char *delim[] = {" ", ""};
        for (const auto &e: vec) {
            strm << e << delim[&e == &vec.back()];
        }
        return strm;
    }

    template <class T> inline vector<T> make_v(const T &initValue, size_t sz) {
        return vector<T>(sz, initValue);
    }

    template <class T, class... Args> inline auto make_v(const T &initValue, size_t sz, Args... args) {
        return vector<decltype(make_v<T>(initValue, args...))>(sz, make_v<T>(initValue, args...));
    }

    template <class A, class B> inline bool chmax(A &a, const B &b) noexcept {
        return b > a && (a = b, true);
    }

    template <class A, class B> inline bool chmin(A &a, const B &b) noexcept {
        return b < a && (a = b, true);
    }

    template <class A, class B> inline common_type_t<A, B> min(const A &a, const B &b) noexcept {
        return a < b ? a : b;
    }

    template <class A, class B, class... Args> inline common_type_t<A, B, Args...> min(const A &a, const B &b, const Args&... args) noexcept {
        return moke::min(a < b ? a : b, args...);
    }

    template <class A, class B> inline common_type_t<A, B> max(const A &a, const B &b) noexcept {
        return a > b ? a : b;
    }

    template <class A, class B, class... Args> inline common_type_t<A, B, Args...> max(const A &a, const B &b, const Args&... args) noexcept {
        return moke::max(a > b ? a : b, args...);
    }

    template <class A, class B> inline common_type_t<A, B> diff(const A &a, const B &b) noexcept {
        return a < b ? b - a : a - b;
    }

} // namespace moke

// }}} End Header

namespace moke {

    size_t N, K;
    vector<intmax_t> h;

    vector<intmax_t> dp;

    intmax_t rec(int idx) {
        if (idx == 0) return 0;

        auto& ret = dp[idx];
        if (~ret) return ret;

        ret = LINF;
        reps(i, 1, K) {
            if (idx - i >= 0) {
                chmin(ret, rec(idx - i) + diff(h[idx], h[idx - i]));
            }
        }

        return ret;
    }

    int main_() {
        ios_base::sync_with_stdio(false);
        cin.tie(nullptr);

        input(N, K);

        h.resize(N);
        input(h);

        dp.resize(N, -1);

        print(rec(N - 1));

        return 0;
    }

} // namespace moke

signed main() { // {{{
    moke::main_();
    return 0;
} // }}}


#include <iostream>
#include <climits>
#define ll long long int
#define endl "\n"

using namespace std;

int main(){
    int N, K;
    cin>>N>>K;
    int arr[N+1];
    for(int i = 1;i<N+1;i++)
        cin>>arr[i];
    int dp[N+1];
    dp[0] = 0;
    dp[1] = 0;
    for(int i = 2;i<N+1;i++){
        int miner = INT_MAX;
        for(int j = 1;j<=K;j++){
            if(i-j>=1)
                miner = min(miner, dp[i-j]+abs(arr[i-j]-arr[i]));
            else
                break;
        }
        dp[i] = miner;
    }
    cout<<dp[N]<<endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

const long long INF = 1LL << 60;

int main() {
  int n, k;
  cin >> n >> k;
  long long h[100010];

  for (int i = 0; i < n; i++) cin >> h[i];

  long long dp[100010];
  for (int i = 0; i < 100010; i++) dp[i] = INF;
  dp[0] = 0;

  for (int i = 0; i < n; i++)
    for (int j = 1; j <= k; j++) {
      chmin(dp[i+j], dp[i] + abs(h[i] - h[i+j]));
    }
  cout << dp[n-1] << endl;
}


#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;
int h[100005];
int d[100005];
int dp(int i, int n, int k);

int main()
{
  memset(d,-1,sizeof d);
  int n, k;
  cin >> n >> k;
  for(int i = 1; i <= n; i++) cin >> h[i];
  cout << dp(1, n, k) << endl;
}

int dp(int i, int n, int k)
{
  //cout << i << endl;
  if(i == n) return 0;
  if(d[i] != -1) return d[i];
  d[i] = INFINITY;
  for(int x = 1; x <= k; x++)
  {
    if(i + x > n) continue;
    d[i] = min(d[i], dp(i + x, n, k) + abs(h[i + x] - h[i]));
  }
  return d[i];
}


#include<bits/stdc++.h>
using namespace std;
#define INF 1<<30
#define MAX 100005
#define FASTIO ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);

typedef long long ll;

int main()
{
    FASTIO
   /*
   double start_time = clock();
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
  #endif
    */
    int n,k;
    cin >> n >> k;
    vector<int> H(n);
    for(int i = 0; i < n; i++) cin >> H[i];

      vector<int> ans(n, 100000);
    ans[0] = 0;
    for(int i = 0; i < n; i++){
      for(int j = 1; j <= k && (i+j) < n; j++){
      ans[i+j] = min(ans[i+j], ans[i] + abs(H[i+j] - H[i]));
    }
  }
    cout << ans[n-1]<<endl;

     //double end_time = clock();
  //printf( "Time = %lf ms\n", ( (end_time - start_time) / CLOCKS_PER_SEC)*1000);

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
    int n,k;
    cin>>n>>k;
    int arr[n];
    for(int i=0;i<n;i++)
        cin>>arr[i];
    int dp[n];
    dp[0] = 0;
    dp[1] = abs(arr[1]-arr[0]);
    for(int i=2;i<n;i++) {
        int mini = 10000000;
        for(int j=1;j<=k;j++) {
            int temp=10000000;
            if(i>=j)
                temp = dp[i-j]+abs(arr[i-j]-arr[i]);
            if(temp<mini)
                mini = temp;
        }
        dp[i] = mini;
    }
    cout<<dp[n-1];
    return 0;
}


#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cfloat>
#include <complex>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;

int main() {
  int N, K;
  cin >> N >> K;

  vector<ll> lst(N);
  for (int i = 0; i < N; i++) {
    cin >> lst[i];
  }

  vector<ll> dp(N, 0);

  for (int i = 1; i < N; i++) {
    ll m = LONG_LONG_MAX;
    for (int j = 1; j <= K; j++) {
      if (i >= j) {
        ll tmp = abs(lst[i] - lst[i - j]) + dp[i - j];
        m = min(tmp, m);
      }
    }
    dp[i] = m;
  }

  cout << dp[N-1] << endl;

  return 0;
}