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

long long x;

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

	cin >> x;

	long long lo = 1, mid, hi = 1e15;
	while (lo <= hi) {
		mid = (lo+hi) / 2;
		long long R = (mid / 2 + (mid&1)) * 6 + (mid / 2) * 5;
		long long L = R - ((mid&1) ? 6 : 5) + 1;
		if (L <= x && x <= R) {
			cout << mid << '\n';
			return 0;
		}
		else if (R <= x) {
			lo = mid+1;
		}
		else {
			hi = mid-1;
		}
	}

	return 0;
}

Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

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

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


#include<bits/stdc++.h>
#define F first
#define S second
#define MP make_pair
#define pb push_back
#define endl '\n'

using namespace std;

typedef long long LL;
typedef pair< int, int > P;
typedef pair< LL, LL > LP;
typedef pair< int, P > iP;
typedef pair< P, P > PP;

static const int INF = INT_MAX;
static const LL LINF = LLONG_MAX;
static const int MIN = INT_MIN;
static const LL LMIN = LLONG_MIN;
static const int MOD = 1000000007;
static const int SIZE = 100005;

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

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

    int n;
    cin >> n;
    int cnt[SIZE] = {};
    for( int i = 0; i < n; ++i ) {
        int a;
        cin >> a;
        ++cnt[a];

    }

    int res = 0;
    for( int i = 1; i < SIZE; ++i ) {
        res += max( 0, cnt[i] - 1 );

    }

    if( res % 2 ) ++res;
    cout << n - res << endl;

    return 0;
}

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

Score : 400 points

Problem Statement

Snuke has decided to play a game using cards.
He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written.

He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept.

Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck.

Constraints

3 ≦ N ≦ 10^{5}

N is odd.

1 ≦ A_i ≦ 10^{5}

A_i is an integer.

Input

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

N
A_1 A_2 A_3 ... A_{N}

Output

Print the answer.

Sample Input 1

5
1 2 1 3 7

Sample Output 1

3

One optimal solution is to perform the operation once, taking out two cards with 1 and one card with 2. One card with 1 and another with 2 will be eaten, and the remaining card with 1 will be returned to deck. Then, the values written on the remaining cards in the deck will be pairwise distinct: 1, 3 and 7.

Sample Input 2

15
1 3 5 2 1 3 2 8 8 6 2 6 11 1 1

Sample Output 2

7

Submitted source-code file size, in bytes.

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

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


// AGC009_A
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <iterator>  // std::back_inserter()
#include <tuple>  // std::tuple std::get
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
#include <algorithm>  // std::copy()
#include <functional>  // std::greater<T>()
#include <utility>  // std::swap()
#include <numeric>  // accumulate(ALL(vec), 0)  0 は初期値
#include <bitset>  // static_cast<std::bitset<8>>
#include <sstream>  // std::stringstream
#include <cmath>
#include <climits>  // INT_MIN
#include <cctype>  // std::isdigit()
#include <iomanip>  // std::setprecision()
using namespace std;

#define ALL(obj) (obj).begin(), (obj).end()
#define REP(i, n) for (ll i=0; i < n; i++)  // 0 ~ n-1
#define REPN(i, n) for (ll i=1; i <= n; i++)  // 1 ~ n
#define MIN(vec) min_element(ALL((vec)))  // イテレータのため、値を取り出すときは * を先頭につける
#define MAX(vec) max_element(ALL((vec)))
#define IDX(vec, element_iter) distance((vec).begin(), element_iter)
#define SUM(vec) accumulate(ALL((vec)), 0LL)  // 0 は初期値
#define COPY(vec1, vec2) copy(ALL(vec1), back_inserter(vec2))  // vec1をvec2にコピーする vec2は空にしておく必要あり
#define zero_pad(num) setfill('0') << std::right << setw(num)
#define space_pad(num) setfill(' ') << std::right << setw(num)

typedef long long ll;

const ll MOD7 = 1000000007;  // 1 000 000 007
const ll MOD9 = 1000000009;  // 1 000 000 009

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

    // input
    ll N;
    cin >> N;
    vector<ll> A(N), B(N), diff(N);
    REP(i, N) {
        cin >> A[i] >> B[i];
        if (A[i] <= B[i]) {
            diff[i] = B[i] - A[i];
        } else {
            diff[i] = B[i] - A[i]%B[i];
        }
    }

    // calculation
    // 何回押さないといけないか
    reverse(diff.begin(), diff.end());
    ll res = diff[0], now;
    for (ll i = 1; i < N; ++i) {
        now = A[i] + res;
        if (now <= B[i]) {
            res += B[i] - A[i];
        } else {
            res += B[i] - now%B[i];
        }
    }

    cout << res << "\n";

    return 0;
}

Score : 300 points

Problem Statement

There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons.
When the i-th (1 ≦ i ≦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1.

There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so that for every i, A_i will be a multiple of B_i.

Find the minimum number of times Takahashi will press the buttons.

Constraints

All input values are integers.

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9(1 ≦ i ≦ N)

1 ≦ B_i ≦ 10^9(1 ≦ i ≦ N)

Input

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

N
A_1 B_1
:
A_N B_N

Output

Print an integer representing the minimum number of times Takahashi will press the buttons.

Sample Input 1

3
3 5
2 7
9 4

Sample Output 1

7

Press the first button twice, the second button twice and the third button three times.

Sample Input 2

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

Sample Output 2

22


/*
ID: y1197771
PROG: test
LANG: C++
*/
#include<bits/stdc++.h>
#define pb push_back
#define FOR(i, n) for (int i = 0; i < (int)n; ++i)
#define dbg(x) cout << #x << " at line " << __LINE__ << " is: " << x << endl
typedef long long ll;
using namespace std;
typedef pair<int, int> pii;
const int maxn = 1e3 + 10;
void solve() {
    int x, y, a, b;
    cin >> x >> y >> a >> b;
    cout << max(x * y, a * b) << endl;
}
int main() {
    //freopen("test.in", "r", stdin);
    //freopen("test.out", "w", stdout);
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    solve();
    return 0;
}

Score : 100 points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B.
The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

1≤A≤10^4

1≤B≤10^4

1≤C≤10^4

1≤D≤10^4

Input

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

A B C D

Output

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of 3×5=15, and the second rectangle has an area of 2×7=14.
Thus, the output should be 15, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000


#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <iomanip>
#include <numeric>
#include <queue>
#include <cmath>
using namespace std;

int main() {
    int n;
    cin >> n;
    string s;
    cin >> s;
    int res = 0;
    int c = 0;
    for (auto ss : s) {
        if (ss == 'I') {
            c++;
        } else {
            c--;
        }
        res = max(res, c);
    }
    cout << res << endl;
}

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

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

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


#include <bits/stdc++.h>
#define rep(i,n) for (int i = (0); i < (n); ++i)
#define rrep(i,n) for(int i = 1; i <= (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
#define rng(x) (x).begin(),(x).end()
#define rrng(x) (x).rbegin(),(x).rend()
#define limit(x,l,r) max(l,min(x,r))
#define lims(x,l,r) (x = max(l,min(x,r)))
#define isin(x,l,r) ((l) <= (x) && (x) < (r))
#define show(x) cout << #x << " = " << (x) << endl
#define show2(x,y) cout << #x << " = " << (x) << ", " << #y << " = " << (y) << endl
#define show3(x,y,z) cout << #x << " = " << (x) << ", " << #y << " = " << (y) <<  ", " << #z << " = " << (z) << endl
#define showv(v) rep(i,v.size()) printf("%d%c", v[i], i==v.size()-1?'\n':' ')
#define showv2(v) rep(j,v.size()) showv(v[j])
#define showt(t,n) rep(i,n) printf("%d%c", t[i], i==n-1?'\n':' ')
#define showt2(t,r,c) rep(j,r) showt(t[j],c)
#define showvp(p) rep(i,p.size()) printf("%d %d\n", p[i].first, p[i].second);
#define printv(v) rep(i,v.size()) printf("%d\n", v[i])
#define printt(t,n) rep(i,n) printf("%d\n", t[i])
#define incl(v,x) find(rng(v),x)!=v.end()
#define incls(s,c) s.find(c)!=string::npos
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define sz(x) (int)(x).size()
#define pcnt __builtin_popcountll
#define bit(n,k) ((n>>k)&1) // nのk bit目
#define bn(x) ((1<<x)-1)
#define dup(x,y) (((x)+(y)-1)/(y))
#define newline puts("")
#define uni(x) x.erase(unique(rng(x)),x.end())
#define SP << " " <<
#define v(T) vector<T>
#define vv(T) v(v(T))
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vl = vector<ll>;
using vs = vector<string>;
using P = pair<int, int>;
using T = tuple<int, int, int>;
using vp = vector<P>;
using vt = vector<T>;
const int mod = 1000000007;
const double EPS = 1e-9;
const int INF = (1<<30)-1;
//const ll INF = (1LL<<62)-1;
#define dame { puts("No"); return 0;}
#define yn {puts("Yes");}else{puts("No");}
//inline int in() { int x; scanf("%d",&x); return x;}
template<class T = int> inline T in() { T x; cin >> x; return (x);}
template<typename T>inline ll suma(const v(T)& a) { ll res(0); for (auto&& x : a) res += x; return res;}
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; }

int main () {
  ll n, a, b;
  cin >> n >> a >> b;
  vl x(n);
  rep(i,n) cin >> x[i];

  ll ans = 0;
  rep(i,n-1) {
    ans += min(a*(x[i+1]-x[i]),b);
  }
  cout << ans << endl;
  return 0;
}

Score : 500 points

Problem Statement

There are N towns on a line running east-west.
The towns are numbered 1 through N, in order from west to east.
Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value.
The coordinate of town i is X_i.

You are now at town 1, and you want to visit all the other towns.
You have two ways to travel:

Walk on the line.
Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.

Teleport to any location of your choice.
Your fatigue level increases by B, regardless of the distance covered.

Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

Constraints

All input values are integers.

2≤N≤10^5

1≤X_i≤10^9

For all i(1≤i≤N-1), X_i<X_{i+1}.

1≤A≤10^9

1≤B≤10^9

Input

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

N A B
X_1 X_2 ... X_N

Output

Print the minimum possible total increase of your fatigue level when you visit all the towns.

Sample Input 1

4 2 5
1 2 5 7

Sample Output 1

11

From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4.
The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.

Sample Input 2

7 1 100
40 43 45 105 108 115 124

Sample Output 2

84

From town 1, walk all the way to town 7.
The total increase of your fatigue level in this case is 84, which is the minimum possible value.

Sample Input 3

7 1 2
24 35 40 68 72 99 103

Sample Output 3

12

Visit all the towns in any order by teleporting six times.
The total increase of your fatigue level in this case is 12, which is the minimum possible value.


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

#define ll long long int
#define pb push_back
#define mk make_pair
#define pq priority_queue

using namespace std;
typedef pair<int, int> P;
typedef pair<ll, int> Pl;
typedef pair<ll, ll> Pll;
const int inf = 1e9;
const ll linf = 1LL << 50;

