// warm heart, wagging tail,and a smile just for you!
//
//                            ▒█████▒▒
//                             ██████████▒
//                             ▒████████████▒
//                            ██████████████████
//                           ████████████████████▒
//                          ▒██████████████████████▒
//                          ▒███████████████████████
//                      ▒████▒▒▒▒▒▒█████████████████▒
//                    ███▒▒▒▒▒▒██████████████████████▒▒▒
//                  ▒██▒▒███████████████████████▒▒▒▒▒██████
//                 ▒█████████████████████████▒▒▒▒▒▒█████████▒
//                 ▒█████████████████████▒▒▒▒▒▒██████████████
//                  ▒████         ████▒▒▒▒▒████         ████▒
//              ▒█████▒    ████    ▒▒▒▒███████    ████    ██████▒
//            ▒██▒▒▒▒▒    ██████    █████████    ██████    ██▒▒▒██▒
//           █████████   ████████   █████████   ████████   ▒▒▒▒█████
//          ▒█████████    ██████    ████████▒    ██████    █████████
//          ▒██████████    ████    █████▒▒▒▒▒▒    ████    ██████████
//           ████████████        ▒▒▒▒▒▒▒████████        ███████████▒
//       ▒██████████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒███████████████████████████████████▒
//     ███▒▒▒▒▒▒▒▒▒▒▒▒█████████████████████████████████████████▒▒████████▒
//   ▒▒▒▒▒▒▒▒▒██████████████                         ███████▒▒▒▒███████████
//   █████████████████████████                     ███████▒▒▒██████████████▒
//   █████████████████████████████             ███████▒▒▒██████████████████▒
//   ██████████████████████████████████████████████████████████████████████
//    ██████████████████████████████████████████████████████████████████▒
//      ▒█████████████████▒▒▒▒▒▒▒██████████████████████████████████▒▒▒
//
#include "bits/stdc++.h"
using namespace std;
#define MOD 1000000007
//#define MOD 998244353
const double EPS = 1e-9;
#define INF (1LL<<60)
#define D double
#define fs first
#define sc second
#define int long long
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define RFOR(i,a,b) for(int i = (b-1);i>=(a);--i)
#define REP(i,n)  FOR(i,0,(n))
#define RREP(i,n) RFOR(i,0,(n))
#define ITR(itr,mp) for(auto itr = (mp).begin(); itr != (mp).end(); ++itr)
#define RITR(itr,mp) for(auto itr = (mp).rbegin(); itr != (mp).rend(); ++itr)
#define range(i,a,b) ((a)<=(i) && (i)<(b))
#define debug(x)  cout << #x << " = " << (x) << endl;
#define SP << " " <<
typedef pair<int,int> P;
typedef vector<int> vec;
typedef vector<vector<int>> mat;

int n,k;
vec w,d;

bool check(int mid){
  int sum = 0;
  REP(i,n){
    sum += max(0LL,(mid-w[i]))/d[i];
    if(mid-w[i]>=0) sum++;
    if(sum >= k) return true;
  }
  return false;
}

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

  cin >> n >> k;

  w.resize(n);
  d.resize(n);

  REP(i,n) cin >> w[i] >> d[i];

  int ng = 0, ok = (1LL<<61);
  while (abs(ng-ok)>1) {
    int mid = (ng+ok)/2;
    (check(mid)?ok:ng) = mid;
  }

  cout << ok << endl;

  return 0;
}

Score : 100 points

Problem Statement

In your garden, there is a long and narrow flowerbed that stretches infinitely to the east. You have decided to plant N kinds of flowers in this empty flowerbed. For convenience, we will call these N kinds of flowers Flower 1, 2, …, N. Also, we will call the position that is p centimeters from the west end of the flowerbed Position p.

You will plant Flower i (1 ≤ i ≤ N) as follows: first, plant one at Position w_i, then plant one every d_i centimeters endlessly toward the east. That is, Flower i will be planted at the positions w_i, w_i + d_i, w_i + 2 d_i, … Note that more than one flower may be planted at the same position.

Find the position at which the K-th flower from the west is planted. If more than one flower is planted at the same position, they are counted individually.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^9

1 ≤ w_i ≤ 10^{18}

1 ≤ d_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
w_1 d_1
:
w_N d_N

Output

When the K-th flower from the west is planted at Position X, print the value of X. (The westmost flower is counted as the 1-st flower.)

Sample Input 1

2 6
20 10
25 15

Sample Output 1

50

Two kinds of flowers are planted at the following positions:

Flower 1: Position 20, 30, 40, 50, 60, …

Flower 2: Position 25, 40, 55, 70, 85, …

The sixth flower from the west is the Flower 1 planted at Position 50. Note that the two flowers planted at Position 40 are counted individually.

Sample Input 2

3 9
10 10
10 10
10 10

Sample Output 2

30

Three flowers are planted at each of the positions 10, 20, 30, … Thus, the ninth flower from the west is planted at Position 30.

Sample Input 3

1 1000000000
1000000000000000000 1000000000

Sample Output 3

1999999999000000000


#include <bits/stdc++.h>

#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)

#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=(int)(a)-1;i>=(int)(b);--i)
#define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__)

#define _all(arg) begin(arg),end(arg)
#define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg))
#define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary)
#define clr(a,b) memset((a),(b),sizeof(a))
#define bit(n) (1LL<<(n))

// #define DEBUG

#ifdef DEBUG
    #define dump(...) fprintf(stderr, __VA_ARGS__)
#else
    #define dump(...)
#endif

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

using namespace std;
using ll=long long;
using vi=vector<int>;
using vll=vector<ll>;

const double EPS = 1e-10;
const double PI = acos(-1.0);
const ll inf =1LL << 62;
const ll mod=1000000007LL;
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};

ll extgcd(ll a,ll b,ll& x,ll& y){x=1,y=0;ll g=a;if(b!=0) g=extgcd(b,a%b,y,x),y-=a/b*x;return g;}
ll ADD(const ll &a, const ll &b,const ll &mod) { return (a+b)%mod;}
ll SUB(const ll &a, const ll &b,const ll &mod) { return (a-b+mod)%mod;}
ll MUL(const ll &a, const ll &b,const ll &mod) { return (1LL*a*b)%mod;}
ll DIV(const ll &a, const ll &b,const ll &mod) {ll x,y; extgcd(b,mod,x,y);return MUL(a,(x+mod)%mod,mod);}

random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dice(1,6);
uniform_real_distribution<double> score(0.0,10.0);

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

    int n, p; cin >> n >> p;
    int q = 100 - p;
    vll w(n), b(n);
    using Elem = tuple<ll, int>;
    vector<Elem> tbl(n);
    ll sum_b = 0;
    rep(i, n) cin >> w[i] >> b[i], tbl[i] = Elem(q * w[i] + p * b[i], i), sum_b += b[i];
    sort(_all(tbl), greater<Elem>());

    ll cur = 0;
    int res = 0;
    for(auto& e : tbl){
        res++;
        cur += get<0>(e);
        if(cur >= p * sum_b){
            cout << res << endl;
            return 0;
        }
    }
    assert(false);

    return 0;
}

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

Score : 100 points

Problem Statement

Ringo Kingdom Congress is voting on a bill.

N members are present, and the i-th member (1 ≤ i ≤ N) has w_i white ballots and b_i blue ballots. Each member i will put all the w_i white ballots into the box if he/she is in favor of the bill, and put all the b_i blue ballots into the box if he/she is not in favor of the bill. No other action is allowed. For example, a member must not forfeit voting, or put only a part of his/her white ballots or a part of his/her blue ballots into the box.

After all the members vote, if at least P percent of the ballots in the box is white, the bill is passed; if less than P percent of the ballots is white, the bill is rejected.

In order for the bill to pass, at least how many members must be in favor of it?

Constraints

1 ≤ N ≤ 10^5

1 ≤ P ≤ 100

1 ≤ w_i ≤ 10^9

1 ≤ b_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N P
w_1 b_1
w_2 b_2
:
w_N b_N

Output

Print the minimum number of members in favor of the bill required for passage.

Sample Input 1

4 75
1 1
1 1
1 1
1 1

Sample Output 1

3

This is a "normal" vote, where each of the four members has one white ballot and one blue ballot. For the bill to pass, at least 75 percent of the four, that is, at least three must be in favor of it.

Sample Input 2

4 75
1 1
1 1
1 1
100 1

Sample Output 2

1

The "yes" vote of the member with 100 white ballots alone is enough to pass the bill.

Sample Input 3

5 60
6 3
5 9
3 4
7 8
4 7

Sample Output 3

3

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<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<bitset>
using namespace std;
#define REP(i,m,n) for(int i=(int)m ; i < (int) n ; ++i )
#define rep(i,n) REP(i,0,n)
typedef long long ll;
typedef pair<int,int> pint;
typedef pair<ll,int> pli;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;
int dx[4]={1,0,-1,0} , dy[4]={0,1,0,-1} ;
vector<int> v[101010];
int depth[101010],sz[101010];

int szdfs(int x,int d=0,int p=-1){
    int ret=1;
    depth[x]=d;
    for(auto to:v[x]){
        if(to==p)continue;
        ret+=szdfs(to,d+1,x);
    }
    return sz[x]=ret;
}
int main(){
   int n;
   cin>>n;
   int a[n-1],b[n-1];
   rep(i,n-1){
       cin>>a[i]>>b[i];
       --a[i];--b[i];
       v[a[i]].push_back(b[i]);
       v[b[i]].push_back(a[i]);
   }
   szdfs(0);
   rep(i,n-1)if(depth[a[i]]>depth[b[i]])swap(a[i],b[i]);
   ll d[n];
   rep(i,n)cin>>d[i];
   int yabai=-1;
   ll ans[n-1];
   rep(i,n-1){
       if(2*sz[b[i]]==n)yabai=i;
       else ans[i]=(d[b[i]]-d[a[i]])/(n-2*sz[b[i]]);
   }
   if(yabai>=0){
       rep(i,n-1){
           if(i==yabai)continue;
           d[0]-=ans[i]*sz[b[i]];
       }
       ans[yabai]=2*d[0]/n;
   }
   rep(i,n-1)cout<<ans[i]<<endl;
   return 0;
}

Score : 800 points

Problem Statement

Snuke found a record of a tree with N vertices in ancient ruins.
The findings are as follows:

The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.

Edge i connected Vertex a_i and b_i.

The length of each edge was an integer between 1 and 10^{18} (inclusive).

The sum of the shortest distances from Vertex i to Vertex 1,...,N was s_i.

From the information above, restore the length of each edge.
The input guarantees that it is possible to determine the lengths of the edges consistently with the record.
Furthermore, it can be proved that the length of each edge is uniquely determined in such a case.

Constraints

2 \leq N \leq 10^{5}

1 \leq a_i,b_i \leq N

1 \leq s_i \leq 10^{18}

The given graph is a tree.

All input values are integers.

It is possible to consistently restore the lengths of the edges.

In the restored graph, the length of each edge is an integer between 1 and 10^{18} (inclusive).

Partial Scores

In the test set worth 300 points, a_i = i, b_i = i+1.

In the test set worth 200 points, N \geq 3, a_i = 1, b_i = i+1.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
s_1 s_2 ... s_{N}

Output

Print N-1 lines. The i-th line must contain the length of Edge i.

Sample Input 1

4
1 2
2 3
3 4
8 6 6 8

Sample Output 1

1
2
1

The given record corresponds to the tree shown below:

Sample Input 2

5
1 2
1 3
1 4
1 5
10 13 16 19 22

Sample Output 2

1
2
3
4

The given record corresponds to the tree shown below:

Sample Input 3

15
9 10
9 15
15 4
4 13
13 2
13 11
2 14
13 6
11 1
1 12
12 3
12 7
2 5
14 8
1154 890 2240 883 2047 2076 1590 1104 1726 1791 1091 1226 841 1000 901

Sample Output 3

5
75
2
6
7
50
10
95
9
8
78
28
89
8


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

