// (c) 2020, redotter

// Roses are red
// The Tardis is blue
// The Doctor once said
// Rose Tyler...

#pragma GCC optimize("O3", "unroll-loops")
#pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
#pragma comment(linker, "/stack:500000000")
#endif

#define pb push_back
#define the(a) (a).begin(), (a).end()
#define ft first
#define sd second
#define endl "\n"
#define forn(i, n) for (int i = 0; i < (n); i++)
#define forr(i, s, n) for (int i = (s); i < (n); i++)

using i64 = long long;
using i32 = int;
using f64 = long double;

template <class T> using vec = vector<T>;
using str = string; using p64 = pair<i64, i64>;
using v64 = vec<i64>; using vv64 = vec<v64>;
using s64 = set<i64>; using m64 = map<i64, i64>;
template <size_t Size1> using a64 = array<i64, Size1>;
template <size_t Size1, size_t Size2> using aa64 = array<a64<Size2>, Size1>;
template <class T> using hash_set = unordered_set<T>;
template <class T, class U> using hash_map = unordered_map<T, U>;

mt19937 gen(998244353);
const i64 inf = numeric_limits<i64>::max() / 2;

template <class T> inline i64 len(const T& a) { return (i64)(a.size()); }
inline void fast() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); }
template <class T, class S>
inline bool check_min(T& a, S b) { if (a > b) return a = b, 1; return 0; }
template <class T, class S>
inline bool check_max(T& a, S b) { if (a < b) return a = b, 1; return 0; }

void read() {}
template<class T, class ...U>
void read(T& a, U& ...b) { cin >> a; read(b...); }
void print() {}
template<class T, class ...U>
void print(const T& a, const U& ...b) { cout << a << " "; print(b...); }
void println() { cout << "\n"; }
template<class T, class ...U>
void println(const T& a, const U& ...b) { cout << a << " "; println(b...); }

struct Problem {
	void files(str in, str out) {
#ifdef ONLINE_JUDGE
		freopen(in.c_str(), "r", stdin), freopen(out.c_str(), "w", stdout);
#endif
	}
	void solve(), input();
	void many() { i32 t; cin >> t; while (t--) input(), solve(); }
	void make(bool mt = 0) { if (mt) many(); else input(), solve(); }
} problem;

signed main() {
	fast();
	problem.make();
#ifdef _DEBUG
	println(); println("[finished]"); system("pause > nul");
#endif
	return 0;
}

i64 n;
v64 a;

void Problem::solve() {
	vv64 dp(n, v64(n, -inf));
	forn(i, n) {
		dp[i][i] = a[i];
	}
	forr(ln, 2, n + 1) {
		forn(i, n) {
			i64 j = i + ln - 1;
			if (j >= n) break;
			check_max(dp[i][j], a[i] - dp[i + 1][j]);
			check_max(dp[i][j], a[j] - dp[i][j - 1]);
		}
	}
	println(dp[0][n - 1]);
}

void Problem::input() {
	read(n);
	a.resize(n);
	forn(i, n) read(a[i]);
}

Score : 100 points

Problem Statement

Taro and Jiro will play the following game against each other.

Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N).
Until a becomes empty, the two players perform the following operation alternately, starting from Taro:

Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.

Let X and Y be Taro's and Jiro's total score at the end of the game, respectively.
Taro tries to maximize X - Y, while Jiro tries to minimize X - Y.

Assuming that the two players play optimally, find the resulting value of X - Y.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the resulting value of X - Y, assuming that the two players play optimally.

Sample Input 1

4
10 80 90 30

Sample Output 1

10

The game proceeds as follows when the two players play optimally (the element being removed is written bold):

Taro: (10, 80, 90, 30) → (10, 80, 90)

Jiro: (10, 80, 90) → (10, 80)

Taro: (10, 80) → (10)

Jiro: (10) → ()

Here, X = 30 + 80 = 110 and Y = 90 + 10 = 100.

Sample Input 2

3
10 100 10

Sample Output 2

-80

The game proceeds, for example, as follows when the two players play optimally:

Taro: (10, 100, 10) → (100, 10)

Jiro: (100, 10) → (10)

Taro: (10) → ()

Here, X = 10 + 10 = 20 and Y = 100.

Sample Input 3

1
10

Sample Output 3

10

Sample Input 4

10
1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1

Sample Output 4

4999999995

The answer may not fit into a 32-bit integer type.

Sample Input 5

6
4 2 9 7 1 5

Sample Output 5

2

The game proceeds, for example, as follows when the two players play optimally:

Taro: (4, 2, 9, 7, 1, 5) → (4, 2, 9, 7, 1)

Jiro: (4, 2, 9, 7, 1) → (2, 9, 7, 1)

Taro: (2, 9, 7, 1) → (2, 9, 7)

Jiro: (2, 9, 7) → (2, 9)

Taro: (2, 9) → (2)

Jiro: (2) → ()

Here, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13.


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

int f(int i, int k, int remainder, int n, int a[]) {

	if (i == n && remainder == 0) return 1;
	if (i == n) return 0;
	if (remainder < 0) return 0;
	int c = 0;

	for (int j = 0; j <= a[i]; j++) {

		c +=  f(i + 1, k, remainder - j, n, a);

	}
	//cout << endl;
	return c%1000000007;
}

int32_t main() {

	//memset(dp, 0, sizeof(dp));
	int t, k;
	cin >> t >> k;
	int a[t ];

	for (int i = 0; i < t; i++)
		cin >> a[i];
	cout << f(0, k , k, t, a);

}

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

Score : 100 points

Problem Statement

There are N children, numbered 1, 2, \ldots, N.

They have decided to share K candies among themselves.
Here, for each i (1 \leq i \leq N), Child i must receive between 0 and a_i candies (inclusive).
Also, no candies should be left over.

Find the number of ways for them to share candies, modulo 10^9 + 7.
Here, two ways are said to be different when there exists a child who receives a different number of candies.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq K \leq 10^5

0 \leq a_i \leq K

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \ldots a_N

Output

Print the number of ways for the children to share candies, modulo 10^9 + 7.

Sample Input 1

3 4
1 2 3

Sample Output 1

5

There are five ways for the children to share candies, as follows:

(0, 1, 3)

(0, 2, 2)

(1, 0, 3)

(1, 1, 2)

(1, 2, 1)

Here, in each sequence, the i-th element represents the number of candies that Child i receives.

Sample Input 2

1 10
9

Sample Output 2

0

There may be no ways for the children to share candies.

Sample Input 3

2 0
0 0

Sample Output 3

1

There is one way for the children to share candies, as follows:

(0, 0)

Sample Input 4

4 100000
100000 100000 100000 100000

Sample Output 4

665683269

Be sure to print the answer modulo 10^9 + 7.

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 long long int lli;
typedef vector <int> vi;
typedef vector <vi> vvi;
typedef pair <int,int> pr;
#define fr(i, n) for(int i = 0; i < n; i++)
#define sz(a) int((a).size())
#define pb push_back
#define all(c)(c).begin(), (c).end()
#define tr(c, i) for (typeof ((c).begin() i = (c).begin(); i != (c).end(); i++)
#define present(c, x)((c).find(x) != (c).end())
#define cpresent(c, x)(find(all(c), x) != (c).end())
// for mod power a^b%m use power<lli> (a,b,m)
template < class mytype >
mytype power(mytype a, mytype b, mytype m){if (b == 1) return a % m;if (b == 0) return 1;
mytype root = power < lli > (a, b / 2, m);mytype ans = (root * root) % m;if (b % 2) ans = (ans * a) % m;
return ans;
}
// for gcd use gcd<int> (a,b)
template < class type >type gcd(type a, type b){if (a == 0) return b;else return gcd(b % a, a);}
template < class type >type mod_inv(type a, type p) {return power(a, p - 2, p);}
const lli MOD = 1e9 + 7;

int main()
{
   int n, k;
   cin >> n >> k;
   vector<int> v(n);
   for(int i = 0 ; i < n ; i++ ) cin >> v[i];
    lli dp[k+1];
   for(int i = 0 ; i <= k ; i++) {
        if(i <= v[0]) dp[i] = 1;
        else dp[i] = 0;
   }lli sum = v[0];
   for(int i = 1 ; i < n ; i++){
    sum += v[i];int count = 0;
    for(int j = 1 ; j <= k && j < sum; j++) {
            if(j <=  v[i])dp[j] = (dp[j] + dp[j-1]) % MOD;
            else{
                dp[j] = (dp[j] + dp[j-1] - dp[count]) % MOD;
                count++;
            }
    }

    if(sum <= k) dp[sum] = 1;
   }
   cout << dp[k] << endl;
    return 0;
}


#include <bits/stdc++.h>
#include<algorithm>
using namespace std;
int mod = 1000000007;
//long long dp[401][401] ;
vector<vector<long long>> dp(401, vector<long long>(401,1000000005));
long long a[401];
long long aa[401];
int main() {
  int n;
  cin >> n;

  for(int i = 1;i < n+1;i++){
    cin >> a[i];
    dp[i][i] = a[i];
    aa[i] = aa[i-1]+ a[i];
  }

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

  long long res = 0;
  for(int i = 1;i < n; i++){
    long long tmp = 10000000000;
    for(int j = 1; j < n;j++){
      if(i+j > n){break;}
      for(int k = j; k < j+i;k++){
        dp[j][j+i] = min(dp[j][k]+dp[k+1][j+i],dp[j][j+i]);
        //cout << j<< " " << k << " " << i+j << " " << dp[j][j+i] << endl;
      }
      tmp = min(tmp,dp[j][j+i]);
    }
    res += tmp;
  }
  cout << res;
}

Score : 100 points

Problem Statement

There are N slimes lining up in a row.
Initially, the i-th slime from the left has a size of a_i.

Taro is trying to combine all the slimes into a larger slime.
He will perform the following operation repeatedly until there is only one slime:

Choose two adjacent slimes, and combine them into a new slime. The new slime has a size of x + y, where x and y are the sizes of the slimes before combining them. Here, a cost of x + y is incurred. The positional relationship of the slimes does not change while combining slimes.

Find the minimum possible total cost incurred.

Constraints

All values in input are integers.

2 \leq N \leq 400

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 20 30 40

Sample Output 1

190

Taro should do as follows (slimes being combined are shown in bold):

(10, 20, 30, 40) → (30, 30, 40)

(30, 30, 40) → (60, 40)

(60, 40) → (100)

Sample Input 2

5
10 10 10 10 10

Sample Output 2

120

Taro should do, for example, as follows:

(10, 10, 10, 10, 10) → (20, 10, 10, 10)

(20, 10, 10, 10) → (20, 20, 10)

(20, 20, 10) → (20, 30)

(20, 30) → (50)

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

6
7 6 8 6 1 1

Sample Output 4

68

Taro should do, for example, as follows:

(7, 6, 8, 6, 1, 1) → (7, 6, 8, 6, 2)

(7, 6, 8, 6, 2) → (7, 6, 8, 8)

(7, 6, 8, 8) → (13, 8, 8)

(13, 8, 8) → (13, 16)

(13, 16) → (29)


#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int MOD = 1e9 + 7;
const ll INF = 1e18L + 5;

ll fast_exp(int base, int exp) {
    ll res=1;
    while(exp>0) {
       if(exp%2==1) res=(res*base)%MOD;
       base=(base*base)%MOD;
       exp/=2;
    }
    return res%MOD;
}

