/****************************************

			LostMartian

****************************************/
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimize("Ofast")
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <functional>
#include <utility>
#include <climits>
#include <numeric>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <cassert>
using namespace std;
typedef long long ll;

template <typename Arg1>
void pn(Arg1&& arg1) {
	cout << arg1 << "\n";
}
template <typename Arg1, typename... Args>
void pn(Arg1&& arg1, Args&&... args) {
	cout << arg1 << " ";
	pn(args...);
}
template <typename Arg1>
void ps(Arg1&& arg1) {
	cout << arg1 << " ";
}
template <typename Arg1, typename... Args>
void ps(Arg1&& arg1, Args&&... args) {
	cout << arg1 << " ";
	ps(args...);
}
template <typename Arg1>
void read(Arg1&& arg1) {
	cin >> arg1;
}
template <typename Arg1, typename... Args>
void read(Arg1&& arg1, Args&&... args) {
	cin >> arg1;
	read(args...);
}

#define rep(i,m,n) for(ll i=m; i<n; i++)
#define repr(i,m,n) for(ll i=m; i>=n; i--)
#define vll vector<ll >
#define vvl vector<vector<ll > >
#define pi pair<ll, ll >
#define vpi vector<pi >
#define umap unordered_map<ll, ll >
#define pb push_back
#define mk make_pair
#define sz size()
#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define test ll t; cin>>t; while(t--)
#define ini(a, x) memset(a, x, sizeof(a))
#define d(x) cout<<"Value of "#x" = "<<x<<"\n";
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#define iAmSpeed ios_base::sync_with_stdio(false); cin.tie(NULL);
void LOCAL();
int main()
{
	clock_t z = clock();
	//LOCAL();
	iAmSpeed
	ll x, k, d;
	cin>>x>>k>>d;
	ll m=abs(x)/d;
	if(m>=k) {
		if(x<0) {
			pn(-x-d*k);
			return 0;
		}
		else {
			pn(x-d*k);
			return 0;
		}
	}
	if(x<0) {
		x+=m*d;
		k-=m;
		if(!(k&1)) {
			pn(min(-x,x+d));
		}
		else {
			pn(min(abs(d-x), abs(-x-d)));
		}
	}
	else {
		x-=m*d;
		k-=m;
		if(!(k&1)) {
			pn(min(x, d-x));
		}
		else {
			pn(min(abs(d+x), abs(x-d)));
		}

	}

	debug("Total Time: %.7f\n", (double)(clock() - z) / CLOCKS_PER_SEC);
	return 0;
}
void LOCAL() {
	#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
	#endif
}


#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
#define PI acos(-1)
typedef  long long ll;
ll gcd(ll x,ll y){
   if(y==0) return x;
   else return gcd(y,x%y);
}
ll lcm(ll x,ll y){
   return x/gcd(x,y)*y;
}

int main(){
   ll x,k,d;
   cin>>x>>k>>d;
   ll ans=10000000000000000;
      ll a=-x/(2*d)+k/2;

   for(ll i=a-10000;i<a+10000;i++){
      if(i<0){
         continue;
      }
      ll y=x+(2*i-k)*d;
      ll z=abs(y);
      if((y-x)/d!=(2*i-k)){
         continue;
      }
      ans=min(ans,z);
   }

   cout<<ans<<endl;
   return 0;
}

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

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.

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 <vector>
#include <cmath>

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

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main()
{
  long long X, K, D;
  cin >> X >> K >> D;

  if (X >= K * D)
  {
    cout << X - K * D << endl;
  }
  else
  {
    int div = X / D;
    K -= div;
    X -= div * D;
    if (K % 2 == 0)
    {
      cout << X << endl;
    }
    else
    {
      cout << std::abs(X - D) << endl;
    }
  }

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define INF 1e9
#define PI 3.14159265359
#define MOD 1000000007
#define ALL(v) v.begin(),v.end()
#define ALLR(v) v.rbegin(),v.rend()
#define F first
#define S second
typedef long long ll;
const int dx[4] = {1,0,-1,0};
const int dy[4] = {0,1,0,-1};
//isPrime
//modpow modinv
//getDigit
template<class T> inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
template<class T> inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
int main() {
  cout << fixed << setprecision(10);
  int n,k;
  cin >> n >> k;
  vector<ll> p(n),c(n);
  rep(i,n) cin >> p[i];
  rep(i,n) p[i]--;
  rep(i,n) cin >> c[i];
  vector<vector<int>> a;
  map<int,int> mp;
  rep(i,n){
    if(mp[i]!=0)continue;
    mp[i]++;
    int q = i;
    vector<int> b;
    rep(j,n){
      b.push_back(c[q]);
      q=p[q];
      if(mp[q]!=0){
        break;
      }
      mp[q]++;
    }
    a.push_back(b);
  }
  ll t = -1e18;
  for(auto b:a){
    int m = b.size();
    vector<ll> d(2*m+1);
    rep(i,m){
      d[i+1]=d[i]+b[i];
    }
    rep(i,m){
      d[i+m+1]=d[i+m]+b[i];
    }
    ll res = 0;
    if((d[m]-d[0])>=0){
      if(k%m==0&&k>=m){
        res+=(k/m-1)*(d[m]-d[0]);
      }else{
        res += (k/m)*(d[m]-d[0]);
      }
    }else{
      res = 0;
    }

    int k1;
    if(k%m==0&&k>=m){
      k1=m;
    }else{
      k1=k%m;
    }
    ll ans = -1e18;
    for(int add=1; add<=k1; add++){
      for(int i=0; i+add<2*m+1; i++){
        ans = max(ans,d[i+add]-d[i]);
      }
    }
    t = max(t,ans+res);
  }
  cout << t << endl;

}

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


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

const int Sz = 3e3 + 3;
using ii = pair<int,int>;

int n, m, k;
int x, y, z;
int val = 0;
int f[Sz][Sz][4];
int a[Sz][Sz];
int dp(int row, int col, int cnt){
    if(row > n || col > m) return 0;
    int &res = f[row][col][cnt];
    if(res != -1) return res;
    res = dp(row + 1, col, 0);
    if(cnt < 3) res += a[row][col];
    if(cnt < 3){
    if(a[row][col] != 0)
        res = max(res, dp(row, col + 1, cnt + 1) + a[row][col]);
        res = max(res, dp(row, col + 1, cnt));
    }
    //cout << row << " " << col << " " << res << '\n';
    return res;
}
void trace(int row, int col, int cnt){
    if(row > n || col > m) return ;
    if(f[row][col][cnt] == f[row + 1][col][0]) return trace(row + 1, col, 0);
    if(f[row][col][cnt] == f[row][col + 1][cnt]) return trace(row, col + 1, cnt);
    cout << row << " " << col << '\n';
    return trace(row, col + 1, cnt + 1);
}
int32_t main()
{
    //freopen("inp.txt" , "r", stdin);
    //freopen("out.txt", "w", stdout);
    memset(f, -1, sizeof f);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m >> k;
    while(k--){
        cin >> x >> y >> z;
        a[x][y] = z;
    }
    cout << dp(1, 1, 0);
    return 0;
}

Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

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

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

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

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142


#include <bits/stdc++.h>

using namespace std;

int n;
string s[54];
long long c[54];
long long dist[54][2][24];
priority_queue<pair<long long, pair<int, pair<int, int>>>> pq;
vector<long long> ans;

void solve(){
    cin>>n;
    memset(dist, -1, sizeof(dist));
    for(int i = 0; i < n; i++){
        cin>>s[i]>>c[i];
        dist[i][0][s[i].length()] = c[i];
        pq.push({-c[i], {i, {0, s[i].length()}}});
    }
    while(!pq.empty()){
        pair<long long, pair<int, pair<int, int>>> now = pq.top();
        pq.pop();
        long long cost = -now.first;
        int idx = now.second.first;
        int dir = now.second.second.first;
        int rem = now.second.second.second;
        if(cost > dist[idx][dir][rem])  continue;
        if(dir == 0){
            for(int nextIdx = 0; nextIdx < n; nextIdx++){
                const int L = s[idx].length();
                const int R = s[nextIdx].length();
                bool can = true;
                int lRem = rem, rRem = R;
                while(lRem && rRem){
                    if(s[idx][L-lRem] != s[nextIdx][rRem-1])  can = false;
                    lRem--;
                    rRem--;
                }
                if(!can)    continue;
                long long nextCost = cost + c[nextIdx];
                if(lRem + rRem <= 1){
                    ans.push_back(nextCost);
                    continue;
                }
                if(lRem && (dist[idx][0][lRem] > nextCost || dist[idx][0][lRem] == -1)){
                    dist[idx][0][lRem] = nextCost;
                    pq.push({-nextCost, {idx, {0, lRem}}});
                }
                if(rRem && (dist[nextIdx][1][rRem] > nextCost || dist[nextIdx][1][rRem] == -1)){
                    dist[nextIdx][1][rRem] = nextCost;
                    pq.push({-nextCost, {nextIdx, {1, rRem}}});
                }
            }
        }
        else {
            for(int nextIdx = 0; nextIdx < n; nextIdx++){
                const int L = s[nextIdx].length();
                const int R = s[idx].length();
                bool can = true;
                int lRem = L, rRem = rem;
                while(lRem && rRem){
                    if(s[nextIdx][L-lRem] != s[idx][rRem-1])  can = false;
                    lRem--;
                    rRem--;
                }
                if(!can)    continue;
                long long nextCost = cost + c[nextIdx];
                if(lRem + rRem <= 1){
                    ans.push_back(nextCost);
                    continue;
                }
                if(lRem && (dist[nextIdx][0][lRem] > nextCost || dist[nextIdx][0][lRem] == -1)){
                    dist[nextIdx][0][lRem] = nextCost;
                    pq.push({-nextCost, {nextIdx, {0, lRem}}});
                }
                if(rRem && (dist[idx][1][rRem] > nextCost || dist[idx][1][rRem] == -1)){
                    dist[idx][1][rRem] = nextCost;
                    pq.push({-nextCost, {idx, {1, rRem}}});
                }
            }
        }
    }
    if(ans.size() == 0) cout<<-1<<endl;
    else
    {
        cout<<*min_element(ans.begin(), ans.end());
    }

}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int TC;
    //cin>>TC;
    TC=1;
    while(TC--){
        solve();
    }
}

Score : 600 points

Problem Statement

We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N.

Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice.

The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times.

Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome.

