#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cmath>
#include <climits>
#include <ctime>
#include <fstream>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#define endl '\n'
//#define ll long long
#define mod 1000000007
#define NCONS 100001
//#define NCONS 100001
//#define NCONS 1001
//#define NCONS 101
#define MCONS 2001
#define LIMIT 1000000000
#define TRUE 1
#define FALSE 0
#define toRadian(degree) ((degree) * (M_PI / 180.))
#define toDegree(radian) ((radian) * (180. / M_PI))
#define int long long
#define double long double
using namespace std;
struct Point{int x; int y;};
struct PPoint{Point x; Point y;};
typedef long long ll;

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

#define YYYY cout << "YES" << endl
#define NNNN cout << "NO" << endl
#define yyyy cout << "Yes" << endl
#define nnnn cout << "No" << endl

int32_t main(void)
{
    cin.tie(NULL); ios_base::sync_with_stdio(false);
    int a; string s; cin >> a >> s;
    if(a < 3200)
        cout << "red";
    else
        cout << s;

    return 0;
}


#include <bits/stdc++.h>

#define loop(s, e, i) for (int i = s; i < e; ++i)
#define print(s) cout << s << endl;
using namespace std;
using ll = long long;

/*
浮動小数点の入力
cout << fixed << setprecision(9) << endl;
*/

ll gcd(ll a, ll b)
{
  if (a < b)
  {
    return gcd(b, a);
  }
  while (b != 0)
  {
    ll tmp = b;
    b = a % b;
    a = tmp;
  }
  return a;
}

int main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int N, Q;
    cin >> N >> Q;

    vector<int> T(N);
    vector<int> C(N);
    loop(0, N-1, i) {
      int t1, t2;
      cin >> t1 >> t2;
      t1--;
      t2--;
      if (t2 < t1) swap(t1, t2);
      T[t2] = t1;
    }

    loop(0, Q, i) {
      int j, n;
      cin >> j >> n;
      j--;
      C[j] += n;
    }

    loop(1, N, i) {
      C[i] += C[T[i]];
    }

    loop(0, N, i) {
      if (i != N-1) {
        cout << C[i] << " ";
      } else {
        cout << C[i] << endl;
      }
    }
}

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

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

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

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

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

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

Sample Output 2

20 20 20 20 20 20

Submitted source-code file size, in bytes.

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

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


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vpii = vector<pair<int, int>>;
#define rep(i, n) for (int i = 0; i < (int)n; i++)
#define rep1(i, n) for (int i = 1; i < (int)n; i++)
const ll mod = 1e9+7;
const ll inf = 1e10;
const double pi = 3.141592;

void f(vector<ll>& c , vector<vector<int>>& v , int id){
  for(const auto& nid : v[id]){
    c[nid] += c[id];
    f(c, v, nid);
  }
  return;
}

