/*
                  友利奈緒ぱわーでACしてくれ！！！！！！！！！！！！
                  Charlotteまだ見てない人は見ような！！！！！！！

                  ／　 /:／　　　　　　　　　　　 　 ＼:ヽ　＼
  　　　　　　　 /　　／　　　　　　 　 　 　 　 　 　 　 ＼　　ヽ
  　　　　　＼__L 彡　　　　　　　　　　　　　　　　　　　 ヽ　　',
  　　　　　　　ﾌ /　　　/　　/　 /　　　,　　 　 　 　 ヽ　　', 　ｊ
  　　　　　　　ﾚ　　　 /　　/ 　/　 　 　 　 　 　 　 　 ', 　ヽ　j
  　　　 　 　 // 　 　 !　/_l＿/__ノ 　　{ ＼}　　　　 　 ',　　',/
  　　　　　　i ﾊ 　 　 {　从j　ﾊ　i　　　 ',　 ト-､}　 i i　 }　　jj
  　　　　　　( ﾊ　　　(　 川　ハ ﾊ　 !　 '　ﾊ　 ﾊ　j j　,' 　 八
  　　　 ＜＿,ｨ∧　　　斗芹ﾃミxハ ﾊ　 ﾚ　} /__ﾚﾚ　/ 　 ∧ ＼　ﾉ
  　　　 　 　 ∨　＼ 　ゝ　辷:ソ　　 　)　芹ﾚ心ヾレ′　/ ト--　´
  　　　＼ｰ‐'　ﾉ　　 ＼ゝ　　　　　　 　 　 ゞ:_ソ "/ 　／ 　ヽ
  　　　　 　 フ　　　　i八 " "　　　,　　　　　　　ム彡　　　　＼
  　　　　 　/　　/　　j　 ト　　　　　　 　 　 " "イト＜　 　 　 ＼＼
  　　　　 /　　/　　　j　/／ヽ､ 　 ∩　　 　 イ　{ {　　￣ フフへ ＼＼
  　　　　(　／　　　 ,/ / 　　i　＞――＜ニニニﾆ┐　 〃／: : ヽ　ヽヽ
  　　　　／　　ィT´/ /┌―　￣￣ /::: , ,)　 　 　 〃／／: : : : : :}　ヽヽ)
  　　　/ /　 ∧ヾi┌― { {￣　　　 ﾉ:::トﾟ<　 　 　 ∥//: : : : : : : : i　 ﾉ ﾉ
  . 　　( 人　 {:ヽヾi∨　∧V　　　 /:::/　､ヽ　　　 ∥/: : : : : : : : : :}　/
  　　　V　( ∧: :＼'∨　∧V　　 ﾉ:::/　 ∧ 〉＿__∥: : : : : :／: : : :ﾚ
  　　 　 　 /∧: : : : ∨　∧V┬ｲ:::ﾉ　 〈 TT　|　|{{: : : : ／: : : : : ∧　　 ﾉ
  　　　 　 (　ハ: : : : :∨'T∧Vi　i (　 　 V　!　!　{{: : ／ : : : : : : /　ｰ　ノ
  　　　　　V　ハ: : : : :∨ﾍ∧V　i ゝゝ　 i／⌒＼{／ : : : : : : : /ｰ― ´
  　　　　　 ∨　ヽ: : : : :∨ﾍ∧∨i　〉 〉 /　/二　 ): : : : : : : : :/

          (https://seesaawiki.jp/asciiart/d/Charlotte より)
*/
#include <bits/stdc++.h>
using namespace std;
using ll = long long; using ull = unsigned long long;
// #define int ll
// #define DEBUG 42
inline void nprint(){}
template <class Head, class... Tail>
inline void nprint(Head &&head, Tail &&... tail) {
    cout << head << endl;
    nprint(move(tail)...);
}
#ifdef DEBUG
  #define eprint(...) nprint(__VA_ARGS__)
#else
  #define eprint(...) if(0==1) cout << 1 << endl;
#endif
#define Yes(a) cout << (a ? "Yes" : "No") << endl
#define YES(a) cout << (a ? "YES" : "NO") << endl
#define POSSIBLE(a) cout << (a ? "POSSIBLE" : "IMPOSSIBLE") << endl
using vb = vector<bool>; using vvb = vector<vb>;
using vi = vector<int>; using vvi = vector<vi>;
using vl = vector<ll>; using vvl = vector<vl>;
template<class T> using V = vector<T>;
template<class T> using VV = vector<V<T>>;
#define fi first
#define se second
#define maxs(x,y) (x=max(x,y))
#define mins(x,y) (x=min(x,y))
using pii = pair<int,int>; using pll = pair<ll,ll>;
#define FOR(i,a,b) for(ll i = (a); i < (ll)(b); ++i)
#define REP(i,n) FOR(i,0,n)
#define REPS(i,n) REP(i,n+1)
#define RFOR(i,a,b) for(ll i = (ll)(b)-1;i >= a;--i)
#define RREP(i,n) RFOR(i,0,n)
#define RREPS(i,n) RREP(i,n+1)
#define ALL(obj) (obj).begin(), (obj).end()
#define RALL(obj) (obj).rbegin(), (obj).rend()
#define PERM(c) sort(ALL(c)); for(bool cp = true;cp;cp = next_permutation(ALL(c)))
#define eb(val) emplace_back(val)
const double PI = acos(-1), EPS = 1e-10;
const ll MOD = 1E9+7;
int dx[] = {1,0,-1,0}; int dy[] = {0,1,0,-1};
template<typename T1, typename T2> ostream& operator<<(ostream& s, const pair<T1, T2>& p){
  return s << "(" << p.first << ", " << p.second << ")";
}
template<class T> istream& operator>>(istream &is,vector<T> &st){
  for(size_t i=0;i<st.size();++i) is >> st[i];
  return is;
}
template<class T> istream& operator>>(istream &is,vector<vector<T>> &st){
  for(size_t i=0;i<st.size();++i) is >> st[i];
  return is;
}
template<class T> ostream& operator<<(ostream &os, const vector<T> &st){
  for(size_t i=0;i<st.size();++i){
    if(i==st.size()-1) os << st[i];
    else os << st[i] << " ";
  }
  return os;
}
template<class T> ostream& operator<<(ostream &os, const vector<vector<T>> &st){
  for(size_t i=0;i<st.size();++i){
    os << st[i];
    if(i!=st.size()-1) os << endl;
  }
  return os;
}
static const int MultiplyDeBruijnBitPosition[32] =
{
  0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
signed main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(10);
  int n;
  cin >> n;
  int ans = 0;
  REP(i,n){
    int a;
    cin >> a;
    ans += MultiplyDeBruijnBitPosition[((uint32_t)((a & -a) * 0x077CB531U)) >> 27];;
  }
  cout << ans << endl;
}

Score: 300 points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3".
Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer.

At most how many operations can be performed?

Constraints

N is an integer between 1 and 10 \ 000 (inclusive).

a_i is an integer between 1 and 1 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially {5, 2, 4}. Three operations can be performed as follows:

First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}.

Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}.

Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 3}.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is 0.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39


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

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

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

  int count = 0;
  for (int i = 0; i < n; i++) {
    while (v[i] / 2 + v[i] / 2 == v[i]) {
      count++;
      v[i] /= 2;
    }
  }
  cout << count << endl;
}

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

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>

#define rep(i, n) for (int i = 0; i < int(n); i++)
#define rrep(i, n) for (int i = int(n) - 1; i >= 0; i--)
#define reps(i, n) for (int i = 1; i <= int(n); i++)
#define rreps(i, n) for (int i = int(n); i >= 1; i--)
#define repi(i, a, b) for (int i = (a); i < int(b); i++)
#define all(a) (a).begin(), (a).end()
#define bit(b) (1ull << (b))

using namespace std;
using i32 = int;
using i64 = long long;
using f64 = double;
using vi32 = vector<i32>;
using vi64 = vector<i64>;
using vf64 = vector<f64>;
using vstr = vector<string>;

template<typename T, typename S> void amax(T &x, S y) { if (x < y) x = y; }
template<typename T, typename S> void amin(T &x, S y) { if (y < x) x = y; }

struct xyz {
  i64 x, y, z;
};

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout << fixed << setprecision(16);
  int n, m;
  cin >> n >> m;
  vector<xyz> v;
  rep(i, n) {
    i64 x, y, z;
    cin >> x >> y >> z;
    v.push_back({x, y, z});
  }
  i64 ans = 0;
  rep(i, bit(3)) {
    vi64 vv;
    rep(j, n) {
      i64 sum = 0;
      if (i & bit(0)) sum += v[j].x; else sum -= v[j].x;
      if (i & bit(1)) sum += v[j].y; else sum -= v[j].y;
      if (i & bit(2)) sum += v[j].z; else sum -= v[j].z;
      vv.push_back(sum);
    }
    sort(all(vv)); reverse(all(vv));
    i64 sum = 0;
    rep(j, m) sum += vv[j];
    amax(ans, sum);
  }
  cout << ans << endl;
  return 0;
}

Score: 400 points

Problem Statement

Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.

The shop sells N kinds of cakes.

Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.

These values may be zero or negative.

Ringo has decided to have M pieces of cakes here. He will choose the set of cakes as follows:

Do not have two or more pieces of the same kind of cake.

Under the condition above, choose the set of cakes to maximize (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity).

Find the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Constraints

N is an integer between 1 and 1 \ 000 (inclusive).

M is an integer between 0 and N (inclusive).

x_i, y_i, z_i \ (1 \leq i \leq N) are integers between -10 \ 000 \ 000 \ 000 and 10 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1 z_1
x_2 y_2 z_2
: :
x_N y_N z_N

Output

Print the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Sample Input 1

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

Sample Output 1

56

Consider having the 2-nd, 4-th and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 3 + 9 = 13

Tastiness: 5 + 5 + 7 = 17

Popularity: 9 + 8 + 9 = 26

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 13 + 17 + 26 = 56. This is the maximum value.

Sample Input 2

5 3
1 -2 3
-4 5 -6
7 -8 -9
-10 11 -12
13 -14 15

Sample Output 2

54

Consider having the 1-st, 3-rd and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 7 + 13 = 21