If there is no choice of strings in which he can make a palindrome, print -1.

Constraints

1 \leq N \leq 50

1 \leq |S_i| \leq 20

S_i consists of lowercase English letters.

1 \leq C_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
S_1 C_1
S_2 C_2
:
S_N C_N

Output

Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice.

Sample Input 1

3
ba 3
abc 4
cbaa 5

Sample Output 1

7

We have ba, abc, and cbaa.

For example, we can use ba once and abc once for a cost of 7, then concatenate them in the order abc, ba to make a palindrome.
Also, we can use abc once and cbaa once for a cost of 9, then concatenate them in the order cbaa, abc to make a palindrome.

We cannot make a palindrome for a cost less than 7, so we should print 7.

Sample Input 2

2
abcab 5
cba 3

Sample Output 2

11

We can choose abcab once and cba twice, then concatenate them in the order abcab, cba, cba to make a palindrome for a cost of 11.

Sample Input 3

4
ab 5
cba 3
a 12
ab 10

Sample Output 3

8

We can choose a once, which is already a palindrome, but it is cheaper to concatenate ab and cba.

Sample Input 4

2
abc 1
ab 2

Sample Output 4

-1

We cannot make a palindrome, so we should print -1.


#include "bits/stdc++.h"

using namespace std;
typedef long long ll;
typedef vector<ll> vll;
#define int ll
typedef pair<int,int> pii;
#define fi first
#define se second
#define Sort(a) sort(a.begin(),a.end())
#define rep(i,n) for(int i = 0;i < (n) ; i++)
#define REP(i,n) for(int i = 0;i < (n) ; i++)
#define MP(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define INF LLONG_MAX/4
#define INTINF INT_MAX/2
#define all(x) (x).begin(),(x).end()
#define debug(x) cerr<<#x<<": "<<x<<endl
#define debug_vec(v) cerr<<#v<<":";rep(i,v.size())cerr<<" "<<v[i];cerr<<endl
template<class T> inline bool chmax(T &a, T b){if(a < b){a = b;return true;}return false;}
template<class T> inline bool chmin(T &a, T b){if(a > b){a = b;return true;}return false;}
/*----------------------------------------------------------------*/
// const int MOD = 998244353;
// const int MOD = 1000000007;
vector<pii> p;
/*----------------------------------------------------------------*/
signed main(){

	int n;
	cin >> n;
	int cnt[300][300] = {};
	rep(i,n){
		string a;
		cin >> a;
		// cerr << a << endl;
		int m = a.size();
		int z = 0;
		int f = 0;
		int x2 = 0;
		int x5 = 0;

		rep(j,m){
			if(a[m-1-j] == '.'){
				f = 1;
				a.erase(m-1-j,1);
				break;
			}else{
				z++;
			}
		}
		if(f==0)z = 0;

		x2 = -z;
		x5 = -z;
		cerr << a << endl;
		int A = stoll(a);
		while(A%2 == 0){
			A /= 2;
			x2++;
		}
		while(A%5 == 0){
			A /= 5;
			x5++;
		}
		p.push_back(MP(x2,x5));
		// cerr << x2 <<" " << x5 << endl;
		cnt[x2+150][x5+150]++;
	}

	int s[310][310] = {};
	rep(i,301)rep(j,301)s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + cnt[i][j];

	int ans = 0;
	rep(i,n){
		int x2 = p[i].first;
		int x5 = p[i].second;
		// cerr << x2 << " " << x5 << endl;
		int y2 = 150-x2;
		int y5 = 150-x5;
		int pl = s[300][300]-s[y2][300]-s[300][y5]+s[y2][y5];
		if(x2>=0&&x5>=0)pl--;
		ans += pl;
		// cerr << x2 <<" " << x5 << " : " << pl << endl;
	}
	cout << ans/2 << endl;

	return 0;
}
/*----------------------------------------------------------------*/

// g++ -std=gnu++17 code1.cpp
// sudo pip3 install --upgrade online-judge-tools
// rm -r -f test;oj dl https://abc174.contest.atcoder.jp/tasks/abc174_b
// rm -r -f test;oj d https://atcoder.jp/contests/agc047/tasks/agc047_a

Score : 300 points

Problem Statement

You are given N real values A_1, A_2, \ldots, A_N.
Compute the number of pairs of indices (i, j)
such that i < j and the product A_i \cdot A_j is integer.

Constraints

2 \leq N \leq 200\,000

0 < A_i < 10^4

A_i is given with at most 9 digits after the decimal.

Input

Input is given from Standard Input in the following format.

N
A_1
A_2
\vdots
A_N

Output

Print the number of pairs with integer product A_i \cdot A_j (and i < j).

Sample Input 1

5
7.5
2.4
17.000000001
17
16.000000000

Sample Output 1

3

There are 3 pairs with integer product:

7.5 \cdot 2.4 = 18

7.5 \cdot 16 = 120

17 \cdot 16 = 272

Sample Input 2

11
0.9
1
1
1.25
2.30000
5
70
0.000000001
9999.999999999
0.999999999
1.000000001

Sample Output 2

8


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double lld;
ll MOD = (1e9)+7;
const int dr[] = {+1, -1, +0, +0, +1, -1, +1, -1};
const int dc[] = {+0, +0, +1, -1, +1, -1, -1, +1};
const int kx[] = {+1, +2, -1, -2, +1, +2, -1, -2};
const int ky[] = {+2, +1, +2, +1, -2, -1, -2, -1};
//#pragma GCC target ("avx2")
//#pragma GCC optimization ("O3")
//#pragma GCC optimization ("unroll-loops")
inline void fastIO(){
  ios_base::sync_with_stdio(0);cin.tie(0);
}
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template<typename T, size_t size> ostream& operator<<(ostream &os, const array<T, size> &arr) { os << '{'; string sep; for (const auto &x : arr) os << sep << x, sep = ", "; return os << '}'; }
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }

void debug_out() { cerr << endl; }
template<typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << ' ' << H; debug_out(T...); }

#ifdef LOCAL
#define debug(...) cerr << "(" << #__VA_ARGS__ << "):", debug_out(__VA_ARGS__)
#else
#define debug(...) 47
#endif
const ll MAXN=5050;

int main(){
  fastIO();
  int x;
  cin>>x;
  if(x>=30){
    cout<<"Yes"<<endl;
  }else{
    cout<<"No"<<endl;
  }
  return 0;
}

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


#include <iostream>
using namespace std;

int main()
{
	int X;
	cin >> X;
	if (X < 30) {
		cout << "Yes" << endl;
	}
	else cout << "No" << endl;

}


#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define int long long
#define pb push_back
#define ff first
#define ss second

bool isvalid(int x,int y,int n,int m)
{
    return (x>=0 && x<n && y>=0 && y<m);
}

int cx[]={0,0,1,1,1,-1,-1,-1};
int cy[]={1,-1,1,0,-1,1,0,-1};

int32_t main()
{
    IOS;
	int t;
	cin>>t;
	while(t--)
	{
	    int n;
	    cin>>n;
	    if(n>=30)
	    cout<<"YES"<<endl;
	    else
	    cout<<"NO"<<endl;

	}
	return 0;
}


#include<iostream>
using namespace std;
const int BUF = 200005;

int N, D;
int pt[BUF][2];

void read() {
    cin >> N >> D;
    for (int i = 0; i < N; ++i) {
        cin >> pt[i][0] >> pt[i][1];
    }
}

void work() {
    int cnt = 0;
    for (int i = 0; i < N; ++i) {
        cnt += 1LL * pt[i][0] * pt[i][0] + 1LL * pt[i][1] * pt[i][1] <= 1LL * D * D;
    }
    cout << cnt << endl;
}

int main() {
    read();
    work();
    return 0;
}

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

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

0 \leq D \leq 2\times 10^5

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


#include<bits/stdc++.h>
using namespace std;
//#pragma gcc optimize("O3")
//#pragma gcc optimize("unroll-loops")
#ifdef EVAH
    #define _WIN32_WINNT 0x0500
    #include<windows.h>
#endif
#define openFile(n) ShellExecute(nullptr,"open",n,nullptr,nullptr,SW_SHOWNORMAL);
#define closeP(n) system((string("taskkill /im ")+n+" /f").c_str());
#define closeConsole PostMessage(GetConsoleWindow(), WM_CLOSE, 0, 0);
#define opf "output.txt"
#define ipf "input.txt"
#define mem(n,x) memset(n,x,sizeof(n));
#define sf scanf
#define pf printf
#define ff first
#define ss second
#define pb push_back
#define PII pair<int,int>
#define For(x,n) for(int i=x; i<n; i++)
#define stv v+2*(mid-tl+1)
#define LL long long int
#define PI acos(-1.0)
#define N 100000000

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    #ifdef EVAH
        //freopen(ipf,"r",stdin);
        //openFile(ipf);
        //closeConsole;
        //freopen(opf,"w",stdout);
    #endif

    LL n,d,x,y,cnt=0;
    cin >> n >> d;
    while(n-- > 0) {
        cin >> x >> y;
        if(sqrt(x*x+y*y)<=d) cnt++;
    }
    cout << cnt << "\n";

    #ifdef EVAH
        //openFile(opf);
        //Sleep(3000);
        //closeP("notepad.exe");
        //closeConsole;
    #endif
}


Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<queue>
#include<deque>
#include<cmath>
#include<map>
#include<unordered_map>
#include<set>
#include<cstring>
#include<iomanip> //cout << fixed << setprecision(15) << x << endl;

using namespace std;
typedef long long ll;
const ll INF = 1e9 + 8;
const ll MOD = 1e9 + 7;
const ll LLINF = 1e18;
#define Pint pair<int, int>
#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rnr(i,a,b) for(int i=int(a);i>=int(b);i--)
#define rep(i,b) rng(i,0,b)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
/* -- template -- */

int main() {
    int x; cin >> x;
    for(int i = 0; i < 8; ++i) {
        if(x < 600 + 200 * i) {
            cout << 8 - i << endl;
            return 0;
        }
    }
}

Score: 100 points

Problem Statement

M-kun is a competitor in AtCoder, whose highest rating is X.

In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:

From 400 through 599: 8-kyu

From 600 through 799: 7-kyu

From 800 through 999: 6-kyu

From 1000 through 1199: 5-kyu

From 1200 through 1399: 4-kyu

From 1400 through 1599: 3-kyu

From 1600 through 1799: 2-kyu

From 1800 through 1999: 1-kyu

What kyu does M-kun have?

