akhauriyash/Code-Regression huggingface dataset:
#include<bits/stdc++.h>
using namespace std;
int n,m;
struct edge{
    int v,nxt;
} e[2019][2];
int head[2019][2],in[2019],out[2019],tot[2]={1,1},vst[2019];
void ae(int u,int v,int f){
    if(!f){
        in[v]++;
        out[u]++;
    }
    e[tot[f]][f]={v,head[u][f]};
    head[u][f]=tot[f]++;
}
queue<int> q;
int ans[2000],tmp[2000],ptr=2000,ptr1=0;
int kkk=2;
void dfs(int u,int len){
    if(len>=ptr)return;
    vst[u]=kkk;
    tmp[len]=u;
    bool ok=0;
    for(int i=head[u][0];i;i=e[i][0].nxt){
        int v=e[i][0].v;
        if(vst[v]==kkk)break;
        if(vst[v]!=1&&vst[v]!=kkk){dfs(v,len+1);ok=1;}
    }
    if(!ok){
        if(len<ptr){
            ptr=len+1;
            for(int i=0;i<ptr;i++){
                ans[i]=tmp[i];
            }
        }
    }
    vst[u]=kkk-1;
}
int main(){
    cin>>n>>m;
    for(int i=0;i<m;i++){
        int u,v;
        cin>>u>>v;
        ae(u,v,0);
        ae(v,u,1);
    }
    int visit=0;
    for(int i=1;i<=n;i++){
        if(in[i]==0||out[i]==0)q.push(i),vst[i]=1;
    }
    while(!q.empty()){
        int u=q.front();
        q.pop();
        if(in[u]==0){
            for(int i=head[u][0];i;i=e[i][0].nxt){
                int v=e[i][0].v;
                in[v]--;
                if(in[v]==0&&!vst[v]){
                    vst[v]=1;
                    q.push(v);
                }
            }
        }
        else{
            for(int i=head[u][1];i;i=e[i][1].nxt){
                int v=e[i][1].v;
                out[v]--;
                if(out[v]==0&&!vst[v]){
                    vst[v]=1;
                    q.push(v);
                }
            }
        }
    }
    for(int i=1;i<=n;i++)if(in[i]==out[i]&&in[i]==0)visit++;
    if(visit==n){cout<<-1<<endl;return 0;}
    int x=1;
    bool ok=0;
    for(;x<=n;x++){
        if(vst[x]!=1){kkk++;dfs(x,0);}
    }
    if(ptr==0||ptr==2000){
        cout<<-1<<endl;
        return 0;
    }
    cout<<ptr<<endl;
    for(int i=0;i<ptr;i++){
        cout<<ans[i]<<endl;
    }
    return 0;
}

Measured memory_bytes: 384
#include<bits/stdc++.h>
using namespace std;
main()
{
    float a,b[1006],c,d,e,r,f,t,g,k=1000;
    int i,j;
    cin>>a>>t>>c;
    for(i=0;i<a;i++)
        cin>>b[i];
    for(i=0;i<a;i++)
    {
        d=t-(b[i]*(.006));
        f=abs(d-c);
        if(k>f)
        {
            k=f;
            r=i+1;

        }}
        cout<<r<<endl;
        return 0;

}


