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

int main(){
  int N,A,B,res = -1,diff,direc,small,big;
  cin >> N >> A >> B;
  if((B - A)%2 != 0){
  	diff = (B - A) -1;
    direc = min((A -1) , (N - B));
   // cout << direc << endl;
    res = direc + 1;
    if(A-direc == 1){
   		A -= direc,B -= direc;
      	B -= 1;
    }else if(B+direc == N){
    	A += direc,B += direc;
      	A += 1;
    }
//	cout << small <<" " << big << " " << diff << " " << direc;
    res += diff / 2;
  }else{
  	res = (B - A)/2;
  }
  cout << res << endl;
}


/************************************************************
	> File Name: a.cpp
	> Author: TSwiftie
	> Mail: 2224273204@qq.com
	> Created Time: Sat 28 Dec 2019 08:02:18 PM CST
************************************************************/

#pragma GCC optimize(2)
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <iomanip>
//#include <unordered_map>
#define lowbit(x) (x&-x)
#define lc (o<<1)
#define rc (o<<1|1)
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5+5;
const int MAXM = 2e5+5;
const int MOD = 1e9+7;
const int dir[4][2] = {1,0,-1,0,0,1,0,-1};
const double PI = acos(-1.0);
const double EXP = 1e-8;
int main(void){
	int n, a, b;
	cin >> n >> a >> b;
	if(a > b)
		swap(a,b);
	if((b-a)%2==0)
		cout << (b-a)/2 << endl;
	else{
		cout << min((n-b)+ceil(1.0*(b-a)/2),(a-1)+ceil(1.0*(b-a)/2)) << endl;
	}
	return 0;
}

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

Score : 300 points

Problem Statement

2N players are running a competitive table tennis training on N tables numbered from 1 to N.

The training consists of rounds.
In each round, the players form N pairs, one pair per table.
In each pair, competitors play a match against each other.
As a result, one of them wins and the other one loses.

The winner of the match on table X plays on table X-1 in the next round,
except for the winner of the match on table 1 who stays at table 1.

Similarly, the loser of the match on table X plays on table X+1 in the next round,
except for the loser of the match on table N who stays at table N.

Two friends are playing their first round matches on distinct tables A and B.
Let's assume that the friends are strong enough to win or lose any match at will.
What is the smallest number of rounds after which the friends can get to play a match against each other?

Constraints

2 \leq N \leq 10^{18}

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the smallest number of rounds after which the friends can get to play a match against each other.

Sample Input 1

5 2 4

Sample Output 1

1

If the first friend loses their match and the second friend wins their match, they will both move to table 3 and play each other in the next round.

Sample Input 2

5 2 3

Sample Output 2

2

If both friends win two matches in a row, they will both move to table 1.

Submitted source-code file size, in bytes.

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

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


#include "bits/stdc++.h"

using namespace std;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<VVI> VVVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef vector<PII> VPII;
typedef long long LL;
typedef priority_queue<int> PQ_DESC;
typedef priority_queue<int, vector<int>, greater<int>> PQ_ASC;
typedef priority_queue<PII> PQ_DESC_PII;
typedef priority_queue<PII, vector<PII>, greater<PII>> PQ_ASC_PII;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;
typedef vector<VVLL> VVVLL;

#define SORT_ASC(c) sort((c).begin(), (c).end())
#define SORT_DESC(c) sort((c).begin(), (c).end(), greater<typeof((c).begin())>())

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define FORL(i,a,b) for(LL i=(a);i<(b);++i)
#define REPL(i,n)  FORL(i,0,n)
#define SIZE(a) int((a).size())
#define ALL(a) (a).begin(),(a).end()

const double EPS = 1e-10;
const double PI  = acos(-1.0);
const int INT_LARGE = 1000000100;

//debug func
template<typename T>
void vecprint(vector<T> v) {
    for(auto x : v) {
        cerr << x << " ";
    }
    cerr << endl;
}

template<typename T>
void vecvecprint(vector<vector<T>> vv) {
    REP(i, SIZE(vv)) {
        REP(j, SIZE(vv[i])) {
            cerr << vv[i][j] << " ";
        }
        cerr << endl;
    }
}

template<typename T>
void pqprint(priority_queue<T> q) {
    while(!q.empty()) {
        cerr << q.top() << " ";
        q.pop();
    }
    cerr << endl;
}

template<typename T>
void qprint(queue<T> q) {
    while(!q.empty()) {
        cerr << q.front() << " ";
        q.pop();
    }
    cerr << endl;
}

template<typename T>
void vecqprint(vector<queue<T>> v) {
    for(int i = 0; i < v.size(); i++) {
        qprint(v[i]);
    }
}

template <typename Iterator>
inline bool next_combination(const Iterator first, Iterator k, const Iterator last)
{
   /* Credits: Thomas Draper */
   if ((first == last) || (first == k) || (last == k))
      return false;
   Iterator itr1 = first;
   Iterator itr2 = last;
   ++itr1;
   if (last == itr1)
      return false;
   itr1 = last;
   --itr1;
   itr1 = k;
   --itr2;
   while (first != itr1)
   {
      if (*--itr1 < *itr2)
      {
         Iterator j = k;
         while (!(*itr1 < *j)) ++j;
         iter_swap(itr1,j);
         ++itr1;
         ++j;
         itr2 = k;
         rotate(itr1,j,last);
         while (last != j)
         {
            ++j;
            ++itr2;
         }
         rotate(k,itr2,last);
         return true;
      }
   }
   rotate(first,k,last);
   return false;
}

inline double get_time_sec(void){
    return static_cast<double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count())/1000000000;
}

template<typename T>
T gcd(T a, T b) {
    if(a > b) swap(a, b);
    if(a == 0) return b;
    else return gcd(b%a, a);
}

template<typename T>
map<T, T> prime_list(T n) {
    map<T, T> ret;
    for(T i = 2; i*i <= n; i++) {
        if(n % i == 0) {
            ret[i] = 0;
            while(n % i == 0) {
                n /= i;
                ret[i]++;
            }
        }
    }
    if(n != 1) ret[n]++;
    return ret;
}

