akhauriyash/Code-Regression huggingface dataset:
h,w = map(int, input().split())

sy, sx = map(int, input().split())
sy -= 1
sx -= 1
gy, gx = map(int, input().split())
gy -= 1
gx -= 1

s = [[""] for _ in range(h)]
for i in range(h):
    s[i] = input()

from collections import deque
d = deque()

visited = [[False]*w for _ in range(h)]

d.append([sy,sx,0])

while len(d) > 0:
    y,x,c = d.popleft()
    
    if visited[y][x] is True:
        continue
    else:
        visited[y][x] = True
    
    if gy == y and gx == x:
        print(c)
        exit(0)

    dxy = [[1,0], [-1, 0], [0, 1], [0, -1]]
    for dx, dy in dxy:
        nx = dx + x
        ny = dy + y
        if nx < 0 or nx >= w or ny < 0 or ny >= h:
            continue
        if s[ny][nx] == "#":
            continue
        if visited[ny][nx] is True:
            continue
        d.appendleft([ny, nx, c])

    for dy in range(-2, 3):
        for dx in range(-2, 3):
            nx = dx + x
            ny = dy + y
            if nx < 0 or nx >= w or ny < 0 or ny >= h:
                continue
            if s[ny][nx] == "#":
                continue
            if visited[ny][nx] is True:
                continue
            d.append([ny, nx, c+1])

print(-1)


Measured memory_bytes: 233756
#include <bits/stdc++.h> 

using namespace std;
using ll=long long;
using ull=unsigned long long;
using pii=pair<int,int>;

#define INF LONG_MAX
#define MOD 1000000007
#define rng(a) a.begin(),a.end()
#define rrng(a) a.end(),a.begin()

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

  int sx,sy,tx,ty;
  cin>>sx>>sy>>tx>>ty;
  int x=abs(sx-tx);
  int y=abs(sy-ty);
  for(int i=0;i<y;i++)cout<<'U';
  for(int i=0;i<x;i++)cout<<'R';
  for(int i=0;i<y;i++)cout<<'D';
  for(int i=0;i<x;i++)cout<<'L';
  cout<<'L';
  for(int i=0;i<y;i++)cout<<'U';
  cout<<'U';
  for(int i=0;i<x;i++)cout<<'R';
  cout<<'R';
  cout<<'D';
  cout<<'R';
  for(int i=0;i<y;i++)cout<<'D';
  cout<<'D';
  for(int i=0;i<x;i++)cout<<'L';
  cout<<'L';
  cout<<'U'<<endl;
  return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstdio>
#include <cmath>
using namespace std;

int main()
{
	int n;
	while(cin >> n){
		int s;
		s = (n * n + n + 2) / 2;
		cout << s << endl;
	}	
}

Measured memory_bytes: 1160
use std::io;

fn read_line() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s
}

macro_rules! from_line {
    ($($a:ident : $t:ty),+) => {
        $(let $a: $t;)+
        {
            let _line = read_line();
            let mut _it = _line.trim().split_whitespace();
            $($a = _it.next().unwrap().parse().unwrap();)+
                assert!(_it.next().is_none());
        }
    };
}

fn main() {
    from_line!(n: i64, y: i64);

    let mut a: i64 = -1;
    let mut b: i64 = -1;
    let mut c: i64 = -1;

    for i in 0..n+1 {
        for j in 0..n+1-i {
            if i * 10 + j * 5 + n-i-j == y / 1000 {
                    a = i;
                    b = j;
                    c = n-i-j;
            }
        }
    }

    println!("{} {} {}", a, b, c);
}


Measured memory_bytes: 4352
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<ll, ll>;
using Pld = pair<ld, ld>;
using Vec = vector<ll>;
using VecP = vector<P>;
using VecB = vector<bool>;
using VecC = vector<char>;
using VecD = vector<ld>;
using VecS = vector<string>;
using Graph = vector<VecP>;
#define REP(i, m, n) for(ll (i) = (m); (i) < (n); ++(i))
#define REPR(i, m, n) for(ll (i) = (m); (i) > (n); --(i))
#define rep(i, n) REP(i, 0, n)
#define R cin>>
#define repr(i, n) REPR(i, n, 0)
#define all(s) (s).begin(), (s).end()
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
#define in(a) insert(a)
#define P(p) cout<<(p)<<endl;
#define ALL(x) (x).begin(),(x).end()
#define ALLR(x) (x).rbegin(),(x).rend()
#define SORT(a) sort((a).begin(), (a).end())
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<long long int> vll;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
typedef pair<ll, ll> pll;
void sonic(){ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);}
void setp(const ll n){cout << fixed << setprecision(n);}
const ll INF = 1e9+1;
const ll LINF = 1e18+1;
const ll MOD = 1e9+7;
//const ll MOD = 998244353;
const ld PI = acos(-1);
const ld EPS = 1e-11;
template<class T>bool chmax(T &a,const T &b){if(a<b){a=b;return true;}return false;}
template<class T>bool chmin(T &a,const T &b){if(a>b){a=b;return true;}return false;}
template<typename T> void co(T e){cout << e << "\n";}
template<typename T> void co(const vector<T>& v){for(const auto& e : v)
    { cout << e << " "; } cout << "\n";}
ll gcd(ll a, ll b) {
    if (a < b)swap(a, b);
    if (b == 0) return a;
    unsigned r;
    while ((r = a % b)) {
        a = b;
        b = r;
    }
    return b;
}
ll lcm(ll a, ll b) {
    ll g = gcd(a, b);
    return a * b / g;
}
bool prime(ll n) {
    for (ll i = 2; i <= sqrt(n); i++) {
        if (n%i == 0)return false;
    }
    return n != 1;
}

Vec fac, finv;

ll PowMod(ll a, ll n){
    if(n == 1) return a;
    if(n%2 == 0) return PowMod(a*a%MOD, n/2);
    return a*PowMod(a*a%MOD, n/2)%MOD;
}

ll combi(ll n, ll k){
    if(k>n) return 0;
    return fac[n]*finv[k]%MOD*finv[n-k]%MOD;
}

int main(){
    int n, m, ans=0;
    R n;
    map<string, int>a;
    rep(i, n){
        string s;
        R s;
        a[s]++;
    }
    R m;
    rep(j, m){
        string s;
        R s;
        a[s]--;
    }
    for(auto itr = a.begin(); itr != a.end(); itr++){
        ans = max(ans, a[itr->first]);
    }
    co(ans);
}