int main(int argc, char const* argv[])
{
  int sx, sy, tx, ty;
  cin >> sx >> sy >> tx >> ty;
  cout << "D";
  for(int i = 0; i < tx - sx + 1; i++)cout << "R";
  for(int i = 0; i < ty - sy + 1; i++)cout << "U";
  cout << "L";
  for(int i = 0; i < ty - sy; i++)cout << "D";
  for(int i = 0; i < tx - sx; i++)cout << "L";
  for(int i = 0; i < ty - sy; i++)cout << "U";
  for(int i = 0; i < tx - sx; i++)cout << "R";
  cout << "U";
  for(int i = 0; i < tx - sx + 1; i++)cout << "L";
  for(int i = 0; i < ty - sy + 1; i++)cout << "D";
  cout << "R" << endl;
	return 0;
}

Score : 300 points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.

Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.

Here, both the x- and y-coordinates before and after each movement must be integers.

He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

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

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.

The i-th character in S should correspond to his i-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)

Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)

Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (-1,0) → (-1,1) → (-1,2) → (-1,3) → (0,3) → (1,3) → (1,2)

Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,-1) → (1,-1) → (0,-1) → (0,0)

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


#include<iostream>
using namespace std;

int main() {
    int sx, sy, tx, ty;
    cin >> sx >> sy >> tx >> ty;
    for (int i = 0; i < ty - sy; i++) {
        cout << 'U';
    }
    for (int i = 0; i < tx - sx; i++) {
        cout << 'R';
    }
    for (int i = 0; i < ty - sy; i++) {
        cout << 'D';
    }
    for (int i = 0; i < tx - sx + 1; i++) {
        cout << 'L';
    }
    for (int i = 0; i < ty - sy + 1; i++) {
        cout << 'U';
    }
    for (int i = 0; i < tx - sx + 1; i++) {
        cout << 'R';
    }
    cout << "DR";
    for (int i = 0; i < ty - sy + 1; i++) {
        cout << 'D';
    }
    for (int i = 0; i < tx -sx + 1; i++) {
        cout << 'L';
    }
    cout << 'U' << endl;
    return 0;
}


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

#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(), (x).end()

typedef long long ll;
typedef long double ld;

const int INF = 1e9;
const ld EPS = 1e-8;

int main(){
  int sx, sy, tx, ty;
  cin >> sx >> sy >> tx >> ty;

  string res;

  REP(i,ty - sy) res += "U";
  REP(i,tx - sx) res += "R";

  REP(i,ty - sy) res += "D";
  REP(i,tx - sx) res += "L";

  res += "L";
  REP(i,ty - sy + 1) res += "U";
  REP(i,tx - sx + 1) res += "R";
  res += "D";

  res += "R";
  REP(i,ty - sy + 1) res += "D";
  REP(i,tx - sx + 1) res += "L";
  res += "U";

  cout << res << endl;
  return 0;
}


#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 110
#define MAX_E 1010
#define INF 10000000

int e[MAX][MAX];
int d[MAX][MAX];
int n;

void warshall_floyd() {
  for (int k = 0; k < n; k++) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        if (d[i][j] > d[i][k] + d[k][j]) {
          d[i][j] = d[i][k] + d[k][j];
        }
      }
    }
  }
}

bool contains(int i, int j) {
  for (int s = 0; s < n; s++) {
    if (s == j) continue;
    if (d[s][i] + e[i][j] == d[s][j]) return true;
  }
  return false;
}

int main() {
  for (int i = 0; i < MAX; i++) {
    for (int j = 0; j < MAX; j++) {
      if (i == j) d[i][j] = 0;
      else d[i][j] = INF;
    }
  }
  int m;
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      if (i == j) e[i][j] = 0;
      else e[i][j] = INF;
    }
  }
  for (int i = 0; i < m; i++) {
    int a, b, c;
    cin >> a >> b >> c;
    e[a - 1][b - 1] = c;
    e[b - 1][a - 1] = c;
    d[a - 1][b - 1] = c;
    d[b - 1][a - 1] = c;
  }
  warshall_floyd();
  int ans = 0;
  for (int i = 0; i < n; i++) {
    for (int j = i; j < n; j++) {
      if (e[i][j] != INF && e[i][j] > d[i][j]) ans++;
    }
  }
  cout << ans << endl;
  return 0;
}

Score : 400 points

Problem Statement

You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

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

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <math.h>
#include <iomanip>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdlib>
#include <map>
using namespace std;
#define int long long
#define rep(i,n) for(int i=0;i<n;i++)
#define pie 3.141592653589793238462643383279
#define mod 1000000007
#define inf 10000000000000007
#define all(vec) vec.begin(),vec.end()
#define ggr getchar(); getchar();return 0;
int gcd(int x, int y) {
	if (y == 0)return x;
	return gcd(y, x % y);
}
int lcm(int x, int y) {
	return x / gcd(x, y) * y;
}
bool prime(int x) {
	for (int i = 2; i <= sqrt(x); i++) {
		if (x % i == 0)return false;
	}
	return true;
}

int n, k, a[100010];
int ta, mu, rin, ans;

signed main() {
	cin >> n >> k;
	rep(i, n) {
		cin >> a[i];
		if (a[i] > 0)ta += a[i];
	}
	rep(i, n) {
		if (i <= k - 1) {
			if (a[i] > 0)mu += a[i];
			rin += a[i];
		}
		else {
			if (a[i - (k - 1)] > 0)mu -= a[i - (k - 1)];
			rin -= a[i - (k - 1)];
			if (a[i] > 0)mu += a[i];
			rin += a[i];
		}
		if (i > k - 2)ans = max({ ans,ta + rin - mu,ta - mu });;
	}
	cout << ans << endl;
}

Score : 400 points

Problem Statement

There are N squares aligned in a row.
The i-th square from the left contains an integer a_i.

Initially, all the squares are white.
Snuke will perform the following operation some number of times:

Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares are overwritten.

After Snuke finishes performing the operation, the score will be calculated as the sum of the integers contained in the black squares.
Find the maximum possible score.

Constraints

1≤N≤10^5

1≤K≤N

a_i is an integer.

|a_i|≤10^9

Input

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

N K
a_1 a_2 ... a_N

Output

Print the maximum possible score.

Sample Input 1

5 3
-10 10 -10 10 -10

Sample Output 1

10

Paint the following squares black: the second, third and fourth squares from the left.

Sample Input 2

4 2
10 -10 -10 10

Sample Output 2

20

One possible way to obtain the maximum score is as follows:

Paint the following squares black: the first and second squares from the left.

Paint the following squares black: the third and fourth squares from the left.

Paint the following squares white: the second and third squares from the left.

Sample Input 3

1 1
-10

Sample Output 3

0

Sample Input 4

10 5
5 -4 -5 -8 -4 7 2 -4 0 7

Sample Output 4

17


#include <bits/stdc++.h>
//typedef
//-------------------------#include <bits/stdc++.h>

const double pi = 3.141592653589793238462643383279;

using namespace std;

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

//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<long long, long long> PLL;
typedef pair<int, PII> TIII;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;

//container util

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

//repetition
//------------------------------------------
#define FOR(i,s,n) for(int i=s;i<(int)n;++i)
#define REP(i,n) FOR(i,0,n)
#define MOD 1000000007

#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const double EPS = 1E-8;

#define chmin(x,y) x=min(x,y)
#define chmax(x,y) x=max(x,y)

class UnionFind {
public:
    vector <int> par;
    vector <int> siz;

    UnionFind(int sz_): par(sz_), siz(sz_, 1) {
        for (ll i = 0; i < sz_; ++i) par[i] = i;
    }
    void init(int sz_) {
        par.resize(sz_);
        siz.assign(sz_, 1LL);
        for (ll i = 0; i < sz_; ++i) par[i] = i;
    }

    int root(int x) {
        while (par[x] != x) {
            x = par[x] = par[par[x]];
        }
        return x;
    }

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

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

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

ll modPow(ll x, ll n, ll mod = MOD){
    ll res = 1;
    while(n){
        if(n&1) res = (res * x)%mod;

        res %= mod;
        x = x * x %mod;
        n >>= 1;
    }
    return res;
}

#define SIEVE_SIZE 5000000+10
bool sieve[SIEVE_SIZE];
void makeSieve(){
    for(int i=0; i<SIEVE_SIZE; ++i) sieve[i] = true;
    sieve[0] = sieve[1] = false;
    for(int i=2; i*i<SIEVE_SIZE; ++i) if(sieve[i]) for(int j=2; i*j<SIEVE_SIZE; ++j) sieve[i*j] = false;
}

bool isprime(ll n){
    if(n == 0 || n == 1) return false;
    for(ll i=2; i*i<=n; ++i) if(n%i==0) return false;
    return true;
}

const int MAX = 2000010;
long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < 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;
    }
}

// 二項係数計算
long long COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

long long extGCD(long long a, long long b, long long &x, long long &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    long long d = extGCD(b, a%b, y, x);
    y -= a/b * x;
    return d;
}
// 負の数にも対応した mod (a = -11 とかでも OK)
inline long long mod(long long a, long long m) {
    return (a % m + m) % m;
}

// 逆元計算 (ここでは a と m が互いに素であることが必要)
long long modinv(long long a, long long m) {
    long long x, y;
    extGCD(a, m, x, y);
    return mod(x, m); // 気持ち的には x % m だが、x が負かもしれないので
}
ll GCD(ll a, ll b){

    if(b == 0) return a;
    return GCD(b, a%b);
}

typedef vector<ll> vec;
typedef vector<vec> mat;

mat mul(mat &A, mat &B) {
    mat C(A.size(), vec((int)B[0].size()));
    for(int i=0; i<A.size(); ++i){
        for(int k=0; k<B.size(); ++k){
            for(int j=0; j<B[0].size(); ++j){
                C[i][j] = (C[i][j] + A[i][k] * B[k][j] %MOD) % MOD;
            }
        }
    }
    return C;
}
mat matPow(mat A, ll n) {
    mat B(A.size(), vec((int)A.size()));

    for(int i=0; i<A.size(); ++i){
        B[i][i] = 1;
    }

    while(n > 0) {
        if(n & 1) B = mul(B, A);
        A = mul(A, A);
        n >>= 1;
    }
    return B;
}

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

    ll ai,ao,at,aj,al,as,az;cin>>ai>>ao>>at>>aj>>al>>as>>az;

    ll ans = 0;

    for(ll i=0; i<=min({ai, aj, al}); i++){
        ans = max(ans, ao+i*3 + (ai-i)/2*2 + (aj-i)/2*2 + (al-i)/2*2);
    }
    cout << ans << endl;
    return 0;
}

Score : 600 points

Problem Statement

A tetromino is a figure formed by joining four squares edge to edge.
We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:

Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession are a_I, a_O, a_T, a_J, a_L, a_S and a_Z, respectively.
Snuke will join K of his tetrominos to form a rectangle that is two squares tall and 2K squares wide.
Here, the following rules must be followed:

When placing each tetromino, rotation is allowed, but reflection is not.

Each square in the rectangle must be covered by exactly one tetromino.

No part of each tetromino may be outside the rectangle.

Snuke wants to form as large a rectangle as possible.
Find the maximum possible value of K.

Constraints

0≤a_I,a_O,a_T,a_J,a_L,a_S,a_Z≤10^9

a_I+a_O+a_T+a_J+a_L+a_S+a_Z≥1

Input

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

a_I a_O a_T a_J a_L a_S a_Z

Output

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

Sample Input 1

2 1 1 0 0 0 0

Sample Output 1

3

One possible way to form the largest rectangle is shown in the following figure:

Sample Input 2

0 0 10 0 0 0 0

Sample Output 2

0

No rectangle can be formed.


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

int an = 1, cy[100001], md = 1e9 + 7, dp[100001][2];
pair<int, int> y[100001], ln[100001];
bool vis[100001];