int main(void) {
    LL n, a, b;
    cin >> n >> a >> b;
    if((b - a) % 2 == 0) {
        cout << (b - a) / 2 << endl;
        return 0;
    }
    cout << min(a + (b - a - 1) / 2, (n - b) + 1 + (b - a - 1) / 2) << endl;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;

#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define X first
#define Y second
#define pb push_back
#define make_unique(x) sort(all(x)), x.resize(unique(all(x)) - x.begin())
#define int long long

const LL mod = 1e9 + 7;

template<class T>
istream& operator >> (istream& in, vector<T>& v){ for (auto &x : v) { in >> x; } return in; }

template<class T, class U>
istream& operator >> (istream& in, pair<T, U> & v){ in >> v.X >> v.Y;return in; }

template<class T, class U>
ostream& operator << (ostream& out, pair<T, U> & v){ out << v.X << " " << v.Y;return out; }

void chkmax(int &a, int b) {
    a = max(a, b);
    return;
}

void chkmin(int &a, int b) {
    a = min(a, b);
    return;
}

LL ppow (LL x, LL s) {
    if (!s) return 1;
    if (!(s - 1)) return x % mod;
    if (s % 2) return (x * ppow (x, s - 1)) % mod;
    LL b = ppow (x, s / 2);
    return (b * b) % mod;
}

main(){
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    //freopen("ILUXA.in", "r", stdin);

    int n;
    string s, t;
    cin >> n >> s >> t;
    for (int i = 0;i < n;i++) {
        cout << s[i] << t[i];
    }
    return 0;
}

Score : 200 points

Problem Statement

Given are strings s and t of length N each, both consisting of lowercase English letters.

Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.

Constraints

1 \leq N \leq 100

|S| = |T| = N

S and T are strings consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S T

Output

Print the string formed.

Sample Input 1

2
ip cc

Sample Output 1

icpc

Sample Input 2

8
hmhmnknk uuuuuuuu

Sample Output 2

humuhumunukunuku

Sample Input 3

5
aaaaa aaaaa

Sample Output 3

aaaaaaaaaa


/*
   THE DARK NIGHT RISES
I LOVE YOU 72 AND WILL FOREVER DO SO
Patience, Persistence, Perseverance, Passion, Purpose
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
typedef long double ld;
const int N = 2e5 + 20 ;
#define F first
#define S second
# define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define mk make_pair
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define rep(i,a,b) for(ll i=a;i<b;i++)
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
#define sz(x)       (int)x.size()
const long long int mod=1e9 + 7;
const long double EPS=1e-12;
#define mem( a, val ) memset(a, val, sizeof( a ) )
#define deci( x ) cout<<fixed<<setprecision( x );
#define bitcount( x ) __builtin_popcountll( x )

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

bool comp(pair<ll,ll> v1 ,pair<ll,ll> v2 )
{

}
bool vis[10] ;

int solve()
{
 	ll n ;
 	cin >> n ;
 	string s ,t ;
 	cin >> s >> t ;
 	int i = 0 , j = 0 ;
 	while(i < n && j < n)
 		cout << s[i++] << t[j++];
}
int main()
{
	fast;
	ll t;
	t=1;
	//cin>>t;
	while(t--)
	{
		solve();
	}

	return 0;
}
// Patience, Persistence, Perseverance, Passion, Purpose
// I LOVE YOU 72 AND WILL FOREVER DO SO.


#include <bits/stdc++.h>

//LIFE IS NOT A PROBLEM TO BE SOLVED

#define rep(i,a,b) for( int i = (int) a; i < (int) b; i++ )
#define F first
#define S second
#define pb push_back
#define debug(a) cout << #a << " = " << a << endl;
#define debug2(a,b) cout << #a << " = " << a << " --- " << #b << " = " << b << endl;
#define debugP(a) cout << a.F << " " << a.S << endl;
#define debugV(v, n) { rep( i, 0, n ) { if(i) printf(" "); printf("%d", v[i]); } printf("\n"); }
#define debugM(mat,n,m) rep( i, 0, n ){ rep( j, 0, m ) { if(j) printf(" "); printf("%d", mat[i][j]); } printf("\n"); }

using namespace std;

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

bool isPrime(int n){
	if(n<=1) return false;
	if(n==2) return true;
	int f = sqrt(n);
	rep(i, 2, f+1) if(n%i==0) return false;
	return true;
}

int main(){

	int n; string s, t;
	cin >> n >> s >> t;
	rep(i, 0, n){
		cout << s[i];
		cout << t[i];
	}	cout << '\n';

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define FOR(i, N) for (int i = 0; i < (int)N; i++)
#define FORIN(i, a, b) for (int i = a; i < (int)b; i++)
#define ALL(x) (x).begin(), (x).end()
#define MOD 1000000007
#define INF (1 << 29)
#define LLINF (1LL << 60)
#define DEBUG(...) debug(__LINE__, ":" __VA_ARGS__)

using Pi = pair<int, int>;
using ll = long long;

string to_string(string s) { return s; }
template <class S>
string to_string(unordered_set<S> s);
template <class S>
string to_string(set<S> s);
template <class S, class T>
string to_string(map<S, T> m);
template <class T>
string to_string(vector<T> v);

template <class S, class T>
string to_string(pair<S, T> p) {
  return "{" + to_string(p.first) + "," + to_string(p.second) + "}";
}

template <class S>
string to_string(unordered_set<S> s) {
  string ret = "{";
  for (S x : s) ret += to_string(x) + ",";
  return ret + "}";
}

template <class S>
string to_string(set<S> s) {
  string ret = "{";
  for (S x : s) ret += to_string(x) + ",";
  return ret + "}";
}

template <class S, class T>
string to_string(map<S, T> m) {
  string ret = "{";
  for (pair<S, T> x : m) ret += to_string(x) + ",";
  return ret + "}";
}

template <class T>
string to_string(vector<T> v) {
  string ret = "{";
  for (int i = 0; i < (int)v.size() - 1; ++i) {
    ret += to_string(v[i]) + ",";
  }
  if (v.size() > 0) {
    ret += to_string(v.back());
  }
  ret += "}";
  return ret;
}

void debug() { cerr << endl; }

template <class Head, class... Tail>
void debug(Head head, Tail... tail) {
  cerr << to_string(head) << " ";
  debug(tail...);
}

void print() { cout << endl; }

template <class Head, class... Tail>
void print(Head head, Tail... tail) {
  cout << to_string(head);
  print(tail...);
}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  int N;
  string s, t;
  cin >> N >> s >> t;
  FOR(i, N) { cout << s[i] << t[i]; }
  cout << endl;
  return 0;
}


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

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

long long int lcm(long long int a, long long int b)
{
  long long int g = gcd(a, b);
  return a / g * b;
}

int main()
{
  long long int A, B;
  cin >> A >> B;
  long long int ans = lcm(A, B);
  cout << ans << endl;
}

Score : 300 points

Problem Statement

Takahashi is organizing a party.

At the party, each guest will receive one or more snack pieces.

Takahashi predicts that the number of guests at this party will be A or B.

Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted.

We assume that a piece cannot be divided and distributed to multiple guests.

Constraints

1 \leq A, B \leq 10^5

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of pieces that can be evenly distributed to the guests in both of the cases with A guests and B guests.

Sample Input 1

2 3

Sample Output 1

6

When we have six snack pieces, each guest can take three pieces if we have two guests, and each guest can take two if we have three guests.

Sample Input 2

123 456

Sample Output 2

18696

Sample Input 3

100000 99999

Sample Output 3

9999900000


#include <iostream>
#include<cstdlib>
#include<queue>
#include<set>
#include<vector>
#include<string>
#include<cmath>
#include<algorithm>
#include<stack>
#include<map>
#include<deque>
#include<cstdio>
#include<cstdio>
using namespace std;
#define rep(i,a) for(int i=0;i<a;i++)
#define mp make_pair
#define pb push_back
#define ll __int64
#define __int64 long long
#define P pair<int,int>
#define PP pair<P,int>

ll n;
ll pow2(ll a,ll b){
    ll ret=1;
    for(int i=0;i<b;i++)ret*=a;
    return ret;
}

ll ko(ll i){
    return i/4LL*10LL+(i%4LL+1LL)*2LL;
}

int main(){

    cin>>n;

    ll ans=0;
    for(ll f=1;f<=1000;f++){
        ll bai=pow2(5LL,f);
        if(bai>n)
            break;

        ll l=0,r=n/bai+1,mid=(r+l)/2;
        while(abs(r-l)>1){
            if(ko(mid)*bai>n)
                r=mid;
            else
                l=mid;
            mid=(r+l)/2LL;
        }
        //cout<<(mid+1)<<endl;
        //cout<<bai<<" "<<mid<<endl;
        ans+=(mid+1)*f;
    }
    cout<<ans<<endl;

    return 0;
}

Score : 500 points

Problem Statement

For an integer n not less than 0, let us define f(n) as follows:

f(n) = 1 (if n < 2)

f(n) = n f(n-2) (if n \geq 2)

Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).

Constraints

0 \leq N \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of trailing zeros in the decimal notation of f(N).

Sample Input 1

12

Sample Output 1

1

f(12) = 12 × 10 × 8 × 6 × 4 × 2 = 46080, which has one trailing zero.

Sample Input 2

5

Sample Output 2

0

f(5) = 5 × 3 × 1 = 15, which has no trailing zeros.

Sample Input 3

1000000000000000000

Sample Output 3

124999999999999995


#include <bits/stdc++.h>

using namespace std;

int main() {
  int a, b, c; cin >> a >> b >> c;
  cout << (a + b + c < 22 ? "win" : "bust") << endl;
}

Score : 100 points

Problem Statement

Given are three integers A_1, A_2, and A_3.

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Constraints

1 \leq A_i \leq 13 \ \ (i=1,2,3)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Sample Input 1

5 7 9

Sample Output 1

win

5+7+9=21, so print win.

Sample Input 2

13 7 2

Sample Output 2

bust

13+7+2=22, so print bust.


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()

int main() {
  string s;
  cin >> s;
  int ans = 0;
  int n = s.size();

  for (int i = 0; i < n / 2; i ++) {
    if (s[i] != s[n - 1 - i]) ans ++;
  }

  cout << ans << endl;
}

Score : 200 points

Problem Statement

Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.

Given is a string S. Find the minimum number of hugs needed to make S palindromic.

Constraints

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of hugs needed to make S palindromic.

Sample Input 1

redcoder

Sample Output 1

1

For example, we can change the fourth character to o and get a palindrome redooder.

Sample Input 2

vvvvvv

Sample Output 2

0

We might need no hugs at all.

Sample Input 3

abcdabc

Sample Output 3

2


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

int main()
{
  // 入力
  int N;
  cin >> N;
  vector<vector<pair<int, int>>> data(N);
  for (int i = 0; i < N; i++)
  {
    int A;
    cin >> A;
    for (int j = 0; j < A; j++)
    {
      int x, y;
      cin >> x >> y;
      x--;
      data.at(i).push_back(make_pair(x, y));
    }
  }

  int M = 0;
  // 正直者の組み合わせを全探索
  // O((2^N)N^2)のアルゴリズム
  for (int i = 0; i < (1 << N); i++)
  {
    bool ok = true;
    for (int j = 0; j < N; j++)
    {
      if (!(i & (1 << j)))
      {
        continue;
      }
      for (int k = 0; k < data.at(j).size(); k++)
      {
        if ((i & (1 << data.at(j).at(k).first)) ^ data.at(j).at(k).second)
        {
          ok = false;
        }
      }
    }
    if (ok)
    {
      M = max(M, __builtin_popcount(i));
    }
  }
  cout << M << endl;
}

Score : 300 points

Problem Statement

There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.

Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.

How many honest persons can be among those N people at most?

Constraints

All values in input are integers.

1 \leq N \leq 15

0 \leq A_i \leq N - 1

1 \leq x_{ij} \leq N

x_{ij} \neq i

x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)

y_{ij} = 0, 1

Input

Input is given from Standard Input in the following format:

N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}

Output

Print the maximum possible number of honest persons among the N people.

Sample Input 1

3
1
2 1
1
1 1
1
2 0

Sample Output 1

2

If Person 1 and Person 2 are honest and Person 3 is unkind, we have two honest persons without inconsistencies, which is the maximum possible number of honest persons.

Sample Input 2

3
2
2 1
3 0
2
3 1
1 0
2
1 1
2 0

Sample Output 2

0

Assuming that one or more of them are honest immediately leads to a contradiction.

Sample Input 3

2
1
2 0
1
1 0

Sample Output 3

1


#include<bits/stdc++.h>
using namespace std;
#define IOS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template <class T>
struct rbtree: tree<T,null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>{};
#define IN freopen("in.txt", "r", stdin);
#define endl '\n'
#define mp make_pair
#define pb push_back
#define lowb lower_bound
#define eb emplace_back
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define sz(x) (int)x.size()
#define mem0(a) memset((a), 0, sizeof(a))
#define mem(a, b) memset((a), (b), sizeof(a))
typedef unsigned long long ull;
typedef long long ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int inf = 0x3f3f3f3f;

const int N = 20;
int res[N];
int c[N];
int a[N][N];

int main(){
    IOS;
    //IN;
    int n; cin>>n;
    for(int i = 1; i <= n; i++){
        cin>>c[i];
        for(int j = 1; j <= c[i]; j++){
            int y, z; cin>>y>>z;
            a[i][y] = z;
        }
    }
    int ans = 0;
    for(int i = 1; i <= (1<<n)-1; i++){
        bool f = 0;
        int cnt=0;
        for(int j = 1; j <= n; j++)res[j] = 0;
        for(int j = 0; j < n; j++){
            if(i&(1<<j)){
                cnt++;
                res[j+1]++;
            }
        }
        for(int j = 1; j <= n; j++){
            if(!res[j])continue;
            for(int z = 1; z <= n; z++){
                if(z==j)continue;
                if((a[j][z] == 0 && res[z]) || (a[j][z] == 1 && !res[z])){
                    //cout<<"2==="<<z<<endl;
                    f=1;
                    break;
                }
            }
            if(f)break;
        }
        //cout<<"1===="<<cnt<<endl;
        if(!f)ans = max(ans, cnt);
    }
    cout<<ans;

    return 0;
}


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

const long long MOD = 1000000007;
const int INF = 1e9;

bool BitFlag(long long n, int i){
  if(n&(1<<i)) return 1;
  else return 0;
}

int main(){
  long long n;
  const long long max_n = 3 * 1e5;
  long long a[max_n + 1];
  cin >> n;
  for(long long i = 0; i < n; i++) cin >> a[i];

  long long num[62] = {};
  for(long long i = 0; i <= 61; i++){
    for(long long j = 0; j < n; j++){
      if(a[j]&(1LL<<i)) num[i] += 1;
    }
  }

  long long ans = 0;
  for(long long i = 0; i <= 61; i++){
    long long now = (1LL << i);
    ans += num[i] * (n-num[i]) * now;
    ans %= MOD;
  }
  cout << ans << endl;

  return 0;
}

Score : 400 points

Problem Statement

We have N integers. The i-th integer is A_i.

Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

2 \leq N \leq 3 \times 10^5

0 \leq A_i < 2^{60}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the value \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

6

We have (1\mbox{ XOR } 2)+(1\mbox{ XOR } 3)+(2\mbox{ XOR } 3)=3+2+1=6.

Sample Input 2

10
3 1 4 1 5 9 2 6 5 3

Sample Output 2

237

Sample Input 3

10
3 14 159 2653 58979 323846 2643383 27950288 419716939 9375105820

Sample Output 3

103715602

Print the sum modulo (10^9+7).


#include <iostream>
using namespace std;
using ll = long long;
ll A[300100];

ll MOD = 1e9 + 7;

int main() {
  int N;

  cin >> N;
  for(int i = 1; i <= N; ++i) {
    cin >> A[i];
  }

  ll total = 0;
  for(int i = 1; i < N; ++i) {
    for(int j = i + 1; j <= N; ++j) {
      total += (A[i] ^ A[j]) % MOD;
      total %= MOD;
    }
  }
  cout << total << endl;
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
constexpr int Inf = 1000000010;
constexpr ll INF= 1000000000000000000;
constexpr ll MOD = 1000000007;
const double PI = 3.1415926535897;
typedef pair<ll,ll> P;

template<typename T>
T Pow(T a,T b) {
    T ret = 1;
    for(int i = 0;i < b;i++) {
        ret *= a;
    }
    return ret;
}

ll mod(ll val) {
    ll res = val % MOD;
    if(res < 0) {
        res += MOD;
    }
    return res;
}

ll RS(ll N, ll P, ll M){
    if(P==0) return 1;
    if(P < 0) {
        return 0;
    }
    if(P%2==0){
        ll t = RS(N, P/2, M);
        return t*t % M;
    }
    return N * RS(N, P-1, M) % M;
}

ll digit(ll a) {
    ll ret = 0;
    while(a > 0) {
        ret += a % 10;
        a /= 10;
    }
    return ret;
}

int H,W;
int red[88][88];
int blue[88][88];
bool dp[88][88][12800]; //dp[i][j][k] = (i,j)までに偏りをkにすることが出来るかどうか

int main() {
    cin >> H >> W;
    for(int i = 0;i < H;i++) {
        for(int j = 0;j < W;j++) {
            cin >> red[i][j];
        }
    }
    for(int i = 0;i < H;i++) {
        for(int j = 0;j < W;j++) {
            cin >> blue[i][j];
        }
    }
    for(int i = 0;i < 88;i++) {
        for(int j = 0;j < 88;j++) {
            for(int k = 0;k < 12800;k++) {
                dp[i][j][k] = false;
            }
        }
    }
    dp[0][0][abs(red[0][0] - blue[0][0])] = true;
    for(int i = 0;i < H;i++) {
        for(int j = 0;j < W;j++) {
            for(int k = 0;k < 12800;k++) {
                if(i > 0) {
                    dp[i][j][k + abs(red[i][j] - blue[i][j])] |= dp[i - 1][j][k];
                    dp[i][j][abs(k - abs(red[i][j] - blue[i][j]))] |= dp[i - 1][j][k];
                }
                if(j > 0) {
                    dp[i][j][k + abs(red[i][j] - blue[i][j])] |= dp[i][j - 1][k];
                    dp[i][j][abs(k - abs(red[i][j] - blue[i][j]))] |= dp[i][j - 1][k];
                }
            }
        }
    }
    for(int i = 0;i < 12800;i++) {
        if(dp[H - 1][W - 1][i] == true) {
            cout << i << endl;
            break;
        }
    }
}

Score : 500 points

Problem Statement

We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.

The square (i, j) has two numbers A_{ij} and B_{ij} written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

Sample Input 2

2 3
1 10 80
80 10 1
1 2 3
4 5 6

Sample Output 2

2


// #pragma GCC optimize("Ofast")
// #pragma GCC optimize ("unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
using namespace std;

using ull = unsigned long long int;
using ll = long long int;
using du = double;
using ld = long du;
using vi = vector<int>;
using vll = vector<ll>;
using vld = vector<ld>;
using vdu = vector<du>;
using vs = vector<string>;
using vc = vector<char>;
using si = set<int>;
using sll = set<ll>;
using sdu = set<du>;
using sld = set<ld>;
using pii = pair<int, int>;
using pll = pair<ll,ll>;
using pdu = pair<du,du>;
using pld = pair<ld,ld>;
using pis = pair<int,string>;

#define FASTIO ios_base::sync_with_stdio(false); cin.tie(nullptr)
#define sp(x) setprecision(x)<<fixed
#define loop(i,n) for(int i=0;i<n;i++)
#define ff first
#define ss second
#define pi acos(-1)
#define meme(a,x) memset(a,x,sizeof(a))
#define all(a) a.begin(),a.end()

//debugger

#ifdef KAIZER
#include "debug.h"
#else
#define debug(x...)
#endif
//debugger

//functions
bool check_pow(ll a)
{
    if((a&(a-1))==0) return true;
    else return false;
}
ld my_pow(ld a,int b)
{
    ld ans=1;
    for(int i=0;i<b;i++) ans*=a;
    return ans;
}
ll digits(ll a)
{
    string line=to_string(a);
    return line.size();
}
bool prime_check(ll a)
{
    bool flag=true;
    for(ll i=2;i<=sqrt(a);i++)
    {
        if(a%i==0) {flag=false; break;}
    }
    return flag;
}
bool comp(const pair<int,int> &a , const pair<int,int> &b)
{
    if(a.ff!=b.ff) return a.ff>b.ff;
    else return a.ss<b.ss;
}
bool comp2(const ll &a, const ll &b)
{
     return a>b;
}

//functions
bool rc(int x, int y)
{
    int z = double(x)*1.08;
    if (z==y) return true;
    else return false;
}

int main() {
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    FASTIO;
    ll t;
    cin>>t;
    int x= (t)/1.08;
    if(rc(x,t)) cout<<x<<endl;
    else if(rc(x+1,t)) cout<<x+1<<endl;
    else if(rc(x-1,t)) cout<<x-1<<endl;
    else cout<<":(\n";
 }

Score: 200 points

Problem Statement

Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it.

The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer).

Takahashi forgot the price of his apple pie before tax, X, and wants to know it again. Write a program that takes N as input and finds X. We assume X is an integer.

If there are multiple possible values for X, find any one of them. Also, Takahashi's memory of N, the amount he paid, may be incorrect. If no value could be X, report that fact.

Constraints

1 \leq N \leq 50000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If there are values that could be X, the price of the apple pie before tax, print any one of them.

If there are multiple such values, printing any one of them will be accepted.

If no value could be X, print :(.

Sample Input 1

432

Sample Output 1

400

If the apple pie is priced at 400 yen before tax, you have to pay 400 \times 1.08 = 432 yen to buy one.

Otherwise, the amount you have to pay will not be 432 yen.

Sample Input 2

1079

Sample Output 2

:(

There is no possible price before tax for which you have to pay 1079 yen with tax.

Sample Input 3

1001

Sample Output 3

927

If the apple pie is priced 927 yen before tax, by rounding down 927 \times 1.08 = 1001.16, you have to pay 1001 yen.


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

template <class T> using V = vector<T>;
template <class S, class T> using P = pair<S, T>;

using ll = long long;
using ull = unsigned long long;
using vll = V<ll>;
using vvll = V<vll>;
using vvvll = V<vvll>;
using pl = P<ll, ll>;
using vpl = V<pl>;
using vvpl = V<vpl>;
using vs = V<string>;
using qll = queue<ll>;
using qpl = queue<pl>;
using mapll = map<ll, ll>;
using setll = set<ll>;
using pqll = priority_queue<ll>;

#define int ll
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define pob pop_back()
#define pf push_front
#define pof pop_front()
#define sz size()
#define bgn begin()
#define en end()
#define emp empty()
#define fr front()
#define bk back()
#define res resize
#define tp top()
#define p_q priority_queue
#define inv inverse()

#define FOR(i,a,b) for(ll i=(a);i<=(ll)(b);i++)
#define rFOR(i,a,b) for(ll i=(b);i>=(ll)(a);i--)
#define REP(i,a) FOR((i),0,(ll)(a)-1)
#define REP0(i,a) FOR((i),0,(ll)(a))
#define REP1(i,a) FOR((i),1,(ll)(a))
#define rREP(i,a) rFOR((i),0,(ll)(a)-1)
#define rREP0(i,a) rFOR((i),0,(ll)(a))
#define rREP1(i,a) rFOR((i),1,(ll)(a))
#define IOTA(a,n) iota((a).bgn,(a).en,(n))
#define SORT(a) sort((a).bgn,(a).en)
#define rSORT(a) sort((a).rbegin(),(a).rend())
#define UNIQUE(a) (a).erase(unique((a).bgn,(a).en),(a).en)
#define BINS(a,b) binary_search((a).bgn,(a).en,(b))
#define LOWB(a,b) (lower_bound((a).bgn,(a).en,(b))-(a).bgn)
#define UPB(a,b) (upper_bound((a).bgn,(a).en,(b))-(a).bgn)
#define CNT(a,b) count((a).bgn,(a).en,b)
#define SUM(a) accumulate((a).bgn,(a).en,0)
#define REV(a) reverse((a).bgn,(a).en)
#define yn(a) cout <<((a)?"yes":"no")<<"\n";
#define Yn(a) cout <<((a)?"Yes":"No")<<"\n";
#define YN(a) cout <<((a)?"YES":"NO")<<"\n";
#define imp(a) cout <<((a)?"possible":"impossible")<<"\n";
#define Imp(a) cout <<((a)?"Possible":"Impossible")<<"\n";
#define IMP(a) cout <<((a)?"POSSIBLE":"IMPOSSIBLE")<<"\n";
#define dbg(a) cerr <<(#a)<<": "<<(a)<<"\n";
#define DigN2(a) ((llabs(a)==0)?(1):((ll)(log2(double(llabs(a))))+1))
#define DigN10(a) ((llabs(a)==0)?(1):((ll)(log10(double(llabs(a))))+1))
#define Dig2(a,b) (((a)>>(b))&1)
#define Dig10(a,b) (ll)(((a)/((ll)(pow(10.0,(double)(b)))))%10)
#define Pow2(a) ((ll)(1)<<(a))
#define Pow10(a) ((ll)(pow(10.0,double(a))))
#define powll(a,b) (ll)(pow((double)(a),(double)(b)))

#define li(...) ll __VA_ARGS__;Input(__VA_ARGS__);
#define si(...) string __VA_ARGS__;Input(__VA_ARGS__);
#define vli(size, ...) vll __VA_ARGS__;vInput(size,__VA_ARGS__);
#define vsi(size, ...) vs __VA_ARGS__;vInput(size,__VA_ARGS__);

const ll MOD = 1e9 + 7;
//const ll MOD = 998244353;
//const ll MOD = 924844033;
//const ll MOD = 9007199254740881;
const ll INF = 1LL << 60;//1.15e18
const double PI = acos(-1.0);
const string alp = "abcdefghijklmnopqrstuvwxyz";
const string ALP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

void Input() {}
template <class Var, class... Args> void Input(Var& var, Args&... args) {
    cin >> var;
    Input(args...);
}

void vInit(ll size) {}
template <class T, class... Args> void vInit(ll size, V<T>& v, Args&... args) {
    v.res(size);
    vInit(size, args...);
}
void vInputNum(ll num) {}
template <class T, class... Args> void vInputNum(ll num, V<T>& v, Args&... args) {
    cin >> v[num];
    vInputNum(num, args...);
}
void vInput(ll size) {}
template <class... Args> void vInput(ll size, Args&... args) {
    vInit(size, args...);
    REP(i, size) vInputNum(i, args...);
}

template <class S, class T> ostream &operator<<(ostream &out, const P<S, T> &p) {
    return out << "[" << p.fi << ", " << p.se << "]";
}

template <class T> ostream &operator<<(ostream &out, V<T> &v) {
    if (v.emp) return out << "{}";
    else {
        auto itr = v.bgn;
        out << "{" << *itr;
        itr++;
        while (itr != v.en) {
            out << ", " << *itr;
            itr++;
        }
        out << "}";
        return out;
    }
}

template <class S, class T> ostream &operator<<(ostream &out, const map<S, T> &m) {
    if (m.emp) return out << "<[]>";
    else {
        auto itr = m.bgn;
        out << "< [" << (itr->fi) << ": " << (itr->se);
        itr++;
        while (itr != m.en) {
            out << "], [" << (itr->fi) << ": " << (itr->se);
            itr++;
        }
        out << "] >";
        return out;
    }
}

template <class T> ostream &operator<<(ostream &out, const set<T> &s) {
    if (s.emp) return out << "<>";
    else {
        auto itr = s.bgn;
        out << "<" << *itr;
        itr++;
        while (itr != s.en) {
            out << ", " << *itr;
            itr++;
        }
        out << ">";
        return out;
    }
}

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

struct UFT {

public:
    ll tsize;
    ll mode;
    vll par;
    vll rank;
    UFT() {}
    UFT(const UFT &uft) {}
    UFT(ll tsizeget, ll modeget = 0){
        tsize = tsizeget;
        mode = modeget;
        par.assign(tsize, -1);
        if (!mode) rank.res(tsize, 0);
    }
    ll root(ll x) {
        return par[x] < 0 ? x : par[x] = root(par[x]);
    }
    bool isRoot(ll x) {
        return x == root(x);
    }
    bool same(ll x, ll y) {
        return root(x) == root(y);
    }
    void merge(ll x, ll y) {
        x = root(x);
        y = root(y);
        if (x == y) return;
        if (mode) {
            par[x] += par[y];
            par[y] = x;
        }
        else {
            if (rank[x] < rank[y]) {
                par[y] += par[x];
                par[x] = y;
            }
            else {
                par[x] += par[y];
                par[y] = x;
                if (rank[x] == rank[y]) rank[x]++;
            }
        }
    }
    ll size(ll x) {
        return -par[root(x)];
    }
};

ll isP(ll n) {
    if (n <= 1) return 0;
    FOR(i, 2, (ll)sqrt(n) + 1) {
        if (n%i == 0) return 0;
    }
    return 1;
}

vvll CombMemo(3000, vll(3000, -1));

ll Comb(ll n, ll k) {
    if ((n < 0) || (k < 0)) return 0;
    if (CombMemo[n][k] == -1) {
        if (n < k) CombMemo[n][k] = 0;
        else {
            if (n == 0) CombMemo[n][k] = 1;
            else if (k == 0) CombMemo[n][k] = 1;
            else if (n == k) CombMemo[n][k] = 1;
            else CombMemo[n][k] = Comb(n - 1, k - 1) + Comb(n - 1, k);
        }
    }
    return CombMemo[n][k];
}

void Solve();

signed main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << setprecision(20) << fixed;
    Solve();
}

void Solve() {
  li(n);
  REP1(i,50000){
    if ((ll)(i*1.08)==n) {
      cout << i;
      return;
    }
  }
  cout << ":(";
}


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

#define int long long
#define double long double
#define rep(i, n) for (int i = 0; i < (n); i++)
#define reps(i, n) for (int i = 1; i <= (n); i++)
#define all(x) (x).begin(), (x).end()
#define uniq(x) (x).erase(unique(all(x)), (x).end())
#define bit(n) (1LL << (n))
#define dump(x) cerr << #x " = " << (x) << endl
using vint=vector<int>;
using vvint=vector<vint>;
using pint=pair<int, int>;
using vpint=vector<pint>;
template<typename T> using priority_queue_rev=priority_queue<T, vector<T>, greater<T>>;
constexpr double pi = 3.1415926535897932384626433832795028L;
constexpr int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
constexpr int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int gcd(int a, int b) {
    while (b) { swap(a %= b, b); }
    return a;
}
int lcm(int a, int b) { return a / gcd(a, b) * b; }
template<typename T> void fin(T mes) {
    cout << mes << endl;
    exit(0);
}
template<typename T1, typename T2> bool chmax(T1 &a, const T2 &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template<typename T1, typename T2> bool chmin(T1 &a, const T2 &b) {
    if (b < a) {
        a = b;
        return true;
    }
    return false;
}
template<typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &rhs) {
    os << "(" << rhs.first << ", " << rhs.second << ")";
    return os;
}
template<typename T> ostream &operator<<(ostream &os, const vector<T> &rhs) {
    os << "{";
    for (auto itr = rhs.begin(); itr != rhs.end(); itr++) {
        os << *itr << (next(itr) != rhs.end() ? ", " : "");
    }
    os << "}";
    return os;
}
struct setup {
    static constexpr int PREC = 20;
    setup() {
        cout << fixed << setprecision(PREC);
        cerr << fixed << setprecision(PREC);
    };
} setup;

int N;
signed main() {
    cin >> N;
    reps(i, N) {
        if (floor(i * 1.08) == N) { fin(i); }
    }
    cout << ":(" << endl;
}


#include<iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
    int x;
    cin >> x;
    if((x/100*5)>=x%100){
        cout << 1;
    }else{
        cout << 0;
    }

}

Score: 300 points

Problem Statement

AtCoder Mart sells 1000000 of each of the six items below:

Riceballs, priced at 100 yen (the currency of Japan) each

Sandwiches, priced at 101 yen each

Cookies, priced at 102 yen each

Cakes, priced at 103 yen each

Candies, priced at 104 yen each

Computers, priced at 105 yen each

Takahashi wants to buy some of them that cost exactly X yen in total.
Determine whether this is possible.

(Ignore consumption tax.)

Constraints

1 \leq X \leq 100000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If it is possible to buy some set of items that cost exactly X yen in total, print 1; otherwise, print 0.

Sample Input 1

615

Sample Output 1

1

For example, we can buy one of each kind of item, which will cost 100+101+102+103+104+105=615 yen in total.

Sample Input 2

217

Sample Output 2

0

No set of items costs 217 yen in total.


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

#define li          long long int
#define rep(i,to)   for(li i=0;i<((li)(to));i++)
#define repp(i,start,to)    for(li i=(li)(start);i<((li)(to));i++)
#define pb          push_back
#define sz(v)       ((li)(v).size())
#define bgn(v)      ((v).begin())
#define eend(v)     ((v).end())
#define allof(v)    (v).begin(), (v).end()
#define dodp(v,n)       memset(v,(li)n,sizeof(v))
#define bit(n)      (1ll<<(li)(n))
#define mp(a,b)     make_pair(a,b)
#define rin rep(i,n)
#define EPS 1e-12
#define ETOL 1e-8
#define MOD 1000000007
typedef pair<li, li> PI;

#define INF bit(60)

#define DBGP 1

#define idp if(DBGP)
#define F first
#define S second
#define p2(a,b)     idp cout<<a<<"\t"<<b<<endl
#define p3(a,b,c)       idp cout<<a<<"\t"<<b<<"\t"<<c<<endl
#define p4(a,b,c,d)     idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<endl
#define p5(a,b,c,d,e)       idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<endl
#define p6(a,b,c,d,e,f)     idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<endl
#define p7(a,b,c,d,e,f,g)       idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<endl
#define p8(a,b,c,d,e,f,g,h)     idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<"\t"<<h<<endl
#define p9(a,b,c,d,e,f,g,h,i)       idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<"\t"<<h<<"\t"<<i<<endl
#define p10(a,b,c,d,e,f,g,h,i,j)        idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<"\t"<<h<<"\t"<<i<<"\t"<<j<<endl
#define foreach(it,v)   for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define p2p(x)      idp p2((x).F, (x).S)
#define dump(x,n)   idp{rep(i,n){cout<<x[i]<<" ";}puts("");}
#define dump2(x,n)  idp{rep(i,n){cout<<"["<<x[i].F<<" , "<<x[i].S<<"] ";}puts("");}
#define dumpi(x)    idp{foreach(it, x){cout<<(*it)<<" ";}puts("");}
#define dumpi2(x)   idp{foreach(it, x){cout<<"["<<(it)->F<<" , "<<(it)->S<<"] ";}puts("");}

#define read2d(a,w,h)   rep(i,h)rep(j,w)cin>>a[i][j]
#define dump2d(a,w,h)   rep(i,h){rep(j,w)cout<<a[i][j]<<" ";puts("");}

bool dp[100300];

int main() {
    vector<li> p;
    repp(i, 100, 106) {
        p.pb(i);
    }
    li x;
    cin >> x;
    rep(i, x + 1) {
        dp[i] = false;
    }
    dp[0] = true;
    rep(i, x + 1) {
        if (!dp[i]) {
            continue;
        }
        for (auto v : p) {
            dp[i + v] = true;
        }
    }
    cout << (dp[x] ? 1 : 0) << endl;

    return 0;
}


#include <iostream>
#include <vector>
#include <utility>
#include <map>
using namespace std;

typedef pair<int,pair<int,int> > triple;

long MOD = 1000000007;

int n;
vector<int> A;
map<triple, int> mem;
long dp(int r, int b, int g){
	int prog = r+b+g;
	if(prog == n) return 1;
	triple c = pair<int, pair<int, int> >(r, pair<int,int>(b,g));
	if(mem.find(c) != mem.end()) return mem[c];
	int at = prog;
	long sm = 0;
	if(r == A[at]) sm += dp(r+1,b,g);
	if(b == A[at]) sm += dp(r,b+1,g);
	if(g == A[at]) sm += dp(r,b,g+1);
	return mem[c] = sm % MOD;
}

int main() {
	cin >> n;
	A = vector<int>(n);
	for(int i = 0; i < n; i++) cin >> A[i];
	cout << dp(0,0,0);
	return 0;
}

Score: 500 points

Problem Statement

N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green.

The person numbered i says:

"In front of me, exactly A_i people are wearing hats with the same color as mine."

Assuming that all these statements are correct, find the number of possible combinations of colors of the N people's hats.

Since the count can be enormous, compute it modulo 1000000007.

Constraints

1 \leq N \leq 100000

0 \leq A_i \leq N-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print the number of possible combinations of colors of the N people's hats, modulo 1000000007.

Sample Input 1

6
0 1 2 3 4 5

Sample Output 1

3

We have three possible combinations, as follows:

Red, Red, Red, Red, Red, Red

Blue, Blue, Blue, Blue, Blue, Blue

Green, Green, Green, Green, Green, Green

Sample Input 2

3
0 0 0

Sample Output 2

6

Sample Input 3

54
0 0 1 0 1 2 1 2 3 2 3 3 4 4 5 4 6 5 7 8 5 6 6 7 7 8 8 9 9 10 10 11 9 12 10 13 14 11 11 12 12 13 13 14 14 15 15 15 16 16 16 17 17 17

Sample Output 3

115295190


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
using vl = vector<ll>;

/* short */
#define pb push_back
#define mp make_pair
#define Fi first
#define Se second
#define ALL(v) begin(v), end(v)
#define RALL(v) rbegin(v), rend(v)

/* REPmacro */
#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define FORR(i, a, b) for(int i = (a); i >= (b); i--)
#define REP(i, n) for(int i = 0; i < (n); i++)
#define FOREACH(x, a) for(auto x : a)

/* exchange */
#define CHMIN(a, b) (a) = min((ll)(a), (ll)(b))
#define CHMAX(a, b) (a) = max((ll)(a), (ll)(b))

/* function */
#define IN(x) cin >> x
#define DEBUG(x) cerr << (x) << " "
#define LN() cerr << "\n"
#define PRINT(x) cout << (x) << endl
#define BR cout << endl

/* const */
const int ARRAY = 100005;
const int INF = 1001001001; // 10^9
const ll LINF = 1001001001001001001; // 10^18
const int MOD = 1e9 + 7;

ll N = 0;
ll t;
ll ret = 0;
ll table[ARRAY][3];
ll color = 0;

void input() {
  IN(N);
  ll A;
  REP(i, ARRAY) {
    REP(j, 3) {
      table[i][j] = -1;
    }
  }
  FOR(i, 1, N+1) {
    IN(A);
    if (table[A][0] == -1) {
      table[A][0] = i;
      CHMAX(color, 1);
    } else if (table[A][1] == -1) {
      table[A][1] = i;
      CHMAX(color, 2);
    } else {
      table[A][2] = i;
      CHMAX(color, 3);
    }
  }
  // REP(i, 20) {
  //   DEBUG(i);
  //   DEBUG("...");
  //   REP(j, 3) {
  //     DEBUG(table[i][j]);
  //   }
  //   LN();
  // }
}

ll align(ll i, ll j) {
  ll ans = 0;
  ll emp = 0;
  vector<ll> a;
  vector<ll> b;
  REP(k, 3) {
    if (table[i][k] != -1) {
      a.pb(table[i][k]);
      b.pb(table[j][k]);
      if (table[j][k] == -1) emp++;
    }
  }
  if (a.size() == 0 || b[0] == -1) {
    return 1;
  }
  ll n = a.size();
  do {
    bool flg = true;
    REP(i, n) {
      if (a[i] < b[i] || b[i] == -1) flg &= true;
      else flg &= false;
    }
    if (flg) {
      ans++;
    }
  } while(next_permutation(a.begin(), a.end()));
  // DEBUG(i);
  // DEBUG(" -> ");
  // DEBUG(j);
  // DEBUG(" = ");
  // DEBUG(ans);
  // LN();
  if (emp == 2) ans /= 2;
  return ans;
}

void solve() {
  ret = 1;
  REP(i, N) {
    ret *= align(i, i+1);
    ret %= MOD;
  }
  if (color == 1) {
    ret *= 3;
    ret %= MOD;
  } else if (color == 2) {
    ret *= 3;
    ret %= MOD;
  } else if (color == 3) {
    ret *= 6;
    ret %= MOD;
  }
  PRINT(ret);
}

int main(void){
  input();
  solve();
}


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

main(){
  string s;
  cin >> s;
  if(s=="SUN"){cout << 7 << endl;}
  else if(s=="MON"){cout << 6 << endl;}
  else if(s=="TUE"){cout << 5 << endl;}
  else if(s=="WED"){cout << 4 << endl;}
  else if(s=="THU"){cout << 3 << endl;}
  else if(s=="FRI"){cout << 2 << endl;}
  else{cout << 1 << endl;}
  return 0;
}

Score : 100 points

Problem Statement

Given is a string S representing the day of the week today.

S is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.

After how many days is the next Sunday (tomorrow or later)?

Constraints

S is SUN, MON, TUE, WED, THU, FRI, or SAT.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of days before the next Sunday.

Sample Input 1

SAT

Sample Output 1

1

It is Saturday today, and tomorrow will be Sunday.

Sample Input 2

SUN

Sample Output 2

7

It is Sunday today, and seven days later, it will be Sunday again.


#include<bits/stdc++.h>
using namespace std;
map<string, int> m = {
  {"MON", 6},
  {"TUE", 5},
  {"WED", 4},
  {"THU", 3},
  {"FRI", 2},
  {"SAT", 1},
  {"SUN", 7}
};
int main(){
  string s; cin >> s;
  cout << m[s] << endl;
}


#include <bits/stdc++.h>
using namespace std;
int main(){
  long long N;
  cin >> N;
  vector<long long> a(N - 1);
  vector<long long> b(N - 1);
  vector<long long> vec(N, 0);
  for(int i = 0; i < N - 1; i++){
    cin >> a.at(i) >> b.at(i);
    vec.at(a.at(i) - 1) += 1;
    vec.at(b.at(i) - 1) += 1;
  }
  long long M = 0;
  for(int i = 0; i < N; i++){
    M = max(M, vec.at(i));
  }
  vector<long long> ans(N - 1, 0);
  vector<long long> vec2(N, 0);
  long long u = 1;
  ans.at(0) = u;
  vec2.at(b.at(0) - 1) = u;
  for(long long i = 1; i < N - 1; i++){
    if(a.at(i - 1) == a.at(i)){
      u++;
      if(vec2.at(a.at(i) - 1) == u){
        u++;
        ans.at(i) = u;
        vec2.at(b.at(i) - 1) = u;
      }
      else{
        ans.at(i) = u;
        vec2.at(b.at(i) - 1) = u;
      }
    }
    else{
      u = 1;
      if(vec2.at(a.at(i) - 1) == u){
        u++;
        ans.at(i) = u;
        vec2.at(b.at(i) - 1) = u;
      }
      else{
        ans.at(i) = u;
        vec2.at(b.at(i) - 1) = u;
      }
    }
  }
  cout << M << endl;
  for(long long i = 0; i < N - 1; i++){
    cout << ans.at(i) << endl;
  }
}

Score : 400 points

Problem Statement

Given is a tree G with N vertices.
The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.

Consider painting the edges in G with some number of colors.
We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.

Among the colorings satisfying the condition above, construct one that uses the minimum number of colors.

Constraints

2 \le N \le 10^5

1 \le a_i \lt b_i \le N

All values in input are integers.

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

Print N lines.

The first line should contain K, the number of colors used.

The (i+1)-th line (1 \le i \le N-1) should contain c_i, the integer representing the color of the i-th edge, where 1 \le c_i \le K must hold.

If there are multiple colorings with the minimum number of colors that satisfy the condition, printing any of them will be accepted.

Sample Input 1

3
1 2
2 3

Sample Output 1

2
1
2

Sample Input 2

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

Sample Output 2

4
1
2
3
4
1
1
2

Sample Input 3

6
1 2
1 3
1 4
1 5
1 6

Sample Output 3

5
1
2
3
4
5


#define DEBUG 0
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 6/8/2020, 2:28:47 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- main() -----

int main()
{
  ll N, K;
  cin >> N >> K;
  vector<ll> A(N);
  for (auto i{0}; i < N; ++i)
  {
    cin >> A[i];
    A[i]--;
  }
  vector<ll> sum(N + 1, 0);
  for (auto i{0}; i < N; ++i)
  {
    sum[i + 1] = A[i] + sum[i];
    sum[i + 1] %= K;
  }
  map<ll, ll> M;
  ll ans{0};
  for (auto i{0}; i < N + 1; ++i)
  {
    if (i - K >= 0)
    {
      M[sum[i - K]]--;
    }
    ans += M[sum[i]];
    M[sum[i]]++;
  }
  cout << ans << endl;
}

Score : 500 points

Problem Statement

Given are a sequence of N positive integers A_1, A_2, \ldots, A_N, and a positive integer K.

Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from different positions, even if they are equal sequences.

Constraints

All values in input are integers.

1 \leq N \leq 2\times 10^5

1 \leq K \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print the number of subsequences that satisfy the condition.

Sample Input 1

5 4
1 4 2 3 5

Sample Output 1

4

Four sequences satisfy the condition: (1), (4,2), (1,4,2), and (5).

Sample Input 2

8 4
4 2 4 2 4 2 4 2

Sample Output 2

7

(4,2) is counted four times, and (2,4) is counted three times.

Sample Input 3

10 7
14 15 92 65 35 89 79 32 38 46

Sample Output 3

8


#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<long>;
using vs = vector<string>;
using vvi = vector<vector<int>>;
using vvb = vector<vector<bool>>;
using vvc = vector<vector<char>>;
using pii = pair<int, int>;
using pll = pair<long, long>;
using pis = pair<int,string>;
#define fix20 cout << fixed << setprecision(20);
#define rep(i,n) for(int i=0; i<(int)(n);i++)
#define MOD 1000000007

int main(){
  long n,k;
  cin >> n >> k;
  vector<long> a(n);
  rep(i,n){
    cin >> a.at(i);
    a.at(i)--;
    if(a.at(i) < 0) a.at(i) += k;
    a.at(i) %= k;
  }
  vector<long> sum(n+1,0);
  rep(i,n){
    sum.at(i+1) = sum.at(i) + a.at(i);
    sum.at(i+1) %= k;
  }
  map<long,long> mp;
  rep(i,n+1){
    long tmp = sum.at(i);
    mp[tmp] = 0;
  }
  int id = 0;
  vvi data(mp.size());
  for(auto P : mp){
    mp.at(P.first) = id;
    id++;
  }
  rep(i,n+1){
    int num = mp.at(sum.at(i));
    data.at(num).push_back(i);
  }

  long ans = 0;
  rep(i,mp.size()){
    rep(j,data.at(i).size()){
      int iter = lower_bound(data.at(i).begin(),data.at(i).end(),data.at(i).at(j)+k) - data.at(i).begin();
      int comb = iter - 1 - j;
      ans += comb;
    }
  }
  cout << ans << endl;
}


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

signed main(){
	int N, K, A, S = 0, i, ans = 0;
	scanf("%lld%lld", &N, &K);
	map<int, int> mp;
	queue<int> q;
	mp[S]++;
	q.push(S);
	for(i = 0; i < N; i++){
		scanf("%lld", &A);
		S = (S + A - 1) % K;
//		printf("S = %lld\n", S);
		ans += mp[S];
//		printf("ans = %lld\n", ans);
		mp[S]++;
		q.push(S);
		if(q.size() >= K){
			mp[q.front()]--;
			q.pop();
		}
	}
	printf("%lld\n", ans);
	return 0;
}


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

int main() {
    int n;
    cin >>n;
    vector <long double> a(n);
    vector<long double>b(n);
    long double sum=0;
    for(int i =0; i <n; i++){
        cin >>a.at(i);
        sum +=a.at(i);
        b.at(i) =sum;
    }
    long double mean =sum/2;

    long double dist =20202020210;
    for(int i =0; i < n; i++){
        if(std::abs(mean - b.at(i))<dist){
            dist = std::abs(mean - b.at(i));
        }

    }
    long int  ans = 2*dist;

    cout <<ans<<endl;

}

Score: 200 points

Problem Statement

Takahashi, who works at DISCO, is standing before an iron bar.
The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters.

Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length.
However, this may not be possible as is, so he will do the following operations some number of times before he does the cut:

Choose one section and expand it, increasing its length by 1 millimeter. Doing this operation once costs 1 yen (the currency of Japan).

Choose one section of length at least 2 millimeters and shrink it, decreasing its length by 1 millimeter. Doing this operation once costs 1 yen.

Find the minimum amount of money needed before cutting the bar into two parts with the same length.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 2020202020

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print an integer representing the minimum amount of money needed before cutting the bar into two parts with the same length.

Sample Input 1

3
2 4 3

Sample Output 1

3

The initial lengths of the sections are [2, 4, 3] (in millimeters). Takahashi can cut the bar equally after doing the following operations for 3 yen:

Shrink the second section from the left. The lengths of the sections are now [2, 3, 3].

Shrink the first section from the left. The lengths of the sections are now [1, 3, 3].

Shrink the second section from the left. The lengths of the sections are now [1, 2, 3], and we can cut the bar at the second notch from the left into two parts of length 3 each.

Sample Input 2

12
100 104 102 105 103 103 101 105 104 102 104 101

Sample Output 2

0


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

using ll=long long;

int in(){
  int a;
  cin >> a;
  return a;
}//int型関数の受け取り

void forin(int* x,int y){
  for (int i=0;i<y;i++){
    cin >> x[i];
  }
}//(x,y) int型配列x[y]の受け取り

int fact(int x){
  if (x == 1) return 1;
  return x*fact(x-1);
}//(x) x!

int div1(ll x){
  return x%1000000007;
}

int xy(int x,int y){
    if (x ==1 && y== 1) return 400000;
    return 0;
}

main(){
    int n=in(),sum=0;
    deque<ll> a;
    for (int i=0;i<n;i++) a.push_back(in());
    ll m=0;
    bool fb=true;
    while(!a.empty()){
        if (fb){
            m+=a.front();
            a.pop_front();
            if (m>0) fb=false;
        }
        else {
            m-=a.back();
            a.pop_back();
            if (m<0) fb=true;
        }
    }
    cout << abs(m) << endl;
}


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

typedef unsigned long ul;
typedef unsigned long long ull;
typedef long long ll;
typedef vector<ll> vint;
typedef vector<vector<ll>> vvint;
typedef vector<vector<vector<ll>>> vvvint;
typedef vector<string> vstring;
typedef vector<vector<string>> vvstring;
typedef vector<char> vchar;
typedef vector<vector<char>> vvchar;
typedef vector<long double> vdouble;
typedef vector<vector<long double>> vvdouble;
typedef vector<vector<vector<long double>>> vvvdouble;
typedef pair<ll,ll> pint;
typedef vector<pint> vpint;
typedef vector<bool> vbool;

#define rep(i,n) for(ll i=0;i<n;i++)
#define repf(i,f,n) for(ll i=f;i<n;i++)
#define repr(i,n) for(ll i=n-1;i>=0;i--)
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define ALL(obj) (obj).begin(), (obj).end()
// #define LLONG_MAX 9223372036854775806
#define vmax(vec) *max_element(vec.begin(), vec.end())
#define vmin(vec) *min_element(vec.begin(), vec.end())
#define vsort(vec) sort(vec.begin(), vec.end())
#define vsortgr(vec) sort(vec.begin(), vec.end(), greater<ll>())
#define MOD 1000000007
// #define MOD 998244353

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

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

template< typename T >
struct edge {
  int src, to;
  T cost;

  edge(int to, T cost) : src(-1), to(to), cost(cost) {}

  edge(int src, int to, T cost) : src(src), to(to), cost(cost) {}

  edge &operator=(const int &x) {
    to = x;
    return *this;
  }

  operator int() const { return to; }
};

template< typename T >
using Edges = vector< edge< T > >;
template< typename T >
using WeightedGraph = vector< Edges< T > >;
using UnWeightedGraph = vector< vector< int > >;
template< typename T >
using Matrix = vector< vector< T > >;

ll gcd(ll a, ll b)
{
    if (a < b) {
        a ^= b;
        b ^= a;
        a ^= b;
    }

    return b ? gcd(b, a % b) : a;
}

ll lcm(int a, ll b)
{
    return a * b / gcd(a, b);
}

// 繰り返し二乗法
ll power(ll a, ll b){
  if(a==1)return a;
  // if(a==0)re
	ll res=1;
	while(b>0){
		if(b&1) res=res*a%MOD;
		a=a*a%MOD;
		b>>=1;
	}
	return res;
}

const int MAX=1000000;

ll fact[MAX], fact_inv[MAX];

void init_fact(ll n){
  fact[0]=1;
  // 階乗の計算
  rep(i, n) fact[i+1]=fact[i]*(i+1)%MOD;
  fact_inv[n]=power(fact[n], MOD-2);
  // 逆元の計算
  for(ll i=n-1;i>=0;i--) fact_inv[i]=fact_inv[i+1]*(i+1)%MOD;
}

ll comb(ll n, ll r){
	return (fact[n]*fact_inv[r])%MOD*fact_inv[n-r]%MOD;
}

ll perm(ll n, ll r){
  return (fact[n]*fact_inv[n-r])%MOD;
}

struct UnionFind {
    vector<ll> par; // par[i]:iの親の番号　(例) par[3] = 2 : 3の親が2
    vector<ll> num;
    // vector<ll> dist; // rootまでの距離

    UnionFind(ll N) : par(N), num(N){ //最初は全てが根であるとして初期化
      for(ll i = 0; i < N; i++) par[i] = i;
      for(ll i = 0; i < N; i++) num[i] = 1;
      // for(ll i = 0; i < N; i++) dist[i] = 0;

    }

    ll root(ll x) { // データxが属する木の根を再帰で得る：root(x) = {xの木の根}
        if (par[x] == x) return x;
        return par[x] = root(par[x]);
    }

    void unite(ll x, ll y) { // xとyの木を併合
        ll rx = root(x); //xの根をrx
        ll ry = root(y); //yの根をry
        if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま
        par[rx] = ry; //xとyの根が同じでない(=同じ木にない)時：xの根rxをyの根ryにつける
        num[ry] = num[rx] + num[ry];
    }

    bool same(ll x, ll y) { // 2つのデータx, yが属する木が同じならtrueを返す
        ll rx = root(x);
        ll ry = root(y);
        return rx == ry;
    }

    ll size(ll x){
      return num[root(x)];
    }

};

vint divisor(ll n){ // nの約数
  vint ret;
  for(ll i=1;i*i<=n;i++){
    if(n%i == 0){
      ret.pb(i);
      if(i*i!=n) ret.pb(n/i);
    }
  }
  vsort(ret);
  return ret;
}

ll get_digit_in(ll n, ll i){ // i桁目の数字を得る。
  for(ll j=0;j<i-1;j++){
    n/=10;
  }
  return n%10;
}

ll get_digit(ll n){
  ll rtn=0;
  while(n>0){
    n/=10;
    rtn++;
  }
  return rtn;
}

map<ll,ll> prime_factor(ll n){
  map<ll,ll> rtn;
  for(ll i=2;i*i<=n;i++){
    while(n%i == 0){
      rtn[i]++;
      n /= i;
    }
  }
  if(n!=1) rtn[n] = 1;
  return rtn;
}

// nPnの順列に対して処理を実行する
void foreach_permutation(ll n, function<void(ll *)> f) {
  ll indexes[n];
  for (ll i = 0; i < n; i++) indexes[i] = i;
  do {
    f(indexes);
  } while (std::next_permutation(indexes, indexes + n));
}

void recursive_comb(ll *indexes, ll s, ll rest, function<void(ll *)> f) {
  if (rest == 0) {
    f(indexes);
  } else {
    if (s < 0) return;
    recursive_comb(indexes, s - 1, rest, f);
    indexes[rest - 1] = s;
    recursive_comb(indexes, s - 1, rest - 1, f);
  }
}

// nCkの組み合わせに対して処理を実行する
void foreach_comb(ll n, ll k, function<void(ll *)> f) {
  ll indexes[k];
  recursive_comb(indexes, n - 1, k, f);
}

// nPkの順列に対して処理を実行する
void foreach_permutation(ll n, ll k, function<void(ll *)> f) {
  foreach_comb(n, k, [&](ll *c_indexes) {
    foreach_permutation(k, [&](ll *p_indexes) {
      ll indexes[k];
      for (ll i = 0; i < k; i++) {
        indexes[i] = c_indexes[p_indexes[i]];
      }
      f(indexes);
    });
  });
}

// ll arr[1000500];
// vint primes;

// //エラトステネスの篩
// void Eratosthenes(){
//   ll N = 1000500;
// 	for(ll i = 0; i < N; i++){
// 		arr[i] = 1;
// 	}
// 	for(ll i = 2; i < sqrt(N); i++){
// 		if(arr[i]){
// 			for(ll j = 0; i * (j + 2) < N; j++){
// 				arr[i *(j + 2)] = 0;
// 			}
// 		}
// 	}

// 	for(ll i = 2; i < N; i++){
// 		if(arr[i]){
//       primes.pb(i);
// 			//cout << i << endl;
// 		}
// 	}
// }

void printv(vint &V){
  for(auto e:V)cout<<e<<" ";
  cout<<endl;
}

void print() {}

template <class Head, class... Tail>
void print(Head&& head, Tail&&... tail){
  cout<< head << " ";
  print(forward<Tail>(tail)...);
}

int main() {
  cout<<fixed<<setprecision(12);

  ll M;cin>>M;
  vint d(M),c(M);rep(i,M)cin>>d[i]>>c[i];

  ll ans = 0;

  vint arr(M,0);

  rep(i,M){
    ll s = d[i]*c[i];
    ans += (c[i]-1);
    ll cnt = 0;

    // ll div = 10;
    // while( s >= div){
    //   cnt++;
    //   div *= 10;
    //   cnt += s / div;
    // }

    cnt = (s-1)/9;

    ans += cnt;
    arr[i] = (d[i]*c[i]+cnt)%10;
    // print(cnt, ans);
    // cout<<endl;
  }

  ll now = arr[0];

  for(ll i = 1; i < M; ++i) {
    now += arr[i];
    ans++;
    while(now >= 10){
      now = now/10 + now%10;
      ans++;
    }
  }

  cout << ans <<endl;

}

//

Score: 500 points

Problem Statement

N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals.

The preliminary stage consists of several rounds, which will take place as follows:

All the N contestants will participate in the first round.

When X contestants participate in some round, the number of contestants advancing to the next round will be decided as follows:

The organizer will choose two consecutive digits in the decimal notation of X, and replace them with the sum of these digits. The number resulted will be the number of contestants advancing to the next round.

For example, when X = 2378, the number of contestants advancing to the next round will be 578 (if 2 and 3 are chosen), 2108 (if 3 and 7 are chosen), or 2315 (if 7 and 8 are chosen).

When X = 100, the number of contestants advancing to the next round will be 10, no matter which two digits are chosen.

The preliminary stage ends when 9 or fewer contestants remain.

Ringo, the chief organizer, wants to hold as many rounds as possible.
Find the maximum possible number of rounds in the preliminary stage.

Since the number of contestants, N, can be enormous, it is given to you as two integer sequences d_1, \ldots, d_M and c_1, \ldots, c_M, which means the following: the decimal notation of N consists of c_1 + c_2 + \ldots + c_M digits, whose first c_1 digits are all d_1, the following c_2 digits are all d_2, \ldots, and the last c_M digits are all d_M.

Constraints

1 \leq M \leq 200000

0 \leq d_i \leq 9

d_1 \neq 0

d_i \neq d_{i+1}

c_i \geq 1

2 \leq c_1 + \ldots + c_M \leq 10^{15}

Input

Input is given from Standard Input in the following format:

M
d_1 c_1
d_2 c_2
:
d_M c_M

Output

Print the maximum possible number of rounds in the preliminary stage.

Sample Input 1

2
2 2
9 1

Sample Output 1

3

In this case, N = 229 contestants will participate in the first round. One possible progression of the preliminary stage is as follows:

229 contestants participate in Round 1, 49 contestants participate in Round 2, 13 contestants participate in Round 3, and 4 contestants advance to the finals.

Here, three rounds take place in the preliminary stage, which is the maximum possible number.

Sample Input 2

3
1 1
0 8
7 1

Sample Output 2

9

In this case, 1000000007 will participate in the first round.


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,n) for(ll i=0;i<n;++i)
#define P pair<ll,ll>
#define Graph vector<vector<P>>
#define fi first
#define se second
constexpr ll mod=1000000007;
constexpr ll INF=(1ll<<60);
constexpr double pi=3.14159265358979323846;
template<typename T> inline bool chmax(T& a,T b){if(a<b){a=b;return 1;} return 0;}
template<typename T> inline bool chmin(T& a,T b){if(a>b){a=b;return 1;} return 0;}