Measured memory_bytes: 256
N = int(input())
alphabet = [
    "z",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y"]
out = []
div = 28


while True:
    N, mod = divmod(N, 26)
    if mod == 0:
        N -= 1
    out.append(alphabet[mod])
    if N == 0:
        break
print("".join(reversed(out)))


Measured memory_bytes: 61712
#include <vector>
#include <iostream>

class DisjointSet
{
  private:
    std::vector<int> P;
    int root(int a);

  public:
    DisjointSet(int N);
    ~DisjointSet();
    void unite(int a, int b);
    bool is_same_set(int a, int b);

    void show_all(int a);
};

DisjointSet::DisjointSet(int N)
{
    for (int i = 0; i <= N; ++i)
    {
        P.push_back(i);
    }
}

// a の木の root の値を返す
int DisjointSet::root(int a)
{
    if (P[a] == a)
        return a;
    return (P[a] = root(P[a]));
}

// a の属する木を b の木に合体する
void DisjointSet::unite(int a, int b)
{
    P[root(a)] = root(b);
    return;
}

// a と b が同じ集合に属しているかどうか
bool DisjointSet::is_same_set(int a, int b)
{
    return root(a) == root(b);
}

// デバッグ用：a から root までの値をすべて表示する
void DisjointSet::show_all(int a)
{
    if (P[a] != a)
        show_all(P[a]);
    std::cout << "P[" << a << "] = " << P[a] << std::endl;
    return;
}

//=========================

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

using namespace std;
typedef pair<int, int> P;

int main()
{
    int n;
    cin >> n;
    vector<int> cost;
    vector<pair<int, P>> edges;

    for (int row = 0; row < n; row++)
    {
        for (int col = 0; col < n; col++)
        {
            int c;
            cin >> c;
            if (row > col && c > -1)
            {
                edges.push_back(
                    make_pair(
                        c, make_pair(row, col)));
            }
        }
    }

    sort(edges.begin(), edges.end());
    DisjointSet *tree = new DisjointSet(n);

    int ans = 0;
    for (int i = 0, size = edges.size(); i < size; i++)
    {
        int cost = edges[i].first;
        int src = edges[i].second.first;
        int dst = edges[i].second.second;

        if (!tree->is_same_set(src, dst))
        {
            tree->unite(src, dst);
            ans += cost;
        }
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 3264
package main

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

func readLine(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

func readInt(sc *bufio.Scanner) (res int) {
	res, _ =strconv.Atoi(readLine(sc))
	return
}

func readInts(sc *bufio.Scanner, n int) []int {
	ns := strings.Split(readLine(sc), " ")
	res := make([]int, n)

	for i, n := range ns {
		res[i], _ = strconv.Atoi(n)
	}
	return res
}

func readMatrix(sc *bufio.Scanner, rows, cols int) [][]int {
	res := make([][]int, rows)
	for i := 0; i < rows; i ++ {
		res[i] = readInts(sc, cols)
	}
	return res
}

func main() {
	sc := bufio.NewScanner(os.Stdin)

	s := readLine(sc)

	fmt.Println(strings.Replace(s, ",", " ", -1))
}

Measured memory_bytes: 640
//============================================================================
#include<bits/stdc++.h>
typedef long long ll;
#define rep(i, n) for(ll i = 0; i < (n); i++)
using namespace std;

int main(){
	int n;
	cin >> n;
	vector<int> x(n);
	vector<int> sorted(n);
	rep(i,n) {
		cin >> x[i];
		sorted[i] = x[i];
	}
	sort(sorted.begin(),sorted.end());
	int med1 = sorted[n / 2 - 1];
	int med2 = sorted[n / 2];
	for(auto&& item : x){
		cout << (item <= med1 ? med2 : med1) << endl;
	}
}


Measured memory_bytes: 3712
MAX=2500
n,a=map(int,input().split())
x=list(map(int,input().split()))
# dp[i][j][k] := x[0:i]のカードからj枚とって合計がkとなる取り方の数
dp = [[[0] * (MAX+1) for _ in range(n+1)] for _ in range(n+1)]
dp[0][0][0] = 1

for i in range(n):
  for j in range(0,n+1):
    for k in range(0, MAX+1):
      dp[i+1][j][k] += dp[i][j][k] # i番目のカードを取らない
  for j in range(1,n+1):
    for k in range(x[i], MAX+1):
      dp[i+1][j][k] += dp[i][j-1][k-x[i]] # i番目のカードを取る

ans = 0
for i in range(1,n+1):
  ans += dp[n][i][a*i]
print(ans)


Measured memory_bytes: 118460
require 'prime'

def calcComb(a, b)
  a - b < b ? calcComb(a, a - b) : (a - b + 1..a).to_a.inject(1, &:*) / (1..b).to_a.inject(1, &:*)
end

mod = 10**9 + 7
n, m = gets.split.map(&:to_i)
pr = m.prime_division
ans = 1
pr.each { |v| ans *= calcComb(n - 1 + v[1], v[1]) % mod } if n != 1
puts ans % mod


Measured memory_bytes: 3964
#include<bits/stdc++.h>
using namespace std;
const int N=100010;
int head[N<<1],to[N<<1],vv[N<<1],w[N<<1],c[N<<1];
int n,m,q,cnt,num;
struct Cz
{
	int dis,pos,val;
}s[N];
int ljb(){
	int u,v;
	scanf("%d%d",&u,&v);
	to[++num]=head[u],head[u]=num,vv[num]=v;
	to[++num]=head[v],head[v]=num,vv[num]=u;
}
int read(int i){
	scanf("%d%d%d",&s[i].pos,&s[i].dis,&s[i].val);
}
void dfs(int x,int ran,int cl){
	if (w[x]>=ran||ran<=0) return;
	w[x]=ran;
	if (!c[x]) c[x]=cl;
	for (int h=head[x],o=vv[h];h;o=vv[h=to[h]]) dfs(o,ran-1,cl);
}
//int 
int main(){
//	freopen("ceshi.txt","r",stdin);
	scanf("%d%d",&n,&m);
	
	for (int i=0;i<m;i++) ljb();
	scanf("%d",&q);cnt=q;
	while (cnt--) 
	   read(cnt);
//	for (int i=0;i<q;i++) 
//	 printf("%d %d %d\n",s[i].dis,s[i].pos,s[i].val);
	for (int i=0;i<q;i++){dfs(s[i].pos,s[i].dis+1,s[i].val);};
	for (int i=1;i<=n;i++) printf("%d\n",c[i]);
}

Measured memory_bytes: 4992
#include <bits/stdc++.h>
#define rep(i, n) for (ll i = 0; i < n; i++)
#define FOR(i, m, n) for(ll i = m;i < n;i++)
#define VSORT(v) sort(v.begin(), v.end());
#define VREV(v) reverse(v.begin(), v.end());
using namespace std;
using ll = long long;
using pll = pair<ll,ll>;
using vll = vector<ll>;
using vdouble = vector<double>;
using vstr = vector<string>;
typedef pair<int,int> P;
int dx[4] = {1, 0, -1, 0},dy[4] = {0, 1, 0, -1};
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;}
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;
const long long MOD = 1000000007;
#include <iostream>

using namespace std;

int main() {
   int n,k;

   string s;
   cin>>n>>s>>k;
   char o=s[k-1];
   rep(i,s.length())
    if(s[i]==o)
     cout<<s[i];
     else
     {
       cout<<"*";
     }
     


   return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
#define pb push_back
#define mp make_pair
#define rep(i,n) for(int i=0;i<(n);++i)
constexpr int mod=1000000007;
constexpr int mod1=998244353;
vector<int> dx={0,1,0,-1},dy={-1,0,1,0};
bool inside(int y,int x,int h,int w){
	if(y<h && y>=0 && x<w && x>=0) return true;
	return false;
}





int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	int h,w,k;cin >> h >> w >> k;
	vector<string> s(h);
	rep(i,h) cin >> s.at(i);
	vector<vector<int>> a(h,vector<int>(w));
	int t = 1;
	rep(i,h){
		rep(j,w){
			if(s[i][j] == '#'){
				a[i][j] = t;
				t++;
			}
		}
	}
	rep(i,h){
		rep(j,w){
			if(a[i][j] != 0){
				for(int x = 0; x < w; x++){
					if(a[i][x] == 0) a[i][x] = a[i][j];
					else if(x > j && a[i][x] != a[i][j]) break;
				}
			}
		}
	}
	rep(j,w){
		for(int i = h - 1; i >= 0; i--){
			if(a[i][j] != 0){
				for(int y = h - 1; y >= 0; y--){
					if(a[y][j] == 0) a[y][j] = a[i][j];
					else if(y <= i && a[y][j] != a[i][j]) break;
				}
			}
		}
	}
	rep(i,h){
		rep(j,w){
			if(j == w - 1) cout << a[i][j] << endl;
			else cout << a[i][j] << " ";
		}
	}
}


Measured memory_bytes: 1280
n, k = map(int, input().split())
li = []
for x in range(k*2):
    li.append(input().split())
li2 = []
i = 1
while i < k*2:
    for j in li[i]:
        li2.append(j)
    i += 2
li2 = set(li2)
print(n - len(li2))

Measured memory_bytes: 9360
#include <vector>
#include <stack>
#include <queue>
#include <list>
#include <bitset>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <iomanip>
#include <string>
#include <chrono>
#include <random>
#include <cmath>
#include <cassert>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <sstream>

using namespace std;


int main(int argc, char** argv) {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int a, b;
    cin >> a >> b;

    if (a % 2 == 1 && b % 2 == 1) {
        cout << "Yes\n";
    } else {
        cout << "No\n";
    }

    return 0;
}

Measured memory_bytes: 256
import math

A,B = (int(x) for x in input().split())
result = False
y = math.ceil(A * 12.5)
z = math.floor((A+1)*12.5)
#if B >= A:

for h in range(y,z):
    #print(h)
    if result == True:
        break

    for i in range(B*10 ,(B+1)*10):
       
        if i == h:
            result = True
            break
       
if result == True:
    print(i)
else:
    print(-1)


Measured memory_bytes: 3060
#![allow(unused)]

//input
//use std::io::Read;

//collections
//use std::collections::BTreeMap;
//use std::collections::BTreeSet;
//use std::collections::HashMap;
//use std::collections::HashSet;

//入力マクロここから
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($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:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}
//入力マクロここまで

fn main() {
    input! {
        h: u64,
        a: u64,
    }
    if h % a == 0 {
        println!("{}", h / a);
    } else {
        println!("{}", h / a + 1);
    }
}

Measured memory_bytes: 4352
//#pragma warning(disable:4996)
//#pragma comment(linker, "/STACK:336777216")
//#pragma GCC optimize("Ofast")

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>

using namespace std;
using namespace __gnu_pbds;

typedef long long ll;
#define int long long int
typedef complex<long double> cd;
const long double pi=acos(-1);
typedef double db;
typedef long double ldb;
typedef pair <int, int> pii;
typedef pair <db, db> pdd;
typedef vector<int> vi;
typedef vector<vector<int> > matrix;

#define m1 make_pair
#define pb push_back
#define flush fflush(stdout)
#define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);
#define reset(x,v) memset(x,v,sizeof(x))
#define sz(x) (int)(x.size())
#define fi first
#define se second
#define endl "\n"
#define debug(x) (cerr << #x << ": " << x << "\n")
#define setbits(x) __builtin_popcount(x)
#define all(x) x.begin(),x.end()
#define pii pair<int,int>

inline ll gcd(ll a,ll b){if(a==0) return b;return gcd(b%a,a);}
inline ll power(ll a,ll n,ll m){if(n==0)return 1;ll p=power(a,n/2,m);p=(p%m*p%m)%m;if(n%2) return (p%m*a%m)%m;else return p;}
const ll MOD =998244353;
const ll hell=1000000007;
const int INF = 1e18;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
typedef tree<int, null_type, less<int>, rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
const int N=200005;

void solve()
{
    int n;
    cin>>n;
    int p[n];
    for(int i=0;i<n;i++)
        cin>>p[i];
    int ans=1;
    int mn=p[0];
    for(int i=1;i<n;i++)
    {
        mn=min(mn,p[i]);
        if(p[i]<=mn)
            ans++;
    }
    cout<<ans;
    cout<<endl;
}

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


Measured memory_bytes: 1792
#include <stdio.h>
#include <cctype>
#include <limits.h>
#include <math.h>
#include <complex>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <iostream>

#define VARIABLE(x) cerr << #x << "=" << x << endl
#define BINARY(x) static_cast<bitset<16> >(x)
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define REP(i,m,n) for (int i=m;i<(int)(n);i++)
#define if_range(x, y, w, h) if (0<=(int)(x) && (int)(x)<(int)(w) && 0<=(int)(y) && (int)(y)<(int)(h))

const int INF = 1e9;
const double EPS = 1e-8;
const double PI = 3.14159;
int dx[4]={0, 1, 0, -1}, dy[4]={-1, 0, 1, 0};
using namespace std;
typedef long long ll;
typedef pair<int, int> P;

/* struct P {
	int x, y, n;
	P(int n, int x, int y):n(n), x(x), y(y){}
	P(){}
}; */


/** Problem1230 : Nim **/
vector<int> lim;
int N;
const int MAX_N = 20, MAX_S = 1<<13;
int dp[MAX_S][MAX_N];


bool isWinning(int n, int p)
{
	if (n==1) return false;
	if (dp[n][p]!=-1) return dp[n][p];
	
	bool res = false;
	for (int i=1; i<=lim[p]; i++) {
		if (n-i>=0)
			res |= !isWinning(n-i, (p+1)%(2*N));
	}
	
	//cerr << n << " " << p << " " << res << endl;
	
	return dp[n][p]=res;
}

int main()
{
	int S;
	while (cin>>N, N) {
		cin>>S;
		memset(dp, -1, sizeof(dp));
		lim.resize(2*N);
		rep(i, 2*N) cin>>lim[i];
		
		cout << isWinning(S, 0) << endl;
	}
}

Measured memory_bytes: 2284
A, B, C, X = 4.times.map{gets.to_i}
cnt = 0
(0..A).each do |i|
  (0..B).each do |j|
    (0..C).each do |k|
      cnt += 1 if i*500 + j*100 + k*50 == X
    end
  end
end
puts cnt

Measured memory_bytes: 1788
li = [int(input()) for _ in range(5)]

sa = 10
count = 0
for i in li:
    count += (10 * (i // 10) )
    if i % 10 != 0:
        count+= 10
        if i % 10 < sa:
            sa = i % 10

if sa == 10:
    print(count)
else:
    print(count - 10 + sa)



Measured memory_bytes: 2940
// abc173_d
#include <bits/stdc++.h>
#ifdef LOCAL
#include "../cxx-prettyprint/prettyprint.hpp"
#endif
using namespace std;

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

#define REP(i, n) for (int (i) = 0 ; (i) < (int)(n) ; ++(i))
#define REPN(i, m, n) for (int (i) = m ; (i) < (int)(n) ; ++(i))
#define REP_REV(i, n) for (int (i) = (int)(n) - 1 ; (i) >= 0 ; --(i))
#define REPN_REV(i, m, n) for (int (i) = (int)(n) - 1 ; (i) >= m ; --(i))
#define ALL(x) x.begin(), x.end()

#define INF (ll)(1e9)
#define MOD (1000000007)

#define print2D(h, w, arr) REP(i, h) { REP(j, w) cout << arr[i][j] << " "; cout << endl; }
#define print_line(vec, n) {for(int i=0;i<(n-1);i++) cout << (vec)[i] << " "; cout << (vec)[(n)-1] << endl;}
template<class T> void print(const T& x){cout << x << endl;}
template<class T, class... A> void print(const T& first, const A&... rest) { cout << first << " "; print(rest...); }
struct PreMain {PreMain(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(20);}} premain;

int main() {
#ifdef LOCAL
    ifstream in("../arg.txt"); cin.rdbuf(in.rdbuf());
#endif

    int N;
    cin >> N;
    vector<ll> A(N);
    REP(i, N) cin >> A[i];
    sort(ALL(A), greater<ll>());

    ll ans = 0;
    REP(i, N){
        if (i == 0){
            ;
        } else if (i == 1){
            ans += A[0];
        } else {
            int idx = i / 2;
            ans += A[idx];
        }
    }
    print(ans);

    return 0;
}


Measured memory_bytes: 4776
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

struct TEdge
{
    int u, v, c, f;
    TEdge *rev = nullptr;
};

const int N = 102;
const int NN = N * N * 2 + N * 2;
const int M = N * N * 10;
const int INF = 1e9;

int h, w, nn, m, s, t;
char a[N][N];
TEdge el[M];
vector<TEdge*> g[NN];
TEdge *pre[NN];

bool Bfs(int s, int t)
{
    fill(pre+1, pre+1+nn, nullptr);
    queue<int> q;
    q.push(s);
    while (!q.empty())
    {
        int u = q.front(); q.pop();
        for (auto e: g[u])
            if (!pre[e->v] && e->f < e->c && e->v != s) q.push(e->v), pre[e->v] = e;
    }
    return pre[t] != nullptr;
}

void AddEdge(int u, int v, int c)
{
    el[m]   = {u, v, c, 0, el+m+1};
    el[m+1] = {v, u, 0, 0, el+m};
    g[u].push_back(el+m);
    g[v].push_back(el+m+1);
    m += 2;
}

int EdmondsKarp()
{
    int flow = 0;
    while (Bfs(s, t))
    {
        int maxflow = INF;
        for (auto e = pre[t]; e != nullptr; e = pre[e->u]) maxflow = min(maxflow, e->c - e->f);
        for (auto e = pre[t]; e != nullptr; e = pre[e->u]) e->f += maxflow, e->rev->f -= maxflow;
        flow += maxflow;
    }
    return flow;
}

int Conv(int i, int j, int layer) {return (i-1) * w + j + (layer ? h * w : 0);}
int Row(int i) {return h * w * 2 + i;}
int Col(int i) {return h * w * 2 + h + i;}

void Solve()
{
    for (int i = 1; i <= h; ++i)
        for (int j = 1; j <= w; ++j)
            if (a[i][j] == 'S') s = Conv(i, j, 0); else
            if (a[i][j] == 'T') t = Conv(i, j, 1);

    nn = h * w * 2 + h + w;

    for (int i = 1; i <= h; ++i)
        for (int j = 1; j <= w; ++j)
            if (a[i][j] != '.')
            {
                AddEdge(Conv(i, j, 1), Conv(i, j, 0), 1);
                AddEdge(Conv(i, j, 0), Row(i), INF);
                AddEdge(Conv(i, j, 0), Col(j), INF);
                AddEdge(Row(i), Conv(i, j, 1), INF);
                AddEdge(Col(j), Conv(i, j, 1), INF);
            }
    int mincut = EdmondsKarp();
    if (mincut >= INF) printf("-1");
    else printf("%d",mincut);
}

int main()
{
    scanf("%d %d", &h, &w);
    for (int i = 1; i <= h; ++i) scanf("%s",a[i]+1);
    Solve();
    return 0;
}


Measured memory_bytes: 4736
#import sys
#import numpy as np
#import math
#import itertools
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
#from fractions  import gcd
#input=sys.stdin.readline
#import bisect

n,s=map(int,input().split())
a=list(map(int,input().split()))
mod=998244353

dp=[[0]*3001 for _ in range(n+1)]
dp[0][0]=1
res={i for i in range(1,n+1)}
for i in range(1,n+1):
    for j in range(3001):
        if j>=a[i-1] and dp[i-1][j-a[i-1]]!=0:
            dp[i][j]=(2*dp[i-1][j]+dp[i-1][j-a[i-1]])%mod
           
        else:
            dp[i][j]=(2*dp[i-1][j])%mod
ans=0
print(dp[n][s])

Measured memory_bytes: 139704
#include <bits/stdc++.h>
#define For(i, a, b) for(int (i)=(int)(a); (i)<(int)(b); ++(i))
#define rFor(i, a, b) for(int (i)=(int)(a)-1; (i)>=(int)(b); --(i))
#define rep(i, n) For((i), 0, (n))
#define rrep(i, n) rFor((i), (n), 0)
#define fi first
#define se second
using namespace std;
typedef long long lint;
typedef unsigned long long ulint;
typedef pair<int, int> pii;
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<class T> T div_floor(T a, T b){
    if(b < 0) a *= -1, b *= -1;
    return a>=0 ? a/b : (a+1)/b-1;
}
template<class T> T div_ceil(T a, T b){
    if(b < 0) a *= -1, b *= -1;
    return a>0 ? (a-1)/b+1 : a/b;
}

constexpr lint mod = 1e9+7;
constexpr lint INF = mod * mod;
constexpr int MAX = 100010;

int main(){
    string s;
    int q;
    cin >> s >> q;
    int flip = false;
    string head, tail;

    rep(_, q){
        int t;
        scanf("%d", &t);
        if(t == 1){
            flip ^= 1;
        }
        else{
            int f;
            char c;
            scanf("%d %c", &f, &c);
            if((f == 1 && !flip) || (f == 2 && flip)) head += c;
            else tail += c;
        }
    }
    reverse(head.begin(), head.end());
    s = head + s + tail;
    if(flip) reverse(s.begin(), s.end());
    cout << s << "\n";
}

Measured memory_bytes: 1348
n, m = gets.split.map(&:to_i)
ab = n.times.map{ gets.split.map(&:to_i) }.sort

sum = 0

n.times do |i|
  price = ab[i][0]
  num = ab[i][1]

  if m > num
    sum += num*price
    m -= num
  else
    sum += m*price
    break
  end
end

puts sum

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

//#pragma GCC optimize("O3,Ofast,no-stack-protector,unroll-loops,fast-math")

#define int long long
typedef pair <int, int> pii;
const int maxn = 2e5 + 5;
string s[10];

int32_t main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
//	long double l;
	int n, m, k;
	cin >> n >> m >> k;
	for (int i = 0; i < n; i++) {
		cin >> s[i];
	}
	int ans = n + m + 5;
	for (int mask = 0; mask < (1 << (n - 1)); mask++) {
		int b = __builtin_popcount(mask), a[b + 2], e[b + 1];
		for (int i = 0; i <= b; i++)
			a[i] = 0;
		for (int i = 0; i < m; i++) {
			fill(e, e + __builtin_popcount(mask) + 1, 0);
			int c = 0;
			for (int j = 0; j < n; j++) {
				e[c] += (s[j][i] == '1');
				a[c] += (s[j][i] == '1');
//				cout << mask << ' ' << i << ' ' << c << ' ' << a[c] << endl;
				if (mask & (1 << j)) {
//					cout << mask << ' ' << i << ' ' << c << ' ' << a[c] << endl;
					c++;
				}
			}
			if (*max_element(e, e + __builtin_popcount(mask) + 1) > k)
				b = n + m + 3;
			bool f = 0;
			for (int j = 0; j <= __builtin_popcount(mask); j++) {
				if (a[j] > k) {
//					if (!mask)
//						cout << "S" << endl;
					f = 1;
					break;
				}
			}
			if (f) {
//				cout << "S " << mask << ' ' << i << endl;
				b++;
				c = 0;
				fill(a, a + __builtin_popcount(mask) + 1, 0);
				for (int j = 0; j < n; j++) {
					a[c] += (s[j][i] == '1');
					if (mask & (1 << j)) {
						c++;
					}
				}
			}
		}
//		cout << mask << ' ' << b << endl;
		ans = min(ans, b);
	}
	cout << ans;
}


Measured memory_bytes: 256
from sys import stdout
printn = lambda x: stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True # and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n,c = inm()
a = []
for i in range(n):
    s,t,c = inm()
    a.append((t,s,c))
a.sort()

h = {}  # h[(t,c)] = s
for z in a:
    t,s,c = z
    if (s,c) in h:
        s0 = h[(s,c)]
        del h[(s,c)]
        h[(t,c)] = s0
    else:
        h[(t,c)] = s

a = []
for z in h:
    t,c = z
    s = h[z]
    a.append((t,s,c))

a.sort()
#ddprint(a)
n = len(a)
nu = 0
ut = [-1]*n
uc = [-1]*n
for i in range(n):
    t,s,c = a[i]
    #ddprint("lp t {} s {} c {} i {}".format(t,s,c,i))
    mx = -1
    for j in range(nu):
        if ut[j] <= s-1 and ut[j]>mx:
            mx = ut[j]
            mxj = j
            if False:
                ddprint("t {} s {} c {} j {}".format(t,s,c,j))
                ddprint(ut)
                ddprint(uc)
    if mx == -1:
        mxj = nu
        nu += 1
    ut[mxj] = t
    uc[mxj] = c
    #ddprint(mxj)
print(nu)


Measured memory_bytes: 88532
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll LIS(vector<int> arr){
  vector<int> dp(arr.size());
  int res = 1;
  dp[0] = 1;

  for(int i = 1;i < arr.size();i++){
    dp[i] = 1;
    for(int j = 0;j < i;j++){
      if(arr[j] < arr[i]){
        dp[i] = max(dp[i], dp[j] + 1);
      }
    }
    res = max(res, dp[i]);
  }
  return res;
}
ll LDS(vector<int> arr){
  reverse(arr.begin(), arr.end());
  return LIS(arr);
}
int main(){
//  freopen("connect.in", "r", stdin);
//  freopen("connect.out", "w", stdout);
//  freopen("in.txt", "r", stdin);
//  freopen("out.txt", "w", stdout);
  int n, a, b;
  cin >> n >> a >> b;
  if(a + b > n + 1 || a == 1 && b != n || b == 1 && a != n){
    cout << -1;
    return 0;
  }
  vector<int> arr(n);
  for(int i = 0;i < arr.size();i++)
    arr[i] = i + 1;
  int ca, cb;
  ca = n, cb = 1;
  reverse(arr.begin(), arr.begin() + b);
  cb = b, ca -= b - 1;
  int cur = b;
  while(ca != a && cur < arr.size()){
    reverse(arr.begin() + cur, arr.begin() + cur + min(n - cur, min(ca - a + 1, b)));
//    swap(arr[cur], arr[cur + 1]);
    int x = min(n - cur, min(ca - a + 1, b));
    ca -= x - 1;
    cur += x;
  }
  if(ca != a){
    cout << -1;
  }else{
//    assert(LIS(arr) == a);
//    assert(LDS(arr) == b);
    for(auto el : arr)
      printf("%d ", el);
  }
}


Measured memory_bytes: 3328
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <climits>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <stack>
#include <queue>
#include <algorithm>
#include <iostream>
#include <string>

#define REP(i,n) for(auto i=0;i<n;++i)
#define REPR(i,n) for(auto i=n;i>=0;--i)
#define REPI(itr,v) for(auto itr=v.begin();itr!=v.end();++itr)
#define REPIR(itr,v) for(auto itr=v.rbegin();itr!=v.rend();++itr)
#define FOR(i,a,b) for(auto i=a;i<b;++i)
#define SORT(v,n) sort(v, v+n)
#define SORTV(v) sort(v.begin(), v.end())
#define ALL(v) v.begin(),v.end()
#define llong long long
#define ll long long
#define INF 999999999
#define MOD 1000000007
#define pb push_back
#define pf push_front
#define MP make_pair
#define SV(n,v) {int tmp;for(int i=0;i<n;++i){scanf("%d",&tmp);v.push_back(tmp);}}

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

using namespace std;

typedef pair<int,int> pii;

int main(){

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

  vector<llong> x(n), y(n), h(n);
  REP(i,n){
    scanf("%lld %lld %lld", &x[i], &y[i], &h[i]);
  }

  llong ans = -1;
  bool f;
  REP(i,101){
    REP(j,101){
      f = true;
      REP(k,n){
        if(h[k] == 0){
          continue;
        }
        ans = h[k] + abs(x[k] - i) + abs(y[k] - j);
        if(ans < 1){
          continue;
        }else{
          break;
        }
      }
      for(int k=0;k<n;++k){
        llong dis = max(ans - abs(x[k] - i) - abs(y[k] - j), (llong)0);
        if(dis != h[k]){
          f = false;
          break;
        }
      }
      if(f){
        printf("%d %d %lld\n", i, j, ans);
        return 0;
      }
    }
  }
  return 0;
}



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


int main()
{
    string S;
    string T;

	cin >> S;
    cin >> T;
    
    T.pop_back();

    if (S == T)
    {
        cout << "Yes";
    }
    else
    {
        cout << "No";
    }
    
    
    return 0;
}

Measured memory_bytes: 3512
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp15
{
    class Class234
    {
        static void Main()
        {
            var DG = Console.ReadLine().Split().Select(long.Parse).ToArray();
            int D =(int) DG[0];long G = DG[1];
            int[] p = new int[D];
            long[] c = new long[D];
            for (int i = 0; i < D; i++)
            {
                var r = Console.ReadLine().Split();
                p[i] = int.Parse(r[0]);
                c[i] = long.Parse(r[1]);
            }

            int maxcount = int.MaxValue;
            for(int i = 0; i < (1 << D); i++)
            {
                long sum = 0;
                int count = 0;
                for(int j = 0; j < D; j++)
                {
                    if ((i & (1 << j)) > 0)
                    {
                        sum += c[j] + p[j]*(j+1)*100;
                        count += p[j];
                    }
                }
                if (sum < G) 
                {
                    for(int j = D-1; ; j--)
                    {
                        if ((i & (1 << j)) == 0)
                        {
                            for(int k = 0; k < p[j] && sum < G; k++)
                            {
                                count++;
                                sum += (j + 1) * 100;
                            }
                            break;
                        }
                    }
                    
                }
                if(sum>=G)
                maxcount = Math.Min(count, maxcount);
            }
            Console.WriteLine(maxcount);
        }
    }
}


Measured memory_bytes: 13396
/*
 * ABC96C.cpp
 *
 *  Created on: May 5, 2018
 *      Author: 13743
 */

#include<cstdio>
#include<algorithm>

using namespace std;

int h, w;

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

	bool grid[52][52] = {0};

	char s[100];
	for(int i=1; i<=h; i++) {
		scanf("%s", s);
		for(int j=1; j<=w; j++) {
			grid[i][j] = (s[j-1] == '#') ? 1 : 0;
		}
	}

	for(int i=1; i<=h; i++) {
		for(int j=1; j<=w; j++) {
			if(grid[i][j]==1 && grid[i-1][j]==0&&grid[i][j-1]==0&&grid[i+1][j]==0&&grid[i][j+1]==0) {
				printf("No\n"); return 0;
			}
		}
	}

	printf("Yes\n");
}




Measured memory_bytes: 128
n=int(input())
a=list(map(int,input().split()))
x=[0 for i in range(n)]
x[0]=0
for i in range(1,n):
  idx_n=i%n
  x[idx_n] = (a[idx_n-1]-x[idx_n-1]//2)*2
y=(a[-1]-x[-1]//2)*2
x[0]=y//2
for i in range(1,n):
  idx_n=i%n
  x[idx_n] = (a[idx_n-1]-x[idx_n-1]//2)*2
print(' '.join(map(str,x)))

Measured memory_bytes: 19132
#include <iostream>
#include<math.h>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	int n, m, x, y;
	cin >> n >> m >> x >> y;
	int f_city[2][100];
	int x_min = -100;
	int y_max = 100;
	for (int i = 0; i < n; ++i) {
		cin >> f_city[0][i];
		x_min = max(f_city[0][i], x_min);
	}
	for (int j = 0; j < m; ++j) {
		cin >> f_city[1][j];
		y_max = min(f_city[1][j], y_max);
	}

	for (int i = x + 1; i <= y; ++i) {
		if (x >= y_max) {
			cout << "War" << endl;
          break;
		}
		else if (y <= x_min) {
			cout << "War" << endl;
          break;
		}else
		if (x_min < i && y_max >= i) {
			cout << "No War" << endl;
			break;
		}
		else if(y_max < i) {
			cout << "War" << endl;
			break;
		}
		else if (i < x_min && i == y) {
			cout << "War" << endl;
			break;
		}
	}

	
	return 0;
	
}


Measured memory_bytes: 256
const main = (input) => {
    input = input.split(' ');
    const S = parseInt(input[0]);
    const W = parseInt(input[1]);

    if (S <= W) {
        console.log('unsafe');
    } else {
        console.log('safe');
    }
};

// 標準入力
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Measured memory_bytes: 29612
n = int(input())
al = list(int(input()) for _ in range(n))
num = [0]*n
i = 0
cnt = 0
while True:
    if al[i] == 2:
        print(cnt+1)
        break
    else:
        if num[al[i]-1] == 1:
            print(-1)
            break
        else:
            num[al[i]-1] += 1
            i = al[i]-1
            cnt += 1


Measured memory_bytes: 13676
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;

public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		
		// 入力
		int n = sc.nextInt();
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		for(int i = 0; i < n; i++){
		    String w = sc.next();
		    if(map.containsKey(w)){
		        map.put(w, map.get(w) + 1);
		    }else{
		        map.put(w, 1);
		    }
		}
		int m = sc.nextInt();
		for(int i = 0; i < m; i++){
		    String w = sc.next();
		    if(map.containsKey(w)){
		        map.put(w, map.get(w) - 1);
		    }
		}
		
		// 計算
		int result = 0;
		for(Integer cnt : map.values()){
		    result = max(result, cnt);
		}
		
		// 出力
		System.out.println(result);
	}
}




Measured memory_bytes: 21716
/*
https://atcoder.jp/contests/dp/tasks/dp_e
*/
#include<bits/stdc++.h>
#define ll long long int
#define inf 1e9+1
using namespace std;


int main(){

    int n,w;  cin>>n>>w;
    int wt[n],val[n];

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

    /// Due to large constrains on weight 10^9 we can't use DP of n,wt so we will use value as it can be upto 1000 only
    /// DP[N][V] denotes that min weight required to get value V given N elements

    /// Base case will be DP[1][x] = w1 only if x = v1 else INT_MAX and DP[1][0] = 0 that is we dont choose any value so no weight is required

    int maxVal = n * 1000;

    int dp[n+1][maxVal+1];

    for(int i=0;i<=maxVal;i++){
        dp[1][i] = inf;
    }

    dp[1][0] = 0;
    dp[1][val[0]] = wt[0];


    for(int i=2;i<=n;i++){
        for(int j=0;j<=maxVal;j++){
            dp[i][j] = dp[i-1][j];
            if(val[i-1] <= j){
                dp[i][j] = min(dp[i][j],wt[i-1] + dp[i-1][j-val[i-1]]);
            }
        }
    }

    int ans = 0;

    for(int i=0;i<=maxVal;i++){
        if(dp[n][i] <= w)
            ans = i;
    }

    cout<<ans<<"\n";

return 0;
}


Measured memory_bytes: 39296
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN=100005;
 
int N;
vector<int> adj[MAXN];
int col[MAXN];
 
bool dfs(int u,int f)
{
    if(adj[u].size()==1U)
    {
        col[u]=0;
        return false;
    }
    int cnt[2]={0};
    for(int i=0;i<(int)adj[u].size();i++)
    {
        int v=adj[u][i];
        if(v==f)
            continue;
        if(dfs(v,u))
            return true;
        cnt[col[v]]++;
    }
    if(cnt[0]>=2)
        return true;
	if(f==0&&(int)adj[u].size()==cnt[1])
		return true;
    if(cnt[0])
        col[u]=1;
    else
        col[u]=0;
    return false;
}
 
int main()
{
    scanf("%d",&N);
    for(int i=1;i<N;i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    if(N==2)
        puts("Second");
    else
    {
        bool ans;
        for(int i=1;i<=N;i++)
            if(adj[i].size()>1U)
            {
                ans=dfs(i,0);
                break;
            }
        puts(ans?"First":"Second");
    }
    return 0;
}

Measured memory_bytes: 6144
#include <bits/stdc++.h>
#define ll long long
using namespace std;
vector<vector<ll>>graph;
void dfs(ll u, vector<int>&vis)
{
        vis[u]=1;
        for(auto v:graph[u])
        {
            if(vis[v]==1)
                continue;
            dfs(v,vis);
        }

}
int main(){
    ll n,m;
    cin>>n>>m;
    graph.resize(n+1);
    for(ll i=0;i<m;i++){
        ll u,v;
        cin>>u>>v;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    vector<int>vis(n+1);
    ll cnt=0;
    for(ll i=1;i<=n;i++)
    {
        if(vis[i]==1)
            continue;
       cnt++;
       dfs(i,vis);
   }    
   cout<<cnt-1;
 }

Measured memory_bytes: 10388
#include <bits/stdc++.h>
using LL = long long;
using namespace std;
int main() {
	int n, p; cin >> n >> p;
	string s; cin >> s;
	LL ans = 0;
	if (p == 2 or p == 5) {
		for (int i = 0; i < n; i++) 
			if ((s[i] - '0') % p == 0) ans += i + 1;
	} else {
		map<int, LL> mp;
		mp[0] = 1;
		LL sum = 0, power = 1;
		for (int i = n - 1; i >= 0; i--) {
			sum = (sum + (s[i] - '0') * power) % p;
			ans += mp[sum % p]++;
			power = power * 10 % p;
		}
	}
	cout << ans;	
}

Measured memory_bytes: 1028
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        NodeList node = new NodeList();
        int n = Integer.parseInt(scan.next());
        int x;
        char[] query = new char[15];
        for(int i=0; i<n; i++) {
            switch (scan.next()) {
                case "insert":
                    node.Insert(Integer.parseInt(scan.next()));
                    break;
                case "delete":
                    node.SearchDelete(Integer.parseInt(scan.next()));
                    break;
                case "deleteFirst":
                    node.DeleteFirst();
                    break;
                case "deleteLast":
                    node.DeleteLast();
                    break;
            }
        }
        node.Print();
    }

}

class Node{
    int key ;
    Node right;
    Node left;

    Node(int key){
        this.key = key;
    }
}

class NodeList{
    Node head;

    NodeList(){
        this.head = new Node(-1);
        this.head.right = this.head;
        this.head.left = this.head;
    }

    void Insert(int x){
        Node newNode = new Node(x);
        newNode.right = this.head.right;
        newNode.right.left = newNode;
        this.head.right = newNode;
        newNode.left = this.head;
    }

    void Print(){
        PrintWriter out = new PrintWriter(System.out);
        for(Node point = this.head.right; point != this.head.left; point = point.right) {
            out.print(point.key + " ");
        }
        out.println(this.head.left.key);
        out.flush();
    }

    void Delete(Node point){
        point.right.left = point.left;
        point.left.right = point.right;
    }

    void SearchDelete(int x){
        for(Node point = this.head.right; point != this.head; point = point.right) {
            if(point.key == x){this.Delete(point); break;}
        }
    }

    void DeleteFirst(){
        this.Delete(this.head.right);
    }

    void DeleteLast(){
        this.Delete(this.head.left);
    }

}





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

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 FORR(i,m,n) for(int i=(m) ; i>=(n) ; i--)

#define All(x) (x).begin(),(x).end()

typedef long long ll;
typedef unsigned long long ull;

const int INF = 1e9;

int main(){
   int a,b,t;
   cin >> a >> b >> t;
   cout << (t / a) * b << endl;
   return 0;
}

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

using namespace std;
typedef long long ll;

ll H,W;
ll m[10][10];
ll A[210][210];

int main(){
    cin >> H >> W;
    for(int i=0;i<10;i++){
        for(int j=0;j<10;j++){
            cin >> m[i][j];
        }
    }
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            cin >> A[i][j];
        }
    }
    for(int i=0;i<10;i++){
        for(int j=0;j<10;j++){
            for(int k=0;k<10;k++){
                m[j][k] = min(m[j][k], m[j][i] + m[i][k]);
            }
        }
    }
    ll sum = 0;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            if(A[i][j] == -1) continue;
            sum += m[A[i][j]][1];
        }
    }
    cout << sum << endl;
    return 0;
}