int main(){
    int n;
    cin >> n;
    map<int,int> m;
    int d[n];
    rep(i,n){
        cin >> d[i];
        m[d[i]]++;
    }
    if(n >= 13) {
        bool can = true;
        for(auto x : m) {
            if(x.second > 2) can = false;
            if(x.first == 12 && x.second >= 2) can = false;
        }
        cout << (can? "1" : "0") << endl;
        return 0;
    }
    int ans = 0;
    rep(i,1<<n){
        int a[n+1] = {};
        a[n] = 0;
        rep(j,n){
            if(d[j] == 0) a[j] = 0;
            else if(i & (1<<j)) a[j] = d[j];
            else a[j] = 24-d[j];
        }
        int c = 25;
        rep(j,n+1){
            for(int k = j+1; k <= n; k++) c = min(c,abs(a[j]-a[k]));
        }
        ans = max(ans,c);
    }
    cout << ans << endl;
    return 0;
}

Score : 500 points

Problem Statement

In CODE FESTIVAL XXXX, there are N+1 participants from all over the world, including Takahashi.

Takahashi checked and found that the time gap (defined below) between the local times in his city and the i-th person's city was D_i hours.
The time gap between two cities is defined as follows. For two cities A and B, if the local time in city B is d o'clock at the moment when the local time in city A is 0 o'clock, then the time gap between these two cities is defined to be min(d,24-d) hours.
Here, we are using 24-hour notation.
That is, the local time in the i-th person's city is either d o'clock or 24-d o'clock at the moment when the local time in Takahashi's city is 0 o'clock, for example.

Then, for each pair of two people chosen from the N+1 people, he wrote out the time gap between their cities. Let the smallest time gap among them be s hours.

Find the maximum possible value of s.

Constraints

1 \leq N \leq 50

0 \leq D_i \leq 12

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the maximum possible value of s.

Sample Input 1

3
7 12 8

Sample Output 1

4

For example, consider the situation where it is 7, 12 and 16 o'clock in each person's city at the moment when it is 0 o'clock in Takahashi's city. In this case, the time gap between the second and third persons' cities is 4 hours.

Sample Input 2

2
11 11

Sample Output 2

2

Sample Input 3

1
0

Sample Output 3

0

Note that Takahashi himself is also a participant.


#include <bits/stdc++.h>
using namespace std;
int main(){
  string n;
  cin>>n;
if((n[0]==n[1]&&n[1]==n[2])||(n[1]==n[2]&&n[2]==n[3])) cout<<"Yes"<<endl;
 else cout<<"No"<<endl;
return 0;
}

Score : 100 points

Problem Statement

We call a 4-digit integer with three or more consecutive same digits, such as 1118, good.

You are given a 4-digit integer N. Answer the question: Is N good?

Constraints

1000 ≤ N ≤ 9999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is good, print Yes; otherwise, print No.

Sample Input 1

1118

Sample Output 1

Yes

N is good, since it contains three consecutive 1.

Sample Input 2

7777

Sample Output 2

Yes

An integer is also good when all the digits are the same.

Sample Input 3

1234

Sample Output 3

No


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

int main() {
  int N,a,b,c;
  cin >> N;
  a=N % 1110;
  b=N & 1000;
  c=b % 111;
  if (a < 10) {
    cout << "Yes" << endl;
  }
  else if (c = 0) {
    cout << "Yes" << endl;
  }
  else {
    cout << "No" << endl;
  }
}


#include<cstdio>

bool isGoodInteger(int thousands, int hundreds, int tens, int ones){
	if(thousands == hundreds && hundreds == tens) return true;
	if(hundreds  == tens     && tens     == ones) return true;
	return false;
}

int main(void){
	int N, thousands, hundreds, tens, ones;
	scanf("%d", &N);

	//Nの各桁を求める
	thousands = N / 1000;
	N = N % 1000;
	hundreds = N / 100;
	N = N % 100;
	tens = N / 10;
	N = N % 10;
	ones = N;
	if(isGoodInteger(thousands, hundreds, tens, ones))
		printf("Yes\n");
	else printf("No\n");
	return 0;
}


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

int main(){
	int n;
	cin >> n;
	long long int a[100];
	a[0]=2;
	a[1]=1;
	for(int i=2;i<=n;i++){
		a[i]=a[i-2]+a[i-1];
	}
	cout << a[n] << endl;
	return 0;
}

Score : 200 points

Problem Statement

It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers.

You are given an integer N. Find the N-th Lucas number.

Here, the i-th Lucas number L_i is defined as follows:

L_0=2

L_1=1

L_i=L_{i-1}+L_{i-2} (i≥2)

Constraints

1≤N≤86

It is guaranteed that the answer is less than 10^{18}.

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the N-th Lucas number.

Sample Input 1

5

Sample Output 1

11

L_0=2

L_1=1

L_2=L_0+L_1=3

L_3=L_1+L_2=4

L_4=L_2+L_3=7

L_5=L_3+L_4=11

Thus, the 5-th Lucas number is 11.

Sample Input 2

86

Sample Output 2

939587134549734843


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <bitset>
typedef long long ll;
#define rep(i,n) for(int i = 0;i<n;++i)
#define repnc(bit,k,n) for (int bit = (1<<k)-1;bit < (1<<n); bit = next_combination(bit))
#define repi(itr,vec) for(auto itr = vec.begin();itr!=vec.end();++itr)
using namespace std;

/* next combination */
int next_combination(int sub) {
  int x = sub & -sub, y = sub + x;
  return (((sub & ~y) / x) >> 1) | y;
}

int int_substr(string abcd, int n){
  return abcd[n]-'0';
}

int main(){
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
  string abcd;
  cin >> abcd;
  string ans;
  ans = abcd[0];
  rep(bit, 1<<3){
    int calc = int_substr(abcd,0);
    char opt[3];
    rep(i, 3){
      if(bit&1<<i){
        opt[i] = '+';
        calc+=int_substr(abcd,i+1);
      }else{
        opt[i] = '-';
        calc-=int_substr(abcd,i+1);
      }
    }
    if(calc == 7){
      rep(i, 3){
        ans+=opt[i];ans+=abcd[i+1];
      }
      break;
    }
  }
  cout << ans << "=7\n";
        return 0;
}

Score : 300 points

Problem Statement

Sitting in a station waiting room, Joisino is gazing at her train ticket.

The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).

In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with + or - so that the formula holds.

The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted.

Constraints

0≤A,B,C,D≤9

All input values are integers.

It is guaranteed that there is a solution.

Input

Input is given from Standard Input in the following format:

ABCD

Output

Print the formula you made, including the part =7.

Use the signs + and -.

Do not print a space between a digit and a sign.

Sample Input 1

1222

Sample Output 1

1+2+2+2=7

This is the only valid solution.

Sample Input 2

0290

Sample Output 2

0-2+9+0=7

0 - 2 + 9 - 0 = 7 is also a valid solution.

Sample Input 3

3242

Sample Output 3

3+2+4-2=7


#include <bits/stdc++.h>

using namespace std;

void init(char *c){
    for(int i = 0; i < 3 ; i++){
        c[i] = '+';
    }
}

int main(){

    string s;cin >> s;
    char c[3];
    int ans;

    for(int i = 0; i < (1 << 3) ; i++){
        init(c);
        ans = s[0]-'0';
        for(int j = 0; j < 3 ; j++){
            if(i & (1 << j)){
                c[j] = '-';
                ans -= s[j+1] - '0';
            }else{
                ans += s[j+1] - '0';
            }
        }
        if(ans == 7){
            break;
        }
    }
    for(int i = 0; i < 3 ; i++){
        cout << s[i];
        cout << c[i];
    }
    cout << s[3];
    cout << "=7" << endl;
    //cout << ans << endl;

    return 0;
}


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const long double EPS = 1e-9;
const ll mod = 1e9 + 7;
const ll INF = 1e9;

#define rep(i, n) for(ll i = 0; i < n ; i++ )
#define For(i, a, b) for(ll i = (a); i < (b) ; i++ )
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()

const ll MAX_N = 100000;

int main(void){
    string S;
    ll a[4];

    cin >> S;
    rep(i, 4) a[i] = ll(S[i]) - ll('0');

    rep(i, 8){
        ll tmp = i;
        ll answer = a[0];
        rep(j, 3){
            if (tmp % 2 == 0) answer += a[j + 1];
            else answer -= a[j + 1];
            tmp /= 2;
        }

        if (answer == 7){
            tmp = i;
            cout << a[0];
            rep(j, 3){
                if (tmp % 2 == 0) cout << "+" << a[j + 1];
                else cout << "-" << a[j + 1];
                tmp /= 2;
            }
            cout << "=" << 7 << endl;
            return 0;
        }
    }

    return 0;
}


#include <map>
#include <set>
#include <unordered_set>
#include <list>
#include <cmath>
#include <stack>
#include <queue>
#include <bitset>
#include <cstdio>
#include <climits>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <algorithm>
#include <array>
#include <assert.h>
#include <functional>
#define _USE_MATH_DEFINES
#include <math.h>
#include <complex>
#include <atomic>
#include <thread>

using namespace std;
typedef long long ll;
#define ln '\n'
#define rep(i,n) for(int i=0;i<(n);++i)
#define drep(i,n) int i = 0;for(;i<(n);++i)
#define FOR(i,s,e) for(int i=s;i<=(e);++i)
#define DFOR(i,s,e) int i = s;for(;i<=(e);++i)
#define FORR(i,s,e) for(int i=s;i>=(e);--i)
#define DFORR(i,s,e) int i = s;for(;i>=(e);--i)
#define fore(a, x) for(auto& a : x)
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define ft first
#define sd second
#define pb push_back
#define eb emplace_back
#define all(a) a.begin(),a.end()
#define Fill(a,b) memset(a,b,sizeof(a))
template<typename T1, typename T2> bool Max(T1& a, T2 b) { return a<b ? a = b, 1 : 0; }
template<typename T1, typename T2> bool Min(T1& a, T2 b) { return a>b ? a = b, 1 : 0; }

const int N = 200001, inf = 10000;

void solve() {
  char a;
  char bcd[3];
  cin >> a;
  rep(i, 3)cin >> bcd[i];
  rep(sub, 8) {
    string str;
    str += a;
    int v = a - '0';

    rep(i, 3) {
      int sign = 1;
      if ((sub >> i) & 1) {
        str += '+';
        sign = 1;
      }
      else {
        str += '-';
        sign = -1;
      }
      str += bcd[i];
      v += sign * (bcd[i] - '0');
    }
    if (v == 7) {
      str += "=7";
      cout << str << ln;
      return;
    }
  }

}

void init() {

}