int main(){
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  int n, q;
  cin >> n >> q;
  vector<vector<int>> v(n+1);
  rep(i, n-1){
    int a, b;
    cin >> a >> b;
    v[a].push_back(b);
  }
  vector<ll> counter(n, 0);
  rep(i, q){
    int p, x;
    cin >> p >> x;
    counter[p] += x;
  }
  f(counter, v, 1);
  rep(i, n) cout << counter[i+1] << "\n";
  return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#define rep(i,n) for(int i=0;i<n;++i)
#define rep1(i,n) for(int i=1;i<=n;++i)
using namespace std;
class Tree{
private:
  int n;
  vector<vector<int>> edge;
  vector<int> d;
  vector<int> res;
public:
  Tree(int _n,vector<int> a,vector<int> b){
    n = _n;
    edge.resize(n);
    d.resize(n,0);
    res.resize(n,0);
    rep(i,n-1){
      edge[a[i]].push_back(b[i]);
      edge[b[i]].push_back(a[i]);
    }
  }

  void init(vector<int> p,vector<int> x){
    rep(i,p.size()) d[p[i]] += x[i];
  }

  void dfs(int v,int p,int point){
    for(auto w:edge[v]){
      if(w==p) continue;
      dfs(w,v,point+d[w]);
    }
    res[v] = point;
  }

  void solve(){
    dfs(0,-1,d[0]);
    rep(i,n) cout << res[i] << " ";
    cout  << "\n";
  }

};

int main()
{
  int n,q;
  cin >> n >> q;
  vector<int> a(n-1),b(n-1);
  rep(i,n-1){
    cin >> a[i] >> b[i];a[i]--;b[i]--;
  }
  Tree tr(n,a,b);

  vector<int> p(q),x(q);
  rep(i,q){
    cin >> p[i] >> x[i];p[i]--;
  }
  tr.init(p,x);
  tr.solve();

  return 0;
}


#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n; i >= 0; i--)
#define FOR(i, m, n) for (int i = m; i < n; i++)
#define ALL(v) v.begin(), v.end()
using namespace std;
typedef long long ll;
typedef long double ld;
int main()
{
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int n,q;
  cin >> n >> q;
  vector<vector<int>> G(n);
  vector<ll> value(n, 0);
  REP(i,n-1){
    int a,b;
    cin >> a >> b;
    G[a-1].push_back(b-1);
    G[b-1].push_back(a-1);
  }
  REP(i,q){
    int p,x;
    cin >> p >> x;
    value[p-1] += (ll)x;
  }
  vector<int> seen(n, 0);
  queue<int> que;
  que.push(0);
  while(!que.empty()){
    int v = que.front();
    seen[v] = 1;
    que.pop();
    for(auto nv: G[v]){
      if(seen[nv]==0){
      	value[nv] += value[v];
      	que.push(nv);
      }
    }
  }
  REP(i,n) cout << value[i] << " ";
  return 0;
}


#include <bits/stdc++.h>
#define ll long long
#define double long double
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define mod (ll)(1e9+7)
#define inf (ll)(3e18+7)
#define P pair<int,int>
#define PiP pair<int,pair<int,int>>
#define all(x) x.begin(),x.end()
using namespace std;

int main() {
  int n, q;
  cin >> n >> q;
  vector<int> a(n-1), b(n-1), ans(n), p(q), x(q), parent(n, 0);
  rep(i, n-1){
    cin >> a.at(i) >> b.at(i);
    parent.at(b.at(i)-1) = a.at(i)-1;
  }
  rep(i, q) {
    cin >> p.at(i) >> x.at(i);
    ans.at(p.at(i)-1) += x.at(i);
  }
  cout << ans.at(0) << " ";
  for(int i = 1; i < n; i++) {
    ans.at(i) += ans.at(parent.at(i));
    cout << ans.at(i) << " ";
  }

}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pll pair<ll,ll>
#define pii pair<int,int>
#define mii map<int,int>
#define msi map<string,int>
#define mci map<char,int>
#define pb push_back
#define mp make_pair
#define M 1101
#define MOD 1000000007
#define fi first
#define se second
#define vi vector<int>
#define vl vector<ll>
#define all(v) v.begin(),v.end()
#define allr(v) v.rbegin(),v.rend()
#define repl(i,l,r) for(long long i=l;i<=r;++i)
#define rep(i,l,r) for(int i=l;i<=r;++i)
#define ins insert
#define inf 10000000000000000ll
#define vpi vector< pair<int,int> >
#define vpl vector< pair<ll,ll> >
#define eps 1e-7
#define endl "\n"
/*ll gcd(ll a,ll b){if(a==0){return b;}return gcd(b%a,a);}
ll modexp(ll x,ll y,ll p)
{ll res=1;x%=p;while(y){if(y&1){res=(res*x)%p;}y=y>>1;x=(x*x)%p;}return res;}
int x[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
int y[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; */
const int maxn=2e5+10;
vector<int>g[maxn];
ll ans[maxn];
int n,q;
void dfs(int v,int p)
{
    for(auto to:g[v])
    {
        if(to==p){continue;}
        ans[to]+=ans[v];
        dfs(to,v);
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin>>n>>q;
    rep(i,1,n-1)
    {
        int a,b;cin>>a>>b;
        g[a].pb(b);
        g[b].pb(a);
    }
    rep(i,1,q)
    {
        int p,x;cin>>p>>x;
        ans[p]+=x;
    }
    dfs(1,1);
    rep(i,1,n)
    {
        cout<<ans[i]<<" ";
    }

    return 0;

    /*check for long long or int*/
}


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

vector<int> adj[200002];
long long ans[200003];

long long dfs(int s, int p,int pay){
    for(int node: adj[s]) {
        if(node == p) continue;
        dfs(node, s, pay + ans[node]);
        ans[node]+=pay;
    }
}
int main() {
	int n, q;
	cin >> n >> q;
	int i;
	for(i=1;i<=n-1;i++) {
	    int a, b;
	    cin >> a >> b;
	    adj[a].push_back(b);
	    adj[b].push_back(a);
	}
	while(q-- ){
	    int a, b;
	    cin >> a >> b;
	    ans[a]+=b;
	}
	dfs(1, 0, ans[1]);
	for(i=1;i<=n;i++) cout<<ans[i]<<" ";
	cout<<"\n";
	return 0;
}


/*
ID: wangjun30
TASK:
LANG: C++
*/
#include<iostream>
using namespace std;
struct NODE{int next,to;}node[200010];
bool vis[200010];
int head[200010],edge=1;
int num[200010];
void add_edge(int u,int v){
	node[edge].to=v;
	node[edge].next=head[u];
	head[u]=edge;
	edge++;
}
void dfs(int x,int val){
	num[x]+=val;
	int i=head[x];
	while(i!=-1){
		if(!vis[node[i].to]){
			vis[node[i].to]=true;
			dfs(node[i].to,val);
			vis[node[i].to]=false;
		}
		i=node[i].next;
	}
}
int main(){
	int n,q;
	cin>>n>>q;
	for(int i=1;i<=n;i++)
		head[i]=-1;
	for(int i=1;i<n;i++){
		int u,v;
		cin>>u>>v;
		add_edge(u,v);
	}
	for(int i=1;i<=q;i++){
		int p,x;
		cin>>p>>x;
		vis[p]=true;
		dfs(p,x);
		vis[p]=false;
	}
	for(int i=1;i<=n;i++)
		cout<<num[i]<<' ';
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(ll i=0, i##_len=(n); i<i##_len; ++i)
#define repin(a,n) vector<ll> a(n);rep(i,n){cin>>a[i];}
#define in(a) ll a;cin>>a;
#define out(a) cout<<a<<endl;

struct node {
	forward_list<node*> c;
	ll count = 0;
};

void addNum(const forward_list<node*>& nodes,ll num){
    for (const auto& no : nodes) {
        no->count += num;
        addNum(no->c,num);
    }
}

int main()
{
	in(n);
	in(q);
	vector<node*> nodes(n);
	rep(i, n) {
		nodes[i] = new node();
	}
	rep(i, n - 1) {
		int a;
		int b;
		cin >> a; cin >> b;
		nodes[a - 1]->c.push_front(nodes[b - 1]);
	}
	rep(i, q) {
		int p;
		int x;
		cin >> p; cin >> x;
        nodes[p - 1]->count += x;
        addNum(nodes[p - 1]->c,x);
	}
	rep(i, n) {
		out(nodes[i]->count);
	}
}


#include <iostream>
#include <vector>
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)

using namespace std;
typedef unsigned long long ull;
int gcd(int a,int b){return b?gcd(b,a%b):a;}

int main(int argc, char const *argv[])
{
  int n, q; cin >> n >> q;
  vector<int> t(n);
  rep(i,n) t[i] = i;
  int a,b;
  rep(i,n-1) {
    cin >> a >> b;
    --a; --b;
    t[max(a,b)] = min(a,b);
  }
  vector<ull> c(n);
  rep(i,q) {
    cin >> a >> b;
    --a;
    c[a] += b;
  }

  vector<bool> visited(n,false);
  visited[0] = true;
  rep(i,n) {
    int j=n-i-1;
    if(visited[j]) continue;
    int k=j;
    vector<int> path(n);
    int r=0;
    path[r] = k;
    while(1) {
      ++r;
      visited[k] = true;
      k=t[k];
      path[r] = k;
      if(visited[k]) break;
    }
    --r;
    while(r>=0) {
      c[path[r]] += c[path[r+1]];
      --r;
    }
  }
  cout << c[0];
  rep(i,n-1) {
    cout << " " << c[i+1];
  }
  cout << endl;
  return 0;
}


#include <iostream>
#include <vector>
using namespace std;
long long INF = 1e18;
struct edge{
    int from;
    int to;
    long long cost;
};
void solve(int N, int M, vector<edge> &es, int s, int t){
    vector<long long> d(N);//各頂点までの距離
    for(int i = 0; i < N; i++) d[i] = INF;
    d[s] = 0;
    long long k = 0;
    long long ans = 0;
    while(true){
        bool flag = false;
        bool flag2 = false;
        long long temp = d[t];
        for(int i = 0; i < M; i++){
            edge e = es[i];
            if(d[e.from] != INF && d[e.to] > d[e.from] + e.cost){
                d[e.to] = d[e.from] + e.cost;
                flag = true;
                if(e.to == t) flag2 = true;
            }
        }
        if(!flag) break;
        ans = min(ans, d[t]);
        k++;
        if(k == N && flag2){//閉路があって無限に更新される場合はinf
            cout << -1 << endl;
            return;
        }
        else if(k == N && !flag2) break;
    }
    cout << -ans << endl;
}
int main(){
    int N, M;
    cin >> N >> M;
    long long P;
    cin >> P;
    vector<edge> es(M);
    for(int i = 0; i < M; i++){
        int x, y;
        long long c;
        cin >> x >> y >> c;
        x--;
        y--;
        edge e = {x, y, -c + P};
        es[i] = e;
    }
    solve(N, M, es, 0, N - 1);
}

Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


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

#define ll long long
#define ii pair<ll, ll>
#define dd pair<double, double>
#define pb(i) push_back(i)
const double PI = 3.14159265359;
const ll inf = 1e18;
const ll mod = 1e9+7;
const double eps = 1e-7;
//int dir1[8] = {0, 0, 1, -1, 1, -1, 1, -1};
//int dir2[8] = {1, -1, 0, 0, 1, 1, -1, -1};
int dir1[4] = {0, 0, 1, -1};
int dir2[4] = {1, -1, 0, 0};

vector<vector<int> > inv_gr;
vector<pair<int, ii> > edges;

void dfs(int u, vector<bool> &visited)
{
    int i, j;
    if(visited[u])
        return;

    visited[u] = true;
    for(i = 0; i < inv_gr[u].size(); i++)
        dfs(inv_gr[u][i], visited);
}

int main()
{
    int i, j;

    int n, m, p;
    cin >> n >> m >> p;

    inv_gr.resize(n+5);
    for(i = 0; i < m; i++)
    {
        pair<ll, ii> aux;
        cin >> aux.second.first >> aux.second.second >> aux.first;
        aux.first = p - aux.first;

        int v = aux.second.second;
        int u = aux.second.first;
        inv_gr[v].pb(u);
        edges.pb(aux);
    }

    vector<bool> visited(n+5, false);
    dfs(n, visited);

    vector<ll> dist(n+5, inf);
    dist[1] = 0;
    for(i = 0; i < n-1; i++)
        for(i = 0; i < (int)edges.size(); i++)
        {
            int w = edges[i].first;
            int v = edges[i].second.second;
            int u = edges[i].second.first;

            if(dist[u] != inf && dist[v] > dist[u]+w)
                dist[v] = dist[u]+w;
        }

    bool truth = true;
    for(i = 0; i < (int)edges.size(); i++)
    {
        int w = edges[i].first;
        int v = edges[i].second.second;
        int u = edges[i].second.first;

        if(dist[u] != inf && dist[v] > dist[u]+w)
        {
            if(visited[u])
                truth = false;
        }
    }

    if(truth)
        cout << max(0LL, -dist[n]) << '\n';
    else
        cout << "-1\n";
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define REP(i, n) for(int i = 0; i < (int)(n); i++)
static const int fast_io = [](){ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);return 0;}();
static const int precise_doubles = [](){cout<<fixed<<setprecision(20);return 0;}();
typedef pair<int, int> PII;
typedef tree<PII, null_type, less<PII>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
// find_by_order(k) - iterator to k'th element (0-based), order_of_key(k) - #things < k
typedef long double LD;
typedef long long LL;
#define EVAL(x) x
#define NEWL EVAL({cout << '\n';})
#define SPA(x) EVAL({cout << #x" = " << x << ' ';})
#define SPAR(a, b) EVAL({cout<<#a" = ";for(auto it=a;it!=b;)cout<<*(it++)<<" ";cout<<'\n';})
#define SPAV(v) EVAL({cout<<#v" = ";for(auto it=v.begin();it!=v.end();)cout<<*(it++)<<" ";cout<<'\n';})
const int INF = 0x3f3f3f3f; // 1.0e9
const LL LINF = 0x3f3f3f3f3f3f3f3fll; // 4.5e18
const LD eps = 1e-20;
const int mod = 1e9 + 7;
inline int msum(int x, int y) {return (x+y<mod ? x+y : x+y-mod);}
inline int mdif(int x, int y) {return (x>=y ? x-y : x-y+mod);}
inline int mprod(int x, int y) { return (1ll*x*y) % mod; }
inline int mpow(int x, LL y) {LL r=1;while(y){if(y&1)r=mprod(r,x);x=mprod(x,x);y>>=1;}return r;}
inline int minv(int x) { return mpow(x, mod-2); }
//------------------------------------------------------------------------------------------------------

const int N = 2500 + 10;

struct Edge {
    int vertex, cost;
};

int n, m, p;
vector<Edge> fwd[N];
vector<int> bwd[N];
bool reachable_from_n[N];
LL dis[N];

void dfs(int u) {
    reachable_from_n[u] = true;
    for (int v : bwd[u]) {
        if (!reachable_from_n[v]) {
            dfs(v);
        }
    }
}

void bellman_ford() {
    for (int u = 1; u <= n; u++) {
        dis[u] = LINF;
    }
    dis[1] = 0;
    REP(rep, n-1) {
        for (int u = 1; u <= n; u++) {
            if (dis[u] == LINF)
                continue;
            for (Edge e : fwd[u]) {
                int v = e.vertex;
                int c = e.cost;
                if (dis[u] + c < dis[v]) {
                    dis[v] = dis[u] + c;
                }
            }
        }
    }
}

bool negative_cycle() {
    for (int u = 1; u <= n; u++) {
        if (dis[u] == LINF)
                continue;
        for (Edge e : fwd[u]) {
            int v = e.vertex;
            int c = e.cost;
            if (dis[u] + c < dis[v]) {
                if (reachable_from_n[v]) {
                    return true;
                }
            }
        }
    }
    return false;
}

int main() {
    cin >> n >> m >> p;
    REP(rep, m) {
        int u, v, c;
        cin >> u >> v >> c;
        fwd[u].push_back({v, p - c});
        bwd[v].push_back(u);
    }
    dfs(n);
    bellman_ford();
    if (negative_cycle()) {
        cout << -1 << endl;
    } else {
        cout << max(-dis[n], 0LL) << endl;
    }
}


#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<set>
#include<string>
#include<map>
#include<string.h>
#include<complex>
#include<math.h>
#include<queue>
#include <functional>
#include<time.h>
#include<iomanip>
using namespace std;
typedef long long int llint;
typedef pair<int, int> pint;
typedef pair<llint, llint> pllint;
typedef vector<int> vint;
typedef vector<llint> vllint;
typedef vector<pint> vpint;
typedef vector<string> vstring;
typedef vector<pair<llint, llint>> vpllint;
typedef vector<vector<int>> vvint;
typedef vector<vector<llint>> vvllint;
typedef vector<vector<pint>> vvpint;
typedef vector<bool> vbool;
typedef vector<vbool> vvbool;
typedef vector<vpllint> vvpllint;
#define rep(i,n) for(int i=0;i<n;i++)
#define drep(i,n) for(int i=n-1;0<=i;i--)
#define yes(ans) if(ans)cout<<"yes"<<endl;else cout<<"no"<<endl;
#define Yes(ans) if(ans)cout<<"Yes"<<endl;else cout<<"No"<<endl;
#define YES(ans) if(ans)cout<<"YES"<<endl;else cout<<"NO"<<endl;
#define POSSIBLE(ans) if(ans)cout<<"POSSIBLE"<<endl;else cout<<"IMPOSSIBLE"<<endl;
#define Pi 3.1415926535897932384626
#define mod llint(1e9+7)
#define Inf 2147483647
#define llInf 9223372036854775807
#define all(x) x.begin(),x.end()
#define pb push_back
#define isin(n,i) 0<=i&&i<n

class UnionFind {
public:
	//親の番号を格納する。親だった場合は-(その集合のサイズ)
	vector<int> Parent;

	//作るときはParentの値を全て-1にする
	//こうすると全てバラバラになる
	UnionFind(int N) {
		Parent = vector<int>(N, -1);
	}

	//Aがどのグループに属しているか調べる
	int root(int A) {
		if (Parent[A] < 0) return A;
		return Parent[A] = root(Parent[A]);
	}

	//自分のいるグループの頂点数を調べる
	int size(int A) {
		return -Parent[root(A)];//親をとってきたい
	}

	//AとBをくっ付ける
	bool connect(int A, int B) {
		//AとBを直接つなぐのではなく、root(A)にroot(B)をくっつける
		A = root(A);
		B = root(B);
		if (A == B) {
			//すでにくっついてるからくっ付けない
			return false;
		}

		//大きい方(A)に小さいほう(B)をくっ付けたい
		//大小が逆だったらひっくり返しちゃう。
		if (size(A) < size(B)) swap(A, B);

		//Aのサイズを更新する
		Parent[A] += Parent[B];
		//Bの親をAに変更する
		Parent[B] = A;

		return true;
	}
};

//セグ木・0-indexed・非再帰・(大きさ・単位元・関数)で初期化
template<typename T>
struct SegTree {
	//比較関数の型
	using F = function<T(T, T)>;
	//二分木を配列で表したもの
	vector<T>seg;
	//木の半分の大きさ
	int siz;
	//単位元
	const T unit;
	//比較する関数
	const F f;

	//大きさn、unit(単位元)、f(モノイド)でsegtreeを初期化する
	SegTree(int n, const T unit, const F f) : unit(unit), f(f) {
		siz = 1;
		while (siz < n)siz <<= 1;
		seg.assign(siz * 2 - 1, unit);
		siz--;
	}

	//k番目にtを入力
	void set(int k, const T& t) {
		seg[k + siz] = t;
	}

	//fによって木を構築する
	void build() {
		for (int i = siz - 1; 0 <= i; i--) {
			seg[i] = f(seg[i * 2 + 1], seg[i * 2 + 2]);
		}
	}

	T operator[](const int i) {
		return seg[i + siz];
	}

	//k番目をxに更新する
	void update(int k, T x) {
		k += siz;
		seg[k] = x;
		while (0 < k) {
			k = (k - 1) >> 1;
			seg[k] = f(seg[k * 2 + 1], seg[k * 2 + 2]);
		}
	}

	//[a,b)について、fした結果を返す
	//半開区域のためa以上b未満の位置を指す
	T query(int a, int b) {
		T l = unit, r = unit;
		for (a += siz, b += siz; a < b; a >>= 1, b >>= 1) {
			if (!(a & 1))l = f(seg[a++], l);
			if (!(b & 1))r = f(seg[--b], r);
		}
		return f(l, r);
	}
};

//aとbの最大公約数を求めるよ
long long GCD(long long a, long long b) {
	if (b == 0) return a;
	else return GCD(b, a % b);
}

// 返り値: a と b の最大公約数
// ax + by = gcd(a, b) を満たす (x, y) が格納される
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. m での a の逆元 a^{-1} を計算する
long long modinv(long long a, long long m) {
	long long b = m, u = 1, v = 0;
	while (b) {
		long long t = a / b;
		a -= t * b; swap(a, b);
		u -= t * v; swap(u, v);
	}
	u %= m;
	if (u < 0) u += m;
	return u;
}

//nCrを1000000007で割った余りを求める
llint nCr(llint n, llint r) {
	llint ans = 1;
	for (llint i = 0; i < r; i++) {
		ans *= n - i;
		ans %= 1000000007;
	}
	for (llint i = 1; i <= r; i++) {
		ans *= modinv(i, 1000000007);
		ans %= 1000000007;
	}
	return ans;
}

//aのb乗をmodで割った余りを求める
llint power(llint a, llint b) {
	if (b == 1)return a;
	if (b == 0)return 1;
	llint tmp = power(a, (llint)b / 2);
	tmp *= tmp;
	tmp %= mod;
	if (b % 2 == 1) {
		tmp *= a;
		tmp %= mod;
	}
	return tmp;
}

//bitを表すsub,要素数を表すlength
bool next_combination(llint& sub, int length) {
	llint x = sub & -sub, y = sub + x;
	sub = (((sub & ~y) / x) >> 1) | y;
	return sub < (llint)(1 << (llint)length);
}

int main() {
	int n, m, p;
	cin >> n >> m >> p;
	vvpint edges(n);
	rep(i, m) {
		int x, y, c;
		cin >> x >> y >> c;
		x--; y--;
		edges[x].pb({ y,c - p });
	}
	//iへの最高スコア
	vint cost(n, -Inf);
	cost[0] = 0;
	//ベルマンフォードやるよー
	rep(i, n) {
		rep(j, n) {
			if (cost[j] == -Inf)continue;
			rep(k, edges[j].size()) {
				cost[edges[j][k].first] = max(cost[edges[j][k].first], cost[j] + edges[j][k].second);
			}
		}
	}
	int ans = cost[n - 1];
	rep(i, n) {
		rep(j, n) {
			if (cost[j] == -Inf)continue;
			rep(k, edges[j].size()) {
				if (cost[edges[j][k].first] < (llint)cost[j] + edges[j][k].second) {
					cost[edges[j][k].first] = Inf;
				}
			}
		}
	}
	if (cost[n - 1] == Inf) {
		cout << -1 << endl;
	}
	else cout << max(0, ans) << endl;
	return 0;
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define zero_pad(num) setfill('0') << std::right << setw(num)
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;

int main() {
    int n, m, p;
    cin >> n >> m >> p;
    vector<vector<P>> to(n);
    rep(i, n){
        int a, b, c;
        cin >> a >> b >> c;
        a--;
        b--;
        to[a].push_back(make_pair(b, -(c - p)));
    }

    ll INF = 1001001001001001001;
    vector<ll> d(n, INF);
    d[0] = 0;
    ll ans = 0;
    rep(i, n){
        rep(j, n){
            for(P t : to[j]){
                if(d[j] != INF && d[t.first] > d[j] + t.second){
                    d[t.first] = d[j] + t.second;
                }
            }
        }
        if(i == n - 2)ans = d[n - 1];
        else if(i == n - 1){
            if(ans == d[n - 1] || -ans <= 0)cout << max(0LL, -ans) << endl;
            else cout << -1 << endl;
        }
    }

}


#include <bits/stdc++.h>
#define all(v) (v).begin(), (v).end()
typedef long long int lint;
using namespace std;

//ただの辺
struct edge {
    using lint = long long int;
    int to;
    lint cost;
    //引数一つの時は距離1
    edge(int t, lint c = 1) : to(t), cost(c) {
    }
};

// Bellman-Ford
// depend:edge
vector<lint> bellman_ford(vector<vector<edge>> g, int s) {
    using lint = long long int;
    int n = g.size();
    vector<lint> res(n, LLONG_MAX);
    res[s] = 0;
    for (int i = 0; i < 2 * n; i++) {
        for (int j = 0; j < n; j++) {
            if (res[j] == LLONG_MAX) continue;
            for (int k = 0; k < (int)g[j].size(); k++) {
                int c = g[j][k].cost, dest = g[j][k].to;
                if (i < n - 1) {
                    res[dest] = min(res[dest], res[j] + c);
                } else {
                    if (res[j] == LLONG_MIN || res[dest] > res[j] + c)
                        res[dest] = LLONG_MIN;
                }
            }
        }
    }
    return res;
}

int main() {
    int n, m, p;
    cin >> n >> m >> p;
    vector<vector<edge>> g(n);
    for (int i = 0; i < m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        a--, b--;
        g[a].push_back(edge(b, p - c));
    }
    vector<lint> dist = bellman_ford(g, 0);
    if (dist[n - 1] == LLONG_MIN) {
        cout << -1 << endl;
    } else {
        cout << max(-dist[n - 1], 0LL) << endl;
    }
}


#include <bits/stdc++.h>
#define _overload3(_1, _2, _3, name, ...) name
#define _rep(i, n) repi(i, 0, n)
#define repi(i, a, b) for (ll i = (ll)(a); i < (ll)(b); ++i)
#define rep(...) _overload3(__VA_ARGS__, repi, _rep, )(__VA_ARGS__)
#define ll long long
#define lld long double
#define ALL(x) x.begin(), x.end()
#ifdef DEBUG
#define line() cerr << "[" << __LINE__ << "] ";
#define dump(i) cerr << #i ": " << i << " ";
#define dumpl(i) cerr << #i ": " << i << endl;
#else
#define line(i)
#define dump(i)
#define dumpl(i)
#endif
using namespace std;

int main(int argc, char const *argv[])
{
    int n, m, p;
    cin >> n >> m >> p;
    ll a[m], b[m], c[m];
    rep(i, m)
    {
        cin >> a[i] >> b[i] >> c[i];
        a[i]--;
        b[i]--;
        c[i] = p - c[i];
    }
    const ll INF = (1ll << 60);
    ll dist[n];
    rep(i, n) dist[i] = INF;
    dist[0] = 0;
    rep(i, n) rep(j, m)
    {
        if (dist[b[j]] > dist[a[j]] + c[j])
        {
            dist[b[j]] = dist[a[j]] + c[j];
        }
    }
    ll nowans = dist[n - 1];
    rep(j, m)
    {
        if (dist[b[j]] > dist[a[j]] + c[j])
        {
            dist[b[j]] = dist[a[j]] + c[j];
        }
    }
    if (nowans == dist[n - 1])
    {
        cout << max(0ll, -nowans) << endl;
    }
    else
    {
        cout << -1 << endl;
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,m,p,head[3000],tot=1;
struct edge{int v,w,nxt;} e[6000];

void add_edge(int u,int v,int w){
    e[tot]={v,w,head[u]};
    head[u]=tot++;
}

int dis[3000],ins[3000];
queue<int> q,cnt;
void spfa(){
    memset(dis,0x3f,sizeof(dis));
    dis[1]=0;
    ins[1]=1;
    q.push(1);
    cnt.push(0);
    bool flag=0;
    while(!q.empty()){
        if(cnt.front()>n){
            flag=1;
            break;
        }
        int u=q.front(),cntt=cnt.front();
        q.pop(),cnt.pop();
        ins[u]=0;
        for(int i=head[u];i;i=e[i].nxt){
            int v=e[i].v,w=e[i].w;
            if(dis[u]+w<dis[v]){
                dis[v]=dis[u]+w;
                if(!ins[v]){
                    ins[v]=1;
                    q.push(v);
                    cnt.push(cntt+1);
                }
            }
        }
    }
    if(flag){
        int xxx=dis[n];
        int u=q.front(),cntt=cnt.front();
        q.pop(),cnt.pop();
        ins[u]=0;
        for(int i=head[u];i;i=e[i].nxt){
            int v=e[i].v,w=e[i].w;
            if(dis[u]+w<dis[v]){
                dis[v]=dis[u]+w;
                if(!ins[v]){
                    ins[v]=1;
                    q.push(v);
                    cnt.push(cntt+1);
                }
            }
        }
        if(dis[n]!=xxx){
            cout<<-1<<endl;
        }else{
    cout<<-dis[n]<<endl;
    }
    }else{
    cout<<-dis[n]<<endl;
    }
}
int main(){
    cin>>n>>m>>p;
    for(int i=0;i<m;i++){
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        add_edge(u,v,min(0,p-w));
    }
    spfa();
    return 0;
}


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

class Edge{
public:
  long long f, t, c;

  Edge(int x, int y, int z) : f(x), t(y), c(z){}
};

int main(){
  int n, m, p; cin >> n >> m >> p;

  vector<long long> v(n+1, numeric_limits<long long>::max());
  vector<Edge> edge;

  for(int i=0; i<m; ++i){
    int a, b, c; cin >> a >> b >> c;
    c -= p;
    edge.push_back(Edge(a, b, -c));
  }

  v[1] = 0;
  for(int i=1; i<=2*v.size(); ++i){
    for(auto e : edge){
      if(v[e.f] == numeric_limits<long long>::max()) continue;

      if(v[e.t] > v[e.f] + e.c){
        if(i >= v.size()){
          v[e.t] = numeric_limits<long long>::min();
        }else{
          v[e.t] = v[e.f] + e.c;
        }
      }
    }
  }

  if(v[n] == numeric_limits<long long>::min())
    cout << -1 << endl;
  else
    cout << max(0LL, -v[n]) << endl;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct ed{int t,n,w;}e[6010];
int n,m,k,h[2510],l,d[2510],cn[2510],t,w,q;
bool v[2510];
queue<int> que;
bool aspeFA()
{
    for(int i=2;i<=n;i++) d[i]=-1e9;
    v[1]=1;
    que.push(1);
    int c;
    while(!que.empty())
    {
       	c=que.front();
   	 	v[c]=0;
   	 	cn[c]++;
   		que.pop();
   	 	if(cn[c]>=n+(n==1))
		{
			if(c==n) return 1;
			if(cn[c]>=n*3 || d[c]>=1e9)continue;
		}
    	for(int i=h[c];i;i=e[i].n)
        {
       	  	if(d[e[i].t]<d[c]+e[i].w)
            {
                d[e[i].t]=d[c]+e[i].w;
                if(!v[e[i].t])
                {
                    que.push(e[i].t);
                   	v[e[i].t]=1;
                }
            }
    	}
    }
    return 0;
}
int main()
{
    scanf("%d%d%d",&n,&m,&t);
    for(int i=1;i<=n;i++) h[i]=0;
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&k,&l,&w);
        e[i].t=l;
        e[i].n=h[k];
        e[i].w=w-t;
        h[k]=i;
        q++;
    }
    if(aspeFA()) printf("-1\n");
	else printf("%d\n",d[n]<0?0:d[n]);
    return 0;
}


#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const int INF = (1<<30);
const ll INFLL = (1ll<<60);
const ll MOD = (ll)(1e9+7);

#define l_ength size

void mul_mod(ll& a, ll b){
	a *= b;
	a %= MOD;
}

void add_mod(ll& a, ll b){
	a = (a<MOD)?a:(a-MOD);
	b = (b<MOD)?b:(b-MOD);
	a += b;
	a = (a<MOD)?a:(a-MOD);
}

int n,a[5555],b[5555];
ll d[2525],c[5555];
bool visited[2525],pos[2525];
vector<int> g[2525];

bool dfs(int v){
	int i;
	visited[v] = true;
	if(v==n){
		return pos[v] = true;
	}
	for(i=0; i<g[v].l_ength(); ++i){
		if(visited[g[v][i]]){
			continue;
		}
		if(dfs(g[v][i])){
			return pos[v] = true;
		}
	}
	return pos[v] = false;
}

int main(void){
	int m,i,cnt=0,j;
	bool update,loop = false;
	ll p;
	fill(d,d+2525,INFLL);
	d[1] = 0ll;
	cin >> n >> m >> p;
	for(i=0; i<m; ++i){
		cin >> a[i] >> b[i] >> c[i];
		c[i] = p - c[i];
		g[a[i]].push_back(b[i]);
	}
	dfs(1);
	while(true){
		update = false;
		for(i=0; i<m; ++i){
			if(d[b[i]]>d[a[i]]+c[i]){
				update = true;
				d[b[i]] = d[a[i]]+c[i];
			}
		}
		if(!update){
			break;
		}
		if(cnt > n){
			break;
		}
		++cnt;
	}
	for(j=0; j<n; ++j){
		for(i=0; i<m; ++i){
			if(d[b[i]]>d[a[i]]+c[i]){
				d[b[i]] = d[a[i]]+c[i];
				if(pos[b[i]]){
					loop = true;
				}
			}
		}
	}
	if(loop){
		cout << -1 << endl;
		return 0;
	}
	cout << max(-d[n],0ll) << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
struct node{
	int v;
	int w;
	int nxt;
}edge[100010];
int head[100010],tot;
void addedge(int u,int v,int w)
{
	edge[tot].v=v;
	edge[tot].w=w;
	edge[tot].nxt=head[u];
	head[u]=tot++;
}
void init()
{
	memset(head,-1,sizeof(head));
	tot=0;
}
int n,m,p;
int vis[100010];
int ans=-(0x3f3f3f3f);
void dfs(int u,int time,int score)
{
	if(u==n)
	{
		ans=max(ans,score-time*p);
	}
	for(int i=head[u];i!=-1;i=edge[i].nxt)
	{
		int v=edge[i].v;
		int w=edge[i].w;
		if(vis[v])continue;
		vis[v]=1;
		edge[i].w=0;
		dfs(v,time+1,score+w);
		edge[i].w=w;
		vis[v]=0;
	}
}
int tmpp,tmppp;
void look(int u,int tt,int ty)
{
	if(u==n)
	{
		tmpp=tt;
		tmppp=ty;
		return;
	}
	for(int i=head[u];i!=-1;i=edge[i].nxt)
	{
		int v=edge[i].v;
		look(v,tt+edge[i].w,ty+1);
	}
}
int main()
{
	init();
	cin>>n>>m>>p;
	for(int i=1;i<=m;i++)
	{
		int u,v,w;
		cin>>u>>v>>w;
		addedge(u,v,w);
	}
	int tmp=-(0x3f3f3f3f);
	for(int i=head[n];i!=-1;i=edge[i].nxt)
	{
		tmpp=0,tmppp=0;
		look(i,0,0);
		if(tmpp>=tmppp*p){
			cout<<-1<<endl;
			return 0;
		}
	}
	dfs(1,0,0);
	cout<<max(ans,0)<<endl;
	return 0;
}


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

ll n,m,p;
vector<ll> g[100005];
ll vis[2560];
bool ok;
void rech(ll s)
{
        if(ok) return;
        vis[s]=1;
        if(s==n-1) {
                ok=true; return;
        }
        for(auto &j : g[s]) {
                if(vis[j]==0) rech(j);
                if(ok) return;
        }
}
// a structure to represent a weighted edge in graph
struct Edge {
    int src, dest, weight;
};

// a structure to represent a connected, directed and
// weighted graph
struct Graph {
    // V-> Number of vertices, E-> Number of edges
    int V, E;

    // graph is represented as an array of edges.
    struct Edge* edge;
};

// Creates a graph with V vertices and E edges
ll A;
struct Graph* createGraph(int V, int E)
{
    struct Graph* graph = new Graph;
    graph->V = V;
    graph->E = E;
    graph->edge = new Edge[graph->E];
    return graph;
}

// The main function that finds shortest distances
// from src to all other vertices using Bellman-
// Ford algorithm.  The function also detects
// negative weight cycle
bool isNegCycleBellmanFord(struct Graph* graph,
                           int src)
{
    int V = graph->V;
    int E = graph->E;
    int dist[V];

    // Step 1: Initialize distances from src
    // to all other vertices as INFINITE
    for (int i = 0; i < V; i++)
        dist[i] = INT_MAX;
    dist[src] = 0;

    // Step 2: Relax all edges |V| - 1 times.
    // A simple shortest path from src to any
    // other vertex can have at-most |V| - 1
    // edges
    for (int i = 1; i <= V - 1; i++) {
        for (int j = 0; j < E; j++) {
            int u = graph->edge[j].src;
            int v = graph->edge[j].dest;
            int weight = graph->edge[j].weight;
            if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
                dist[v] = dist[u] + weight;
        }
    }

    // Step 3: check for negative-weight cycles.
    // The above step guarantees shortest distances
    // if graph doesn't contain negative weight cycle.
    // If we get a shorter path, then there
    // is a cycle.
    A = dist[n-1];
    for (int i = 0; i < E; i++) {
        int u = graph->edge[i].src;
        int v = graph->edge[i].dest;
        int weight = graph->edge[i].weight;
        if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
            {
                    ok=false;
                    for(ll i=0;i<n;i++) vis[i]=0;
                    rech(v);
                    if(ok) return true;
            }
    }

    return false;
}

// Driver program to test above functions
int main()
{
    /* Let us create the graph given in above example */
    /*int V = 5; // Number of vertices in graph
    int E = 8; // Number of edges in graph
    struct Graph* graph = createGraph(V, E);

    // add edge 0-1 (or A-B in above figure)
    graph->edge[0].src = 0;
    graph->edge[0].dest = 1;
    graph->edge[0].weight = -1;

    // add edge 0-2 (or A-C in above figure)
    graph->edge[1].src = 0;
    graph->edge[1].dest = 2;
    graph->edge[1].weight = 4;

    // add edge 1-2 (or B-C in above figure)
    graph->edge[2].src = 1;
    graph->edge[2].dest = 2;
    graph->edge[2].weight = 3;

    // add edge 1-3 (or B-D in above figure)
    graph->edge[3].src = 1;
    graph->edge[3].dest = 3;
    graph->edge[3].weight = 2;

    // add edge 1-4 (or A-E in above figure)
    graph->edge[4].src = 1;
    graph->edge[4].dest = 4;
    graph->edge[4].weight = 2;

    // add edge 3-2 (or D-C in above figure)
    graph->edge[5].src = 3;
    graph->edge[5].dest = 2;
    graph->edge[5].weight = 5;

    // add edge 3-1 (or D-B in above figure)
    graph->edge[6].src = 3;
    graph->edge[6].dest = 1;
    graph->edge[6].weight = 1;

    // add edge 4-3 (or E-D in above figure)
    graph->edge[7].src = 4;
    graph->edge[7].dest = 3;
    graph->edge[7].weight = -3;

    if (isNegCycleBellmanFord(graph, 0))
        cout << "Yes";
    else
        cout << "No";
        */
    cin >> n >> m >> p;
        struct Graph* graph = createGraph(n, m);
        for(ll i=0;i<m;i++) {
                ll a,b,c;
                cin >> a >> b >> c;
                g[a-1].pb(b-1);
                graph->edge[i].src=a-1;
                graph->edge[i].dest=b-1;
                graph->edge[i].weight=p-c;
        }
        if(isNegCycleBellmanFord(graph, 0)){
                cout << "-1\n";
                //cout << A << endl; return 0;
        }else {
                cout << max(-A, 0LL) << endl; return 0;
        }

    return 0;
}


#include <bits/stdc++.h>
#define repi(i, a, b) for (int i = (int)(a) ; i < (int)(b) ; i++)
#define rep(i, n) repi(i, 0, n)
#define SZ(x) ((int)(x).size())
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
struct Vec{
    double x, y;
};
template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
     return false;
}
using namespace std;
int main()
{
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    // cout << fixed << setprecision(15);
    int n, cnt = 0;
    bool ok = true;
    cin >> n;
    vector<ll> h(n);
    rep(i, n) cin >> h[i];
    repi(i,1, n) {
        if (h[i - 1] <= h[i]) {
            cnt = 0;
            continue;
        }
        if (h[i - 1] - 1 <= h[i]) {
            cnt++;
        } else {
            ok = false;
            break;
        }
        if (cnt == 2) {
            ok = false;
            break;
        }
    }
    if (ok) cout << "Yes" << endl;
    else cout << "No" << endl;
    return 0;
}

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.

For each square, you will perform either of the following operations once:

Decrease the height of the square by 1.

Do nothing.

Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

Sample Input 1

5
1 2 1 1 3

Sample Output 1

Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

Sample Input 2

4
1 3 2 1

Sample Output 2

No

Sample Input 3

5
1 2 3 4 5

Sample Output 3

Yes

Sample Input 4

1
1000000000

Sample Output 4

Yes


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using ld = long double;
long double const pi = std::acos(-1.0L);
typedef pair<int,int> P;
const int INF = 1001001001;

int main() {
  int n; cin >> n;
  vector<int> h(n);
  cin >> h[0];
  bool ok = true;
  for(int i = 1; i < n; ++i) {
    cin >> h[i];
    if(h[i]==h[i-1]) continue;
    h[i]--;
    if(h[i]<h[i-1]){
      ok = false;
      break;
    }
  }
  if(ok) cout <<"Yes" << endl;
  else cout << "No" << endl;
  return 0;
}


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

signed main(void)
{
	int n;
	cin >> n;
	int h[n];
	int maxi;

	rep(i, 0, n) cin >> h[i];
	maxi = h[0];
	rep (i, 1, n - 1)
	{
		if (h[i + 1] < maxi)
		{
			h[i]--;
			if (!(h[i + 1] >= h[i] && h[i] >= h[i - 1]))
			{
				cout << "No" << endl;
				return 0;
			}
		}
		else
			maxi = h[i + 1];

	}
	cout << "Yes" << endl;
	return 0;
}


#include <bits/stdc++.h>
#define GET_REP(_1, _2, _3, NAME, ...) NAME
#define rep(...) GET_REP(__VA_ARGS__, irep, _rep)(__VA_ARGS__)
#define rep1(...) GET_REP(__VA_ARGS__, irep1, _rep1)(__VA_ARGS__)
#define _rep(i, n) irep (i, 0, n)
#define _rep1(i, n) irep1(i, 1, n)
#define irep(i, a, n) for (int i = a; i < (int)(n); ++i)
#define irep1(i, a, n) for (int i = a; i <= (int)(n); ++i)
#define rrep(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define rrep1(i, n) for (int i = (int)(n); i >= 1; --i)
#define allrep(X, x) for (auto &&X : x)
#define all(x) (x).begin(), (x).end()
#ifdef LOCAL
  #include "../../Lib/cout_container.hpp"
  #define debug(x) cerr << #x " => " << (x) << endl
#else
  #define debug(x) 0
#endif
using lint = long long;
constexpr int    INF  = 1 << 29;
constexpr lint   INFL = 1LL << 61;
constexpr int    MOD  = (int)1e9 + 7;
constexpr double EPS  = 1e-9;
using namespace std;
namespace { struct INIT { INIT() { cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(15); } } INIT; }

int main(void) {
  int n;
  cin >> n;
  vector<int> h(n);
  rep (i, n) cin >> h[i];
  int  mini = 0;
  bool ok = true, done = false;
  rep (i, 0, n) {
    if (h[i] >= mini) {
      mini = h[i];
      if (h[i] > mini) done = false;
    } else {
      if (h[i] == mini - 1) continue;
      ok = false;
      break;
    }
  }
  cout << (ok ? "Yes" : "No") << endl;
  return 0;
}


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

#define vint vector<int>
#define vstr vector<string>
#define vll vector<long long>
#define ll long long
#define pf printf
#define sf scanf
#define sfd(n) scanf("%d", &n)
#define sflf(n) scanf("%lf", &n)
#define sfll(n) scanf("%lld", &n)
#define pfd(n) printf("%d", n)
#define pflf(n) printf("%lf", n)
#define pfll(n) printf("%lld", n)
#define pft	printf("\t")
#define pfn printf("\n")
#define pfk printf(" ")
#define PI 3.1415926
#define MAX 100000
#define M 100003

using namespace std;

bool vj(int *p, int n) {
	for( int i=0; i<n-1; i++ ) {
		if( p[i]>p[i+1] ) {
			return false;
		}
	}
	return true;
}

int main() {
//	int n;
//	sfd(n);
// 	double* value = new double[n];
//	for( int i=0; i<n; i++ ) {
//		sflf(value[i]);
//	}
	int n;
	sfd(n);
	int* num = new int[n];
	for( int i=0; i<n; i++ ) {
		sfd(num[i]);
	}
	bool f = true;
	for( int i=0; i<n-1; i++ ) {
		if( num[i]>num[i+1] ) {
			num[i]--;
			f = vj(num, n);
		}
	}
	if( f ) {
		cout << "Yes";
	}else {
		cout << "No";
	}

	return 0;
}


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

int A[100005];

int main() {

    ios::sync_with_stdio(0);
    cin.tie(NULL), cout.tie(NULL);

    int N;
    cin >> N;

    for(int i=1; i<=N; i++)
        cin >> A[i];

    for(int i=N-1; i>=1; i--)
    {
        if(A[i] > A[i-1])
            A[i]--;

        if(A[i] > A[i-1])
        {
            cout << "No\n";
            return 0;
        }
    }

    cout << "Yes\n";
    return 0;
}


/**
 *      purpose :
 *      author  : kyomukyomupurin
 *      created :
**/

// input/output
#include <iostream>
#include <fstream>
#include <sstream>
// container class
#include <array>
#include <deque>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// math, algorithm
#include <algorithm>
#include <cmath>
#include <complex>
#include <numeric>
// etc
#include <bitset>
#include <cassert>
#include <cctype>
#include <cstring>
#include <chrono>
#include <iomanip>
#include <random>
#include <utility>
// using-directive
using namespace std;
// alias template
using int64 = int64_t;
using vi = vector<int>;
using vl = vector<int64_t>;
using pii = pair<int, int>;
using pll = pair<int64_t, int64_t>;
// text macro replacement
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define print(x) cout << (x) << '\n'
#define debug(x) cerr << #x << ": " << (x) << '\n'
// variadic template
template<typename T> inline void chmin(T &a, T b) {if (a > b) a = b; return;}
template<typename T> inline void chmax(T &a, T b) {if (a < b) a = b; return;}
// constant
const int INF = (1<<30) - 1;
const int64_t INF64 = (1LL<<62) - 1;
const int MOD = 1000000007;

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

  int n; cin >> n;
  vector<int> a(n);
  rep(i, n) cin >> a[i];

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

  for (int i = 0; i < n - 1; ++i) {
    if (a[i] > a[i + 1]) {
      print("No"); return 0;
    }
  }

  print("Yes");

  return 0;
}


#include<iostream>
#define INF 1000000000
using namespace std;

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

    int a[n];

    for(i = 0; i < n; i++){
        a[i] = INF;
    }

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

    for(i = 0; i < n; i++){
        if(a[i - 1] < a[i] && a[i] >= a[i + 1]){
            a[i] -= 1;
        }
    }
    int flag = 0;

    for(i = 0; i < n; i++){
        if(a[i] >= a[i + 1]){
            flag = 1;
            break;
        }
    }

    if(flag == 0 || n == 1){
        cout << "Yes" << endl;
    }else{
        cout << "No" << endl;
    }
}


#include<iostream>

using namespace std;

int main(){
    long long N;
    cin >> N;
    bool isOK=true;
    long long H[N+2];
    H[0]=0;
    H[1]=0;
    for(long long i=0;i<N;i++){
        cin >> H[i+2];
    }
    for(long long i=1;i<N+1;i++){
        long long d = H[i+1]-H[i];
        if (d>=0)continue;
        if(d<-1){
            isOK=false;
            break;
        }
        if(d==-1){
            H[i]-=1;
            if(H[i]<H[i-1]){
                isOK=false;
                break;
            }
        }
    }
    if(isOK){
        cout << "Yes" << endl;
    }else{
        cout << "No" << endl;
    }

}


#include <iostream>
#include <vector>

using namespace std;

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

    vector<int> H(N);

    for (int i = 0; i < N; i++) {
        cin >> H.at(i);
    }

    int prev = 0;
    bool done = false;
    bool finish = false;
    for (int i = 0; i < N; i++) {
        int h = H.at(i);
        if (prev == 0) {
            prev = h;
            continue;
        } else if (prev > h) {
            if (done) {
                finish = true;
            } else {
                if (prev - 1 == h) {
                    done = true;
                } else {
                    finish = true;
                }
            }
        }

        if (finish) {
            cout << "NO" << endl;
            return 0;
        }

        prev = h;
    }

    cout << "YES" << endl;
}


#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    int n;
    vector<int> h;
    cin >> n;
    for (int i = 0; i < n; i++) {
        int input;
        cin >> input;
        h.push_back(input);
    }

    h[0] = h[0]-1;
    for (int i = 1; i < n-1; i++) {
        if (h[i-1] <= h[i] && h[i] <= h[i+1]) {
            continue;
        } else if (h[i-1] <= h[i]-1 && h[i]-1 <= h[i+1]) {
            h[i] = h[i]-1;
            continue;
        } else {
            cout << "No" << endl;
            exit(0);
        }
    }
    cout << "Yes" << endl;
}


#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
int main(){
	int n;
	cin>>n;
	bool down=false;
	bool p=true;
	int before=0;
	for(int i=0;i<n;i++){
		int j;cin>>j;
		if(j<before){
			if(before-j>=2){p=false;}
			if(down==true){p=false;}
			else{down=true;}
		}
		if(j>before){
			down=false;
		}
		before=j;
	}
	if(p==true){cout<<"Yes"<<endl;}
	else{cout<<"No"<<endl;}
}


#include <iostream>
using namespace std;

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

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

    int dec = 0;
    for(int i=0; i<n-1; i++){
        int delta = h[i] - h[i+1];
        if(delta > 0) dec++;
        if(delta > 1) dec++;
    }

    if(dec > 1) cout<<"No"<<endl;
    else cout<<"Yes"<<endl;
}


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <tuple>
#include <vector>