int main(){
    ll r;cin>>r;
    cout<<r*r<<endl;
    return 0;
}

Score : 100 points

Problem Statement

Given is an integer r.

How many times is the area of a circle of radius r larger than the area of a circle of radius 1?

It can be proved that the answer is always an integer under the constraints given.

Constraints

1 \leq r \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r

Output

Print the area of a circle of radius r, divided by the area of a circle of radius 1, as an integer.

Sample Input 1

2

Sample Output 1

4

The area of a circle of radius 2 is 4 times larger than the area of a circle of radius 1.

Note that output must be an integer - for example, 4.0 will not be accepted.

Sample Input 2

100

Sample Output 2

10000


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
using namespace std;

int main() {
  int r;
  cin >> r;
  cout << r * r << endl;
}


#include<iostream>
using namespace std;
int main()
{
    int r;
    cin>>r;
    if(r>=1&&r<=100)
    cout<<r*r;

}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e9;
const ll mod = 1e9+7;
typedef pair<int,int> P;
#define rep(i,N) for(int i=0;i<N;i++)
#define rep2(i,m,N) for(int i=m;i<N;i++)
#define mm(n,m) memset(n,m,sizeof(n))

ll dp[3001][3001];

int main(){
  int n,t;
  cin>>n>>t;
  int a[n+1],b[n+1];
  a[0]=0,b[0]=0;
  vector<pair<int,int>>ab(n+1);
  rep(i,n){
    cin>>a[i+1]>>b[i+1];
    ab[i+1]=make_pair(b[i+1],a[i+1]);
  }
  sort(ab.begin(),ab.end(),greater<pair<int,int>>());
  //rep(i,n)cout<<ab[i].first<<endl;
  mm(dp,0);
  rep2(i,1,n+1){
    rep(j,t){
      dp[i][j+ab[i].second] = max(dp[i-1][j]+ab[i].first,dp[i-1][j]);
    }
  }

  // rep2(i,1,n+1){
  //   rep(j,t){
  //     cout<<"i , j:"<<i<<" "<<j<<" dp:"<<dp[i][j]<<endl;
  //   }
  // }
  ll ans = 0;
  rep2(i,1,n+1){
    ans = max(ans,dp[i][t-1]);
  }
  ans += ab[0].first;
  cout<<ans<<endl;
}