Measured memory_bytes: 640
#include<bits/stdc++.h>
using namespace std;
struct State{
    int num,cost;
    bool operator < (const State &obj)const{
        if(cost != obj.cost) return cost > obj.cost;
        return false;
    }
};
int mini[21];

int main(){
    int n,m;
    scanf("%d",&n);
    vector<State> costs[n+1];
    scanf("%d",&m);
    for(int i=0;i<m;++i){
        int a,b,c,d;
        scanf("%d,%d,%d,%d",&a,&b,&c,&d);
        costs[a].push_back((State){b,c});
        costs[b].push_back((State){a,d});
    }
    int s,g,v,p;
    scanf("%d,%d,%d,%d",&s,&g,&v,&p);
    int wayToG, wayToS;
    for(int j=0;j<2;++j){
        for(int i=0;i<=n;++i)mini[i]=INT_MAX;
        priority_queue<State> Q;
        if(j==0){
            mini[s] = 0;
            Q.push((State){s,0});
        }
        else{
            mini[g] = 0;
            Q.push((State){g,0});
        }
        while(!Q.empty()){
            State now = Q.top();
            Q.pop();
            int oldNum = now.num, oldCost = now.cost;
            if(j == 0 && oldNum == g){
                wayToG = oldCost;
                break;
            }
            else if(j == 1 && oldNum == s){
                wayToS = oldCost;
                break;
            }
            for(int i=0;i<costs[oldNum].size();++i){
                int newNum = costs[oldNum][i].num;
                int newCost = oldCost + costs[oldNum][i].cost;
                if(newCost < mini[newNum]){
                    mini[newNum] = newCost;
                    Q.push((State){newNum,newCost});
                }
            }
        }
    }
    printf("%d\n",v-(p+wayToS+wayToG));

    return 0;
}