int main(void) {
  ios::sync_with_stdio(false); cin.tie(0); cout.setf(ios::fixed); cout.precision(20);
  //freopen("C:\\Users\\LENOVO\\Documents\\Visual Studio 2015\\Projects\\Test\\Input\\in.in", "r", stdin);

  init();
  int TC = 1;
#if 0
  cin >> TC; cin.get();
#endif
  FOR(TI, 1, TC) {
    //cout << "Case #" << TI << ": ";
    solve();
  }

  return 0;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <list>
#include <numeric>
#include <utility>
#include <ctime>
#define INF 100000000
#define LINF 9000000000000000000
#define mod 1000000007

#define rep(i,n) for(int i=0;i<int(n);i++)
#define REP(i,a,b) for(int i=(a);i<int(b);i++)
#define all(x) (x).begin(),x.end()
#define pb push_back
#define mp make_pair
#define MOD(x) (x%(mod))

using namespace std;

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

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

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

int data[4];

void string_to_int(string s){
  rep(i,4){
    char c=s[i];
    //cout<<c-'0'<<endl;
    data[i]=(c-'0');
  }
}

void solve(){
  int sum=0;
  rep(i,2){
    rep(j,2){
      rep(k,2){
	sum=data[0];
	string ans=to_string(data[0]);
	if(i==0){
	  sum+=data[1];
	  ans=ans+'+'+to_string(data[1]);
	}else{
	  sum-=data[1];
	  ans=ans+'-'+to_string(data[1]);
	}

	if(j==0){
	  sum+=data[2];
	  ans=ans+'+'+to_string(data[2]);
	}else{
	  sum-=data[2];
	  ans=ans+'-'+to_string(data[2]);
	}

	if(k==0){
	  sum+=data[3];
	  ans=ans+'+'+to_string(data[3]);
	}else{
	  sum-=data[1];
	  ans=ans+'-'+to_string(data[3]);
	}

	if(sum==7){
	  ans=ans+"=7";
	  cout<<ans<<endl;
	  return ;
	}
      }
    }
  }
}

int main(){
  string s;
  cin>>s;
  string_to_int(s);
  solve();
  return 0;
}


#include <iostream>
#include <sstream>
#include <bitset>
using namespace std;

int main(){
  string a, b;
  cin >> a >> b;
  int x = a[0] - b[0];

  if (x > 0)
    cout
        << ">" << endl;
  else if(x==0)
    cout << "=" << endl;
  else
    cout << "<" << endl;
  //cout << x;
}

Score : 100 points

Problem Statement

In programming, hexadecimal notation is often used.

In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters A, B, C, D, E and F are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.

In this problem, you are given two letters X and Y. Each X and Y is A, B, C, D, E or F.

When X and Y are seen as hexadecimal numbers, which is larger?

Constraints

Each X and Y is A, B, C, D, E or F.

Input

Input is given from Standard Input in the following format:

X Y

Output

If X is smaller, print <; if Y is smaller, print >; if they are equal, print =.

Sample Input 1

A B

Sample Output 1

<

10 < 11.

Sample Input 2

E C

Sample Output 2

>

14 > 12.

Sample Input 3

F F

Sample Output 3

=

15 = 15.


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

int main() {
    int N, Z, W;
    cin >> N >> Z >> W;
    vector<int> a(N + 1);
    for(int i = 0; i < N; ++i) {
        cin >> a[i + 1];
    }

    vector<vector<int>> dp(N + 1, vector<int>(2, -1));//dp[i][j]:=topがai
    // 直前の相手の手: top, turn: 今の手番
    function<int(int, int)> rec = [&] (int top, int turn) {
        int& res = dp[top][turn];
        if(dp[top][turn] != -1) {
            return dp[top][turn];
        }

        if(top == 0) {
            res = abs(W - a.back()); // 最後まで引く
        }
      /*else {
            res = abs(a[top] - a.back()); // 最後まで引く
        }*/
        //topはどこまでひかれたか
        if(turn == 0) { // 先手途中まで引く
            for(int nex = top + 1; nex < N; ++nex) {
                res = max(res, rec(nex, turn^1));
            }
        } else {
            for(int nex = top + 1; nex < N; ++nex) {
                res = min(res, rec(nex, turn^1));
            }
        }
        return res;
    };

    cout << rec(0, 0) << endl;
}

Score : 500 points

Problem Statement

We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i.

Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they will alternately perform the following action:

Draw some number of cards from the top of the deck. Then, discard the card in his hand and keep the last drawn card instead. Here, at least one card must be drawn.

The game ends when there is no more card in the deck. The score of the game is the absolute difference of the integers written on the cards in the two players' hand.

X will play the game so that the score will be maximized, and Y will play the game so that the score will be minimized. What will be the score of the game?

Constraints

All input values are integers.

1 \leq N \leq 2000

1 \leq Z, W, a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N Z W
a_1 a_2 ... a_N

Output

Print the score.

Sample Input 1

3 100 100
10 1000 100

Sample Output 1

900

If X draws two cards first, Y will draw the last card, and the score will be |1000 - 100| = 900.

Sample Input 2

3 100 1000
10 100 100

Sample Output 2

900

If X draws all the cards first, the score will be |1000 - 100| = 900.

Sample Input 3

5 1 1
1 1 1 1 1

Sample Output 3

0

Sample Input 4

1 1 1
1000000000

Sample Output 4

999999999


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
#define MOD @
#define ADD(X,Y) ((X) = ((X) + (Y)%MOD) % MOD)
typedef long long i64; typedef vector<int> ivec; typedef vector<string> svec;

int N;
i64 Z, W;
i64 A[2020];

i64 dpx[2020][2020], dpy[2020][2020];

const i64 HOGE = 12345679803412LL;

i64 solveY(int, int);

i64 solveX(int sp, int having)
{
	if (sp == N) {
		return abs(A[sp - 1] - A[having]);
	}
	if (dpx[sp][having] != HOGE) return dpx[sp][having];

	i64 ret = -HOGE;
	for (int i = sp; i < N; ++i) {
		ret = max(ret, solveY(i + 1, sp - 1));
	}
	return dpx[sp][having] = ret;
}
i64 solveY(int sp, int having)
{
	if (sp == N) {
		return abs(A[sp - 1] - A[having]);
	}
	if (dpx[sp][having] != HOGE) return dpx[sp][having];

	i64 ret = HOGE;
	for (int i = sp; i < N; ++i) {
		ret = min(ret, solveX(i + 1, sp - 1));
	}
	return dpx[sp][having] = ret;
}

int main()
{
	scanf("%d%lld%lld", &N, &Z, &W);
	for (int i = 2; i < N + 2; ++i) scanf("%lld", A + i);
	A[0] = Z;
	A[1] = W;

	N += 2;

	for (int i = 0; i <= N; ++i) {
		for (int j = 0; j <= N; ++j) {
			dpx[i][j] = dpy[i][j] = HOGE;
		}
	}
	printf("%lld\n", solveX(2, 0));

	return 0;
}


#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstring>
#include <map>
#include <queue>
#include <cmath>
#include <complex> // complex<double> a(1.2 , 2.3);// real(): 1.2, imag()2.3
using namespace std;

#define MOD 1000000007
#define ll long long
#define ld long double
#define FOR(i,a,b) for(ll i=(ll)a;i<(ll)b;i++)
#define rep(i,n) FOR(i,0,n)
#define pb push_back
#define mp make_pair
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define rmsame(a) sort(all(a)),a.erase(unique(all(a)), a.end())
#define rmvector(a,b) rep(i,a.size())rep(j,b.size())if(a[i]==b[j]){a.erase(a.begin()+i);i--;break;}
template<typename X> bool exist(vector<X> vec, X item){return find(all(vec), item)!=vec.end();}
ll price[101];
ll N;
void reset(){
  for(ll i = 1;i<= N ;i++)
    price[i]=0;
}

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

  cin >> N;
  vector<ll> a;
  a.pb(0);
  rep(i,N){
    ll inp; cin >> inp;
    a.pb(inp);
  }

  while(true){
    reset();
    ll loss = 0,lossindex;
    for(ll i =1;i<= N ;i++){
      for(ll j = 1; j*i<= N ;j++){
	price[i]+=a[i*j];
      }
      if(price[i]<0){loss = price[i],lossindex = i;}
    }

    if(loss>=0)break;

    for(ll i = 1;i*lossindex <= N;i++)
      a[i*lossindex]=0;

  }

  cout << price[1] << endl;

  //cout << fixed << setprecision(16) << ans << endl;
  return 0;
}

Score : 700 points

Problem Statement

We have N gemstones labeled 1 through N.

You can perform the following operation any number of times (possibly zero).

Select a positive integer x, and smash all the gems labeled with multiples of x.

Then, for each i, if the gem labeled i remains without getting smashed, you will receive a_i yen (the currency of Japan).
However, a_i may be negative, in which case you will be charged money.

By optimally performing the operation, how much yen can you earn?

Constraints

All input values are integers.

1 \leq N \leq 100

|a_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum amount of money that can be earned.

Sample Input 1

6
1 2 -6 4 5 3

Sample Output 1

12

It is optimal to smash Gem 3 and 6.

Sample Input 2

6
100 -100 -100 -100 100 -100

Sample Output 2

200

Sample Input 3

5
-1 -2 -3 -4 -5

Sample Output 3

0

It is optimal to smash all the gems.

Sample Input 4

2
-1000 100000

Sample Output 4

99000


#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <map>
#include <set>
#include <cmath>
using namespace std;

void solve(){
  string s, t; cin >> s >> t;
  reverse(t.begin(), t.end());
  if(s == t) cout << "YES\n";
  else cout << "NO\n";
  return;
}

int main(){
  solve();
  return 0;
}

Score : 100 points

Problem Statement

You are given a grid with 2 rows and 3 columns of squares.
The color of the square at the i-th row and j-th column is represented by the character C_{ij}.

Write a program that prints YES if this grid remains the same when rotated 180 degrees, and prints NO otherwise.

Constraints

C_{i,j}(1 \leq i \leq 2, 1 \leq j \leq 3) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

C_{11}C_{12}C_{13}
C_{21}C_{22}C_{23}

Output

Print YES if this grid remains the same when rotated 180 degrees; print NO otherwise.

Sample Input 1

pot
top

Sample Output 1

YES

This grid remains the same when rotated 180 degrees.

Sample Input 2

tab
bet

Sample Output 2

NO

This grid does not remain the same when rotated 180 degrees.

Sample Input 3

eye
eel

Sample Output 3

NO


#include <iostream>
#include <algorithm>
using namespace std;

int main(){
	long long int s = 0, n;
	cin >> n;
	long long int a[n], b[n], c[n], d[n], e[n];
	bool flag = true;
	for(int j = 0; j < n; j++){
		cin >> a[j];
	}
	for(int j = 0; j < n; j++){
		cin >> b[j];
	}
	for(int j = 0; j < n; j++){
		cin >> c[j];
	}
	for(int j = 0; j < n; j++){
		d[j] = 0;
		e[j] = 0;
	}
	sort(a, a + n);
	sort(b, b + n);
	sort(c, c + n);
	int p = 0;
	for(int i = 0; i < n; i++){
		flag = true;
		if(i > 0){
			d[i] = d[i - 1];
		}
		for(int j = p; j < n; j++){
			if(b[i] > a[j]){
				d[i] += 1;
			}else{
				p = j;
				flag = false;
				break;
			}
		}
		if(flag) p = n;
	}
	p = 0;
	for(int i = 0; i < n; i++){
		flag = true;
		if(i > 0){
			e[i] = e[i - 1];
		}
		for(int j = p; j < n; j++){
			if(c[i] > b[j]){
				e[i] += d[j];
			}else{
				p = j;
				flag = false;
				break;
			}
		}
		if(flag) p = n;
		s += e[i];
	}
	cout << s << endl;
	return 0;
}

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9(1\leq i\leq N)

1 \leq B_i \leq 10^9(1\leq i\leq N)