using namespace std;
typedef long long ll;

#define rep(i, n) for (ll i = 0; i < (n); i++)
#define reps(i, f, n) for (ll i = (f); i < (n); i++)
#define repr(i, n) for (ll i = n; i >= 0; i--)
#define repv(v) for (auto it = (v).begin(); it != (v).end(); it++)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define pb push_back
#define INIT    \
    cin.tie(0); \
    ios::sync_with_stdio(false);

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

ll const INF = 1LL << 60;
ll const MOD = 1000000007;

int main() {
    INIT;

    ll L, R;
    cin >> L >> R;

    if (L / 2019 != R / 2019) {
        cout << 0 << endl;
        return 0;
    }

    ll ans = INF;
    reps(i, L, R + 1) {
        // cout << i * i + 1 << "," << (i * i + 1) % 2019 << endl;
        chmin(ans, (i * i + 1) % 2019);
    }

    cout << ans << endl;

    return 0;
}

Score : 300 points

Problem Statement

You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

Constraints

All values in input are integers.

0 \leq L < R \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

L R

Output

Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019 = 2.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: (i, j) = (4, 5).


// ConsoleApplication1.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。
//

#include <iostream>
#include <cmath>
#include <climits>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include <map>
#include <numeric>
#include <set>
#include <queue>
#include <bitset>
using namespace std;