Score : 500 points

Problem Statement

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.

The restaurant has the following rules:

You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.

You cannot order the same kind of dish more than once.

Until you finish eating the dish already served, you cannot order a new dish.

After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

2 \leq N \leq 3000

1 \leq T \leq 3000

1 \leq A_i \leq 3000

1 \leq B_i \leq 3000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

By ordering the first and second dishes in this order, Takahashi's happiness will be 110.

Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within 60 minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

By ordering the second and third dishes in this order, Takahashi's happiness will be 50.

We cannot order three dishes, in whatever order we place them.

Sample Input 4

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Sample Output 4

145


#include <iostream>
#include <numeric>
#include <iomanip>
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

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

	cout << (N-1)/2<< endl;
}

Score : 100 points

Problem Statement

How many ways are there to choose two distinct positive integers totaling N, disregarding the order?

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

4

Sample Output 1

1

There is only one way to choose two distinct integers totaling 4: to choose 1 and 3. (Choosing 3 and 1 is not considered different from this.)

Sample Input 2

999999

Sample Output 2

499999


#include<bits/stdc++.h>
#define endl "\n"
#define pb push_back
#define ll long long
#define ld long double
#define d1(x)  cerr << #x << "--> " << x << endl
#define d2(x, y)  cerr << #x << "--> " << x << " | " << #y << "--> " << y <<endl
#define d3(x, y,z)  cerr << #x << "--> " << x << " | " << #y << "--> " << y <<" | " << #z << "--> "<< z<< endl
#define vpll vector<pair<ll,ll>>
#define F first
#define S second
using namespace std;