1 \leq C_i \leq 10^9(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_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87


#include <bits/stdc++.h>

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

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

const llong inf = llong(1e18)+7;
const llong mod = 1e9+7;

int main(){
	int N;
	vector<llong> A,B,C;

	cin >> N;
	A.resize(N);
	B.resize(N);
	C.resize(N);
	A.push_back(-inf);
	for(int i = 0; i < N; i++)
		cin >> A[i];
	for(int i = 0; i < N; i++)
		cin >> B[i];
	for(int i = 0; i < N; i++)
		cin >> C[i];

	sort(BE(A));
	sort(BE(B));
	sort(BE(C));

	// cerr << endl;
	// for(auto x : A)
	// 	cerr << x << " ";
	// cerr << endl;
	// for(auto x : B)
	// 	cerr << x << " ";
	// cerr << endl;
	// for(auto x : C)
	// 	cerr << x << " ";
	// cerr << endl;

	llong ans = 0;
	for(int i = 0; i < N; i++){
		llong tg = B[i];
		auto Ait = lower_bound(BE(A), tg);
		auto Cit = upper_bound(BE(C), tg);
		Ait--;

		// cerr << tg << endl;
		// cerr << *Ait << " " << Ait - A.begin() << endl;
		// cerr << *Cit << " " << C.end() - Cit << endl << endl;

		ans += (Ait - A.begin())*(C.end() - Cit);
	}

	cout << ans << endl;

	return 0;
}


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

int main() {
	long long K, N;
	cin >> K >> N;
	if (K % 2 == 0) {
		cout << K / 2;
		for (int i = 1; i < N; i++) {
			cout << " " << K;
		}
		cout << endl;
		return 0;
	}
	stack<long long> ANS;
	long long Size = N;
	for (int i = 0; i < N; i++) ANS.push((K + 1) / 2);
	for (int i = 0; i < N / 2; i++) {
		if (ANS.top() == 1) ANS.pop(), Size--;
		else {
			ANS.top()--;
			for (int j = Size; j < N; j++) ANS.push(K);
			Size = N;
		}
	}
	vector<long long> ANS2;
	while (!ANS.empty()) ANS2.push_back(ANS.top()), ANS.pop();
	reverse(ANS2.begin(), ANS2.end());
	for (int i = 0; i < ANS2.size(); i++) {
		cout << ANS2[i];
		if (i == ANS2.size() - 1) cout << endl;
		else cout << " ";
	}
}

Score : 800 points

Problem Statement

In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.

Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.

Constraints

1 \leq N,K \leq 3 × 10^5

N and K are integers.

Input

Input is given from Standard Input in the following format:

K N

Output

Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.

Sample Input 1

3 2

Sample Output 1

2 1

There are 12 sequences listed in FEIS: (1),(1,1),(1,2),(1,3),(2),(2,1),(2,2),(2,3),(3),(3,1),(3,2),(3,3).
The (12/2 = 6)-th lexicographically smallest one among them is (2,1).

Sample Input 2

2 4

Sample Output 2

1 2 2 2

Sample Input 3

5 14

Sample Output 3

3 3 3 3 3 3 3 3 3 3 3 3 2 2


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

int main() {
  int R , G;
  cin >> R >> G;
  cout << 2 * G - R << endl;
}

Score : 100 points

Problem Statement

Takahashi is a user of a site that hosts programming contests.

When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows:

Let the current rating of the user be a.

Suppose that the performance of the user in the contest is b.

Then, the new rating of the user will be the avarage of a and b.

For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000.

Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest.

Find the performance required to achieve it.

Constraints

0 \leq R, G \leq 4500

All input values are integers.

Input

Input is given from Standard Input in the following format:

R
G

Output

Print the performance required to achieve the objective.

Sample Input 1

2002
2017

Sample Output 1

2032

Takahashi's current rating is 2002.

If his performance in the contest is 2032, his rating will be the average of 2002 and 2032, which is equal to the desired rating, 2017.

Sample Input 2

4500
0

Sample Output 2

-4500

Although the current and desired ratings are between 0 and 4500, the performance of a user can be below 0.


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

int main() {
  int R,G;
  cin >> R >> G;
  cout << (R+G)/2.0 << endl;
  }


#include <iostream>
#include <algorithm>
#include<cstdio>
#include<string>

using namespace std;
int main() {
	double r, j, ans;
	cin >> r >> j;
	ans = j * 2 - r;
	cout << ans << endl;
	return 0;
}


#include<bits/stdc++.h>

using namespace std;

#define LCM(a,b)                (a / __gcd(a,b) ) *b
#define GCD(a,b)                __gcd(a,b)
#define dist(x1,y1,x2,y2)       sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))
#define distl(x1,y1,x2,y2)      sqrtl((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))
#define fRead(x)                freopen(x,"r",stdin)
#define fWrite(x)               freopen (x,"w",stdout)
#define LL                      long long
#define ULL                     unsigned long long
#define pb                      push_back
#define tcase                   cout<<"Case "<<C++<<": ";
#define all(a)                  a.begin(),a.end()
#define Unique(a)               sort(all(a)),a.erase(unique(all(a)),a.end
#define ABS(x)                  ((x)<0?-(x):(x))
#define min3(a,b,c)             min(a,min(b,c))
#define min4(a,b,c,d)           min(a,min(b,min(c,d)))
#define max3(a,b,c)             max(a,max(b,c))
#define max4(a,b,c,d)           max(a,max(b,max(c,d)))
#define PI                      acos(-1.0)
#define ff                      first
#define ss                      second
#define SP(x,y)                 fixed<<setprecision((y))<<(x)
#define FastRead                ios_base::sync_with_stdio(0);cin.tie(NULL);
#define FOR(x, l, r)            for (int x = l; x<=r; ++x)
#define REP(x,r)                for (int x = 0; x <r; ++x)
#define NN                      cout<<"\n";
#define NNN                     cout<<"\n------------------------------\n";
#define SORT(v) sort(v.begin(),v.end())
#define REV(v) reverse(v.begin(),v.end())
//***********************************************************************//
//                      SHAHED AHMED, CSE'15, IUT                        //
//***********************************************************************//

LL lim[200020];
LL fix[200020];
LL val[200020];

int main()
{
    LL n;

    cin>>n;

    vector<LL> t(n);
    vector<LL> v(n);

    for(LL i=0;i<n;i++) cin>>t[i];
    for(LL i=0;i<n;i++) cin>>v[i];

    LL pos = 0;

    for(LL i=0;i<t.size();i++)
    {
        lim[pos] = min(lim[pos],v[i]);
        while(t[i]--)
        {
            lim[++pos]= v[i];
        }

    }

    fix[0]=1;
    fix[pos]=1;

    LL increase = 111;

    while(increase--)
    {
        for(LL i=1;i<=pos;i++)
        {
            if(val[i]==lim[i]) fix[i]=1;
            if(val[i]==val[i-1]+1 && fix[i-1]==1) fix[i]=1;
        }

        for(LL i=pos;i>=1;i--)
        {
            if(val[i]==val[i+1]+1 && fix[i+1]==1) fix[i]=1;
        }

        for(LL i=1;i<=pos;i++)
        {
            if(fix[i]!=1)
            {
                val[i]++;
            }
        }
    }

    double tot=0;
    for(LL i=1;i<=pos;i++)
    {
        //cout<<val[i]<<" ";
        tot+=val[i];
    }

    for(LL i=1;i<=pos;i++)
    {
        if(val[i]==val[i-1] && (val[i]<max(lim[i],lim[i-1])))
        {
            tot+=0.25;
        }

    }
//
//    cout<<"\n";
//    for(LL i=1;i<=pos;i++)
//    {
//        cout<<val[i]<<" ";
//    }
//    cout<<"\n";

    cout<<SP(tot,18)<<"\n";

}

Score : 400 points

Problem Statement

In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.

In the plan developed by the president Takahashi, the trains will run as follows:

A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.

In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.

According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.

Find the maximum possible distance that a train can cover in the run.

Constraints

1 \leq N \leq 100

1 \leq t_i \leq 200

1 \leq v_i \leq 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N

Output

Print the maximum possible that a train can cover in the run.

Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.

Sample Input 1

1
100
30

Sample Output 1

2100.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 30 seconds, it accelerates at a rate of 1m/s^2, covering 450 meters.

In the subsequent 40 seconds, it maintains the velocity of 30m/s, covering 1200 meters.

In the last 30 seconds, it decelerates at the acceleration of -1m/s^2, covering 450 meters.

The total distance covered is 450 + 1200 + 450 = 2100 meters.

Sample Input 2

2
60 50
34 38

Sample Output 2

2632.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 34 seconds, it accelerates at a rate of 1m/s^2, covering 578 meters.

In the subsequent 26 seconds, it maintains the velocity of 34m/s, covering 884 meters.

In the subsequent 4 seconds, it accelerates at a rate of 1m/s^2, covering 144 meters.

In the subsequent 8 seconds, it maintains the velocity of 38m/s, covering 304 meters.

In the last 38 seconds, it decelerates at the acceleration of -1m/s^2, covering 722 meters.

The total distance covered is 578 + 884 + 144 + 304 + 722 = 2632 meters.

Sample Input 3

3
12 14 2
6 2 7

Sample Output 3

76.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 6 seconds, it accelerates at a rate of 1m/s^2, covering 18 meters.

In the subsequent 2 seconds, it maintains the velocity of 6m/s, covering 12 meters.

In the subsequent 4 seconds, it decelerates at the acceleration of -1m/s^2, covering 16 meters.

In the subsequent 14 seconds, it maintains the velocity of 2m/s, covering 28 meters.

In the last 2 seconds, it decelerates at the acceleration of -1m/s^2, covering 2 meters.

The total distance covered is 18 + 12 + 16 + 28 + 2 = 76 meters.

Sample Input 4

1
9
10

Sample Output 4

20.250000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 4.5 seconds, it accelerates at a rate of 1m/s^2, covering 10.125 meters.

In the last 4.5 seconds, it decelerates at the acceleration of -1m/s^2, covering 10.125 meters.

The total distance covered is 10.125 + 10.125 = 20.25 meters.

Sample Input 5

10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70

Sample Output 5

20291.000000000000


#include<bits/stdc++.h>

using namespace std;
int main()

{
    int a,b,c;
    cin>>a>>b>>c;

    if(a==b){
        cout<<c<<endl;
    }
    else if(a==c){
        cout<<b<<endl;
    }
    else if(b==c){
        cout<<a<<endl;
    }

return 0;

}

Score : 100 points

Problem Statement

You are given three integers, A, B and C.

Among them, two are the same, but the remaining one is different from the rest.

For example, when A=5,B=7,C=5, A and C are the same, but B is different.

Find the one that is different from the rest among the given three integers.

Constraints

-100 \leq A,B,C \leq 100

A, B and C are integers.

The input satisfies the condition in the statement.

Input

Input is given from Standard Input in the following format:

A B C

Output

Among A, B and C, print the integer that is different from the rest.

Sample Input 1

5 7 5

Sample Output 1

7

This is the same case as the one in the statement.

Sample Input 2

1 1 7

Sample Output 2

7

In this case, C is the one we seek.

Sample Input 3

-100 100 100

Sample Output 3

-100


#include <iostream>
#include <vector>

using namespace std;

using int64 = long long;

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

    vector<int64> x(n);
    vector<int64> y(n);
    for (int i=0; i<n; i++) cin >> x[i] >> y[i];

    vector<int64> xv = x;
    vector<int64> yv = y;

    sort(xv.begin(), xv.end());
    sort(yv.begin(), yv.end());

    int64 ans = LONG_MAX;
    for (int xs=0; xs<n; xs++) {
        for (int xe=xs+1; xe<n; xe++) {
            for (int ys=0; ys<n; ys++) {
                for (int ye=ys+1; ye<n; ye++) {

                    int cnt = 0;
                    for (int i=0; i<n; i++) {
                        if (xv[xs] <= x[i] && x[i] <= xv[xe] && yv[ys] <= y[i] && y[i] <= yv[ye])
                            cnt++;
                    }
                    if (cnt >= k) {
                        ans = min(ans, (xv[xe] - xv[xs]) * (yv[ye] - yv[ys]));
                    }
              }
            }
        }
    }

    cout << ans << endl;
}

Score : 400 points

Problem Statement

We have N points in a two-dimensional plane.

The coordinates of the i-th point (1 \leq i \leq N) are (x_i,y_i).

Let us consider a rectangle whose sides are parallel to the coordinate axes that contains K or more of the N points in its interior.

Here, points on the sides of the rectangle are considered to be in the interior.

Find the minimum possible area of such a rectangle.

Constraints

2 \leq K \leq N \leq 50

-10^9 \leq x_i,y_i \leq 10^9 (1 \leq i \leq N)

x_i≠x_j (1 \leq i<j \leq N)

y_i≠y_j (1 \leq i<j \leq N)

All input values are integers. (Added at 21:50 JST)

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1
:
x_{N} y_{N}

Output

Print the minimum possible area of a rectangle that satisfies the condition.

Sample Input 1

4 4
1 4
3 3
6 2
8 1

Sample Output 1

21

One rectangle that satisfies the condition with the minimum possible area has the following vertices: (1,1), (8,1), (1,4) and (8,4).

Its area is (8-1) × (4-1) = 21.

Sample Input 2

4 2
0 0
1 1
2 2
3 3

Sample Output 2

1

Sample Input 3

4 3
-1000000000 -1000000000
1000000000 1000000000
-999999999 999999999
999999999 -999999999

Sample Output 3

3999999996000000001

Watch out for integer overflows.


// This amazing code is by Eric Sunli Chen.
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;
template<typename T> void get_int(T &x)
{
	char t=getchar();
	bool neg=false;
	x=0;
	for(; (t>'9'||t<'0')&&t!='-'; t=getchar());
	if(t=='-')neg=true,t=getchar();
	for(; t<='9'&&t>='0'; t=getchar())x=x*10+t-'0';
	if(neg)x=-x;
}
template<typename T> void print_int(T x)
{
	if(x<0)putchar('-'),x=-x;
	short a[20]= {},sz=0;
	while(x>0)a[sz++]=x%10,x/=10;
	if(sz==0)putchar('0');
	for(int i=sz-1; i>=0; i--)putchar('0'+a[i]);
}
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define get1(a) get_int(a)
#define get2(a,b) get1(a),get1(b)
#define get3(a,b,c) get1(a),get2(b,c)
#define printendl(a) print_int(a),puts("")
typedef long long LL;
typedef unsigned long long uLL;
typedef pair<int,int> pii;
const int inf=0x3f3f3f3f;
const LL Linf=1ll<<61;
const double pi=acos(-1.0);