#define ll long long
#define ld long double
#define pi 3.14159265359;
// %llu %lf

// double result = 0;
// printf("%.12f\n", result);

// v:vector  type:型  order:greater(大きい順) or less(小さい順)
#define _sort(v,type,order) do { sort(v.begin(),v.end(),order<type>()); } while(0)
/*
	◆pairでもソートは可能

	vector<pair<int32_t, int32_t>> pr(n);
	sort(pr.begin(), pr.end(),_compare);

	bool _compare(pair<int32_t, int32_t> a, pair<int32_t, int32_t> b)
	{

	#if 0	// first での sort

	#if 0
		// 昇順
		if (a.first != b.first) {
			return a.first < b.first;
		}
		// secondが同じならfirstでソート
		return a.second < b.second;
	#else
		// 降順
		if (a.first != b.first) {
			return a.first > b.first;
		}
		// secondが同じならfirstでソート
		return a.second > b.second;
	#endif

	#else	// second での sort

	#if 1
		// 昇順
		if (a.second != b.second) {
			return a.second < b.second;
		}
		// secondが同じならfirstでソート
		return a.first < b.first;
	#else
		// 降順
		if (a.second != b.second) {
			return a.second > b.second;
		}
		// secondが同じならfirstでソート
		return a.first > b.first;
	#endif

	#endif

	}

*/