Constraints

400 \leq X \leq 1999

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the kyu M-kun has, as an integer.
For example, if he has 8-kyu, print 8.

Sample Input 1

725

Sample Output 1

7

M-kun's highest rating is 725, which corresponds to 7-kyu.

Thus, 7 is the correct output.

Sample Input 2

1600

Sample Output 2

2

M-kun's highest rating is 1600, which corresponds to 2-kyu.

Thus, 2 is the correct output.


#include<cstdio>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<unordered_map>
#include<stack>
#include<string>
#include<algorithm>
#include<functional>
#include<cstring>
#include<complex>
#include<bitset>
#include<iostream>
#include<cassert>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
typedef pair<ll, P> Q;
typedef complex<double> C;
#define cx real()
#define cy imag()
const ll INF = 1LL << 60;
const double DINF = 1e30;
const ll mod = 1000000007;
const ll dx[4] = {1, 0, -1, 0};
const ll dy[4] = {0, -1, 0, 1};
const C I = C(0, 1);
const double EPS = 1e-10;
const ll NCK_MAX = 510000;

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

ll extgcd(ll a, ll b, ll& x, ll& y) {
  if (b == 0) {
    x = 1, y = 0; return a;
  }
  ll q = a/b, g = extgcd(b, a - q*b, x, y);
  ll z = x - q * y;
  x = y;
  y = z;
  return g;
}

ll invmod (ll a, ll m) { // a^-1 mod m
  ll x, y;
  extgcd(a, m, x, y);
  x %= m;
  if (x < 0) x += m;
  return x;
}

ll *fac, *finv, *inv;

void nCk_init(ll mod) {
  fac = new ll[NCK_MAX];
  finv = new ll[NCK_MAX];
  inv = new ll[NCK_MAX];
  fac[0] = fac[1] = 1;
  finv[0] = finv[1] = 1;
  inv[1] = 1;
  for (ll i = 2; i < NCK_MAX; i++) {
    fac[i] = fac[i-1] * i % mod;
    inv[i] = mod - inv[mod%i] * (mod / i) % mod;
    finv[i] = finv[i-1] * inv[i] % mod;
  }
}

ll nCk(ll n, ll k, ll mod) {
  if (fac == NULL) nCk_init(mod);
  if (n < k) return 0;
  if (n < 0 || k < 0) return 0;
  return fac[n] * (finv[k] * finv[n-k] % mod) % mod;
}

template <typename T>
class Zip {
  vector<T> d;
  bool flag;
  void init() {
    sort(d.begin(), d.end());
    d.erase(unique(d.begin(), d.end()), d.end());
    flag = false;
  }
public:
  Zip() {
    flag = false;
  }
  void add(T x) {
    d.push_back(x);
    flag = true;
  }
  ll getNum(T x) {
    if (flag) init();
    return lower_bound(d.begin(), d.end(), x) - d.begin();
  }
  ll size() {
    if (flag) init();
    return (ll)d.size();
  }
};

class UnionFind {
  vector<ll> par, rank; // par > 0: number, par < 0: -par
public:
  UnionFind(ll n) : par(n, 1), rank(n, 0) {}
  ll getSize(ll x) {
    return par[find(x)];
  }
  ll find(ll x) {
    if (par[x] > 0) return x;
    return -(par[x] = -find(-par[x]));
  }
  void merge(ll x, ll y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (rank[x] < rank[y]) {
      par[y] += par[x];
      par[x] = -y;
    } else {
      par[x] += par[y];
      par[y] = -x;
      if (rank[x] == rank[y]) rank[x]++;
    }
  }
  bool isSame(ll x, ll y) {
    return find(x) == find(y);
  }
};

template <typename T>
class SegmentTree {
  ll n;
  vector<T> node;
  function<T(T, T)> fun, fun2;
  bool customChange;
  T outValue, initValue;
public:
  void init(ll num, function<T(T, T)> resultFunction, T init, T out, function<T(T, T)> changeFunction = NULL) {
    // changeFunction: (input, beforevalue) => newvalue
    fun = resultFunction;
    fun2 = changeFunction;
    customChange = changeFunction != NULL;
    n = 1;
    while (n < num) n *= 2;
    node.resize(2 * n - 1);
    fill(node.begin(), node.end(), init);
    outValue = out;
    initValue = init;
  }
  void valueChange(ll num, T value) {
    num += n-1;
    if (customChange) node[num] = fun2(value, node[num]);
    else node[num] = value;
    while (num > 0) num = (num - 1) / 2, node[num] = fun(node[num * 2 + 1], node[num * 2 + 2]);
  }
  T rangeQuery(ll a, ll b, ll l = 0, ll r = -1, ll k = 0) { // [a, b)
    if (r == -1) r = n;
    if (a <= l && r <= b) return node[k];
    if (b <= l || r <= a) return outValue;
    ll mid = (l + r) / 2;
    return fun(rangeQuery(a, b, l, mid, 2*k+1), rangeQuery(a, b, mid, r, 2*k+2));
  }
};

template <typename T>
class Graph {
  struct edge { ll to; T cost; };
  struct edge_data { ll from, to; T cost; };

  ll v;
  vector<vector<edge>> e, re;
  vector<edge_data> ed;
  vector<bool> used;
  vector<ll> vs, cmp;
  bool isDirected, isMinasEdge;
public:
  Graph(ll _v, bool _isDirected = true, ll range_add = 0) {
    // range_add 0:no / 1:in / 2:out / 3:in+ut
    //_v++;
    v = _v, isDirected = _isDirected; isMinasEdge = false;
    e.resize(v), re.resize(v);
  }
  void add_edge(ll s, ll t, T cost = 1) {
    e[s].push_back((edge){t, cost});
    if (!isDirected) e[t].push_back((edge){s, cost});
    else re[t].push_back((edge){s, cost});
    ed.push_back((edge_data){s, t, cost});
    if (cost < 0) isMinasEdge = true;
  }
  vector<T> dijkstra(ll s) {
    vector<T> d(v, INF);
    d[s] = 0;
    auto edge_cmp = [](const edge& a, const edge& b) { return a.cost > b.cost; };
    priority_queue<edge, vector<edge>, decltype(edge_cmp)> pq(edge_cmp);
    pq.push((edge){s, 0});
    while (!pq.empty()) {
      edge temp = pq.top(); pq.pop();
      if (d[temp.to] < temp.cost) continue;
      for (const edge& next : e[temp.to]) {
        T cost = temp.cost + next.cost;
        if (d[next.to] > cost) {
          d[next.to] = cost;
          pq.push((edge){next.to, cost});
        }
      }
    }
    return d;
  }
  vector<T> bellmanford(ll s) {
    vector<T> d(v, INF);
    d[s] = 0;
    for (ll i = 0; i < v; i++) {
      for (const edge_data& temp : ed) {
        if (d[temp.from] != INF && d[temp.to] > d[temp.from] + temp.cost) d[temp.to] = d[temp.from] + temp.cost;
        if (!isDirected && d[temp.to] != INF && d[temp.from] > d[temp.to] + temp.cost) d[temp.from] = d[temp.to] + temp.cost;
      }
    }
    for (ll i = 0; i < v; i++) {
      for (const edge_data& temp : ed) {
        if (d[temp.from] != INF && d[temp.to] > d[temp.from] + temp.cost) d[temp.to] = -INF;
        if (!isDirected && d[temp.to] != INF && d[temp.from] > d[temp.to] + temp.cost) d[temp.from] = -INF;
      }
    }
    return d;
  }
  vector<T> shortest_path(ll s) {
    if (isMinasEdge) return bellmanford(s);
    else return dijkstra(s);
  }
  T kruskal() {
    // if (isDirected)
    UnionFind uf(v);
    auto edge_data_cmp = [](const edge_data& a, const edge_data& b) { return a.cost < b.cost; };
    sort(ed.begin(), ed.end(), edge_data_cmp);
    T ans = 0;
    for (const edge_data& temp : ed) {
      if (uf.isSame(temp.from, temp.to)) continue;
      uf.merge(temp.from, temp.to);
      ans += temp.cost;
    }
    return ans;
  }
  void scc_dfs(ll s) {
    used[s] = true;
    for (const edge& i : e[s]) if (!used[i.to]) scc_dfs(i.to);
    vs.push_back(s);
  }
  void scc_rdfs(ll s, ll k) {
    used[s] = true;
    cmp[s] = k;
    for (const edge& i : re[s]) if (!used[i.to]) scc_rdfs(i.to, k);
  }
  vector<ll> scc() {
    used.resize(v);
    fill(used.begin(), used.end(), false);
    cmp.resize(v);
    vs.clear();
    for (ll i = 0; i < v; i++) if (!used[i]) scc_dfs(i);
    used.resize(v);
    fill(used.begin(), used.end(), false);
    ll k = 0;
    for (ll i = vs.size() - 1; i >= 0; i--) if (!used[vs[i]]) scc_rdfs(vs[i], k++);
    return cmp;
  }
};

class RollingHash {
  int base;
  vector<__int128> hash;
  vector<__int128> pw;
  const __int128 hashmod = (1ull << 61) - 1;
public:
  RollingHash(string s, int base = 10007) : base(base), hash(s.length()+1, 0), pw(s.length()+1, 1) {
    for (int i = 0; i < (int)s.length(); i++) {
      hash[i+1] = (hash[i] * base + s[i]) % hashmod;
      pw[i+1] = pw[i] * base % hashmod;
    }
  }
  ll get(ll a, ll b) { // [a, b)
    __int128 tmp = hashmod + hash[b] - hash[a] * pw[b-a] % hashmod;
    if (tmp >= hashmod) tmp -= hashmod;
    return (ll)tmp;
  }
};

ll n, x[15], y[15], p[15], ans[16], dir[15];

void check() {
  vector<ll> vx, vy;
  vx.push_back(0);
  vy.push_back(0);
  ll counter = 0;
  for (ll i = 0; i < n; i++) {
    if (dir[i] == 1) vx.push_back(x[i]), counter++;
    if (dir[i] == 2) vy.push_back(y[i]), counter++;
  }
  ll tmp = 0;
  for (ll i = 0; i < n; i++) {
    ll mn = INF;
    for (ll j : vx) mn = min(mn, abs(x[i] - j));
    for (ll j : vy) mn = min(mn, abs(y[i] - j));
    tmp += mn * p[i];
  }
  ans[counter] = min(ans[counter], tmp);
}