Tastiness: (-2) + (-8) + (-14) = -24

Popularity: 3 + (-9) + 15 = 9

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 21 + 24 + 9 = 54. This is the maximum value.

Sample Input 3

10 5
10 -80 21
23 8 38
-94 28 11
-26 -2 18
-69 72 79
-26 -86 -54
-72 -50 59
21 65 -32
40 -94 87
-62 18 82

Sample Output 3

638

If we have the 3-rd, 4-th, 5-th, 7-th and 10-th kinds of cakes, the total beauty, tastiness and popularity will be -323, 66 and 249, respectively.

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 323 + 66 + 249 = 638. This is the maximum value.

Sample Input 4

3 2
2000000000 -9000000000 4000000000
7000000000 -5000000000 3000000000
6000000000 -1000000000 8000000000

Sample Output 4

30000000000

The values of the beauty, tastiness and popularity of the cakes and the value to be printed may not fit into 32-bit integers.


#include <iostream>
using namespace std;
int main(){
    int a,b,h;
    cin >> a >> b;
    for (int i=1;i<=b-a;i++) {
        h += i;
    }
    cout << h-b << endl;
    return 0;
}

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1


#include <bits/stdc++.h>
using namespace std;
#define rep(i,n)for(int i=0;i<(n);i++)
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define pb push_back
using ll = long long;
using P = pair<int, int>;

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

const int MAX = 110000;
int dp[MAX];

int main(){
    int n; cin >> n;
    for(int i = 0; i < MAX; ++i) dp[i] = n;
    dp[0] = 0;
    priority_queue<P, vector<P>, greater<P>> q;
    q.push(make_pair(0,0));//(dist, pos)
    while(!q.empty()){
        int cur = q.top().first;
        int v = q.top().second;
        q.pop();
        if(cur > dp[v]) continue;
        for(int pow6 = 1; v + pow6 <= n; pow6 *= 6){
            int nv = v + pow6;
            if(chmin(dp[nv], dp[v]+1)) q.push(make_pair(dp[nv], nv));
        }
        for(int pow9 = 1; v + pow9 <= n; pow9 *= 9){
            int nv = v + pow9;
            if(chmin(dp[nv], dp[v]+1)) q.push(make_pair(dp[nv], nv));
        }
    }
    cout << dp[n] << endl;
}

Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16


//include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>

using namespace std;

//conversion
//------------------------------------------
inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v; }
template<class T> inline string toString(T x) { ostringstream sout; sout << x; return sout.str(); }

//math
//-------------------------------------------
template<class T> inline T sqr(T x) { return x * x; }

//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;

//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())

//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI = acos(-1.0);

//clear memory
#define CLR(a) memset((a), 0 ,sizeof(a))

//debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

VI c = { 1,9,
			9 * 9,
			9 * 9 * 9,
			9 * 9 * 9 * 9,
			9 * 9 * 9 * 9 * 9,
			9 * 9 * 9 * 9 * 9 * 9,
	6,
	6 * 6,
	6 * 6 * 6,
	6 * 6 * 6 * 6,
	6 * 6 * 6 * 6 * 6,
	6 * 6 * 6 * 6 * 6 * 6,
	6 * 6 * 6 * 6 * 6 * 6 * 6
};
const int inf = 1000000;

int main()
{
	int n;
	cin >> n;
	VVI dp = VVI(c.size()+1);
	REP(i, c.size()+1) {
		dp[i] = VI(n+1);
		REP(j, n+1)
		{
			dp[i][j] = inf;
		}
	}

	dp[0][0] = 0;
	REP(i, c.size())
	{
		REP(j, n+1)
		{
			if (j < c[i]) dp[i + 1][j] = dp[i][j];
			else {
				dp[i + 1][j] = min(dp[i][j], dp[i+1][j - c[i]] + 1);
			}
		}
	}
	cout << dp[c.size()-1][n] << endl;
	return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <climits>
#include <cmath>
#include <vector>
#include <string>

#define REP(i, n) for (int i=0;i<(n);i++)
#define FOR(i, a, b) for (int i=(a);i<(b);i++)

using namespace std;

int N;
int dp[100001];
vector<int> a;

int main()
{
    scanf("%d", &N);
    int i = 1;
    while(true) {
        if(pow(6, i)<100000)
            a.push_back(pow(6, i));
        else
            break;
        i++;
    }
    i = 1;
    while(true) {
        if(pow(9, i)<100000)
            a.push_back(pow(9, i));
        else
            break;
        i++;
    }
    a.push_back(1);
    sort(a.begin(), a.end());
    //REP(i, a.size())
    //    printf("%d ", a[i]);

    dp[0] = 0;
    dp[1] = 1;
    FOR(i, 2, 100001)
        dp[i] = 100000000;
    FOR(i, 2, 100001){
        REP(j, a.size()){
            if(i>=a[j])
                dp[i] = min(dp[i], dp[i-a[j]]+1);
            else
                break;
        }
    }
    printf("%d\n", dp[N]);

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
  int N,C_;cin>>N>>C_;
  vector<vector<int>> D(C_,vector<int>(C_));
  vector<vector<int>> c(N,vector<int>(N));
  for(int i=0;i<C_;i++){
    for(int j=0;j<C_;j++)cin>>D[i][j];//iは行
  }
  for(int i=0;i<N;i++){
    for(int j=0;j<N;j++)cin>>c[i][j];//iは行
  }
  vector<int> A;
  vector<int> B;
  vector<int> C;
  for(int i=0;i<N;i++){
    for(int j=0;j<N;j++){
      if((i+j)%3==0)A.push_back(c[i][j]-1);
      if((i+j)%3==1)B.push_back(c[i][j]-1);
      if((i+j)%3==2)C.push_back(c[i][j]-1);
    }
  }
  int ans=INT_MAX;
  for(int ca=0;ca<C_;ca++){
    for(int cb=0;cb<C_;cb++){
      for(int cc=0;cc<C_;cc++){
        if(ca==cb||cb==cc||cc==ca)continue;
        int tmp=0;
        for(int i=0;i<A.size();i++)tmp+=D[A[i]][ca];
        for(int i=0;i<B.size();i++)tmp+=D[B[i]][cb];
        for(int i=0;i<C.size();i++)tmp+=D[C[i]][cc];
        if(tmp<ans)ans=tmp;
      }
    }
  }
  cout<<ans;
}

Score : 400 points

Problem Statement

There is a grid with N rows and N columns of squares. Let (i,j) be the square at the i-th row from the top and the j-th column from the left.

These squares have to be painted in one of the C colors from Color 1 to Color C. Initially, (i,j) is painted in Color c_{i,j}.

We say the grid is a good grid when the following condition is met for all i,j,x,y satisfying 1 \leq i,j,x,y \leq N:

If (i+j) \% 3=(x+y) \% 3, the color of (i,j) and the color of (x,y) are the same.

If (i+j) \% 3 \neq (x+y) \% 3, the color of (i,j) and the color of (x,y) are different.

Here, X \% Y represents X modulo Y.

We will repaint zero or more squares so that the grid will be a good grid.

For a square, the wrongness when the color of the square is X before repainting and Y after repainting, is D_{X,Y}.

Find the minimum possible sum of the wrongness of all the squares.

Constraints

1 \leq N \leq 500

3 \leq C \leq 30

1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)

1 \leq c_{i,j} \leq C

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N C
D_{1,1} ... D_{1,C}
:
D_{C,1} ... D_{C,C}
c_{1,1} ... c_{1,N}
:
c_{N,1} ... c_{N,N}

Output

If the minimum possible sum of the wrongness of all the squares is x, print x.

Sample Input 1

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

Sample Output 1

3

Repaint (1,1) to Color 2. The wrongness of (1,1) becomes D_{1,2}=1.

Repaint (1,2) to Color 3. The wrongness of (1,2) becomes D_{2,3}=1.

Repaint (2,2) to Color 1. The wrongness of (2,2) becomes D_{3,1}=1.

In this case, the sum of the wrongness of all the squares is 3.

Note that D_{i,j} \neq D_{j,i} is possible.

Sample Input 2

4 3
0 12 71
81 0 53
14 92 0
1 1 2 1
2 1 1 2
2 2 1 3
1 1 2 2

Sample Output 2

428


#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
long long CN[400005];
long long mod = 998244353;
long long fstp(long long base, long long p) {
    long long rt = 1;
    while (p) {
        if (p & 1) {
            rt *= base;
            rt %= mod;
        }
        base *= base;
        base %= mod;
        p >>= 1;
    }
    return rt;
}
long long ny(long long x) {
    return fstp(x, mod - 2);
}

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

int main() {
    long long n, a, b, k;
    cin >> n >> a >> b >> k;
    if (k == 0) {
        cout << 1 << endl;
        return 0;
    }
    if (b < a) swap(a, b);
    CN[0] = 1;
    for (long long i = 1; i <= n; ++i) {
        CN[i] = CN[i - 1] * (n - i + 1) % mod * ny(i) % mod;
    }
    long long bs = n + 1;
    for (long long i = 0; i < b && i * a <= k; ++i) {
        if ((k - i * a) % b == 0) {
            bs = i;
            break;
        }
    }
    if (bs > n) {
        puts("0");
        return 0;
    }
    cout << bs << endl;
    long long bb = b / gcd(a, b);
    long long rs = 0;
    for (long long i = bs; i <= n; i += bb) {
        long long usb = (k - i * a) / b;
        if (i > n || usb > n) continue;
        rs += CN[i] * CN[usb] % mod;
        rs %= mod;
    }
    cout << rs << endl;
    return 0;
}

Score : 700 points

Problem Statement

Takahashi has a tower which is divided into N layers.
Initially, all the layers are uncolored. Takahashi is going to paint some of the layers in red, green or blue to make a beautiful tower.
He defines the beauty of the tower as follows:

The beauty of the tower is the sum of the scores of the N layers, where the score of a layer is A if the layer is painted red, A+B if the layer is painted green, B if the layer is painted blue, and 0 if the layer is uncolored.

Here, A and B are positive integer constants given beforehand. Also note that a layer may not be painted in two or more colors.