unordered_map<int,vector<int>> graph;
int N;
// #define black 1
// #define white 2 //1-black and 2-white
// vector<bool> visited;
vector<vector<int>> dp;
int dfs(int src,int color,int par){
    if(dp[src][color]!=-1){
        return dp[src][color];
    }

    //dp[src][color] = 1;
    ll ans=1;
    for(auto neigh:graph[src]){
        if(neigh!=par){
            if(color==0){
                ans = ans*(dfs(neigh,0,src)+dfs(neigh,1,src))%MOD;
            }
            else{
                ans = ans*dfs(neigh,0,src)%MOD;
            }
        }
    }

    return dp[src][color]=ans;
}
int main(){

   int n;
   cin>>n;
   N=n;
   int u,v;
   graph.clear();
    dp.clear();

   for(int i=1;i<=n-1;i++){
       cin>>u>>v;
       graph[u].push_back(v);
       graph[v].push_back(u);
   }

   ll ans = (dfs(1,1,0)+dfs(1,0,0))%MOD;
   cout<<ans<<endl;
   return 0;
}

Score : 100 points

Problem Statement

There is a tree with N vertices, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.

Taro has decided to paint each vertex in white or black.
Here, it is not allowed to paint two adjacent vertices both in black.

Find the number of ways in which the vertices can be painted, modulo 10^9 + 7.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}

Output

Print the number of ways in which the vertices can be painted, modulo 10^9 + 7.

Sample Input 1

3
1 2
2 3

Sample Output 1

5

There are five ways to paint the vertices, as follows:

Sample Input 2

4
1 2
1 3
1 4

Sample Output 2

9

There are nine ways to paint the vertices, as follows:

Sample Input 3

1

Sample Output 3

2

Sample Input 4

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

Sample Output 4

157


#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <string>
#include <iostream>
#include <vector>
#include <iomanip>
#define lsb(x) ((x) & -(x))
using namespace std;

const int NMAX = 200010;
typedef long long i64;
int n;
i64 aib[NMAX];

i64 query(int x)
{
    i64 ans = 0;
    while (x)
        ans = max(ans, aib[x]), x -= lsb(x);
    return ans;
}
void update(i64 val, int poz)
{
    while (poz <= n)
        aib[poz] = max(aib[poz], val), poz += lsb(poz);
}

int h[NMAX], val[NMAX];

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

    for (int i = 1; i <= n; i++)
        scanf("%d", h + i);

    for (int i = 1; i <= n; i++)
        scanf("%d", val + i);

    for (int i = 1; i <= n; i++) {
        i64 prev = query(h[i]);
        prev += val[i];

        update(prev, h[i]);
    }

    cout << query(n) << '\n';

    return 0;
}

Score : 100 points

Problem Statement

There are N flowers arranged in a row.
For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively.
Here, h_1, h_2, \ldots, h_N are all distinct.

Taro is pulling out some flowers so that the following condition is met:

The heights of the remaining flowers are monotonically increasing from left to right.

Find the maximum possible sum of the beauties of the remaining flowers.

Constraints

All values in input are integers.

1 \leq N \leq 2 × 10^5

1 \leq h_i \leq N

h_1, h_2, \ldots, h_N are all distinct.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N
a_1 a_2 \ldots a_N

Output

Print the maximum possible sum of the beauties of the remaining flowers.

Sample Input 1

4
3 1 4 2
10 20 30 40

Sample Output 1

60

We should keep the second and fourth flowers from the left.
Then, the heights would be 1, 2 from left to right, which is monotonically increasing, and the sum of the beauties would be 20 + 40 = 60.

Sample Input 2

1
1
10

Sample Output 2

10

The condition is met already at the beginning.

Sample Input 3

5
1 2 3 4 5
1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

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

Sample Output 4

31

We should keep the second, third, sixth, eighth and ninth flowers from the left.


#include <bits/stdc++.h>
#include <algorithm>
#include <cmath>
#include <set>
#include <cstdio>
#include <vector>
#include <iostream>
#include <utility>
#include <queue>
#include <map>

#define fir first
#define sec second
#define sz(s) (s).size();
#define pb push_back
#define get(n) scanf("%d",&n);
#define gets(s) string s;cin >> (s);
#define prfi(n) printf("%d", &n);
#define prfd(n) printf("%lf", &n);
#define All(s) (s).begin(), (s).end()
#define rep(i,j,k) for(int (i)=(j);(i)<=(k);(i)++)
#define rep0(i,j) for(int (i)=0;(i)<(j);(i)++)
#define repdown(i, j, k) for(int (i)=(j);(i)>=(k);(i)--)
#define repdown0(i,j) for(int (i)=(j);i>=0;i--)
#define dump(x)  std::cout << #x << " = " << (x) << std::endl;
#define debug(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

using ll = long long;
using vi = std::vector<int> ;
using vvi = std::vector<vi> ;
using vll = std::vector<ll>;
using vvll = std::vector<vll>;
using vd = std::vector<double> ;
using vvd = std::vector<vd> ;
using qi = std::queue<int> ;
using vpii = std::vector<std::pair<int, int> >;
using namespace std;

const int Mod = (1e9) + 7;
const int max_n = 3 * (1e5) + 1;
const int max_m = 83 * (1e5) + 1;
const int INF = 10241024;
//const ll INFL = (1ll << 63) - 1;

//_____________________________________Templates_________________________________________//

template<class T1, class T2> inline void chmin(T1 &a, T2 b){if(a > b) a = b;}
template<class T1, class T2> inline void chmax(T1 &a, T2 b){if(a < b) a = b;}

//mainly use for dynamic prog
template<class T1, class T2>
void update(T1 &a, T2 b){
  a += b;
  if(a > Mod) a %= Mod;
}

inline void IN(void){
  return;
}

template <typename First, typename... Rest>
void IN(First& first, Rest&... rest){
  cin >> first;
  IN(rest...);
  return;
}

inline void OUT(void){
  cout << "\n";
  return;
}

template <typename First, typename... Rest>
void OUT(First first, Rest... rest){
  cout << first << " ";
  OUT(rest...);
  return;
}

//_____________________array calc____________________________________//

vvll mul(vvll &A, vvll &B){
  vvll C (A.size(), vll(B[0].size()));
  rep0(i,A.size()){
    rep0(j,B.size()){
      rep0(k,B[0].size()){
        C[i][j] += (C[i][j] + A[i][k] * B[k][j])%Mod;
      }
    }
  }
  return C;
}

vvll pow(vvll A, ll n){
  vvll B(A.size(), vll(A.size()));
  rep0(i,A.size()){
    B[i][i] = 1;
  }
  while(n > 0){
    if(n & 1)B = mul(B , A);
    A = mul(A, A);
    n >>= 1;
  }
  return B;
}
//_____________________Bynary Indexed Tree __________________________//
/*
const max_st = (1 << 15) - 1;
int bit[max_st];
int sum (int i){
  int s = 0;
  while(i > 0){
    s += bit[i];
    i -= i & -i;
  }
  return s;
}

void add(int i, int x){
  while(i <= n){
    bit[i] += x;
    i += i & -i;
  }
}
*/

//____________________RMQ____________________________//
/*
struct RMQ{
  #define s (1 << 20)
  ll dat[s];
  int n;

  void init(){
    memset(dat, -1e10, sizeof(dat));
  }

  void upd(int k, ll a){
    k += s/2 - 1;
    dat[k] = a;
    while(k > 0){
      k = (k -1) /2;
      dat[k] = max(dat[k*2+1], dat[k*2+2]);
    }
  }

  ll query(int a, int b, int k, int l, int r){
    if(r <= a || b <= l) return -1e8;
    if( a <= l && r <= b)return dat[k];
    else
    {
      ll vl = query(a, b, k*2+1, l, (l+r)/2);
      ll vr = query(a, b, k*2+2, (l+r)/2, r);
      return max(vl, vr);
    }
  }

  void Debug(int a){
    a += s/2 - 1;
    rep(i,s/2 - 1,a){
      dump(dat[i]);
    }
  }
};
*/
//_____________________　following sorce code_________________________//
int n,m,k,x,y;
vvll dp(50, vll(50));
vvll v(50, vll(50));
ll ans = 0ll;

int main () {
  cin.tie(0);
  ios::sync_with_stdio(false);
  ll z;
  IN(n,z);

  rep0(i,n){
    rep0(j,n){
      int a;IN(a);
      v[i][j] = a;
    }
  }
  dp = pow(v, z);
  rep0(i,n){
    rep0(j,n){
      ans += dp[i][j];
      ans %= Mod;
    }
  }
  OUT(ans);
  return 0;
}

Score : 100 points

Problem Statement

There is a simple directed graph G with N vertices, numbered 1, 2, \ldots, N.

For each i and j (1 \leq i, j \leq N), you are given an integer a_{i, j} that represents whether there is a directed edge from Vertex i to j.
If a_{i, j} = 1, there is a directed edge from Vertex i to j; if a_{i, j} = 0, there is not.

Find the number of different directed paths of length K in G, modulo 10^9 + 7.
We will also count a path that traverses the same edge multiple times.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 10^{18}

a_{i, j} is 0 or 1.

a_{i, i} = 0

Input

Input is given from Standard Input in the following format:

N K
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}

Output

Print the number of different directed paths of length K in G, modulo 10^9 + 7.

Sample Input 1

4 2
0 1 0 0
0 0 1 1
0 0 0 1
1 0 0 0

Sample Output 1

6

G is drawn in the figure below:

There are six directed paths of length 2:

1 → 2 → 3

1 → 2 → 4

2 → 3 → 4

2 → 4 → 1

3 → 4 → 1

4 → 1 → 2

Sample Input 2

3 3
0 1 0
1 0 1
0 0 0

Sample Output 2

3

G is drawn in the figure below:

There are three directed paths of length 3:

1 → 2 → 1 → 2

2 → 1 → 2 → 1

2 → 1 → 2 → 3

Sample Input 3

6 2
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 0

Sample Output 3

1

G is drawn in the figure below:

There is one directed path of length 2:

4 → 5 → 6

Sample Input 4

1 1
0

Sample Output 4

0

Sample Input 5

10 1000000000000000000
0 0 1 1 0 0 0 1 1 0
0 0 0 0 0 1 1 1 0 0
0 1 0 0 0 1 0 1 0 1
1 1 1 0 1 1 0 1 1 0
0 1 1 1 0 1 0 1 1 1
0 0 0 1 0 0 1 0 1 0
0 0 0 1 1 0 0 1 0 1
1 0 0 0 1 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
1 0 1 1 1 0 1 1 1 0

Sample Output 5

957538352

Be sure to print the count modulo 10^9 + 7.


#include <bits/stdc++.h>

using namespace std;
const int maxn = 18;

int n;
int niz[maxn][maxn];
long long dp[(1 << maxn)];
long long cost[(1 << maxn)];

long long f(int mask) {
	if (mask == 0) return 0;
	long long &ret = dp[mask];
	if (ret != -1) return ret;

	vector<int> koji;
	for (int i = 0; i < n; i++)
		if (mask & (1 << i)) koji.push_back(i);

	int siz = koji.size();
	ret = 0;
	for (int i = 0; i < (1 << siz); i++) {
		int ac = 0;
		for (int j = 0; j < siz; j++)
			if (i & (1 << j)) ac |= (1 << koji[j]);
		ret = max(ret, cost[ac] + f(mask & (~ac)));
	}
	return ret;
}