Measured memory_bytes: 1212
#include <bits/stdc++.h>
#define rep(i, m, n) for(int i = m; i < (n); i++)
#define print(x) cout << (x) << endl;
#define printv(x) for(int i = 0; i < x.size(); i++){ cout << (x[i]) << " "; } cout << endl; 
#define printa(x) for(int i = 0; i < (sizeof(x)/sizeof(x[0])); i++){ cout << (x[i]) << " ";} cout << endl;
#define printaa(x) for(int i = 0; i < (sizeof(x)/sizeof(x[0])); i++){ for(int j = 0; j < (sizeof(x[0])/sizeof(x[0][0])); j++){ cout << x[i][j] << " ";} cout << endl;}
#define INF (1e9)
typedef long long ll;
typedef struct{
    int x;
    int y;
} P;

using namespace std;

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N,M;
    int L[200001],R[200001],D[200001];
    cin >> N >> M;
    rep(i,0,M){
        cin >> L[i] >> R[i] >> D[i];
    }
    int x[100001];
    rep(i,1,N+1){
        x[i] = INF;
    }
    vector<vector<P> > v(200001);
    rep(i,0,M){
        P tmp = {L[i],D[i]};
        P tmp2 = {R[i], -1*D[i]};
        v[R[i]].push_back(tmp);
        v[L[i]].push_back(tmp2);
    }
    // rep(i,1,N+1){
    //     rep(j,0,v[i].size()){
    //         cout << v[i][j].x << " " << v[i][j].y << endl;
    //     }
    //     print("---");
    // }
    int is_visit[100001] = {};
    stack<int> s;
    bool is_ok = true;
    rep(i,1,N+1){
        // rep(i,1,N+1){
        //     cout << is_visit[i] << " ";
        // }
        // cout << endl;
        if(is_visit[i] == 0){
            s.push(i);
            // cout << "n = " << i << endl;
            x[i] = 0;
            while(1){
                if(s.empty()) break;
                int next = s.top();
                s.pop();
                // print(next);
                if(is_visit[next] == 1) continue;
                is_visit[next] = 1;
                rep(j,0,v[next].size()){
                    s.push(v[next][j].x);
                    if(x[v[next][j].x] == INF){
                        x[v[next][j].x] = x[next] - v[next][j].y;
                    }
                    if(x[v[next][j].x] != INF && x[next] != INF && x[next] - x[v[next][j].x] != v[next][j].y){
                        is_ok = false;
                    }
                }

            }
        }
    }
    if(!is_ok){
        print("No");
    }else{
        print("Yes");
    }

}