Takahashi is planning to paint the tower so that the beauty of the tower becomes exactly K.
How many such ways are there to paint the tower? Find the count modulo 998244353.
Two ways to paint the tower are considered different when there exists a layer that is painted in different colors, or a layer that is painted in some color in one of the ways and not in the other.

Constraints

1 ≤ N ≤ 3×10^5

1 ≤ A,B ≤ 3×10^5

0 ≤ K ≤ 18×10^{10}

All values in the input are integers.

Input

Input is given from Standard Input in the following format:

N A B K

Output

Print the number of the ways to paint tiles, modulo 998244353.

Sample Input 1

4 1 2 5

Sample Output 1

40

In this case, a red layer worth 1 points, a green layer worth 3 points and the blue layer worth 2 points. The beauty of the tower is 5 when we have one of the following sets of painted layers:

1 green, 1 blue

1 red, 2 blues

2 reds, 1 green

3 reds, 1 blue

The total number of the ways to produce them is 40.

Sample Input 2

2 5 6 0

Sample Output 2

1

The beauty of the tower is 0 only when all the layers are uncolored. Thus, the answer is 1.

Sample Input 3

90081 33447 90629 6391049189

Sample Output 3

577742975


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int a,b,y;
	cin>>a>>b;
	if(a*b>a-b&&a+b)
	{
		cout<<a*b<<endl;
	}
	else if(a-b>a+b)
	{
		cout<<a-b<<endl;
	}
	else
	{
	    cout<<a+b<<endl;
	}
	return 0;
}

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest value among A+B, A-B and A \times B.

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


#include<iostream>
#include<vector>
#include<math.h>
using namespace std;

long ope(long a,long b,long c){
  long res;
  res = b + c;
  return res;
}

int main(){
  long a,b,c,k;
  long ta,tb,tc;
  long ii,jj;
  long unfair = pow(10,18);
  long keisuu;

  cin >> a >> b >> c >> k;

  if(k <= 2){
	for(ii=1;ii<=k;ii++){
	  ta = a;
	  tb = b;
	  tc = c;

	  a = tb + tc;
	  b = ta + tc;
	  c = tb + tc;
	  if(a - b > unfair){
		break;
	  }
	}
  }
  else{
	keisuu = pow(2,k) - pow(2,k-1) - (2*(k-2)-1);
	if(k % 2 == 0){
	  a = (keisuu+1)* a + keisuu * b + keisuu * c;
	  b = (keisuu+1)* b + keisuu * a + keisuu * c;
	}
	else{
	  a = (keisuu-1)* a + keisuu * b + keisuu * c;
	  b = (keisuu-1)* b + keisuu * a + keisuu * c;
	}
  }

  if(a -b <= unfair){
	cout << (a - b)  << endl;
  }
  else{
	cout << "Unfair"  << endl;
  }

  // a1 = b0 + c0
  // a2 = b1 + c1 = a0 + c0 + a0 + b0 = 2*a0 + b0 + c0
  return 0;
}

Score : 300 points

Problem Statement

Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively.
After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get:

Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own integer with the result.

However, if the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Constraints

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

0 \leq K \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the integer Takahashi will get minus the integer Nakahashi will get, after repeating the following operation K times.
If the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Sample Input 1

1 2 3 1

Sample Output 1

1

After one operation, Takahashi, Nakahashi and Hikuhashi have 5, 4 and 3, respectively. We should print 5-4=1.

Sample Input 2

2 3 2 0

Sample Output 2

-1

Sample Input 3

1000000000 1000000000 1000000000 1000000000000000000

Sample Output 3

0


#include <bits/stdc++.h>
#define pb push_back
#define ll long long
#define ull unsigned long long
#define FF first
#define SS second
#define MOD 1000000007

using namespace std;

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

ll modpower(ll x, ll y, ll p) //x^y mod p
{
    ll res = 1;      // Initialize result

    x = x % p;  // Update x if it is more than or
                // equal to p

    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y %2!= 0)
            res = (res*x) % p;

        // y must be even now
        y = y/2;
        x = (x*x) % p;
    }
    return res;
}

int main()
{
	ios_base::sync_with_stdio(false);
	ll a,b,c,k;
	cin>>a>>b>>c>>k;
	if(k%2==0)
	{
		cout<<a-b;
	}
	else
	{
		cout<<b-a;
	}
}


#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <sstream>
#include <algorithm>
#include <deque>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <list>
#include <cstdio>
#include <iostream>
#include <cmath>
#include <climits>
#include <bitset>
#include <functional>
#include <numeric>
#include <ctime>
#include <cassert>
#include <cstring>
#include <fstream>

using namespace std;
int main(){
int a,b,c,d;
cin>>a>>b>>c>>d;
if(a-b<=d&&b-c<=d) cout<<"Yes"<<endl;
else if (c-b<=d&&b-a<=d) cout<<"Yes"<<endl;
else if(a-c<=d&&c-b<=d) cout<<"Yes"<<endl;
else if(c-a<=d&&a-b<=d) cout<<"Yes"<<endl;
else if(b-a<=d&&a-c<=d) cout<<"Yes"<<endl;
else if(b-c<=d&&c-a<=d) cout<<"Yes"<<endl;
else if(c-a<=d) cout<<"Yes"<<endl;
else if(a-c<=d) cout<<"Yes"<<endl;

else cout<<"No"<<endl;
}

Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


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

int main() {

	ll X;
	cin >> X;
	ll an = 1;
	for (ll i = 2; i * i <= X; i++) {
		ll k = i * i;
		while (k <= X) {
			an = max(an, k);
			k *= i;
		}
	}
	cout << an << endl;
}

Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <iomanip>
using namespace std;
typedef long long unsigned int ll;

#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))

#define DEBUG

#ifdef DEBUG
#define var_dump(...) fprintf(stdout, __VA_ARGS__)
#define dump(a) cout << a << "\n";
#else
#define var_dump(...) 42
#define dump(a) 42
#endif

typedef pair<int, int> P;
typedef pair<ll, ll> LP;
typedef pair<int, P> PP;
typedef pair<ll, LP> LPP;

int dy4[]={0, 0, 1, -1};
int dx4[]={1, -1, 0, 0};
int dx8[]={0, 0, 1, -1, 1, 1, -1, -1};
int dy8[]={1, -1, 0, 0, 1, -1, -1, 1};

// https://beta.atcoder.jp/contests/abc097/tasks/abc097_b

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

    set<ll> s;
    s.insert(1);
    for (ll i = 2; i <= 1000; i++) {
        for (ll j = i * i; j <= 1000; j=j*i) {
            s.insert(j);
        }
    }

    int prev = 1;
    for (int i = 1; i <= 1000; i++) {
        if (!s.count(i)) continue;
        if (i > X) {
            cout << prev << "\n";
            return 0;
        }

        prev = i;
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
#define forn(i,n) for(ll i=0;i<ll(n);++i)
#define all(x) (x).begin(),(x).end()

int main() {
    ios::sync_with_stdio(false);
    string s;
    ll k;
    cin >> s >> k;
    set<string> S;
    ll n = s.size();
    forn(i, n) {
        for (ll j = i; j < n; ++j) {
            string t = s.substr(i, j-i+1);
            if ((ll)S.size() < k || t < *S.rbegin()) {
                S.insert(t);
            }
            else break;
            while ((ll)S.size() > k) {
                S.erase(prev(S.end()));
            }
        }
    }
    cout << *S.rbegin() << '\n';
}

Score : 300 points

Problem Statement

You are given a string s.
Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s.
For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z and an empty string are not.
Also, we say that substrings are different when they are different as strings.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

200 points will be awarded as a partial score for passing the test set satisfying |s| ≤ 50.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

s has five substrings: a, b, ab, ba and aba.
Among them, we should print the fourth smallest one, b.
Note that we do not count a twice.

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


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

#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()

typedef long long ll;
typedef array<int, 3> tri;
typedef long double ld;

template <class T> istream& operator>>(istream& I, vector<T>& v) {for (T &e: v) I >> e; return I;}
template <class T> ostream& operator<<(ostream &O, const vector<T>& v) {for (const T &e: v) O << e << ' '; return O;}

void dfs(int a, const vector<vector<int>>& adj, vector<bool>& vis, vector<int>& cc) {
        cc.emplace_back(a);
        vis[a] = 1;
        for (auto b: adj[a]) {
                if (!vis[b]) {
                        dfs(b, adj, vis, cc);
                }
        }
}

void _main() {
        int n, m; cin >> n >> m;
        vector<int> perm(n + 1);
        for (int i = 1; i <= n; i++) cin >> perm[i];
        vector<vector<int>> adj(n + 1);
        while (m--) {
                int a, b; cin >> a >> b;
                adj[a].emplace_back(b);
                adj[b].emplace_back(a);
        }

        vector<bool> vis(n + 1);
        int ans = 0;
        for (int i = 1; i <= n; i++) {
                if (vis[i]) continue;
                vector<int> cc;
                dfs(i, adj, vis, cc);
                vector<int> bb;
                for (auto it: cc) bb.emplace_back(perm[it]);
                sort(all(bb));
                sort(all(cc));
                for (auto b: bb) {
                        ans += binary_search(all(cc), b);
                }
        }

        cout << ans;
}

signed main() {
        ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//        freopen("input.txt", "r", stdin);
        int _t = 1;
//        cin >> _t;
        while (_t--) _main();
        return 0;
}

Score : 400 points

Problem Statement

We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N.
We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M).
AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized:

Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}.

Find the maximum possible number of i such that p_i = i after operations.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

p is a permutation of integers from 1 through N.

1 ≤ x_j,y_j ≤ N

x_j ≠ y_j

If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
p_1 p_2 .. p_N
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the maximum possible number of i such that p_i = i after operations.

Sample Input 1

5 2
5 3 1 4 2
1 3
5 4

Sample Output 1

2

If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2.

Sample Input 2

3 2
3 2 1
1 2
2 3

Sample Output 2

3

If we perform the operation by, for example, choosing j=1, j=2, j=1 in this order, p becomes 1 2 3, which is obviously optimal.
Note that we may choose the same j any number of times.

Sample Input 3

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

Sample Output 3

8

Sample Input 4

5 1
1 2 3 4 5
1 5