int main() {
	memset(dp, -1, sizeof dp);
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			scanf("%d", &niz[i][j]);

	for (int i = 0; i < (1 << n); i++) {
		for (int x = 0; x < n; x++) {
			for (int y = x + 1; y < n; y++) {
				if ((i & (1 << x)) && (i & (1 << y))) cost[i] += niz[x][y];
			}
		}
	}

	printf("%lld", f((1 << n) - 1));
	return 0;
}

Score : 100 points

Problem Statement

There are N rabbits, numbered 1, 2, \ldots, N.

For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}.
Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N).

Taro is dividing the N rabbits into some number of groups.
Here, each rabbit must belong to exactly one group.
After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group.

Find Taro's maximum possible total score.

Constraints

All values in input are integers.

1 \leq N \leq 16

|a_{i, j}| \leq 10^9

a_{i, i} = 0

a_{i, j} = a_{j, i}

Input

Input is given from Standard Input in the following format:

N
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}

Output

Print Taro's maximum possible total score.

Sample Input 1

3
0 10 20
10 0 -100
20 -100 0

Sample Output 1

20

The rabbits should be divided as \{1, 3\}, \{2\}.

Sample Input 2

2
0 -10
-10 0

Sample Output 2

0

The rabbits should be divided as \{1\}, \{2\}.

Sample Input 3

4
0 1000000000 1000000000 1000000000
1000000000 0 1000000000 1000000000
1000000000 1000000000 0 -1
1000000000 1000000000 -1 0

Sample Output 3

4999999999

The rabbits should be divided as \{1, 2, 3, 4\}.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 4

16
0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7
5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9
-4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9
-5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1
-8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3
-4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2
7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5
2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8
-4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7
0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6
7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3
0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0
2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1
-3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8
7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9
7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0

Sample Output 4

132


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define rrep(i,n) for(int (i)=((n)-1);(i)>=0;(i)--)
#define itn int
#define miele(v) min_element(v.begin(), v.end())
#define maele(v) max_element(v.begin(), v.end())
#define SUM(v) accumulate(v.begin(), v.end(), 0LL)
#define lb(a, key) lower_bound(a.begin(),a.end(),key)
#define ub(a, key) upper_bound(a.begin(),a.end(),key)
#define COUNT(a, key) count(a.begin(), a.end(), key)
#define BITCOUNT(x) __builtin_popcount(x)
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define F first
#define S second
using P = pair <int,int>;
using WeightedGraph = vector<vector <P>>;
using UnWeightedGraph = vector<vector<int>>;
const long long INF = 1LL << 60;
const int MOD = 1000000007;
void YN(bool flg) {cout<<(flg?"YES":"NO")<<'\n';}
void Yn(bool flg) {cout<<(flg?"Yes":"No")<<'\n';}
void yn(bool flg) {cout<<(flg?"yes":"no")<<'\n';}
template <typename T>
int getIndexOfLowerBound(vector <T> &v, T x){
    return lower_bound(v.begin(),v.end(),x)-v.begin();
}
template <typename T>
int getIndexOfUpperBound(vector <T> &v, T x){
    return upper_bound(v.begin(),v.end(),x)-v.begin();
}
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
#define DUMPOUT cerr
#define repi(itr, ds) for (auto itr = ds.begin(); itr != ds.end(); itr++)
template <typename T, typename U>
istream &operator>>(istream &is, pair<T,U> &p_var) {
    is >> p_var.first >> p_var.second;
    return is;
}
template <typename T>
istream &operator>>(istream &is, vector<T> &vec) {
    for (T &x : vec) is >> x;
    return is;
}
template <typename T>
istream &operator>>(istream &is, vector<vector<T>> &df) {
    for(int i=0;i<df.size();i++)for(int j=0;j<df[i].size();j++)
    is >> df[i][j];
    return is;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, pair<T, U> &pair_var) {
    DUMPOUT<<'{';
    os << pair_var.first;
    DUMPOUT<<',';
    os << " "<< pair_var.second;
    DUMPOUT<<'}';
    return os;
}
template <typename T>
ostream &operator<<(ostream &os, vector<T> &vec) {
    DUMPOUT<<'[';
    for (int i = 0; i < vec.size(); i++)
    os << vec[i] << (i + 1 == vec.size() ? "" : " ");
    DUMPOUT<<']';
    return os;
}
template <typename T>
ostream &operator<<(ostream &os, vector<vector<T>> &df) {
  for (auto& vec : df) os<<vec;
  return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, map<T, U> &map_var) {
    DUMPOUT << "{";
    repi(itr, map_var) {
        os << *itr;
        itr++;
        if (itr != map_var.end()) DUMPOUT << ", ";
        itr--;
    }
    DUMPOUT << "}";
    return os;
}
template <typename T>
ostream &operator<<(ostream &os, set<T> &set_var) {
    DUMPOUT << "{";
    repi(itr, set_var) {
        os << *itr;
        itr++;
        if (itr != set_var.end()) DUMPOUT << ", ";
        itr--;
    }
    DUMPOUT << "}";
    return os;
}
void print() {cout << endl;}
template <class Head, class... Tail>
void print(Head&& head, Tail&&... tail) {
  cout << head;
  if (sizeof...(tail) != 0) cout << " ";
  print(forward<Tail>(tail)...);
}
void dump_func() {DUMPOUT << '#'<<endl;}
template <typename Head, typename... Tail>
void dump_func(Head &&head, Tail &&... tail) {
    DUMPOUT << head;
    if (sizeof...(Tail) > 0) DUMPOUT << ", ";
    dump_func(std::move(tail)...);
}
#ifdef DEBUG_
#define DEB
#define dump(...)                                                              \
    DUMPOUT << "  " << string(#__VA_ARGS__) << ": "                            \
            << "[" << to_string(__LINE__) << ":" << __FUNCTION__ << "]"        \
            << endl                                                            \
            << "    ",                                                         \
        dump_func(__VA_ARGS__)
#else
#define DEB if (false)
#define dump(...)
#endif
int n, m;
UnWeightedGraph g;
vector <int> data;
vector <vector<int>> l, r;
int dfs(int now = 0, int pre = -1){
    int res = 1;
    int x = 0;
    vector <int> tmp;

    for(auto e: g[now]){
        if(e != pre) {
            int multiply = dfs(e, now)+1;
            res *= multiply;
        }
        res %= m;
    }
    return data[now] = res;
}
vector <int> ans;
signed main(void) { cin.tie(0); ios::sync_with_stdio(false);
    cin>>n>>m;
    g.resize(n), data.resize(n), l.resize(n), r.resize(n), ans.resize(n);
    rep(i, n-1){
        int a,b; cin>>a>>b;
        a--; b--;
        g[a].pb(b);
        g[b].pb(a);
    }
    dfs();
    queue <tuple <int,int,int>> q;
    q.push(make_tuple(0, -1, -1));
    while(!q.empty()){
        int now = get <0>(q.front()), pre = get <1>(q.front()), idx = get <2>(q.front());
        q.pop();
        if(now == 0) ans[0] = data[0];
        l[now].pb(1);
        int x = 0;
        for(auto e:g[now]){
            if(e == pre){
                int multiply = l[pre][idx]*r[pre][idx+1]+1;
                multiply %= m;
                l[now].pb(multiply), r[now].pb(multiply);
            }else{
                l[now].pb(data[e]+1);
                r[now].pb(data[e]+1);
                q.push(make_tuple(e, now, x));
            }
            x++;
        }
        r[now].pb(1);
        for(int i=1;i<l[now].size();i++){
            l[now][i] *= l[now][i-1];
            l[now][i] %= m;
        }
        for(int i=l[now].size()-2;i>=0;i--){
            r[now][i] *= r[now][i+1];
            r[now][i] %= m;
        }
        if(now == 0) ans[0] = data[0];
        ans[now] = r[now][0];
    }
    rep(i, n) print(ans[i]);
}

Score : 100 points

Problem Statement

There is a tree with N vertices, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.

Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.

You are given a positive integer M.
For each v (1 \leq v \leq N), answer the following question:

Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

2 \leq M \leq 10^9

1 \leq x_i, y_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}

Output

Print N lines.
The v-th (1 \leq v \leq N) line should contain the answer to the following question:

Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.

Sample Input 1

3 100
1 2
2 3

Sample Output 1

3
4
3

There are seven ways to paint the vertices, as shown in the figure below.
Among them, there are three ways such that Vertex 1 is black, four ways such that Vertex 2 is black and three ways such that Vertex 3 is black.

Sample Input 2

4 100
1 2
1 3
1 4

Sample Output 2

8
5
5
5

Sample Input 3

1 100

Sample Output 3

1

Sample Input 4

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

Sample Output 4

0
0
1
1
1
0
1
0
1
1

Be sure to print the answers modulo M.


#include"bits/stdc++.h"
using namespace std;
int head[100001],to[100001],nxt[100001];
int f[100001];
int g[100001];
int tot;
int n,m;
void addedge(int u,int v)
{
	tot++;
	nxt[tot]=head[u];
	to[tot]=v;
	head[u]=tot;
}
int dfs(int index,int parent)
{
	g[index]=1;
	for(int i=head[index];i;i=nxt[i])
	{
		int v=to[i];
		if(parent==v)
			continue;
		g[index]=(int)(((long long)(dfs(v,index)+1)*g[index])%m);
	}
	return g[index];
}
void dfs2(int index,int parent)
{
	if(index==1)
		f[index]=g[index];
	else
		f[index]=(int)(((long long)g[index]*(((f[parent]==0?m:f[parent])/(g[index]+1))%m)+1)%m);
	for(int i=head[index];i;i=nxt[i])
	{
		int v=to[i];
		if(parent==v)
			continue;
		dfs2(v,index);
	}
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<n;i++)
	{
		int u,v;
		scanf("%d%d",&u,&v);
		addedge(u,v);
		addedge(v,u);
	}
	dfs(1,0);
	dfs2(1,0);
	for(int i=1;i<=n;i++)
		printf("%d %d\n",g[i],f[i]);
}


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