Measured memory_bytes: 256
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	public static void main(String[] args){

		Scanner sc=new Scanner(System.in);

		int N=sc.nextInt();

		int[] d=new int[N];

		for(int i=0;i<N;i++) d[i]=sc.nextInt();

		sc.close();

		Arrays.sort(d);

		System.out.println(d[N/2]-d[(N/2)-1]);
	}
}


Measured memory_bytes: 51240
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define si(X) scanf("%d", &(X))
#define sll(X) scanf("%lld",&(X))
#define INFL 0x3f3f3f3f3f3f3f3fLL
const ll mod = 1e9+7;

//-------------------------<MATH>-------------------------------------------------------//
ll gcd(ll a,ll b){if(b==0)return a;return gcd(b,a%b);}
ll expo(ll base,ll pow){ll ans = 1;
   while(pow!=0){if(pow&1==1){ans = ans*base;ans = ans%mod;}
   base *= base;base%=mod;pow/=2;}return ans;}
ll inv(ll x){return expo(x,mod-2);}
ll mult_mod(ll a , ll b){a = a%mod; b = b%mod;
ll c = (a * b)%mod;
//cout << a << " " << b << endl;
return c;}
ll add_mod(ll a , ll b){a = (a + mod)%mod;b = (b + mod)%mod;ll c = (a + b)%mod;return c;}
ll fac[(int)(5e5 + 5)] , inv_fac[(int)(5e5 + 5)];
void precomp_factorial(int M){fac[0] = 1;for(int i = 1 ; i <= M ; i++) fac[i] = mult_mod(i , fac[i - 1]);
    inv_fac[M] = inv(fac[M]);for(int i = M - 1 ; i >= 0 ; i--) inv_fac[i] = mult_mod(i + 1 , inv_fac[i + 1]);}
ll nCk(ll n , ll k){ll ans = fac[n];ans = mult_mod(ans , inv_fac[n - k]);ans = mult_mod(ans , inv_fac[k]);return ans;}
int lo[(int)(1e3 + 6)];
void sieve(int M){for(int i = 2 ; i < M ; i++){ if(lo[i]) continue; for(int j = i ; j < M ; j += i)lo[j] = i;}}
int max_expo_prime_n_fac(ll N , int prime){int ress = 0;while(N){ress += (N/prime);N /= prime;}return ress;}
//-------------------------</MATH>-------------------------------------------------------//

//-------------------------<STRING>-------------------------------------------------------//
string get_prefix(string x , int MAX){return x.substr(0 , min((int)x.size() , MAX));}
string get_suffix(string x,int MAX){int dn=1;for(int i=x.size()-1;i>=0;i--){if(dn==MAX)return x.substr(i);dn++;}return x;}
string convert_to_binary(int x,int len) {string ans=""; while(x){if(x&1){ans='1'+ans;}
    else{ans ='0'+ans;}x/=2;}int k = ans.size();while(k < len){ans = '0' + ans;k++;}return ans;}
//-------------------------</STRING>-------------------------------------------------------//

ull llrand() {ull r = 0;for(int i = 0; i < 5; ++i){r = (r << 15)|(rand() & 0x7FFF);}return r & 0xFFFFFFFFFFFFFFFFULL;}
int dx[8] = {1 , 0 , -1 , 0 , 1 , -1 , -1 , 1};    // last 4 diagonal
int dy[8] = {0 , 1 , 0 , -1 , 1 , 1 , -1 , -1};
const int M = 60;

int arr[M][M];
bool vis[M][M];

int n, m;
int till = 0;

void reset(){
    till = 0;
    for(int i = 0 ; i <= n + 2 ; i++){
        for(int j = 0 ; j <= m + 2 ; j++){
            vis[i][j] = 0;
            arr[i][j] = 0;
        }
    }
}

bool inside(int x, int y){
    return (x >= 1 && x <= n && y >= 1 && y <= m);
}

void dfs(int x, int y){
    if(vis[x][y]) return;
    vis[x][y] = 1;
    if(arr[x][y] == 2) till++;
    for(int d = 0 ; d < 4 ; d++){
        int nx = x + dx[d];
        int ny = y + dy[d];
        if(inside(nx, ny) && (arr[nx][ny] == 0 || arr[nx][ny] == 2)){
            dfs(nx, ny);
        }
    }

}
int main(){

    string s, t;
    cin >> s >> t;
    int cnt = 0;
    for(int i = 0; i < s.size(); i++){
        if(s[i] != t[i]) cnt++;
    }
    cout << cnt;
}






Measured memory_bytes: 3864
#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 7;
int visit[N], P[N], in[N], d[N];

vector <int> adj[N], parents[N];

int dp[N];

int dfs(int u, int p) {
     if(~dp[u]) return dp[u];
     int res = 0;
     for(int v: adj[u]){
        if(v != p) {
           res = max(res, dfs(v, u));
        }
     }
     return dp[u] = res + 1;

}

int main() {
        memset(dp, -1, sizeof dp);
        int n, m; cin >> n >> m;
        for(int i = 1; i <= n + m - 1; i++) {
                int u, v; cin >> u >> v;
                adj[u].push_back(v);
                parents[v].push_back(u);
                in[v]++;
        }
        for(int i = 1; i <= n; i++) if(!in[i]) dfs(i, 0);

        for(int i = 1; i <= n; i++) {
                int mx = INT_MAX, px = 0;
                for(int j: parents[i]) {
                        if(dp[j] < mx) {
                                mx = dp[j];
                                px = j;
                        }
                }
                P[i] = px;
        }

        for(int i = 1; i <= n; i++) cout << P[i] << endl;
}


Measured memory_bytes: 19584
#include <bits/stdc++.h>
using namespace std;
 
const int MAXL = 128;
const int Q = 850;
int L;
const string chars = 
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		"abcdefghijklmnopqrstuvwxyz"
		"0123456789";