int main() {
  scanf("%lld", &n);
  for (ll i = 0; i < n; i++) scanf("%lld%lld%lld", &x[i], &y[i], &p[i]);
  for (ll i = 0; i <= n; i++) ans[i] = INF;
  check();
  for (ll i = 0; i < 10000000; i++) {
    ll tmp = rand() % n;
    dir[tmp]++;
    if (dir[tmp] == 3) dir[tmp] = 0;
    check();
  }
  for (ll i = 1; i <= n; i++) ans[i] = min(ans[i], ans[i-1]);
  for (ll i = 0; i <= n; i++) printf("%lld\n", ans[i]);
}

Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.


#include <algorithm>
#include <iostream>
#include <iomanip>
#include <numeric>
#include <cassert>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#define syosu(x) fixed<<setprecision(x)
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef pair<double,double> pdd;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<string> vs;
typedef vector<P> vp;
typedef vector<vp> vvp;
typedef vector<pll> vpll;
typedef pair<int,P> pip;
typedef vector<pip> vip;
const int inf=1<<28;
const ll INF=1ll<<60;
const double pi=acos(-1);
const double eps=1e-8;
const ll mod=998244353;
const int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};

const int M=500001;
int n;
vi x,y,a;
map<char,int> mp={
	{'U',0},
	{'R',1},
	{'D',2},
	{'L',3},
};

int main(){
	cin>>n;
	int res=inf;
	x=y=a=vi(n);
	for(int i=0;i<n;i++){
		char c;
		cin>>x[i]>>y[i]>>c;
		a[i]=mp[c];
	}
	vvp b(M);
	for(int i=0;i<n;i++) if(a[i]%2==0) b[x[i]].push_back({y[i],a[i]});
	for(int i=0;i<M;i++) if(!b[i].empty()){
		sort(b[i].begin(),b[i].end());
		int tmp=-inf;
		for(auto p:b[i]){
			if(p.second==0) tmp=p.first;
			else res=min(res,p.first-tmp);
		}
	}
	b=vvp(M);
	for(int i=0;i<n;i++) if(a[i]%2==1) b[y[i]].push_back({x[i],a[i]});
	for(int i=0;i<M;i++) if(!b[i].empty()){
		sort(b[i].begin(),b[i].end());
		int tmp=-inf;
		for(auto p:b[i]){
			if(p.second==1) tmp=p.first;
			else res=min(res,p.first-tmp);
		}
	}
	b=vvp(M);
	for(int i=0;i<n;i++) b[x[i]+y[i]].push_back({x[i],a[i]});
	for(int i=0;i<M;i++) if(!b[i].empty()){
		sort(b[i].begin(),b[i].end());
		int tmp=-inf;
		for(auto p:b[i]){
			if(p.second==1) tmp=p.first;
			if(p.second==0) res=min(res,(p.first-tmp)*2);
		}
		tmp=-inf;
		for(auto p:b[i]){
			if(p.second==2) tmp=p.first;
			if(p.second==3) res=min(res,(p.first-tmp)*2);
		}
	}
	b=vvp(M);
	for(int i=0;i<n;i++) b[x[i]-y[i]+M].push_back({x[i],a[i]});
	for(int i=0;i<M;i++) if(!b[i].empty()){
		sort(b[i].begin(),b[i].end());
		int tmp=-inf;
		for(auto p:b[i]){
			if(p.second==0) tmp=p.first;
			if(p.second==3) res=min(res,(p.first-tmp)*2);
		}
		tmp=-inf;
		for(auto p:b[i]){
			if(p.second==1) tmp=p.first;
			if(p.second==2) res=min(res,(p.first-tmp)*2);
		}
	}
	if(res==inf) cout<<"SAFE"<<endl;
	else cout<<res*5<<endl;
}

Score: 600 points

Problem Statement

M-kun is a brilliant air traffic controller.

On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude.

Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the direction of the airplane is as follows:

if U_i is U, it flies in the positive y direction;

if U_i is R, it flies in the positive x direction;

if U_i is D, it flies in the negative y direction;

if U_i is L, it flies in the negative x direction.

To help M-kun in his work, determine whether there is a pair of airplanes that will collide with each other if they keep flying as they are now.

If there is such a pair, find the number of seconds after which the first collision will happen.

We assume that the airplanes are negligibly small so that two airplanes only collide when they reach the same coordinates simultaneously.

Constraints

1 \leq N \leq 200000

0 \leq X_i, Y_i \leq 200000

U_i is U, R, D, or L.

The current positions of the N airplanes, (X_i, Y_i), are all distinct.

N, X_i, and Y_i are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 U_1
X_2 Y_2 U_2
X_3 Y_3 U_3
:
X_N Y_N U_N

Output

If there is a pair of airplanes that will collide with each other if they keep flying as they are now, print an integer representing the number of seconds after which the first collision will happen.

If there is no such pair, print SAFE.

Sample Input 1

2
11 1 U
11 47 D

Sample Output 1

230

If the airplanes keep flying as they are now, two airplanes numbered 1 and 2 will reach the coordinates (11, 24) simultaneously and collide.

Sample Input 2

4
20 30 U
30 20 R
20 10 D
10 20 L

Sample Output 2

SAFE

No pair of airplanes will collide.

Sample Input 3

8
168 224 U
130 175 R
111 198 D
121 188 L
201 116 U
112 121 R
145 239 D
185 107 L

Sample Output 3

100


#include <iostream>
using namespace std;
int main(){
  int l,r,d,result=0;
  cin >> l >> r >> d;
  for(;l<=r;l++){
    if(l%d==0) result++;
  }
  cout << result << endl;
  return 0;
}

Score : 100 points

Problem Statement

How many multiples of d are there among the integers between L and R (inclusive)?

Constraints

All values in input are integers.

1 \leq L \leq R \leq 100

1 \leq d \leq 100

Input

Input is given from Standard Input in the following format:

L R d

Output

Print the number of multiples of d among the integers between L and R (inclusive).

Sample Input 1

5 10 2

Sample Output 1

3

Among the integers between 5 and 10, there are three multiples of 2: 6, 8, and 10.

Sample Input 2

6 20 7

Sample Output 2

2

Among the integers between 6 and 20, there are two multiples of 7: 7 and 14.

Sample Input 3

1 100 1

Sample Output 3

100


#include <bits/stdc++.h>

#ifdef NON_SUBMIT
#define TEST(n) (n)
#define tout cerr
#else
#define TEST(n) ((void)0)
#define tout cin
#endif

using namespace std;

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	TEST(freopen("input.txt","r",stdin));
	TEST(freopen("output.txt","w",stdout));
	TEST(freopen("debug.txt","w",stderr));
	int L, R, D;
	cin>>L>>R>>D;
	cout<<R/D-(L-1)/D<<'\n';
	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define ull unsigned long long
#define mp make_pair
#define pb(x) push_back(x)
#define vi vector<int>
#define vs vector<string>
#define vll vector<long long>
#define vc vector<char>
#define vs vector<string>
#define pii pair<int, int>
#define pll pair<long long, long long>
#define pil pair<int, long long>
#define pli pair<long long, int>
#define pcc pair<char, char>
#define pdd pair<double, double>
#define mll map<long long ,long long>
#define gcd __gcd
using namespace std;
int main()
{
	ll n;
	ll a[100];
	ll ct=0;
	cin>>n;
	for(ll i=0;i<n;i++)
	{
		cin>>a[i];
	}
	for(ll i=0; i<n;i++)
	{
		if((i+1)%2!=0 && (a[i]%2!=0))
			ct++;
	}
	cout<<ct<<"\n";
}

Score : 200 points

Problem Statement

We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i.

How many squares i satisfy both of the following conditions?

The assigned number, i, is odd.

The written integer is odd.

Constraints

All values in input are integers.

1 \leq N, a_i \leq 100

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \cdots a_N

Output

Print the number of squares that satisfy both of the conditions.

Sample Input 1

5
1 3 4 5 7

Sample Output 1

2

Two squares, Square 1 and 5, satisfy both of the conditions.

For Square 2 and 4, the assigned numbers are not odd.

For Square 3, the written integer is not odd.

Sample Input 2

15
13 76 46 15 50 98 93 77 31 43 84 90 6 24 14

Sample Output 2

3


#include <iostream>
using namespace std;
int main()
{
    int cnt = 0, val, n;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> val;
        if ((i % 2) == 1 && (val % 2) == 1)
            cnt++;
    }
    cout << cnt << endl;
    return 0;
}


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

int main() {
    int N;
    cin >> N;
    int ans = 0;
    for (int i = 1; i <= N; i++) {
        int A;
        cin >> A;
        if (i % 2 == 1 && A % 2 == 1) ans++;
    }
    cout << ans << endl;
}


#include <iostream>

using namespace std;

int main()
{
    int n;
    cin>>n;
    int arr[10001] = {0};
    int m =  min(n,99);
    for(int i = 1 ; i <= m ; i++)
    {
        for(int j = 1 ; j <= m ;j++)
        {
            for(int z = 1 ; z <= m ;z++)
            {
                if(i*i+j*j+z*z+i*j+i*z+j*z <= 10000)
                    arr[i*i+j*j+z*z+i*j+i*z+j*z]++;
            }
        }
    }
    for(int  i = 1 ; i <= n ; i++)
    {
        cout<<arr[i]<<endl;
    }
    return 0;
}

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


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

int func(int A){
  int count=0;
  for(int i=1;i<55;i++){
    for(int j=1;j<55;j++){
      for(int k=1;k<55;k++){
        int B=i*i+j*j+k*k+i*j+j*k+k*i;
        if(A==B){
          count++;
        }
      }
    }
  }
  return count;
}

int main(){
  int N;
  cin >> N;
  for(int i=0;i<N;i++){
    cout << func(i+1) << endl;
  }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int n,m,i,j,k,l,p,b,t;
    cin>>n;
    t=0;
    for(i=1; i<=n; i++)
    {
        p = sqrt(i/2);
        t=0;
        for(j=1; j<=p; j++)
        {
            for(k=1; k<=p; k++)
            {
                for(l=1; l<=p; l++)
                {
                    b = j*j+k*k+l*l+j*k+k*l+j*l;
                    if(b==i)
                    {
                        t++;
                        break;
                    }
                }
            }
        }
        cout<<t<<endl;
    }
}


#pragma region Headers
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cwchar>
#include <cwctype>

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <codecvt>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif
#pragma endregion