Measured memory_bytes: 14976
N, K = map( int, input().split())
T = [(0,0)]*N
for i in range(N):
    t, d = map( int, input().split())
    T[i] = (d,t)
T.sort( key= None, reverse = True)
C = T[:K]
AC = T[K:]
kiso = 0
s = 0
S = [0]*(N+1)
for i in range(K):
    d, t = T[i]
    kiso += d
    if S[t] == 0:
        S[t] = 1
        s += 1
    else:
        S[t] += 1
ans = kiso + s**2
C.sort()
r = 0

for i in range(K):
    d, t = C[i]
    if S[t] >= 2:
        while r < N-K:
            if S[ AC[r][1]] == 0:
                S[t] -= 1
                S[ AC[r][1]] += 1
                s += 1
                kiso -= d
                kiso += AC[r][0]
                r += 1
                break
            r += 1
    ans = max( ans, kiso + s**2)
print( ans)


Measured memory_bytes: 20236
#include <iostream>
#include <math.h>
#include <numeric>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <queue>
#include <queue>
#include <stack> 
#include <sstream>
#include <set>

typedef  long long ll;
const int dx[8]={1,0,-1,0,1,-1,-1,1};
const int dy[8]={0,1,0,-1,1,1,-1,-1};
const int dr[4] = {-1, 0, 1, 0};
const int dc[4] = { 0, 1, 0,-1};
const int INF = 1e9;
#define FOR(i, a, n) for(int i = (int)(a); i < (int)(n); ++i)
#define REP(i, n) FOR(i, 0, n)
#define SORT(a) sort(a.begin(),a.end())
#define REVERSE(a) reverse(a.begin(),a.end())
int guki (int a){
    if(a%2==0) return 0;
    else return 1;
}
int gcd(int a, int b){
    if(a%b==0){
        return b;
    }else{
        return (gcd(b,a%b));
    }
}
int lcm(int a, int b){
    int x = gcd(a,b);
    return (a*b/x);
}