vector<int> cnts(62);
int query(string s){
	cout<<"? "<<s<<endl;
	int v; cin>>v; return v;
}
bool is_subseq(string s){
	return (int)s.size()+query(s)==L;
}
string combine(string a,string b){
	if(!a.size()||!b.size()) return a+b;
	string ret="";
	for(int i=0,j=0,s1=a.size(),s2=b.size();i<s1||j<s2;)
		if(i<s1&&(j==s2||is_subseq(a.substr(0,i+1)+b.substr(j)))) ret+=a[i++];
		else ret+=b[j++];
	return ret;
}
string solve(int l,int r){
	if(l==r) return string(cnts[l],chars[l]);
	int mid=(l+r)>>1;
	return combine(solve(l,mid),solve(mid+1,r));
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0);
	
	assert(chars.size() == 62);
	auto get_cnt = [&](char c) -> int {
		return MAXL - query(string(MAXL, c));
	};
	
	for (int i = 0; i < 62; i++) {
		cnts[i] = get_cnt(chars[i]);
		L += cnts[i];
	}
	string ans = solve(0, 61);
	cout << '!' << ' ' << ans << '\n';
}

Measured memory_bytes: 3796
import sys
from collections import deque
import heapq
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

a = I()
s = S()

if a >= 3200:
  print(s)
else:
  print("red")

Measured memory_bytes: 3436
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
#include <cmath>

using ll = long long;

using namespace std;

int main() {
    int n;
    cin >> n;
    string s = "12345678";
    s = s.substr(0, n);
    string p = "", q = "";
    for (int i=0, pi; i<n; i++) {
        cin >> pi;
        p += (char)('0' + pi);
    }
    for (int i=0, qi; i<n; i++) {
        cin >> qi;
        q += (char)('0' + qi);
    }
    int i=0, a, b;
    do {
        if (p == s) a = i;
        if (q == s) b = i;
        i++;
    } while (next_permutation(s.begin(), s.end()));
    cout << abs(a - b) << '\n';
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;

int main() {
  int N,M;
  cin >> N>>M;
  vector<int> a(M);
  for (int i = 0; i < M; i++) {
    cin >> a.at(i);
  }
  sort(a.begin(), a.end());
  vector<int> b(M-1);
  for (int i = 0; i < M-1; i++) {
    b.at(i)=a.at(i+1)-a.at(i);
  }
  sort(b.begin(), b.end());
  reverse(b.begin(), b.end());
  if(N>=M){
    cout<<0<<endl;
  }
  else{
    int ans=a.at(M-1)-a.at(0);
    for (int i = 1; i <= N-1; i++) {

      ans-=b.at(i-1);
    }
    cout<<ans<<endl;
    
  }

}

Measured memory_bytes: 1024
#include <bits/stdc++.h>
using namespace std;

int main(){
    int n,m;
    cin>>n>>m;
    int s=(1<<n);
    vector<int> dp(s,1000000009);
    dp[0]=0;
    for (int i = 0; i < m; ++i) {
        int a,b;
        cin>>a>>b;
        int t=0;
        for (int j = 0; j < b; ++j) {
            int c;
            cin>>c;
            --c;
            t+=(1<<c);
        }
        for (int k = 0; k < s; ++k) {
            dp[k|t]=min(dp[k|t],dp[k]+a);
        }
    }
    if(dp[s-1]==1000000009)cout<<"-1"<<endl;
    else cout<<dp[s-1]<<endl;
    return 0;
}

Measured memory_bytes: 256
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <set>
#include <map>
typedef long long ll;
using namespace std;

class UnionFind{
public:
  vector<int> par;
  vector<int> rank;
  vector<int> sz;
  int N;

  UnionFind(int n) : N(n) {
      init();
  }

  //初期化
  void init(){
      par.resize(N);
      rank.resize(N, 0);
      sz.resize(N, 1);
      for(int i = 0; i < N; i++) par[i] = i;
  }

  //木の根を求める
  int find(int x){
    if(par[x] == x) return x;
    else {
      par[x] = find(par[x]);
      return par[x];
    }
  }

  //xとyの集合の併合
  void unite(int x, int y){
    x = find(x);
    y = find(y);
    if(x == y) return;

    if(rank[x] < rank[y]){
      par[x] = y;
      sz[y] += sz[x];
    }else{
      par[y] = x;
      sz[x] += sz[y];
      if(rank[x] == rank[y]) rank[x]++;
    }
  }

  //x,yが同じ集合にあるか
  bool same(int x, int y){
      return find(x) == find(y);
  }

  //xの木のサイズ
  int size(int x){
      return sz[find(x)];
  }

  //ufの連結成分の数
  int cnt_connection(){
      int res = 0;
      bool ex[N];
      fill(ex, ex + N, false);
      for(int i = 0; i < N; i++){
          ex[find(i)] = true;
      }

      for(int i = 0; i < N; i++){
          if(ex[i]) res++;
      }

      return res;
  }
};


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

    UnionFind uf = UnionFind(N);
    vector<int> f(N, 0);
    vector<vector<int>> e(N);

    for(int i = 0; i < M; i++) {
        int a, b;
        cin >> a >> b;
        a--;
        b--;
        uf.unite(a, b);
        f[a]++;
        f[b]++;
    }

    for(int i = 0; i < K; i++) {
        int a, b;
        cin >> a >> b;
        a--;
        b--;
        e[a].push_back(b);
        e[b].push_back(a);
    }

    for(int i = 0; i < N; i++) {
        int ans = uf.size(i) - 1 - f[i];
        for(int j = 0; j < (int)e[i].size(); j++) {
            if(uf.same(i, e[i][j])) ans--;
        }
        cout << ans << " ";
    }
    cout << endl;

    return 0;
}


Measured memory_bytes: 7552
from collections import defaultdict
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
Adic = defaultdict(int)
Bdic = defaultdict(int)
for i in range(N):
    Adic[A[i]] += 1
    Bdic[B[i]] += 1
nums = []
for i in range(1,N+1):
    nums.append((Adic[i],Bdic[i],i))
nums.sort(key=lambda x:x[0]+x[1],reverse=True)
index = 0
Aindex = 0
Bindex = 0
ansA = [-1]*N
ansB = [-1]*N
OK = False
for nA,nB,i in nums:
    if nA + nB > N:
        print('No')
        exit()
    else:
        if not OK:
            while nA and index < N:
                ansA[index] = i
                index += 1
                nA -= 1
            if index == N:
                OK = True
            while nB and index < N:
                ansB[index] = i
                index += 1
                nB -= 1
            if index == N:
                OK = True
        if OK:
            while nA:
                while ansA[Aindex] != -1:
                    Aindex += 1
                ansA[Aindex] = i
                nA -= 1
            while nB:
                while ansB[Bindex] != -1:
                    Bindex += 1
                ansB[Bindex] = i
                nB -= 1