void no(){
	printf("0\n");
	exit(0);
}

int V;
bool go(int v, int m = 0, int d = 0){
	if (vis[v]){
		if (v == V) { ln[m].first = d; return true; }
		return false;
	}
	vis[v] = true;
	if (!y[v].first) { ln[m].second = d; return false; }
	bool k = go(y[v].first, y[v].second ? v : m, d + 1);
	if (y[v].second)ln[m].first = d, k |= go(y[v].second, v, d + 1);
	return k;
}

inline void ad(int s, int l){
	dp[0][0] = 1;
	int z = (s & 1 && s != 1) + 1;
	f(i, 1, l + 1){
		dp[i][0] = ((ll)dp[i - 1][0] * z + (ll)dp[i - 1][1] * s) % md;
		dp[i][1] = ((ll)dp[i - 1][1] * z + dp[i - 1][0]) % md;
	}
	an = (ll)an * dp[l][0] % md;
}

int main(){
	int n;
	scanf("%d", &n);
	f(i, 1, n + 1){
		int t;
		scanf("%d", &t);
		if (y[t].first){
			if (y[t].second)no();
			y[t].second = i;
		}
		else y[t].first = i;
	}
	f(i, 1, n + 1)if (y[i].second){
		V = i;
		if (!vis[i] && !go(i))no();
		if (!ln[i].second)no();
		if (ln[i].first > ln[i].second) { if ((an <<= 1) >= md)an -= md; }
		else if (ln[i].first < ln[i].second)no();
	}
	f(i, 1, n + 1)if (!vis[i]){
		V = i;
		if (go(i, i))++cy[ln[i].first];
	}
	f(i, 1, n + 1)if (cy[i])ad(i, cy[i]);
	printf("%d\n", an);
}

Score : 1400 points

Problem Statement

You are given an integer sequence a of length N.
How many permutations p of the integers 1 through N satisfy the following condition?

For each 1 ≤ i ≤ N, at least one of the following holds: p_i = a_i and p_{p_i} = a_i.

Find the count modulo 10^9 + 7.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ N

Input

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

N
a_1 a_2 ... a_N

Output

Print the number of the permutations p that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

3
1 2 3

Sample Output 1

4

The following four permutations satisfy the condition:

(1, 2, 3)

(1, 3, 2)

(3, 2, 1)

(2, 1, 3)

For example, (1, 3, 2) satisfies the condition because p_1 = 1, p_{p_2} = 2 and p_{p_3} = 3.

Sample Input 2

2
1 1

Sample Output 2

1

The following one permutation satisfies the condition:

(2, 1)

Sample Input 3

3
2 1 1

Sample Output 3

2

The following two permutations satisfy the condition:

(2, 3, 1)

(3, 1, 2)

Sample Input 4

3
1 1 1

Sample Output 4

0

Sample Input 5

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

Sample Output 5

6


#include <iostream>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#define llint long long
#define inf 1000000000

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

llint n;
vector<llint> G[200005];
vector<llint> dp[200005], dp2[200005];
llint pid[200005];
vector<P> E;
string s;

map<P, llint> Ginv;
vector<llint> lmin[200005], rmin[200005];

void dfs(int v, int p)
{
	pid[v] = -1;
	for(int i = 0; i < G[v].size(); i++){
		int u = G[v][i];
		if(u == p){
			pid[v] = i;
			continue;
		}
		dfs(u, v);

		llint mx = 0, mn = inf;
		for(int j = 0; j < G[u].size(); j++){
			if(G[u][j] == v) continue;
			mx = max(mx, dp[u][j]);
			mn = min(mn, dp2[u][j]);
		}
		dp[v][i] = mx + 1;
		if(s[u] == '1') mn = 0;
		if(s[v] == '1') mn = -1;
		dp2[v][i] = mn + 1;
	}
}

llint lmx[200005], rmx[200005];
llint lmn[200005], rmn[200005];
void dfs2(int v, int p)
{
	for(int i = 0; i < G[v].size(); i++){
		lmx[i] = dp[v][i];
		if(i > 0) lmx[i] = max(lmx[i], lmx[i-1]);
		lmn[i] = dp2[v][i];
		if(i > 0) lmn[i] = min(lmn[i], lmn[i-1]);
	}
	for(int i = (int)G[v].size()-1; i >= 0; i--){
		rmx[i] = dp[v][i];
		if(i < (int)G[v].size()-1) rmx[i] = max(rmx[i], rmx[i+1]);
		rmn[i] = dp2[v][i];
		if(i < (int)G[v].size()-1) rmn[i] = min(rmn[i], rmn[i+1]);
	}
	for(int i = 0; i < G[v].size(); i++){
		int u = G[v][i];
		if(u == p) continue;
		llint mx = 0;
		if(i > 0) mx = max(mx, lmx[i-1]);
		if(i < (int)G[v].size()-1) mx = max(mx, rmx[i+1]);
		dp[u][pid[u]] = mx+1;

		llint mn = inf;
		if(i > 0) mn = min(mn, lmn[i-1]);
		if(i < (int)G[v].size()-1) mn = min(mn, rmn[i+1]);
		if(s[v] == '1') mn = 0;
		if(s[u] == '1') mn = -1;
		dp2[u][pid[u]] = mn+1;
	}
	for(int i = 0; i < G[v].size(); i++){
		if(G[v][i] == p) continue;
		dfs2(G[v][i], v);
	}
}

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

	cin >> n;
	llint u, v;
	for(int i = 1; i <= n-1; i++){
		cin >> u >> v;
		G[u].push_back(v);
		G[v].push_back(u);
		E.push_back(make_pair(u, v));
	}
	cin >> s;
	s = "#" + s;

	for(int i = 1; i <= n; i++) dp[i].resize(G[i].size()), dp2[i].resize(G[i].size());
	dfs(1, -1);
	dfs2(1, -1);

	/*for(int i = 1; i <= n; i++){
		for(int j = 0; j < dp[i].size(); j++){
			cout << i << G[i][j] << " " << dp2[i][j] << endl;
		}
	}*/

	llint ans = 0;
	for(int i = 1; i <= n; i++){
		//cout << i << " " << ans << endl;
		if(s[i] == '1'){
			ans++;
			vector<llint> vec;
			if(G[i].size() <= 1) continue;
			for(int j = 0; j < G[i].size(); j++) vec.push_back(dp[i][j]);
			sort(vec.rbegin(), vec.rend());
			ans += min(vec[0], vec[1]);
		}
		else{
			vector<P> vec, vec2;
			if(G[i].size() <= 1) continue;
			for(int j = 0; j < G[i].size(); j++){
				llint dep = dp[i][j], dep2 = dp2[i][j], x = 1;
				if(dep >= dep2) x = 0;
				vec.push_back(make_pair(dep, x));
			}
			sort(vec.begin(), vec.end());

			bool flag = false;
			for(int j = 0; j < vec.size(); j++){
				if(vec[j].second == 0) flag = true;
				if(flag) vec2.push_back(vec[j]);
			}
			if(vec2.size() <= 1) continue;

			if(vec2.size() >= 3){
				llint mx2 = vec2[vec2.size()-2].first;
				ans += max(0LL, mx2 - vec2.front().first + 1);
			}
			/*set<llint> S;
			if(vec[1].first < mn2 && vec[1].second == 1) S.insert(vec[1].first);
			if(vec[0].first < mn2 && vec[0].second == 1) S.insert(vec[0].first);
			ans += S.size();*/
		}
		//cout << i << " " << ans << endl;
	}

	for(int i = 1; i <= n; i++){
		lmin[i].resize(G[i].size()), rmin[i].resize(G[i].size());
		for(int j = 0; j < G[i].size(); j++){
			Ginv[make_pair(i, G[i][j])] = j;
			lmin[i][j] = dp2[i][j];
			if(j > 0) lmin[i][j] = min(lmin[i][j], lmin[i][j-1]);
		}
		for(int j = (int)G[i].size()-1; j >= 0; j--){
			rmin[i][j] = dp2[i][j];
			if(j < (int)G[i].size()-1) rmin[i][j] = min(rmin[i][j], rmin[i][j+1]);
		}
	}

	for(int i = 0; i < E.size(); i++){
		llint u = E[i].first, v = E[i].second;
		llint umx = dp[v][Ginv[make_pair(v, u)]]-1, vmx = dp[u][Ginv[make_pair(u, v)]]-1;
		llint d = min(umx, vmx);

		llint umx2 = inf, vmx2 = inf;
		if(s[u] == '1') umx2 = 0; if(s[v] == '1') vmx2 = 0;
		llint upos = Ginv[make_pair(u, v)], vpos = Ginv[make_pair(v, u)];
		if(upos > 0) umx2 = min(umx2, lmin[u][upos-1]);
		if(upos < (int)G[u].size()-1) umx2 = min(umx2, rmin[u][upos+1]);
		if(vpos > 0) vmx2 = min(vmx2, lmin[v][vpos-1]);
		if(vpos < (int)G[v].size()-1) vmx2 = min(vmx2, rmin[v][vpos+1]);

		//bool flag = (umx == d && umx >= umx2) || (vmx == d && vmx >= vmx2);
		//cout << u << " " << v << " " << umx2 << " " << vmx2 << " " << flag << endl;

		if((umx == d && umx >= umx2) || (vmx == d && vmx >= vmx2)) ans++;
		//cout << u << " " << v << " " << flag << endl;
	}

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

Score : 1900 points

Problem Statement

There is a tree with N vertices.
The vertices are numbered 1 through N.
For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i.
The lengths of all the edges are 1.

Snuke likes some of the vertices.
The information on his favorite vertices are given to you as a string s of length N.
For each 1 ≤ i ≤ N, s_i is 1 if Snuke likes vertex i, and 0 if he does not like vertex i.

Initially, all the vertices are white.
Snuke will perform the following operation exactly once:

Select a vertex v that he likes, and a non-negative integer d. Then, paint all the vertices black whose distances from v are at most d.

Find the number of the possible combinations of colors of the vertices after the operation.

Constraints

2 ≤ N ≤ 2×10^5

1 ≤ a_i, b_i ≤ N

The given graph is a tree.

|s| = N

s consists of 0 and 1.

s contains at least one occurrence of 1.

Partial Score

In the test set worth 1300 points, s consists only of 1.

Input

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

N
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
s

Output

Print the number of the possible combinations of colors of the vertices after the operation.

Sample Input 1

4
1 2
1 3
1 4
1100

Sample Output 1

4

The following four combinations of colors of the vertices are possible:

Sample Input 2

5
1 2
1 3
1 4
4 5
11111

Sample Output 2

11

This case satisfies the additional constraint for the partial score.

Sample Input 3

6
1 2
1 3
1 4
2 5
2 6
100011

Sample Output 3

8


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define F first
#define S second
#define pi acos(-1)
using ll = long long;
using namespace std;
using namespace __gnu_pbds;
using vl = vector<ll>;
using pll =  pair<ll,ll>;
const ll mod = 1000000007;
const ll infi = 1000000000000000;
const ll md = 998244353;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set;

int counter = 0;

void solve(){
	int a,b;
	char ch;
	cin>>a>>ch>>b;
	if(ch == '-')
		cout<<a-b;
	else
		cout<< a+b;
}

int main()
{

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
  //  int n; cin>>n; for (counter = 0; counter < n; ++counter)
    solve();
    return 0;
}

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

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

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