int main() {
        int n, m;
        scanf("%d%d", &n, &m);
        vector<vector<int>> tmp(n);
        rep(i, n - 1) {
                int a, b;
                scanf("%d%d", &a, &b);
                a --, b --;
                tmp[a].push_back(b);
                tmp[b].push_back(a);
        }
        vector<vector<int>> g(n);
        function<void (int, int)> modify = [&](int u, int prev) {
                for (auto v : tmp[u]) if (v != prev) {
                        g[u].push_back(v);
                        modify(v, u);
                }
        };
        modify(0, -1);

        vector<long long> dp(n);
        vector<vector<long long>> left(n), right(n);
        function<void (int)> dfs = [&](int u) {
                for (auto v : g[u]) {
                        dfs(v);
                }
                if (g[u].size() == 0) {
                        dp[u] = 1;
                        return;
                }
                dp[u] = 1;
                for (auto v : g[u]) {
                        (dp[u] *= dp[v] + 1) %= m;
                }
                left[u].resize(g[u].size());
                right[u].resize(g[u].size());
                left[u][0] = dp[g[u][0]] + 1;
                right[u][g[u].size() - 1] = dp[g[u].back()] + 1;
                for (int i = 1; i < g[u].size(); i ++) {
                        left[u][i] = left[u][i - 1] * (dp[g[u][i]] + 1) % m;
                }
                for (int i = (int) g[u].size() - 2; i >= 0; i --) {
                        right[u][i] = right[u][i + 1] * (dp[g[u][i]] + 1) % m;
                }
        };
        dfs(0);
        vector<long long> ans(n);
        function<void (int, long long)> dfs2 = [&](int u, long long r) {
                ans[u] = dp[u] * (r + 1);
                for (int i = 0; i < g[u].size(); i ++) {
                        long long nxt = (i > 0 ? left[u][i - 1] : 1) * (i < (int) g[u].size() - 1 ? right[u][i + 1] : 1) % m;
                        dfs2(g[u][i], nxt * (r + 1) % m);
                }
        };
        dfs2(0, 0);
        rep(i, n) {
                printf("%lld\n", ans[i]);
        }
        return 0;
}


#include <bits/stdc++.h>

 using namespace std;
 typedef long long ll;

 int main() {
   ll A, B, C;

   cin >> A >> B >> C;

   ll ans;

   if (A + B - 1 >= C) ans = B + C;

   else ans = A + 2 * B + 1;

   cout << ans << endl;
   }

Score : 200 points

Problem Statement

Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.

Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death.
As he wants to live, he cannot eat one in such a situation.
Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.

Find the maximum number of tasty cookies that Takahashi can eat.

Constraints

0 \leq A,B,C \leq 10^9

A,B and C are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum number of tasty cookies that Takahashi can eat.

Sample Input 1

3 1 4

Sample Output 1

5

We can eat all tasty cookies, in the following order:

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9


#include <iostream>
using namespace std;

int main(void) {
  long long l, n;
  bool isFirstHarf = false;
  cin >> l >> n;
  long long x[n], ans = 0, ans_, sum;
  for (int i = 0; i < n; i++) {
    cin >> x[i];
    if (i > 0) {
      if ((l / 2) < x[i]) {
        ans_ = ((l - x[i-1]) * 2) + x[i];
        if (!isFirstHarf) {
          if (((l/2) - x[i]) > x[i-1]) {
            sum -= x[i-1];
          } else {
            sum += x[i];
          }
          isFirstHarf = true;
        } else {
          sum += (l - x[i]) * 2;
        }
      } else {
        ans_ = ((l - x[i]) * 2) + x[i - 1];
        sum += x[i] * 2;
      }
      // cout << "i=" << i << endl;
      // cout << "l / 2=" << l/2 << endl;
      // cout << "sum=" << sum << endl;
      if (ans < ans_)
        ans = ans_;
    } else {
      sum = x[i] * 2;
    }
  }
  if (ans < sum)
    ans = sum;
  cout << ans << endl;
  return 0;
}

Score : 800 points

Problem Statement

Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi.
Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise.

There are N trees around the lake; the coordinate of the i-th tree is X_i. There is no tree at coordinate 0, the location of Takahashi's residence.

Starting at his residence, Takahashi will repeat the following action:

If all trees are burnt, terminate the process.

Specify a direction: clockwise or counter-clockwise.

Walk around the lake in the specified direction, until the coordinate of a tree that is not yet burnt is reached for the first time.

When the coordinate with the tree is reached, burn that tree, stay at the position and go back to the first step.

Find the longest possible total distance Takahashi walks during the process.

Partial Score

A partial score can be obtained in this problem:

300 points will be awarded for passing the input satisfying N \leq 2000.

Constraints

2 \leq L \leq 10^9

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

1 \leq X_1 < ... < X_N \leq L-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L N
X_1
:
X_N

Output

Print the longest possible total distance Takahashi walks during the process.

Sample Input 1

10 3
2
7
9

Sample Output 1

15

Takahashi walks the distance of 15 if the process goes as follows:

Walk a distance of 2 counter-clockwise, burn the tree at the coordinate 2 and stay there.

Walk a distance of 5 counter-clockwise, burn the tree at the coordinate 7 and stay there.

Walk a distance of 8 clockwise, burn the tree at the coordinate 9 and stay there.

Sample Input 2

10 6
1
2
3
6
7
9

Sample Output 2

27

Sample Input 3

314159265 7
21662711
77271666
89022761
156626166
160332356
166902656
298992265

Sample Output 3

1204124749


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <iomanip>
#include <array>
#include <numeric>
#include <regex>
#include <bitset>
#include <deque>

using namespace std;
typedef long long ll;
typedef pair<int, int> p_ii;

const int INF = 1e9;
const double PI = acos(-1.0);
const ll MOD = 1e9 + 7;

int main() {
    int N; cin>>N;
    vector<int> a(N);
    for (int i = 0; i < N; i++) {
        cin>>a[i];
    }
    for (int i = 0; i < N; i++) {
        if(a[i]%2){
            puts("first");
            return 0;
        }
    }
    puts("second");

    return 0;
}

Score : 500 points

Problem Statement

There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.

You and Lunlun the dachshund alternately perform the following operation (starting from you):

Choose one or more apples from the tree and eat them. Here, the apples chosen at the same time must all have different colors.

The one who eats the last apple from the tree will be declared winner. If both you and Lunlun play optimally, which will win?

Constraints

1 \leq N \leq 10^5

1 \leq a_i \leq 10^9

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

If you will win, print first; if Lunlun will win, print second.

Sample Input 1

2
1
2

Sample Output 1

first

Let Color 1 be red, and Color 2 be blue. In this case, the tree bears one red apple and two blue apples.

You should eat the red apple in your first turn. Lunlun is then forced to eat one of the blue apples, and you can win by eating the other in your next turn.

Note that you are also allowed to eat two apples in your first turn, one red and one blue (not a winning move, though).

Sample Input 2

3
100000
30000
20000

Sample Output 2

second


#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <cstring>
#include <climits>
#include <iomanip>
#include <bitset>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <list>
#include <map>
#include <unordered_map>

using namespace std;

const int N = 200005;

int n;
int arr[N];

bool ok(int x) {
  unordered_map <int, int> cnt;
  for (int i = 1; i < n; i++) {
    if (arr[i] <= arr[i - 1]) {
      int ce = arr[i];
      while (cnt[ce] == x - 1) {
        if (ce == 1) return 0;
        cnt[ce--] = 0;
      }
      cnt[ce]++;
    }
  }
  return 1;
}

int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
  }
  int l = 1, r = 1e9, ans = 1;
  while (l <= r) {
    int mid = (l + r) >> 1;
    if (ok(mid)) {
      ans = mid;
      r = mid - 1;
    } else {
      l = mid + 1;
    }
  }
  cout << ans << endl;
  return 0;
}

Score : 700 points

Problem Statement

There are N strings arranged in a row.
It is known that, for any two adjacent strings, the string to the left is lexicographically smaller than the string to the right.
That is, S_1<S_2<...<S_N holds lexicographically, where S_i is the i-th string from the left.

At least how many different characters are contained in S_1,S_2,...,S_N, if the length of S_i is known to be A_i?

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Note

The strings do not necessarily consist of English alphabet; there can be arbitrarily many different characters (and the lexicographic order is defined for those characters).

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible number of different characters contained in the strings.

Sample Input 1

3
3 2 1

Sample Output 1

2

The number of different characters contained in S_1,S_2,...,S_N would be 3 when, for example, S_1=abc, S_2=bb and S_3=c.

However, if we choose the strings properly, the number of different characters can be 2.

Sample Input 2

5
2 3 2 1 2

Sample Output 2

2


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