ans = []
for i in range(N):
    ans.append((ansA[i],ansB[i]))
    if ansA[i] == ansB[i]:
        print('No')
        exit()
ans.sort(key=lambda x:x[0])
ANS = []
for i in range(N):
    ANS.append(ans[i][1])
print('Yes')
print(*ANS)

Measured memory_bytes: 178036
s = input()

s_set = set(s)
a_set = set('abcdefghijklmnopqrstuvwxyz')
left_list = sorted(list(a_set - s_set))

ans = -1
if len(left_list) == 0:#未使用文字なし
    while ans == -1:
        left_list.append(s[-1])
        s = s[:-1]
        if len(s) == 0:
            break
        left_list = sorted(left_list)
        #print(s, left_list)
        for c in left_list:
            #print(c, s[-1])
            if c > s[-1]:
                ans = s[:-1] + c
                break
else:#未使用文字あり
    ans = s + left_list[0]
print(ans)

Measured memory_bytes: 3064
#include <bits/stdc++.h>
using namespace std;

int main(){
  int n, m; cin >> n >> m;
  vector<long long> A(n);
  for(int i = 0; i < n; i++){
    cin >> A.at(i);
  }
  vector<pair<long long, int>> BC(m);
  for(int i = 0; i < m; i++){
    int b; long long c;
    cin >> b >> c;
    BC.at(i) = make_pair(c, b);
  }
  sort(A.begin(), A.end());
  sort(BC.begin(), BC.end());
  int cnt1 = m-1; int cnt2 = 0;
  bool fin = false;
  while(true){
  	int b = BC.at(cnt1).second;
    long long c = BC.at(cnt1).first;
    for(int i = cnt2; i < min(n, cnt2 + b); i++){
      if(c > A.at(i)) A.at(i) = c;
      else fin = true;
    }
    if(fin) break;
    cnt2 += b;
    if(cnt1 == 0 || cnt2 >= n) break;
    cnt1--;
  }
  long long ans = 0;
  for(long long k: A) ans += k;
  cout << ans << endl;
}

Measured memory_bytes: 2560
import sys
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def II(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def SI(): return input()
YN = lambda b: print('YES') if b else print('NO')
yn = lambda b: print('Yes') if b else print('No')

def main():
    N, M = LI()
    s_li = []
    for i in range(M):
        s_li.append(LI()[1:])
    p_li = LI()

    import itertools
    counter = 0
    for i in itertools.product([0,1], repeat=N):  # product of switches
        for s, p in zip(s_li, p_li): # for each lights
            if sum([i[num-1] for num in s])%2 != p:
                break
        else:
            counter += 1
    print(counter)

main()

Measured memory_bytes: 3064
#include<iostream>
#include<string>
#include<array>
#include<algorithm>
#include<deque>
#include<vector>

int main(void) {
	int N;
	int A, B;
	std::cin >> N;
	if (N == 1) {
		std::cout << "Hello World" << std::endl;
	}
	else if (N == 2) {
		std::cin >> A >> B;
		std::cout << A + B << std::endl;
	}
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define ll long long
#define debug(a) cout<<a<<endl
#define pii pair<int,int>
#define maxn 100009
using namespace std;
int main(){
    ios::sync_with_stdio(false);
    string s;
    cin>>s;
    int dat1=(s[0]-'0')*10 +(s[1]-'0');
    int dat2=(s[2]-'0')*10 +(s[3]-'0');
    if((dat1>12 || dat1==0) && (dat2>12 || dat2==0)){
        cout<<"NA"<<endl;
        return 0;
    }
    if((dat1>12 || dat1==0) && dat2<=12)cout<<"YYMM"<<endl;
    else if(dat1>0 && dat1<=12 && dat2>0 && dat2<=12)cout<<"AMBIGUOUS"<<endl;
    else cout<<"MMYY"<<endl;
    return 0;
}
///usar double sempre ou long double
///pensar em casos que coisas dao negativas
///N esquecer de limpar as coisas em quest de varios testes
///OLHAR A COMPLEXIDADE PRA VER SE N PASSA POR BRUTE FORCE OU BRUTE FORCE COM ALGUMAS OTIMIZACOES

Measured memory_bytes: 256
N, k = map(int, input().split())
a = 1
b = [bi - 1 for bi in map(int, input().split())]
a -= 1

now = b[a]
S = set()
S.add(a)
while now not in S:
    S.add(now)
    now = b[now]
root = now

count = 1
now = b[root]
while now != root:
    now = b[now]
    count += 1

start = len(S) - count

if k <= start:
    now = a
    for _ in range(k):
        now = b[now]
    print(now + 1)
else:
    k -= start
    k %= count
    now = root
    for _ in range(k):
        now = b[now]
    print(now + 1)


Measured memory_bytes: 32772
import java.util.*;

public class Main{
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		int num = scan.nextInt();
		int[] ar = new int[num];
		for(int i = 0;i<num;i++){
			ar[i] = scan.nextInt();
		}
		int[] e = new int[2];
		int[] log = new int[2];
		int k = 0;
		for(int j = 0;j<num-1;j++){
			if(ar[j+1]<ar[j]&&k!=1){
				e[0]=ar[j];
				log[0]=j;
				j=0;
				k++;
				// System.out.println(e[0]+" "+log[0]);
			}else if(ar[j+1]<ar[j]&&k==1&&j!=log[0]){
				e[1]=ar[j+1];
				log[1]=j+1;
				// System.out.println(e[1]+" "+log[1]);
				break;

			}
		}
		if(k==1){
		ar[log[0]]=e[1];
		ar[log[1]]=e[0];
	}
		for(int l = 0;l<num-1;l++){
			if(ar[l+1]<ar[l]){
				System.out.println("NO");
				System.exit(0);
			}
		}
		System.out.println("YES");
	}
}

Measured memory_bytes: 23764
import sys
input = sys.stdin.buffer.readline

H, N = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]

INF = 10 ** 15
dp = [INF] * H
dp[0] = 0
answer = INF
for a, b in AB:
  for i in range(H):
    if dp[i] != INF:
      if i + a < H:
        dp[i + a] = min(dp[i + a], dp[i] + b)
      else:
        answer = min(dp[i] + b, answer)

print(answer)