// vector 要素の総和算出
// v:vector  default_value:初期値
#define _sum(v,default_value) accumulate(v.begin(),v.end(),default_value )
// vector 最大値( return ite )
#define _max_element(v) max_element(v.begin(),v.end())
// vector 最小値( return ite )
#define _min_element(v) min_element(v.begin(),v.end())
// vector 最大値が格納されている要素値
#define _max_element_number(v) distance(v.begin(),max_element(v.begin(),v.end()))
// 特定コンテナの中から特定の値をカウントする
#define _count(v,value) count(v.begin(),v.end(),value)

//set<uint32_t> member;	// 重複するデータを保持する事はできない member.insert(2) member.insert(2) ⇒ member.count(2)は1
//                                                              member.emplace(2)とかも同じ member.size()で確認すると同じ値の挿入ではサイズ変化はない
//multiset<uint32_t> v;	// 重複するデータも保持する事はできる   member.insert(2) member.insert(2) ⇒ member.count(2)は2

// 丸め
#define _round(v) round(v)
// 2乗 / 3乗
#define _square(v) pow(v,2)
#define _cube(v)   pow(v,3)
// 大小判定
#define _max(x,y) max(x,y)
#define _min(x,y) min(x,y)
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; }

// string ⇒ int
#define _stringtoi(s) stoi(s)
// double 平方根
#define _sqrt(x) sqrt(x)
// double 引数 x 以上で最小の整数値 ex) 3.30303 ⇒ 4
#define _ceil(x) ceil(x)
// 指定された要素 【以上の】　　値が現れる最初の位置のイテレータを取得する
#define _lower_bound(v,min) lower_bound(v.begin(), v.end(), min)
// 指定された要素 【より大きい】値が現れる最初の位置のイテレータを取得する
#define _upper_bound(v,min) upper_bound(v.begin(), v.end(), min)

// 順列 n個の数が与えられる
// 0,1,2,...,n-1
// 全ての並べ方を1行ごとに出力する
// ex 0 1 2 / 0 2 1 / 1 0 2 / 1 2 0 / 2 0 1 / 2 1 0
#define _next_permutation(v) do {     \
	for (auto num : v) {              \
		printf("%d ", num);           \
	}                                 \
	printf("\n");                     \
	/* ※ 昇順である必要がある     */ \
	/* ※ pair も pair.firstで可能 */ \
} while (next_permutation(v.begin(), v.end()))

// ■bitset
// 100 桁の 2 進数を定義する。
// bitset<100> bs;
//
// 8桁 の 2進数を定義し、10進数 131で初期化
// bitset<8> bs(131);			// 7 ビット目から 0 ビット目への順番で、10000011 になる
//
// 8桁 の 2進数を定義し、2進数で初期化
// bitset<8> bs("10000011");	// 7 ビット目から 0 ビット目への順番で、10000011 となる。
// string _bs; cin >> _bs; bitset<100> bs(_bs); _bs = "10000011"であれば上記と同様
//
// 与えられる数値について、それぞれの和を算出する場合
// 下記コードでビットが立っている要素値＝和の値となる
// ex.) AGC 020 C https://atcoder.jp/contests/agc020/tasks/agc020_c
// bitset<1000> dp;
// p[0] = 1;
// for (int i = 0; i < N; ++i) {
//    dp |= (dp << A[i]);
// }

// 絶対値
template<typename T>
static T _abs(const T x) { return  (x > 0 ? x : -x); }

// 最大公約数
int64_t gcd(int64_t a, int64_t b) { while (b) { int64_t c = b; b = a % b; a = c; } return a; }
// 最小公倍数
int64_t lcm(int64_t a, int64_t b) { if (!a || !b) return 0; return a * b / gcd(a, b); }

// 多次元 std::vector 生成
template<class T>
vector<T> make_vec(size_t a) { return vector<T>(a); }
template<class T, class... Ts>
auto make_vec(size_t a, Ts... ts) { return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...)); }
// ex) auto dp = make_vec<uint64_t>(SIZE + 1, 2, 2);
//
// 2次元 vector の初期化
// vector< vector<int> >  s( n, vector<int>(m, 0) );

// pair
// vector<vector<pair<int32_t,int32_t>>> f(n);
// ⇒ 挿入 f[i].push_back(make_pair(x, y));

// Union Find Tree

class UnionFind
{
public:
	vector <int32_t> par; // 各元の親を表す配列
	vector <int32_t> siz; // 素集合のサイズを表す配列(1 で初期化)

	// Constructor 初期では親は自分自身
	UnionFind(int32_t sz_) : par(sz_), siz(sz_, 1LL) { for (int32_t i = 0; i < sz_; ++i) par[i] = i; }