#include <iostream>
using namespace std;

int main () {
    int a, b;
    char c;
    cin >> a >> c >> b;
    if(c == '+') {
        cout << a+b << endl;
    } else if(c == '-') {
        cout << a-b << endl;
    }
}


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

int main(){
  long long A,B,ans;
  char o;
  cin>>A>>o>>B;
  if(o=='+'){
    ans=A+B;
    cout<<ans<<endl;
  }
  else if(o=='-'){
    ans=A-B;
    cout<<ans<<endl;
  }
  return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include<cstdio>
#include<cstring>
#include<queue>
#include<stack>
#include<cmath>
using namespace std;
typedef long long ll;
typedef unsigned long long LL;
typedef pair<int,int> P;
typedef pair<double,double> P_f;
#define rep(i, n) for (int i = 0; i < (int)n; i++)
#define reprev(i, n) for (int i = (int)n - 1; i >= 0; i--)
#define bitrep(bit,n) for(int bit=0; bit<=(1<<n);bit++)
#define MAX 100100
#define MAX_N 200100
#define MAX_T 2001001
#define SENTINEL 20010010010
#define NIL -1
static const int INF = 1 << 29;
const ll INFTY = 1LL<<50;
const int MOD=1e9+7;
int n;
int a[MAX];
int main(){
    cin>>n;rep(i,n)cin>>a[i];
    sort(a,a+n);
    if(n%2==0){int m=n/2;
    rep(i,m){
        if(a[2*i]!=a[2*i+1] || a[2*i]!=2*i+1){
            cout<<0<<endl;return 0;
        }
    }
    LL ans = (m%MOD)*(m%MOD);
    cout<<ans<<endl;
    }
    else {
        int m=n/2;
        for(int i=1;i<m;i++){
            if(a[0]!=0 ||a[2*i-1]!=a[2*i] ||a[2*i]!=2*i){
                cout<<0<<endl;return 0;
            }
        }
        LL ans=(m%MOD)*(m%MOD);
        cout<<ans<<endl;
    }
    return 0;

}

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

Input

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

N
A_1 A_2 ... A_N

Output

Print the number of the possible orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


#include <bits/stdc++.h>
typedef unsigned long long ull;
typedef long long ll;
#define __TRUE "YES"
#define __FALSE "NO"
#define MAX 100001
using namespace std;

int main() {
  ll N,ans=0;
  cin >> N;
  vector<ll> a(N),odd(N/2+1,0);
  for(int i=0;i<N;i++) {
    cin >> a[i];
  }
  sort(a.begin(),a.end());
  ll num=0;
  for(int i=0;i<N-1;i++) {
    if(N%2!=0) i++;
    if(a[i]==a[i+1]) num++;
  }
  if(N/2==num) {
    ans=pow(2,N/2);
  }else{
    ans=0;
  }
  cout << ans << endl;
}


#include<iostream>
#include<iomanip>
#include<math.h>
#include<vector>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<time.h>
#define INF 1000000000ll
#define MOD 1000000007ll
#define EPS 1e-10
#define REP(i,m) for(long long i=0; i<m; ++i)
#define FOR(i,n,m) for(long long i=n; i<m; ++i)
#define DUMP(n,a) for(long long dump=0; dump<n; ++dump) { cout<<a[dump]; if(dump!=n-1) cout<<" "; else cout<<endl; }
#define ALL(v) v.begin(),v.end()
#define pb push_back
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
typedef long double ld;

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	ll n;
	cin>>n;
	vector<ll> b(n,0);
	REP(i,n) {
		ll a;
		cin>>a;
		b[a]++;
	}
	for(ll i=n-1; i>=0; i-=2) {
		if(i==0) {
			if(b[i]!=1) {
				cout<<0<<endl;
				return 0;
			}
		}
		else if(b[i]!=2) {
			cout<<0<<endl;
			return 0;
		}
	}
	ll ret=1;
	REP(i,n/2) {
		ret*=2;
		ret%=MOD;
	}
	cout<<ret<<endl;
}


#include"bits/stdc++.h"

#define PB push_back
#define PF push_front
#define LB lower_bound
#define UB upper_bound
#define fr(x) freopen(x,"r",stdin)
#define fw(x) freopen(x,"w",stdout)
#define iout(x) printf("%d\n",x)
#define lout(x) printf("%lld\n",x)
#define REP(x,l,u) for(int x = (l);x<=(u);x++)
#define RREP(x,l,u) for(int x = (l);x>=(u);x--)
#define mst(x,a) memset(x,a,sizeof(x))
#define PII pair<int,int>
#define PLL pair<ll,ll>
#define MP make_pair
#define se second
#define fi first
#define dbg(x) cout<<#x<<" = "<<(x)<<endl;
#define sz(x) ((int)x.size())
#define cl(x) x.clear()

typedef  long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ld;
using namespace std;

const int maxn = 300010;
const int mod = 1e9+7;
const int MAX = 1000000010;
const double eps = 1e-6;
const double PI = acos(-1);

template<typename T> inline void read(T &x){
x=0;T f=1;char ch;do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9');do x=x*10+ch-'0',ch=getchar();while(ch<='9'&&ch>='0');x*=f;
}

template<typename A,typename B> inline void read(A&x,B&y){read(x);read(y);}
template<typename A,typename B,typename C> inline void read(A&x,B&y,C&z){read(x);read(y);read(z);}
template<typename A,typename B,typename C,typename D> inline void read(A&x,B&y,C&z,D&w){read(x);read(y);read(z);read(w);}
template<typename A,typename B> inline A fexp(A x,B p){A ans=1;for(;p;p>>=1,x=1LL*x*x%mod)if(p&1)ans=1LL*ans*x%mod;return ans;}
template<typename A,typename B> inline A fexp(A x,B p,A mo){A ans=1;for(;p;p>>=1,x=1LL*x*x%mo)if(p&1)ans=1LL*ans*x%mo;return ans;}

int n,q;

int t[maxn];

int Q[maxn],top;

ll sm[maxn],f[maxn],y[maxn],pre[maxn],suf[maxn],tmp[maxn],Ans[maxn];

void DP(){
	REP(i,1,n)sm[i]=sm[i-1]+t[i];
	Q[top=1]=0;
	REP(i,1,n){
		f[i]=f[i-1];
		while(top>1&&(y[Q[top]]-y[Q[top-1]])<=2ll*i*(Q[top]-Q[top-1]))top--;
		f[i]=max(f[i],f[Q[top]]+1ll*(i-Q[top])*(i-Q[top]+1)/2+sm[Q[top]]-sm[i]);
		y[i]=f[i]*2+1ll*i*i-i+sm[i]*2;
		while(top>1&&(y[Q[top]]-y[Q[top-1]])*(i-Q[top])<=(y[i]-y[Q[top]])*(Q[top]-Q[top-1]))top--;
		Q[++top]=i;
	}
}

void solve(int l,int r){
//	cout<<l<<' '<<r<<endl;
	if(l==r){
		Ans[l]=max(Ans[l],pre[l-1]+suf[l+1]+1-t[l]);
		return;
	}
	int M=l+r>>1;
	top=0;
	REP(i,l-1,M-1){
		y[i]=pre[i]*2+1ll*i*i-i+sm[i]*2;
		while(top>1&&(y[Q[top]]-y[Q[top-1]])*(i-Q[top])<=(y[i]-y[Q[top]])*(Q[top]-Q[top-1]))top--;
		Q[++top]=i;
	}
	REP(i,M,r){
		while(top>1&&(y[Q[top]]-y[Q[top-1]])<=2ll*i*(Q[top]-Q[top-1]))top--;
		tmp[i]=pre[Q[top]]+suf[i+1]+1ll*(i-Q[top])*(i-Q[top]+1)/2+sm[Q[top]]-sm[i];
	}
	RREP(i,r-1,M)tmp[i]=max(tmp[i],tmp[i+1]);
//	REP(i,M+1,r)cout<<tmp[i]<<' ';cout<<endl;
	REP(i,M,r)Ans[i]=max(Ans[i],tmp[i]);
	solve(l,M);solve(M+1,r);

}

void Work(){
	read(q);
	while(q--){
		int p,x;read(p,x);
		ll ans=max(pre[p-1]+suf[p+1],Ans[p]-x+t[p]);
		printf("%lld\n",ans);
	}
}

void Init(){
	read(n);
	REP(i,1,n)read(t[i]);
	DP();REP(i,1,n)pre[i]=f[i];
	reverse(t+1,t+n+1);
	DP();REP(i,1,n)suf[i]=f[i];
	reverse(t+1,t+n+1);reverse(suf+1,suf+n+1);

//	REP(i,1,n)cout<<pre[i]<<' ';cout<<endl;
//	REP(i,1,n)cout<<suf[i]<<' ';cout<<endl;

	REP(i,1,n)Ans[i]=-t[i],sm[i]=sm[i-1]+t[i];
	solve(1,n);
	reverse(t+1,t+n+1);REP(i,1,n)sm[i]=sm[i-1]+t[i];
	reverse(pre+1,pre+n+1);reverse(suf+1,suf+n+1);reverse(Ans+1,Ans+n+1);REP(i,1,n)swap(pre[i],suf[i]);
	solve(1,n);
	reverse(t+1,t+n+1);REP(i,1,n)sm[i]=sm[i-1]+t[i];
	reverse(pre+1,pre+n+1);reverse(suf+1,suf+n+1);reverse(Ans+1,Ans+n+1);REP(i,1,n)swap(pre[i],suf[i]);
}

int main(){
	Init();
	Work();
	return 0;
}

Score : 1400 points

Problem Statement

Joisino is about to compete in the final round of a certain programming competition.
In this contest, there are N problems, numbered 1 through N.
Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).

In this contest, a contestant will first select some number of problems to solve.
Then, the contestant will solve the selected problems.
After that, the score of the contestant will be calculated as follows:

(The score) = (The number of the pairs of integers L and R (1≦L≦R≦N) such that for every i satisfying L≦i≦R, problem i is solved) - (The total number of seconds it takes for the contestant to solve the selected problems)

Note that a contestant is allowed to choose to solve zero problems, in which case the score will be 0.

Also, there are M kinds of drinks offered to the contestants, numbered 1 through M.
If Joisino takes drink i(1≦i≦M), her brain will be stimulated and the time it takes for her to solve problem P_i will become X_i seconds.
Here, X_i may be greater than the length of time originally required to solve problem P_i.
Taking drink i does not affect the time required to solve the other problems.

A contestant is allowed to take exactly one of the drinks before the start of the contest.
For each drink, Joisino wants to know the maximum score that can be obtained in the contest if she takes that drink.
Your task is to write a program to calculate it instead of her.

Constraints

All input values are integers.

1≦N≦3*10^5

1≦T_i≦10^9

(The sum of T_i) ≦10^{12}

1≦M≦3*10^5

1≦P_i≦N

1≦X_i≦10^9

Input

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

N
T_1 T_2 ... T_N
M
P_1 X_1
P_2 X_2
:
P_M X_M

Output

For each drink, print the maximum score that can be obtained if Joisino takes that drink, in order, one per line.

Sample Input 1

5
1 1 4 1 1
2
3 2
3 10

Sample Output 1

9
2

If she takes drink 1, the maximum score can be obtained by solving all the problems.

If she takes drink 2, the maximum score can be obtained by solving the problems 1,2,4 and 5.

Sample Input 2