Measured memory_bytes: 43116
#include <bits/stdc++.h>
using namespace std;
#define FASTIO  ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll double
#define vi vector<ll>
#define all(a) (a).begin(), (a).end()
#define rep(i,a,b)  for(int i=a;i<b;i++)
#define tr(it, a)   for(auto it=a.begin();it!=a.end();it++)
#define pb push_back
#define endl  "\n"
const int  MAX=3000+3;
//const int  mod=1e9+7;
int n;
vi v(MAX);

double dp[MAX][MAX];
/*
ll fun(int i,int  k)
{
    if(i==n && k<=n/2)
        return 0;
    if(i==n && k>n/2)
        return 1;
       if(dp[i][k]>=0)
       return dp[i][k];
   ll a=v[i]*fun(i+1,k+1);
    ll b=(1-v[i])*fun(i+1,k);
    dp[i][k]=a+b;
    //cout<<a+b<<endl;;
    return a+b;
}*/
ll fun()
{
    memset(dp,0.0,sizeof(dp));
    dp[0][0]=1.0;
    for(int i=1;i<=n;i++)
    {
        dp[i][0]=(1-v[i-1])*dp[i-1][0];
    }
     for(int i=1;i<=n;i++)
    {
        dp[i][i]=(v[i-1])*dp[i-1][i-1];
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<i;j++)
        {
            dp[i][j]=(dp[i-1][j-1]*v[i-1] )+ (dp[i-1][j]*(1-v[i-1]));
        }
    }
   /* rep(i,0,n+1)
    {
        rep(j,0,n+1)
        {
            cout<<dp[i][j]<<" ";
        }
        cout<<endl;
    }*/
    double ans=0.0;
    for(int i=(n/2)+1;i<=n;i++)
        ans+=dp[n][i];
    return ans;
}
int main()
{
   FASTIO

    cin>>n;
    rep(i,0,n)
    cin>>v[i];

    double ans=fun();
    cout << fixed << setprecision(12) << ans;
 return 0;
}


Measured memory_bytes: 70784
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <iostream>

using namespace std;
/** Problem0105 : Book Index **/
int main()
{
	map<string, vector<int> >index;
	string s; int p;
	
	while (cin >> s >> p) {
		index[s].push_back(p);
	}
	
	map<string, vector<int> >::iterator it = index.begin();
	for (;it != index.end(); it++) {
		cout << it->first << endl;
		
		sort(index[it->first].begin(), index[it->first].end());
		
		vector<int>::iterator it2 = index[it->first].begin();
		cout << *it2;
		for (++it2 ;it2 != index[it->first].end(); it2++) {
			cout << " " << *it2;
		}
		cout << endl;
	}
}

Measured memory_bytes: 1244
s = gets.chomp
i = s.length - 1
#p i
while i > 0
#    puts s[i-4,5]
    if i-4 >= 0 && s[i-4,5] == 'erase'
        i -= 5
    elsif i-4 >= 0 && s[i-4,5] == 'dream'
        i -= 5
    elsif i-5 >= 0 && s[i-5,6] == 'eraser'
        i -= 6
    elsif i-6 >= 0 && s[i-6,7] == 'dreamer'
        i -= 7
    else
        puts "NO"
        exit
    end
end
puts "YES"


Measured memory_bytes: 1916
import java.util.*;

public class Main {
	public static void main (String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		int[] ans = new int[n];
		ans[0] = 0;
		for (int i = 1; i < n; i++) {
			int min = Integer.MAX_VALUE;
			for (int j = Math.max(0, i - k); j < i; j++) {
				int t = ans[j] + Math.abs(arr[j] - arr[i]);
				if (min > t) {
					min = t;
				}
			}
			ans[i] = min;
		}
		System.out.println(ans[n - 1]);
	}
}


Measured memory_bytes: 50156
#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#define rep(i,n) for (int i = 0; i < n; i++)
using namespace std;
using ll = long long;
using P = pair<int,int>;

int main() {
  int n;
  cin >> n;
  double n1 = (double)n/2;
  cout << round(n1) << endl;
  return 0;
}


Measured memory_bytes: 888
use std::io;
use std::cmp;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::f64::consts::PI;

fn read_line() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).ok();
    buf
}


fn main() {
    let line: Vec<usize> = read_line().split_whitespace().map(|s| s.parse().unwrap()).collect();
    let a= line[0];
    let b= line[1];
    if 0 < a && a < 10 && 0 < b && b < 10 {
        println!("{}", a * b);
    } else {
        println!("-1");
    }
}


Measured memory_bytes: 4352
object Main {
    def step(s: String, cmd: Array[String]) = (cmd(0), cmd(1).toInt, cmd(2).toInt) match {
        case ("print", x, y) => {println(s.slice(x, y+1)); s}
        case ("reverse", x, y) => s.take(x) + s.slice(x, y+1).reverse +s.drop(y+1)
        case ("replace", x, y) => s.patch(x, cmd(3), y-x+1)
    }
    def main(args: Array[String]): Unit = {
        val in = io.Source.stdin.getLines
        val s = in.next
        in.next
        in.map(_.split(" ")).foldLeft(s)(step)
    }
}

Measured memory_bytes: 45192
#include <bits/stdc++.h>

using namespace std;
#define SPEED ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define fileio freopen("http://in.in", "r", stdin),freopen("out.out", "w", stdout);
#define ll long long
#define pb push_back
#define pll pair<ll,ll>
#define ff first
#define ss second
#define N 2000001
#define M 1000000007
#define INF 1000000000000000


int main()
{
 string s;
 cin>>s;
 ll rain=0,ans=0;
 for(ll i=0;i<3;i++)
 {
     if(s[i]=='R')rain++;
     else rain=0;
     ans=max(ans,rain);
 }
 cout<<ans;
}

Measured memory_bytes: 3616
import datetime

S=input()

YYMM_OK = True
try:
	datetime.datetime.strptime("20" + S, "%Y%m")
except ValueError:
	YYMM_OK = False

MMYY_OK = True
try:
	mmyy=S[:2] + "20"+S[2:]
	# print(mmyy)
	datetime.datetime.strptime(mmyy, "%m%Y")
except ValueError:
	MMYY_OK = False

ans ="NA"
if YYMM_OK and MMYY_OK:
	ans = "AMBIGUOUS"
elif YYMM_OK:
	ans = "YYMM"
elif MMYY_OK:
	ans = "MMYY"

print(ans)


Measured memory_bytes: 4592
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = a; i <= b; ++i)
const int N = 1e5 + 7;