#define ll long long
#define pb push_back
#define sz(x) (int)(x).size()
#define mp make_pair
#define f first
#define s second
#define all(x) x.begin(), x.end()

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>; ///find_by_order(),order_of_key()
template<class T1, class T2> ostream& operator<<(ostream& os, const pair<T1,T2>& a) { os << '{' << a.f << ", " << a.s << '}'; return os; }
template<class T> ostream& operator<<(ostream& os, const vector<T>& a) {
	os << '{';
	for(int i=0;i<sz(a);i++)
	{
		if(i>0&&i<=sz(a)-1)
			os << ", ";
		os << a[i];
	}
	os << '}';
    return os;
}
struct Node{
    int l;
    int r;
    Node* left;
    Node* right;
    bool lazy;
    int val;
    bool nula;
    Node()
    {
        left=NULL;
        right=NULL;
        lazy=false;
    }
    void extend()
    {
        if(left==NULL&&l!=r)
        {
            left=new Node();
            right=new Node();
            int m=(l+r)>>1;
            left->l=l;
            left->r=m;
            right->l=m+1;
            right->r=r;
        }
    }
    void prop()
    {
        if(nula)
        {
            nula=false;
            left->nula=true;
            right->nula=true;
            left->lazy=false;
            right->lazy=false;
            if(left->val==0)
                left->val=1;
            if(right->val==0)
                right->val=1;
        }
        if(lazy)
        {
            lazy=false;
            left->lazy=true;
            right->lazy=true;
            left->nula=false;
            right->nula=false;
            left->val=0;
            right->val=0;
        }
    }
    void set(int qs,int qe)
    {
        if(qs>r||qe<l)
            return;
        if(qs<=l&&qe>=r){
            lazy=true;
            nula=false;
            val=0;
            return;
        }
        extend();
        prop();
        left->set(qs,qe);
        right->set(qs,qe);
    }
    void set_nula(int qs,int qe)
    {
        if(qs>r||qe<l)
            return;
        if(qs<=l&&qe>=r){
            nula=true;
            lazy=false;
            if(val==0)
                val=1;
            return;
        }
        extend();
        prop();
        left->set_nula(qs,qe);
        right->set_nula(qs,qe);
    }
    int get(int p)
    {
        if(l>p||r<p)
            return 0;
        if(l==r&&l==p)
            return val;
        extend();
        prop();
        return left->get(p)+right->get(p);
    }
    void sett(int p,int k)
    {
        if(l>p||r<p)
            return;
        if(l==r&&l==p)
        {
            lazy=false;
            nula=false;
            val=k;
            return;
        }
        extend();
        prop();
        left->sett(p,k);
        right->sett(p,k);
    }
};
vector<int> niz;
bool test(int m)
{
   // printf("Testiram %i:\n",m);
    Node* root=new Node();
    root->l=0;
    root->r=1e9;
    for(auto p:niz)
    {

        //printf("Usao za %i\n",p);
        int t=root->get(p);
        //printf("Trenutna vrednos u p:%i\n",t);
        root->set_nula(0,p);
        if(p<(int)1e9)
            root->set(p+1,(int)1e9);
        t++;
        root->sett(p,t);
        //printf("%i %i %i\n",p,t,root->get(p));
        int tr=p;
        while(t>m)
        {
            if(tr==1)
                return false;
            root->sett(tr,1);
            int nxt=root->get(tr-1);
            nxt++;
            root->sett(tr-1,nxt);
            t=nxt;
            tr--;
        }
    }
    return true;
}
int main()
{
    int n;
    scanf("%i",&n);
    bool test5=true;
    int last=0;
    for(int i=0;i<n;i++)
    {
        int a;
        scanf("%i",&a);
        if(a<=last)
            test5=false;
        last=a;
        if(a<30)
            niz.pb(a);
    }
    if(test5)
    {
        printf("1\n");
        return 0;
    }
    int l=2,r=2e5+5;
    while(l<r)
    {
        int m=(l+r)>>1;
        if(test(m))
            r=m;
        else
            l=m+1;
    }
    printf("%i\n",l);
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define REP1(i,n) for(int i=1, i##_len=(n); i<i##_len; ++i)
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define pow(x) x*x
#define ll long long
static const ll MAX = 1000000;
static const ll INFTY = 1e12;
static const ll MOD = 1000000007;

template < typename T > inline string toString( const T &a ) { ostringstream oss; oss << a; return oss.str(); };

struct edge {
    ll to, cost;
};

using Graph = vector<vector<int>>;
using _Graph = vector<vector<edge>>;

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

// 深さ優先探索
vector<bool> seen;
vector<int> colors;

int H, W, N;
int sx, sy, gx, gy;
vector<vector<char>> field;
vector<vector<int>> dist;
//vector<pair<int, int>> gx, gy;
deque<pair<int, int>> que;

typedef vector<vector<int> > Matrix;

const ll INF = 1e18;

int main() {

    int N;
    cin >> N;
    vector<int> p(N);
    REP(i, N) cin >> p[i];

    sort(p.begin(), p.end(), greater<int>());
    ll ans = 0;
    REP(i, N){
        if(i==0)p[i] = (int)(p[i]/2);
        ans += p[i];
    }

    cout << ans << endl;

}
/*
みんな、くるくるぱーにな〜れ
　∧＿∧
（｡･ω･｡)つ━☆・*。
⊂　　 ノ 　　　・゜+.
　しーＪ　　　°。+ *´¨)
　　　　　　　　　.· ´¸.·*´¨) ¸.·*¨)
　　　　　　　　　　(¸.·´ (¸.·'* ☆
*/

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


#include <cmath>
#include <cstdlib>
#include <iostream>
#include <bitset>
#include <deque>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <chrono>
#include <random>
#include <tuple>
#include <utility>
#include <fstream>
#include <complex>

const long INF = (1l << 30);
const long LINF = (1l << 60);

long n, k;
long h[100005];
long ans = LINF;

int main(){
    scanf("%ld%ld", &n, &k);
    for(int i = 0; i < n; i++){
        scanf("%ld", h+i);
    }
    std::sort(h, h+n);
    for(int i = 0; i + k - 1 < n; i++){
        ans = std::min(ans, h[i+k-1] - h[i]);
    }
    printf("%ld\n", ans);
}

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


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

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

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

    int ans = 100000;
    for (int i = 0; i < n; ++i) {
        if (i + k - 1 >= n) {
            break;
        } else {
            ans = min(ans, abs(h[i] - h[i+k-1]));
        }
    }
    cout << ans << endl;
    return 0;
}


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

int main(){
//    https://abc114.contest.atcoder.jp/tasks/abc114_a
    int x;
    cin>>x;
    if(x == 3 || x == 5 || x == 7){
        cout << "YES" << endl;
    }else{
        cout << "NO" << endl;
    }
    return 0;
}

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(ll i=0;i<n;i++)
#define repl(i,l,r) for(ll i=(l);i<(r);i++)
#define per(i,n) for(ll i=n-1;i>=0;i--)
#define lper(i,r,l) for(ll i=r-1;i>=l;i--)
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ins insert
#define all(x) (x).begin(),(x).end()
#define CST(x) cout<<fixed<<setprecision(x)
using ll=long long;
using vl=vector<ll>;
using vvl=vector<vector<ll>>;
using pl=pair<ll,ll>;
using vpl=vector<pl>;
const ll MOD=1000000007;
const ll MOD9=998244353;
const int inf=1e9+10;
const ll INF=4e18;
const ll dy[4]={1,0,-1,0};
const ll dx[4]={0,-1,0,1};
ll modfac(ll a){
    ll ans=1;
    while(a>1){
        ans*=a;
        ans%=1000000007;
        a--;
    }
    return ans;
}
ll modinv(ll a,ll m) {
    ll b = m, u = 1, v = 0;
    while (b) {
        ll t = a / b;
        a -= t * b; swap(a, b);
        u -= t * v; swap(u, v);
    }
    u %= m;
    if (u < 0) u += m;
    return u;
}
struct UnionFind {
    vector<int> par;

    UnionFind(int n) : par(n, -1) {}

    int root(int x) {
        if (par[x] < 0) return x;
        else return par[x] = root(par[x]);
    }

    bool same(int x, int y) {
        return root(x) == root(y);
    }

    bool merge(int x, int y) {
        x = root(x); y = root(y);
        if (x == y) return false;
        if (par[x] > par[y]) swap(x, y);
        par[x] += par[y];
        par[y] = x;
        return true;
    }

    int size(int x) {
        return -par[root(x)];
    }
};
ll modpow(ll a, ll n, ll mod) {
    ll res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}
template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
int main(){
    ll n;cin >> n;
    ll d=log10(n)+1;
    ll count=0;
    while(d>=3){
        rep(bit,(ll)pow(3,d)){
            ll x=0;
            ll p=bit;
            bool a=0,b=0,c=0;
            rep(i,d){
                if(p%3==0){
                    x+=3*pow(10,i);
                    a=true;
                }
                if(p%3==1){
                    x+=5*pow(10,i);
                    b=true;
                }
                if(p%3==2){
                    x+=7*pow(10,i);
                    c=true;
                }
                p/=3;
            }
            if(a&&b&&c){
                if(x<=n)count++;
            }
        }
        d--;
    }
    cout << count <<endl;
}

Score : 300 points

Problem Statement

You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there?

Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:

When the number is written in base ten, each of the digits 7, 5 and 3 appears at least once, and the other digits never appear.

Constraints

1 \leq N < 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go-San numbers between 1 and N (inclusive).

Sample Input 1

575

Sample Output 1

4

There are four Shichi-Go-San numbers not greater than 575: 357, 375, 537 and 573.

Sample Input 2

3600

Sample Output 2

13

There are 13 Shichi-Go-San numbers not greater than 3600: the above four numbers, 735, 753, 3357, 3375, 3537, 3557, 3573, 3575 and 3577.

Sample Input 3

999999999

Sample Output 3

26484


// template version 1.6
// {{{ define basic macro
using namespace std;
#include <iostream>
#include <bits/stdc++.h>
// varibable settings
#define int long long
#define INF 1000000000000000000LL
// #define INF 2147483647
#define MOD 1000000007LL
// #define MOD 998244353LL
#define infile "../test/sample-1.in"

#define _overload3(_1,_2,_3,name,...) name
#define _rep(i,n) repi(i,0,n)
#define repi(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define rep(...) _overload3(__VA_ARGS__,repi,_rep,)(__VA_ARGS__)
#define _rrep(i,n) rrepi(i,0,n)
#define rrepi(i,a,b) for(int i=(int)(b-1);i>=(int)(a);--i)
#define rrep(...) _overload3(__VA_ARGS__,rrepi,_rrep,)(__VA_ARGS__)
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define uni(x) sort(all(x));x.erase(unique(all(x)),x.end())
#define ten(n) ((int)1e##n)
template<class T, size_t N> size_t sza(const T (&array)[N]) { return N; }
template<class T> inline void chmax(T &a, const T &b) { if(a < b) a = b; }
template<class T> inline void chmin(T &a, const T &b) { if(a > b) a = b; }
template<class T=int> T in() {T x; cin>>x; return (x);}
struct Fast { Fast(){ std::cin.tie(0); ios::sync_with_stdio(false); } } fast;

// dump macro
#ifdef PCM
  #include "dump.hpp"
#else
  #define dump(...) 42
  #define dump_1d(...) 42
  #define dump_2d(...) 42
#endif

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long double ld;
typedef pair<int,int> pii;
typedef tuple<int,int,int> iii;
template<typename T> using PQ = priority_queue<T, vector<T>, greater<T>>;
int dx[]={1, -1, 0, 0};
int dy[]={0, 0, 1, -1};
#define fi first
#define se second

// }}}

map<int, int> pf;

void prime_factor(int n) { // 素因数分解 (o(√N))
    for(int i = 2; i * i <= n; i++) {
        while(n % i == 0) {
            ++pf[i];
            n /= i;
        }
    }
    if (n != 1) pf[n] += 1;
}

int solve(){
  int N;cin>>N;
  rep(i, 2, N+1){
    prime_factor(i);
  }
  dump(pf);

  map<int, int> c;
  for (auto el:pf){
    if (el.second>=75) c[75]++;
    if (el.second>=24) c[24]++;
    if (el.second>=14) c[14]++;
    if (el.second>=4) c[4]++;
    if (el.second>=2) c[2]++;
  }
  int res=0;
  res += c[75];
  res += c[24]*(c[2]-1);
  res += c[14]*(c[4]-1);
  if (c[4]>=2 and c[2]>=3) res+=c[4]*(c[4]-1)/2*(c[2]-2);
  cout << res << endl;

  return 0;
}

signed main() { //{{{
#ifdef INPUT_FROM_FILE
  std::ifstream in(infile);
  std::cin.rdbuf(in.rdbuf());
#endif
  solve();
  return 0;
} //}}}

Score : 400 points

Problem Statement

You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?

Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.

Note

When a positive integer A divides a positive integer B, A is said to a divisor of B.
For example, 6 has four divisors: 1, 2, 3 and 6.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go numbers that are divisors of N!.

Sample Input 1

9

Sample Output 1

0

There are no Shichi-Go numbers among the divisors of 9! = 1 \times 2 \times ... \times 9 = 362880.

Sample Input 2

10

Sample Output 2

1

There is one Shichi-Go number among the divisors of 10! = 3628800: 32400.

Sample Input 3

100

Sample Output 3

543


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

typedef long long lint;
typedef pair<int, int> P;
#define REP(i, x, n) for(int i = x ; i < n ; ++i)
#define rep(i, n) REP(i, 0, n)
#define repr(i, n) for(int i = n - 1 ; i >= 0 ; --i)
#define ALL(x) (x).begin(), (x).end()
#define SORT(x) sort(ALL(x))

const int IINF = 1e9 + 10;
const lint LLINF = (lint)1e18 + 10;
const lint MOD = (lint)1e9 + 7;
const int dx4[] = {1, 0, -1, 0}, dy4[] = {0, 1, 0, -1};
const int dx8[] = {1, 1, 0, -1, -1, -1, 0, 1}, dy8[] = {0, -1, -1, -1, 0, 1, 1, 1};

int main(){
    int n;
    cin >> n;
    map<int, lint> mp;
    REP(i, 2, n + 1){
        int tmp = i;
        for(int j = 2 ; j * j <= tmp ; ++j){
            lint cnt = 0;
            while(tmp % j == 0){
                tmp /= j;
                ++cnt;
            }
            mp[j] += cnt;
        }
        if(tmp > 1){
            ++mp[tmp];
        }
    }
    lint ans = 0;
    for(auto x : mp){
        if(x.second >= 74){
            ++ans;
        }
        for(auto y : mp){
            if(x.first == y.first){
                continue;
            }
            if(x.second >= 2 && y.second >= 24){
                ++ans;
            }
            if(x.second >= 4 && y.second >= 14){
                ++ans;
            }
            for(auto z : mp){
                if(x.first == z.first || y.first >= z.first){
                    continue;
                }
                if(x.second >= 2 && y.second >= 4 && z.second >= 4){
                    ++ans;
                }
            }
        }
    }
    cout << ans << endl;
    return 0;
}


#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <bitset>
#include <string>
#include <algorithm>
#include <numeric>
#include <vector>
#define REP(i, n) for(int i = 0; i < (n); i++)
#define ALL(c) c.begin(),c.end()
#define PB push_back
#define INF 1100000000
#define LLINF 1100000000000000000
#define MOD 1000000007
#define FI first
#define SE second
#define MP make_pair

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

int main()
{
  int N; cin >> N;
  int sum = 0;
  vector<ll> A(N);
  REP(i, N) {
    cin >> A[i];
    sum += A[i];
  }

  int ans, mindist = INF;
  REP(i, N) {
    if (mindist > abs(sum - N*A[i])) {
      mindist = abs(sum - N*A[i]);
      ans = i;
    }
  }
  cout << ans << endl;

  return 0;
}

Score : 200 points

Problem Statement

Niwango-kun is an employee of Dwango Co., Ltd.

One day, he is asked to generate a thumbnail from a video a user submitted.

To generate a thumbnail, he needs to select a frame of the video according to the following procedure:

Get an integer N and N integers a_0, a_1, ..., a_{N-1} as inputs. N denotes the number of the frames of the video, and each a_i denotes the representation of the i-th frame of the video.

Select t-th frame whose representation a_t is nearest to the average of all frame representations.

If there are multiple such frames, select the frame with the smallest index.

Find the index t of the frame he should select to generate a thumbnail.

Constraints

1 \leq N \leq 100

1 \leq a_i \leq 100

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N
a_{0} a_{1} ... a_{N-1}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

1

Since the average of frame representations is 2, Niwango-kun needs to select the index 1, whose representation is 2, that is, the nearest value to the average.

Sample Input 2

4
2 5 2 5

Sample Output 2

0

The average of frame representations is 3.5.

In this case, every frame has the same distance from its representation to the average.

Therefore, Niwango-kun should select index 0, the smallest index among them.


#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
#include <string>
#include <list>
#include <set>

#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)
#define all(c) c.begin(),c.end()

using namespace std;

int N, M, K, W,X;
int dp[101];

int main() {
	int Ma, Mb,sum=0;
	double k,res=101,num;

	cin >> N;

	vector <int> a(N),b(N);

	rep(i, N) {
		cin >> a[i];
		sum += a[i];
	}
	k = sum / double(N);
	//もっとも差が小さい項を選びたい。
	//なんかいいやり方あったかな？
	//
	rep(i, N) {
		if (fabs(a[i] - k) < res) {
			res = min(res, fabs(a[i] - k));
				num=i;

		}
	}
	cout << num;

}


#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <bitset>
#include <map>
#include <tuple>
#include <unordered_map>
#include <list>
#include <numeric>
#include <utility>
#include <iterator>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <ctime>
#include <cassert>
#include <random>

#define INF 1000000000
#define LINF 9000000000000000000
#define mod  1000000007

#define rep(i,n) for(int i=0;i<int(n);i++)
#define rrep(i,n) for(int i=n-1;i>=0;i--)
#define REP(i,a,b) for(int i=(a);i<int(b);i++)
#define all(x) (x).begin(),x.end()
#define pb push_back
#define mp make_pair

using namespace std;

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

int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int ddx[8]={-1,-1,0,1,1,1,0,-1};
int ddy[8]={0,1,1,1,0,-1,-1,-1};
bool debug=false;

/*---------------------------------------------------*/

int main(){
  ll N, K;
  cin >> N >> K;
  vector<ll> a(N);
  rep(i, N) cin >> a[i];
  vector<ll> data;

  // REP(i, 1, N) a[i] += a[i - 1];
  REP(i, 0, N){
    int sum = 0;
    REP(j, i, N){
      sum += a[j];
      data.push_back(sum);
    }
  }
  sort(all(data), greater<ll>());
  int sum = 0;
  for(int i = 0; i < data.size(); i++) sum |= data[i];
  // cout << sum << endl;
  int bit = 1;

  while(1000000000 >= (2LL<<bit)){
    bit++;
  }bit--;

  int cnt = 0;
  while(bit){
    vector<int> hit;
    for(auto &x : data){
      if(x&(2LL<<bit)) hit.push_back(x);
    }
    if(K<=hit.size()){
      data.resize(hit.size());
      copy(all(hit), data.begin());
    }
    // for(auto x : data) cout << x << " ";cout << endl;
    bit--;
  }

  ll ans = LLONG_MAX;
  for(auto &x : data)if(x)ans = ans & x;
  cout << ans << endl;
  return 0;
}

Score : 400 points

Problem Statement

One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N.
He is interested in properties of the sequence a.

For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to know the maximum possible value of the bitwise AND of the beauties of K nonempty contiguous subsequences among all N(N+1)/2 nonempty contiguous subsequences. (Subsequences may share elements.)

Find the maximum possible value for him.

Constraints

2 \leq N \leq 1000

1 \leq a_i \leq 10^9

1 \leq K \leq N(N+1)/2

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the answer.

Sample Input 1

4 2
2 5 2 5

Sample Output 1

12

There are 10 nonempty contiguous subsequences of a. Let us enumerate them:

contiguous subsequences starting from the first element: \{2\}, \{2, 5\}, \{2, 5, 2\}, \{2, 5, 2, 5\}

contiguous subsequences starting from the second element: \{5\}, \{5, 2\}, \{5, 2, 5\}

contiguous subsequences starting from the third element: \{2\}, \{2, 5\}

contiguous subsequences starting from the fourth element: \{5\}

(Note that even if the elements of subsequences are equal, subsequences that have different starting indices are considered to be different.)

The maximum possible bitwise AND of the beauties of two different contiguous subsequences is 12.
This can be achieved by choosing \{5, 2, 5\} (with beauty 12) and \{2, 5, 2, 5\} (with beauty 14).

Sample Input 2

8 4
9 1 8 2 7 5 6 4

Sample Output 2

32


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

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())

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

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