ll mode=pow(10,9)+7;
bool cmp(pair<ll,ll> x, pair<ll, ll> y){
	return x.S<y.S;
}

int main(){

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

	ios::sync_with_stdio(0);
    cin.tie(0);

	ll n;
	cin>>n;
	ll a[n];
	ll f[n]={0};
	for (int i=0;i<n;i++){
		cin>>a[i];
		f[a[i]]++;
	}
	ll ans=1;
	sort(a, a+n);
	for (int i=1;i<n;i++){
		ans=(ans%998244353*f[a[i]-1]%998244353)%998244353;
	}
	if (f[0]!=1){
		cout<<0<<endl;
	}
	else{
		cout<<ans<<endl;
	}

 	return 0;
}

Score : 300 points

Problem Statement

Given is an integer sequence D_1,...,D_N of N elements. Find the number, modulo 998244353, of trees with N vertices numbered 1 to N that satisfy the following condition:

For every integer i from 1 to N, the distance between Vertex 1 and Vertex i is D_i.

Notes

A tree of N vertices is a connected undirected graph with N vertices and N-1 edges, and the distance between two vertices are the number of edges in the shortest path between them.

Two trees are considered different if and only if there are two vertices x and y such that there is an edge between x and y in one of those trees and not in the other.

Constraints