Sample Output 4

5

We do not have to perform the operation.


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
// #include <numeric>
#include <complex>

#define FAST ios_base::sync_with_stdio(false); cin.tie(0)
#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 repr(i, a, b) for(int i=int(a); i>=int(b); i--)
#define FOR(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it)
typedef long long int ll;
#define iceil(x,y) (x+y-1)/y
#define min(x,y)(x<y?x:y)

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

int main() {
	FAST;

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

	int res;
	if (b>12) res = a;
	else res = (a<b? a:b);
	cout << res;

	return 0;
}

Score: 100 points

Problem Statement

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.

For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.

How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

a is an integer between 1 and 12 (inclusive).

b is an integer between 1 and 31 (inclusive).

2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Sample Input 1

5 5

Sample Output 1

5

There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.

Sample Input 2

2 1

Sample Output 2

1

There is only one day that is Takahashi: 1-1.

Sample Input 3

11 30

Sample Output 3

11

There are eleven days that are Takahashi: 1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 9-9, 10-10 and 11-11.


#include <iostream>
using namespace std;
bool isprime(int p) {
	if (p == 1) return false;
	for (int i = 2; i*i < p; i++) {
		if (p%i == 0) return false;
	}
	return true;
}

int n;

int main() {
	cin >> n;
	for (int i = 31; i <= 55555; i += 30) {
		if (isprime(i) == true) {
			if (i != 31) cout << " ";
			cout << i; n--;
		}
		if (n == 0) break;
	}
	cout << endl;
	return 0;
}

Score: 400 points

Problem Statement

Print a sequence a_1, a_2, ..., a_N whose length is N that satisfies the following conditions:

a_i (1 \leq i \leq N) is a prime number at most 55 555.

The values of a_1, a_2, ..., a_N are all different.

In every choice of five different integers from a_1, a_2, ..., a_N, the sum of those integers is a composite number.

If there are multiple such sequences, printing any of them is accepted.

Notes

An integer N not less than 2 is called a prime number if it cannot be divided evenly by any integers except 1 and N, and called a composite number otherwise.

Constraints

N is an integer between 5 and 55 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print N numbers a_1, a_2, a_3, ..., a_N in a line, with spaces in between.

Sample Input 1

5

Sample Output 1

3 5 7 11 31

Let us see if this output actually satisfies the conditions.

First, 3, 5, 7, 11 and 31 are all different, and all of them are prime numbers.

The only way to choose five among them is to choose all of them, whose sum is a_1+a_2+a_3+a_4+a_5=57, which is a composite number.

There are also other possible outputs, such as 2 3 5 7 13, 11 13 17 19 31 and 7 11 5 31 3.

Sample Input 2

6

Sample Output 2

2 3 5 7 11 13

2, 3, 5, 7, 11, 13 are all different prime numbers.

2+3+5+7+11=28 is a composite number.

2+3+5+7+13=30 is a composite number.

2+3+5+11+13=34 is a composite number.

2+3+7+11+13=36 is a composite number.

2+5+7+11+13=38 is a composite number.

3+5+7+11+13=39 is a composite number.

Thus, the sequence 2 3 5 7 11 13 satisfies the conditions.

Sample Input 3

8

Sample Output 3

2 5 7 13 19 37 67 79


#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	int pn = 1;
	if (*ci == '-') {
		pn = -pn;
		ci++;
	}
	ll tmp = *(ll*)ci;
	int dig = ((tmp & ma0) ^ ma0) ? 68 - __builtin_ctzll((tmp & ma0) ^ ma0) : 0;
	tmp = tmp << dig & ma1;
	tmp = tmp * 10 + (tmp >> 8) & ma2;
	tmp = tmp * 100 + (tmp >> 16) & ma3;
	tmp = tmp * 10000 + (tmp >> 32) & ma4;
	ci += (64 - dig >> 3);
	while ((ct = *ci++) >= '0') tmp = tmp * 10 + ct - '0';
	return pn * tmp;
}

ll A[200001];
void pakuri_sort(int N, ll A[]) {
	const int b = 8;
	ll tmp[200001];
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
	}
}

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

	int N = getint();
	rep1(i, N) {
		A[i] = getint() + A[i - 1];
	}

	pakuri_sort(N + 1, A);

	ll kotae = 0;
	ll mae = 1e18;
	int kazu = 0;
	rep(i, N + 1) {
		if (mae != A[i]) {
			mae = A[i];
			kazu = 0;
		}
		kotae += kazu++;
	}

	printf("%lld\n", kotae);

	Would you please return 0;
}

Score : 200 points

Problem Statement

We have an integer sequence A, whose length is N.

Find the number of the non-empty contiguous subsequences of A whose sums are 0.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

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

-10^9 \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

Find the number of the non-empty contiguous subsequences of A whose sum is 0.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are 0: (1,3,-4), (-4,2,2) and (2,-2).

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of (1, -1) are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

int main(){
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  int N; cin >> N;
  ll a[N+1];
  for(int i=1;i<=N;i++){
    cin >> a[i];
  }
  ll sum = 0;
  map<ll, int> mp;
  mp[0] = 1;
  ll cnt = 0;
  for(int i=1;i<=N;i++){
    sum += a[i];
    if(mp.find(sum) == mp.end()){
      mp[sum] = 1;
    }else{
      cnt += mp[sum];
      mp[sum] = mp[sum] + 1;
    }
  }
  cout << cnt << endl;
}


#include <bits/stdc++.h>

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

using namespace std;

class mint{
	static const int MOD=1e9+7;
	int x;
public:
	mint():x(0){}
	mint(long long y){ x=y%MOD; if(x<0) x+=MOD; }

	mint& operator+=(const mint& m){ x+=m.x; if(x>=MOD) x-=MOD; return *this; }
	mint& operator-=(const mint& m){ x-=m.x; if(x<   0) x+=MOD; return *this; }
	mint& operator*=(const mint& m){ x=1LL*x*m.x%MOD; return *this; }
	mint& operator/=(const mint& m){ return *this*=inverse(m); }
	mint operator+(const mint& m)const{ return mint(*this)+=m; }
	mint operator-(const mint& m)const{ return mint(*this)-=m; }
	mint operator*(const mint& m)const{ return mint(*this)*=m; }
	mint operator/(const mint& m)const{ return mint(*this)/=m; }
	mint operator-()const{ return mint(-x); }

	friend mint inverse(const mint& m){
		int a=m.x,b=MOD,u=1,v=0;
		while(b>0){ int t=a/b; a-=t*b; swap(a,b); u-=t*v; swap(u,v); }
		return u;
	}

	friend istream& operator>>(istream& is,mint& m){ long long t; is>>t; m=mint(t); return is; }
	friend ostream& operator<<(ostream& os,const mint& m){ return os<<m.x; }
	int to_int()const{ return x; }
};

mint operator+(long long x,const mint& m){ return mint(x)+m; }
mint operator-(long long x,const mint& m){ return mint(x)-m; }
mint operator*(long long x,const mint& m){ return mint(x)*m; }
mint operator/(long long x,const mint& m){ return mint(x)/m; }

mint fact(int n){
	static vector<mint> memo={1};
	if(memo.size()<=n){
		int k=memo.size();
		memo.resize(n+1);
		for(;k<=n;k++) memo[k]=memo[k-1]*k;
	}
	return memo[n];
}

mint fact_inverse(int n){
	static vector<mint> memo={1};
	if(memo.size()<=n){
		int k=memo.size();
		memo.resize(n+1);
		memo[n]=inverse(fact(n));
		for(int i=n;i>k;i--) memo[i-1]=memo[i]*i;
	}
	return memo[n];
}

mint choose(int n,int k,int type=0){
	if(k==0) return 1;
	if(n< k) return 0;
	if(type==0){
		return fact(n)*fact_inverse(k)*fact_inverse(n-k);
	}
	else{
		if(k>n-k) k=n-k;
		mint res=fact_inverse(k);
		rep(i,k) res*=n-i;
		return res;
	}
}

mint multichoose(int n,int k,int type=0){
	return choose(n+k-1,k,type);
}

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

	mint ans=0;
	for(int k=n-1;k>0;k--){
		ans+=fact(n-1);
		if(2*k-n-2>=0) ans-=multichoose(n-k+1,2*k-n-2)*fact(n-k)*fact(k-1);
	}
	cout<<ans<<'\n';

	return 0;
}

Score : 800 points

Problem Statement

There are N squares lining up in a row, numbered 1 through N from left to right.
Initially, all squares are white.
We also have N-1 painting machines, numbered 1 through N-1.
When operated, Machine i paints Square i and i+1 black.

Snuke will operate these machines one by one.
The order in which he operates them is represented by a permutation of (1, 2, ..., N-1), P, which means that the i-th operated machine is Machine P_i.

Here, the score of a permutation P is defined as the number of machines that are operated before all the squares are painted black for the first time, when the machines are operated in the order specified by P.
Snuke has not decided what permutation P to use, but he is interested in the scores of possible permutations.
Find the sum of the scores over all possible permutations for him.
Since this can be extremely large, compute the sum modulo 10^9+7.

Constraints

2 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the sum of the scores over all possible permutations, modulo 10^9+7.

Sample Input 1

4

Sample Output 1

16

There are six possible permutations as P.
Among them, P = (1, 3, 2) and P = (3, 1, 2) have a score of 2, and the others have a score of 3.
Thus, the answer is 2 \times 2 + 3 \times 4 = 16.

Sample Input 2

2

Sample Output 2

1

There is only one possible permutation: P = (1), which has a score of 1.

Sample Input 3

5

Sample Output 3

84

Sample Input 4

100000

Sample Output 4

341429644


#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;

int main() {
  string s;
  cin >> s;
  int cnt = 700;
  rep(i, s.size()) if (s[i] == 'o') {
    cnt += 100;
  }
  cout << cnt << endl;
  return 0;
}

Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