12
1 2 1 3 4 1 2 1 12 3 12 12
10
9 3
11 1
5 35
6 15
12 1
1 9
4 3
10 2
5 1
7 6

Sample Output 2

34
35
5
11
35
17
25
26
28
21


#include<bits/stdc++.h>
using namespace std;
namespace FAST_IO
{
	template<typename T> void read(T &a)
	{
		a=0;
		int f=1;
		char c=getchar();
		while(!isdigit(c))
		{
			if(c=='-')
			{
				f=-1;
			}
			c=getchar();
		}
		while(isdigit(c))
		{
			a=a*10+c-'0';
			c=getchar();
		}
		a=a*f;
	}
	template <typename T> void write(T a)
	{
		if(a<0)
		{
			a=-a;
			putchar('-');
		}
		if(a>9)
		{
			write(a/10);
		}
		putchar(a%10+'0');
	}
	template <typename T> void writeln(T a)
	{
		write(a);
		puts("");
	}
}
int main()
{
	char a;
	cin>>a;
	if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u')
	{
		cout<<"vowel";
	}
	else
	{
		cout<<"consonant";
	}
}

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

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

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


#pragma GCC optimize ("O3")

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <queue>
using namespace std;

using QWORD = unsigned long long;
using SQWORD = long long;
using DWORD = unsigned int;
using SDWORD = int;
using WORD = unsigned short;
using SWORD = short;
using BYTE = unsigned char;
using SBYTE = char;
using DOUBLE = double;
using FLOAT = float;

#define MIN_SDWORD (-2147483648)
#define MAX_SDWORD (2147483647)
#define MIN_SBYTE (-128)
#define MAX_SBYTE (127)

#define MAX_QWORD (0xFFFFFFFFFFFFFFFF)
#define MAX_DWORD (0xFFFFFFFF)
#define MAX_WORD  (0xFFFF)
#define MAX_BYTE  (0xFF)

#define ArrayLength(a)  (sizeof(a) / sizeof(a[0]))

static inline QWORD MAX(QWORD a, QWORD b) { return a > b ? a : b; }
static inline DWORD MAX(DWORD a, DWORD b) { return a > b ? a : b; }
static inline SDWORD MAX(SDWORD a, SDWORD b) { return a > b ? a : b; }
static inline QWORD MIN(QWORD a, QWORD b) { return a < b ? a : b; }
static inline DWORD MIN(DWORD a, DWORD b) { return a < b ? a : b; }
static inline SDWORD MIN(SDWORD a, SDWORD b) { return a < b ? a : b; }

#define BYTE_BITS   (8)
#define WORD_BITS   (16)
#define DWORD_BITS  (32)
#define QWORD_BITS  (64)

using M_BOOL = bool;
#define M_TRUE (true)
#define M_FALSE (false)
#define DIVISOR (1000000007)

static inline void inputString(char *pcStr)
{
    char *pcCur = pcStr;
    for (;;) {
        char c = getchar();
        if (('\n' == c) || (EOF == c)) {
            break;
        }
        *pcCur = c;
        pcCur++;
    }
    *pcCur = '\0';
}

static inline SDWORD inputSDWORD(void)
{
    SDWORD lNumber = 0;
    M_BOOL bRead = M_FALSE;
    for (;;) {
        char c = getchar();
        if (('0' <= c) && (c <= '9')) {
            lNumber *= 10;
            lNumber += (c - '0');
            bRead = M_TRUE;
        } else {
            if (bRead) {
                return lNumber;
            }
        }
    }
}

typedef struct {
    DWORD   *pdwPar;
    DWORD   *pdwRank;
    DWORD   *pdwCnt;
    DWORD   dwSize;
} ST_UNION_FIND;

static void initUnionFind(
    ST_UNION_FIND *pstUf,
    DWORD *pdwPar,
    DWORD *pdwRank,
    DWORD *pdwCnt,
    DWORD dwSize)
{
    pstUf->dwSize = dwSize;
    pstUf->pdwPar = pdwPar;
    pstUf->pdwRank = pdwRank;
    pstUf->pdwCnt = pdwCnt;

    for (DWORD dwIdx = 0; dwIdx < dwSize; dwIdx++) {
        *(pstUf->pdwPar + dwIdx)  = dwIdx;
        *(pstUf->pdwRank + dwIdx) = 0;
        *(pstUf->pdwCnt + dwIdx)  = 1;
    }
}

static DWORD ufGetParent(const ST_UNION_FIND *pstUf, DWORD dwIdx)
{
    return *(pstUf->pdwPar + dwIdx);
}

static DWORD ufGetRank(const ST_UNION_FIND *pstUf, DWORD dwIdx)
{
    return *(pstUf->pdwRank + dwIdx);
}

static void ufSetParent(ST_UNION_FIND *pstUf, DWORD dwIdx, DWORD dwParent)
{
    *(pstUf->pdwPar + dwIdx) = dwParent;
    if (ufGetRank(pstUf, dwIdx) == ufGetRank(pstUf, dwParent)) {
        (*(pstUf->pdwRank + dwParent))++;
    }
}

static DWORD ufGetRoot(ST_UNION_FIND *pstUf, DWORD dwIdx)
{
    if (ufGetParent(pstUf, dwIdx) == dwIdx) {
        return dwIdx;
    } else {
        DWORD dwParent = ufGetParent(pstUf, dwIdx);
        DWORD dwRoot = ufGetRoot(pstUf, dwParent);
        ufSetParent(pstUf, dwIdx, dwParent);
        return dwRoot;
    }
}

static void ufUnite(ST_UNION_FIND *pstUf, DWORD dwX, DWORD dwY)
{
    DWORD dwRootX = ufGetRoot(pstUf, dwX);
    DWORD dwRootY = ufGetRoot(pstUf, dwY);

    if (dwRootX == dwRootY) {
        return;
    }

    if (ufGetRank(pstUf, dwRootX) < ufGetRank(pstUf, dwRootY)) {
        ufSetParent(pstUf, dwRootX, dwRootY);
        (*(pstUf->pdwCnt + dwRootY)) += (*(pstUf->pdwCnt + dwRootX));
    } else {
        ufSetParent(pstUf, dwRootY, dwRootX);
        (*(pstUf->pdwCnt + dwRootX)) += (*(pstUf->pdwCnt + dwRootY));
    }
}

static M_BOOL ufIsSame(ST_UNION_FIND *pstUf, DWORD dwX, DWORD dwY)
{
    return (ufGetRoot(pstUf, dwX)  == ufGetRoot(pstUf,dwY));
}

#define MAX_CITY_NUM         (100000)
#define CITY_INFO_ARY_SIZE   (100000 + 1)

int main()
{
    DWORD dwInput_N;
    DWORD dwInput_K;
    DWORD dwInput_L;

    static DWORD adwRoad_Parents[CITY_INFO_ARY_SIZE];
    static DWORD adwRoad_Rank[CITY_INFO_ARY_SIZE];
    static DWORD adwRoad_Cnt[CITY_INFO_ARY_SIZE];
    static DWORD adwRail_Parents[CITY_INFO_ARY_SIZE];
    static DWORD adwRail_Rank[CITY_INFO_ARY_SIZE];
    static DWORD adwRail_Cnt[CITY_INFO_ARY_SIZE];

    ST_UNION_FIND stUfRoad;
    ST_UNION_FIND stUfRail;

    initUnionFind(&stUfRoad, adwRoad_Parents, adwRoad_Rank, adwRoad_Cnt, ArrayLength(adwRoad_Parents));
    initUnionFind(&stUfRail, adwRail_Parents, adwRail_Rank, adwRail_Cnt, ArrayLength(adwRail_Parents));

    dwInput_N = inputSDWORD();
    dwInput_K = inputSDWORD();
    dwInput_L = inputSDWORD();

    for (DWORD dwIdx = 0; dwIdx < dwInput_K; dwIdx++) {
        DWORD dwInput_p = inputSDWORD();
        DWORD dwInput_q = inputSDWORD();
        ufUnite(&stUfRoad, dwInput_p, dwInput_q);
    }
    for (DWORD dwIdx = 0; dwIdx < dwInput_L; dwIdx++) {
        DWORD dwInput_r = inputSDWORD();
        DWORD dwInput_s = inputSDWORD();
        if (ufIsSame(&stUfRoad, dwInput_r, dwInput_s)) {
            ufUnite(&stUfRail, dwInput_r, dwInput_s);
        }
    }
    for (DWORD dwIdxJ = 1; dwIdxJ <= dwInput_N; dwIdxJ++) {
        printf("%d", *(stUfRail.pdwCnt + ufGetRoot(&stUfRail, dwIdxJ)));
        if (dwIdxJ != dwInput_N) {
            printf(" ");
        }
    }
    printf("\n");
}

Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

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

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

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

Sample Output 3

1 1 2 1 2 2 2


#include<bits/stdc++.h>
using namespace std;
int vis1[200005],vis2[200005];
vector<int>g[200005],e[200005];
map<pair<int,int>,int>mp;
void dfs1(int x,int xx)
{
	vis1[x]=xx;
	for(int i=0;i<g[x].size();i++)if(!vis1[g[x][i]])dfs1(g[x][i],xx);
}
void dfs2(int x,int xx)
{
	vis2[x]=xx;
	for(int i=0;i<e[x].size();i++)if(!vis2[e[x][i]])dfs2(e[x][i],xx);
}
int main()
{
	int n,m,k;
	scanf("%d%d%d",&n,&m,&k);
	for(int i=1;i<=m;i++)
	{
		int u,v;
		scanf("%d%d",&u,&v);
		g[u].push_back(v);
		g[v].push_back(u);
	}
	for(int i=1;i<=k;i++)
	{
		int u,v;
		scanf("%d%d",&u,&v);
		e[u].push_back(v);
		e[v].push_back(u);
	}
	int cnt=1;
	memset(vis1,0,sizeof(vis1));
	memset(vis2,0,sizeof(vis2));
	for(int i=1;i<=n;i++)if(!vis1[i])dfs1(i,cnt++);
	for(int i=1;i<=n;i++)if(!vis2[i])dfs2(i,cnt++);
	for(int i=1;i<=n;i++)mp[make_pair(vis1[i],vis2[i])]++;
	for(int i=1;i<=n;i++)printf("%d ",mp[make_pair(vis1[i],vis2[i])]);
	puts("");
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <deque>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <cstring>
#include <iomanip>

#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,n) for(int i=1;i<=(n);i++)
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3fLL;
using namespace std;

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

    int a,b,x,i;
    cin>>a>>b>>x;

    int sum=0;
    for(i=a;i<=b;i++){
	if(i%x==0){
	    break;
	}
    }

    for(i=i;i<=b;i+=x){
	sum++;
    }
    cout<<sum<<'\n';

    return 0;
}

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

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

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


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

#define rep(i,n) for(long long i = 0; i < (long long)(n); i++)
#define repi(i,a,b) for(long long i = (long long)(a); i < (long long)(b); i++)
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
#define mt make_tuple
#define mp make_pair
template<class T1, class T2> bool chmin(T1 &a, T2 b) { return b < a && (a = b, true); }
template<class T1, class T2> bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }

using ll = long long; using vll = vector<ll>; using vvll = vector<vll>; using P = pair<ll, ll>;
using ld = long double;  using vld = vector<ld>;
using vi = vector<int>; using vvi = vector<vi>; vll conv(vi& v) { vll r(v.size()); rep(i, v.size()) r[i] = v[i]; return r; }