using namespace std;
#pragma region Macros
#define CHOOSE(a) CHOOSE2 a
#define CHOOSE2(a0, a1, a2, a3, a4, x, ...) x
#define debug_1(x1) cout << #x1 << ": " << x1 << endl
#define debug_2(x1, x2) cout << #x1 << ": " << x1 << ", " #x2 << ": " << x2 << endl
#define debug_3(x1, x2, x3) cout << #x1 << ": " << x1 << ", " #x2 << ": " << x2 << ", " #x3 << ": " << x3 << endl
#define debug_4(x1, x2, x3, x4) cout << #x1 << ": " << x1 << ", " #x2 << ": " << x2 << ", " #x3 << ": " << x3 << ", " #x4 << ": " << x4 << endl
#define debug_5(x1, x2, x3, x4, x5) cout << #x1 << ": " << x1 << ", " #x2 << ": " << x2 << ", " #x3 << ": " << x3 << ", " #x4 << ": " << x4 << ", " #x5 << ": " << x5 << endl
#ifdef _DEBUG
#define debug(...)                                                      \
  CHOOSE((__VA_ARGS__, debug_5, debug_4, debug_3, debug_2, debug_1, ~)) \
  (__VA_ARGS__)
#else
#define debug(...)
#endif
#pragma region end

#pragma region Libraries
template <typename T>
string to_string(T o)
{
  stringstream s;
  s << o;
  return s.str();
}

template <typename T>
string to_string(vector<T> v)
{
  stringstream s;
  s << "[";
  for (auto i = 0; i < v.size(); i++)
  {
    s << to_string(v.at(i));
    if (i != v.size() - 1)
    {
      s << ", ";
    }
  }
  s << "]";
  return s.str();
}

template <typename T>
ostream &operator<<(ostream &o, const vector<T> &obj)
{
  o << to_string(obj);
  return o;
}

template <typename T>
string to_string(vector<vector<T>> m)
{
  stringstream s;
  s << "[" << endl;
  for (auto i = 0; i < m.size(); i++)
  {
    auto v = m[i];
    s << "  "
      << "#" << i << ":"
      << " " << to_string(v);
    s << ", " << endl;
  }
  s << "]";
  return s.str();
}

template <typename T>
ostream &operator<<(ostream &o, const vector<vector<T>> &obj)
{
  o << to_string(obj);
  return o;
}

template <typename K, typename V>
string to_string(pair<K, V> p)
{
  stringstream s;
  s << "pair(" << to_string(p.first) << ", " << to_string(p.second) << ")";
  return s.str();
}

template <typename K, typename V>
ostream &operator<<(ostream &o, const pair<K, V> &obj)
{
  o << to_string(obj);
  return o;
}

template <typename K, typename V>
string to_string(map<K, V> m)
{
  stringstream s;
  s << "{" << endl;
  for (const auto &p : m)
  {
    s << "  " << to_string(p.first) << ": " << to_string(p.second) << "," << endl;
  }
  s << "}";
  return s.str();
}

template <typename K, typename V>
ostream &operator<<(ostream &o, const map<K, V> &obj)
{
  o << to_string(obj);
  return o;
}

template <typename T>
string to_string(set<T> ss)
{
  stringstream s;
  s << "set"
    << "{";
  for (auto itr = ss.begin(); itr != ss.end(); itr++)
  {
    s << to_string(*itr);
    if (next(itr, 1) != ss.end())
    {
      s << ", ";
    }
  }
  s << "}";
  return s.str();
}

template <typename T>
ostream &operator<<(ostream &o, const set<T> &obj)
{
  o << to_string(obj);
  return o;
}

template <typename T>
string to_string(queue<T> q)
{
  auto temp = queue<T>{};
  stringstream s;
  s << "queue{";
  while (!q.empty())
  {
    auto top = q.front();
    s << to_string(top) << ", ";
    q.pop();
    temp.push(top);
  }
  s << "}";

  while (!temp.empty())
  {
    auto top = temp.front();
    temp.pop();
    q.push(top);
  }

  return s.str();
}

template <typename T>
ostream &operator<<(ostream &o, const queue<T> &obj)
{
  o << to_string(obj);
  return o;
}
#pragma endregion

typedef long long ll;

int main()
{
  cin.tie(0);
  ios::sync_with_stdio(false);
  std::cout << std::setprecision(20);

  ll n;
  cin >> n;
  map<ll, ll> cnt;

  for (int x = 1; x <= 100; x++)
  {
    for (int y = 1; y <= 100; y++)
    {
      for (int z = 1; z <= 100; z++)
      {
        ll val = x * x + y * y + z * z + x * y + y * z + z * x;
        if (val >= 1 && val <= 10000)
        {
          cnt[val]++;
        }
      }
    }
  }

  for (auto i = 1; i <= n; i++)
  {
    cout << cnt[i] << endl;
  }

  return 0;
}


#include "bits/stdc++.h"

#define MOD 1000000007
#define rep(i, n) for(ll i=0; i < (n); i++)
#define rrep(i, n) for(ll i=(n)-1; i >=0; i--)
#define ALL(v) v.begin(),v.end()
#define rALL(v) v.rbegin(),v.rend()
#define FOR(i, j, k) for(ll i=j;i<k;i++)
#define debug_print(var) cerr << #var << "=" << var <<endl;
#define DUMP(i, v)for(ll i=0;i<v.size();i++)cerr<<v[i]<<" "

using namespace std;
typedef long long int ll;
typedef vector<ll> llvec;
typedef vector<double> dvec;
typedef pair<ll, ll> P;
typedef long double ld;
struct edge{ll x, c;};

ll mod(ll a, ll mod){
  ll res = a%mod;
  while(res<0){
    res=res + mod;
  }
  return res;
}

ll modpow(ll a, ll n, ll mod){
  ll res=1;
  while(n>0){
    if(n&1) res=res*a%mod;
    a=a*a%mod;
    n>>=1;
  }
  return res;
}

ll modinv(ll a, ll mod){
  return modpow(a, mod-2, mod);
}

ll gcd(ll a, ll b){
  ll r = a%b;
  if(r==0) return b;
  else return gcd(b, a%b);
}

bool is_prime(ll n){
  ll i = 2;
  if(n==1)return false;
  if(n==2)return true;
  bool res = true;
  while(i*i <n){
    if(n%i==0){
      res = false;
    }
    i = i+1;
  }

  //if(i==1)res = false;
  if(n%i==0)res=false;
  return res;
}

struct UnionFind{
  ll N;
  llvec p;
  llvec cnt;
  UnionFind(ll n){
    N = n;
    p=llvec(N);
    cnt=llvec(N, 0);
    rep(i, N){
      p[i] = i;
      cnt[i] = 1;
    }
  }

  void con(ll a, ll b){
    P at = root(a);
    P bt = root(b);
    if(at.second!=bt.second){
      if(at.first>bt.first){
        swap(at, bt);
        swap(a, b);
      }
      p[at.second] = bt.second;
      cnt[bt.second]+=cnt[at.second];
      p[a]=bt.second;
    }
  }

  P root(ll a){
    ll atmp = a;
    ll c=0;
    while(atmp!=p[atmp]){
      atmp = p[atmp];
      c++;
    }
    p[a] = atmp;
    return {c, atmp};
  }

  bool is_con(ll a, ll b){
    P at=root(a);
    P bt=root(b);
    return at.second == bt.second;
  }

};

struct dijkstra{
  ll N;
  llvec d;
  vector<vector<edge>> e;
  dijkstra(ll n){
    N = n;
    //d = llvec(N, 1e18);
    e = vector<vector<edge>>(N);
  }

  void add_edge(ll from, ll to, ll cost){
    e[from].push_back({to, cost});
  }

  void run(ll start){
    priority_queue<P, vector<P>, greater<P>> que;
    que.push({0, start});
    d = llvec(N, 1e18);
    d[start]=0;
    while(!que.empty()){
      P q = que.top();que.pop();
      ll dc = q.first;
      ll x = q.second;
      if(dc>d[x]){
        continue;
      }else{
        for(auto ip: e[x]){
          if(d[ip.x]<=d[x]+ip.c){
            continue;
          }else{
            d[ip.x]= d[x]+ip.c;
            que.push({d[ip.x], ip.x});
          }
        }
      }
    }
  }
};

ll dp[5000000];
ll func2(ll n, ll s){
  if(n==0)return s;
  ll cnt = 0;
  rep(i, 20){
    if(n>>i&1)cnt++;
  }
  ll ans = 0;
  rep(i, 20){
    if(n>>i&1){
      ans = mod(ans + modpow(2, i, cnt), cnt);
    }
  }
  return func2(ans, s+1);
}

/**************************************
** A main function starts from here  **
***************************************/
int main(){
  ll N;
  cin >> N;
  string X;
  cin >> X;
  ll cnt=0;
  rep(i, N){
    if(X[i]=='1')cnt++;
  }
  ll cnt_m1=0;
  ll cnt_p1=0;
  rep(i, N){
    if(X[i]=='1'){
      if(cnt>0)cnt_m1 = mod(cnt_m1+modpow(2, N-i-1, cnt-1), cnt-1);
      cnt_p1 = mod(cnt_p1+modpow(2, N-i-1, cnt+1), cnt+1);
    }
  }
  /*
  rep(i, N+1){
    dp[i] = func2(i, 0);
  }
  */
  rep(i, N){
    if(X[i]=='0'){
      ll tmp = mod(cnt_p1+modpow(2, N-i-1, cnt+1), cnt+1);
      cout << func2(tmp, 1)<<endl;
    }else{
      ll tmp = mod(cnt_m1-modpow(2, N-i-1, cnt-1), cnt-1);
      tmp = mod(tmp, cnt-1);
      cout << func2(tmp, 1)<<endl;
    }
  }

  return 0;
}

Score : 400 points

Problem Statement

Let \mathrm{popcount}(n) be the number of 1s in the binary representation of n.
For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.

Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n is divided by \mathrm{popcount}(n)." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)

For example, when n=7, it becomes 0 after two operations, as follows:

\mathrm{popcount}(7)=3, so we divide 7 by 3 and replace it with the remainder, 1.

\mathrm{popcount}(1)=1, so we divide 1 by 1 and replace it with the remainder, 0.

You are given an integer X with N digits in binary.
For each integer i such that 1 \leq i \leq N, let X_i be what X becomes when the i-th bit from the top is inverted.
Find f(X_1), f(X_2), \ldots, f(X_N).

Constraints

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

