0% found this document useful (0 votes)
10 views9 pages

SUST - Iupt1110

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

SUST - Iupt1110

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

return result; if(l>r)return vector<ll>(42, 0);

} if(l==tl and r==tr)return tree[node];


1. nCr mod prime 4.Eular totient from 1 to n ll mid=(tl+tr)>>1;
return combine(get(node<<1, tl, mid, l,
void phi_1_to_n(int n) {
min(r, mid)), get(node<<1|1, mid+1, tr,
ll fact[N]; vector<int> phi(n + 1); max(mid+1, l), r));
ll pwr(ll a,ll b) for (int i = 0; i <= n; i++) }
{ phi[i] = i;
if(b==0) return 1; 8. Lazy
for (int i = 2; i <= n; i++) {
ll ret=pwr(a,b/2)%mod; if (phi[i] == i) {
if(b%2==0) struct Node {
for (int j = i; j <= n; j += i)
ll small, lazy;
{ phi[j] -= phi[j] / i;
return ((ret)*(ret))%mod; } void merge (const Node& a, const Node&
} } b) {
else return small = min (a.small, b.small);
} }
((a%mod)*(((ret)*(ret))%mod))%mod;
5.Seive
void add (ll x) {
} mark[1] = 1; small += x;
ll inverseMod(ll a){ for (ll i = 4; i <= N; i += 2)mark[i] = 1; lazy += x;
}
return pwr(a, mod-2); for (ll i = 3; i * i <= N; i += 2){
};
} if (!mark[i])
ll nCrMod(ll n, ll r){ for (ll j = i * i; j <= N; j += i + i) ll TYPE_ADD = 1, TYPE_MAX = 2;
if(r==0)return 1; mark[j] = 1;
ve < Node > tree;
if(r>n) return 0; }
return primes.push_back(2); void rec (ll id, ll l, ll r, ll q_l, ll
(fact[n]*inverseMod(fact[r]*fact[n-r]%mod))%mod; for (ll i = 3; i <= N; i += 2) q_r, ll type, ll& x) {
} if (r < q_l or q_r < l) return;
if (!mark[i])
void fact_cal(){ primes.push_back(i); if (q_l <= l and r <= q_r) {
fact[0]=1; if (type == TYPE_ADD) {
6.Random tree[id].add (x);
for(ll i=1; i<N; i++){
const uint64_t SEED = }
fact[i]=(fact[i-1]*i)%mod;
chrono::steady_clock::now().time_since_epoch( else {
} x = min (x, tree[id].small);
).count() * (random_address() | 1);
} }
mt19937_64 rng(SEED);
return;
int num = rng(); }