inline void input(int &v){ v=0;char c=0;int p=1; while(c<'0' || c>'9'){if(c=='-')p=-1;c=getchar();} while(c>='0' && c<='9'){v=(v<<3)+(v<<1)+c-'0';c=getchar();} v*=p; } // これを使うならば、tieとかを消して！！
template <typename T, typename U> ostream &operator<<(ostream &o, const pair<T, U> &v) {  o << "(" << v.first << ", " << v.second << ")"; return o; }
template<size_t...> struct seq{}; template<size_t N, size_t... Is> struct gen_seq : gen_seq<N-1, N-1, Is...>{}; template<size_t... Is> struct gen_seq<0, Is...> : seq<Is...>{};
template<class Ch, class Tr, class Tuple, size_t... Is>
void print_tuple(basic_ostream<Ch,Tr>& os, Tuple const& t, seq<Is...>){ using s = int[]; (void)s{0, (void(os << (Is == 0? "" : ", ") << get<Is>(t)), 0)...}; }
template<class Ch, class Tr, class... Args>
auto operator<<(basic_ostream<Ch, Tr>& os, tuple<Args...> const& t) -> basic_ostream<Ch, Tr>& { os << "("; print_tuple(os, t, gen_seq<sizeof...(Args)>()); return os << ")"; }
ostream &operator<<(ostream &o, const vvll &v) { rep(i, v.size()) { rep(j, v[i].size()) o << v[i][j] << " "; o << endl; } return o; }
template <typename T> ostream &operator<<(ostream &o, const vector<T> &v) { o << '['; rep(i, v.size()) o << v[i] << (i != v.size()-1 ? ", " : ""); o << "]";  return o; }
template <typename T> ostream &operator<<(ostream &o, const deque<T> &v) { o << '['; rep(i, v.size()) o << v[i] << (i != v.size()-1 ? ", " : ""); o << "]";  return o; }
template <typename T>  ostream &operator<<(ostream &o, const set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]";  return o; }
template <typename T>  ostream &operator<<(ostream &o, const unordered_set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]";  return o; }
template <typename T, typename U>  ostream &operator<<(ostream &o, const map<T, U> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]";  return o; }
template <typename T, typename U, typename V>  ostream &operator<<(ostream &o, const unordered_map<T, U, V> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it; o << "]";  return o; }
vector<int> range(const int x, const int y) { vector<int> v(y - x + 1); iota(v.begin(), v.end(), x); return v; }
template <typename T> istream& operator>>(istream& i, vector<T>& o) { rep(j, o.size()) i >> o[j]; return i;}
template <typename T, typename S, typename U> ostream &operator<<(ostream &o, const priority_queue<T, S, U> &v) { auto tmp = v; while (tmp.size()) { auto x = tmp.top(); tmp.pop(); o << x << " ";} return o; }
template <typename T> ostream &operator<<(ostream &o, const queue<T> &v) { auto tmp = v; while (tmp.size()) { auto x = tmp.front(); tmp.pop(); o << x << " ";} return o; }
template <typename T> ostream &operator<<(ostream &o, const stack<T> &v) { auto tmp = v; while (tmp.size()) { auto x = tmp.top(); tmp.pop(); o << x << " ";} return o; }
template <typename T> unordered_map<T, ll> counter(vector<T> vec){unordered_map<T, ll> ret; for (auto&& x : vec) ret[x]++; return ret;};
string substr(string s, P x) {return s.substr(x.fi, x.se - x.fi); }
void vizGraph(vvll& g, int mode = 0, string filename = "out.png") { ofstream ofs("./out.dot"); ofs << "digraph graph_name {" << endl; set<P> memo; rep(i, g.size())  rep(j, g[i].size()) { if (mode && (memo.count(P(i, g[i][j])) || memo.count(P(g[i][j], i)))) continue; memo.insert(P(i, g[i][j])); ofs << "    " << i << " -> " << g[i][j] << (mode ? " [arrowhead = none]" : "")<< endl;  } ofs << "}" << endl; ofs.close(); system(((string)"dot -T png out.dot >" + filename).c_str()); }
size_t random_seed; namespace std { using argument_type = P; template<> struct hash<argument_type> { size_t operator()(argument_type const& x) const { size_t seed = random_seed; seed ^= hash<ll>{}(x.fi); seed ^= (hash<ll>{}(x.se) << 1); return seed; } }; }; // hash for various class
struct timeval start; double sec() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec - start.tv_sec) + (tv.tv_usec - start.tv_usec) * 1e-6; }
struct init_{init_(){ ios::sync_with_stdio(false); cin.tie(0); gettimeofday(&start, NULL); struct timeval myTime; struct tm *time_st; gettimeofday(&myTime, NULL); time_st = localtime(&myTime.tv_sec); srand(myTime.tv_usec); random_seed = RAND_MAX / 2 + rand() / 2; }} init__;
#define ldout fixed << setprecision(40)

#define EPS (double)1e-14
#define INF (ll)1e18
#define mo  (ll)(1e9+7)

int main(void) {
    ll a,b,x;cin>>a>>b>>x;
    cout<<(b+1+x-1)/x-(a+x-1)/x<<endl;;
    return 0;
}


#include <iostream>
#include <cstring>
using namespace std;
int main(){
  string s;
  cin>>s;
  if(s[0]==s[s.length()-1]){
    if(s.length()%2==0)
      cout<<"First"<<endl;
    else cout<<"Second"<<endl;
  }
  else {
    if(s.length()%2==0)
      cout<<"Second"<<endl;
    else cout<<"First"<<endl;
  }
  return 0;
}

Score : 500 points

Problem Statement

There is a string s of length 3 or greater.
No two neighboring characters in s are equal.

Takahashi and Aoki will play a game against each other.
The two players alternately performs the following operation, Takahashi going first:

Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.

The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.

Constraints

3 ≤ |s| ≤ 10^5

s consists of lowercase English letters.

No two neighboring characters in s are equal.

Input

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

s

Output

If Takahashi will win, print First. If Aoki will win, print Second.

Sample Input 1

aba

Sample Output 1

Second

Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of s, would result in s becoming aa, with two as neighboring.

Sample Input 2

abc

Sample Output 2

First

When Takahashi removes b from s, it becomes ac.
Then, Aoki cannot perform the operation, since there is no character in s, excluding both ends.

Sample Input 3

abcab

Sample Output 3

First


#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define all(a) (a).begin(),(a).end()
#define endl "\n"
#define rep(i, a, b) for (auto (i) = (a); (i) < (b); (i)++)
#define rrep(i, a, b) for (auto (i) = (a); (i) > (b); (i)--)

#define aim_cpo do{ios::sync_with_stdio(false);\
cin.tie(nullptr);cout.precision(12);cout<<fixed;}while(0)

#define LOCAL_INPUT do{FILE *stream1;\
stream1=freopen("/Users/aim_cpo/CLionProjects/competitive/in.txt","r",stdin);\
if(stream1==nullptr)return 0;}while(0)
#define LOCAL_OUTPUT do{FILE *stream2;\
stream2 = freopen("out.txt", "w", stdout);\
if (stream2 == nullptr) return 0;}while(0)

#ifdef LOCAL_DEFINE
#define show(x) cerr << #x << " = " << (x) << endl
#define dump(x) cerr << #x << " = " << (x) << " (line " << __LINE__ << ")" << endl
#define showV(v, n) do{\
for(int _i_t_e_=0; _i_t_e_<(n);_i_t_e_++)\
cerr<<"("<<_i_t_e_<<" = "<<(v)[_i_t_e_]<<") ";\
cerr<<endl;}while(0)
#define showA(a, n) do{\
for(int _i_t_e_=0;_i_t_e_<(n);_i_t_e_++)\
cerr<<"("<<_i_t_e_<<" = "<<(a)[_i_t_e_]<<") ";\
cerr<<endl;}while(0)
#define showA2(a, n, m) do{\
for(int _i_t_e_=0;_i_t_e_<(n);_i_t_e_++){\
for(int _i_t_e_2=0;_i_t_e_2<(m);_i_t_e_2++){\
cerr<<"("<<_i_t_e_<<", "<<_i_t_e_2<<" = "<<(a)[_i_t_e_][_i_t_e_2]<<") ";\
}cerr<<endl;}cerr<<endl;}while(0)
#else
#define show(x)
#define dump(x)
#define showV(v, n)
#define showA(a, n)
#define showA2(a, n, m)
#endif

typedef long long ll;
typedef unsigned long long ull;

constexpr const int INT_INF=0x3f3f3f3f; //1061109567
constexpr const ll LL_INF=0x3f3f3f3f3f3f3f3f; //4557430888798830399

template <typename T> bool chmin(T &a, T b){return a>b?(a=b,true):false;}
template <typename T> bool chmax(T &a, T b){return a<b?(a=b,true):false;}
template <typename T> void ln(T i, T n){cout<<(i==n-1?"\n":" ");}
template <typename T, typename S>
ostream &operator<<(ostream &out,const pair<T, S> &pair1){
  out<<'('<<pair1.fi<<", "<<pair1.se<<')';return out;}
template <typename T>
ostream &operator<<(ostream &out,const vector<T> &vector1){
  out<<'[';for(unsigned int i=0;i<vector1.size();i++){
    out<<vector1[i];if(i==vector1.size()-1)out<<"]";else out<<", ";
  }return out;
}

// INT
#define GCD(a, b) __gcd(a, b)
template <typename T> T LCM(T a, T b) {return a / GCD(a, b) * b;}
template <typename T> T EXTGCD(T a, T b, T& x, T& y) {
  T d = a;
  if (b != 0) {d=EXTGCD(b,a%b,y,x);y-=(a/b)*x;}
  else x=1,y=0;
  return d;
}
template <typename T> bool is_prime(T a) {
  for(int i=2;i*i<=a;i++)if(a%i==0)return 1;
  return 0;
}
template <typename T, typename S> T Pow(T a, S b) {
  T res = 1, now = a;
  while(b){if(b&1)res*=now;b>>=1;now*=now;}return res;
}

// MOD
ll MOD = 1000000000L + 7L;
#define add(a, b) ((a % MOD) + (b % MOD)) % MOD
#define mul(a, b) ((a % MOD) * (b % MOD)) % MOD
#define sub(a, b) ((a % MOD) + MOD - (b % MOD)) % MOD
template <typename T, typename S> T ModPow(T a, S b) {
  T res = 1, now = a;
  while(b){if(b&1)res=mul(res,now);b>>=1;now=mul(now,now);}return res;
}
template <typename T> T mod_inverse(T a, T mod, bool prime){ // if mod is prime, "prime" is true.
  if(prime)return ModPow(a, mod - 2);
  else{T x,y;EXTGCD(a,mod,x,y);return (mod+x%mod)%mod;}
}
#define divide(a, b) ((a % MOD) * (mod_inverse(b, MOD, true))) % MOD

//LLの数値をつかう時は最後にLをつける癖をつけよう
//
//  ┏┓┏┓　┓　┏┓
//  ┏┛┃┃　┃　┗┫
//  ┗┛┗┛　┻　┗┛
//
//   謹┃賀┃新┃年┃
//   ━┛━┛━┛━┛
//WWWWWWWWWWWWWWWWWWWWWW

vector < pair < pair <int, int>, int> > v;
vector < pair <int, double> > g[1011];
double d[1011];