X is an integer with N digits in binary, possibly with leading zeros.

Input

Input is given from Standard Input in the following format:

N
X

Output

Print N lines. The i-th line should contain the value f(X_i).

Sample Input 1

3
011

Sample Output 1

2
1
1

X_1 = 7, which will change as follows: 7 \rightarrow 1 \rightarrow 0. Thus, f(7) = 2.

X_2 = 1, which will change as follows: 1 \rightarrow 0. Thus, f(1) = 1.

X_3 = 2, which will change as follows: 2 \rightarrow 0. Thus, f(2) = 1.

Sample Input 2

23
00110111001011011001110

Sample Output 2

2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3


#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
using namespace std;
typedef long long int ll;
using ull = unsigned long long;

ll solve(vector<pair<int,int>> v){
    int n=v.size();
    for(int i=0;i<n;i++){
        v[i].first=min(v[i].first,n);
    }
    vector<vector<int>> s(n+1);
    for(int i=0;i<n;i++){
        s[v[i].first].push_back(v[i].second);
    }
    ll res=0;
    priority_queue<ll> q;
    for(int i=n;i>=1;i--){
        for(int x:s[i]){q.push(x);}
        if(q.size()){
            res+=q.top();
            q.pop();
        }
    }
    return res;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int q; cin >> q;
    while(q--){
        int n; cin >> n;
        vector<pair<int,int>> pl,pr;
        ll res=0;
        for(int i=0;i<n;i++){
            int k,l,r; cin >> k >> l >> r;
            int m=min(l,r);
            res+=m;
            l-=m,r-=m;
            if(l>0)pl.push_back({k,l});
            else pr.push_back({n-k,r});
        }
        res+=solve(pl);
        res+=solve(pr);
        printf("%lld\n",res );
    }
}

Score : 500 points

Problem Statement

We have N camels numbered 1,2,\ldots,N.
Snuke has decided to make them line up in a row.

The happiness of Camel i will be L_i if it is among the K_i frontmost camels, and R_i otherwise.

Snuke wants to maximize the total happiness of the camels. Find the maximum possible total happiness of the camel.

Solve this problem for each of the T test cases given.

Constraints

All values in input are integers.

1 \leq T \leq 10^5

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

1 \leq K_i \leq N

1 \leq L_i, R_i \leq 10^9

The sum of values of N in each input file is at most 2 \times 10^5.

Input

Input is given from Standard Input in the following format:

T
\mathrm{case}_1
\vdots
\mathrm{case}_T

Each case is given in the following format:

N
K_1 L_1 R_1
\vdots
K_N L_N R_N

Output

Print T lines. The i-th line should contain the answer to the i-th test case.

Sample Input 1

3
2
1 5 10
2 15 5
3
2 93 78
1 71 59
3 57 96
19
19 23 16
5 90 13
12 85 70
19 67 78
12 16 60
18 48 28
5 4 24
12 97 97
4 57 87
19 91 74
18 100 76
7 86 46
9 100 57
3 76 73
6 84 93
1 6 84
11 75 94
19 15 3
12 11 34

Sample Output 1

25
221
1354

In the first test case, it is optimal to line up the camels in the order 2, 1.

Camel 1 is not the frontmost camel, so its happiness will be 10.

Camel 2 is among the two frontmost camels, so its happiness will be 15.

In the second test case, it is optimal to line up the camels in the order 2, 1, 3.

Camel 1 is among the two frontmost camels, so its happiness will be 93.

Camel 2 is the frontmost camel, so its happiness will be 71.

Camel 3 is among the three frontmost camels, so its happiness will be 57.


#include <bits/stdc++.h>
using namespace std;
#define m_p make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
typedef long long ll;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnf(2106);
const int N = 200005;
struct ban
{
    int k, l, r;
};
bool operator<(const ban& a, const ban& b)
{
    return abs(a.l - a.r) < abs(b.l - b.r);
}

int n;
ban a[N];

void ubd(int tl, int tr, int x, int y, int pos, vector<int>& s, vector<int>& p)
{
    if (tl == tr)
    {
        s[pos] += y;
        p[pos] = min(p[pos], 0);
        return;
    }
    int m = (tl + tr) / 2;
    if (x <= m)
        ubd(tl, m, x, y, pos * 2, s, p);
    else
        ubd(m + 1, tr, x, y, pos * 2 + 1, s, p);
    s[pos] = s[pos * 2] + s[pos * 2 + 1];
    p[pos] = min(p[pos * 2], s[pos * 2] + p[pos * 2 + 1]);
}

void solv()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
        scanf("%d%d%d", &a[i].k, &a[i].l, &a[i].r);
    sort(a + 1, a + n + 1);
    reverse(a + 1, a + n + 1);

    vector<int> sl, pl, sr, pr;
    sl.assign(n * 4 + 5, 0);
    pl.assign(n * 4 + 5, 0);
    sr.assign(n * 4 + 5, 0);
    pr.assign(n * 4 + 5, 0);

    for (int i = 1; i <= n; ++i)
    {
        ubd(1, n, i, 1, 1, sl, pl);
        ubd(1, n, i, 1, 1, sr, pr);
    }

    ll ans = 0;
    for (int i = 1; i <= n; ++i)
    {
        if (a[i].l > a[i].r)
        {
            ubd(1, n, a[i].k, -1, 1, sl, pl);
            if (pl[1] < 0)
            {
                ubd(1, n, a[i].k, 1, 1, sl, pl);
                ans += a[i].r;
            }
            else
                ans += a[i].l;
        }
        else
        {
            if (n - a[i].k == 0)
            {
                ans += a[i].l;
                continue;
            }
            ubd(1, n, n - a[i].k, -1, 1, sr, pr);
            if (pr[1] < 0)
            {
                ubd(1, n, n - a[i].k, 1, 1, sr, pr);
                ans += a[i].l;
            }
            else
                ans += a[i].r;
        }
        //ubd(1, n, n, -2, 1, sl, pl);
        //ubd(1, n, 1, -2, 1, sr, pr);
    }
    printf("%lld\n", ans);
}

int main()
{
    #ifdef SOMETHING
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    #endif // SOMETHING
    int tt;
    scanf("%d", &tt);
    while (tt--)
        solv();
    return 0;
}

//while ((double)clock() / CLOCKS_PER_SEC <= 0.9){}


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

int main(){

int n;
cin >> n;
vector<string> s(100010);
int a=0, w=0, t=0, r=0;
rep(i,n) {
    cin >> s[i];
    if(s[i]=="AC") a++;
    if(s[i]=="WA") w++;
    if(s[i]=="TLE") t++;
    if(s[i]=="RE") r++;
}
cout << "AC x " << a << endl;
cout << "WA x " << w << endl;
cout << "TLE x " << t << endl;
cout << "RE x " << r << endl;

}

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;
typedef long long ll;
int H,W,K;

int main(){
  cin >> H >> W >> K;
  vector<vector<int> > c(H,vector<int>(W));
  int all =0;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      char a;
      cin >> a;
      if(a=='#') {
	all++;
	c[i][j]=1;
      }
      else c[i][j]=0;
    }
  }
  int ans =0;
  for(int bith = 0;bith<(1<<H);++bith){
    for(int bitw = 0;bitw<(1<<W);++bitw){
      int black=0;
      for(int i=0;i<H;i++){
	for(int j=0;j<W;j++){
	  if((bith & (1<<i)) && (bitw & (1<<j))){
	    black+=c[i][j];
	  }
	}
      }
      if(black==K) ans++;
    }
  }
  cout << ans << endl;
}

Score : 300 points

Problem Statement

We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is ., and black if c_{i,j} is #.

Consider doing the following operation:

Choose some number of rows (possibly zero), and some number of columns (possibly zero). Then, paint red all squares in the chosen rows and all squares in the chosen columns.

You are given a positive integer K. How many choices of rows and columns result in exactly K black squares remaining after the operation? Here, we consider two choices different when there is a row or column chosen in only one of those choices.

Constraints

1 \leq H, W \leq 6

1 \leq K \leq HW

c_{i,j} is . or #.

Input

Input is given from Standard Input in the following format:

H W K
c_{1,1}c_{1,2}...c_{1,W}
c_{2,1}c_{2,2}...c_{2,W}
:
c_{H,1}c_{H,2}...c_{H,W}

Output

Print an integer representing the number of choices of rows and columns satisfying the condition.

Sample Input 1

2 3 2
..#
###

Sample Output 1

5

Five choices below satisfy the condition.

The 1-st row and 1-st column

The 1-st row and 2-nd column

The 1-st row and 3-rd column

The 1-st and 2-nd column

The 3-rd column

Sample Input 2

2 3 4
..#
###

Sample Output 2

1

One choice, which is choosing nothing, satisfies the condition.

Sample Input 3

2 2 3
##
##

Sample Output 3

0

Sample Input 4

6 6 8
..##..
.#..#.
#....#
######
#....#
#....#

Sample Output 4

208


#include <bits/stdc++.h>
#include <limits>
#include <math.h>
#include <cmath>
#include <cctype>
#include <cstdio>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pll = pair<ll, ll> ;
using vs = vector<string>;
using vb = vector<bool>;
using vll = vector<long long>;
using vvll = vector<vector<long long >>;
#define PI  3.1415926535
#define rep(i, k, n) for(ll i = k; i < n; i++)

int main(){
  ll h, w, k;
  cin >> h >> w >> k;

  vector<vector<char>> block(h,vector<char>(w));

  rep(i, 0, h){
    rep(j, 0, w){
      cin >> block[i][j];
    }
  }

  ll ans = 0;
  for(ll bit = 0; bit < (1<<(h+w)); bit ++){

    vector<vector<char>> painted(h,vector<char>(w));
    rep(i, 0, h){
      rep(j, 0, w){
        painted[i][j] = block[i][j];
      }
    }

    rep(i, 0, h+w){
      if(bit & (1 << i)){
        if(i < h){
          rep(j, 0, w){painted[i][j] = 'R';}
        }
        else{
          rep(j, 0, h){painted[j][i-h] = 'R';}
        }
      }
    }

    ll cnt = 0;
    rep(i, 0, h){
      rep(j, 0, w){
        if(painted[i][j] == '#'){cnt++;}
      }
    }

    if(cnt == k){ans++;}
  }

  cout << ans << endl;

}


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