	void init(int32_t sz_)
	{
		par.resize(sz_);
		siz.assign(sz_, 1LL);  // resize だとなぜか初期化されなかった
		for (int32_t i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身
	}

	// Find
	int32_t root(int32_t x)
	{
		// x の親の親を x の親とする
		while (par[x] != x) {
			x = par[x] = par[par[x]];
			//			printf("%d\n", x);
		}
		return x;
	}

	// Union(Unite, Merge)
	bool merge(int32_t x, int32_t y)
	{
		x = root(x);
		y = root(y);
		if (x == y) return false;
		// merge technique（データ構造をマージするテク．小を大にくっつける）
		if (siz[x] < siz[y]) swap(x, y);
		siz[x] += siz[y];
		par[y] = x;
		return true;
	}

	// 連結判定
	bool is_same(int32_t x, int32_t y) { return root(x) == root(y); }

	// 素集合のサイズ
	int32_t size(int32_t x) { return siz[root(x)]; }

	// 参照
	void view(void) {
		for (size_t i = 0; i < par.size(); i++) {
			printf("%d\n", par[i]);
		}
	}

};

// ■
// UINT32_MAX
// 4294967295 ≒ 4 * 1e9

// ■
// 割り算した結果との比較での丸め対処時
// ABC 161 B
// https://atcoder.jp/contests/abc161/tasks/abc161_b
// double   border = _sum(v, 0 / (double)(4 * m);
//            ↓
// uint32_t border = (_sum(v, 0) + (4 * m) - 1) / (4 * m);

/*************************************************************/
// ABC 133
// C - Megalomania
// https://atcoder.jp/contests/abc133/tasks/abc133_c
/*
	■問題文
	非負整数 L,R が与えられます。
	2 つの整数 i,j を L ≤ i < j ≤ R を満たすように選びます。
	(i×j) mod 2019 の最小値を求めてください。

	■制約
	・入力は全て整数
	・0 ≤ L < R ≤ 2×1e9

	■入力
	L R

	■出力
	条件を満たすように i,j を選んだ時の、(i×j) mod 2019 の最小値を出力せよ。

	■入力例
	2020 2040

	■出力例
	2

	(i,j)=(2020,2021) とすると、(i×j) mod 2019=2 となります。
*/

const int32_t mod = 2019;
int main()
{
	int64_t l, r;
	cin >> l >> r;

	int64_t result = INT64_MAX;
	for (int64_t i = l; i < r; i++) {
		for (int64_t j = l + 1; j <= r; j++) {
			result = _min(result, (i * j) % mod);
			if (result) { continue; }
			cout << result << endl;
			return 0;
		}
	}

	cout << result << endl;
	return 0;
}

// プログラムの実行: Ctrl + F5 または [デバッグ] > [デバッグなしで開始] メニュー
// プログラムのデバッグ: F5 または [デバッグ] > [デバッグの開始] メニュー

// 作業を開始するためのヒント:
//    1. ソリューション エクスプローラー ウィンドウを使用してファイルを追加/管理します
//   2. チーム エクスプローラー ウィンドウを使用してソース管理に接続します
//   3. 出力ウィンドウを使用して、ビルド出力とその他のメッセージを表示します
//   4. エラー一覧ウィンドウを使用してエラーを表示します
//   5. [プロジェクト] > [新しい項目の追加] と移動して新しいコード ファイルを作成するか、[プロジェクト] > [既存の項目の追加] と移動して既存のコード ファイルをプロジェクトに追加します
//   6. 後ほどこのプロジェクトを再び開く場合、[ファイル] > [開く] > [プロジェクト] と移動して .sln ファイルを選択します


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

int main() {
  ll l, r;
  cin >> l >> r;

  set<int> mods;
  for (ll i = l; i <= r; i++) {
    mods.insert(i % 2019);
  }

  vector<int> m;
  for (auto itr = mods.begin(); itr != mods.end(); itr++) {
    m.push_back(*itr);
  }

  int ans = 2020;
  for (int i = 0; i < m.size(); i++) {
    for (int j = i + 1; j < m.size(); j++) {
      ans = min(ans, (m[i] * m[j]) % 2019);
    }
  }

  cout << ans << endl;
}


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

int main() {
  ll L, R;
  cin >> L >> R;
  cout << L * (L+1) % 2019 << endl;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <cctype>
#include<math.h>
using namespace std;

#define int long long
//#define endl "\n"
#define fi first
#define se second
#define fr front
#define m_p make_pair
#define mod 1000000007
#define all(v)  v.begin(),v.end()
#define rep(i,n)  for(int i=0; i<(int) (n); i++)
#define all(v)  v.begin(),v.end()
#define vecin(v) for(int i=0; i<(int)v.size(); i++)cin>>v[i];
using namespace std;

int jousu(int, int);
int jousu(int x00, int y00) {
	int z00 = 1;
	for (int i = 0; i < y00; i++) {
		z00 *= x00;
	}
	return z00;
}
int keta(int x00) {
	int z00 = x00;
	int w00 = 0;
	while (z00 != 0) {
		z00 /= 10;
		w00++;
	}
	return w00;
}
int modinv(int a, int m) {
	int b = m, u = 1, v = 0;
	while (b) {
		int t = a / b;
		a -= t * b; swap(a, b);
		u -= t * v; swap(u, v);
	}
	u %= m;
	if (u < 0) u += m;
	return u;
}

signed main() {
	int l, r, ans=2018;
	cin >> l >> r;
	l %= 2019;
	r %= 2019;
	for (int i = l; i <= r; i++) {
		for (int j = i+1; j <= r; j++) {
			ans = min(ans, (i * j) % 2019);
		}
	}
	cout << ans << endl;
}


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

long long L, R;

int main() {
    cin >> L >> R;

    R = min(R, L + 2019);

    long long ans = 1e18;
    for (long long i = L; i <= R; i++) {
        for (long long j = L + 1; j <= R; j++) {
            long long a1 = i;
            long long a2 = j;
            ans = min((a1 * a2) % 2019, ans);
        }
    }

    cout << ans << endl;
}


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

int main(){
	ll l,r;
	cin >> l >> r;
	int ans=2020;
	if(r-l >= 2018){
		ans=0;
	}else{
		for(int i=l; i<=r-1; i++){
			for(int j=i+1; j<=r; j++){
				ans = min(ans, (i*j)%2019);
			}
		}
	}
	cout << ans << endl;

	return 0;
}


#include<iostream>
using namespace std;
#include<string>
#include<utility>
#include<algorithm>
#include<vector>
#include<math.h>
#include<bits/stdc++.h>
#include<stdio.h>

int main(){
    long long int L,R;
    cin >> L >> R;
    long long int num=(L*(L+1))%2019;
    long long int tmp=0;
       for(int i=L;i<R;++i){
           for(int j=i+1;j<=R;++j){
               tmp=i*j;
               tmp=tmp%2019;
               if(tmp==0){
                   num=0;
                   break;
                   break;
               }
               else{
                   if(tmp<num){
                       num=tmp;
                   }
               }
           }
       }
       cout << num;
}


#pragma GCC optimize ("O3")
#pragma GCC optimize ("unroll-loops")

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

#define pb push_back
#define F first
#define S second
#define f(i,a,b)  for(int i = a; i < b; i++)
// #define endl '\n'

using ll = long long;
using db = long double;
using ii = pair<int, int>;

const int N = 1e5+5, LG = 17, MOD = 998244353;
const int SQ = 450;
const long double EPS = 1e-7;

int32_t main(){
#ifdef ONLINE_JUDGE
    ios_base::sync_with_stdio(0);
    cin.tie(0);
#endif
  int l, r;
  cin >> l >> r;

  if(r-l+1>=5000){
    cout<<0<<'\n';
    return 0;
  }
  ll ans = 2019;
  f(i,l,r+1)
    f(j,i+1,r+1)
      ans=min(ans,1ll*i*j%2019);

  cout<<ans<<'\n';

  return 0;
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repm(i, m, n) for (int i = (m); i < (int)(n); i++)
#define repr(i, n) for (int i = (n); i > 0; i--)
#define all(vec) vec.begin(), vec.end()
using namespace std;

int main(){
  int a, b;
  cin >> a >> b;

  int ans = 0;
  //string ans = "Yes";
  //string ans = "No";
  //string ans = "YES";
  //string ans = "NO";
  if (b - a + 1 < 2019){
    repm(i, a, b){
      repm(j, i + 1, b + 1) ans = min(ans, i * j);
    }
  }

  cout << ans << endl;
}


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

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

using namespace std;
typedef long long ll;
const int mod = 1000000007;

int main() {
    ll l, r;
    cin >> l >> r;
    if ((r - l) >= 2018) {
        cout << 0 << endl;
        return 0;
    }
    int ml, mr;
    mr = r % 2019;
    ml = l % 2019;

    int ans = 0;
    if (ml < mr) ans = ml * (ml + 1);
    else ans = 0;
    cout << ans << endl;
    return 0;
}


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

int main() {
  int L,R;
  cin>>L>>R;
  vector<int>amari(R-L+1);
  int init = L%2019;
  int ret;
  if((R-L+1)>=2019||L==0){
    ret=0;
  }else{
    for(int i=0;i<(R-L+1);i++){
    amari.at(i)=(L+i)%2019;
  }
    sort(amari.begin(),amari.end());
    ret=  amari.at(0)*amari.at(1);
  }
  cout<<ret<<endl;
}


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

typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef pair<int,ii> iii;
typedef pair<int, iii> iiii;
typedef pair<double, ii> dii;
typedef long long ll;
typedef pair<ll, ii> lii;
const int INF = 1000000000;
const double EPS = 1e-9;
#define LSOne(S) (S & (-S))
int mods(int a, int b) { return (b + (a%b)) % b; }

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

    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);

    int L, R, n, ans = INF;
    bitset<2025> visited;

    cin >> L >> R;

    int mx = -INF;
    for (int i = L; i <= R; i++) {
        n = i % 2019;
        if (visited[n]) break;
        else visited[n] = 1;
        mx = max(mx, n);
    }

    for (int i = 0; i <= mx; i++) {
        if (!visited[i]) continue;
        for (int j = i+1; j <= mx; j++) {
            if (!visited[j]) continue;
            ans = min(ans, (i*j) % 2019);
        }
    }

    cout << ans << '\n';

    return 0;
}


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

int main(void){
  int l;
  vector <int> a;
    while(cin>>l){
        a.push_back(l);
    }
  int L = a[0];
  int R = a[1];
  int tmp=2019;

  if (R-L >= 2019){
  tmp =0;
  }
  else if(L==0){
    tmp = 1;
    for (int i = L+1;i < R;++i){
      for (int ii = L+2;ii <= R;++ii){
        int diff =(i*ii)%2019;
        if (tmp > diff && diff>0){
          tmp = diff;
        }
      }
    }
  }
  else{
    for (int i = L;i < R;++i){
      for (int ii = L+1;ii <= R;++ii){
        int diff =(i*ii)%2019;
        if (tmp > diff && diff >0){
          tmp = diff;
        }
      }
    }
  }
  cout << tmp;
}


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

using namespace std;
const int VALUE = 2019;

int Find(const long L, const long R)
{
	int ans = VALUE;
	for (long i = L; i <= R; ++i)
	{
		for (long j = i + 1; j <= R; ++j)
		{
			ans = min(ans, static_cast<int>((i*j) % VALUE));
			if (ans == 0)
			{
				return ans;
			}
		}
	}
	return ans;
}

int main()
{
	long L, R;
	cin >> L >> R;

	cout << Find(L, R) << endl;
}


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

int main(){
  ll l, r;
  cin >> l >> r;
  int ans = 1e9;
  ll a = min(r, l+2019);
  for(ll i = l; i <= r; i++){
    for(ll j = i+1; j <= r; j++){
      int a = (i*j) % 2019;
      if(a < ans) ans = a;
    }
  }
  cout << ans << endl;
  return 0;
}


#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
#include <math.h>
#include <iomanip>
#include <limits>
#include <list>
#include <queue>
#include <tuple>
#include <map>
using namespace std;
#define MOD (long long int)(1e9+7)
#define ll long long int
#define rep(i,n) for(int i=0; i<(int)(n); i++)
#define reps(i,n) for(int i=1; i<=(int)(n); i++)
#define REP(i,n) for(int i=n-1; i>=0; i--)
#define REPS(i,n) for(int i=n; i>0; i--)
#define INF (int)(1123456789)
#define LINF (long long int)(112345678901234567)
#define chmax(a, b) a = (((a)<(b)) ? (b) : (a))
#define chmin(a, b) a = (((a)>(b)) ? (b) : (a))
#define all(v) v.begin(), v.end()

int main(void){
    ll L, R, ans;
    cin >> L >> R;

    ans = 2019;

    if(R-L>=2018){
        ans = 0;
    }else{
        ll L1 = L%2019;
        ll R1 = R%2019;
        for(ll i = L1; i<L1+R-L; i++){
            for(ll j = 1; j<R-L+1; j++){
                if(ans > (i*(i+j))%2019){
                    ans = (i*(i+j))%2019;
                }
            }
        }

    }

    cout << ans << endl;

    return 0;
}


#include<iostream>
#include<string>
#include<cmath>
#include<algorithm>/*toupperとかが入っている*/
#include<vector>/*可変長配列vectorのインクルード*/

const int MOD=1000000007;/* 1,000,000,007 で割った余りを出力する　のとき使う*/
using namespace std;/*標準名前空間を利用する。cinやcoutはこれによって利用可能になる*/

long long int L,R;

int main(void) {
  cin >> L >> R;

  int max = 2020;

  while(L+2019 < R){
    L=L+2019;
  }

  for(long long int i=L; i<R; i++){
    for(long long int j=i+1; j<=R; j++){

      long long int x = i%2019;
      long long int y = j%2019;
      long long int z = x*y%2019;

      if(z<max) max=z;

    }
  }
  if(max==2020)max=0;

  cout << max << endl;
  return 0;
}


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

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

const int INF = 1e9;
const int MOD =1e9+7;
const ll LINF = 1e18;

int main(){
    int L, R;
    cin >> L >> R;

    int i=0, j= R - L;
    int min = INF;
    while (i < j)
    {
        ll tmp = ((L + i) * (L + j)) % 2019;
        if(tmp < min) {
            min = tmp;
        }else{
            j--;
        }
    }
    cout << min << endl;
}


#include <bits/stdc++.h>
using namespace std;;
#define ll long long
#define rep(i, n) for(int i = 0;i < n;i++)
#define repr(i, n) for(int i = n;i >= 0;i--)
#define FOR(i, m, n) for(int i = m;i < n;i++)
#define FORR(i, m, n) for(int i = m;i >= n;i--)
#define INF 1<<30
#define LINF 1LL<<62
#define all(x) (x).begin(), (x).end()
#define mp make_pair
#define pb push_back
const int MOD = 1000000007;

typedef pair<ll, ll> P;
typedef pair<ll, P> PP;

int main(){
  ios::sync_with_stdio(false);
  cin.tie(0);
  int l,r; cin >>  l >> r;
  int ans = 2018;
  FOR(i,l,l+2022){
      FOR(j,i+1,i+2022){
          if(l<=i && i <= r && l <= j && j <= r){
              ans = min(ans , (i*j)%2019);
          }
      }
  }
  cout << ans << endl;
}


#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<math.h>
#include<utility>

#define lli long long
#define all(i) i.begin(),i.end()
#define rall(i) i.rbegin(),i.rend()
#define rep0(i,j) for(int i=0;i<j;i++)
#define rep1(i,j) for(int i=1;i<=j;i++)
#define rep0d(i,j) for(int i=j-1;i>=0;i--)
#define MAX 1000000007
int a[2001][2001];
using namespace std;

int main() {
	lli l,r,min=MAX;
	cin >> l >> r;

	if(l%2019>r%2019||l+2019<=r)cout << 0;
	else{
	for(int i=l%2019; i<r%2019;i++){
		for(int j=i+1;j<=r%2019;j++){
			if((i*j)%2019<min)min=(i*j)%2019;
		}

	}
	cout << min;

	}
}


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

int main(){
	long long l,r;
	scanf("%lld %lld",&l,&r);
	if(l%mod==0 || r%mod==0 || r-l>=mod || l/mod<r/mod) puts("0");
	else if(l==r-1) printf("%lld\n",(l*r)%mod);
	else{
		printf("%lld\n",l%mod*(l+1)%mod);
	}
	return 0;
}


#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<cmath>
#include<stack>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<bitset>
using namespace std;
typedef long long ll;
typedef vector<int> VI;
#define FOR(i,a,n) for(ll (i)=(a);(i)<(n);(i)++)
#define eFOR(i,a,n) for(ll (i)=(a);(i)<=(n);(i)++)
#define SORT(i) sort((i).begin(),(i).end())
#define rSORT(i,a) sort((i).begin(),(i).end(),(a))
constexpr auto INF = 1000000000;
constexpr auto LLINF = 1LL << 62;
constexpr auto mod = 1000000007;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; }return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; }return 0; }

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

    ll l, r;
    cin >> l >> r;

    chmin(r, l + 2019);
    ll ans = INF;
    eFOR(i, l, r)eFOR(j, i + 1, r) {
        chmin(ans, i * j % 2019);
    }
    cout << ans << "\n";
}