int main() {
  aim_cpo; // インタラクティブのときは消すように.
#ifdef LOCAL_DEFINE
  LOCAL_INPUT; // インタラクティブのときは消すように.
//  LOCAL_OUTPUT; // ファイルに出力したいときのみ
  show(MOD);
#endif
  // テキトー考察
  //
  // いろんな行き方がありそうだから、ダイクストラかな...(でもどうやって辺を貼れば良いんだろう)
  // 例えば、ある座標からある座標に行くときに、その途中で関係ない場所のバリアを通ってしまうようなときは辺のコストをどんな値にすれば
  // 良いのだろう...
  // でも、よく考えたらそんな経路が最短になるわけないよね.
  // 途中で、どこかのバリアをかすってしまうなら、そのバリアの中心に向かって移動して、そこからまた目的の場所に行くほうが
  // 絶対に短くなるはず
  // じゃあ、どうせその経路は使われないんだから、厳密なコストを求める必要はなくて、それよりもう少し長いコストでも良さそう.
  // じゃあ、シンプルに座標同士の距離をコストにすれば丁度いい感じに求められそう.
  // 個人的に、辺のコストを求める部分がこの問題の本質だなって思った.
  // ある座標からある座標への経路の中に、絶対使われない経路が存在することに気づくことが大切.
  int sx, sy; cin >> sx >> sy;
  int gx, gy; cin >> gx >> gy;
  v.push_back(mp(mp(sx, sy), 0));
  v.push_back(mp(mp(gx, gy), 0));
  int n; cin >> n;
  rep(i, 0, n) {
    int x, y, r; cin >> x >> y >> r;
    v.push_back(mp(mp(x, y), r));
  }
  rep(i, 0, (int)v.size()) {
    rep(j, 0, (int)v.size()) {
      if (i == j) continue;
      double cost = sqrt(Pow((double)v[i].fi.fi - v[j].fi.fi, 2) + Pow((double)v[i].fi.se - v[j].fi.se, 2));
      if (cost - v[i].se - v[j].se < 0) cost = 0.;
      else cost -= v[i].se + v[j].se;
      g[i].emplace_back(j, cost);
    }
  }
  priority_queue<pair<double, int> > q;
  fill(d, d + n + 2, 1e17);
  d[0] = 0.;
  q.push(mp(0., 0));
  while (!q.empty()) {
    int now = q.top().se;
    double cost = -q.top().fi; q.pop();
    if (d[now] < cost) continue;
    rep(i, 0, (int)g[now].size()) {
      if (d[g[now][i].fi] > d[now] + g[now][i].se) {
        d[g[now][i].fi] = d[now] + g[now][i].se;
        q.push(mp(-d[g[now][i].fi], g[now][i].fi));
      }
    }
  }
  cout << d[1] << endl;
#ifdef  LOCAL_DEFINE
  cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << "s." << endl;
#endif
  return 0;
}

Score : 600 points

Problem Statement

On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t).
He can move in arbitrary directions with speed 1.
Here, we will consider him as a point without size.

There are N circular barriers deployed on the plane.
The center and the radius of the i-th barrier are (x_i, y_i) and r_i, respectively.
The barriers may overlap or contain each other.

A point on the plane is exposed to cosmic rays if the point is not within any of the barriers.

Snuke wants to avoid exposure to cosmic rays as much as possible during the travel.
Find the minimum possible duration of time he is exposed to cosmic rays during the travel.

Constraints

All input values are integers.

-10^9 ≤ x_s, y_s, x_t, y_t ≤ 10^9

(x_s, y_s) ≠ (x_t, y_t)

1≤N≤1,000

-10^9 ≤ x_i, y_i ≤ 10^9

1 ≤ r_i ≤ 10^9

Input

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

x_s y_s x_t y_t
N
x_1 y_1 r_1
x_2 y_2 r_2
:
x_N y_N r_N

Output

Print the minimum possible duration of time Snuke is exposed to cosmic rays during the travel.
The output is considered correct if the absolute or relative error is at most 10^{-9}.

Sample Input 1

-2 -2 2 2
1
0 0 1

Sample Output 1

3.6568542495

An optimal route is as follows:

Sample Input 2

-2 0 2 0
2
-1 0 2
1 0 2

Sample Output 2

0.0000000000

An optimal route is as follows:

Sample Input 3

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

Sample Output 3

4.0000000000

An optimal route is as follows:


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct {
  int type;
  int x;
} S;

int64_t MOD = 1000000007;

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

  vector<S> v;

  for (int i = 0; i < N; i++) {
    int a;
    cin >> a;
    v.push_back({ 0, a });
  }

  for (int i = 0; i < N; i++) {
    int b;
    cin >> b;
    v.push_back({ 1, b });
  }

  sort(v.begin(), v.end(), [](S a, S b) { return a.x < b.x; });

  int cnt0 = 0;
  int cnt1 = 0;
  int64_t ans = 1;
  for (auto i: v) {
    if (i.type == 0) {
      if (cnt1 == 0) {
        cnt0 += 1;
      } else {
        ans = ans * cnt1 % MOD;
        cnt1 -= 1;
      }
    } else {
      if (cnt0 == 0) {
        cnt1 += 1;
      } else {
        ans = ans * cnt0 % MOD;
        cnt0 -= 1;
      }
    }
  }

  cout << ans << endl;
}

Score : 500 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

There are N computers and N sockets in a one-dimensional world.
The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i.
It is guaranteed that these 2N coordinates are pairwise distinct.

Snuke wants to connect each computer to a socket using a cable.
Each socket can be connected to only one computer.

In how many ways can he minimize the total length of the cables?
Compute the answer modulo 10^9+7.

Constraints

1 ≤ N ≤ 10^5

0 ≤ a_i, b_i ≤ 10^9

The coordinates are integers.

The coordinates are pairwise distinct.

Input

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

N
a_1
:
a_N
b_1
:
b_N

Output

Print the number of ways to minimize the total length of the cables, modulo 10^9+7.

Sample Input 1

2
0
10
20
30

Sample Output 1

2

There are two optimal connections: 0-20, 10-30 and 0-30, 10-20.
In both connections the total length of the cables is 40.

Sample Input 2

3
3
10
8
7
12
5

Sample Output 2

1


#include <iostream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <queue>
#include <set>
#include <map>

using namespace std;
typedef long long ll;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout << setprecision(10) << fixed;
    int a, b, c; cin >> a >> b >> c;
    cout << a << ' ' << b << ' ' << 3*c-(a+b) << endl;
    cout << 4*c-2*a-b << ' ' << c << ' ' << 2*a+b-2*c << endl;
    cout << a+b-c << ' ' << 2*c-b << ' ' << 2*c-a << endl;
}

Score : 100 points

Problem Statement

A 3×3 grid with a integer written in each square, is called a magic square if and only if the integers in each row, the integers in each column, and the integers in each diagonal (from the top left corner to the bottom right corner, and from the top right corner to the bottom left corner), all add up to the same sum.

You are given the integers written in the following three squares in a magic square:

The integer A at the upper row and left column

The integer B at the upper row and middle column

The integer C at the middle row and middle column

Determine the integers written in the remaining squares in the magic square.

It can be shown that there exists a unique magic square consistent with the given information.

Constraints

0 \leq A, B, C \leq 100

Input

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

A
B
C

Output

Output the integers written in the magic square, in the following format:

X_{1,1} X_{1,2} X_{1,3}
X_{2,1} X_{2,2} X_{2,3}
X_{3,1} X_{3,2} X_{3,3}

where X_{i,j} is the integer written in the square at the i-th row and j-th column.

Sample Input 1

8
3
5

Sample Output 1

8 3 4
1 5 9
6 7 2

Sample Input 2

1
1
1

Sample Output 2

1 1 1
1 1 1
1 1 1


#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <vector>

using namespace std;

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

void solve() {
  int n;
  cin >> n;
  set<int> s;
  int tot = 0;
  for(int i = 1; tot < n; i++) {
    s.insert(i);
    tot += i;
  }
  s.erase(tot-n);
  for(int out: s) cout << out << "\n";
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL); cout.tie(NULL);
  /*
  int t;
  cin >> t;
  for(int i = 1; i <= t; i++) {
    cout << "Case #" << i << ": ";
    solve();
  }
  */
  solve();
}

Score : 300 points

Problem Statement

The problem set at CODE FESTIVAL 20XX Finals consists of N problems.

The score allocated to the i-th (1≦i≦N) problem is i points.

Takahashi, a contestant, is trying to score exactly N points. For that, he is deciding which problems to solve.

As problems with higher scores are harder, he wants to minimize the highest score of a problem among the ones solved by him.

Determine the set of problems that should be solved.

Constraints

1≦N≦10^7

Partial Score

200 points will be awarded for passing the test set satisfying 1≦N≦1000.

Additional 100 points will be awarded for passing the test set without additional constraints.

Input

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

N

Output

Among the sets of problems with the total score of N, find a set in which the highest score of a problem is minimum, then print the indices of the problems in the set in any order, one per line.

If there exists more than one such set, any of them will be accepted.

Sample Input 1

4

Sample Output 1

1
3

Solving only the 4-th problem will also result in the total score of 4 points, but solving the 1-st and 3-rd problems will lower the highest score of a solved problem.

Sample Input 2

7

Sample Output 2

1
2
4

The set \{3,4\} will also be accepted.

Sample Input 3

1

Sample Output 3

1


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

struct UnionFind {
	const int V;
	// par[x] := xのroot
	vector<int> par;
	// sz[x] := xを含む集合のサイズ
	vector<int> sz;
	UnionFind(const int V) :
		V(V),
		par(vector<int>(V)),
		sz(vector<int>(V, 1))
		{
			for(int i = 0; i < V; ++i) par[i] = i;
		}
	bool unite(int x, int y) {
		x = root(x), y = root(y);
		if(same(x, y)) return false;
		if(y < x) swap(x, y);
		par[y] = x;
		sz[x] += sz[y];
		return true;
	}
	int root(int x) {
		if(par[x] == x) return x;
		return (par[x] = root(par[x]));
	}
	bool same(int x, int y) {
		return (root(x) == root(y));
	}
	int size(int x) {
		return sz[root(x)];
	}
};

int main() {
	int n, m; cin >> n >> m;
	vector<int> l[n];
	for(int i = 0; i < n; ++i) {
		int k; cin >> k;
		while(k--) {
			int ll; cin >> ll;
			--ll;
			l[i].push_back(ll);
		}
	}
	UnionFind uf(m);
	for(int i = 0; i < n; ++i) {
		for(int j = 1; j < (int)l[i].size(); ++j) {
			uf.unite(l[i][j - 1], l[i][j]);
		}
	}
	set<int> ans;
	for(int i = 0; i < n; ++i) {
		ans.insert(uf.root(l[i].front()));
	}
	if(ans.size() == 1) {
		cout << "YES" << '\n';
	} else {
		cout << "NO" << '\n';
	}
	return 0;
}

Score : 400 points

Problem Statement

On a planet far, far away, M languages are spoken. They are conveniently numbered 1 through M.

For CODE FESTIVAL 20XX held on this planet, N participants gathered from all over the planet.

The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}.

Two participants A and B can communicate with each other if and only if one of the following conditions is satisfied:

There exists a language that both A and B can speak.

There exists a participant X that both A and B can communicate with.

Determine whether all N participants can communicate with all other participants.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦K_i≦M

(The sum of all K_i)≦10^5

1≦L_{i,j}≦M

L_{i,1}, L_{i,2}, ..., L_{i,{}K_i} are pairwise distinct.