int a,b,c;
string now,dp[55][55][55];
bool ok[55][55][55];
void update(int i,int j,int k,const string&s)
{
	if(s+now>=now+now.substr(0,s.size()))
	{
		if(!ok[i][j][k])
		{
			ok[i][j][k]=1;
			dp[i][j][k]=s;
		}
		else if(dp[i][j][k]<s)dp[i][j][k]=s;
	}
}
bool check()
{
	memset(ok,0,sizeof(ok));
	ok[0][0][0]=1;dp[0][0][0]="";
	for(int i=0;i<=a;i++)for(int j=0;j<=b;j++)for(int k=0;k<=c;k++)
	{
		if(!ok[i][j][k])continue;
		if(i<a)update(i+1,j,k,'a'+dp[i][j][k]);
		if(j<b)update(i,j+1,k,'b'+dp[i][j][k]);
		if(k<c)update(i,j,k+1,'c'+dp[i][j][k]);
	}
	return ok[a][b][c];
}
int main()
{
	cin>>a>>b>>c;
	for(int i=0;i<a+b+c;i++)now+='a';
	for(int i=0,j;i<a+b+c;i++)
	{
		for(j='b';j<='c';j++)
		{
			now[i]=j;
			if(!check())break;
		}
		now[i]=j-1;
	}
	cout<<now<<endl;
	return 0;
}

Score : 1600 points

Problem Statement

For a string S, let f(S) be the lexicographically smallest cyclic shift of S.
For example, if S = babca, f(S) = ababc because this is the smallest among all cyclic shifts (babca, abcab, bcaba, cabab, ababc).

You are given three integers X, Y, and Z.
You want to construct a string T that consists of exactly X as, exactly Y bs, and exactly Z cs.
If there are multiple such strings, you want to choose one that maximizes f(T) lexicographically.

Compute the lexicographically largest possible value of f(T).

Constraints

1 \leq X + Y + Z \leq 50

X, Y, Z are non-negative integers.

Input

Input is given from Standard Input in the following format:

X Y Z

Output

Print the answer.

Sample Input 1

2 2 0

Sample Output 1

abab

T must consist of two as and two bs.

If T = aabb, f(T) = aabb.

If T = abab, f(T) = abab.

If T = abba, f(T) = aabb.

If T = baab, f(T) = aabb.

If T = baba, f(T) = abab.

If T = bbaa, f(T) = aabb.

Thus, the largest possible f(T) is abab.

Sample Input 2

1 1 1

Sample Output 2

acb


#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define copy(from, to) copy(from.begin(), from.end(), back_inserter(to))
#define sort(a) sort(a.begin(), a.end())
#define p(s) cout << (s) << endl

typedef long long ll;
using namespace std;

template<class T>
void load(vector<T> &v, int n) {
  for (int i = 0; i < n; ++i) {
    T t;
    cin >> t;
    v.push_back(t);
  }
}

int main() {
  string s;
  cin >> s;

  string ch = s.substr(0, 4);
  if (ch == "YAKI") {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
}

Score : 100 points

Problem Statement

Ringo is giving a present to Snuke.

Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with YAKI in Japanese, and does not like other things.

You are given a string S representing the Japanese name of Ringo's present to Snuke. Determine whether S starts with YAKI.

Constraints

1 \leq |S| \leq 10

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S starts with YAKI, print Yes; otherwise, print No.

Sample Input 1

YAKINIKU

Sample Output 1

Yes

YAKINIKU starts with YAKI.

Sample Input 2

TAKOYAKI

Sample Output 2

No

TAKOYAKI (a Japanese snack. tako: octopus) does not start with YAKI.

Sample Input 3

YAK

Sample Output 3

No


//#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
#include <numeric>
typedef long long Int;
#define rep(i,a,b) for(Int i=a;i<b;++i)
#define rrep(i,a,b) for(Int i=a;i>=b;--i)
using namespace std;

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

    Int A, B, C, D, E, F;
    cin >> A >> B >> C >> D >> E >> F;

    Int resSugarWater = 0, resSugar = 0;
    double maxDensity = 0.0;

    for(Int a = 0; 100*A*a <= F; ++a) {
        for(Int b = 0; 100*A*a+100*B*b <= F; ++b) {
            for(Int c = 0; 100*A*a+100*B*b+C*c <= F; ++c) {
                for(Int d = 0; 100*A*a+100*B*b+C*c+D*d <= F; ++d) {
                    Int mWater = 100*A*a + 100*B*b;
                    Int mSugar = C*c + D*d;
                    if (mSugar > E*mWater/100 or (mWater+mSugar) == 0) continue;

                    double density = (double)mSugar/(double)(mWater+mSugar);
                    if (density > maxDensity) {
                        maxDensity = density;
                        resSugarWater = mWater+mSugar;
                        resSugar = C*c+D*d;
                    }
                }
            }
        }
    }

    cout << resSugarWater << " " << resSugar << endl;
}

Score : 300 points

Problem Statement

Snuke is making sugar water in a beaker.
Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.

Operation 1: Pour 100A grams of water into the beaker.

Operation 2: Pour 100B grams of water into the beaker.

Operation 3: Put C grams of sugar into the beaker.

Operation 4: Put D grams of sugar into the beaker.

In our experimental environment, E grams of sugar can dissolve into 100 grams of water.

Snuke will make sugar water with the highest possible density.

The beaker can contain at most F grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker.
Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it.
If there is more than one candidate, any of them will be accepted.

We remind you that the sugar water that contains a grams of water and b grams of sugar is \frac{100b}{a + b} percent.
Also, in this problem, pure water that does not contain any sugar is regarded as 0 percent density sugar water.

Constraints

1 \leq A < B \leq 30

1 \leq C < D \leq 30

1 \leq E \leq 100

100A \leq F \leq 3 000

A, B, C, D, E and F are all integers.

Inputs

Input is given from Standard Input in the following format:

A B C D E F

Outputs

Print two integers separated by a space.
The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.

Sample Input 1

1 2 10 20 15 200

Sample Output 1

110 10

In this environment, 15 grams of sugar can dissolve into 100 grams of water, and the beaker can contain at most 200 grams of substances.

We can make 110 grams of sugar water by performing Operation 1 once and Operation 3 once.
It is not possible to make sugar water with higher density.
For example, the following sequences of operations are infeasible:

If we perform Operation 1 once and Operation 4 once, there will be undissolved sugar in the beaker.

If we perform Operation 2 once and Operation 3 three times, the mass of substances in the beaker will exceed 200 grams.

Sample Input 2

1 2 1 2 100 1000

Sample Output 2

200 100

There are other acceptable outputs, such as:

400 200

However, the output below is not acceptable:

300 150

This is because, in order to make 300 grams of sugar water containing 150 grams of sugar, we need to pour exactly 150 grams of water into the beaker, which is impossible.

Sample Input 3

17 19 22 26 55 2802

Sample Output 3

2634 934


#include<bits/stdc++.h>

#define rep(i,n) for(int i = 0; i < (n); i++)
#define rrep(i,n) for(int i = (n)-1; i >= 0; i--)
#define rep1(i,n) for(int i = 1; i <= (n); i++)
#define rrep1(i,n) for(int i = (n); i > 0; i--)

#define ll long long
#define pi pair<int, int>
#define pll pair<ll, ll>

#define MOD 1000000007
#define INF 1000000000000000LL

using namespace std;

#define MAXN 300

int main(){
  int n;cin>>n;
  ll og[MAXN][MAXN], g[MAXN][MAXN];
  rep(i, n)rep(j, n){ cin>>og[i][j]; og[j][i]=og[i][j]; }
  rep(i, n)rep(j, n)g[i][j]=og[i][j];

  rep(k, n)rep(i, n)rep(j, n)g[i][j] = min<ll>(g[i][j], g[i][k]+g[k][j]);

  bool f=true;
  rep(i, n)rep(j, n)if(og[i][j]!=g[i][j])f=false;
  if(!f){ cout<<-1<<endl; return 0; }

  vector<pair<ll, pi>> edges;
  rep(i, n)rep(j, n)if(i!=j)edges.push_back({g[i][j], {i, j}});

  rep(i, n)rep(j, n)rep(k, n)if(g[i][k]!=0 && g[k][j]!=0 && g[i][j]==g[i][k]+g[k][j]) g[i][j]=g[j][i]=0;

  ll result = 0;
  rep(i, n)rep(j, n) result += g[i][j];

  cout<<result/2<<endl;

  return 0;
}

Score : 500 points

Problem Statement

In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads.
The following are known about the road network:

People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.

Different roads may have had different lengths, but all the lengths were positive integers.

Snuke the archeologist found a table with N rows and N columns, A, in the ruin of Takahashi Kingdom.
He thought that it represented the shortest distances between the cities along the roads in the kingdom.

Determine whether there exists a road network such that for each u and v, the integer A_{u, v} at the u-th row and v-th column of A is equal to the length of the shortest path from City u to City v.
If such a network exist, find the shortest possible total length of the roads.

Constraints

1 \leq N \leq 300

If i ≠ j, 1 \leq A_{i, j} = A_{j, i} \leq 10^9.

A_{i, i} = 0

Inputs

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}
...
A_{N, 1} A_{N, 2} ... A_{N, N}

Outputs

If there exists no network that satisfies the condition, print -1.
If it exists, print the shortest possible total length of the roads.

Sample Input 1

3
0 1 3
1 0 2
3 2 0

Sample Output 1

3

The network below satisfies the condition:

City 1 and City 2 is connected by a road of length 1.

City 2 and City 3 is connected by a road of length 2.

City 3 and City 1 is not connected by a road.

Sample Input 2

3
0 1 3
1 0 1
3 1 0

Sample Output 2

-1

As there is a path of length 1 from City 1 to City 2 and City 2 to City 3, there is a path of length 2 from City 1 to City 3.
However, according to the table, the shortest distance between City 1 and City 3 must be 3.

Thus, we conclude that there exists no network that satisfies the condition.

Sample Input 3

5
0 21 18 11 28
21 0 13 10 26
18 13 0 23 13
11 10 23 0 17
28 26 13 17 0

Sample Output 3

82

Sample Input 4

3
0 1000000000 1000000000
1000000000 0 1000000000
1000000000 1000000000 0

Sample Output 4

3000000000


#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <queue>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define int long long
#define INF 1e9 + 7
#define cae cout << ans << endl;
#define cye cout << "Yes" << endl;
#define cne cout << "No" << endl;
#define r0 return 0;
#define ll long long
using namespace std;
typedef pair<int,int>P;
signed main() {
    int n;
    cin >> n;
    if (n % 10 == 9 || n / 10 == 9) {
        cye
    } else {
        cne
    }
    r0
}

Score : 100 points

Problem Statement

It is September 9 in Japan now.

You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?

Constraints

10≤N≤99

Input

Input is given from Standard Input in the following format:

N

Output

If 9 is contained in the decimal notation of N, print Yes; if not, print No.

Sample Input 1

29

Sample Output 1

Yes

The one's digit of 29 is 9.

Sample Input 2

72

Sample Output 2

No

72 does not contain 9.

Sample Input 3

91

Sample Output 3

Yes


#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 ALL(v) (v).begin(),(v).end()
#define fi first
#define se second
template<typename A, typename B> inline bool chmax(A &a, B b) { if (a<b) { a=b; return 1; } return 0; }
template<typename A, typename B> inline bool chmin(A &a, B b) { if (a>b) { a=b; return 1; } return 0; }
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<int, pii> pip;
const ll INF = 1ll<<29;
const ll MOD = 1000000007;
const double EPS = 1e-10;
const bool debug = 0;
//------------------------------//

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

	if (n % 10 == 9 || n >= 90) puts("Yes");
	else puts("No");

	return 0;
}


#include<stdio.h>
#include<malloc.h>