#define min(a, b) ((a) < (b)? (a):(b))
#define max(a, b) ((a) > (b)? (a):(b))
#define rep(i, n) REP(i, 0, (n))
#define REP(i, a, n) for(int i=(a); i<(n); i++)
#define abs(a) ((a) < (0)? -(a):(a))
#define rep(i, n) REP(i, 0, (n))
#define REP(i, a, n) for(int i=(a); i<(n); i++)
#define pb push_back

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

    int ans = 700;
    if(s[0] == 'o') ans+= 100;
    if(s[1] == 'o') ans+= 100;
    if(s[2] == 'o') ans+= 100;

    cout << ans << endl;
}


#include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < n; ++i)
#define repR(i, n) for(int i = n; i >= 0; ++i)
#define FDS(i, n) for(int i = 0; i < n; ++i)
#define FDSR(i, n) for(int i = n; i >= 0; ++i)
#define FOR(i, m, n) for(int i = m; i < n; ++i)
#define FORR(i, m, n) for(int i = m;i >= n;--i)
#define VSORT(v) sort(v.begin(), v.end());
#define INF 999999999
#define itn int
#define ednl endl
using namespace std;
typedef long long ll;
int main(){
	ll A,B,C,X,Y;
	cin>>A>>B>>C>>X>>Y;
	if(X==Y){
		cout<<min((C*X*2),((A+B)*X))<<endl;
	}
	else{
	    ll sum=0;
		int t=min(X,Y);
		sum+=(min((C*2),(A+B)))*t;
		sum+=(abs(X-Y))*min(A,2*C);
		cout<<sum<<endl;
	}
}

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


#include<iostream>
#include<algorithm>

using namespace std;
int main()
{
    int A, B, C, X, Y;
    cin >> A >> B >> C >> X >> Y;
  	int val=0;

    if(A > C*2){
        val= C*2*X;
        if(X<Y){
            if(B > C*2){
                val+= (Y-X)*C*2;
            }
            else{
                val+= (Y-X)*B;
            }
        }
    }
    else if(B > C*2){
        val= C*2*Y;
        if(Y<X){
            if(A > C*2){
                val+= (X-Y)*C*2;
            }
            else{
                val+= (X-Y)*A;
            }
        }
    }
    else if(A+B > C*2){
        if(X > Y){
            val = C*2*Y;
            val += A*(X-Y);
        }
        else{
            val = C*2*X;
            val += B*(Y-X);
        }
    }
    else{
        val= A*X + B*Y;
    }
    cout << val << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cassert>
using namespace std;
using VI = vector<long>;

long lefts[101010];
long leftback[101010];
long rights[101010];
long rightback[101010];

int main() {
    long n, c;
    cin >> n >> c;
    VI xs, vs;
    VI kankaku;
    for (int i = 0; i < n; i++) {
        long x, v;
        cin >> x >> v;
        if (i == 0) {
            kankaku.push_back(x);
        } else {
            kankaku.push_back(x - xs.back());
        }
        if (i == n - 1) {
            kankaku.push_back(c - x);
        }
        xs.push_back(x);
        vs.push_back(v);
        lefts[i + 1] = v - kankaku[i] + lefts[i];
        leftback[i + 1] = v - 2 * kankaku[i] + leftback[i];
    }
    for (int i = n - 1; i >= 0; i--) {
        int j = n - 1 - i;
        long v = vs[i];
        rights[j + 1] = v - kankaku[i + 1] + rights[j];
        rightback[j + 1] = v - 2 * kankaku[i + 1] + rightback[j];
    }

    long ans = 0;
    for (int i = 1; i <= n; i++) {
        ans = max(ans, lefts[i]);
        lefts[i] = max(lefts[i], lefts[i - 1]);
        ans = max(ans, rights[i]);
        rights[i] = max(rights[i], rights[i - 1]);
    }
    for (int i = 1; i < n; i++) {
        ans = max(ans, rightback[i] + lefts[n - i]);
        ans = max(ans, leftback[i] + rights[n - i]);
    }

    cout << ans << endl;
}

Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.


#include <iostream>
#include <vector>

using namespace std;

int main() {
	int N;
	long long C;

	cin >> N >> C;
	vector<long long>     cw(N + 1);
	vector<long long>  cwRev(N + 1);
	vector<long long>  sumCw(N + 1);
	vector<long long>    acw(N + 1);
	vector<long long> acwRev(N + 1);
	vector<long long> sumAcw(N + 1);
	vector<long long> x(N);
	vector<long long> v(N);
	for(int i = 0; i < N; i++) {
		cin >> x[i] >> v[i];
	}

	 sumCw[0] = 0;
	    cw[0] = 0;
	 cwRev[0] = 0;
	sumAcw[0] = 0;
	   acw[0] = 0;
	acwRev[0] = 0;
	for(int i = 1; i <= N; i++) {
		 sumCw[i] = sumCw[i - 1] + v[i - 1];
		    cw[i] = sumCw[i] - x[i - 1];
		 cwRev[i] = sumCw[i] - 2*x[i - 1];
		sumAcw[i] = sumAcw[i - 1] + v[N - i];
		   acw[i] = sumAcw[i] - (C - x[N - i]);
		acwRev[i] = sumAcw[i] - 2*(C - x[N - i]);
	}

	long long cal = 0;
	/*Bがスタート地点にいるとき*/
	for(int a = 0; a <= N; a++) {
		//printf("%lld\n", cw[a]);
		cal = max(cw[a], cal);
	}

	for(int b = 1; b <= N; b++) {
		for(int a = 0; a + b <= N; a++) {
			//printf("a:%d, b:%d ... ", a, b);
			//printf("%lld, %lld\n", cwRev[a] + acw[b], cw[a] + acwRev[b]);
			cal = max(max(cwRev[a] + acw[b], cw[a] + acwRev[b]), cal);
		}
	}

	cout << cal << endl;
	/*
	cout << endl;
	cout << "sumcw: " << flush;
	for(int i = 0; i <= N; i++) cout << sumCw[i] << ' ';
	cout << endl;
	cout << "cw: " << flush;
	for(int i = 0; i <= N; i++) cout << cw[i] << ' ';
	cout << endl;
	cout << "cwRev: " << flush;
	for(int i = 0; i <= N; i++) cout << cwRev[i] << ' ';
	cout << endl;
	cout << "sumacw: " << flush;
	for(int i = 0; i <= N; i++) cout << sumAcw[i] << ' ';
	cout << endl;
	cout << "acw: " << flush;
	for(int i = 0; i <= N; i++) cout << acw[i] << ' ';
	cout << endl;
	cout << "acwRev: " << flush;
	for(int i = 0; i <= N; i++) cout << acwRev[i] << ' ';
	cout << endl;
	*/

	return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;
const int maxn = 1e5 + 10;
const ll oo = 0x3f3f3f3f3f3f3f3f;
class Point{
public:
	ll x;
	int v;
};
Point p[maxn];
int n;
ll C;
ll ans = 0;
bool cmp(Point p1 , Point p2){
	return p1.x < p2.x;
}

ll sum[maxn];
void solve(){
	sort(p + 1 , p + n + 1 , cmp);
	sum[0] = 0;
	ll cur = 0 , mx = 0;
	for(int i = 1 ; i <= n ; ++ i){
		cur += p[i].v - (p[i].x - p[i - 1].x);
		if(cur > mx) mx = cur;
		sum[i] = mx;
	}
	ans = max(ans , sum[n]);
	ll now = 0;
	for(int i = n ; i >= 1 ; -- i){
		now += p[i].v;
		ans = max(ans , sum[i - 1] - 2 * (C - p[i].x) + now);
	}
}
int main(){
	ios::sync_with_stdio(0);
	cin >> n >> C;
	for(int i = 1 ; i <= n ; ++ i)
		cin >> p[i].x >> p[i].v;
	solve();
	for(int i = 1 ; i <= n ; ++ i)
		p[i].x = C - p[i].x;
	solve();
	cout << ans << endl;
	return 0;
}


#include "bits/stdc++.h"
using namespace std;
using ll=long long;
#define print(n) cout<<n<<endl
#define rep(i,a,n) for(int i=a;i<n;i++)
#define ALL(s) s.begin(),s.end()
#define P pair<ll,ll>
#define vl vector<ll>
#define vi vector<int>
#define vvl vector<vector<ll>>
#define vvi vector<vector<int>>
const int M=200111;
const int inf=1000000007;
const long long INF=1e18;
int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
int ddx[8]={1,-1,0,0,1,-1,-1,1},ddy[8]={0,0,1,-1,1,-1,1,-1};

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); // merge technique
		par[x] += par[y];
		par[y] = x;
		return true;
	}

	int size(int x) {
		return -par[root(x)];
	}
};

vvl comb(int n, int r) {
	vvl v(n + 1,vl(n + 1, 0));
	for (int i = 0; i < v.size(); i++) {
		v[i][0] = 1;
		v[i][i] = 1;
	}
	for (int j = 1; j < v.size(); j++) {
		for (int k = 1; k < j; k++) {
			v[j][k] = (v[j - 1][k - 1] + v[j - 1][k]);
		}
	}
	return v;
}

void sosu(ll x,bool f[]){
	ll y=x;
	for(ll i=2;i<=sqrt(y);i++){
		if(x%i==0){
			x/=i;
			f[i]=true;
			i--;
		}
	}
}

ll __gcd(ll x,ll y){
	if(x<y)swap(x,y);
	while(1){
		ll tmp=x%y;
		x=y;
		y=tmp;
		if(y==0)break;
	}
	return x;
}

int keta(ll a){
	int ke=1;
	while(a/=10)ke++;
	return ke;
}

int n,a,b,cnt=0;
int flag[M];
int dist1[M]={},distn[M]={};
vi g[M];

void __dist(int node,int y[]){
	flag[node]=true;
	for(auto x:g[node])
		if(!flag[x]){
			y[x]=(y[node]+1);
			__dist(x,y);
		}
}

int main(){
	int n;ll m,i,t;
	ll h1[M],h2[M],h3[M],h4[M],x[M],y[M],s;
	cin>>n>>m;
	for (i=1;i<=n;i++)
		cin>>x[i]>>y[i];
	for (i=1,t=0;i<=n;i++)
		t=t+y[i],h1[i]=max(h1[i-1],t-x[i]),h2[i]=max(h2[i-1],t-2*x[i]);
	for (i=n,t=0;i>0;i--)
		t=t+y[i],h3[i]=max(h3[i+1],t-(m-x[i])),h4[i]=max(h4[i+1],t-2*(m-x[i]));
	for (i=0;i<=n;i++)
		s=max(s,max(h1[i]+h4[i+1],h2[i]+h3[i+1]));
	print(s);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define sc(x) scanf("%d",&x);

ll fac(ll n){
    if (n < 2) return 1;
    return n * fac(n - 1);
}
ll COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac(n) / fac(k) / fac(n - k);
}