int n, m; long long ans;
pair <int, int> p[N];
priority_queue <int, vector<int>, greater<int> > q;

int main() {
	ios::sync_with_stdio(0);
	cin >> n >> m;
	rep(i, 1, n) {
		int x; cin >> x;
		q.push(x);
	}
	rep(i, 1, m) {
		int b, c; cin >> b >> c;
		p[i] = make_pair(c, b);
	} sort(p + 1, p + m + 1);
	for (int i = m; i > 0; --i) if (p[i].first > q.top()) {
		int k = p[i].second; while (k--) {
			q.pop(); q.push(p[i].first);
		}
	} else break;
	while (!q.empty()) {
//		cout << q.top() << ' ';
		ans += 1LL * q.top(); q.pop();
	}
	cout << ans << '\n';
	return 0;
}

Measured memory_bytes: 1528
import Control.Applicative
import Data.List
import Debug.Trace

check :: Integer -> [Integer] -> Integer
check n lst = 
    let validate_odd :: Integer -> [Integer] -> Bool
        validate_odd m [] = False
        validate_odd m [a] = if a == 0 then True else False
        validate_odd m (x:y:rest) = if m == x && m == y then validate_odd (m - 2) rest else False
        validate_even m [] = True
        validate_even m [_] = False
        validate_even m (x:y:rest) = if m == x && m == y then validate_even (m - 2) rest else False
        validate :: Bool
        validate = if mod n 2 == 0 then validate_even (n - 1) lst else validate_odd (n - 1) lst
        --in trace ((show n) ++ " " ++ (show lst)) $ if validate then power2 (div n 2) else 0
        in if validate then mod (2 ^ (div n 2)) (10 ^ 9 + 7) else 0

main = print =<< check <$> ((\a -> read a :: Integer) <$> getLine) <*> (reverse . sort . ((map (\a -> read a :: Integer)) . words) <$> getLine)


Measured memory_bytes: 29052
#include<bits/stdc++.h>
using namespace std;
long long a,b;
int main()
{
	scanf("%lld%lld",&a,&b);
	if(a>b)swap(a,b);
	if(a<=0&&0<=b)
	{
		printf("Zero");
		return 0;
	}
	if(0<a&&0<b)
	{
		printf("Positive");
		return 0;
	}
	a=b-a;
	if(a&1)printf("Positive");
	else printf("Negative");
}

Measured memory_bytes: 256
list_ab = [int(x) for x in input().split()]
dict_ab = []
for x in list_ab:
  dict_ab.append(x)
dict_result = 0
for y in range(2):
  dic_max_i = max(dict_ab)
  dict_result = dict_result + dic_max_i
  dict_ab.remove(dic_max_i)
  dict_ab.append(dic_max_i-1)
print(dict_result)


Measured memory_bytes: 2940
fn main() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let mut iter = s.trim()
        .split_whitespace()
        .map(|c| c.parse::<u32>().ok().unwrap());
    println!(
        "{}",
        (iter.next().unwrap() - 1) * (iter.next().unwrap() - 1)
    );
}


Measured memory_bytes: 4352
// template version 1.15
using namespace std;
#include <bits/stdc++.h>

// varibable settings
#define int long long
const int INF=1e18;

// define basic macro {{{
#define _overload3(_1,_2,_3,name,...) name
#define _rep(i,n) repi(i,0,n)
#define repi(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define rep(...) _overload3(__VA_ARGS__,repi,_rep,)(__VA_ARGS__)
#define _rrep(i,n) rrepi(i,0,n)
#define rrepi(i,a,b) for(int i=(int)((b)-1);i>=(int)(a);--i)
#define rrep(...) _overload3(__VA_ARGS__,rrepi,_rrep,)(__VA_ARGS__)
#define each(i,a) for (auto&& i : a)
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define mt(a, b, c) make_tuple(a, b, c)
#define ub upper_bound
#define lb lower_bound
#define posl(A, x) (lower_bound(all(A), x)-A.begin())
#define posu(A, x) (upper_bound(all(A),x)-A.begin())
template<class T> inline void chmax(T &a, const T &b) { if((a) < (b)) (a) = (b); }
template<class T> inline void chmin(T &a, const T &b) { if((a) > (b)) (a) = (b); }

#define divceil(a,b) ((a)+(b)-1)/(b)
#define is_in(x, a, b) ((a)<=(x) && (x)<(b))
#define uni(x) sort(all(x));x.erase(unique(all(x)),x.end())
#define slice(l, r) substr(l, r-l)

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long double ld;
typedef pair<int,int> pii;
typedef tuple<int,int,int> iii;

template<typename T> using PQ = priority_queue<T, vector<T>, greater<T>>;
struct Fast { Fast(){ std::cin.tie(0); ios::sync_with_stdio(false); } } fast;

#if defined(PCM) || defined(LOCAL)
    #include "lib/dump.hpp"
#else
    #define dump(...) 42
    #define dump_1d(...) 42
    #define dump_2d(...) 42
    #define cerrendl 42
#endif
//}}}