void solve(){
    ll N, K;
    cin >> N >> K;

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

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

    ll numele = N * (N+1) / 2;
    vector<ll> B(numele);
    for (int i = 0; i < N; i++) {
        B[i] = a[i];
    }
    ll idx = N;
    for (int i = 0; i < N-1; i++) {
        for (int j = i+1; j < N; j++) {
            // cout << "i" << i << "j" << j << endl;
            B[idx] = a[j] - a[i];
            idx++;
        }
    }

    // for (int i = 0; i < (int)B.size(); i++) {
    //     cout << B[i] << endl;
    // }

    sort(all(B), greater<ll>());
    ll maxans = -1;
    for (int i = 0; i < numele - K + 1; i++) {
        ll ans = B[i];
        for (int j = 0; j < K; j++) {
            ans &= B[i+j];
        }
        maxans = max(maxans, ans);
    }

    cout << maxans << endl;
    return;
}

int main(int argc, char const* argv[])
{
    solve();
    return 0;
}


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

int main()
{
  double N, T, A;
  double t[1001];
  double res=INF;
  cin >> N >> T >> A;

  rep(i,N) {
    double h;
    cin >> h;
    t[i]= abs(A - (T - h*0.006));
  }

  int index = 0;
  rep(i,N){
    if(res > t[i]) {
      res = t[i];
      index = i+1;
    }
  }

  cout << index << endl;
}

Score: 200 points

Problem Statement

A country decides to build a palace.

In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.

There are N places proposed for the place. The elevation of Place i is H_i meters.

Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.

Print the index of the place where the palace should be built.

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

Print the index of the place where the palace should be built.

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.

The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


#include<bits/stdc++.h>
#include<iostream>
#include<vector>
#include<utility>
#include<functional>
#include<algorithm>
#include<queue>
#include<map>
#include<string>
#include<numeric>

#define FOR(i, a, b) for(int i=a; i<b; i++)
#define rep(i, n) for(int i=0; i<n; i++)
#define COUT(a) cout << a << endl;
#define PB push_back

using namespace std;
using ll = long long;
using P = pair<ll, ll>;

int main() {
    ll N, T, A;
    cin >> N;
    cin >> T >> A;
    vector<ll> H(N);

    ll ans = 100000;
    ll ans_ = 0;

    rep(i, N){
        cin >> H[i];
        float value = T - H[i] * 0.006 - A;
        if (value < 0) value = -value;
        if (ans >= value)
        {
            ans_ = i;
            ans = value;
        }
    }

    COUT(ans_+1);

}


#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<map>
#include<cstdio>
#include<stack>
#include<queue>
#include<fstream>
#include<cstdio>
#include<deque>
#include<iomanip>
#include <numeric>
//#include<bits/stdc++.h>

using namespace std;
#define ok1 printf("ok1\n");
#define ok2 printf("ok2\n");
#define M 1000000000000000000LL
#define rep(i,n) for(int i=0;i<n;i++)
#define REP(i,s,n) for(int i=(s);i<(n);i++)
#define repr(i,n) for(int i=n-1;i>=0;i--)
#define REPR(i,s,n) for(int i=(s);i>=(n);(i)--)
#define all(a) (a).begin(),(a).end()
#define reall(a) (a).rbegin(),(a).rend()
#define pb push_back
#define pf push_front
#define MIN(a,b) a=min((a),(b))
#define MAX(a,b) a=max((a),(b))
#define SIZE(v) (int)v.size()
const double pi = acos(-1.0);

typedef vector<int> vi;
typedef vector<string> vs;
typedef long long ll;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef deque<ll> dll;
typedef pair<ll, ll> P;
#define mod 1e9 + 7;
ll gcd(ll x, ll y)
{
	ll r;
	while ((r = x % y) != 0)
	{
		x = y;
		y = r;
	}
	return y;
}
ll lcm(ll x, ll y)
{
	x /= gcd(x, y);
	y /= gcd(x, y);
	return (x * y);
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	ll n, m;
	cin >> n >> m;
	vector<P> vec[100005];
	vi p(m), y(m), a(m), b(m);
	rep(i, m) {
		cin >> p[i] >> y[i];
		a[i] = p[i];
		vec[p[i]-1].pb(P(y[i], i));
	}
	rep(i, n) {
		sort(all(vec[i]));
		rep(j, vec[i].size()) {
			b[vec[i][j].second] = j;
		}
	}
	rep(i, m) {
		printf("%06d%06d\n", a[i], b[i] + 1);
	}
	return 0;
}

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003


#include <iostream>
#include <vector>
#include <cmath>
//https://qiita.com/ofutonfuton/items/92b1a6f4a7775f00b6ae

using namespace std;
typedef long long ll;

const ll M = pow(10,9)+7;

vector<ll> fac(300001); //n!(mod M)
vector<ll> ifac(300001); //k!^{M-2} (mod M)
// k^{M-2} == k^{-1}
//a,bの範囲的にこれだけ配列を用意していけば十分

ll mpow(ll x, ll n){ //x^n(mod M) ←普通にpow(x,n)では溢れてしまうため，随時mod計算
    ll ans = 1;
    while(n != 0){
        if(n&1) ans = ans*x % M;
        x = x*x % M;
        n = n >> 1;
    }
    return ans;
}