using namespace std;


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

    int x = d *2 + 1;
    int l = x;

    int ans = 1;
    while (n > x){
        ans ++;
        x += l;
    }

    cout << ans  <<endl;
}






Measured memory_bytes: 256
#include <bits/stdc++.h>
#if 1
#define int long long
#define MAX LLONG_MAX
#define MIN LLONG_MIN
#define stoi stoll
#else
#define MAX INT_MAX
#define MIN INT_MIN
#endif
#define ALL(obj) (obj).begin(), (obj).end()
#define fi first
#define se second
const int NIL = -1;
const int MOD = 1000000007;
#define REP(i,n) for (int i=0; i < (n); ++i)
#define FOR(i,a,b) for (int i=(a); i < (b); ++i)
using namespace std;

int get_gcd(int a, int b){while(1){if (a < b) swap(a, b); if (b == 0) return a; a %= b;}}
int get_lcm(int a, int b){return a * b / get_gcd(a, b);}
//int dx[4]={1,0,-1,0};
//int dy[4]={0,1,0,-1};

//-------------------------テンプレここまで-------------------------//

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

int w, h;
// 0なら海、1なら陸（未探索)
bool field[50][50];
// 探索済かどうか
bool seen[50][50];

void dfs(int i, int j){
  seen[i][j] = true;

  REP(k,8) {
    int ni = i+dx[k];
    int nj = j+dy[k];
    if (ni<0 || ni>=h || nj<0 || nj>=w) continue;
    if (!field[ni][nj] || seen[ni][nj]) continue;
    dfs(ni, nj);
  }
}

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

  while(1) {
    cin >> w >> h;
    if(w==0 && h==0) break;

    REP(i,h) {
      REP(j,w) {
        cin >> field[i][j];
        seen[i][j] = false;
      }
    }

    int ans = 0;
    REP(i,h) {
      REP(j,w) {
        if (!field[i][j] || seen[i][j]) continue;
        dfs(i,j);
        ans++;
        //cout << i << " " << j << endl;
      }
    }

    cout << ans << endl;
  }

  return 0;
}



Measured memory_bytes: 3172