#include <bits/stdc++.h>
#include <cassert>
#define rep(i, n) for (int i = 0; i < (n); i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;
struct Edge
{
  int to;
  int weight;
  Edge(int t, int w) : to(t), weight(w) {}
};
using Graph = vector<vector<Edge>>;
// using Graph = vector<vector<int>>;

const long long INF = 1LL << 60;
const int INT_INF = 1000000000;

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

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  string s;
  cin >> s;
  ll cnt = 0;
  if (s.size() <= 2)
  {
    cout << 0 << endl;
    return 0;
  }
  for (int i = 0; i < s.size() - 2; i++)
  {
    if (s[i] == 'A' && s[i + 1] == 'B' && s[i + 2] == 'C')
    {
      cnt++;
      s[i] = 'B', s[i + 1] = 'C', s[i + 2] = 'A';
      i += 2;
    }
  }
  cerr << cnt << endl;
  bool ABC = false;
  int ABCs = 0;
  for (int i = 0; i < s.size() - 1; i++)
  {
    if (s[i] == 'A' && s[i + 1] == 'B' && s[i + 2] == 'C')
    {
      s[i] = 'B', s[i + 1] = 'C', s[i + 2] = 'A';
      i += 2;
      ABC = true;
      ABCs++;
    }
    else
    {
      cnt += ABCs * (1 + ABCs) / 2;
      ABCs = 0;
      ABC = false;
    }
  }
  cout << cnt << endl;
  return 0;
}

Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define double long double
#define fo(a,b) for(int a=0;a<b;a++)
#define Sort(a) sort(a.begin(),a.end())
#define rev(a) reverse(a.begin(),a.end())
#define fi first
#define se second
#define sz size()
#define bgn begin()
#define en end()
#define pb push_back
#define pp() pop_back()
#define V vector
#define P pair
#define yuko(a) setprecision(a)
#define uni(a) a.erase(unique(a.begin(),a.end()),a.end())
#define Q queue
#define pri priority_queue
#define Pri priority_queue<int,vector<int>,greater<int>>
#define PriP priority_queue<P<int,int>,vector<P<int,int>>,greater<P<int,int>>>
#define ff first.first
#define fs first.second
#define sf second.first
#define ss second.second
#define all(a)  (a).begin(),(a).end()

int low(V<int> &a,int b){
  auto c=lower_bound(a.begin(),a.end(),b);
  int d=c-a.bgn;
  return d;
}
int upp(V<int> &a,int b){
  auto c=upper_bound(a.begin(),a.end(),b);
  int d=c-a.bgn;
  return d;
}
template<class T>
 void cou(vector<vector<T>> a){
  int b=a.size();
  int c=a[0].size();
  fo(i,b){
    fo(j,c){
      cout<<a[i][j];
      if(j==c-1)
        cout<<endl;
      else
        cout<<' ';
    }
  }
}
int wari(int a,int b) {
  if(a%b==0)
    return a/b;
  else
    return a/b+1;
}
int keta(int a){
  double b=a;
  b=log10(b);
  int c=b;
  return c+1;
}
int souwa(int a){
  return a*(a+1)/2;
}
int gcm(int a,int b){
  if(a%b==0)
    return b;
  return gcm(b,a%b);
}
bool prime(int a){
  if(a<2)
    return false;
  else if(a==2)
    return true;
  else if(a%2==0)
    return false;
  for(int i=3;i<=sqrt(a)+1;i+=2){
    if (a%i==0)
      return false;
  }
  return true;
}
struct Union{
  vector<int> par;
  Union(int a){
  par=vector<int>(a,-1);
  }
  int find(int a){
    if(par[a]<0)
      return a;
    else
      return par[a]=find(par[a]);
  }
  bool same(int a,int b){
    return find(a)==find(b);
  }
  int Size(int a){
    return -par[find(a)];
  }
  void unite(int a,int b){
    a=find(a);
    b=find(b);
    if(a==b)
      return;
    if(Size(b)>Size(a))
      swap<int>(a,b);
    par[a]+=par[b];
    par[b]=a;
  }
};
int ketas(int a){
  string b=to_string(a);
  int c=0;
  fo(i,keta(a)){
    c+=b[i]-'0';
  }
  return c;
}
bool fe(int a,int b){
  a%=10;
  b%=10;
  if(a==0)
    a=10;
  if(b==0)
    b=10;
  if(a>b)
    return true;
  else
    return false;
}
int INF=1000000007;
struct edge{int s,t,d; };
V<int> mojisyu(string a){
  V<int> b(26,0);
  fo(i,a.sz){
    b[a[i]-'a']++;
  }
  return b;
}
int wa2(int a){
  if(a%2==1)
    return a/2;
  return a/2-1;
}
/*signed main(){
  int a,b,c;
  cin>>a>>b>>c;
  V<V<edge>> d(a);
  fo(i,b){
    edge e;
    cin>>e.s>>e.t>>e.d;
    d[e.s].pb(e);
  }
  V<int> e(a,INF);
  e[c]=0;
  priority_queue<P<int,int>,V<P<int,int>>,greater<P<int,int>>> f;
  f.push({0,c});
  int h=INF;
  while(!f.empty()){
    P<int,int> g;
    g=f.top();
    f.pop();
    int v = g.second, i = g.first;
    for(edge l : d[v]){
      if(e[l.t] > i + l.d){
        e[l.t] = i + l.d;
        f.push({i+l.d , l.t});
      }
    }
  }
  fo(i,a){
    if(e[i]==INF)
      cout<<"INF"<<endl;
    else
      cout<<e[i]<<endl;
  }
}
?*/
int nCr(int n,int r){
  int a=1;
  r=min(r,n-r);
  for(int i=n;i>n-r;i--){
    a*=i;
    a/=n-i+1;
  }
  return a;
}
/*void sea(int x,int y){
  if(x<0||a<=x||y<0||b<=y||c[x][y]=='#')
    return;
  if(d[x][y])
    return;
  d[x][y]++;
  sea(x+1,y);
  sea(x-1,y);
  sea(x,y+1);
  sea(x,y-1);
}*/
int kaijou(int a){
  int b=1;
  fo(i,a)
    b*=i+1;
  return b;
}
int nPr(int a,int b){
  if(a<b)
    return 0;
  if(b==0)
    return 1;
  int c=1;
  for(int i=a;i>a-b;i--){
    c*=i;
    c%=INF;
  }
  return c;
}
long long modpow(long long a, long long n, long long mod) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

// a^{-1} mod を計算する
long long modinv(long long a, long long mod) {
    return modpow(a, mod - 2, mod);
}

int lcm(int a,int b){
  int c=modinv(gcm(a,b),INF);
  return ((a*c)%INF)*(b%INF)%INF;
}
int MOD=INF;
int fac[1000010], finv[1000010], inv[1000010];
// テーブルを作る前処理
//先にCOMinit()で前処理をする
//ABC145D
void COMinit() {
  fac[0]=fac[1]=1;
  finv[0]=finv[1]=1;
  inv[1]=1;
  for(int i=2;i<1000010;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;
  }
}
// 二項係数計算
int 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;
}
bool naka(int a,int b,V<V<char>> c){
  return (a>=0&&b>=0&&a<c.sz&&b<c[0].sz);
}

V<P<int,int>> mawari8={{0,-1},{0,1},{1,0},{-1,0},{-1,-1},{1,1},{1,-1},{-1,-1}};
int inf=1000000000000000007;
/*
signed main(){
  int a,b,c;
  cin>>a>>b>>c;
  V<V<edge>> d(a);
  fo(i,b){
    edge e;
    cin>>e.s>>e.t>>e.d;
    d[e.s].pb(e);
  }
  V<int> e(a,INF);
  e[c]=0;
  priority_queue<P<int,int>,V<P<int,int>>,greater<P<int,int>>> f;
  f.push({0,c});
  int h=INF;
  while(!f.empty()){
    P<int,int> g;
    g=f.top();
    f.pop();
    int v = g.second, i = g.first;
    for(edge l : d[v]){
      if(e[l.t] > i + l.d){
        e[l.t] = i + l.d;
        f.push({i+l.d , l.t});
      }
    }
  }
  fo(i,a){
    if(e[i]==INF)
      cout<<"INF"<<endl;
    else
      cout<<e[i]<<endl;
  }
}*/
V<P<int,int>> mawari4={{0,-1},{0,1},{1,0},{-1,0}};
//最短経路の表 a(全部INFで初期化)
//縦横 x,y
//迷路 f
//スタートsx,sy
//ゴールgx,gy
//文字はgから使おうね
/*int bfs_haba(){
  Q<P<int,int>> b;
  a[sx][sy]=0;
  b.push({sx,sy});
  while(!b.empty()){
    P<int,int> c=b.front();
    b.pop();
    if(c.fi==gx&&c.se==gy){
      break;
    }
    fo(i,4){
      int d=c.fi+mawari4[i].fi;
      int e=c.se+mawari4[i].se;
      if(0<=d&&0<=e&&d<x&&e<y&&f[d][e]!='#'&&a[d][e]==INF){
        b.push({d,e});
        a[d][e]=1+a[c.fi][c.se];
      }
    }
  }
  return a[gx][gy];
}*/
V<int> onajibubun(string a){
  V<int> b(a.sz);
  for(int i=1,j=0;i<a.sz;i++){
    if(i+b[i-j]<j+b[j])
      b[i]=b[i-j];
    else{
      int c=max<int>(0,j+b[j]-i);
      while(i+c<a.sz&&a[c]==a[i+c])
        c++;
      b[i]=c;
      j=i;
    }
  }
  b[0]=a.sz;
  return b;
}
//各頂点ごとにどこに辺が出てるかの表がc
//各頂点ごとの色を表すV<int>(頂点数max)のcolorを用意する
//aはどこ塗るか、bは何で塗るかなので、(0,1,c)でよぶとおけ
V<int> color(205);
bool nibu_hantei(int a,int b,V<V<int>> c){
  color[a]=b;
  fo(i,c[a].sz){
    if(b==color[c[a][i]])
      return false;
    if(color[c[a][i]]==0&&!nibu_hantei(c[a][i],-b,c))
      return false;
  }
  return true;
}
//aは頂点数
//nibu_hanteiの上にcolorを用意する
//各頂点ごとにどこに辺が出てるかの表がc
bool renketujanai_nibu_hantei(int a,V<V<int>> c){
  fo(i,a){
    if(color[i]==0){
      if(!nibu_hantei(i,1,c))
        return false;
    }
  }
  return true;
}
struct segmin{
  vector<int> seg;
  int b;
  segmin(V<int> a){
    b=1;
    while(b<a.sz)
      b*=2;
    seg=vector<int>(2*b-1,inf);
    fo(i,a.sz){
      seg[i+b-1]=a[i];
    }
    for(int i=b-2;i>=0;i--){
      seg[i]=min(seg[2*i+1],seg[2*i+2]);
    }
  }
  void update(int i,int a){
    i+=b-1;
    seg[i]=a;
    while(i){
      i=(i-1)/2;
      seg[i]=min(seg[2*i+1],seg[2*i+2]);
    }
  }
  //最初呼び出すときは要求区間x,y+1(yは添え字+1)とa=0,l=0,r=INFで
  //l,rは探すところ
  int getmin(int x,int y,int a,int l,int r){
    if(r==INF)
      r=b;
    if(r<=x||y<=l)
      return INF;
    if(x<=l&&r<=y)
      return seg[a];
    int a1=getmin(x,y,2*a+1,l,(l+r)/2);
    int a2=getmin(x,y,2*a+2,(l+r)/2,r);
    return min(a1,a2);
  }
};
struct segadd{
  vector<int> seg;
  int b;
  segadd(V<int> a){
    b=1;
    while(b<a.sz)
      b*=2;
    seg=vector<int>(2*b-1,0);
    fo(i,a.sz){
      seg[i+b-1]=a[i];
    }
    for(int i=b-2;i>=0;i--){
      seg[i]=seg[2*i+1]+seg[2*i+2];
    }
  }
  void update(int i,int a){
    i+=b-1;
    seg[i]=a;
    while(i){
      i=(i-1)/2;
      seg[i]=seg[2*i+1]+seg[2*i+2];
    }
  }
  //最初呼び出すときは要求区間x,y+1(yは添え字+1)とa=0,l=0,r=INFで
  //l,rは探すところ
  int getadd(int x,int y,int a,int l,int r){
    if(r==INF)
      r=b;
    if(r<=x||y<=l)
      return 0;
    if(x<=l&&r<=y)
      return seg[a];
    int a1=getadd(x,y,2*a+1,l,(l+r)/2);
    int a2=getadd(x,y,2*a+2,(l+r)/2,r);
    return a1+a2;
  }
};
V<P<int,int>> factorize(int n){
  V<P<int,int>> res;
  for(int i=2; i*i<=n; i++){
    if(n%i)
      continue;
    res.emplace_back(i,0);
    while(n%i==0){
      n/=i;
      res.back().second++;
    }
  }
  if(n!=1)
    res.emplace_back(n,1);
  return res;
}
int pow_kai(int a, int b){
  int c=1;
  while(b>0){//bit全部捨てるまで
    if(b%2){//一番右のbitが1
      c=c*a;
    }
    a=a*a;
    b>>=1;//全体右に1つシフト
  }
  return c;
}

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