signed main() {
    int h, w, k;
    cin >> h >> w >> k;
    vector<string> s(h);
    int ans = 0;
    rep(i, h) cin >> s[i];

    rep(is, 1<<h)rep(js, 1<<w){
        int cnt = 0;
        rep(i, h)rep(j, w){
            if(is>>i & 1) continue;
            if(js>>i & 1) continue;
            if(s[i][j] == '#') cnt++;
        }
        if(cnt == k) ans++;
    }

    cout << ans << endl;
}


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
const double PI=3.1415926535897932;
using namespace std;
typedef long long ll;

int main(void){
    ll h,w,q;
    cin>>h>>w>>q;
    int a[h][w];
    rep(i,h){
        rep(j,w){
            char c;
            cin>>c;
            if(c=='.')a[i][j]=1;
            else a[i][j]=0;
        }
    }
    int ans=0;
    for(int bit=0;bit<(1<<h);bit++){
        vector <int>ex;
        for(int i=0;i<h;i++){
            if(bit&1<<i){
                ex.push_back(i);
            }
        }
        for(int c=0;c<(1<<w);c++){
            vector <int> ew;
            for(int j=0;j<w;j++){
                if(c&1<<j){
                    ew.push_back(j);
                }
            }
            int s=0;
            rep(k,h){
                int fa=1;
                for(auto x:ex){
                    if(k==x)fa=0;
                }
                if(fa==0)continue;
                rep(l,w){
                    int f=1;
                    for(auto y:ew){
                        if(l==y)f=0;
                    }
                    if(f){
                        if(a[k][l]==0)s++;
                    }
                }
            }
            if(q==s)ans++;
        }
    }
    cout<<ans<<endl;
}


#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define forn(i,a,b) for(int i =a;i<b;i++)
#define fi first
#define se second
#define fast ios_base::sync_with_stdio(false);
using namespace std;

//for debugging
/*
g++ -D_GLIBCXX_ASSERTIONS -DDEBUG -ggdb3 -std=c++14
*/
int recur_depth = 0;
#ifdef DEBUG
#define dbg(x) {++recur_depth; auto x_=x; --recur_depth; cerr<<string(recur_depth, '\t')<<"\e[91m"<<__func__<<":"<<__LINE__<<"\t"<<#x<<" = "<<x_<<"\e[39m"<<endl;}
#else
#define dbg(x)
#endif
template<typename Ostream, typename Cont>
typename enable_if<is_same<Ostream,ostream>::value, Ostream&>::type operator<<(Ostream& os,  const Cont& v){
	os<<"[";
	for(auto& x:v){os<<x<<", ";}
	return os<<"]";
}
template<typename Ostream, typename ...Ts>
Ostream& operator<<(Ostream& os,  const pair<Ts...>& p){
	return os<<"{"<<p.first<<", "<<p.second<<"}";
}
// debugging ends here

typedef long long int ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

void solve(){
	int n;
	cin >> n;
	ll a[n];
	forn(i,0,n) cin >> a[i];
	sort(a,a+n);
	reverse(a,a+n);
	long long int ans = 0;
	ans+=a[0];
	for(int i=0;i<((n-1)/2 - 1);i++){
		ans+=(2*a[i+1]);
		// cout << ans << endl;
	}
	if(n%2){
		ans+=a[(n-1)/2];
	}
	else{
		ans+=2*a[(n-1)/2];
	}
	cout << ans << endl;
}

int main(){
	fast;
	#ifndef ONLINE_JUDGE
		freopen("input.txt","r",stdin);
		freopen("output.txt","w",stdout);
	#endif

	// int t;cin >> t;while(t--)
		solve();
}

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


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

//template
#define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define ALL(v) (v).begin(),(v).end()
typedef long long int ll;
const int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-12;
template<typename T>inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}
template<typename T>inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}
//end

template<unsigned mod=1000000007>struct fp {
   int v; static unsigned get_mod(){return mod;}
   int inv() const{
      int tmp,a=v,b=mod,x=1,y=0;
      while(b)tmp=a/b,a-=tmp*b,swap(a,b),x-=tmp*y,swap(x,y);
      if(x<0){x+=mod;} return x;
   }
   fp():v(0){}
   fp(ll x):v(x>=0?x%mod:mod+(x%mod)){}
   fp operator-()const{return fp(-v);}
   fp pow(ll t){fp res=1,b=*this; while(t){if(t&1)res*=b;b*=b;t>>=1;} return res;}
   fp& operator+=(const fp& x){if((v+=x.v)>=(int)mod)v-=mod; return *this;}
   fp& operator-=(const fp& x){if((v+=mod-x.v)>=(int)mod)v-=mod; return *this;}
   fp& operator*=(const fp& x){v=ll(v)*x.v%mod; return *this;}
   fp& operator/=(const fp& x){v=ll(v)*x.inv()%mod; return *this;}
   fp operator+(const fp& x)const{return fp(*this)+=x;}
   fp operator-(const fp& x)const{return fp(*this)-=x;}
   fp operator*(const fp& x)const{return fp(*this)*=x;}
   fp operator/(const fp& x)const{return fp(*this)/=x;}
   bool operator==(const fp& x)const{return v==x.v;}
   bool operator!=(const fp& x)const{return v!=x.v;}
}; using Fp=fp<>;

int main(){
   int n,k; cin>>n>>k;
   vector<int> a(n);
   rep(i,0,n)cin>>a[i];
   sort(ALL(a));
   if(a.back()<0 and k%2==1){
      Fp res=1;
      rep(i,n-k,n)res*=a[i];
      cout<<res.v<<endl; return 0;
   }
   vector<int> pos,neg;
   rep(i,0,n){
      if(a[i]>=0)pos.push_back(a[i]);
      else neg.push_back(-a[i]);
   }
   sort(ALL(pos),greater<int>());
   sort(ALL(neg),greater<int>());
   Fp res=1;
   int pi=0,ni=0;
   while(k){
      if(k==1){
         res*=pos[pi]; k--;
         continue;
      }
      if(neg.size()-ni<=1){
         res*=1LL*pos[pi]*pos[pi+1];
         pi+=2; k-=2;
      }
      else if(pos.size()-pi==0){
         res*=1LL*neg[ni]*neg[ni+1];
         ni+=2; k-=2;
      }
      else{
         ll P=1LL*pos[pi]*pos[pi+1];
         ll Q=1LL*neg[ni]*neg[ni+1];
         if(P<Q){
            res*=Q; ni+=2; k-=2;
         }
         else{
            res*=P; pi+=2; k-=2;
         }
      }
   }
   cout<<res.v<<endl;
   return 0;
}

Score : 500 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.

Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Constraints

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

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 \ldots A_N

Output

Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Sample Input 1

4 2
1 2 -3 -4

Sample Output 1

12

The possible products of the two chosen elements are 2, -3, -4, -6, -8, and 12, so the maximum product is 12.

Sample Input 2

4 3
-1 -2 -3 -4

Sample Output 2

1000000001

The possible products of the three chosen elements are -24, -12, -8, and -6, so the maximum product is -6.

We print this value modulo (10^9+7), that is, 1000000001.

Sample Input 3

2 1
-1 1000000000

Sample Output 3

1000000000

The possible products of the one chosen element are -1 and 1000000000, so the maximum product is 1000000000.

Sample Input 4

10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1

Sample Output 4

999983200

Be sure to print the product modulo (10^9+7).


#include<iostream>
#include<math.h>
#include<algorithm>
#include<stdint.h>
#include<vector>
#include<deque>
#include<stack>
#include<functional>
#include<string>
#include<cstring>
#include<time.h>
#include<array>
#include<iomanip>
#include<list>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<random>
#include<bitset>
#include <queue>
#include <map>

using namespace std;
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
using ldouble = long double;

//BDD,ZDD,kdtree, bdtree,bicalc, bolonoy, doloney, tree, chinesemod,segmenttree,daikusutora, saidairyuu, 2bugurahu, heirokenshutu, topologicalsort, kyourenketuseibun

#define REP(i,a,b) for(int i = a; i < b; ++i)
#define PRI(s) cout << s << endl
#define PRIY PRI("Yes")
#define PRIN PRI("No")

ll N, K;
vector<ll> a;
vector<ll> ap;
vector<ll> am;
ll MOD = 1000000007;