int main(){
    int n; sc(n)
    vector<int> A(n);
    for (int i = 0; i < n; i++) sc(A[i])
    sort(A.begin(), A.end());

    P ans = P(A[1], A[0]);
    ll maxv = COM(A[1], A[0]), tmp2;
    for (int i = 2; i < n; i++){
        auto tmp = upper_bound(A.begin(), A.end(), A[i]/2);
        if (A[i]/2 - *tmp < A[i]/2 - *(tmp+1) && *(tmp+1) <= A[i]) tmp++;
        tmp2 = COM(A[i], *tmp);
        if (tmp2 > maxv){
            maxv = tmp2;
            ans = P(A[i], *tmp);
        }
    }
    cout << ans.first << " " << ans.second << endl;
    return 0;
}

Score : 400 points

Problem Statement

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i=0; i<(int)(n); ++i)
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using Graph = vector<vi>;  // vi <=> vl
using vb = vector<bool>;
using boolGraph = vector<vb>;
using P = pair<int, int>;  // int <=> ll
const int MOD = 1e9+7;
const double EPS = 1e-9;

int main() {
  int n; cin >> n;
  vi arr(n+1);
  rep(i,n) cin >> arr[i];
  arr[n] = -1;

  sort(all(arr));

  int i = arr.back();

  auto iter = lower_bound(all(arr), i/2);
  int r1 = *iter;
  --iter;
  int r2 = *iter;

  int j;
  if (abs(i - 2*r1) < abs(i - 2*r2)) j = r1;
  else j = r2;

  cout << i << ' ' << j << endl;
  return 0;
}


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

typedef pair<int,int> P;

int h, w;
string s[12];

void check(vector<P> A, int S){

  string t[12];

  for(int i=0;i<(int)A.size();i++){

    t[i] = s[A[i].first];

    t[h-i-1] = s[A[i].second];

  }

  if( h % 2 == 1 ){

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

      if( S >> i & 1 ) continue;

      t[h/2] = s[i];

    }

  }

  int S2 = 0;

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

    if( S2 >> i & 1 ) continue;

    for(int j=i+1;j<w;j++){

      if( S2 >> j & 1 ) continue;

      int flag = 1;

      for(int k=0;k<h;k++){
	if( t[k][i] != t[h-k-1][j] ) flag = 0;
      }

      if( flag == 1 ){
	S2 |= ( 1 << i ) | ( 1 << j );
	break;
      }

    }

  }

  if( w % 2 == 0 && __builtin_popcount(S2) == w ){
    cout << "YES" << endl;
    exit(0);
  }

  if( w % 2 == 1 && __builtin_popcount(S2) == w - 1 ){

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

      if( S2 >> i & 1 ) continue;

      int flag = 1;

      for(int j=0;j<h;j++){
	if( t[j][i] != t[h-j-1][i] ) flag = 0;
      }

      if( flag == 1 ){
	cout << "YES" << endl;
	exit(0);
      }

    }

  }

}

void dfs(vector<P> A, int S, int X){

  if( h - __builtin_popcount(S) <= 1 ){

    check( A, S );

    return;
  }

  int idx = -1;

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

    if( i == X ) continue;

    if( S >> i & 1 ) continue;

    idx = i;

    break;

  }

  if( idx == -1 ) return;

  for(int i=idx+1;i<h;i++){

    if( i == X ) continue;

    if( S >> i & 1 ) continue;

    vector<P> nA = A;

    nA.push_back(P( idx, i ));

    int nS = S | ( 1 << idx ) | ( 1 << i );

    dfs( nA, nS, X );

  }

}

signed main(){

  cin>>h>>w;

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

  if( h % 2 == 0 ) dfs( vector<P>(0), 0, -1 );
  else{
    for(int i=0;i<h;i++) dfs( vector<P>(0), 0, i );
  }

  cout << "NO" << endl;

  return 0;
}

Score : 700 points

Problem Statement

There is an H \times W grid (H vertical, W horizontal), where each square contains a lowercase English letter.
Specifically, the letter in the square at the i-th row and j-th column is equal to the j-th character in the string S_i.

Snuke can apply the following operation to this grid any number of times:

Choose two different rows and swap them. Or, choose two different columns and swap them.

Snuke wants this grid to be symmetric.
That is, for any 1 \leq i \leq H and 1 \leq j \leq W, the letter in the square at the i-th row and j-th column and the letter in the square at the (H + 1 - i)-th row and (W + 1 - j)-th column should be equal.

Determine if Snuke can achieve this objective.

Constraints

1 \leq H \leq 12

1 \leq W \leq 12

|S_i| = W

S_i consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

If Snuke can make the grid symmetric, print YES; if he cannot, print NO.

Sample Input 1

2 3
arc
rac

Sample Output 1

YES

If the second and third columns from the left are swapped, the grid becomes symmetric, as shown in the image below:

Sample Input 2

3 7
atcoder
regular
contest

Sample Output 2

NO

Sample Input 3

12 12
bimonigaloaf
faurwlkbleht
dexwimqxzxbb
lxdgyoifcxid
ydxiliocfdgx
nfoabgilamoi
ibxbdqmzxxwe
pqirylfrcrnf
wtehfkllbura
yfrnpflcrirq
wvcclwgiubrk
lkbrwgwuiccv

Sample Output 3

YES


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

typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pl;

const int INT_INF = 2147483646;
const ll LL_INF = 9223372036854775807;

bool SecondCompare(const pair<int,int> &a,const pair<int,int> &b)
{
       return a.second<b.second;
}

bool SecondCompareDes(const pair<int,int> &a,const pair<int,int> &b)
{
       return a.second>b.second;
}

int n, a, b;
string s;
int are[100];
int main(){
    cin >> s;
    for(int i = 0; i < s.length(); i++){
        are[s[i]-'a']++;
    }
    for(int i = 0; i < 3; i++){
        if(are[i] != 1){
            cout << "No\n";
            return 0;
        }
    }
    cout << "Yes\n";
}

Score : 100 points

Problem Statement

You are given a string S of length 3 consisting of a, b and c. Determine if S can be obtained by permuting abc.

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If S can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll q,a,b,cnt,p,l;
int main()
{
	cin>>q;
	while(q--){
		cin>>a>>b;
		p=a*b;
		l=sqrt(p);
		if(l*(l+1)<p) cnt=2*(l-1)+1;
		else cnt=2*(l-1);
		if(l*l==p&&a!=b) cnt--;
		if(a*b==4) cnt=1;
		cout<<cnt<<endl;
	}
}

Score : 700 points

Problem Statement

10^{10^{10}} participants, including Takahashi, competed in two programming contests.
In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th.

The score of a participant is the product of his/her ranks in the two contests.

Process the following Q queries:

In the i-th query, you are given two positive integers A_i and B_i. Assuming that Takahashi was ranked A_i-th in the first contest and B_i-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's.

Constraints

1 \leq Q \leq 100

1\leq A_i,B_i\leq 10^9(1\leq i\leq Q)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
A_1 B_1
:
A_Q B_Q

Output

For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's.

Sample Input 1

8
1 4
10 5
3 3
4 11
8 9
22 40
8 36
314159265 358979323

Sample Output 1

1
12
4
11
14
57
31
671644785

Let us denote a participant who was ranked x-th in the first contest and y-th in the second contest as (x,y).

In the first query, (2,1) is a possible candidate of a participant whose score is smaller than Takahashi's. There are never two or more participants whose scores are smaller than Takahashi's, so we should print 1.


#pragma GCC optimize ("O3")
#pragma GCC optimize ("unroll-loops")
#pragma comment(linker, "/STACK:2000000")

#include "bits/stdc++.h"

using namespace std;

#define pb push_back
#define F first
#define S second
#define f(i,a,b)  for(int i = a; i < b; i++)
// #define endl '\n'
using ll = long long;
using db = long double;
using ii = pair<int, int>;

const int N = 2e5 + 5, LG = 19, MOD = 998244353;
const int SQ =320;
const long double EPS = 1e-7;
void print(vector<int> v){
  for(auto x : v)cout << x << ' ';
  exit(0);
}
int32_t main(){
#ifdef ONLINE_JUDGE
    ios_base::sync_with_stdio(0);
    cin.tie(0);
#endif

  int n;
  cin >> n;
  if(n == 3){
    cout << "2 5 63\n";
    return 0;
  }
  if(n <= 100){
    cout<<2<<' '<<3<<' '<<5<<' '<<20;
    f(i,0,n-4)cout<<' '<<30+i*30; return 0;
  }

  ll tot = 2 + 3 + 5;
  int cnt = n - 4;
  vector<int> v({2,3,5});
  for(int cur = 30000; cnt&&cur>=6;--cur){
    if((cur%2==0||cur%3==0||cur%5==0)&&(cur%30!=0)){
      v.push_back(cur);
      cnt--;
      tot += cur;
    }
  }

  while((tot%30)){
    tot-=v.back();
    v.pop_back();
  }
  for(int i = 0; v.size() < n; i++)v.pb((i+1)*30);

  print(v);

  return 0;
}

Score : 600 points

Problem Statement

Nagase is a top student in high school. One day, she's analyzing some properties of special sets of positive integers.

She thinks that a set S = \{a_{1}, a_{2}, ..., a_{N}\} of distinct positive integers is called special if for all 1 \leq i \leq N, the gcd (greatest common divisor) of a_{i} and the sum of the remaining elements of S is not 1.

Nagase wants to find a special set of size N. However, this task is too easy, so she decided to ramp up the difficulty. Nagase challenges you to find a special set of size N such that the gcd of all elements are 1 and the elements of the set does not exceed 30000.

Constraints

3 \leq N \leq 20000

Input

Input is given from Standard Input in the following format:

N

Output