1 \leq N \leq 10^5

0 \leq D_i \leq N-1

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the answer.

Sample Input 1

4
0 1 1 2

Sample Output 1

2

For example, a tree with edges (1,2), (1,3), and (2,4) satisfies the condition.

Sample Input 2

4
1 1 1 1

Sample Output 2

0

Sample Input 3

7
0 3 2 1 2 2 1

Sample Output 3

24


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i, n) for(ll i=0; i<n; i++)
#define repr(i, s, e) for(ll i=s; i>=e; i--)
#define reps(i, s, e) for(ll i=s; i<=e; i++)
#define inf 1e18
#define all(v) v.begin(),v.end()
#define vsort(v) sort(v.begin(), v.end())
#define vsortr(v) sort(v.begin(), v.end(), greater<ll>())
#define ceil(a, b) (a+b-1)/b
#define ok cout << "ok" << endl;
#define sp << " " <<
template<typename A, size_t N, typename T> void Fill(A (&array)[N], const T &val){ fill((T*)array, (T*)(array+N), val); }
template<typename T> inline bool chmax(T &a, T b){ if(a<b){ a=b; return true; } return false; }
template<typename T> inline bool chmin(T &a, T b){ if(b<a){ a=b; return true; } return false; }
template<typename T> void vdebug(vector<T> v){ cout << "vdebug" << endl; for(auto vv : v){ cout << vv << " "; } cout << endl; }
template<typename T> void adebug(T arr[], ll n){ cout << "adebug" << endl; reps(i, 0, n){ cout << arr[i] << " "; } cout << endl; }
template<typename T1, typename T2> void mdebug(map<T1, T2> mp){ cout << "mdebug" << endl; for(auto const& m : mp){ cout << m.first sp m.second << endl; }}
template<typename T1, typename T2> void mldebug(multimap<T1, T2> mp){ cout << "mldebug" << endl; for(auto const& m : mp){ cout << m.first sp m.second << endl; }}
template<typename T1, typename T2> void mdebugr(map<T1, T2, greater<T1>> mp){ cout << "mdebug" << endl; for(auto const& m : mp){ cout << m.first sp m.second << endl; }}
template<typename T1, typename T2> void mldebugr(multimap<T1, T2, greater<T1>> mp){ cout << "mldebug" << endl; for(auto const& m : mp){ cout << m.first sp m.second << endl; }}
void ans(bool b){ if(b) cout << "Yes" << endl; else cout << "No" << endl; }
void ans2(bool b){ if(b) cout << "YES" << endl; else cout << "NO" << endl; }
int dx[] = {1, -1, 0, 0, 1, -1, 1, -1};
int dy[] = {0, 0, 1, -1, 1, -1, -1, 1};