ll comb(ll a, ll b){ //aCbをmod計算
    if(a == 0 && b == 0)return 1;
    if(a < b || a < 0)return 0;
    ll tmp = ifac[a-b]* ifac[b] % M;
    return tmp * fac[a] % M;
}

ll comb2(ll a, ll b){ //aCbをmod計算
    if(a == 0 && b == 0)return 1;
    if(a < b || a < 0)return 0;
    ll tmp = ifac[a-b]* ifac[b] % M;
    return tmp * fac[a] % M;
}

long long gcd(long long a, long long b)
{
    long long c;

    if (a < b) {
        a+=b; b=a-b; a-=b;
    }

    while (b != 0) {
        c = a % b;
        a = b;
        b = c;
    }

    return a;
}

ll lcm( ll m, ll n )
{
	// 引数に０がある場合は０を返す
	if ( ( 0 == m ) || ( 0 == n ) )
		return 0;

	return ((m / gcd(m, n)) * n); // lcm = m * n / gcd(m,n)
}//lcm

pair<ll, ll> add_bunsuu(pair<ll, ll> a, pair<ll, ll> b){
    ll bunbo = lcm(a.second, b.second);

    cout << a.first << "/" << a.second << endl;
    cout << b.first << "/" << b.second << endl;
    cout << a.first * bunbo / a.second + b.first * bunbo / b.second << "/" << bunbo << endl;

    return make_pair(a.first * bunbo / a.second + b.first * bunbo / b.second , bunbo);
}

ll valid_amida_pattern(ll w){
    if(w <= 0){
        return 1;
    }
    return valid_amida_pattern(w - 1) + valid_amida_pattern(w - 2);
}

int main()
{
    ll H, W, K;
    cin >> H >> W >> K;
    ll** int_probs = new ll*[H + 1];
    for(ll i = 0; i < H + 1; i ++){
        int_probs[i] = new ll[W];
    }

    if(W == 1){
        return 1;
    }

    for(ll i = 0; i < W; i ++){
        if(i == 0){
            int_probs[0][i] = 1;
        }
        else{
            int_probs[0][i] = 0;
        }
    }

    for(ll i = 1; i < H + 1; i ++){
        for(ll n = 0; n < W; n ++){
            if(n == 0){
                int_probs[i][n] = int_probs[i - 1][n] * valid_amida_pattern(W - 2) + int_probs[i - 1][n + 1] * valid_amida_pattern(W - 3);
            }
            else if (n == W - 1){
                int_probs[i][n] = int_probs[i - 1][n] * valid_amida_pattern(W - 2) + int_probs[i - 1][n - 1] * valid_amida_pattern(W - 3);
            }
            else{
                int_probs[i][n] = int_probs[i - 1][n] * valid_amida_pattern(n - 1) * valid_amida_pattern(W - n - 2)
                    + int_probs[i - 1][n + 1] * valid_amida_pattern(n - 1) * valid_amida_pattern(W - n - 3)
                    + int_probs[i - 1][n - 1] * valid_amida_pattern(n - 2) * valid_amida_pattern(W - n - 2);
            }
            int_probs[i][n] = int_probs[i][n] % 1000000007;
        }
    }
    cout << int_probs[H][K - 1];

    return 0;
}

Score: 400 points

Problem Statement

Amidakuji is a traditional method of lottery in Japan.

To make an amidakuji, we first draw W parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is H+1 [cm], and the endpoints of the horizontal lines must be at 1, 2, 3, ..., or H [cm] from the top of a vertical line.

A valid amidakuji is an amidakuji that satisfies the following conditions:

No two horizontal lines share an endpoint.

The two endpoints of each horizontal lines must be at the same height.

A horizontal line must connect adjacent vertical lines.

Find the number of the valid amidakuji that satisfy the following condition, modulo 1\ 000\ 000\ 007: if we trace the path from the top of the leftmost vertical line to the bottom, always following horizontal lines when we encounter them, we reach the bottom of the K-th vertical line from the left.

For example, in the following amidakuji, we will reach the bottom of the fourth vertical line from the left.

Constraints

H is an integer between 1 and 100 (inclusive).

W is an integer between 1 and 8 (inclusive).

K is an integer between 1 and W (inclusive).

Input

Input is given from Standard Input in the following format:

H W K

Output

Print the number of the amidakuji that satisfy the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

1 3 2

Sample Output 1

1

Only the following one amidakuji satisfies the condition:

Sample Input 2

1 3 1

Sample Output 2

2

Only the following two amidakuji satisfy the condition:

Sample Input 3

2 3 3

Sample Output 3

1

Only the following one amidakuji satisfies the condition:

Sample Input 4

2 3 1

Sample Output 4

5

Only the following five amidakuji satisfy the condition:

Sample Input 5

7 1 1

Sample Output 5

1

As there is only one vertical line, we cannot draw any horizontal lines. Thus, there is only one amidakuji that satisfies the condition: the amidakuji with no horizontal lines.

Sample Input 6

15 8 5

Sample Output 6

437760187

Be sure to print the answer modulo 1\ 000\ 000\ 007.


#define _CRT_SECURE_NO_WARNINGS
#define mp	make_pair
#define pb	push_back
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

typedef long long	ll;

using namespace std;

vector<ll> a, b, vec, a1, b1;
ll n;

ll minim() {
	ll l = 1, r = n - 3;
	bool e = true;
	a.pb(vec[0]);
	a.pb(vec[n - 1]);
	b.pb(vec[n - 2]);
	while (l <= r)
	{
		ll y = vec[r];
		ll q, w;
		bool aa, bb;
		if (abs(a[a.size() - 1] - y) > abs(b[b.size() - 1] - y))
		{
			q = abs(a[a.size() - 1] - y);
			aa = true;
		}
		else
		{
			q = abs(b[b.size() - 1] - y);
			aa = false;
		}

		ll u = vec[l];
		if (abs(a[a.size() - 1] - u) > abs(b[b.size() - 1] - u))
		{
			w = abs(a[a.size() - 1] - u);
			bb = true;
		}
		else
		{
			w = abs(b[b.size() - 1] - u);
			bb = false;
		}
		if (w > q)
		{
			l++;
			if (bb)
			{
				a.pb(u);
			}
			else
			{
				b.pb(u);
			}
		}
		else
		{
			r--;
			if (aa)
			{
				a.pb(y);
			}
			else
			{
				b.pb(y);
			}
		}
	}
	ll rr = 0;
	for (ll i = a.size() - 1; i > 0; i--)
	{
		rr += abs(a[i] - a[i - 1]);
	}
	rr += abs(a[0] - b[0]);
	for (ll i = 1; i < b.size(); i++)
	{
		rr += abs(b[i] - b[i - 1]);
	}
	return rr;
}

ll maxim() {
	ll l = 2, r = n - 2;
	bool e = true;
	a1.pb(vec[n - 1]);
	a1.pb(vec[0]);
	b1.pb(vec[1]);
	while (l <= r)
	{
		ll y = vec[r];
		ll q, w;
		bool aa, bb;
		if (abs(a1[a1.size() - 1] - y) > abs(b1[b1.size() - 1] - y))
		{
			q = abs(a1[a1.size() - 1] - y);
			aa = true;
		}
		else
		{
			q = abs(b1[b1.size() - 1] - y);
			aa = false;
		}

		ll u = vec[l];
		if (abs(a1[a1.size() - 1] - u) > abs(b1[b1.size() - 1] - u))
		{
			w = abs(a1[a1.size() - 1] - u);
			bb = true;
		}
		else
		{
			w = abs(b1[b1.size() - 1] - u);
			bb = false;
		}
		if (w > q)
		{
			l++;
			if (bb)
			{
				a1.pb(u);
			}
			else
			{
				b1.pb(u);
			}
		}
		else
		{
			r--;
			if (aa)
			{
				a1.pb(y);
			}
			else
			{
				b1.pb(y);
			}
		}
	}
	ll rr = 0;
	for (ll i = a1.size() - 1; i > 0; i--)
	{
		rr += abs(a1[i] - a1[i - 1]);
	}
	rr += abs(a1[0] - b1[0]);
	for (ll i = 1; i < b1.size(); i++)
	{
		rr += abs(b1[i] - b1[i - 1]);
	}
	return rr;
}

int main()
{
	cin >> n;
	vec.resize(n);
	for (ll i = 0; i < n; i++)
	{
		cin >> vec[i];
	}
	if (n == 2)
	{
		cout << max(vec[0] - vec[1], vec[1] - vec[0]);
	}
	sort(vec.begin(), vec.end());
	ll r1 = maxim();
	ll r2 = minim();
	cout << max(r1, r2);
	return 0;
}

Score : 400 points

Problem Statement

You are given N integers; the i-th of them is A_i.
Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.

Constraints

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like.

Sample Input 1

5
6
8
1
2
3

Sample Output 1

21

When the integers are arranged as 3,8,1,6,2, the sum of the absolute differences between the adjacent elements is |3 - 8| + |8 - 1| + |1 - 6| + |6 - 2| = 21. This is the maximum possible sum.

Sample Input 2

6
3
1
4
1
5
9

Sample Output 2

25

Sample Input 3

3
5
5
1

Sample Output 3

8


/*
				   _ooOoo_
				  o8888888o
				  88" . "88
				  (| -_- |)
				  O\  =  /O
			   ____/`---'\____
			 .'  \\|     |//  `.
			/  \\|||  :  |||//  \
		   /  _||||| -:- |||||-  \
		   |   | \\\  -  /// |   |
		   | \_|  ''\---/''  |   |
		   \  .-\__  `-`  ___/-. /
		 ___`. .'  /--.--\  `. . __
	  ."" '<  `.___\_<|>_/___.'  >'"".
	 | | :  `- \`.;`\ _ /`;.`/ - ` : | |
	 \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
				   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
		fozubaoyou    pass System Test!
		quoted from "https://codeforces.com/contest/472/submission/7996840"
*/

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cctype>
#include <climits>
#include <string>
#include <bitset>
#include <cfloat>
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int,int> > vpii;
typedef vector<vector<int> > vvi;
typedef vector<vector<char> > vvc;
typedef vector<vector<string> > vvs;
typedef vector<vector<ll> > vvll;
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define rrep(i,n) for(int i = 1; i <= (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
#define fin(ans) cout<<(ans)<<endl
#define STI(s) atoi(s.c_str())
#define mp(p,q) make_pair(p,q)
#define pb(n) push_back(n)
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define Sort(a) sort(a.begin(),a.end())
#define Rort(a) sort(a.rbegin(),a.rend())
#define PI acos(-1)
template<class T> inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}
template<class T> inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}
struct io{io(){ios::sync_with_stdio(false);cin.tie(0);};};
const int MOD = 1000000007;
const int INF = INT_MAX;
const ll LLINF = 1LL<<60;

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

int main(void){

	int n,m;
	string s,t;
	cin>>n>>m>>s>>t;
	int x=lcm(n,m);

	vector<char> u(x,'%');
	int pos=0;
	bool ch=1;
	for(int i=0;i<x;i+=x/n){
		u[i]=s[pos];
		pos++;
	}
	pos=0;
	// rep(i,u.size()){
	// 	cout<<u[i]<<" ";
	// }
	// cout<<endl;
	for(int i=0;i<x;i+=x/m){
		if(u[i]==t[pos]||u[i]=='%'){
			u[i]=t[pos];
		} else {
			ch=0;
		}
		pos++;
	}
	if(ch){
		fin(x);
	} else {
		fin(-1);
	}

}