signed main() {
    int n,a,b;cin>>n>>a>>b;

    int ans = 0;
    ans += n/(a+b)*a;
    ans += min(n%(a+b), a);
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 256
#include <stdio.h>

int main(void) {
    int n; scanf("%d",&n);
	int ary[n]; for (int i=0; i<n; i++) { scanf("%d",&ary[i]); }
	
	int max=0, snd=0, k=0;
	for (int i=0; i<n; i++) {
		if (ary[i] > max) {
			snd = max;
			max = ary[i];
			k = 1;
		} else if (ary[i] == max) {
			k++;
		} else if (max > ary[i] && ary[i] > snd) {
			snd = ary[i];
		}
	}
	for (int i=0; i<n; i++) {
		if (k > 1) {
			printf("%d\n",max);
		} else if (ary[i] != max) {
			printf("%d\n",max);
		} else {
			printf("%d\n",snd);
		}
	}
	
    return 0;
}


Measured memory_bytes: 2304
#include<string>
#include<string.h>
#include<map>
#include<set>
#include<vector>
#include<stdio.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
long long n,k;
long long ans;
int main(){
    cin>>n>>k;
    bool b;
    if (k%2==0) b=true;
    else b=false;
    long long c=n/k;
    ans+=c*c*c;
    if (b) {
               if (n>=k*c+k/2) c+=1;
               ans+=c*c*c;
            }
    cout<<ans<<endl;
    return 0;
}

Measured memory_bytes: 256
import java.util.*;

public class Main {
	public static void main(String[] args) {
		//ABC081A
		Scanner sc = new Scanner(System.in);
		// スペース区切りの整数の入力
		long a = sc.nextInt();
		long b = sc.nextInt();
		long c = sc.nextInt();
		long d = sc.nextInt();

		long ac = a * c;
		long ad = a * d;
		long bc = b * c;
		long bd = b * d;

		long out = 0;

		if(ac > ad) out = ac;
		else out = ad;
		if(out < bc) out = bc;
		if(out < bd) out = bd;
		
		// 出力
		System.out.println(out);

		sc.close();
	}
}


Measured memory_bytes: 27092
/*input
10
10
*/
#include <bits/stdc++.h>
using namespace std;
const long long md=1e9+7;
long long a[1000005],n,k;
int get(int i){
	return (1<<i)+k*(n-i);
}
int main(){
	#ifdef ONLINE_JUDGE
	ios_base::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	#endif
	int q,m,h,ans=1e9,sum=0,p,x,y;
	cin>>n>>k;
	for(int i=0;i<=n;++i)
		ans=min(ans,get(i));
	cout<<ans;
}

Measured memory_bytes: 256
# 2019-11-20 21:11:21(JST)
import sys
import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# import re
# import heapq
# import array
# from scipy.misc import comb # (default: exact=False)
# import numpy as np 


def main():
    s = sys.stdin.readline().rstrip()
    
    if len(s) == 1:
        print('YES')
        sys.exit()

    c = collections.Counter(s).values()
    if len(c) == 1:
        ans = 'NO'
    elif len(c) == 2:
        if len(s) == 2:
            ans = 'YES'
        else:
            ans = 'NO'
    else: 
        if max(c) - min(c) >= 2:
            ans = 'NO'
        else:
            ans = 'YES'
    
    print(ans)
if __name__ == "__main__":
    main()


Measured memory_bytes: 3444
#include <bits/stdc++.h>
using namespace std;
constexpr int IINF = INT_MAX;

double dp[505][505];  // i番目の区画までみてj個の区画を確定したときの最大値

int main() {
    int n, m;
    cin >> n >> m;
    vector<double> a(n+1, 0);
    for(int i=0;i<n;i++){
        cin >> a[i+1];
        a[i+1] += a[i];
    }
    for(int i=0;i<=n;i++) fill(dp[i], dp[i]+m+1, -IINF);
    dp[0][0] = 0;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            for(int k=j;k<=i;k++){
                dp[i+1][j+1] = max(dp[i+1][j+1], dp[k][j] + (a[i+1]-a[k])/(i+1-k));
            }
        }
    }
    printf("%.10lf\n", dp[n][m]);
    return 0;
}



Measured memory_bytes: 5260
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> l_l;
typedef vector<ll> vel;
typedef vector<int> vei;
typedef vector<char> vec;
typedef vector<string> ves;
typedef vector<vector<int>> ve_vei;
typedef vector<vector<char>> ve_vec;
typedef vector<vector<string>> ve_ves;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<(int)(n);i++)
#define rep2(i,n) for(int i=2;i<(int)(n);i++)
#define fs first
#define sc second
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
#define mod (1000000007)

int main(){
    int N,L; cin >> N >> L;
    ves S(N);
    rep(i,N) cin >> S[i];

    sort(all(S));
    rep(i,N) cout << S[i];
    cout << endl;
    return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; ++i)
#define FOR(i, a, b) for(int i = a; i < b; ++i)
#define F first
#define S second
#define OUT(x) cout << (x) << "\n"
using namespace std;
using point = pair< int,int >;
using ll = long long;

int main() {
    int cnt = 0;
    int bit; // 0 : B, 1 : W
    string str;
    cin >> str;

    if (str[0] == 'B') {
        bit = 0;
    } else {
        bit = 1;
    }

    FOR(i, 1, str.size()) {
        if (bit && str[i] == 'B') {
            cnt++;
            bit = !bit;
        } else if (!bit && str[i] == 'W') {
            cnt++;
            bit = !bit;
        }
    }

    OUT(cnt);

    return 0;
}



Measured memory_bytes: 512
#include <bits/stdc++.h>
using namespace std;

using pii = pair<int, int>;

constexpr int map_size = 51;

enum direction {
    north,
    east,
    south,
    west
};

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

bool is_valid_move(int from, int to) {
    return !((from == north && to == south) || (from == east && to == west)
             || (from == south && to == north) || (from == west && to == east));
}

int main() {
    int n, x0, y0, t;
    cin >> n >> x0 >> y0 >> t;
    vector<vector<vector<bool>>> is_connected(map_size, vector<vector<bool>>(map_size, vector<bool>(4)));
    for(int i = 0; i < n; ++i) {
        int xs, ys, xe, ye;
        cin >> xs >> ys >> xe >> ye;
        if(xs > xe) swap(xs, xe);
        if(ys > ye) swap(ys, ye);
        if(ys == ye) {
            for(int x = xs; x + 1 <= xe; ++x) {
                is_connected[x][ys][east] = is_connected[x + 1][ys][west] = true;
            }
        }
        if(xs == xe) {
            for(int y = ys; y + 1 <= ye; ++y) {
                is_connected[xs][y][north] = is_connected[xs][y + 1][south] = true;
            }
        }
    }

    vector<int> dist(t), dir(t);
    for(int i = 0; i < t; ++i) {
        char tdir;
        cin >> dist[i] >> tdir;
        if(tdir == 'N')      dir[i] = north;
        else if(tdir == 'E') dir[i] = east;
        else if(tdir == 'S') dir[i] = south;
        else                 dir[i] = west;
    }

    // (x, y, from_dir, to_dir)
    using state = tuple<int, int, int, int>;
    vector<state> now;
    for(int i = 0; i < 4; ++i) {
        if(is_connected[x0][y0][i]) {
            now.emplace_back(x0, y0, i, i);
        }
    }
    for(int i = 0; i < t; ++i) {
        for(int j = 0; j < dist[i]; ++j) {
            vector<state> nxt;
            for(auto& p : now) {
                int cur_x, cur_y, cur_fdir, cur_tdir;
                tie(cur_x, cur_y, cur_fdir, cur_tdir) = p;
                //cout << "cur_x: " << cur_x << " cur_y: " << cur_y << "  cur_tdir: " << cur_tdir << endl;
                const int ny = cur_y + dy[cur_tdir],
                          nx = cur_x + dx[cur_tdir];
                for(int ndir = 0; ndir < 4; ++ndir) {
                    if(is_valid_move(cur_tdir, ndir) && is_connected[nx][ny][ndir]) {
                        nxt.emplace_back(nx, ny, cur_tdir, ndir);
                    }
                }
            }
            sort(begin(nxt), end(nxt));
            nxt.erase(unique(begin(nxt), end(nxt)), end(nxt));
            now = move(nxt);
        }
        now.erase(remove_if(begin(now), end(now),
                  [&](auto const& st) { return get<2>(st) != dir[i] && get<3>(st) != dir[i]; }),
                  end(now));
    }

    vector<pii> ans;
    for(const auto& st : now) {
        ans.emplace_back(get<0>(st), get<1>(st));
    }
    sort(begin(ans), end(ans));
    ans.erase(unique(begin(ans), end(ans)), end(ans));
    for(const auto& pos : ans) {
        cout << pos.first << ' ' << pos.second << endl;
    }
}