Partial Score

200 points will be awarded for passing the test set satisfying the following: N≦1000, M≦1000 and (The sum of all K_i)≦1000.

Additional 200 points will be awarded for passing the test set without additional constraints.

Input

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

N M
K_1 L_{1,1} L_{1,2} ... L_{1,{}K_1}
K_2 L_{2,1} L_{2,2} ... L_{2,{}K_2}
:
K_N L_{N,1} L_{N,2} ... L_{N,{}K_N}

Output

If all N participants can communicate with all other participants, print YES. Otherwise, print NO.

Sample Input 1

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

Sample Output 1

YES

Any two participants can communicate with each other, as follows:

Participants 1 and 2: both can speak language 2.

Participants 2 and 3: both can speak language 4.

Participants 1 and 3: both can communicate with participant 2.

Participants 3 and 4: both can speak language 6.

Participants 2 and 4: both can communicate with participant 3.

Participants 1 and 4: both can communicate with participant 2.

Note that there can be languages spoken by no participant.

Sample Input 2

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

Sample Output 2

NO

For example, participants 1 and 3 cannot communicate with each other.


#include <vector>
#include <queue>
#include <unordered_map>
#include <tuple>
#include <cstdio>
using namespace std;

namespace std{
	template<typename T>
	inline void hash_combine(size_t& seed, T const& v){
		seed ^= hash<T>()(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
	}
	template<typename A,typename B>
	class hash<pair<A,B>>{
		public:
		size_t operator()(pair<A,B> const &p) const{
			size_t seed=0;
			hash_combine(seed,p.first);
			hash_combine(seed,p.second);
			return seed;
		}
	};
}

int main(){
	long long N,A,R;
	scanf("%lld%lld",&N,&A);R=N;
	if(N>1000000)return 1;

	unordered_map<pair<long long,long long>,long long>m; //m<n,speed>=time
	m[{0,1}]=0;
	queue<tuple<long long,long long,long long> >q;
	q.push(make_tuple(0,1,0));
	for(;!q.empty();){
		auto cur=q.front();q.pop();
		long long n=get<0>(cur);
		long long speed=get<1>(cur);
		long long time=get<2>(cur);
		if(time>=R)continue;

		vector<tuple<int,int,int>> nxt={
			make_tuple(0,n,time+A),
			make_tuple(n+speed,speed,time+1)
		};
		for(auto &e:nxt){
			long long nxtn=get<0>(e);
			long long nxtspeed=get<1>(e);
			long long nxttime=get<2>(e);
			if(nxtn>=N){
				R=min(R,nxttime);
			}else if(m.find({nxtn,nxtspeed})==m.end()||m[{nxtn,nxtspeed}]>nxttime){
				m[{nxtn,nxtspeed}]=nxttime;
				q.push(e);
			}
		}
	}
	printf("%lld\n",R);
}

Score : 1000 points

Problem Statement

Rng is baking cookies.

Initially, he can bake one cookie per second.

He can also eat the cookies baked by himself.
When there are x cookies not yet eaten, he can choose to eat all those cookies. After he finishes eating those cookies, the number of cookies he can bake per second becomes x. Note that a cookie always needs to be baked for 1 second, that is, he cannot bake a cookie in 1/x seconds when x > 1.
When he choose to eat the cookies, he must eat all of them; he cannot choose to eat only part of them.
It takes him A seconds to eat the cookies regardless of how many, during which no cookies can be baked.

He wants to give N cookies to Grandma.
Find the shortest time needed to produce at least N cookies not yet eaten.

Constraints

1≦N≦10^{12}

0≦A≦10^{12}

A is an integer.

Partial Score

500 points will be awarded for passing the test set satisfying N≦10^6 and A≦10^6.

Additional 500 points will be awarded for passing the test set without additional constraints.

Input

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

N A

Output

Print the shortest time needed to produce at least N cookies not yet eaten.

Sample Input 1

8 1

Sample Output 1

7

It is possible to produce 8 cookies in 7 seconds, as follows:

After 1 second: 1 cookie is done.

After 2 seconds: 1 more cookie is done, totaling 2. Now, Rng starts eating those 2 cookies.

After 3 seconds: He finishes eating the cookies, and he can now bake 2 cookies per second.

After 4 seconds: 2 cookies are done.

After 5 seconds: 2 more cookies are done, totaling 4.

After 6 seconds: 2 more cookies are done, totaling 6.

After 7 seconds: 2 more cookies are done, totaling 8.

Sample Input 2

1000000000000 1000000000000

Sample Output 2

1000000000000


#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <utility>

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

using namespace std;

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

const ll INF = 1001001001001001ll;

signed main()
{
    ll n, a;
    cin >> n >> a;

    if(a <= 1000000){
        vi dp(1000000 * 45);
        rep(t, dp.size()) dp[t] = t;

        int mae = 1;

        rep(t, dp.size()){
            reps(s, mae, t){
                ll tmp = dp[s] * (t-s-a);
                if(tmp > dp[t]){
                    mae = s;
                    dp[t] = tmp;
                }
            }

            if(dp[t] >= n){
                cout << t << endl;
                return 0;
            }
            if(t==100) break;
        }
    }
    else{
        vi dp(2000000, INF);
        dp[1] = 0;

        reps(i, 1, dp.size()){
            for(int j=i*2; j<dp.size(); j+=i){
                dp[j] = min(dp[j], dp[i] + (i/j) + a);
            }
        }

        ll ans = INF;
        reps(i, 1, dp.size()){
            ans = min(ans, dp[i] + (n+i-1)/i);
        }

        cout << ans << endl;
    }
}


#include <iostream>

using namespace std;

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

    long long ans = 0LL;
    for (int i = 1; i <= n - 3 + 1; ++i) {
        for (int j = 1; j <= 5; ++j) {
            if ((8 * i + 9 * j + 9) % 11 == k) ans++;
        }
    }

    cout << ans << endl;
}

Max Score: $250$ Points

Problem Statement

Snuke has a very long calendar. It has a grid with $n$ rows and $7$ columns. One day, he noticed that calendar has a following regularity.

The cell at the $i$-th row and $j$-th column contains the integer $7i+j-7$.

A good sub-grid is a $3 \times 3$ sub-grid and the sum of integers in this sub-grid mod $11$ is $k$.

How many good sub-grid are there? Write a program and help him.

Input

The input is given from standard input in the following format.

$n \quad k$

Output

Print the number of good sub-grid. If there are no solution exists, print 0.

Constraints

$1 \le n \le 10^9$

$0 \le k \le 10$

Subtasks

Subtask 1 [ $150$ points ]

The testcase in the subtask satisfies $1 \le n \le 100$.

Subtask 2 [ $100$ points ]

There are no additional constraints.

Sample Input 1

7 7

Sample Output 1

2

In this case, the calendar likes this matrix.

Sun.

Mon.

Tue.

Wed.

Thu.

Fri.

Sat.

Week 1

1

2

3

4

5

6

7

Week 2

8

9

10

11

12

13

14

Week 3

15

16

17

18

19

20

21

Week 4

22

23

24

25

26

27

28

Week 5

29

30

31

32

33

34

35

Week 6

36

37

38

39

40

41

42

Week 7

43

44

45

46

47

48

49

The cell at $i$-th row and $j$-th column is denoted $(i, j)$.

If upper-left is $(1, 5)$, the sum of integers is $5+6+7+12+13+14+19+20+21=117$.

If upper-left is $(3, 2)$, the sum of integers is $16+17+18+23+24+25+30+31+32=216$.

Therefore, there are 2 good sub-grids.

Sample Input 2

6 0

Sample Output 2

2

If upper-left is $(1, 3)$ or $(4, 4)$, it is a good sub-grid.

Sample Input 3

18 10


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

static const int INF = 0x3f3f3f3f;

int main() {
        int n;
        scanf("%d", &n);
        string s, t;
        cin >> s >> t;
        if (s == t) return !puts("0");
        if (s[0] != t[0]) return !puts("-1");
        vector<int> a, b;
        b.push_back(0);
        a.push_back(0);
        set<int> check;
        for (int i = 1; i < n; i ++) if (t[i] != t[i - 1]) b.push_back(i);
        for (int i = 1; i < b.size(); i ++) {
                int p = b[i];
                while (p > 0 && s[p] != t[b[i]]) p --;
                if (p == 0) return !puts("-1");
                if (check.count(p)) return !puts("-1");
                check.insert(p);
                a.push_back(p);
        }
        int lb = -1, ub = INF;
        while (ub - lb > 1) {
                int s = (lb + ub) / 2;
                bool ok = true;
                for (int i = 0; i < b.size(); i ++) {
                        if (i + s < a.size()) ok &= a[i + s] - s >= b[i];
                }
                if (ok) ub = s;
                else lb = s;
        }
        printf("%d\n", ub + 1);
        return 0;
}

Score : 1500 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

Shik's job is very boring. At day 0, his boss gives him a string S_0 of length N which consists of only lowercase English letters. In the i-th day after day 0, Shik's job is to copy the string S_{i-1} to a string S_i. We denote the j-th letter of S_i as S_i[j].

Shik is inexperienced in this job. In each day, when he is copying letters one by one from the first letter to the last letter, he would make mistakes. That is, he sometimes accidentally writes down the same letter that he wrote previously instead of the correct one. More specifically, S_i[j] is equal to either S_{i-1}[j] or S_{i}[j-1]. (Note that S_i[1] always equals to S_{i-1}[1].)

You are given the string S_0 and another string T.
Please determine the smallest integer i such that S_i could be equal to T. If no such i exists, please print -1.

Constraints

1 \leq N \leq 1,000,000

The lengths of S_0 and T are both N.

Both S_0 and T consist of lowercase English letters.

Input

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

N
S_0
T

Output

Print the smallest integer i such that S_i could be equal to T. If no such i exists, print -1 instead.

Sample Input 1

5
abcde
aaacc

Sample Output 1

2

S_0 = abcde, S_1 = aaccc and S_2 = aaacc is a possible sequence such that S_2 = T.

Sample Input 2

5
abcde
abcde

Sample Output 2

0

Sample Input 3

4
acaa
aaca

Sample Output 3

2

Sample Input 4

5
abcde
bbbbb

Sample Output 4

-1


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

int main()
{
    int v_x, v_y, p;
    cin>>v_x>>v_y>>p;
    int x[p], y[p], c[p], xf = 0, xl = v_x, yf = 0, yl = v_y, ans;

    for(int i = 0; i < p; i++)
    {
        cin>>x[i]>>y[i]>>c[i];

        if(c[i] == 1)
            xf = max(x[i], xf);

        else if(c[i] == 2)
            xl = min(x[i], xl);

        else if(c[i] == 3)
            yf = max(y[i], yf);

        else if(c[i] == 4)
            yl = min(y[i], yl);
    }
    ans = (xl - xf) * (yl - yf);
    if(ans < 0)
        ans = 0;
    cout<<ans<<endl;

}

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

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

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

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

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

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

Sample Output 3

64


#include <iostream>
using namespace std;

int main(){
	int n, t, count = 0, diff = 0;
	cin >> n >> t;
	int a[n];
	for(int i = 0; i < n; i++) cin >> a[i];
	for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++){
		if(a[j] - a[i] > diff){
			diff = a[j] - a[i];
			count = 1;
		}else if(a[j] - a[i] == diff) count++;
	}
	cout << count << endl;
}

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

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

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

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

Sample Output 3

2