ll mod = 998244353;

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

    ll n, d[100010];
    ll cnt[100010];
    Fill(cnt, 0);
    ll maxi = 0;
    cin >> n;
    reps(i, 1, n){
        cin >> d[i];
        cnt[d[i]]++;
        maxi = max(maxi, d[i]);
    }

    if(d[1] != 0){
        cout << 0 << endl;
        return 0;
    }

    ll res = 1;
    reps(i, 0, maxi){
        if(i == 1 || i == 0) continue;
        ll num = long(pow(cnt[i-1], cnt[i]))%mod;
        res *= pow(cnt[i-1], cnt[i]);
        res %= mod;
    }

    cout << res << endl;

    return 0;
}


#include <iostream>
#include <vector>
#include <array>
#include <deque>
#include <stack>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <utility>
#include <cmath>
#include <iomanip>
#include <cassert>
#include <complex>
#include <bitset>
#include <functional>

using namespace std;
using ll=long long int;

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (auto &e: a) cin >> e;
    vector<int> b(n);
    for (auto &e: b) cin >> e;

    vector<pair<int, int>> t(n);
    for (int i = 0; i < n; ++i) {
        t[i].first = b[i];
        t[i].second = a[i];
    }
    sort(t.begin(), t.end());
    for (int i = 0; i < n; ++i) {
        a[i] = t[i].second;
        b[i] = t[i].first;
    }

    vector<int> si(n);
    iota(si.begin(), si.end(), 0);
    sort(si.begin(), si.end(), [&](int l, int r){
        return a[l] < a[r];
    });

    for (int i = 0; i < n; ++i) {
        if (a[si[i]] > b[i]) {
            cout << "No" << endl;
            return 0;
        }
    }

    int len = 0;
    int cur = si[0];
    while (cur != 0) {
        cur = si[cur];
        ++len;
    }

    if (len < n-1) {
        cout << "Yes" << endl;
        return 0;
    }

    for (int i = 0; i < n-1; ++i) {
        if (a[si[i+1]] <= b[i]) {
            cout << "Yes" << endl;
            return 0;
        }
    }

    cout << "No" << endl;

    return 0;
}

Score : 600 points

Problem Statement

Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N.
Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:

Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y.

Constraints

2 \leq N \leq 10^5

1 \leq A_i,B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

3
1 3 2
1 2 3

Sample Output 1

Yes

We should swap the values of A_2 and A_3.

Sample Input 2

3
1 2 3
2 2 2

Sample Output 2

No

Sample Input 3

6
3 1 2 6 3 4
2 2 8 3 4 3

Sample Output 3

Yes


#include<bits/stdc++.h>
#define pb push_back
#define all(v) (v).begin() , (v).end()
#define popcnt(x) __builtin_popcount(x)
#define inf 0x3f3f3f3f
#define watch(x) cout << (#x) << " is " << (x) << endl
#define rand() (rand() << 15 | rand())
using namespace std;
typedef long long  ll;
#define EPS 1e-9
#define PI acos(-1.0)

int main() {
   ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
   int n;
   cin >> n;
   vector<int> b(n);
   vector<pair<int ,int>> a(n);
   set<pair<pair<int , int> , int>> s;
   for(int i = 0 ; i < n ; ++i){
      cin >> b[i];
   }
   for(int i = 0 ; i < n ; ++i){
      cin >> a[i].first;
      a[i].second = i;
   }
   for(int i = 0 ; i < n ; ++i){
      s.insert({{b[i] , (a[i].first > b[i])} , i});
   }
   vector<pair<int , int>> sor(all(a));
   sort(all(sor));
   int cnt = 0;
   for(int i = n - 1 ; i >= 0 ; --i){
      int j = sor[i].second;
      if(b[j] > a[j].first){
         ++cnt;
         auto it = s.rbegin();
//         cout << it->first.first << ' ' <<  a[j].first << endl;
         if(it->first.first < a[j].first){
            cout << "No\n";
            return 0;
         }
         int k = it->second;
//         cout << j << ' ' << k << endl;
         swap(b[j] , b[k]);
         s.erase(*it);
      }
      else{
         s.erase({{b[j] , (a[i].first > b[i])} , j});
      }
   }
//   watch(cnt);
//   for(int i = 0 ; i < n ; ++i){
//      cout << b[i] << ' ' << a[i].first << endl;
//   }
   cout << (cnt <= n - 2 ? "Yes\n" : "No\n");
}


#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
   int n;
   cin>>n;
   long long int a[n],b[n];
   for(int i=0;i<n;i++){
      cin>>a[i];
   }
   for(int i=0;i<n;i++){
      cin>>b[i];
   }
   int count=0;
   for(int i=0;i<n;i++){
      if(a[i]>b[i]){
	 count++;
      }
   }
   if(count>n-2){
      cout<<"No"<<endl;
      exit(0);
   }
   int maxa=a[0];
   for(int i=1;i<n;i++){
      if(a[i]>maxa){
	 maxa=a[i];
      }
   }
   int maxb=b[0];
   for(int i=1;i<n;i++){
      if(b[i]>maxb){
	 maxb=b[i];
      }
   }
   if(maxa>maxb){
      cout<<"No"<<endl;
   }
   else if(count<=n-2 && maxa<=maxb){
      cout<<"Yes"<<endl;
   }
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (long long i = 0; i < (long long)(n); i++)
typedef long long ll;
typedef pair<ll, ll> P;
int main(){
    ll n;
    ll k;
    cin >> n >> k;
    vector<ll> a(n),b(n),c(n);
    vector<P> ans(n);
    rep(i,n){
        c[i] = 2*n+k+i;
        a[i] = k+i;
        b[i] = 2*n+k-i-1;
    }
    vector<bool>fin(n);
    int j = 1;
    rep(i,n){
        if(i+j<n && fin[i]==false&&fin[i+j]==false){
            swap(a[i],a[i+j]);
            fin[i]=true;
            fin[i+j]=true;
            j++;
        }
        ans[i] = P(a[i]+b[i],a[i]);
    }
    sort(ans.begin(),ans.end());
    rep(i,n){
        if(c[i]<ans[i].first){
            cout << "-1" << endl;
            return 0;
        }
    }
    rep(i,n){
        cout << ans[i].second << ' ' << ans[i].first-ans[i].second <<' ' << c[i]<<endl;
    }
    return 0;
}

Score : 700 points

Problem Statement

Given are positive integers N and K.

Determine if the 3N integers K, K+1, ..., K+3N-1 can be partitioned into N triples (a_1,b_1,c_1), ..., (a_N,b_N,c_N) so that the condition below is satisfied. Any of the integers K, K+1, ..., K+3N-1 must appear in exactly one of those triples.

For every integer i from 1 to N, a_i + b_i \leq c_i holds.

If the answer is yes, construct one such partition.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq 10^9

Input

Input is given from Standard Input in the following format:

N K

Output

If it is impossible to partition the integers satisfying the condition, print -1. If it is possible, print N triples in the following format:

a_1 b_1 c_1
:
a_N b_N c_N

Sample Input 1

1 1

Sample Output 1

1 2 3

Sample Input 2

3 3

Sample Output 2

-1


#include <bits/stdc++.h>

using namespace std;

#define sim template <class c
#define ris return *this
#define dor > debug &operator<<
#define eni(x)                                                                        \
	sim > typename enable_if<sizeof dud<c>(0) x 1, debug &>::type operator<<(c i) \
	{
sim > struct rge
{
	c b, e;
};
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c *x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug
{
#ifdef LOCAL
	~debug()
	{
		cerr << endl;
	}
	eni(!=) cerr << boolalpha << i;
	ris;
} eni(==) ris << range(begin(i), end(i));
}
sim, class b dor(pair<b, c> d)
{
	ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d)
{
	*this << "[";
	for (auto it = d.b; it != d.e; ++it)
		*this << ", " + 2 * (it == d.b) << *it;
	ris << "]";
}
#else
	sim dor(const c &)
	{
		ris;
	}