Output N space-separated integers, denoting the elements of the set S. S must satisfy the following conditions :

The elements must be distinct positive integers not exceeding 30000.

The gcd of all elements of S is 1, i.e. there does not exist an integer d > 1 that divides all elements of S.

S is a special set.

If there are multiple solutions, you may output any of them. The elements of S may be printed in any order. It is guaranteed that at least one solution exist under the given contraints.

Sample Input 1

3

Sample Output 1

2 5 63

\{2, 5, 63\} is special because gcd(2, 5 + 63) = 2, gcd(5, 2 + 63) = 5, gcd(63, 2 + 5) = 7. Also, gcd(2, 5, 63) = 1. Thus, this set satisfies all the criteria.

Note that \{2, 4, 6\} is not a valid solution because gcd(2, 4, 6) = 2 > 1.

Sample Input 2

4

Sample Output 2

2 5 20 63

\{2, 5, 20, 63\} is special because gcd(2, 5 + 20 + 63) = 2, gcd(5, 2 + 20 + 63) = 5, gcd(20, 2 + 5 + 63) = 10, gcd(63, 2 + 5 + 20) = 9. Also, gcd(2, 5, 20, 63) = 1. Thus, this set satisfies all the criteria.


#include<bits/stdc++.h>
using namespace std;
inline int read(){
	register int x=0;
	register char ch=getchar();
	while(ch<'0'||ch>'9')	ch=getchar();
	while(ch>='0'&&ch<='9')	x=x*10+(ch^48),ch=getchar();
	return x;
}
const int N=3e5+5;
int n,L,x[N],t[N],l[N],r[N],vi[N];
int main(){
	int ans=0;
	n=read(),L=read(),ans=n+1;
	for(int i=1;i<=n;i++)	x[i]=read();
	for(int i=1;i<=n;i++){
		ans+=(t[i]=read())/(2*L);
		t[i]%=2*L;
	}
	for(int i=1;i<=n;i++)	l[i]=(x[i]*2>=t[i]);
	for(int i=1;i<=n;i++)	r[i]=((L*2-x[i]*2)>=t[i]);
	for(int i=1;i<=n;i++){
		if(!t[i])	vi[i]=1,--ans;
		if(!r[i]&&!l[i])	vi[i]=1;
	}
	if(t[n])	ans-=r[n];
	int sum=0,pos=n,top=0;
	for(int i=1;i<n;i++){
		if(vi[i])	continue;
		if(!r[i]){
			pos=i; break;
		}
		l[i]?++top:(top?--top,--ans:top=0);
	}
	sum+=top,top=0;
	for(int i=n-1;i>pos;i--){
		if(!vi[i])	continue;
		r[i]?++top:(top?--top,--ans:top=0);
	}
	printf("%lld\n",2LL*L*(ans-(sum+top)/2));
	return 0;
}

Score : 1600 points

Problem Statement

Yui loves shopping. She lives in Yamaboshi City and there is a train service in the city. The city can be modelled as a very long number line. Yui's house is at coordinate 0.

There are N shopping centres in the city, located at coordinates x_{1}, x_{2}, ..., x_{N} respectively. There are N + 2 train stations, one located at coordinate 0, one located at coordinate L, and one located at each shopping centre.

At time 0, the train departs from position 0 to the positive direction. The train travels at a constant speed of 1 unit per second. At time L, the train will reach the last station, the station at coordinate L. The train immediately moves in the opposite direction at the same speed. At time 2L, the train will reach the station at coordinate 0 and it immediately moves in the opposite direction again. The process repeats indefinitely.

When the train arrives at a station where Yui is located, Yui can board or leave the train immediately. At time 0, Yui is at the station at coordinate 0.

Yui wants to go shopping in all N shopping centres, in any order, and return home after she finishes her shopping. She needs to shop for t_{i} seconds in the shopping centre at coordinate x_{i}. She must finish her shopping in one shopping centre before moving to the next shopping centre. Yui can immediately start shopping when she reaches a station with a shopping centre and she can immediately board the train when she finishes shopping.

Yui wants to spend the minimum amount of time to finish her shopping. Can you help her determine the minimum number of seconds required to complete her shopping?

Constraints

1 \leq N \leq 300000

1 \leq L \leq 10^{9}

0 < x_{1} < x_{2} < ... < x_{N} < L

1 \leq t_{i} \leq 10^{9}

All values in the input are integers.

Partial Score

1000 points will be awarded for passing the testset satisfying 1 \leq N \leq 3000.

Input

Input is given from Standard Input in the following format:

N L
x_{1} x_{2} ... x_{N}
t_{1} t_{2} ... t_{N}

Output

Print the minimum time (in seconds) required for Yui to finish shopping at all N shopping centres and return home.

Sample Input 1

2 10
5 8
10 4

Sample Output 1

40

Here's one possible way for Yui to finish her shopping :

Travel to the station at coordinate 8 with the train. She arrives at coordinate 8 at time 8.

Shop in the shopping centre at coordinate 8. She finishes her shopping at time 12.

The train arrives at coordinate 8 at time 12. She boards the train which is currently moving in the negative direction.

She arrives at coordinate 5 at time 15. She finishes her shopping at time 25.

The train arrives at coordinate 5 at time 25. She boards the train which is currently moving in the positive direction.

She arrives at coordinate L = 10 at time 30. The train starts moving in the negative direction immediately.

She arrives at coordinate 0 at time 40, ending the trip.

Sample Input 2

2 10
5 8
10 5

Sample Output 2

60

Sample Input 3

5 100
10 19 28 47 68
200 200 200 200 200

Sample Output 3

1200

Sample Input 4

8 1000000000
2018 123456 1719128 1929183 9129198 10100101 77777777 120182018
99999999 1000000000 1000000000 11291341 1 200 1 123812831

Sample Output 4

14000000000

Beware of overflow issues.


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

#define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define RFOR(i,a,b) for(int i=(int)(b)-1;i>=(int)(a);i--)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) RFOR(i,0,n)
#define LL long long
#define INF INT_MAX

const double EPS = 1e-14;
const double PI  = acos(-1.0);

int main(){
  int a, b, c, d;
  cin >> a >> b >> c >> d;
  cout << min(a, b) + min(c, d) << endl;
}

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152


#include<iostream>
#include<algorithm>
using namespace std;
int n;
int a[100010];
int main()
{
	ios::sync_with_stdio(false);
	int sum = 0;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
		sum += abs(a[i] - a[i-1]);
	}
	sum += abs(a[n ] - a[0]);
	for (int i = 1; i <= n; i++)
	{
		cout << sum - abs(a[i] - a[i - 1]) - abs(a[i + 1] - a[i]) + abs(a[i + 1] - a[i - 1]) << endl;
	}
	return 0;
}

Score : 300 points

Problem Statement

There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.

You planned a trip along the axis.
In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.

However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.

For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.

Constraints

2 \leq N \leq 10^5

-5000 \leq A_i \leq 5000 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N lines.
In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.

Sample Input 1

3
3 5 -1

Sample Output 1

12
8
10

Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively.
For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows:

For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen.

For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen.

For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen.

Sample Input 2

5
1 1 1 2 0

Sample Output 2

4
4
4
2
4

Sample Input 3

6
-679 -2409 -3258 3095 -3291 -4462

Sample Output 3

21630
21630
19932
8924
21630
19288


#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
const int P=1e9+7;
int n,m,s,a[N],f[N];
long long  fac[N],inv[N];
long long A(int n,int m){
	if(m>n||n<0)	return 0;
	return fac[n]*inv[n-m]%P;
}
long long fsp(long long x,int y){
	long long ans=1;
	while(y){
		if(y&1)	ans=ans*x%P;
		y>>=1,x=x*x%P;
	}
	return ans;
}
int main(){
	scanf("%d%d",&n,&m),s=1<<n,fac[0]=inv[0]=1;
	for(int i=0;i<m;i++)	scanf("%d",&a[i]);
	for(int i=1;i<=s;i++){
		fac[i]=fac[i-1]*i%P;
		inv[i]=fsp(fac[i],P-2);
	}
	f[0]=1;
	for(int i=m-1;~i;i--)
		for(int j=s-1;j;j--)
			for(int k=0;k<n;k++){
				int d=1<<k;
				if(!(j&d))	continue;
				f[j]=(f[j]+f[j^d]*A(s-a[i]-j+d,d-1)%P*d)%P;
			}
	long long ans=fac[s-1];
	for(int i=1;i<s;i++){
		int ty=1;
		for(int j=0;j<n;j++)
			if(i>>j&1)	ty=-ty;
		ans=(ans+ty*fac[s-i-1]*f[i]%P+P)%P;
	}
	printf("%lld\n",ans*s%P);
	return 0;
}

Score : 1100 points

Problem Statement

There are 2^N players, numbered 1, 2, ..., 2^N.
They decided to hold a tournament.

The tournament proceeds as follows:

Choose a permutation of 1, 2, ..., 2^N: p_1, p_2, ..., p_{2^N}.

The players stand in a row in the order of Player p_1, Player p_2, ..., Player p_{2^N}.

Repeat the following until there is only one player remaining in the row:

Play the following matches: the first player in the row versus the second player in the row, the third player versus the fourth player, and so on. The players who lose leave the row. The players who win stand in a row again, preserving the relative order of the players.

The last player who remains in the row is the champion.

It is known that, the result of the match between two players can be written as follows, using M integers A_1, A_2, ..., A_M given as input:

When y = A_i for some i, the winner of the match between Player 1 and Player y (2 \leq y \leq 2^N) will be Player y.

When y \neq A_i for every i, the winner of the match between Player 1 and Player y (2 \leq y \leq 2^N) will be Player 1.

When 2 \leq x < y \leq 2^N, the winner of the match between Player x and Player y will be Player x.

The champion of this tournament depends only on the permutation p_1, p_2, ..., p_{2^N} chosen at the beginning.
Find the number of permutation p_1, p_2, ..., p_{2^N} chosen at the beginning of the tournament that would result in Player 1 becoming the champion, modulo 10^9 + 7.

Constraints

1 \leq N \leq 16

0 \leq M \leq 16

2 \leq A_i \leq 2^N (1 \leq i \leq M)