Measured memory_bytes: 3764
#include <bits/stdc++.h>
//#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
//using namespace boost::multiprecision;
typedef long long int ll;
typedef long double ld;
#define MOD 1000000007
#define ALL(obj) (obj).begin(),(obj).end()
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;
bool pairCompare(const pair<double,ll>& firstElof, const pair<double,ll>& secondElof){
    return firstElof.first < secondElof.first;
}
bool pairCompareSecond(const pair<double,ll>& firstElof, const pair<double,ll>& secondElof){
    return firstElof.second < secondElof.second;
}
//四方向への移動ベクトル
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

struct edge{//グラフに使うヤツ
    ll from,to,cost;
};

typedef vector<vector<edge> > G;
ll gcd(ll a,ll b){
    if (a%b==0)return(b);
    else return(gcd(b,a%b));
}


int main(){
    ll n;
    cin >> n;
    vector<ll> ki[n];
    for (ll i=0;i<n-1;i++){
        ll a,b;
        cin >> a >> b;
        a--;
        b--;
        ki[a].push_back(b);
        ki[b].push_back(a);
    }
    ll f[n],s[n];
    bool fvisited[n],svisited[n];
    fill(fvisited,fvisited+n,false);
    fill(svisited,svisited+n,false);
    queue<pair<ll,ll> > fque;
    queue<pair<ll,ll> > sque;
    fque.push(make_pair(0,0));
    sque.push(make_pair(n-1,0));
    while(!fque.empty()){
        pair<ll,ll> p=fque.front();
        fque.pop();
        ll x=p.first,y=p.second;
        f[x]=y;
        fvisited[x]=true;
        for (ll i=0;i<ki[x].size();i++){
            if (!fvisited[ki[x][i]]){
                fque.push(make_pair(ki[x][i],y+1));
            }
        }
    }
    while(!sque.empty()){
        pair<ll,ll> p=sque.front();
        sque.pop();
        ll x=p.first,y=p.second;
        s[x]=y;
        svisited[x]=true;
        for (ll i=0;i<ki[x].size();i++){
            if (!svisited[ki[x][i]]){
                sque.push(make_pair(ki[x][i],y+1));
            }
        }
    }
    ll fc=0,sc=0;

    for (ll i=0;i<n;i++){
        if (f[i]<=s[i]){
            fc++;
        }else sc++;
    }
    if (fc>sc){
        cout << "Fennec" << endl;
    }else{
        cout << "Snuke" << endl;
    }
    return 0;
}


Measured memory_bytes: 11632
# Problem: https://atcoder.jp/contests/abc042/tasks/abc042_b
# Python 1st Try

import sys
# from collections import defaultdict
# import heapq,copy
# from collections import deque


def II(): return int(sys.stdin.readline())


def MI(): return map(int, sys.stdin.readline().split())


def LI(): return list(map(int, sys.stdin.readline().split()))


def LLI(rows_number): return [LI() for _ in range(rows_number)]


def solver(allNum, longLeng, eachString):
    result = ''
    eachString.sort()
    result = "".join(eachString)
    return result


if __name__ == "__main__":
    N, L = MI()
    SI = []
    for _ in range(0, N, +1):
        getStrList = sys.stdin.readline().split()
        SI.append(getStrList[0])
    print("{}".format(solver(N, L, SI)))


Measured memory_bytes: 3064
#include <iostream>

using namespace std;

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

    int summ = 0, minm = x;
    for(int i=0; i<n; i++) {
        int m;
        cin >> m;
        summ += m;
        minm = min(minm, m);
    }
    int rest = x - summ;
    int rct = rest / minm;
    cout << n + rct << endl;
}

Measured memory_bytes: 256
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    }};

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused)]
macro_rules! debug {
    ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());
}
#[allow(unused)]
macro_rules! debugln {
    ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (write!(out,$($format)*).unwrap());
    }
    input! {
        a: i64, b: i64,
    }
    let mi = min(a, b);
    let ma = max(a, b);
    for _ in 0..ma {
        puts!("{}", mi);
    }
    puts!("\n");
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}


Measured memory_bytes: 8572
#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>

#ifdef __GXX_EXPERIMENTAL_CXX0X__
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#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>

#ifdef __GXX_EXPERIMENTAL_CXX0X__
#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 <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif

using namespace std;


int main ()
{
	int n , m;
	while( cin >> n >> m , n || m )
	{
		vector<int>data;
		data.resize ( n );
		int now = m;
		for( size_t i = 0; i < n; i++ )
		{
			int j = m;
			while( j )
			{
				now++;
				now %= n;
				if( !data[now] )j--;
			}
			data[now] = 1;
		}
		int ans;
		if( ( now + n - m ) % n == 0 )
		{
			ans = n;
		} else
		{
			ans = ( now + n - m ) % n;
		}
		cout << ans << endl;
	}

}

Measured memory_bytes: 1196
input_line = input()

if input_line == "SUN":
    ans = 7
elif input_line == "MON":
    ans = 6
elif input_line == "TUE":
    ans = 5
elif input_line == "WED":
    ans = 4
elif input_line == "THU":
    ans = 3
elif input_line == "FRI":
    ans = 2
elif input_line == "SAT":
    ans = 1
print(ans)

Measured memory_bytes: 2940