int main(){
	int n;
	int i,j,count=0;
	int **Data;
	scanf("%d",&n);

	Data = (int **)malloc(n*sizeof(int *));
	for(i=0;i<n;i++){
		Data[i] = (int *)malloc(2*sizeof(int));
	}
	for(i=0;i<n;i++){
			scanf("%d",&Data[i][0]);
	}
	for(i=0;i<n;i++){
			Data[i][1]	= 0;
	}
	for(i=0;i<n;i++){
		for(j=0;j<n;j++){
			if(Data[i][0] == Data[j][0])
	            Data[i][1]++;
		}
	}
	for(i=0;i<n;i++){
	    if(Data[i][1]%2!=0)
			count++;
	}
	printf("%d",count);

	return 0;
}

Score : 300 points

Problem Statement

You are playing the following game with Joisino.

Initially, you have a blank sheet of paper.

Joisino announces a number. If that number is written on the sheet, erase the number from the sheet; if not, write the number on the sheet. This process is repeated N times.

Then, you are asked a question: How many numbers are written on the sheet now?

The numbers announced by Joisino are given as A_1, ... ,A_N in the order she announces them. How many numbers will be written on the sheet at the end of the game?

Constraints

1≤N≤100000

1≤A_i≤1000000000(=10^9)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print how many numbers will be written on the sheet at the end of the game.

Sample Input 1

3
6
2
6

Sample Output 1

1

The game proceeds as follows:

6 is not written on the sheet, so write 6.

2 is not written on the sheet, so write 2.

6 is written on the sheet, so erase 6.

Thus, the sheet contains only 2 in the end. The answer is 1.

Sample Input 2

4
2
5
5
2

Sample Output 2

0

It is possible that no number is written on the sheet in the end.

Sample Input 3

6
12
22
16
22
18
12

Sample Output 3

2


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for( int i = 0; i < n; i++ )
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define INF 2000000000
#define mod 1000000007
#define INF2 1000000000000000000

int main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N;
    cin >> N;
    int A[N];
    rep(i ,N) cin >> A[i];
    sort(A, A+N);
    int ans = 0;
    rep(i, N) {
        int count = 1;
        while (A[i] == A[i+1]) {
            count++;
            i++;
        }
        if (count % 2 == 1) {
            ans++;
        }
    }
    cout << ans << endl;
    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long LL;
int p[100001];

int main(){
    int n;
    cin>>n;
    for (int i=1;i<=n;i++){
        cin>>p[i];
    }
    int cnt=0;
    for (int i=1;i<=n;i++) {
        if (p[i]==i) {
            swap(p[i],p[i+1]);
            cnt++;
        }
    }
    cout<<cnt<<endl;
}

Score : 400 points

Problem Statement

You are given a permutation p_1,p_2,...,p_N consisting of 1,2,..,N.
You can perform the following operation any number of times (possibly zero):

Operation: Swap two adjacent elements in the permutation.

You want to have p_i ≠ i for all 1≤i≤N.
Find the minimum required number of operations to achieve this.

Constraints

2≤N≤10^5

p_1,p_2,..,p_N is a permutation of 1,2,..,N.

Input

The input is given from Standard Input in the following format:

N
p_1 p_2 .. p_N

Output

Print the minimum required number of operations

Sample Input 1

5
1 4 3 5 2

Sample Output 1

2

Swap 1 and 4, then swap 1 and 3. p is now 4,3,1,5,2 and satisfies the condition.
This is the minimum possible number, so the answer is 2.

Sample Input 2

2
1 2

Sample Output 2

1

Swapping 1 and 2 satisfies the condition.

Sample Input 3

2
2 1

Sample Output 3

0

The condition is already satisfied initially.

Sample Input 4

9
1 2 4 9 5 8 7 3 6

Sample Output 4

3


#include<bits/stdc++.h>
using namespace std;
long long v,n,a;
double d[]={0.25,0.5,1,2};
vector<pair<long long,double> >V;
main(){
  for(int i=0;i<4;++i)cin>>v,V.push_back(make_pair(v,d[i]));
  cin>>n;
  for(int i=0;i<4;++i)for(int j=3;j>i;--j)if(V[j-1].first/V[j-1].second>V[j].first/V[j].second)swap(V[j-1],V[j]);
  for(int i=0;i<4&&n;++i){
    int x=n/V[i].second;
    a+=x*V[i].first;
    n-=int(x*V[i].second);
  }
  cout<<a<<endl;
}

Score : 300 points

Problem Statement

You've come to your favorite store Infinitesco to buy some ice tea.

The store sells ice tea in bottles of different volumes at different costs.
Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen.
The store has an infinite supply of bottles of each type.

You want to buy exactly N liters of ice tea. How many yen do you have to spend?

Constraints

1 \leq Q, H, S, D \leq 10^8

1 \leq N \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q H S D
N

Output

Print the smallest number of yen you have to spend to buy exactly N liters of ice tea.

Sample Input 1

20 30 70 90
3

Sample Output 1

150

Buy one 2-liter bottle and two 0.5-liter bottles. You'll get 3 liters for 90 + 30 + 30 = 150 yen.

Sample Input 2

10000 1000 100 10
1

Sample Output 2

100

Even though a 2-liter bottle costs just 10 yen, you need only 1 liter.
Thus, you have to buy a 1-liter bottle for 100 yen.

Sample Input 3

10 100 1000 10000
1

Sample Output 3

40

Now it's better to buy four 0.25-liter bottles for 10 + 10 + 10 + 10 = 40 yen.

Sample Input 4

12345678 87654321 12345678 87654321
123456789

Sample Output 4

1524157763907942


#include <bits/stdc++.h>
using namespace std;
long double spi=3.1415926535898*5.00;
int x[400005],y[400005];
int u[400005],t[400005];
struct node
{int x,y;
}p[400005];
int cnt=0;
inline bool cmp(node a,node b)
{return a.x<b.x;}
inline void add(int pos)
{while (pos<=cnt)
{t[pos]++;pos+=(pos&(-pos));}
}
inline int q(int pos)
{int s=0;
while (pos)
{s+=t[pos];pos-=(pos&(-pos));}
return s;
}
int main (){
	int n,xs,xt,ys,yt,i;
	scanf ("%d%d%d%d",&xs,&ys,&xt,&yt);
	if (xs>xt) {swap(xs,xt);swap(ys,yt);}
	scanf ("%d",&n);
	for (i=1;i<=n;i++)
	{scanf ("%d%d",&x[i],&y[i]);}
	if (ys<=yt)
	{for (i=1;i<=n;i++)
	{if (x[i]>=xs&&x[i]<=xt&&y[i]>=ys&&y[i]<=yt)
	{p[++cnt].x=x[i];p[cnt].y=y[i];}
	}
	sort(p+1,p+cnt+1,cmp);
	for (i=1;i<=cnt;i++)
	{u[i]=p[i].y;}
	sort(u+1,u+cnt+1);
	for (i=1;i<=cnt;i++)
	{p[i].y=lower_bound(u+1,u+cnt+1,p[i].y)-u;}
	int ans=0;
	for (i=1;i<=cnt;i++)
	{int t=q(p[i].y);
	if (t+1>ans) {ans=t+1;}
	add(p[i].y);
	}
	long double res=((long double)(yt-ys+xt-xs))*100.00+(spi-20.0)*((long double)(ans));
	if (ans==min(yt-ys+1,xt-xs+1)) {res+=spi;}
	printf ("%.15Lf\n",res);
	return 0;
	}
	for (i=1;i<=n;i++)
	{if (x[i]>=xs&&x[i]<=xt&&y[i]>=yt&&y[i]<=ys)
	{p[++cnt].x=x[i];p[cnt].y=y[i];}
	}
	sort(p+1,p+cnt+1,cmp);
	for (i=1;i<=cnt;i++)
	{u[i]=p[i].y;}
	sort(u+1,u+cnt+1);
	for (i=1;i<=cnt;i++)
	{p[i].y=lower_bound(u+1,u+cnt+1,p[i].y)-u;}
	int ans=0;
	for (i=1;i<=cnt;i++)
	{int t=q(cnt)-q(p[i].y);
	if (t+1>ans) {ans=t+1;}
	add(p[i].y);
	}
	long double res=((long double)(ys-yt+xt-xs))*100.00+(spi-20.0)*((long double)(ans));
	if (ans==min(ys-yt+1,xt-xs+1)) {res+=spi;}
	printf ("%.15Lf\n",res);
	return 0;
}

Score : 900 points

Problem Statement

In the city of Nevermore, there are 10^8 streets and 10^8 avenues, both numbered from 0 to 10^8-1.
All streets run straight from west to east, and all avenues run straight from south to north.
The distance between neighboring streets and between neighboring avenues is exactly 100 meters.

Every street intersects every avenue. Every intersection can be described by pair (x, y), where x is avenue ID and y is street ID.

There are N fountains in the city, situated at intersections (X_i, Y_i).
Unlike normal intersections, there's a circle with radius 10 meters centered at the intersection, and there are no road parts inside this circle.

The picture below shows an example of how a part of the city with roads and fountains may look like.

City governors don't like encountering more than one fountain while moving along the same road.
Therefore, every street contains at most one fountain on it, as well as every avenue.

Citizens can move along streets, avenues and fountain perimeters.
What is the shortest distance one needs to cover in order to get from intersection (x_1, y_1) to intersection (x_2, y_2)?

Constraints

0 \leq x_1, y_1, x_2, y_2 < 10^8

1 \leq N \leq 200,000

0 \leq X_i, Y_i < 10^8

X_i \neq X_j for i \neq j

Y_i \neq Y_j for i \neq j

Intersections (x_1, y_1) and (x_2, y_2) are different and don't contain fountains.

All input values are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N

Output

Print the shortest possible distance one needs to cover in order to get from intersection (x_1, y_1) to intersection (x_2, y_2), in meters.
Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-11}.

Sample Input 1

1 1 6 5
3
3 2
5 3
2 4

Sample Output 1

891.415926535897938

One possible shortest path is shown on the picture below. The path starts at the blue point, finishes at the purple point and follows along the red line.

Sample Input 2

3 5 6 4
3
3 2
5 3
2 4

Sample Output 2

400.000000000000000

Sample Input 3

4 2 2 2
3
3 2
5 3
2 4

Sample Output 3

211.415926535897938


#include <bits/stdc++.h>
using namespace std;
int main(){
  int x, a, b;
  cin >> x >> a >> b;
  if (abs(x-a) < abs(x-b)){
    cout << 'A' << endl;
  }
  else {
    cout << 'B' << endl;
  }
}

Score : 100 points

Problem Statement

Snuke lives at position x on a number line.
On this line, there are two stores A and B, respectively at position a and b, that offer food for delivery.

Snuke decided to get food delivery from the closer of stores A and B.
Find out which store is closer to Snuke's residence.

Here, the distance between two points s and t on a number line is represented by |s-t|.

Constraints

1 \leq x \leq 1000

1 \leq a \leq 1000

1 \leq b \leq 1000

x, a and b are pairwise distinct.

The distances between Snuke's residence and stores A and B are different.

Input

Input is given from Standard Input in the following format:

x a b

Output

If store A is closer, print A; if store B is closer, print B.

Sample Input 1

5 2 7

Sample Output 1

B

The distances between Snuke's residence and stores A and B are 3 and 2, respectively.
Since store B is closer, print B.

Sample Input 2

1 999 1000

Sample Output 2

A


#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <utility>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <numeric>

#define rep(i,j,k) for(int i=(int)j;i<(int)k;i++)
#define itrep(i,x) for(auto i=(x).begin(); i!=(x).end();i++)
#define Sort(x) sort((x).begin(),(x).end())
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define vec vector
#define INF (int)1e9
#define INFL 1e18
#define MOD 1000000007
#define pb push_back
#define MP make_pair
#define PI 3.1415926535
#define fcout cout<<fixed<<setprecision(10)
typedef long long int ll;
typedef std::pair<int,int> P;
int D=1;
int dx[4]={0,1,0,-1},dy[4]={-1,0,1,0};
int day[12]={31,28,31,30,31,30,31,31,30,31,30,31};
//template<typename T>void pp(T x){cout<<x<<endl;}

using namespace std;
template<typename T> void test(vector<T> v){for(int i=0;i<v.size();i++){if(i)cout<<" ";cout<<v[i];}cout<<endl;}