signed main(){
  string s;
  cin>>s;
  V<char> a;
  int n=s.size();
  fo(i,n){
    if(i<n-1&&s.substr(i,2)=="BC"){
      a.pb('D');
      i++;
    }
    else
      a.pb(s[i]);
  }
  int cnt=0;
  int ans=0;
  fo(i,a.size()){
    if(a[i]=='A')
      cnt++;
    else if(a[i]=='D')
      ans+=cnt;
    else
      cnt=0;
  }

  cout<<ans<<endl;
}


#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<sstream>
#include<string>
#include<numeric>
using namespace std;
typedef long long ll;
ll mod = 1e9+7;
//ll mod = 998244353;
#define rep(i,n) for(int i = 0; i < (n); ++i)

int main(){
    string s;
    cin >> s;
    int cnt = 0;
    if ( s.length() < 3 ) {
        cout << 0 << endl;
        return 0;
    }
    vector<int> cont_a_cnt(s.length()+2, 0);
    vector<int> cont_bc_cnt(s.length()+2, 0);
    rep(i, s.length()) {
        if ( s[i] == 'A' ) {
            cont_a_cnt[i+1] = cont_a_cnt[i]+1;
        }
        if ( i < 2 ) continue;
        if ( s[i-1] == 'B' && s[i] == 'C' ) {
            cont_bc_cnt[i+1] = cont_bc_cnt[i] = cont_bc_cnt[i-1] + 1;
        }
    }
    int a_num = 0;
    int b_num = 0;
    bool a_flg = 0;
    bool b_flg = 0;
    int ans = 0;
    for ( int i = 1; i <= s.length()+1; ++i ) {
//        cout << i << " " << a_num << " " << b_num << endl;
        if ( cont_a_cnt[i] != 0 ) {
            a_flg = 1;
        }
        else if ( a_flg ) {
            a_num += cont_a_cnt[i-1];
            a_flg = 0;
            b_flg = 1;
        }
        if ( !b_flg ) {
            continue;
        }
        if ( cont_bc_cnt[i] == 0 ) {
            b_num = cont_bc_cnt[i-1];
//            cout << b_num << endl;
            ans += a_num * b_num;
            b_flg = 0;
            if ( cont_a_cnt[i] == 0 ) {
                a_num = 0;
            }
            b_num = 0;
        }
    }
    cout << ans << endl;
    return 0;
}


#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<utility>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
using namespace std;
#define INF 1000000007
#define LINF 100000000000000007
#define MOD 1000000007
#define int long long
#define rep(i,n) for(int i=0;i<n;i++)
#define repb(i, n) for (int i = n - 1; i >= 0; i--)
#define MODE 1
#ifdef MODE
#define DEB(X) cout<< #X <<": "<<X<<" ";
#define ARDEB(i,X) cout<< #X <<"["<<i<<"]: "<<X[i]<<" ";
#define END cout<<endl;
#else
#define DEB(X) {}
#define ARDEB(i,X) {}
#define END {}
#endif
typedef long long ll;
typedef pair<int,int> P;
struct edge{int to,cost;};
using namespace std;

int n,ans;
string s,t;
signed main(){
    cin>>s;
    n=s.size();
    rep(i,n){
    	if(s[i]=='B'&&s[i+1]=='C'){
    		t+="X";
    		i++;
    	}
    	else t+=s[i];
    }
    int cnt=0,cntX=0;
    rep(i,n){
    	if(t[i]=='A'||t[i]=='X'){
    		cnt++;
    		if(t[i]=='X'){
    			cntX++;
    			ans+=cnt-cntX;
    		}
    	}
    	else {
    		cnt=0;cntX=0;
    	}
    }
    cout<<ans<<endl;
}


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

int main()
{   int ans = 0;
    string s;
    cin >> s;
    vector <int> v;
    for(int i = 0; i < s.size(); i++){
        if(s[i] == 'B' && s[i+1] == 'C' && i + 1 < s.size()){
            v.push_back('D');
            i++;
            continue;
        }
        v.push_back(s[i]);
    }
    int m = 5000;
    while(m--){
        int cnt = 0;
        for(int i  =0; i < max((int)v.size() - 1 , 0); i++){
            if(v[i] == 'A' && v[i+1] == 'D'){
                v[i] = 'D'; v[i+1] = 'A';
                ans++;
            }
        }
        for(int i  =0; i < max((int)v.size() - 1 , 0); i++){
            if(v[i] == 'A' && v[i+1] == 'D'){
                cnt++;
                break;
            }
        }
        if(cnt==0){
            break;
        }
    }
    cout << ans << '\n';
}


#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <typeinfo>
#include <numeric>
#include <functional>
#include <unordered_map>
#include <bitset>
#include <stack>
#include <assert.h>
#include <unordered_set>
#include <random>

using namespace std;
using ll = long long;
using ull = unsigned long long;

const ll INF = 1e16;
const ll MOD = 1e9 + 7;

#define REP(i, n) for(ll i = 0; i < n; i++)

int main(){
    string s;
    cin >> s;
    ll ans = 0, abc = 0, a = 0, p = 0;
    bool f = true;
    for(ll i = 0; i < s.size(); i++){
        if(f){
            if(s[i] == 'A'){
                a++;
            }
            else if(s[i] == 'B'){
                if(a > 0){
                    f = false;
                    a--;
                    p = 2;
                }
            }
            else{
                a = 0;
            }
        }
        else{
            if(p == 2){
                if(s[i] == 'C'){
                    abc++;
                    p = 0;
                }
                else{
                    if(abc > 0){
                        ans += abc * (abc + 1) / 2;
                        ans += a * abc;
                    }
                    a = 0;
                    if(s[i] == 'A') a = 1;
                    abc = 0;
                    f = true;
                }
            }
            else if(p == 1){
                if(s[i] == 'B'){
                    p = 2;
                }
                else{
                    if(abc > 0){
                        ans += abc * (abc + 1) / 2;
                        ans += a * abc;
                    }
                    if(s[i] == 'A'){
                        a = a + abc + 2;
                    }
                    else{
                        a = 0;
                    }
                    abc = 0;
                    f = true;
                }
            }
            else{
                if(s[i] == 'A'){
                    p = 1;
                }
                else{
                    if(abc > 0){
                        ans += abc * (abc + 1) / 2;
                        ans += a * abc;
                    }
                    if(s[i] == 'B'){
                        p = 2;
                        a = abc - 1 + a;
                    }
                    else{
                        f = true;
                        a = 0;
                    }
                    abc = 0;
                }
            }
        }
        // cerr << i << " " << a << " " << abc << " " << ans << endl;
    }
    if(abc > 0){
        ans += abc * (abc + 1) / 2;
        ans += a * abc;
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>

#ifdef DEBUG
#define PRINT(x)\
    cout<<"func "<<__func__<<": line "<<__LINE__<<": "<<#x<<" = "<<(x)<<endl;
#define PRINTA(a,first,last)\
    cout<<"func "<<__func__<<": line "<<__LINE__<<": "<<#a<<"["<<(first)<<", "<<(last)<<")"<<endl;\
    for (int i=(first);i<(last);++i){cout<<#a<<"["<<i<<"] = "<<(a)[i]<<endl;}
#define PRINTP(p)\
    cout<<"func "<<__func__<<": line "<<__LINE__<<": "<<#p<<" = ("<<(p.first)<<", "<<(p.second)<<")"<<endl;
#define PRINTI(a,i)\
    cout<<"func "<<__func__<<": line "<<__LINE__<<": "<<#a<<"["<<#i<<"] = "<<#a<<"["<<(i)<<"] = "<<(a)[i]<<endl;
#else
#define PRINT(x)
#define PRINTA(a,first,last)
#define PRINTP(p)
#define PRINTI(a,i)
#endif

#define FOR(i,a,b) for (int i=(a);i<(b);++i)
#define RFOR(i,a,b) for (int i=(b)-1;i>=(a);--i)
#define REP(i,n) for (int i=0;i<(n);++i)
#define RREP(i,n) for (int i=(n)-1;i>=0;--i)
#define pb push_back
#define mp make_pair
#define all(a) (a).begin(),(a).end()
#define MOD 1000000007

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

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

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

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    string S;
    cin >> S;
    ll A = -100;
    ll BC = -100;
    int n = S.size();
    bool reading_A = false;
    bool reading_BC = false;
    ll result = 0;
    S.append("BB");
    REP(i, n + 2) {
        if (S[i] == 'A') {
            if (reading_BC) {
                assert(A >= 0);
                assert(BC >= 0);
                result += A * BC;
                //printf("add %d * %d\n", A, BC);
                BC = 0;
                reading_BC = false;
                if (S[i - 1] == 'B') {
                    A = 0;
                }
            } else if (!reading_A) {
                A = 0;
                BC = 0;
            }
            A++;
            reading_A = true;
        } else if (S[i] == 'B') {
            if (i - 1 >= 0 && S[i - 1] == 'A') {
                reading_A = false;
                reading_BC = true;
            } else if (reading_BC) {
                if (S[i - 1] == 'C') {
                } else if (S[i - 1] == 'B') {
                    assert(A >= 0);
                    assert(BC >= 0);
                    result += A * BC;
                    //printf("add %d * %d\n", A, BC);
                    A = 0;
                    BC = 0;
                    reading_A = false;
                    reading_BC = false;
                }
            } else {
                A = -100;
                BC = -100;
                reading_A = false;
                reading_BC = false;
            }
        } else if (S[i] == 'C') {
            if (reading_BC) {
                if (S[i - 1] == 'B') {
                    BC++;
                } else if (S[i - 1] == 'C') {
                    assert(A >= 0);
                    assert(BC >= 0);
                    result += A * BC;
                    //printf("add %d * %d\n", A, BC);
                    A = 0;
                    BC = 0;
                    reading_A = false;
                    reading_BC = false;
                }
            } else {
                A = -100;
                BC = -100;
                reading_A = false;
                reading_BC = false;
            }
        }
        PRINT(i);
        PRINT(A);
        PRINT(BC);
        PRINT(reading_A);
        PRINT(reading_BC);
    }
    cout << result << endl;
    return 0;
}


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

#define MP make_pair
#define N 200005
typedef long long LL;
const int mod = 1e9 +7;

char s[N];

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);

	int n;
	scanf("%s", s+1);
	n = strlen(s+1);
	LL ans = 0;
	int cnt = 0;
	while (n)
	{
		if (s[n] == 'C')
		{
			if (n == 1) break;
			if (s[n-1] == 'C') cnt = 0, --n;
			else if (s[n-1] == 'B') ++cnt, n -= 2;
			else cnt = 0, --n;
		}
		else if (s[n] == 'B') --n;
		else ans += cnt, --n;
	}
	cout << ans << endl;

	return 0;
}


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

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)   FOR(i,0,n)
#define ALL(a)  (a).begin(),(a).end()
#define LL long long
string s;
int main(){
  cin>>s;
  int n = s.size();
  LL cnt=0;
  LL ret=0;
  int idx=0;
  while(idx < n-1){
    if(s[idx]=='A'){
      cnt++;
      idx++;
    }else if(s[idx]=='B' && s[idx+1]=='C'){
      ret+=(LL)cnt;
      idx+=2;
    }else{
      idx++;
    }
  }
  cout<<ret<<endl;
  return 0;
}


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

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef pair<int, int> P;

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()

int inf = 1000000000;
int di[4] = {0, 1, 0, -1};
int dj[4] = {1, 0, -1, 0};

int main(){
  int h, w; cin >> h >> w;
  char a[h][w];
  int dist[h][w];
  rep(i, h)rep(j, w) dist[i][j] = inf;
  deque <P> d;
  rep(i, h)rep(j, w){
    cin >> a[i][j];
    if (a[i][j] == '#'){
      dist[i][j] = 0;
      d.emplace_back(P(i, j));
    }
  }
  while (d.size() > 0){
    int now_i = d.front().first;
    int now_j = d.front().second;
    d.pop_front();
    rep(i, 4){
      int nex_i = now_i + di[i];
      int nex_j = now_j + dj[i];
      if (nex_i < 0 || nex_i >= h||nex_j < 0 || nex_j >= w) continue;
      else if (a[nex_i][nex_j] ==  '#')continue;
      else{
        dist[nex_i][nex_j] = min(dist[now_i][now_j] + 1,  dist[nex_i][nex_j]);
        a[nex_i][nex_j] = '#';
        d.emplace_back(P(nex_i, nex_j));
      }
    }
  }
  int ans = 0;
  rep(i, h)rep(j, w) {
    ans = max(ans, dist[i][j]);
  }
  cout << ans << endl;
}

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3