Score : 300 points

Problem Statement

You are given a string S of length N and another string T of length M.
These strings consist of lowercase English letters.

A string X is called a good string when the following conditions are all met:

Let L be the length of X. L is divisible by both N and M.

Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \frac{L}{N}+1)-th, ..., ((N-1)\times\frac{L}{N}+1)-th characters of X, without changing the order, results in S.

Concatenating the 1-st, (\frac{L}{M}+1)-th, (2 \times \frac{L}{M}+1)-th, ..., ((M-1)\times\frac{L}{M}+1)-th characters of X, without changing the order, results in T.

Determine if there exists a good string. If it exists, find the length of the shortest such string.

Constraints

1 \leq N,M \leq 10^5

S and T consist of lowercase English letters.

|S|=N

|T|=M

Input

Input is given from Standard Input in the following format:

N M
S
T

Output

If a good string does not exist, print -1; if it exists, print the length of the shortest such string.

Sample Input 1

3 2
acp
ae

Sample Output 1

6

For example, the string accept is a good string.
There is no good string shorter than this, so the answer is 6.

Sample Input 2

6 3
abcdef
abc

Sample Output 2

-1

Sample Input 3

15 9
dnsusrayukuaiia
dujrunuma

Sample Output 3

45


#include <bits/stdc++.h>
#define  rep(i,a,b)for(int i=a;i<b;++i)
#define  rrep(i,a,b)for(int i=a;i>=b;--i)
#define  yesno(flag)if(flag)cout<<"Yes"<<endl; else cout<<"No"<<endl;
using namespace std;
typedef long long ll;
const int INF=1000000000LL;
const ll r197=1000000007;
typedef pair<int,int>P;
typedef pair<int,P>Pa;
char e[100001],f[100001];

int main() {
	ll n,m;
	string s,t;
	cin>>n>>m;
	cin>>s>>t;
	ll a=n,b=m;
	while(1){
		if(a<b){
			ll d=a;
			a=b;
			b=d;
		}
		if(!b)break;
		a%=b;
	}
	ll l=(n*m)/a;
	rep(i,0,n){
		e[i]=s[i*(l/n)];
	}
	rep(i,0,m){
		f[i]=t[i*(l/m)];
	}
	bool ans=false;
	ll x=0,y=0;
	while(1){
		if(x>=n||y>=m)break;
		if(x*l/n==y*l/m){
			if(e[x]!=f[y])ans=true;
			if(x<n-1)x++;
			else y++;
		}else{
			if(x*(l/n)>y*(l/m))y++;
			else if(x*(l/n)<y*(l/m))x++;
		}
	}
	if(!ans)cout<<l<<endl;
	else cout<<-1<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FAST ios_base::sync_with_stdio(0); cin.tie(); cout.tie();

#define MAXX 500005
#define PI 3.14159265358979323846264338327950
#define F first
#define S second
#define ll   long long int
#define mod  1000000007

int main()
{
	FAST;
	ll n;
	cin >> n;
	if(n == 1){
		cout << "Hello World";
		return 0;
	}
	ll a, b;
	cin >> a >> b;
	cout << a + b;
}

Score: 100 points

Problem Statement

In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers A, B and prints A+B.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age N (1 or 2) as input, then prints Hello World if N=1, and additionally receives integers A, B and prints A+B if N=2.

Write this program for him.

Constraints

N is 1 or 2.

A is an integer between 1 and 9 (inclusive).

B is an integer between 1 and 9 (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
A
B

Output

If N=1, print Hello World; if N=2, print A+B.

Sample Input 1

1

Sample Output 1

Hello World

As N=1, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As N=2, Takahashi is two years old. Thus, we should print A+B, which is 8 since A=3 and B=5.


#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <deque>
#include <complex>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <ctime>
#include <iterator>
#include <bitset>
#include <numeric>
#include <list>
#include <iomanip>
using namespace std;
#define ll int64_t
const long MOD = 1e9 + 7;

int main()
{
  int a,b,n; //かっている数//最大100
  cin >> n >> a >> b;

  if (n==1){
    cout << "Hello World";
  }else{
    cout << a+b;
  }

  return 0;
}


#include <iostream>
using namespace std;

int main(){

    int N, T;
    int cost, time;
    int ans = 1e8;

    cin >> N >> T;
    for(int i = 0; i < N; i++){
        cin >> cost >> time;
        if(T >= time && ans > cost) ans = cost;
    }
    if(ans == 1e8) cout << "TLE" << endl;
    else cout << ans << endl;

    return 0;
}

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


#include <algorithm>
#include <cassert>
#include <cfloat>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#define FOR(i,k,n) for (int (i)=(k); (i)<(n); ++(i))
#define rep(i,n) FOR(i,0,n)
#define all(v) begin(v), end(v)
#define debug(x) std::cerr<< #x <<": "<<x<<"\n"
#define debug2(x,y) std::cerr<< #x <<": "<< x <<", "<< #y <<": "<< y <<"\n"

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef vector<ll> vll;
typedef vector<vector<ll> > vvll;
typedef deque<bool> db;
template<class T> using vv=vector<vector< T > >;

inline void scan(int&a){scanf("%d",&a);}
inline void scan(int&a,int&b){scanf("%d%d",&a,&b);}
inline void scan(int&a,int&b,int&c){scanf("%d%d%d",&a,&b,&c);}
inline void scan(int&a,int&b,int&c,int&d){scanf("%d%d%d%d",&a,&b,&c,&d);}
inline void scan(vector<int>&v){int sz=v.size();rep(i,sz){scan(v[i]);}}
inline void scan(vector<vector<int> >&v){int sz=v.size();rep(i,sz){scan(v[i]);}}
inline void scan(ll&a){scanf("%lld",&a);}
inline void scan(ll&a,ll&b){scanf("%lld%lld",&a,&b);}
inline void scan(ll&a,ll&b,ll&c){scanf("%lld%lld%lld",&a,&b,&c);}
inline void scan(ll&a,ll&b,ll&c,ll&d){scanf("%lld%lld%lld%lld",&a,&b,&c,&d);}
inline void scan(vector<ll>&v){int sz=v.size();rep(i,sz){scan(v[i]);}}
inline void scan(vector<vector<ll> >&v){int sz=v.size();rep(i,sz){scan(v[i]);}}
inline void scan(char&a){scanf(" %c",&a);}
inline void scan(vector<char>&v){int sz=v.size();rep(i,sz){scan(v[i]);}}
inline void scan(vector<vector<char> >&v){int sz=v.size();rep(i,sz){scan(v[i]);}}
inline void scan(string&s){char BUF[3000000];scanf(" %s",BUF);s=string(BUF);}

inline void print(int a){printf("%d\n",a);}
inline void print(int a,int b){printf("%d %d\n",a,b);}
inline void print(ll a){printf("%lld\n",a);}
inline void print(ll a,ll b){printf("%lld %lld\n",a,b);}
inline void print(string s){cout << s << "\n";}
inline void print_yn(bool flg){if(flg){printf("Yes\n");}else{printf("No\n");}}

// cout vector
template<typename T> ostream& operator<<(ostream& s, const vector<T>& v) {
  int len=v.size();s<<"\n";rep(i,len){s<<v[i];if(i<len-1){s << "\t";}}s<<"\n";return s; }
// cout 2-dimentional vector
template<typename T> ostream& operator<<(ostream& s, const vector< vector<T> >& vv) {
  int len=vv.size();rep(i,len){s<<vv[i];} return s; }
// cout deque
template<typename T> ostream& operator<<(ostream& s, const deque<T>& v) {
  int len=v.size();s<<"\n";rep(i,len){s<<v[i];if(i<len-1){s << "\t";}}s<<"\n";return s; }
// cout 2-dimentional deque
template<typename T> ostream& operator<<(ostream& s, const deque< deque<T> >& vv) {
  int len=vv.size();rep(i,len){s<<vv[i];} return s; }
// cout set<cout-able>
template<typename T> ostream& operator<<(ostream& s, const set<T>& v) {
  s<<"\n";for(auto elm : v){s<<elm<<"\t";}s<<"\n";return s; }

struct Prime {
  int max_check;
  int max_prime;
  int prime_number;
  vector<int> primes;
  map<int, int> prime_id;
  Prime() {};
  Prime(int m) {
    initialize(m);
  };
  void initialize(int m) {
    sieve(m);
    prime_number = (int)primes.size();
    max_check = m;
  }

  void sieve(int m) {
    max_prime = 2;
    deque<bool> is_prime(m+1, true);
    is_prime[0] = is_prime[1] = false;
    int i;
    for (i = 2; i <= m; ++i) {
      if (!is_prime[i]) {
        continue;
      }
      if (i * i > m) {
        break;
      }
      for (int j = i*2; j <= m; j += i) {
        is_prime[j] = false;
      }
      prime_id[i] = (int)primes.size();
      primes.push_back(i);
      max_prime = i;
    }
    for (int j = i; j <= m; ++j) {
      if (!is_prime[j]) {
        continue;
      }
      prime_id[j] = (int)primes.size();
      primes.push_back(j);
      max_prime = j;
    }
  }

  map<int, int> prime_factor(ll x) {
    map<int, int> ret;
    if ((ll)max_check * (ll)max_check < x) {
      return ret;
    }
    for (int i = 0; i < prime_number; ++i) {
      if (x == 1) {
        break;
      }
      while (x % primes[i] == 0) {
        x /= primes[i];
        ret[primes[i]] += 1;
      }
    }
    if (x != 1) {
      ret[x] += 1;
    }
    return ret;
  }
};

int main() {
  int n, m;
  scan(n, m);
  auto pr = Prime(32000);
  auto fac = pr.prime_factor(m);
  vector<int> facv = {1};
  for (auto f : fac) {
    int mult = 1;
    int l = facv.size();
    vvi addv(f.second, facv);
    rep (i, f.second) {
      mult *= f.first;
      rep (j, l) {
        addv[i][j] *= mult;
      }
    }
    rep (i, f.second) {
      facv.insert(facv.end(), all(addv[i]));
    }
  }
  sort(all(facv));
  int ind = upper_bound(all(facv), m/n) - facv.begin() - 1;
  print(facv[ind]);

  return 0;
}

Score : 400 points

Problem Statement

You are given integers N and M.

Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

N \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.

Sample Input 1

3 14

Sample Output 1

2

Consider the sequence (a_1, a_2, a_3) = (2, 4, 8). Their greatest common divisor is 2, and this is the maximum value.

Sample Input 2

10 123

Sample Output 2

3

Sample Input 3

100000 1000000000

Sample Output 3

10000


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

int main() {
    int N=0;
    cin >> N;
    for(int i=N; i<=999; i++){
        int x = (i/100)%10;
        int y = (i/10)%10;
        int z = i%10;
        if(x==y && y==z ){
            cout << i << endl;
            return 0;
        }
    }
    return 0;
}

Score : 200 points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

100 \leq N \leq 999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If the earliest ABC where Kurohashi can make his debut is ABC n, print n.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC 111, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC 112, which means Kurohashi can no longer participate in ABC 111.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC 222.

Sample Input 3

750

Sample Output 3

777