A_i < A_{i + 1} (1 \leq i < M)

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the answer.

Sample Input 1

2 1
3

Sample Output 1

8

Examples of p that satisfy the condition are: [1, 4, 2, 3] and [3, 2, 1, 4]. Examples of p that do not satisfy the condition are: [1, 2, 3, 4] and [1, 3, 2, 4].

Sample Input 2

4 3
2 4 6

Sample Output 2

0

Sample Input 3

3 0

Sample Output 3

40320

Sample Input 4

3 3
3 4 7

Sample Output 4

2688

Sample Input 5

16 16
5489 5490 5491 5492 5493 5494 5495 5497 18993 18995 18997 18999 19000 19001 19002 19003

Sample Output 5

816646464


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int a,b,n;
	scanf("%d %d %d",&a,&b,&n);
	if(a+b>=n)
	{
		printf("Yes");
	}
	else
	{
		printf("No");
	}
	return 0;
}

Score : 100 points

Problem Statement

An elementary school student Takahashi has come to a variety store.

He has two coins, A-yen and B-yen coins (yen is the currency of Japan), and wants to buy a toy that costs C yen. Can he buy it?

Note that he lives in Takahashi Kingdom, and may have coins that do not exist in Japan.

Constraints

All input values are integers.

1 \leq A, B \leq 500

1 \leq C \leq 1000

Input

Input is given from Standard Input in the following format:

A B C

Output

If Takahashi can buy the toy, print Yes; if he cannot, print No.

Sample Input 1

50 100 120

Sample Output 1

Yes

He has 50 + 100 = 150 yen, so he can buy the 120-yen toy.

Sample Input 2

500 100 1000

Sample Output 2

No

He has 500 + 100 = 600 yen, but he cannot buy the 1000-yen toy.

Sample Input 3

19 123 143

Sample Output 3

No

There are 19-yen and 123-yen coins in Takahashi Kingdom, which are rather hard to use.

Sample Input 4

19 123 142

Sample Output 4

Yes


#include<iostream>
using namespace std;

int main(){
    int a,i = 0;
    cin >> a;
    int b[10001];
    for(i=0;i<a;i++) cin >> b[i];

    int cnt = 0;
    for(i=0;i<a;i++){
        while(b[i]%2==0){
            b[i]/=2;
            cnt++;
        }
    }
    cout << cnt << endl;
    return 0;
}

Score : 400 points

Problem Statement

On a two-dimensional plane, there are N red points and N blue points.
The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).

A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, and the y-coordinate of the red point is also smaller than that of the blue point.

At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.

Constraints

All input values are integers.

1 \leq N \leq 100

0 \leq a_i, b_i, c_i, d_i < 2N

a_1, a_2, ..., a_N, c_1, c_2, ..., c_N are all different.

b_1, b_2, ..., b_N, d_1, d_2, ..., d_N are all different.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N

Output

Print the maximum number of friendly pairs.

Sample Input 1

3
2 0
3 1
1 3
4 2
0 4
5 5

Sample Output 1

2

For example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).

Sample Input 2

3
0 0
1 1
5 2
2 3
3 4
4 5

Sample Output 2

2

For example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).

Sample Input 3

2
2 2
3 3
0 0
1 1

Sample Output 3

0

It is possible that no pair can be formed.

Sample Input 4

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

Sample Output 4

5

Sample Input 5

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

Sample Output 5

4


// finish date: 2018/03/17

#include <bits/stdc++.h>

using namespace std;

#define FOR(i, a, b) for(int (i)=a;(i)<(b);(i)++)
#define rep(i, n)  FOR(i,0,n)
#define ll long long
#define vi vector<int>
#define vvi vector<vector<int>>
#define vvvi vector<vector<vector<int>>>
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vd vector<double>
#define vvd vector<vector<double>>
#define vb vector<bool>
#define vvb vector<vector<bool>>
#define vs vector<string>
#define vc vector<char>
#define vvc vector<vector<char>>
#define bigmod 1000000007
#define INF 1050000000
#define pii pair<int,int>

int main() {
    int N;
    cin >> N;
    vl a(N);
    ll maxVal = -LONG_LONG_MAX;
    int maxIndex;
    rep(i, N) {
        cin >> a[i];
        if (maxVal < a[i]) {
            maxVal = a[i];
            maxIndex = i;
        }
    }
    if (N == 2) {
        cout << max(a[0], a[1]) << endl;
        cout << 1 << endl;
        if (a[0] > a[1]) cout << 2 << endl;
        else cout << 1 << endl;
        return 0;
    }
    if (maxVal <= 0) {
        cout << maxVal << endl;
        cout << N - 1 << endl;
        FOR(i, maxIndex + 1, N) {
            cout << maxIndex + 2 << endl;
        }
        rep(i, maxIndex) {
            cout << 1 << endl;
        }
        return 0;
    }

    ll oddMax = 0;
    ll evenMax = 0;
    rep(i, N) {
        if (i % 2 == 0) oddMax += max(a[i], (ll) 0);
        else evenMax += max(a[i], (ll) 0);
    }
    vi operate;
    int l, r;
    if (oddMax > evenMax) l = 0;
    else {
        operate.emplace_back(0);
        l = 1;
    }
    r = l + 1;

    while (r < N) {
        if (r + 1 >= N) {
            operate.emplace_back(1);
            break;
        }
        if (a[l] < 0) {
            operate.emplace_back(0);
            operate.emplace_back(0);
            l += 2;
            r = l + 1;
        } else if (a[r + 1] < 0) {
            operate.emplace_back(2);
            if (r + 2 >= N) {
                operate.emplace_back(1);
                break;
            }
            r += 2;

        } else {
            operate.emplace_back(1);
            a[r + 1] += a[l];
            l = r + 1;
            r = l + 1;
        }

    }

    cout << max(evenMax, oddMax) << endl;
    cout << operate.size() << endl;
    rep(i, operate.size()) {
        cout << operate[i] + 1 << endl;
    }

    return 0;
}

Score : 700 points

Problem Statement

You have an integer sequence of length N: a_1, a_2, ..., a_N.

You repeatedly perform the following operation until the length of the sequence becomes 1:

First, choose an element of the sequence.

If that element is at either end of the sequence, delete the element.

If that element is not at either end of the sequence, replace the element with the sum of the two elements that are adjacent to it. Then, delete those two elements.

You would like to maximize the final element that remains in the sequence.

Find the maximum possible value of the final element, and the way to achieve it.

Constraints

All input values are integers.

2 \leq N \leq 1000

|a_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

In the first line, print the maximum possible value of the final element in the sequence.

In the second line, print the number of operations that you perform.

In the (2+i)-th line, if the element chosen in the i-th operation is the x-th element from the left in the sequence at that moment, print x.

If there are multiple ways to achieve the maximum value of the final element, any of them may be printed.

Sample Input 1

5
1 4 3 7 5

Sample Output 1

11
3
1
4
2

The sequence would change as follows:

After the first operation: 4, 3, 7, 5

After the second operation: 4, 3, 7

After the third operation: 11(4+7)

Sample Input 2

4
100 100 -1 100

Sample Output 2

200
2
3
1

After the first operation: 100, 200(100+100)

After the second operation: 200

Sample Input 3

6
-1 -2 -3 1 2 3

Sample Output 3

4
3
2
1
2

After the first operation: -4, 1, 2, 3

After the second operation: 1, 2, 3

After the third operation: 4

Sample Input 4

9
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

5000000000
4
2
2
2
2


#include <iostream>
using namespace std;

int main(){
  string a,b,c;
  cin>>a>>b>>c;
  cout<<a[0]<<b[1]<<c[2]<<endl;
  return 0;
}

Score : 100 points

Problem Statement

We have a 3×3 square grid, where each square contains a lowercase English letters.
The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.

Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Constraints

Input consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

c_{11}c_{12}c_{13}
c_{21}c_{22}c_{23}
c_{31}c_{32}c_{33}

Output

Print the string of length 3 that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Sample Input 1

ant
obe
rec

Sample Output 1

abc

The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.

Sample Input 2

edu
cat
ion

Sample Output 2

ean


#include<iostream>
using namespace std;
int main(){
  int N,M;
  cin >> N >> M;
  if(min(N,M) > 2){
    cout << N * M - (2 *(N+M) - 4) << endl;
  }
  else{
    if(min(N,M) == 1){
      if(max(N,M) > 1){
        cout << max(N,M) - 2 << endl;
      }
      else{
        cout << 1 << endl;
      }
    }
    else{
      cout << 0 << endl;
    }
  }
}

Score : 300 points

Problem Statement

There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region.
The front and back sides of these cards can be distinguished, and initially every card faces up.

We will perform the following operation once for each square contains a card:

For each of the following nine squares, flip the card in it if it exists: the target square itself and the eight squares that shares a corner or a side with the target square.

It can be proved that, whether each card faces up or down after all the operations does not depend on the order the operations are performed.
Find the number of cards that face down after all the operations.

Constraints

1 \leq N,M \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of cards that face down after all the operations.

Sample Input 1

2 2

Sample Output 1

0

We will flip every card in any of the four operations. Thus, after all the operations, all cards face up.

Sample Input 2

1 7

Sample Output 2

5

After all the operations, all cards except at both ends face down.

Sample Input 3

314 1592

Sample Output 3

496080


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

int main() {
  int n,k,l = 0;
  cin >> n >> k;

  if (k == 0) {
    cout << n * n << endl;
    return 0;
  }

  for (int b = k + 1; b <= n; b++) {
    l += (b - k) * (n / b) + max(n % b - k + 1, 0);
  }

  cout << l << endl;
}

Score : 400 points

Problem Statement

Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten.
He remembers that the remainder of a divided by b was greater than or equal to K.
Find the number of possible pairs that he may have had.

Constraints

1 \leq N \leq 10^5

0 \leq K \leq N-1

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of possible pairs that he may have had.

Sample Input 1

5 2

Sample Output 1

7

There are seven possible pairs: (2,3),(5,3),(2,4),(3,4),(2,5),(3,5) and (4,5).

Sample Input 2

10 0

Sample Output 2

100

Sample Input 3

31415 9265

Sample Output 3

287927211