#endif
}
;
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

#define forn(i, n) for (ll i = 0; i < int(n); i++)
#define rfor(n, i) for (ll i = (n - 1); i >= 0; --i)
#define all(V) V.begin(), V.end()
#define rall(V) V.rbegin(), V.rend()
#define len(V) (int)V.size()
#define ll long long
#define ld long double
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define endl '\n'
#define M_PI 3.14159265358979323846
#define EPS 1e-7

void solve()
{
	string s; cin >> s;
	int n = s.length();
	ll res = 0, cnt = 0;
	for (int i = 0; i < n; ++i)
	{
		if (s[i] == '>')
		{
			cnt++;
			res += cnt;
		}
		else
		{
			cnt = 0;
		}
	}
	cnt = 0;
	for (int i = n - 1; i >= 0; --i)
	{
		if (s[i] == '<')
		{
			cnt++;
			res += cnt;
		}
		else
		{
			cnt = 0;
		}
	}
	cnt = 0;
	//cout << res << endl;
	for (int i = 1; i < n; ++i)
	{
		if (s[i] != s[i - 1])
		{
			res--;
			i++;
		}
	}
	cout << res;
}

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

Score : 300 points

Problem Statement

Given is a string S of length N-1.
Each character in S is < or >.

A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1):

If S_i= <: a_i<a_{i+1}

If S_i= >: a_i>a_{i+1}

Find the minimum possible sum of the elements of a good sequence of N non-negative integers.

Constraints

2 \leq N \leq 5 \times 10^5

S is a string of length N-1 consisting of < and >.

Input

Input is given from Standard Input in the following format:

S

Output

Find the minimum possible sum of the elements of a good sequence of N non-negative integers.

Sample Input 1

<>>

Sample Output 1

3

a=(0,2,1,0) is a good sequence whose sum is 3.
There is no good sequence whose sum is less than 3.

Sample Input 2

<>>><<><<<<<>>><

Sample Output 2

28


#include <bits/stdc++.h>

using namespace std;

int main(){
  string s;
  char c;
  int64_t ans=0;
  cin >> s;
  vector<int> a(s.size()+1);
  vector<int> b(s.size()+1);
  a.front() = 0;
  b.back() = 0;

  for(int i=0;i<s.size();i++){
    if(s.at(i) == '<'){
      a.at(i+1) = a.at(i)+1;
    }
    else{
      a.at(i+1) = 0;
    }
  }

  for(int i=s.size()-1;i>=0;i--){
    if(s.at(i) == '>'){
      b.at(i) = b.at(i+1)+1;
    }
    else{
      b.at(i) = 0;
    }
  }

  for(int i=0;i<s.size()+1;i++){
    //cout << a.at(i) << "  " << b.at(i) << endl;
    ans = ans + max(a.at(i),b.at(i));
  }

  cout << ans << endl;

  return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fr first
#define sc second
#define clr(a) memset(a, 0, sizeof(a))
#define sz(x) x.size()
#define printarray(arr) for (auto it = arr.begin(); it != arr.end(); ++it) cout<<*it<<" "; cout<<endl;
#define rep(n) for (ll i = 0; i < n; i++)
#define repc(i, n) for (ll i = 0; i < n; i++)
#define FOR(i, x, y) for (int i = x; i < y; i++)
#define DEC(i, x, y) for (int i = x; i >= y; i--)
#define all(v) v.begin(), v.end()
#define min3(a, b, c) min(a, min(b, c))
#define max3(a, b, c) max(a, max(b, c))
#define alla(a, n) a, a + n
#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) (a * b)/gcd(a, b)
#define int long long int
#define ull unsigned long long

using namespace std;
const int MOD = 1e9 + 7;
const int MAXN = 5e5 + 5;

vector<int> adj[MAXN];
int deg[MAXN];
bool visited[MAXN];
int depth[MAXN] = {0};

void dfs(int s){
	visited[s] = true;
	for(int u: adj[s]){
		if(!visited[u]){
			dfs(u);
			depth[s] = max(depth[s], depth[u]+1);
		}
	}
	return;
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    string s;
    cin>>s;
    int n = s.length() + 1;
    for(int i = 1;i<n;i++){
    	if(s[i-1] == '<'){
    		adj[i+1].pb(i);
    		deg[i]++;
    	} else {
    		adj[i].pb(i+1);
    		deg[i+1]++;
    	}
    }
    for(int i = 1;i<=n;i++){
    	if(deg[i] == 0){
    		memset(visited, 0, sizeof(visited));
    		dfs(i);
    	}
    }
    int sum = 0;
    for(int i = 1;i<=n;i++){
    	sum += depth[i];
    }
    cout<<sum<<endl;

    return 0;
}


/**
SXR0aXAkI0JwbXptI3FhI3Z3I293bCNqY2IjUG0jMCNicG0jVHFkcXZvLyNCcG0jQW10bjBhY2phcWFicXZvLyNNYm16dml0MSNWdyNhdGN1am16I2tpdiNhbXF9bSNQcXUjVnd6I0F0bW14MSNQcWEjaXptI2l0dCNicHF2b2EjUXYjYnBtI3BtaWRtdmEjaXZsI3d2I21pemJwMSNFcHcjcWEjYnBtem0ja2l2I3F2Ym16a21sbSNRdiNQcWEjeHptYW12a20jbXtrbXhiI0lhI3BtI3htenVxYmJtYnBHI1BtI3N2d2VtYnAjRXBpYiMraXh4bWl6bWJwI2J3I1BxYSNrem1pYmN6bWEjSWEsI0ptbnd6bSN3eiNJbmJteiN3eiNKbXBxdmwjYnBtdTEjVnd6I2FwaXR0I2JwbXwja3d1eGlhYSNJY29wYiN3biNwcWEjc3Z3ZXRtbG9tI017a214YiNpYSNQbSNlcXR0bWJwMSNQcWEjYnB6d3ZtI2x3YnAjbXtibXZsI1dkbXojYnBtI3BtaWRtdmEjSXZsI3d2I21pemJwLyNpdmwjUG0jbm1tdG1icCNWdyNuaWJxb2NtI3F2I29jaXpscXZvI0l2bCN4em1hbXpkcXZvI2JwbXUvI053eiNQbSNxYSNicG0jVXdhYiNQcW9wMSNCcG0jQWN4em11bSMrcXYjb3R3enwsMQ==
*/
#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back

const long long MOD = 1e9 + 7;
const long long MAXN = 1e6 + 1;
using namespace std;

typedef long long ll;

long long readInt() {
    bool minus1 = false;
    long long result = 0;
    char ch;
    ch = getchar();
    while (true) {
        if (ch == '-') break;
        if (ch >= '0' && ch <= '9') break;
        ch = getchar();
    }
    if (ch == '-') minus1 = true; else result = ch-'0';
    while (true) {
        ch = getchar();
        if (ch < '0' || ch > '9') break;
        result = result*10 + (ch - '0');
    }
    if (minus1)
        return -result;
    else
        return result;
}

pair<int,int> a[MAXN];

int main() {
    int n = readInt();
    for (int i = 1; i <= n; i++) {
        a[i] = {readInt(), readInt()};
    }
    sort(a + 1, a + 1 + n);
    multiset <int> s1;
    multiset <int> s2;
    for (int i = 1; i <= n; i++) {
        s2.insert(a[i].S);
    }
    ll ans = 0;
    for (int i = 1; i < n; i ++) {
        /// min(R) - max(L) + 1
        s2.erase(s2.find(a[i].S));
        s1.insert(a[i].S);
        int min_R_1 = *s1.begin();
        int min_R_2 = *s2.begin();
        if (min_R_1 <= min_R_2) {
            ///checking for >
            auto nxt = s1.upper_bound(min_R_2);
            if (nxt == s1.end()) {
                //correct
              	ans = max(ans, max(1ll * min_R_1 - a[i].F + 1, 0ll) + max(1ll * min_R_2 - a[n].F + 1, 0ll));
            } else {
                ans = max(ans, max(1ll * (*nxt) - a[i].F + 1, 0ll) + max(1ll * min_R_1 - a[n].F + 1, 0ll));
            }
            /// checking for =
            if (s1.count(min_R_2) > 1) {
				ans = max(ans, max(1ll * min_R_2 - a[i].F + 1, 0ll) + max(1ll * min_R_2 - a[n].F + 1, 0ll));
            }
        } else {
            ans = max(ans, max(1ll * min_R_1 - a[i].F + 1, 0ll) + max(1ll * min_R_2 - a[n].F + 1, 0ll));
        }
        if (min_R_1 >= min_R_2) {
        	//correct
          	auto nxt = s1.end();
        	nxt--;
			ans = max(ans, max(1ll * (*nxt) - a[i].F + 1, 0ll) + max(1ll * min_R_2 - a[n].F + 1, 0ll));
        }
        if (a[i].F == a[n].F) assert(0);
    }
    cout << ans;
    return 0;
}

Score : 600 points

Problem Statement

10^9 contestants, numbered 1 to 10^9, will compete in a competition.
There will be two contests in this competition.

The organizer prepared N problems, numbered 1 to N, to use in these contests.
When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclusive), and will not be solved by any other contestants.

The organizer will use these N problems in the two contests.
Each problem must be used in exactly one of the contests, and each contest must have at least one problem.

The joyfulness of each contest is the number of contestants who will solve all the problems in the contest.
Find the maximum possible total joyfulness of the two contests.

Constraints

2 \leq N \leq 10^5

1 \leq L_i \leq R_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
L_2 R_2
\vdots
L_N R_N

Output

Print the maximum possible total joyfulness of the two contests.

Sample Input 1

4
4 7
1 4
5 8
2 5

Sample Output 1

6

The optimal choice is:

Use Problem 1 and 3 in the first contest. Contestant 5, 6, and 7 will solve both of them, so the joyfulness of this contest is 3.

Use Problem 2 and 4 in the second contest. Contestant 2, 3, and 4 will solve both of them, so the joyfulness of this contest is 3.

The total joyfulness of these two contests is 6. We cannot make the total joyfulness greater than 6.

Sample Input 2

4
1 20
2 19
3 18
4 17

Sample Output 2

34

Sample Input 3

10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526

Sample Output 3

540049931


#include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
#include "numeric"
#include "cassert"
#include "functional"

using namespace std;

constexpr long long int MOD = 1000000007;
//const int MOD = 1000000007;
//constexpr int MOD = 998244353;
//constexpr long long int MOD = 998244353;

constexpr double EPS = 1e-8;

//int N, M, K, H, W, L, R;
long long int N, M, K, H, W, L, R;

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

	cin >> N;
	vector<pair<long long int, long long int>>v(N);
	for (auto &i : v)cin >> i.first >> i.second;
	long long int minl = MOD;
	long long int maxr = 0;
	for (auto i : v) {
		maxr = max(maxr, i.second);
	}
	sort(v.begin(), v.end());
	minl = v[0].first;
	long long int ans = 0;
	vector<long long int>vl(N);
	vector<long long int>revl(N, v.back().first);
	for (int i = 0; i < N; i++) {
		vl[i] = v[i].first;
	}
	vector<long long int>vr(N);
	vector<long long int>revr(N);
	for (int i = 0; i < N; i++) {
		revr[i] = vr[i] = v[i].second;
		if (i)vr[i] = min(vr[i], vr[i - 1]);
	}
	for (int i = N - 2; i >= 0; i--)revr[i] = min(revr[i], revr[i + 1]);
	for (int i = 0; i < N - 1; i++) {
		ans = max(ans, max(0LL, vr[i] - vl[i] + 1) + max(0LL, revr[i + 1] - revl[i + 1] + 1));
		//cout << i << " " << ans << endl;
	}
}