2.Extended Euclid mt19937 for (ll jd : {id << 1, id << 1 | 1}) {


//this algorithm find's x, y such that ax+by=gcd(a, b); rng(chrono::steady_clock::now().time_since_ep tree[jd].add (tree[id].lazy);
och().count()); }
// we know gcd(a, b)=gcd(b, a%b) so ax+by= bx1+(a-a/b
*b)y1= ay1+b(x1-a/b*y1)
tree[id].lazy = 0;
// so, x=y1, and y=x1-a/b*y1 and as gcd(a, 0)=a,
ax+0y=a. so base case is x=1 and y=anything.
7. Segtree:
rec (id << 1, l, l + r >> 1, q_l, q_r,
pair<ll,ll> Extended_gcd(ll a, ll b){ type, x);
vector<vector<ll>>tree(N*4, vector<ll>(42, 0)); rec (id << 1 | 1, l + r + 2 >> 1, r,
if(b==0)return {1, 1};
q_l, q_r, type, x);
auto [x1, y1]=Extended_gcd(b, a%b); vector<ll>v(N);

ll x=y1, y=x1-(a/b)*y1; vector<ll> combine(vector<ll>st1, vector<ll>st2){ tree[id].merge (tree[id << 1], tree[id
return {x, y}; for(ll i=1; i<st1.size(); i++){ << 1 | 1]);
}
} st2[i]+=st1[i];

// gcd(a, m) = 1 is also the condition for the modular } 9.Building graph from matrix
inverse to exist. return st2; vector<ll>graph[25], val(25, 0);// 25=maximum number
//ax+my=1 mod m so ax=1 mod m. so here x is modular of nodes
}
vector<pair<ll,ll>>moves={{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
inverse of a.
void update(ll node, ll tl, ll tr, ll ind, ll val){ bool valid(ll x, ll y, ll row, ll col){
3.Eular totient return x<row and y<row and x>=0 and
if(tl==tr){ y>=0;
int phi(int n) { if(tree[node][v[ind]])tree[node][v[ind]]--; }
void build_graph(string s[], ll row, ll col){
int result = n; v[ind]=val; for(ll i=0; i<row; i++){
for (int i = 2; i * i <= n; i++) { tree[node][v[ind]]++; for(ll j=0; j<col; j++){
ll node= i*row + j;// representing each cell
if (n % i == 0) { return; as a node of a graph.
while (n % i == 0) } if(s[i][j]=='J'){//meet our necessery condition
then set the value of node
n /= i; ll mid=(tl+tr)>>1; val[node]=1;
result -= result / i; if(ind<=mid)update(node<<1, tl, mid, ind, val); }
for(auto &[x, y]:moves){
} else update(node<<1|1, mid+1, tr, ind, val); ll new_i=i+x, new_j=j+y;
} tree[node]=combine(tree[node<<1], tree[node<<1|1]);
if(valid(new_i, new_j, row, col)){//means cell
if (n > 1) } is adjacent to node's cell
result -= result / n; vector<ll> get(ll node, ll tl, ll tr, ll l, ll new_node=new_i*row+new_j;
graph[node].push_back(new_node);
ll r){
}
{ ll stable[LOG][N];
} if(color[child]==0) ll func(ll a, ll b){
} { return min(a, b);
} if(color[parent]==1)color[child]=2; }
} else color[child]=1; ll rangeMinQuery(ll l, ll r){
qu.push(child); ll len = r - l + 1, i = log2(len);
10.Floyed_warshal } return min(stable[i][l], stable[i][r - (1 << i) + 1]);
else if(color[child]==color[parent])return false; }
} ll rangeQuery(ll l, ll r){
ll INF=1e18, d[N][N], nxt[N][N] //initially next[i][j]=j, d[i][i]=0;
} ll sum = 0;
void floyed_warshal()
return true; for (int i = LOG; i >= 0; i--){
{
} if ((1 << i) <= r - l + 1){
for (int k = 0; k < v; ++k) {
sum += stable[i][l];
for (int i = 0; i < v; ++i) {
14.Topo sort l += 1 << i;
for (int j = 0; j < v; ++j) {
}
if (d[i][k] < INF && d[k][j] < INF)
int in_degree[N]; }
if(d[i][k] + d[k][j]<d[i][j]){
vector<int> ans; return sum;
d[i][j]=d[i][k] + d[k][j];
set<int> st; }
nxt[i][j]=nxt[i][k];
int cnt = 0; void spharseTable(vector<ll> &array)
}
void bfs() {
}
{ copy(array.begin(), array.end(), stable[0]);
}
while(!st.empty()) for (ll i = 1; i < LOG; i++){
}
{ for (ll j = 0; j + (1ll << i) < N; j++){
}
cnt++; stable[i][j] = func(stable[i - 1][j], stable[i - 1][j +
vector<ll> path;
int u = *st.begin(); (1 << (i - 1))]}}
void find_path(ll i, ll j){
path.push_back(i); st.erase(st.begin());
while(i!=j){ ans.pb(u);
i=nxt[i][j]; vector<int> temp; 17.cycle detection
path.push_back(i); for(auto &it: graph[u]) int n;
} { vector<vector<int>> adj;
} in_degree[it]--; vector<char> color;
if(!in_degree[it])
11.MST and DSU {
vector<int> parent;
int cycle_start, cycle_end;
parent[N], sz[N]; st.insert(it);}
void make_set(ll n){ } bool dfs(int v) {
} color[v] = 1;
for(ll i=1; i<=n; i++)parent[i]=i, ans[i]=0, ssz[i]=1;
} for (int u : adj[v]) {
}
if (color[u] == 0) {
ll find_par(ll u){
return parent[u]==u? u: parent[u]=find_par(parent[u]);
15. Spharse Table and Lca on tree parent[u] = v;
if (dfs(u))
} const int N=1e5+10, Log=21; return true;
ll ans=0; vector<vector<ll>>up(N, vector<ll>(Log, 1)); } else if (color[u] == 1) {
void Union(ll u, ll v, ll w){ vector<vector<ll>>stablemx(N, vector<ll>(Log, -1)), cycle_end = v;
stablemi(N, vector<ll>(Log, INT64_MAX)); cycle_start = u;
u=find_par(u), v=find_par(v);
vector<ll>depth(N, 0); return true;
if(u!=v){ }
if(sz[u]<sz[v])swap(u, v); vector<pair<ll,ll>>graph[N];
// ll stablemx[N][Log], stablemi[N][Log]; }
parent[v]=u; color[v] = 2;
void dfs(ll u, ll parent){
sz[u]+=sz[v]; for(auto &[v, w]: graph[u]){ return false;
ans+=w; if(v==parent)continue; }
} depth[v]=depth[u]+1;
up[v][0]=u; void find_cycle() {
}
stablemx[v][0]=w; color.assign(n, 0);
stablemi[v][0]=w; parent.assign(n, -1);
cycle_start = -1;

12.Dijkstra for(ll j=1; j<Log; j++){


ll p=up[v][j-1]; for (int v = 0; v < n; v++) {
up[v][j]=up[p][j-1]; if (color[v] == 0 && dfs(v))
stablemx[v][j]=max(stablemx[v][j-1], break;
ll INF=1e18, d[N][N], nxt[N][N] //initially next[i][j]=j, d[i][i]=0;
stablemx[p][j-1]); }
void floyed_warshal()
{ stablemi[v][j]=min(stablemi[v][j-1],
stablemi[p][j-1]); if (cycle_start == -1) {
for (int k = 0; k < v; ++k) {
} cout << "Acyclic" << endl;
for (int i = 0; i < v; ++i) {
dfs(v, u); } else {
for (int j = 0; j < v; ++j) {
} vector<int> cycle;
if (d[i][k] < INF && d[k][j] < INF)
} cycle.push_back(cycle_start);
if(d[i][k] + d[k][j]<d[i][j]){
pair<ll,ll> get_lca(ll u, ll v){ for (int v = cycle_end; v != cycle_start; v =
d[i][j]=d[i][k] + d[k][j];
ll mx=0, mi=INT64_MAX; parent[v])
nxt[i][j]=nxt[i][k];
if(depth[u]<depth[v])swap(u, v); cycle.push_back(v);
}
ll k=depth[u]-depth[v]; cycle.push_back(cycle_start);
}
reverse(cycle.begin(), cycle.end());
}
} for(ll j=Log-1; j>=0; j--){
if(k&(1<<j)){ cout << "Cycle found: ";
}
mx=max(stablemx[u][j], mx); for (int v : cycle)
vector<ll> path;
mi=min(stablemi[u][j], mi); cout << v << " ";
void find_path(ll i, ll j){
u=up[u][j]; cout << endl;
path.push_back(i);
} }
while(i!=j){
} }
i=nxt[i][j];
path.push_back(i); if(u==v)return {mi, mx};
} for(ll j=Log-1; j>=0; j--){ 18.bellman
} if(up[u][j]!=up[v][j]){ #include<bits/stdc++.h>
mx=max({stablemx[u][j], stablemx[v][j], mx}); using namespace std;
13.Bicoloring mi=min({stablemi[u][j], stablemi[v][j], mi});
u=up[u][j]; const int N = 3e5 + 9;
v=up[v][j];
int color[N];
} struct st {
bool color_bfs(int source)
} int a, b, cost;
{
mx=max({stablemx[u][0], stablemx[v][0], mx}); } e[N];
queue<ll> qu;
mi=min({stablemi[u][0], stablemi[v][0], mi}); const int INF = 2e9;
qu.push(source);
return {mi, mx}; int32_t main() {
color[source]=1;
} int n, m;
while(!qu.empty())
{ cin >> n >> m;
ll parent=qu.front(); 16. Spharse table for(int i = 0; i < m; i++) cin >> e[i].a >> e[i].b >> e[i].cost;
qu.pop(); int s;
for(auto &child: graph[parent]) const int LOG = 31;
cin >> s;//is there any negative cycle which is reachable
from s?
mod;
vector<int> d (n, INF);//for finding any cycle(not 21.MO’s h = h % mod;
necessarily from s) set d[i] = 0 for all i
d[s] = 0; void remove(int idx){ power = (power * base)%mod;
vector<int> p (n, -1); } // TODO: remove value at idx from data
int x; structure }
for (int i=0; i<n; ++i) {
x = -1;
void add(int idx){ return h;
} // TODO: add value at idx from data
for (int j=0; j<m; ++j) {
if (d[e[j].a] < INF) { structure }
if (d[e[j].b] > d[e[j].a] + e[j].cost) { int get_answer(){
vector<ll>power(N);
d[e[j].b] = max (-INF, d[e[j].a] + e[j].cost);//for } // TODO: extract the current answer of the
overflow data structure void power_calc(ll n, ll base){
p[e[j].b] = e[j].a;
x = e[j].b;
int block_size;// block_size=sqrt(n);
power[0]=1;
}
} for(ll i=1; i<n; i++){
} struct Query {
} int l, r, idx;
if (x == -1) cout << "No negative cycle from "<<s;
else {
//In odd blocks sort the right index power[i]=(power[i-1]*base)%mod;
in ascending order and in even blocks sort it
int y = x; //x can be on any cycle or reachable
in descending order. This will minimize the }
from some cycle
for (int i=0; i<n; ++i) y = p[y]; movement of right pointer }
bool operator<(Query other) const
vector<int> path; { //prev= s[i-len], now=s[i]
for (int cur=y; ; cur=p[cur]) {
path.push_back (cur);
if(l/block_size != //http://www.shafaetsplanet.com/?p=3
other.l/block_size)
if (cur == y && path.size() > 1) break;
}
return l<other.l; 028
reverse (path.begin(), path.end()); return (l/ block_size & 1) ? (r <
void update(ll &hash, ll len, char prev,
other.r) : (r > other.r);
cout << "Negative cycle: "; } char now, ll base, ll mod){
for (int i=0; i<path.size(); ++i) cout << path[i] <<
' '; };
hash = (hash - (power[len-1] *
}
return 0;
vector<int> mo_s_algorithm(vector<Query> (prev-'a'+1) % mod)) % mod;
queries) {
}
vector<int> answers(queries.size());
hash = (hash + mod) % mod;
sort(queries.begin(), hash = (hash * base) % mod;
19.lis in O(nlogn) queries.end());
#include<bits/stdc++.h> // TODO: initialize data structure hash = (hash + (now -'a'+1)) %
using namespace std;
#define ll long long
//VVI mod;
int cur_l = queries[0].l;
int cur_r = queries[0].l; }
int main(){
ll n;
// invariant: data structure will
always reflect the range [cur_l, cur_r]
23.Ternary search:
cin>>n; double ternary_search(double l, double r) {
for (Query q : queries) {
vector<ll>sequence; double eps = 1e-9; //set
while (cur_l > q.l) {
the error limit here
for(ll i=0; i<n; i++){ cur_l--;
while (r - l > eps) {
ll value; add(cur_l);
double m1 = l + (r - l) / 3;
cin>>value; }
double m2 = r - (r - l) / 3;
while (cur_r < q.r) {
ll ind=lower_bound(sequence.begin(), double f1 = f(m1); //evaluates
cur_r++;
sequence.end(), value)-sequence.begin(); the function at m1
add(cur_r); double f2 = f(m2); //evaluates
if(ind==sequence.size())
sequence.push_back(value); } the function at m2
else sequence[ind]=value; while (cur_l < q.l) { if (f1 < f2)
} remove(cur_l); l = m1;
cout<<sequence.size(); cur_l++; else
} } r = m2;
20.Basic while (cur_r > q.r) { }
typedef long long ll; remove(cur_r); return f(l); //return
typedef vector<ll> vll; cur_r--; the maximum of f(x) in [l, r]
const ll N = 2e5 + 10, inf=2e18;
ll mod = 1000000007;
} }
answers[q.idx] = get_answer();
#define pi acos(-1.0) }
23. Pi function
double eps = 1e-12; return answers;
#define precision(n) cout << setprecision(n) << fixed; } vector<int> prefix_function(string s)
typedef long double ld; {
int n = (int)s.length();
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp> vector<int> pi(n);
template <typename T> for (int i = 1; i < n; i++) {
using order_set = __gnu_pbds::tree<T, int j = pi[i-1];
__gnu_pbds::null_type, std::less<T>, 22.Hash: while (j > 0 && s[i] != s[j])
__gnu_pbds::rb_tree_tag,
__gnu_pbds::tree_order_statistics_node_update>;; ll mod = (1ll<<56)-5; j = pi[j-1];
//kthElement = *myTree.find_by_order(1), index(zero if (s[i] == s[j])
based) = myTree.order_of_key(8)
j++;
void solve(ll tc)
//ll mod= (1ll<<56)-5; pi[i] = j;
{ ll Hash(const string &s, ll len, ll base, }
return pi;
} ll mod){
int main() }
{ ll h = 0 , power = 1;
fastio;ll T = 1;
cin >> T; for(ll i = len-1;i>=0;i--){
for (ll i = 1; i <= T; i++)solve(i);
return 0;
h = h + ((s[i]-'a'+1) * power) %
2. Geo while (q--) {
int u, v; cin >> u >> v; }
cout << dist(u, v) << '\n';
}
return 0; } return 0;
Ternary Search }

Mo
const int K = 350, mxN = 1e6+5; Ordered Set
BIT int a[mxN], l=0, r=0, res=0; #include<ext/pb_ds/assoc_container.hpp>
std::unordered_map<int,int> cnt; #include<ext/pb_ds/tree_policy.hpp>
template <class T>
using namespace __gnu_pbds;
struct BIT { //1-indexed
void add(int x) {
int n; vector<T> t;
BIT() {} x = a[x]; template <typename T> using oSet = tree<T,
BIT(int _n) { if (cnt[x]==x&&x) res--; null_type, std::less<T>, rb_tree_tag,
n = _n; t.assign(n + 1, 0);
cnt[x]++; tree_order_statistics_node_update>;
}
T query(int i) { if (cnt[x]==x&&x) res++; template <typename T, typename R> using
T ans = 0; }
for (; i >= 1; i -= (i & -i)) ans += t[i]; oMap = tree<T, R, std::less<T>,
return ans; rb_tree_tag,
} void rem(int x) { tree_order_statistics_node_update>;
void upd(int i, T val) { x = a[x];
if (i <= 0) return;
for (; i <= n; i += (i & -i)) t[i] += val; if (cnt[x]==x&&x) res--; // oSet<int> os, oMap<int,int> om
} cnt[x]--;
void upd(int l, int r, T val) { if (cnt[x]==x&&x) res++; *os.find_by_order(k) // k th element
upd(l, val);
upd(r + 1, -val); } os.order_of_key(2) // number of elements
} less than k
T query(int l, int r) { void que(int L, int R) { om.insert({1, 10});
return query(r) - query(l - 1);
} while (l>L) add(--l); om.insert({2, 20});
}; while (l<L) rem(l++); mp.find_by_order(0)->second //k th element
while (r>R) rem(r--); mp.order_of_key(2) //number of first
while (r<R) add(++r); elements less than k
LCA }

const int N = 3e5 + 9, LG = 18;


vector<int> g[N]; struct Q{ Basic Grundy
int par[N][LG + 1], dep[N], sz[N]; int id, l, r;
void dfs(int u, int p = 0) {
}; const int mxN = 10001;
par[u][0] = p;
dep[u] = dep[p] + 1; int G[mxN+5], used[mxN+5];
sz[u] = 1; signed main() {
for (int i = 1; i <= LG; i++) par[u][i] = par[par[u][i - 1]][i -
int testCases=1; signed main() {
1];
for (auto v: g[u]) if (v != p) { // scanf("%d",&testCases); int testCases=1;
dfs(v, u); scanf("%d",&testCases);
sz[u] += sz[v];
for (int T = 1; T <= testCases; T++) {
}
} int n; scanf("%d",&n); auto grundy = [&] () {
int lca(int u, int v) { int m; scanf("%d",&m); int offset = 0;
if (dep[u] < dep[v]) swap(u, v);
for (int k = LG; k >= 0; k--) if (dep[par[u][k]] >= dep[v]) for (int i = 1; i < mxN; i++) {
u = par[u][k]; for (int i = 1; i <= n; i++) int lim = i/2; if (i%2==0) lim--;
if (u == v) return u; scanf("%d",&a[i]);
for (int k = LG; k >= 0; k--) if (par[u][k] != par[v][k]) u = for (int j = 1,xorVal; j <= lim;
par[u][k], v = par[v][k]; j++) {
return par[u][0]; std::vector<Q> q(m);
xorVal = G[j]^G[i-j];
} for (int i = 0,l,r; i < m; i++) {
int kth(int u, int k) { used[xorVal] = offset+1;
scanf("%d%d",&q[i].l,&q[i].r);
assert(k >= 0); }
for (int i = 0; i <= LG; i++) if (k & (1 << i)) u = par[u][i]; q[i].id = i;
int ok = 0; // MEX calculation
return u; }
} helper
int dist(int u, int v) { for (int j = 0; j < 2*mxN; j++) {
int l = lca(u, v); sort(q.begin(),q.end(),[](Q fi, Q
return dep[u] + dep[v] - (dep[l] << 1); if (used[j]<=offset) {
se){
} G[i] = j;
int fi_block_id = fi.l/K;
//kth node from u to v, 0th node is u
ok = 1;
int se_block_id = se.l/K;
int go(int u, int v, int k) { if (fi_block_id==se_block_id) break;
int l = lca(u, v); }
int d = dep[u] + dep[v] - (dep[l] << 1); return fi.r<se.r;
assert(k <= d); return fi_block_id < se_block_id; }
if (dep[l] + k <= dep[u]) return kth(u, k); }); if (ok==0) G[i] = 2*mxN;
k -= dep[u] - dep[l]; offset++;
return kth(v, dep[v] - dep[l] - k);
} int ans[m]; }
int32_t main() { for (int i = 0; i < m; i++) { };
int n; cin >> n;
que(q[i].l,q[i].r); grundy();
for (int i = 1; i < n; i++) {
int u, v; cin >> u >> v; ans[q[i].id] = res;
g[u].push_back(v); } for (int T = 1; T <= testCases; T++) {
g[v].push_back(u);
} int n; scanf("%d",&n);
dfs(1); for (int i = 0; i < m; i++) int ans = 0;
int q; cin >> q; printf("%d\n",ans[i]);
for (int i = 0,x; i < n; i++) { } return 0;
scanf("%d",&x); ts.push_back(i); }
ans ^= G[x]; for (int i=0; i<m; ++i) if (where[i] == -1)
} } return INF;
return 1;
printf("Case %d: st.clear(); }
%s\n",T,ans?"Alice":"Bob"); ts.clear();
MCM
} for (int i = N-1; i >= 0; i--) { void matMul(ll R[2][2],ll a[2][2],ll b[2][2]){
while ((int)st.size() && ll i,j,k;
return 0; a[st.back()] <= a[i]) { ll R1[2][2];
} st.pop_back(); memset(R1,0,sizeof(R1));
} for(i=0; i<2; i++) for(j=0; j<2; j++)
if ((int)st.size()) { for(k=0; k<2; k++)
NGR[i] = st.back(); R1[i][k]=add(R1[i][k],mul(a[i][j],b[j][k]));
} else { memcpy(R,R1,sizeof(R1));
NGR[i] = -1; }
} void matExp(ll R[2][2],ll a[2][2],ll k){
st.push_back(i); R[0][0]=R[1][1]=1; R[0][1]=R[1][0]=0;
Misere Nim for(; k; k>>=1){
while ((int)ts.size() && if(k&1) matMul(R,R,a);
int n; scanf("%d",&n); a[ts.back()] >= a[i]) { matMul(a,a,a);
int ans = 0, greaterThanOne=0; ts.pop_back(); }
} }
for (int i = 0,x; i < n; i++) { if ((int)ts.size()) {
scanf("%d",&x); NSR[i] = ts.back();
if (x>1) greaterThanOne = 1;
ans ^= x;
} else {
Knuth Optimization
NSR[i] = -1;
} } int n, k;
ts.push_back(i); int a[N], mid[N][N];
if (greaterThanOne==0) { } ll res[N][N];
ans = n&1 ? 0:1; ll solve() {
} for (int s = 0; s <= k; s++) { //
s - length of the subarray

printf("Case %d: %s\n",T,ans?"Alice":"Bob");


Gausss for (int l = 0; l + s <= k; l++) { // l
- left point
const double EPS = 1e-9; int r = l + s; // r -
right point
const int INF = 2; // it doesn’t actually have
if (s < 2) {
Bigmod to be infinity or a big number res[l][r] = 0; // base
int gauss (vector < vector<double> > a, case- nothing to break
int bigmod(int a, int b, int MOD) { mid[l][r] = l; // mid
vector<double> & ans) {
if (b==0) return 1;
int n = (int) a.size(); is equal to left border
ll x = bigmod(a,b/2,MOD); ( x *= x ) %= MOD; continue;
int m = (int) a[0].size() - 1;
if (b&1) ( x *= a ) %= MOD; }
vector<int> where (m, -1); int mleft = mid[l][r - 1];
return (int)x;
for (int col=0, row=0; col<m && row<n; int mright = mid[l + 1][r];
} res[l][r] = 2e18;
++col) {
int sel = row; for (int m = mleft; m <= mright; m++)
{ // iterating for m in the bounds only
for (int i=row; i<n; ++i)
ll tmp = res[l][m] + res[m][r] +
NGR, NGL, NSR, NSL if (abs (a[i][col]) > abs (a[sel][col])) (a[r] - a[l]);
sel = i; if (res[l][r] > tmp) {
std::vector<int> st, ts; if (abs (a[sel][col]) < EPS) continue; // relax current solution
for (int i = 0; i < N; i++) { res[l][r] = tmp;
for (int i=col; i<=m; ++i)
while ((int)st.size() && mid[l][r] = m;
swap (a[sel][i], a[row][i]);
}
a[st.back()] <= a[i]) {
}
st.pop_back(); where[col] = row; }
} for (int i=0; i<n; ++i) }
if ((int)st.size()) { ll ans = res[0][k];
if (i != row) {
NGL[i] = st.back(); return ans;
double c = a[i][col] / a[row][col];
}
} else { for (int j=col; j<=m; ++j) int main() {
NGL[i] = -1; a[i][j] -= a[row][j] * c; int i, j, m;
} } while(cin >> n >> k) {
st.push_back(i); for(i = 1; i <= k; i++) cin >> a[i];
++row;
a[0] = 0;
} a[k + 1] = n;
while ((int)ts.size() && ans.assign (m, 0); k++;
a[ts.back()] >= a[i]) { for (int i=0; i<m; ++i) if (where[i] != -1) cout << solve() << endl;
ts.pop_back(); ans[i] = a[where[i]][m] / a[where[i]][i]; }
} return 0;
for (int i=0; i<n; ++i) {
if ((int)ts.size()) { }
double sum = 0;
NSL[i] = ts.back(); for (int j=0; j<m; ++j) sum += ans[j] *
} else { a[i][j];
NSL[i] = -1; if (abs (sum - a[i][m]) > EPS)
echo "WA on the following test:" #define flush fflush(stdout)
# RUN: bash stressTest.sh cat in
set -e echo "Your answer is: " using ll = long long int;
g++ -std=c++17 -o gen generator.cpp cat out using pii = std::pair<int,int>;
g++ -std=c++17 -o a B.cpp echo "Correct answer is: "
# g++ brute.cpp -o brute cat correctAnswer const int MOD = 1000000007;
g++ -std=c++17 -o b C.cpp // const int MOD = 998244353;
for((i = 1; ; ++i)); do Template const int mxN = 500005;
./gen $i > in
./a < in > out #include "bits/stdc++.h" signed main() {
./b < in > correctAnswer int testCases=1;
diff -Z out correctAnswer > #define fastIO scanf("%d",&testCases);
/dev/null || break std::ios::sync_with_stdio(0);std::cin. // std::cin >> testCase;
echo "Passed Test: " $i tie(0);
done

Equations: representation. Then the number of


odd terms will be 2x. 33. Derangement: a permutation of the
● Every entry in row 2n−1,n≥0, is elements of a set, such that no element
odd. appears in its original position. Let d(n) be
the number of derangements of the identity
24. An integer n≥2 is prime if and only if all permutation fo size n.
the intermediate binomial coefficients

are divisible by n.
34. Involutions: permutations such that p2=
25. Kummer’s Theorem: For given integers identity permutation. a0=a1=1 and
n≥m≥0 and a prime number p, the largest an=an-1+(n−1)an−2 for n>1.

power of p dividing is equal to the 35. Let T(n,k) be the number of permutations
number of carries when m is added to n-m in of size n for which all cycles have length ≤k.
base p. For implementation take inspiration
from lucas theorem.

26. Number of different binary sequences of


length n such that no two 0’s are
adjacent=Fibn+1.
36. Lucas Theorem:
27. Combination with repetition: Let’s say
we choose k elements from an n-element set,
the order doesn’t matter and each element - For non-negative integers m and n and a
can be chosen more than once. In that case, prime p, the following congruence relation
the number of different combinations is: holds:

28. Number of ways to divide n persons in n/k


equal groups i.e. each having size k is-

are the base p expansions of m and n


respectively. This uses the convention that
29. The number non-negative solution of the
22. Highest Power of 2 that divides 2nCn: Let equation: x1+x2+x3+…+xk=n is when m < n.
x be the number of 1s in the binary
representation. Then the number of odd
terms will be 2x. Let it form a sequence. The
n-th value in the sequence (starting from n = 30. Number of ways to choose n ids from 1
0) gives the highest power of 2 that divides to b such that every id has distance at least k
2n
Cn.
=
23. Pascal Triangle:
● In a row p where p is a prime
number, all the terms in that row
except the 1s are multiples of p.
● Parity: To count odd terms in row n,
convert n to binary. Let x be the
number of 1s in the binary
44. Number of correct bracket sequence
consisting of n opening and n closing
brackets.

45. The number of ways to completely


parenthesize n+1 factors.

46. The number of triangulations of a convex


polygon with n+2 sides (i.e. the number of
partitions of polygon into disjoint triangles
by using the diagonals).

47. The number of ways to connect the 2n


points on a circle to form n disjoint i.e.
non-intersecting chords.
79. Lagrange’s identity:
48. The number of monotonic lattice paths
from point (0,0) to point (n,n) in a square
lattice of size n×n, which do not pass above
the main diagonal (i.e. connecting (0,0) to
(n,n)).

49. The number of rooted full binary trees


of the second kind. with n+1 leaves (vertices are not numbered).
So, instead of O(n), now you can calculate A rooted binary tree is full if every vertex
the original equation in O(k2) or even in has either two children or no children.
O(klog2n) using NTT. 81. Vieta’s formulas:
50. Number of permutations of 1,…,n that Any general polynomial of degree n
avoid the pattern 123 (or any of the other
patterns of length 3); that is, the number of
permutations with no three-term increasing
(with the coefficients being real or complex
sub-sequence. For n=3, these permutations
numbers and an≠0) is known by the
are 132, 213, 231, 312 and 321.\displaystyle
fundamental theorem of algebra to have n
For n=4, they are 1432, 2143, 2413, 2431,
(not necessarily distinct) complex roots
3142, 3214, 3241, 3412, 3421, 4132, 4213,
r1,r2,…,rn.)
4231, 4312 and 4321.
If we continuously do this n times then the
polynomial of the first column of the n-th 51. Balanced Parentheses count with prefix:
row will be The count of balanced parentheses sequences
consisting of n+k pairs of parentheses where
the first k symbols are open brackets. Let the
number be Cn(k), then

Vieta’s formulas can equivalently be written


as

82. We are given n numbers a1,a2,…,an and


our task is to find a value x that minimizes
the sum,
|a1−x|+|a2−x|+...+|an−x|.

optimal x= median of the array.


If n is even x= [left median,right median] i.e.
every number in this range will work.
For minimizing,
(a1−x)2+(a2−x)2+...+(an−x)2
Divisor Function

83. Given an array a of n non-negative 113.


integers. The task is to find the sum of the
product of elements of all the possible
subsets. It is equal to the product of (ai+1)
for all ai Here, d(x)= number of divisors of x.

84. =

The exponents 1,2,5,7,12,⋯ on the right hand 116. It is multiplicative i.e if


side are given by the formula gcd(a,b)=1→σx(ab)=σx(a)σx(b)

for k=1,−1,2,−2,3,⋯ and are


called (generalized) pentagonal numbers.
It is useful to find the partition number in
O(n √ n). 117. d=gcd(m,n).

118. Divisor Summatory Function Note the special cases,


● Let σ0(k) be the number of divisors
of k.

● 132. φ(lcm(m,n))⋅φ(gcd(m,n))=φ(m)⋅φ(n)
Where, u=√x Compare this to the formula
lcm(m,n)⋅gcd(m,n)=m⋅n
● D(n)= Number of increasing
arithmetic progressions where n+1 133. φ(n) is even for n≥3. Moreover, if if n
is the second or later term. (i.e. The has r distinct odd prime factors, 2r|φ(n)
last term, starting term can be any
positive integer ≤n. For example,
D(3)=5 and there are 5 such
arithmetic progressions:
(1,2,3,4);(2,3,4);(1,4);(2,4);(3,4).

119. Let σ1(k) be the sum of divisors of k.

Then,

120. if n is not a perfect square, nx mod m=n ϕ(m )+ x mod ϕ(m) mod
94. A number is Fibonacci if and only if one
or both of (5⋅n2+4) or (5⋅n2−4) is a perfect and if n is a perfect square.
square
Euler’s Totient function where d(n) is number of divisors.
95. Every third number of the sequence is Same equation for gcd(a⋅k−1,n) where a and
even and more generally, every kth number of 121. The function is multiplicative. This n are coprime.
the sequence is a multiple of Fk means that if gcd(m,n)=1, 141. For every n there is at least one other
ϕ(m⋅n)=ϕ(m)⋅ϕ(n). integer m≠n such that φ(m)=φ(n).
96. gcd(Fm,Fn)=Fgcd(m,n)

97. Any three consecutive Fibonacci


numbers are pairwise coprime, which means
that, for every n,
gcd(Fn,Fn+1)=gcd(Fn,Fn+2),gcd(Fn+1,Fn+2)=1
Note that [] is used here to denote round
98. If the members of the Fibonacci 124. Jk(n), the Jordan totient function, is the operator not floor or ceil.
sequence are taken mod n, the resulting number of k-tuples of positive integers all
sequence is periodic with period at most 6n. less than or equal to n that form a coprime
(k+1)-tuple together with n. It is a 144.
generalization of Euler’s totient, ϕ(n)=J1(n).
145. Average of coprimes of n which are less
than n is (n / 2)

190. 1⊕2⊕3⊕⋯⊕(4k−1)=0 for any k≥0

191. Erdos Gallai Theorem: The degree


sequence of an undirected graph is the
non-increasing sequence of its vertex
degrees A sequence of non-negative integers
d1≥d2≥⋯≥dn can be represented as the
degree sequence of finite simple graph on n
vertices if and only if d1+d2+⋯+dn is even
and

holds for every k in 1≤k≤n.


1. INTEGER LIMIT OUT OF BOUNDS
2. ARRAY INDEX OUT OF BOUNDS
3. DIVISION BY ZERO
4. MEMSET BIG SIZE ARRAY IN EVERY
TEST CASE
5. INFINITE LOOP
7. BIG SIZE ARRAY DECLARATION INSIDE
MAIN FUNCTION
8. DELETE ARRAY ELEMENT WHILE IN A
LOOP RUNNING ON THE ARRAY
9. UPDATE ARRAY ELEMENT WITHOUT
PROPER MEMORY ADDRESSING
10. FORGET TO RESET THE ARRAY
11. FOR BIG SIZE USE DYNAMIC VECTOR
IN C++
12. x&(1<<b)==0 IS WRONG, WRITE (
x&(1<<b) )==0
13. FOR BIG STRING
std::cin >> s; IS BETTER THAN
scanf("%s",s);
BUT, AGAIN std::cin>>s IS SLOW
WITHOUT ios_base

14. TL ISSUE: USE BFS INSTEAD OF DFS

15. FIRST DEFINE THE ALGO, THEN


IMPLEMENT

16. REDUCE AS MUCH FLOAR OPERATION


AS POSSIBLE
17. vec.erase(vec.begin()) CAN CAUSE TLE
ISSUE

18. cin/cout WITH FASTIO IS FASTER THAN


scanf/printf

You might also like