ll mod(ll x) { return (x%MOD + MOD) % MOD; }
int main() {
	cin >> N >> K;
	a.resize(N);
	REP(i,0, N) {
		cin >> a[i];
		if (a[i] >= 0)ap.push_back(a[i]);
		else am.push_back(a[i]);
	}

	bool minus = false;
	int ccc = 0;
	while (ccc + 2 <= K && ccc + 2 <= am.size()) ccc += 2;
	if (ccc + ap.size() < K) minus = true;
	if (minus) {
		sort(a.begin(), a.end(), [](ll x, ll y) {return abs(x) < abs(y); });
		ll ret = 1;
		REP(i, 0, K) ret = mod(ret * a[i]);
		PRI(ret);
		return 0;
	}
	sort(ap.begin(), ap.end(), greater<ll>());
	sort(am.begin(), am.end(), less<ll>());
	vector<ll> pick(K);
	REP(i, 0, K) pick[i] = i < a.size() ? ap[i] : 0;
	sort(pick.begin(), pick.end(), less<ll>());
	for (int i = 0; i + 1 < K && i + 1 < am.size(); i += 2) {
		if (pick[i] * pick[i + 1] < am[i] * am[i + 1]) {
			pick[i] = am[i];
			pick[i + 1] = am[i + 1];
		}
		else break;
	}
	ll ret = 1;
	REP(i, 0, K) ret = mod(ret * pick[i]);
	PRI(ret);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int a[100005];
int zheng[100005];
int ffu[100005];
const long long mod=1e9+7;
bool cmp(int a,int b){
    return abs(a)>abs(b);
}

int n,k;
int main()
{
    scanf("%d%d",&n,&k);
    int s1=0,s2=0,kk=k;
    for(int i=0;i<n;i++)
	{
        scanf("%d",&a[i]);
        if(a[i]>0){
           zheng[s1]=a[i];s1++;
		   }
        if(a[i]<0){
           ffu[s2]=a[i];s2++;
		   }
    }
    sort(zheng,zheng+s1,cmp);
    sort(ffu,ffu+s2,cmp);
    long long ans=1;
    int ss1=0,ss2=0;
    while(true)
	{
        if(k==0)
           break;
        if(abs(zheng[ss1])>abs(ffu[ss2]))
		{
            ans=(ans*zheng[ss1])%mod;
            ss1++;
            k--;
        }
        else
		{
            ans=(ans*ffu[ss2])%mod;
            ss2++;
            k--;
        }
    }
    if(ans>0){
    printf("%lld\n",ans%mod);
    return 0;
    }
     if(ans>0){
    printf("%lld\n",ans%mod);
    return 0;
    }
    if(ans<0&&s1>0)
	{
        long long ans1=1;
        if(ss1<s1)
        ans1=(ans/ffu[ss2-1])*zheng[ss1]%mod;
        if(ss2<s2)
        ans=(ans/zheng[ss1-1])*ffu[ss2]%mod;
        printf("%lld",max(ans1,ans)%mod);
        return 0;
    }
    if(ans<0&&s1==0)
	{
        sort(ffu,ffu+s2);
        long long ans2=1;
        for(int i=s2-1;i>=0;i--)
            ans2=(ffu[i]*ans2%mod);
        printf("%lld",ans2%mod);
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using LL = long long;
using LD = long double;
using PII = pair<int, int>;
using PLI = pair<long long, int>;
using PLL = pair<long long, long long>;
using TI = tuple<int, int, int>;
mt19937 mrand(random_device{}());
int rnd(int x) { return mrand() % x; }
template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {
    return out << "(" << p.first << ", " << p.second << ")";
}
template <typename T, size_t N>
ostream& operator <<(ostream& out, const array<T, N>& a) {
    out << "["; bool first = true;
    for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
    return out;
}
template <typename T>
ostream& operator <<(ostream& out, const vector<T>& a) {
    out << "["; bool first = true;
    for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
    return out;
}
template <typename T>
ostream& operator <<(ostream& out, const deque<T>& a) {
    out << "["; bool first = true;
    for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
    return out;
}
template <typename T, class Cmp>
ostream& operator <<(ostream& out, const set<T, Cmp>& a) {
    out << "{"; bool first = true;
    for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "}";
    return out;
}
template <typename T>
ostream& operator <<(ostream& out, const unordered_set<T>& a) {
    out << "{"; bool first = true;
    for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "}";
    return out;
}
template <typename U, typename T, class Cmp>
ostream& operator <<(ostream& out, const map<U, T, Cmp>& a) {
    out << "{"; bool first = true;
    for (auto& p : a) { out << (first ? "" : ", "); out << p.first << ":" << p.second; first = 0;} out << "}";
    return out;
}
template<class T> inline void YES(T condition) {
    if(condition) cout << "YES" << '\n';
    else cout << "NO" << '\n';
}
template<class T> inline void Yes(T condition) {
    if(condition) cout << "Yes" << '\n';
    else cout << "No" << '\n';
}
template<class T> T gcd(T a, T b) {
    while (b) {
        T tmp = b;
        b = a % b;
        a = tmp;
    }
    return a;
}
template<class T> T lcm(T a, T b){
    return a / gcd(a, b) * b;
}

#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    cerr << name << ": " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');
    cerr.write(names, comma - names) << ": " << arg1 << " |";
    __f(comma + 1, args...);
}

long long qpow(long long a, long long b, int MOD) {
    if (b == 0) return 1;
    long long res = 1;
    while (b) {
        if (b & 1) res = (res * a) % MOD;
        a = (a * a) % MOD;
        b >>= 1;
    }
    return res;
}

const int MOD = 1e9 + 7;
const int maxn = 2e6;
int fac[maxn + 5];
int invfac[maxn + 5];
void init() {
    fac[0] = 1;
    for (int i = 1; i <= maxn; i++) fac[i] = 1LL * fac[i - 1] * i % MOD;
    invfac[maxn] = (int)(qpow(fac[maxn], MOD - 2, MOD));
    for (int i = maxn - 1; i >= 0; i--) invfac[i] = 1LL * invfac[i + 1] * (i + 1) % MOD;
}
int C(int n, int k) {
    assert(0 <= k && n >= k);
    int tmp = (int)(1LL * invfac[k] * invfac[n - k] % MOD);
    return (int)(1LL * fac[n] * tmp % MOD);
}

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

    int n, k;
    cin >> n >> k;
    vector<LL> a(n), pos, zero, neg;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        if (a[i] > 0) {
            pos.push_back(a[i]);
        } else if (a[i] == 0) {
            zero.push_back(a[i]);
        } else {
            neg.push_back(a[i]);
        }
    }
    sort(pos.begin(), pos.end());
    sort(neg.begin(), neg.end());
    reverse(neg.begin(), neg.end());
    int pcnt = pos.size(), zcnt = zero.size(), ncnt = neg.size();
    LL ALL = 1;
    for (auto& v: a) ALL = (ALL * v) % MOD;
    ALL = (ALL + MOD) % MOD;
    if (k == 1) {
        LL ans = *max_element(a.begin(), a.end()) % MOD;
        cout << (ans + MOD) % MOD << '\n';
        return 0;
    }
    if (k == pcnt + zcnt + ncnt) {
        cout << ALL << '\n';
        return 0;
    }
    if (k > pcnt + ncnt) {
        cout << 0 << '\n';
        return 0;
    } else if (pcnt == 0) {
        if (k & 1) {
            if (zcnt) { cout << 0 << '\n'; return 0; }
            LL now = 1;
            for (int i = 0; i < k; i++) now = (now * neg[i]) % MOD;
            cout << (now + MOD) % MOD << '\n';
            return 0;
        } else {
            if (k > ncnt) { cout << 0 << '\n'; return 0; }
            LL now = 1;
            for (int i = ncnt - 1; i; i--) now = (now * neg[i]) % MOD;
            cout << (now + MOD) % MOD << '\n';
            return 0;
        }
    } else {
        LL now = 1;
        int i = pos.size() - 1, j = neg.size() - 1;
        for (; k; ) {
            if (k == 1) {
                if (i >= 0) now = now * pos[i--] % MOD;
                else if (j >= 1) {
                    now = now * qpow(a[0], MOD - 2, MOD) % MOD;
                    now = now * abs(neg[j--]) % MOD;
                    now = now * abs(neg[j--]) % MOD;
                } else {
                    now = now * a[j] % MOD;
                }
                k--;
            } else {
                LL P = 0, N = 0;
                if (i >= 1) P = pos[i] * pos[i - 1];
                else if (i == 0) P = pos[i];
                if (j >= 1) N = neg[j] * neg[j - 1];
                else if (j == 0) N = neg[j];
                if (P > N) {
                    now = now * (P % MOD) % MOD;
                    k -= 1 + (i > 0);
                    i -= 1 + (i > 0);
                } else {
                    now = now * (N % MOD) % MOD;
                    k -= 1 + (j > 0);
                    j -= 1 + (j > 0);
                }
            }
        }

        cout << (now + MOD) % MOD << '\n';
    }

    return 0;
}


/*
* welcome to my code!
* ------------------------------------------
* author : lynmisakura(twitter : @andoreiji11)
*/

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

using ll = long long;

#define REP(i,n) for(int i = 0;i < n;i++)
#define all(x) x.begin(),x.end()
#define dup(x,y) (x + y - 1)/y
#define sz(v) (int)v.size()
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define fi first
#define se second

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

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

    int N;
    cin >> N;

    ll ans = 0;
    for(ll i = 0;i <= N - 1;i++){
        ans += (i + 1) * (N - i);
    }

    REP(i,N - 1){

       int u,v;cin >> u >> v;
       if(u > v)swap(u,v);

       ans -= u * (N + 1 - v);

    }

    cout << ans << '\n';

}

Score : 600 points

Problem Statement

We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i.

For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows:

Let S be the set of the vertices numbered L through R. f(L, R) represents the number of connected components in the subgraph formed only from the vertex set S and the edges whose endpoints both belong to S.

Compute \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Constraints

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

1 \leq u_i, v_i \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Sample Input 1

3
1 3
2 3

Sample Output 1

7

We have six possible pairs (L, R) as follows:

For L = 1, R = 1, S = \{1\} and we have 1 connected component.

For L = 1, R = 2, S = \{1, 2\} and we have 2 connected components.

For L = 1, R = 3, S = \{1, 2, 3\} and we have 1 connected component, since S contains both endpoints of each of the edges 1, 2.

For L = 2, R = 2, S = \{2\} and we have 1 connected component.

For L = 2, R = 3, S = \{2, 3\} and we have 1 connected component, since S contains both endpoints of Edge 2.

For L = 3, R = 3, S = \{3\} and we have 1 connected component.

The sum of these is 7.

Sample Input 2

2
1 2

Sample Output 2

3

Sample Input 3

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

Sample Output 3

113


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    cout<<n+n*n+n*n*n<<endl;
    return 0;
}

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


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

int main() {
  int a;
  cin >> a;
  int ans = a;
  ans += a * a;
  ans += a * a * a;
  cout << ans << endl;
  return 0;
}


#include<bits/stdc++.h>

#define all(n) n.begin(),n.end()
#define ll long long

#define pb push_back
#define eb emplace_back
#define endl "\n"
#define pll pair<ll,ll>

#define ff first
#define ss second

using namespace std;
const ll maxn=1e6+2;
const ll maxx=1e16;
const ll mod=998244353;
const ll mod1=998244353;

vector<ll>  ans[maxn];
pll a[maxn];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    if (fopen("TEAMS.INP","r"))
    {
        freopen("TEAMS.INP", "r", stdin);
        freopen("TEAMS.OUT", "w", stdout);
    }
   string s;
    string t;
     cin>>s>>t;
      ll ans=0;
      for (int i=0;i<s.length();i++)
      {
          if (s[i]!=t[i]) ans++;
      }
      cout <<ans;

}

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


#include<bits/stdc++.h>
using namespace std;
int main()
{
  char c;
  cin>>c;
  int d=(int)c;
  if(d>=65 && d<=90)
  {
    cout << 'A'<<'\n';
  }
  if(d>=97 && d<=122)
  {
    cout << 'a'<<'\n';
  }
}

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


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

int main() {
    char c;
    cin >> c;
    if (c >= 'A' && c <= 'Z') cout << 'A' << endl;
    else cout << 'a' << endl;
    return 0;
}


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

int main () {
    int n, k;
    while (scanf("%d %d", &n, &k) == 2) {
        vector<int> p(n, 0);
        for (int i = 0; i < n; i++) scanf("%d", &p[i]);
        sort(p.begin(), p.end());
        long long s = 0;
        for (int i = 0; i < n && i < k; i++) s += p[i];
        printf("%lld\n", s);
    }
}

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000