int main(){
    int n;
    cin>>n;
    vector<ll> v(n);
    rep(i,0,n)cin>>v[i];

    Sort(v);
    ll ans[2]={};
    ll spans=0;
    int index=0;
    rep(i,0,n){
        int ct=0;
        while(v[i]==v[i+1]){
            ct++;
            i++;
        }

        if(ct>=3)spans=v[i];
        else if(ct && ans[0]<v[i]){
            ans[1]=ans[0];
            ans[0]=v[i];
        }
    }
    cout<<max(spans*spans,ans[1]*ans[1-1])<<endl;

    return 0;
}

Score : 300 points

Problem Statement

We have N sticks with negligible thickness.
The length of the i-th stick is A_i.

Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides.
Find the maximum possible area of the rectangle.

Constraints

4 \leq N \leq 10^5

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible area of the rectangle.
If no rectangle can be formed, print 0.

Sample Input 1

6
3 1 2 4 2 1

Sample Output 1

2

1 \times 2 rectangle can be formed.

Sample Input 2

4
1 2 3 4

Sample Output 2

0

No rectangle can be formed.

Sample Input 3

10
3 3 3 3 4 4 4 5 5 5

Sample Output 3

20


#include <iostream>
#define NUM 1000000007

using namespace std;

int main(){
    string a, b;
    int i,n;
    int flag = 1;
    long long answer = 3;
    cin >> n >> a >> b;
    for(i = 0; i < n; i++){
        if(a[i] == b[i]){
            if(flag * i){
                answer = answer * 2 % NUM;
            }
            flag = 1;
        }else{
            if(flag){
                answer = answer * 2 % NUM;
            }else{
                answer = answer * 3 % NUM;
            }
            flag = 0;
            i++;
        }
    }
    cout << answer << endl;
}

Score : 400 points

Problem Statement

We have a board with a 2 \times N grid.
Snuke covered the board with N dominoes without overlaps.
Here, a domino can cover a 1 \times 2 or 2 \times 1 square.

Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.

Find the number of such ways to paint the dominoes, modulo 1000000007.

The arrangement of the dominoes is given to you as two strings S_1 and S_2 in the following manner:

Each domino is represented by a different English letter (lowercase or uppercase).

The j-th character in S_i represents the domino that occupies the square at the i-th row from the top and j-th column from the left.

Constraints

1 \leq N \leq 52

|S_1| = |S_2| = N

S_1 and S_2 consist of lowercase and uppercase English letters.

S_1 and S_2 represent a valid arrangement of dominoes.

Input

Input is given from Standard Input in the following format:

N
S_1
S_2

Output

Print the number of such ways to paint the dominoes, modulo 1000000007.

Sample Input 1

3
aab
ccb

Sample Output 1

6

There are six ways as shown below:

Sample Input 2

1
Z
Z

Sample Output 2

3

Note that it is not always necessary to use all the colors.

Sample Input 3

52
RvvttdWIyyPPQFFZZssffEEkkaSSDKqcibbeYrhAljCCGGJppHHn
RLLwwdWIxxNNQUUXXVVMMooBBaggDKqcimmeYrhAljOOTTJuuzzn

Sample Output 3

958681902


#include <bits/stdc++.h>
#define fi first
#define se second
#define rep(i,n) for(int i=0;i<(n);i++)
#define rrep(i,n) for(int i = 1; i <= (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
#define all(v) v.begin(),v.end()
#define len(x) (ll)(x).length()
#define maxs(x,y) x = max(x,y)
#define mins(x,y) x = min(x,y)
#define pb push_back
#define sz(x) (ll)(x).size()
#define v(T) vector<T>
#define vv(T) vector<vector<T>>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<P> vp;
ll gcd(ll a,ll b){if(a%b==0){return b;}else{return(gcd(b,a%b));}}
ll lcm(ll a,ll b){return a*b/gcd(a,b);}
const int INF=1e9;
const ll INFS=1e18;
const int MOD=INF+7;
const int di[] = {-1,0,1,0};
const int dj[] = {0,-1,0,1};
const double PI=acos(-1);

int main() {
  ll n;
  cin>>n;
  vi cnt;
  ll ans=0;
  map<ll,ll> mp;
  rep(i,n){
    ll a;
    cin>>a;
    mp[a]++;
    if(mp[a]==2){
      cnt.pb(a);
      mp[a]=0;
    }
  }
  if(sz(cnt)==0){
    cout<<0<<endl;
    return 0;
  }
  if(sz(cnt)==1){
    cout<<0<<endl;
    return 0;
  }
  sort(all(cnt));
  reverse(all(cnt));
  ans=cnt[0]*cnt[1];
  cout<<ans<<endl;
}


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

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)

using ll = long long;
using ld = long double;
ll INF = LLONG_MAX;

using vi = vector<int>;
using vll = vector<ll>;
using pii = pair<int, int>;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }

	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);

	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
		pr(t); pr(ts...);
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) {
		pr("{",x.f,", ",x.s,"}");
	}
	template<class T> void pr(const T& x) {
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
		pr("}");
	}

	void print() { pr("\n"); } // print w/ spaces
	template<class T, class... Ts> void print(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(" "); print(ts...);
	}
}

using namespace output;

ll MOD = 1e9+7;
int main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

	int N; cin >> N;
	string S1, S2; cin >> S1 >> S2;

	ll used = 0;
	ll cols = 1;
	F0R(i, N) {
		if (S1[i] == S2[i]) {
			cols *= (3 - used);
			used = 1;
		} else {
			if (used == 0) cols *= 6;
			else if (used == 1) cols *= 2;
			else cols *= 3;
			used = 2;
			++i;
		}
		cols %= MOD;
	}
	print(cols);
}


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

void solve(long long N, vector<string> S){
  long long ans = 1;
  long long M = 1000000007;
  long long type = 0;
	for ( long long i = 0; i < N; i++ ) {
    if (S[0][i] == S[1][i]) {
      if ( type == 0 ) {
        ans = 3;
        type = 1;
      } else if ( type == 1 ) {
        ans *= 2;
      } else if ( type == 2 ) {
        ans *= 1;
        type = 1;
      }
    } else if ( i < S[0].length() - 1 &&  S[0][i] == S[0][i+1] && S[1][i] == S[1][i+1] ) {
      i += 1;
      if ( type == 0 ) {
        ans = 6;
        type = 2;
      } else if ( type == 1 ) {
        ans *= 2;
        type = 2;
      } else if ( type == 2 ) {
        ans *= 3;
      }
    }
    ans %= M;
  }
  cout << ans << endl;
}

int main(){
	long long N;
	vector<string> S(2-1+1);
	scanf("%lld",&N);
	for(int i = 0 ; i <= 2-1 ; i++){
		cin >> S[i];
	}
	solve(N, S);
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long unsigned int ll;

int main() {

  string a;
  cin >> a;

  if(a[0]==a[2]){
    cout << "Yes" << endl;
  }else{
    cout << "No" << endl;
  }

   return 0;
}

Score : 100 points

Problem Statement

You are given a three-digit positive integer N.

Determine whether N is a palindromic number.

Here, a palindromic number is an integer that reads the same backward as forward in decimal notation.

Constraints

100≤N≤999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a palindromic number, print Yes; otherwise, print No.

Sample Input 1

575

Sample Output 1

Yes

N=575 is also 575 when read backward, so it is a palindromic number. You should print Yes.

Sample Input 2

123

Sample Output 2

No

N=123 becomes 321 when read backward, so it is not a palindromic number. You should print No.

Sample Input 3

812

Sample Output 3

No


#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
char s[10];
int main()
{
    cin>>s;
    if(s[0]==s[2]) cout<<"yes";
    else cout<<"no";
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int a, b, c, d, ans, i, v[N];
int main() {
	cin >> a >> b >> c >> d;
	for (i = a + 1; i <= b; i++) v[i] = 1;
	for (i = c + 1; i <= d; i++) if (v[i]) ans++;
	cout << ans << endl;
	return 0;
}

Score : 200 points

Problem Statement

Alice and Bob are controlling a robot. They each have one switch that controls the robot.

Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up.

Bob started holding down his button C second after the start-up, and released his button D second after the start-up.

For how many seconds both Alice and Bob were holding down their buttons?

Constraints

0≤A<B≤100

0≤C<D≤100

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.

Sample Input 1

0 75 25 100

Sample Output 1

50

Alice started holding down her button 0 second after the start-up of the robot, and released her button 75 second after the start-up.

Bob started holding down his button 25 second after the start-up, and released his button 100 second after the start-up.

Therefore, the time when both of them were holding down their buttons, is the 50 seconds from 25 seconds after the start-up to 75 seconds after the start-up.

Sample Input 2

0 33 66 99

Sample Output 2

0

Alice and Bob were not holding their buttons at the same time, so the answer is zero seconds.

Sample Input 3

10 90 20 80

Sample Output 3

60


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

int main()
{
    int a, b, c, d;
    cin >> a >> b >> c >> d;
    int x = 0;
    if (a <= c && c <= b && b <= d)
    {
        x = b - c;
    }
    else if (a <= c && c <= d && d <= b)
    {
        x = d - c;
    }
    else if (c <= a && a <= d && d <= b)
    {
        x = d - a;
    }
    else if (c <= a && a <= b && b <= d)
    {
        x = b - a;
    }

    cout << x << endl;
}


#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	int A,B,C,D;
	cin>>A>>B>>C>>D;
	if(B<C&&A>D)cout<<0;
	else if(C<=A&&B<=D)cout<<abs(A-B);
	else if(A<=C&&D<=B)cout<<abs(C-D);
	else if(D>=B&&B>=C&&C>=A)cout<<abs(B-C);
	else if(D>=A&&A>=C&&B>=D)cout<<abs(A-D);
}


#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
	long long int a, b, c, d;
	cin >> a >> b >> c >> d;
	if (b < d){
		if (b < c){
			cout << 0 << endl;
			return 0;
		}
		else{
			cout << b - c << endl;
			return 0;
		}
	}
	else{
		if (c >= a){
			cout << d - c << endl;
			return 0;
		}
		else{
			if (d >= a){
				cout << d - a << endl;
				return 0;
			}
			else{
				cout << 0 << endl;
				return 0;
			}
		}
	}
}


#include <iostream>
#include <string>
#include <vector>

using IV = std::vector<int>;
IV ToFixedIntArray(std::istream& is, int n) {
	IV ret(n);
	auto* dst = ret.data();
	while(n > 0) {
		--n;
		is >> *dst++;
	}
	return ret;
}

#define _For(idx, from, to, inc, cmp) \
	for(auto idx=(from) ; idx cmp (to) ; inc idx)
#define ForLE(idx, from, to) \
	_For(idx, from, to, ++, <=)
#define ForGE(idx, from, to) \
	_For(idx, from, to, --, >=)
#define ForLT(idx, from, to) \
	_For(idx, from, to, ++, <)
#define ForGT(idx, from, to) \
	_For(idx, from, to, --, >)
#define For(idx, from, to) \
	_For(idx, from, to, ++, <)
#define Assert(expr) if(!(expr)) {__builtin_trap();}

void DisableIOSync() {
	std::cin.tie(0);
	std::cout.tie(0);
	std::ios::sync_with_stdio(false);
}
struct Node {
	using Link = std::vector<std::pair<Node*, int>>;
	Link	link;
	uint64_t toKCost;
};

#include <unordered_set>
std::unordered_set<Node*> Used;
void CalcCost(Node* node, const uint64_t cost) {
	if(Used.count(node) != 0)
		return;
	Used.emplace(node);
	node->toKCost = cost;
	for(auto& nd : node->link) {
		CalcCost(nd.first, cost + nd.second);
	}
}
int main() {
	DisableIOSync();

	const int N = ToFixedIntArray(std::cin, 1)[0];
	std::vector<Node> node(N);
	For(i, 0, N-1) {
		const auto inp = ToFixedIntArray(std::cin, 3);
		const int i0 = inp[0]-1,
				i1 = inp[1]-1;
		const int cost = inp[2];
		node[i0].link.emplace_back(&node[i1], cost);
		node[i1].link.emplace_back(&node[i0], cost);
	}
	const auto qk = ToFixedIntArray(std::cin, 2);
	const auto Q = qk[0],
				K = qk[1]-1;

	CalcCost(&node[K], 0);
	For(i, 0, Q) {
		const auto query = ToFixedIntArray(std::cin, 2);
		std::cout << node[query[0]-1].toKCost + node[query[1]-1].toKCost << "\n";
	}
	std::cout.flush();
	return 0;
}

Score : 400 points

Problem Statement

You are given a tree with N vertices.

Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.

The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.

You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):

find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.

Constraints

3≤N≤10^5

1≤a_i,b_i≤N (1≤i≤N-1)

1≤c_i≤10^9 (1≤i≤N-1)

The given graph is a tree.

1≤Q≤10^5

1≤K≤N

1≤x_j,y_j≤N (1≤j≤Q)

x_j≠y_j (1≤j≤Q)

x_j≠K,y_j≠K (1≤j≤Q)

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}

Output

Print the responses to the queries in Q lines.

In the j-th line j(1≤j≤Q), print the response to the j-th query.

Sample Input 1

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

Sample Output 1

3
2
4

The shortest paths for the three queries are as follows:

Query 1: Vertex 2 → Vertex 1 → Vertex 2 → Vertex 4 : Length 1+1+1=3

Query 2: Vertex 2 → Vertex 1 → Vertex 3 : Length 1+1=2

Query 3: Vertex 4 → Vertex 2 → Vertex 1 → Vertex 3 → Vertex 5 : Length 1+1+1+1=4

Sample Input 2

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

Sample Output 2

5
14
22

The path for each query must pass Vertex K=2.

Sample Input 3

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

Sample Output 3

17000000000


#include<cstdio>
using namespace std;
int n,m;
int main()
{
	scanf("%d%d",&n,&m);
	printf("%d\n",(n-1)*(m-1));
	return 0;
}

Score : 100 points

Problem Statement

In K-city, there are n streets running east-west, and m streets running north-south. Each street running east-west and each street running north-south cross each other. We will call the smallest area that is surrounded by four streets a block. How many blocks there are in K-city?

Constraints

2 ≤ n, m ≤ 100

Input

Input is given from Standard Input in the following format:

n m

Output

Print the number of blocks in K-city.

Sample Input 1

3 4

Sample Output 1

6

There are six blocks, as shown below:

Sample Input 2

2 2

Sample Output 2

1

There are one block, as shown below:


#include "bits/stdc++.h"
using namespace std;
const int MOD = 1e9 + 7;
typedef long long lint;
const int INF =1e7;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define trep(i, k, n) for (int i = (k); i < (int)(n); ++i)
typedef pair<int,int> P;
typedef vector<int> vi;
typedef vector<vi> vvi;
int main(){
    string s;
    cin >> s;
    cout << s[0] << s.size() - 2 << s[s.size()-1] << endl;
    return 0;
}

Score : 200 points

Problem Statement

The word internationalization is sometimes abbreviated to i18n.
This comes from the fact that there are 18 letters between the first i and the last n.

You are given a string s of length at least 3 consisting of lowercase English letters.
Abbreviate s in the same way.

Constraints

3 ≤ |s| ≤ 100 (|s| denotes the length of s.)

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the abbreviation of s.

Sample Input 1

internationalization

Sample Output 1

i18n

Sample Input 2

smiles

Sample Output 2

s4s

Sample Input 3

xyz

Sample Output 3

x1z


#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
int a[10005],x[105][105];
int h,w,n;
int main(){
	scanf("%d%d",&h,&w);
	scanf("%d",&n);
	for (int i=1;i<=n;i++) scanf("%d",&a[i]);
	int t=1;
	for (int i=1;i<=h;i++){
		if (i%2) {
			for (int j=1;j<=w;j++) {
				if (!a[t]) t++;
				x[i][j]=t,a[t]--;
			}
		}
		else for (int j=w;j>=1;j--) {
				if (!a[t]) t++;
				x[i][j]=t,a[t]--;
			}
	}
	for (int i=1;i<=h;i++){
		for (int j=1;j<=w;j++) printf("%d ",x[i][j]);
		printf("\n");
	}
	return 0;
}

Score : 400 points

Problem Statement

We have a grid with H rows and W columns of squares.
Snuke is painting these squares in colors 1, 2, ..., N.
Here, the following conditions should be satisfied:

For each i (1 ≤ i ≤ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W.

For each i (1 ≤ i ≤ N), the squares painted in Color i are 4-connected. That is, every square painted in Color i can be reached from every square painted in Color i by repeatedly traveling to a horizontally or vertically adjacent square painted in Color i.

Find a way to paint the squares so that the conditions are satisfied.
It can be shown that a solution always exists.

Constraints

1 ≤ H, W ≤ 100

1 ≤ N ≤ H W

a_i ≥ 1

a_1 + a_2 + ... + a_N = H W

Input

Input is given from Standard Input in the following format:

H W
N
a_1 a_2 ... a_N

Output

Print one way to paint the squares that satisfies the conditions.
Output in the following format:

c_{1 1} ... c_{1 W}
:
c_{H 1} ... c_{H W}

Here, c_{i j} is the color of the square at the i-th row from the top and j-th column from the left.

Sample Input 1

2 2
3
2 1 1

Sample Output 1

1 1
2 3

Below is an example of an invalid solution:

1 2
3 1

This is because the squares painted in Color 1 are not 4-connected.

Sample Input 2

3 5
5
1 2 3 4 5

Sample Output 2

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

Sample Input 3

1 1
1
1

Sample Output 3

1


#include <bits/stdc++.h>
using namespace std;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1;} return 0;}
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1;} return 0;}
const long long INFLL = 1LL<<60;
const int INF = 1<<28;
const long long MOD =1000000000+7;
void solve(int a){cout<<( a?"Yes":"No")<<endl;}

int main()
{
	int h,w,n;
	cin >> h >> w>> n;
	int count=0;
	int at=0;
	vector<int>a(n+1,0);
	vector<int> t(n + 1, 0);
	vector<vector<int>>ans(h+1,vector<int>(w+1,0));
	for(int i=0; i<n;i++){
		cin >>a[i];
		t[i]=a[i]+(i==0?0:a[i-1]);
	}
	for(int a=0;a<h;a++){
		for(int b=0;b<w;b++){
			if(a%2==0){
				ans[a][b]=at+1;
			}else{
				ans[a][w-b-1]=at+1;
			}
			count++;
			if(count >=t[at]){
				at++;
			}
		}
	}
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
		cout << ans[i][j]<<((j==w-1)?"\n":" ");

		}

	}
}


/**
 * Copyright (c) 2017, xehoth
 * All rights reserved.
 * 「ARC 080E」Young Maids 26-08-2017
 * 线段树 + 堆
 * @author xehoth
 */
#include <bits/stdc++.h>

namespace Task {

const int MAXN = 100000;

int M;

inline void init(const int n) {
    for (M = 1; M < n + 2; M <<= 1)
        ;
}

struct SegmentTree {
    int d[MAXN * 4];

    inline void maintain(int k) { d[k] = std::min(d[k << 1], d[k << 1 | 1]); }

    inline void build() {
        for (register int i = M - 1; i; i--) maintain(i);
    }

    inline int query(int s, int t) const {
        register int ret = INT_MAX;
        for (s = s + M - 1, t = t + M + 1; s ^ t ^ 1; s >>= 1, t >>= 1) {
            (~s & 1) ? ret = std::min(ret, d[s ^ 1]) : 0;
            (t & 1) ? ret = std::min(ret, d[t ^ 1]) : 0;
        }
        return ret;
    }
};

SegmentTree even, odd;

int a[MAXN + 1], pos[MAXN + 1];

struct Node {
    int l, r, x;

    Node(int l, int r, int x) : l(l), r(r), x(x) {}

    inline bool operator<(const Node &b) const { return x > b.x; }
};

template <typename T>
class PriorityQueue : public std::priority_queue<T> {
   private:
#define super std::priority_queue<T>
   public:
    inline void reserve(const int n) { super::c.reserve(n); }
#undef super
};

inline void initRmq(const int n, const int *a) {
    init(n);
    for (register int i = 1; i <= n; i++) {
        if (i & 1) {
            odd.d[M + i] = a[i], even.d[M + i] = INT_MAX;
        } else {
            even.d[M + i] = a[i], odd.d[M + i] = INT_MAX;
        }
    }
    even.build(), odd.build();
}

inline void solve() {
    std::ios::sync_with_stdio(false), std::cin.tie(NULL), std::cout.tie(NULL);
    register int n;
    std::cin >> n;
    for (register int i = 1; i <= n; i++) std::cin >> a[i], pos[a[i]] = i;
    initRmq(n, a);
    static PriorityQueue<Node> q;
    q.reserve(n * 2);
    q.push(Node(1, n, odd.query(1, n)));
    const SegmentTree *t[2] = {&even, &odd};
    while (!q.empty()) {
        Node d = q.top();
        q.pop();
        register int l = d.l, r = d.r;
        register int p1 = pos[d.x], p2 = pos[t[~p1 & 1]->query(p1 + 1, r)];
        std::cout << a[p1] << ' ' << a[p2] << ' ';
        if (l < p1) q.push(Node(l, p1 - 1, t[l & 1]->query(l, p1 - 1)));
        if (p1 < p2 - 1)
            q.push(Node(p1 + 1, p2 - 1, t[~p1 & 1]->query(p1 + 1, p2 - 1)));
        if (p2 < r) q.push(Node(p2 + 1, r, t[~p2 & 1]->query(p2 + 1, r)));
    }
}
}

int main() {
    Task::solve();
    return 0;
}

Score : 800 points

Problem Statement

Let N be a positive even number.

We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N).
Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.

First, let q be an empty sequence.
Then, perform the following operation until p becomes empty:

Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.

When p becomes empty, q will be a permutation of (1, 2, ..., N).

Find the lexicographically smallest permutation that can be obtained as q.

Constraints

N is an even number.

2 ≤ N ≤ 2 × 10^5

p is a permutation of (1, 2, ..., N).

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print the lexicographically smallest permutation, with spaces in between.

Sample Input 1

4
3 2 4 1

Sample Output 1

3 1 2 4

The solution above is obtained as follows:

p

q

(3, 2, 4, 1)

()

↓

↓

(3, 1)

(2, 4)

↓

↓

()

(3, 1, 2, 4)

Sample Input 2

2
1 2

Sample Output 2

1 2

Sample Input 3

8
4 6 3 2 8 5 7 1

Sample Output 3

3 1 2 7 4 6 8 5

The solution above is obtained as follows:

p

q

(4, 6, 3, 2, 8, 5, 7, 1)

()

↓

↓

(4, 6, 3, 2, 7, 1)

(8, 5)

↓

↓

(3, 2, 7, 1)

(4, 6, 8, 5)

↓

↓

(3, 1)

(2, 7, 4, 6, 8, 5)

↓

↓

()

(3, 1, 2, 7, 4, 6, 8, 5)


#include <stdio.h>
#include <iostream>
#include <queue>
#include <string>
#include <algorithm>
#include <cstdio>
#include <stack>
#include <vector>
#include <map>
#include <ctime>
#include <cmath>
#include <string.h>
#define inf 0x7fffffff
using namespace std;
struct I
{
    int x,y;
};

int a,b,c,k,n,m,i,e,d,o[211010],l[200212],dx[20]={1,0,-1,0},dy[20]={0,1,0,-1},dz[20]={1,-1};
long long x,y,z[110];
//map <string,int> m;
int j[1060];

stack<int> s;
//char r[55];
//deque<int> d;
struct P
{
    int x,y,z;
    bool operator<(const P &a)const
    {

        return z<a.z;
    }
};
double u;
//P u[500000];
vector <int> v[211010];
priority_queue<P> q;
string r,r1[100];
map<string,int > p;
//A==65
//Z==90

//a==97

void f()
{
    for(;q.size()&&(l[q.top().x]==0||l[q.top().y]==0);q.pop());
    if(q.size()==0) return;
    P u=q.top();
    q.pop();
    l[u.x]=0;
    l[u.y]=0;
    if(u.x>1&&u.y<a)
    q.push({u.x-1,u.y+1,o[u.x-1]+o[u.x+1]});
    f();
    printf("%d %d ",o[u.x],o[u.y]);
}

int main()
{
    scanf("%d",&a);
    for(int t=1;t<=a;l[t]=1,t++)
        scanf("%d",&o[t]);
    for(int t=2;t<=a;t++)
    {
        q.push({t-1,t,o[t]+o[t-1]});
    }
    f();
}