Author: loud_mouth
Idea: Bignubie
Editorial
Tutorial is loading...
Solution (Loud_mouth)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int last=0;
for(int i=0; i<30; ++i)
{
if(((n>>i)&1) == 1)
{
last=i;
}
}
cout<<(1<<last)-1<<"\n";
}
return 0;
}
Solution (the_nightmare)
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define pb push_back
#define ppb pop_back
#define endl '\n'
#define mii map<ll,ll>
#define msi map<string,ll>
#define mis map<ll, string>
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define repr(i,a,b) for(ll i=b-1;i>=a;i--)
#define trav(a, x) for(auto& a : x)
#define pii pair<ll,ll>
#define vi vector<ll>
#define vii vector<pair<ll, ll>>
#define vs vector<string>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define lbnd lower_bound
#define ubnd upper_bound
#define DEBUG cerr<<"/n>>>I'm Here<<</n"<<endl;
#define display(x) trav(a,x) cout<<a<<" ";cout<<endl;
#define what_is(x) cerr << #x << " is " << x << endl;
#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace __gnu_pbds;
using namespace std;
#define PI 3.141592653589793
#define N 200005
void solve()
{
ll n;
cin >> n;
ll cnt=0;
while(n!=0){
cnt++;
n=n/2;
}
cout << (1<<(cnt-1))-1 << endl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen ("input.txt","r",stdin);
#endif
ll int TEST=1;
cin >> TEST;
//init();
while(TEST--)
{
solve();
}
}
1527B1 - Palindrome Game (easy version)
Author: DenOMINATOR
Idea: shikhar7s
Editorial
Tutorial is loading...
Solution (DenOMINATOR)
#include<bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
string s;
cin >> s;
bool is_palindrome=1;
int cnt_0 = 0;
for(int i=0;i<n;i++){
cnt_0 += s[i]=='0';
}
if(cnt_0 == 1){
cout << "BOB\n";
return;
}
if(cnt_0%2){
cout << "ALICE\n";
return;
}
cout << "BOB\n";
return;
}
signed main()
{
int t;
cin >> t;
while(t--){
solve();
}
return 0;
}
Solution (shikhar7s)
#include<bits/stdc++.h>
using namespace std;
#define int long long int
#define mp(a,b) make_pair(a,b)
#define vi vector<int>
#define mii map<int,int>
#define mpi map<pair<int,int>,int>
#define vp vector<pair<int,int> >
#define pb(a) push_back(a)
#define fr(i,n) for(i=0;i<n;i++)
#define rep(i,a,n) for(i=a;i<n;i++)
#define F first
#define S second
#define endl "\n"
#define fast std::ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define mod 1000000007
#define dom 998244353
#define sl(a) (int)a.length()
#define sz(a) (int)a.size()
#define all(a) a.begin(),a.end()
#define pii pair<int,int>
#define mini 2000000000000000000
#define time_taken 1.0 * clock() / CLOCKS_PER_SEC
//const long double pi = acos(-1);
//mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());
//primes for hashing 937, 1013
template<typename T, typename U> static inline void amin(T &x, U y)
{
if (y < x)
x = y;
}
template<typename T, typename U> static inline void amax(T &x, U y)
{
if (x < y)
x = y;
}
void shikhar7s(int cas)
{
int n,i;
cin>>n;
string s;
cin>>s;
int f=1,z=0;
fr(i,n)
{
if(s[i]=='0')
z++;
}
int x=0;
fr(i,n/2)
{
if(s[i]!=s[n-1-i])
{
f=0;
x++;
}
}
if(f)
{
if(z==1||z%2==0)
cout<<"BOB"<<endl;
else
cout<<"ALICE"<<endl;
}
else
{
if(x==1&&z==2)
cout<<"DRAW"<<endl;
else
cout<<"ALICE"<<endl;
}
}
signed main()
{
fast;
//freopen("input.txt", "rt", stdin);
//freopen("output.txt", "wt", stdout);
int t=1;
cin>>t;
int cas=1;
while(cas<=t)
{
//cout<<"Case #"<<cas<<": ";
shikhar7s(cas);
cas++;
}
return 0;
}
1527B2 - Palindrome Game (hard version)
Author: DenOMINATOR
Idea:DenOMINATOR
Editorial
Tutorial is loading...
Solution(Greedy) (DenOMINATOR)
#include<bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
string s;
cin >> s;
bool is_palindrome=1;
int cnt_0 = 0, cnt_1 = 0;
for(int i=0;i<n;i++){
cnt_0 += s[i]=='0';
}
for(int i=0;i<n/2;i++){
if(s[i]!=s[n-1-i]) is_palindrome = 0;
if( (s[i]=='1' || s[n-1-i]=='1') && s[i]!=s[n-1-i]){
cnt_1++;
}
}
if(is_palindrome){
if(cnt_0 == 1){
cout << "BOB\n";
return;
}
if(cnt_0%2){
cout << "ALICE\n";
return;
}
cout << "BOB\n";
return;
}
if(cnt_0==2 && cnt_1==1){
cout << "DRAW\n";
return;
}
cout << "ALICE\n";
return;
}
signed main()
{
int t;
cin >> t;
while(t--){
solve();
}
return 0;
}
Solution(DP) (DenOMINATOR)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
double pi = acos(-1);
#define _time_ 1.0 * clock() / CLOCKS_PER_SEC
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define all(a) a.begin(),a.end()
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
int dp[505][505][2][2];
void precompute(){
for(int i=0;i<=500;i++){
for(int j=0;j<=500;j++){
for(int k=0;k<2;k++){
for(int l=1;l>=0;l--){
dp[i][j][k][l] = 1e9;
}
}
}
}
dp[0][0][0][0]=0;
dp[0][0][0][1]=0;
for(int i=0;i<=500;i++){
for(int j=0;j<=500;j++){
for(int k=0;k<2;k++){
for(int l=1;l>=0;l--){
if(l==0 && j>0) dp[i][j][k][l] = min(dp[i][j][k][l],-dp[i][j][k][1]);
if(i>0) dp[i][j][k][l] = min(dp[i][j][k][l],1-dp[i-1][j+1][k][0]);
if(j>0) dp[i][j][k][l] = min(dp[i][j][k][l],1-dp[i][j-1][k][0]);
if(k==1) dp[i][j][k][l] = min(dp[i][j][k][l],1-dp[i][j][0][0]);
}
}
}
}
}
void solve(){
int n;
cin >> n;
string s;
cin >> s;
int cnt00=0,cnt01=0,mid=0;
for(int i=0;i<n/2;i++){
if(s[i]=='0' && s[i]==s[n-i-1]) cnt00++;
if(s[i]!=s[n-i-1]) cnt01++;
}
if(n%2 && s[n/2]=='0') mid=1;
if(dp[cnt00][cnt01][mid][0]<0){
cout << "ALICE";
}else if(dp[cnt00][cnt01][mid][0]>0){
cout << "BOB";
}else{
cout << "DRAW";
}
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#ifdef SIEVE
sieve();
#endif
#ifdef NCR
init();
#endif
precompute();
int t;
cin >> t;
while(t--){
solve();
cout << "\n";
}
return 0;
}
Author: sharabhagrawal25
Idea: rivalq
Editorial
Tutorial is loading...
Solution (sharabhagrawal25)
#include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int a[n];
for (int i = 0 ; i < n; i++){
cin >> a[i];
}
vector <long long> dp(n, 0);
map <long long,long long> value;
long long final_ans = 0;
for (long long i = 0 ; i < n ; i++){
if (i > 0) dp[i] = dp[i - 1];
if (value.count(a[i])){
dp[i] += value[a[i]];
}
value[a[i]] += (i + 1);
final_ans += dp[i];
}
cout << final_ans << endl;
}
}
Solution (mallick630)
t = int(input())
for j in range(t):
n = int(input())
a = list(map(int,input().split()))
value = {}
fa, ca = 0, 0
for i in range(n):
if a[i] in value:
ca += value[a[i]]
else:
value[a[i]]=0
value[a[i]] += i+1
fa += ca
print(fa)
Author: mallick630
Idea: CoderAnshu
Editorial
Tutorial is loading...
Solution (shikhar7s)
#include<bits/stdc++.h>
using namespace std;
#define int long long int
#define mp(a,b) make_pair(a,b)
#define vi vector<int>
#define mii map<int,int>
#define mpi map<pair<int,int>,int>
#define vp vector<pair<int,int> >
#define pb(a) push_back(a)
#define fr(i,n) for(i=0;i<n;i++)
#define rep(i,a,n) for(i=a;i<n;i++)
#define F first
#define S second
#define endl "\n"
#define Endl "\n"
#define fast std::ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define mod 1000000007
#define dom 998244353
#define sl(a) (int)a.length()
#define sz(a) (int)a.size()
#define all(a) a.begin(),a.end()
#define pii pair<int,int>
#define mini 2000000000000000000
#define time_taken 1.0 * clock() / CLOCKS_PER_SEC
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//const long double pi = acos(-1);
//mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());
//primes for hashing 937, 1013
template<typename T, typename U> static inline void amin(T &x, U y)
{
if (y < x)
x = y;
}
template<typename T, typename U> static inline void amax(T &x, U y)
{
if (x < y)
x = y;
}
vector<int> adj[200005];
int vis[200005],c[200005],t;
pii p[200005];
void dfs(int x)
{
vis[x]=1;
c[x]=1;
int i;
p[x]=mp(t,t);
t++;
fr(i,sz(adj[x]))
{
if(!vis[adj[x][i]])
{
dfs(adj[x][i]);
c[x]+=c[adj[x][i]];
p[x].S=p[adj[x][i]].S;
}
}
}
void shikhar7s(int cas)
{
int n,i;
cin>>n;
t=0;
fr(i,n)
{
vis[i]=0;
adj[i].clear();
}
int x,y;
fr(i,n-1)
{
cin>>x>>y;
adj[x].pb(y);
adj[y].pb(x);
}
dfs(0);
int ans=0;
fr(i,sz(adj[0]))
{
int x=c[adj[0][i]];
x=(x*(x-1))/2;
ans+=x;
}
cout<<ans<<" ";
int s=0,ss=0,got=1;
y=-1;
fr(i,sz(adj[0]))
{
int x=c[adj[0][i]];
if(p[adj[0][i]].F<=p[1].F&&p[adj[0][i]].S>=p[1].S)
{
y=adj[0][i];
x-=c[1];
}
if(adj[0][i]!=y)
got+=x;
s+=x;
x*=x;
ss+=x;
}
ans=(s*s-ss)/2;
ans+=s;
cout<<ans<<" ";
i=2;
int l=0,r=1,j,b=0;
while(i<n)
{
if((p[i].F<=p[l].F&&p[i].S>=p[l].S)||(p[i].F<=p[r].F&&p[i].S>=p[r].S))
{
cout<<0<<" ";
i++;
continue;
}
if(!l)
{
int f=2;
ss=c[r];
if(p[r].F<=p[i].F&&p[r].S>=p[i].S)
{
f=1;
ss-=c[i];
}
if(!(p[y].F<=p[i].F&&p[y].S>=p[i].S))
{
ans=1;
fr(j,sz(adj[0]))
{
int x=adj[0][j];
if(x==y)
continue;
int su=c[x];
if(p[x].F<=p[i].F&&p[x].S>=p[i].S)
{
f=0;
su-=c[i];
}
ans+=su;
}
}
else
ans=got;
ans*=ss;
cout<<ans<<" ";
if(!f)
l=i;
else if(f==1)
r=i;
else
{
i++;
b=1;
break;
}
}
else
{
int f=2;
s=c[l];
ss=c[r];
if(p[l].F<=p[i].F&&p[l].S>=p[i].S)
{
f=0;
s-=c[i];
}
if(p[r].F<=p[i].F&&p[r].S>=p[i].S)
{
f=1;
ss-=c[i];
}
ans=s*ss;
cout<<ans<<" ";
if(!f)
l=i;
else if(f==1)
r=i;
else
{
i++;
b=1;
break;
}
}
i++;
}
if(!b)
cout<<1<<" ";
else
{
while(i<=n)
{
cout<<0<<" ";
i++;
}
}
cout<<endl;
}
signed main()
{
fast;
//freopen("output.txt", "rt", stdin);
//freopen("output.txt", "wt", stdout);
int t=1;
cin>>t;
int cas=1;
while(cas<=t)
{
//cout<<"Case #"<<cas<<": ";
shikhar7s(cas);
cas++;
}
return 0;
}
Solution (the_nightmare)
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define pb push_back
#define ppb pop_back
#define endl '\n'
#define mii map<ll,ll>
#define msi map<string,ll>
#define mis map<ll, string>
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define repr(i,a,b) for(ll i=b-1;i>=a;i--)
#define trav(a, x) for(auto& a : x)
#define pii pair<ll,ll>
#define vi vector<ll>
#define vii vector<pair<ll, ll>>
#define vs vector<string>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define lbnd lower_bound
#define ubnd upper_bound
#define DEBUG cerr<<"/n>>>I'm Here<<</n"<<endl;
#define display(x) trav(a,x) cout<<a<<" ";cout<<endl;
#define what_is(x) cerr << #x << " is " << x << endl;
#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace __gnu_pbds;
using namespace std;
#define PI 3.141592653589793
#define N 200005
ll add(ll x,ll y){return (x+y)%hell;}
ll mul(ll x,ll y){return (x*y)%hell;}
vector <ll> adj[N];
ll subtree[N];
ll min1[N];
ll ans[N];
ll vis[N];
ll le;
int v;int u;
ll n;
int prevv;int prevu;
void init(){
rep(i,0,n){
adj[i].clear();
subtree[i]=0;
min1[i]=n;
ans[i]=0;
vis[i]=0;
}
le=n*(n-1)/2;
v=0;u=0;
prevv=-1;
prevu=-1;
}
void dfs(int v,int prev=-1){
subtree[v]=1;
min1[v]=v;
for (auto it: adj[v]){
if (it==prev) continue;
dfs(it,v);
subtree[v]+=subtree[it];
min1[v]=min(min1[v],min1[it]);
}
}
void find(int val){
//cout << v << " " << u << " " << prevv << " " << prevu << " " << val << endl;
if (v==val or u==val){
ll a,b;
if (subtree[prevv]>subtree[v] or prevv==-1) a=subtree[v];
else a=n-subtree[prevv];
if (subtree[prevu]>subtree[u] or prevu==-1) b=subtree[u];
else b=n-subtree[prevu];
ans[val]=le-a*b;
//cout << a << " " << b << endl;
le=a*b;
return;
}
for (auto it: adj[v]){
if (it==prevv) continue;
if (min1[it]==val){
if (v==u) prevu=it;
prevv=v;
v=it;
vis[it]=1;
find(val);
return;
}
}
for (auto it: adj[u]){
if (it==prevu) continue;
if (min1[it]==val){
prevu=u;
u=it;
vis[it]=1;
find(val);
return;
}
}
ans[val]=le;
le=0;
}
void solve()
{
cin >> n;
init();
rep(i,0,n-1){
int x,y;
cin >> x >> y;
adj[x].pb(y);
adj[y].pb(x);
}
dfs(0);
//cout << le << endl;
for (auto it: adj[0]) {ans[0]+=(subtree[it]*(subtree[it]-1))/2;}
//cout << endl;
//cout << ans[0] << endl;
le-=ans[0];
rep(i,1,n){
if (vis[i]==1 or le==0) ans[i]=0;
else find(i);
}
ans[n]=le;
rep(i,0,n+1) cout << ans[i] << " ";
cout << endl;
return;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen ("input.txt","r",stdin);
#endif
ll int TEST=1;
cin >> TEST;
while(TEST--)
{
solve();
}
}
Editorial
Tutorial is loading...
Solution (rivalq)
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define ll long long
//#define int long long
#define pb push_back
#define all(v) v.begin(),v.end()
#define endl "\n"
#define x first
#define y second
#define gcd(a,b) __gcd(a,b)
#define mem1(a) memset(a,-1,sizeof(a))
#define mem0(a) memset(a,0,sizeof(a))
#define sz(a) (int)a.size()
#define pii pair<int,int>
#define hell 1000000007
#define elasped_time 1.0 * clock() / CLOCKS_PER_SEC
template<typename T1,typename T2>istream& operator>>(istream& in,pair<T1,T2> &a){in>>a.x>>a.y;return in;}
template<typename T1,typename T2>ostream& operator<<(ostream& out,pair<T1,T2> a){out<<a.x<<" "<<a.y;return out;}
template<typename T,typename T1>T maxs(T &a,T1 b){if(b>a)a=b;return a;}
template<typename T,typename T1>T mins(T &a,T1 b){if(b<a)a=b;return a;}
const int N = 5e4+5;
struct node{
int a=0;
node (int val=0){
a=val;
}
void merge(node &n1,node &n2){
this->a=min(n1.a,n2.a);
}
};
struct update{
int val=0;
update(int t=0){
val=t;
}
void combine(update &par,int tl,int tr){
val+=par.val;
}
void apply(node &node){
node.a+=val;
val=0;
}
};
template<typename node,typename update>
struct segtree{
node t[4*N];
bool lazy[4*N];
update zaker[4*N];
int tl[4*N];
int tr[4*N];
node nul;
inline void pushdown(int v){
if(lazy[v]){
apply(zaker[v],v);
lazy[v]=0;
zaker[v].apply(t[v]);
}
}
inline void apply(update &u,int v){
if(tl[v]!=tr[v]){
lazy[2*v]=lazy[2*v+1]=1;
zaker[2*v].combine(u,tl[2*v],tr[2*v]);
zaker[2*v+1].combine(u,tl[2*v+1],tr[2*v+1]);
}
}
void build(int v,int start,int end,int arr[]){
tl[v]=start;
tr[v]=end;
lazy[v]=0;
zaker[v].val = 0;
if(start==end){
t[v].a=arr[start];
}
else{
int m=(start+end)/2;
build(2*v,start,m,arr);
build(2*v+1,m+1,end,arr);
t[v].merge(t[2*v],t[2*v+1]);
}
}
void zeno(int v,int l,int r,update val){
pushdown(v);
if(tr[v]<l || tl[v]>r)return;
if(l<=tl[v] && tr[v]<=r){
t[v].a+=val.val;
apply(val,v);
return;
}
zeno(2*v,l,r,val);
zeno(2*v+1,l,r,val);
t[v].merge(t[2*v],t[2*v+1]);
}
node query(int v,int l,int r){
if(tr[v]<l || tl[v]>r)return node(hell);
pushdown(v);
if(l<=tl[v] && tr[v]<=r){
return t[v];
}
node a=query(2*v,l,r);
node b=query(2*v+1,l,r);
node ans;
ans.merge(a,b);
return ans;
}
public:
node query(int l,int r){
return query(1,l,r);
}
void upd(int l,int r,update val){
return zeno(1,l,r,val);
}
};
segtree<node,update>seg;
int dp[101][N];
int solve(){
int n,k; cin >> n >> k;
vector<int>a(n+1);
rep(i,1,n+1){
cin >> a[i];
}
for(int i = 0; i <= n; i++){
for(int j = 0; j <= k; j++){
dp[j][i] = hell;
}
}
dp[0][0] = 0;
seg.build(1,0,n,dp[0]);
for(int j = 1; j <= k; j++){
vector<int>last(n+1);
dp[j][0] = 0;
for(int i = 1; i <= n; i++){
if(last[a[i]] == 0){
last[a[i]] = i;
}
else{
seg.upd(0,last[a[i]]-1,i-last[a[i]]);
last[a[i]] = i;
}
dp[j][i] = seg.query(0,i-1).a;
}
seg.build(1,0,n,dp[j]);
}
cout << dp[k][n] << endl;
//cout << elasped_time << endl;
return 0;
}
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//freopen("test.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#ifdef SIEVE
sieve();
#endif
#ifdef NCR
init();
#endif
int t=1;//cin>>t;
while(t--){
solve();
}
return 0;
}
Solution (the_nightmare)
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define pb push_back
#define ppb pop_back
#define endl '\n'
#define mii map<ll,ll>
#define msi map<string,ll>
#define mis map<ll, string>
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define repr(i,a,b) for(ll i=b-1;i>=a;i--)
#define trav(a, x) for(auto& a : x)
#define pii pair<ll,ll>
#define vi vector<ll>
#define vii vector<pair<ll, ll>>
#define vs vector<string>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define lbnd lower_bound
#define ubnd upper_bound
#define DEBUG cerr<<"/n>>>I'm Here<<</n"<<endl;
#define display(x) trav(a,x) cout<<a<<" ";cout<<endl;
#define what_is(x) cerr << #x << " is " << x << endl;
#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace __gnu_pbds;
using namespace std;
#define PI 3.141592653589793
#define MAXN 35005
int tree1[4*MAXN];
int lazy[4*MAXN];
int s[MAXN];
void build(int node, int start, int end)
{
lazy[node]=0;
if(start == end)
{
// Leaf node will have a single element
tree1[node] = s[start];
//cout << tree1[node] << " ";
}
else
{
int mid = (start + end) / 2;
// Recurse on the left child
build(2*node, start, mid);
// Recurse on the right child
build(2*node+1, mid+1, end);
// Internal node will have the sum of both of its children
tree1[node] = min(tree1[2*node],tree1[2*node+1]);
}
}
void updateRange(int node, int start, int end, int l, int r, int val)
{
if (l>r) return;
if(lazy[node] != 0)
{
// This node needs to be updated
tree1[node] = tree1[node]+lazy[node]; // Update it
if(start != end)
{
lazy[node*2] += lazy[node]; // Mark child as lazy
lazy[node*2+1] += lazy[node]; // Mark child as lazy
}
lazy[node] = 0; // Reset it
}
if(start > end or start > r or end < l) // Current segment is not within range [l, r]
return;
if(start >= l and end <= r)
{
// Segment is fully within range
tree1[node] = tree1[node]+val;
if(start != end)
{
// Not leaf node
lazy[node*2] += val;
lazy[node*2+1] += val;
}
return;
}
int mid = (start + end) / 2;
updateRange(node*2, start, mid, l, r, val); // Updating left child
updateRange(node*2 + 1, mid + 1, end, l, r, val); // Updating right child
tree1[node] = min(tree1[node*2],tree1[node*2+1]); // Updating root with max value
}
ll queryRange(int node, int start, int end, int l, int r)
{
if(start > end or start > r or end < l)
return hell; // Out of range
if(lazy[node] != 0)
{
// This node needs to be updated
tree1[node] = tree1[node]+lazy[node]; // Update it
if(start != end)
{
lazy[node*2] += lazy[node]; // Mark child as lazy
lazy[node*2+1] += lazy[node]; // Mark child as lazy
}
lazy[node] = 0; // Reset it
}
if(start >= l and end <= r) // Current segment is totally within range [l, r]
return tree1[node];
int mid = (start + end) / 2;
ll p1 = queryRange(node*2, start, mid, l, r); // Query left child
ll p2 = queryRange(node*2 + 1, mid + 1, end, l, r); // Query right child
return min(p1,p2);
}
void solve()
{
ll n,k;
cin >> n >> k;
int a[n];
rep(i,0,n) cin >> a[i];
int lastoc[n];
map <int,int> m1;
rep(i,0,n){
if (m1.find(a[i])==m1.end()) lastoc[i]=-1;
else lastoc[i]=m1[a[i]];
m1[a[i]]=i;
}
int dp[n][k+1];
dp[0][1]=0;
rep(i,1,n){
dp[i][1]=dp[i-1][1];
if (lastoc[i]!=-1) dp[i][1]+=i-lastoc[i];
}
rep(i,2,k+1){
rep(j,0,n) s[j]=dp[j][i-1];
build(1,0,n-1);
rep(j,0,i-1) dp[j][i]=hell;
dp[i-1][i]=0;
rep(j,i,n)
{
int lastj=lastoc[j];
if (lastj>0 and (i-2)<(lastj)) {
updateRange(1,0,n-1,i-2,lastj-1,j-lastj);
}
dp[j][i] = queryRange(1,0,n-1,i-2,j-1);
}
}
cout << dp[n-1][k] << endl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen ("input.txt","r",stdin);
#endif
ll int TEST=1;
//cin >> TEST;
//init();
while(TEST--)
{
solve();
}
}
}
contest was the_nightmare
haha, nice one XD
nightmare round
How to solve E using divide and conquer DP? (and especially how to maintain the cost around?)
link here is my code for divide and conquer technique
i took the idea from the code given below and understood it link
basically what we are doing here is we are maintaining a persistent segment tree on every ith index which will provide us with the information that if we consider a segment of [i,j] then what will be its cost. The basic idea here is to use segment tree with range updates and point query.You could see from my code how to update ranges its pretty straightforward.
now that we can find out the cost of any segment in log(n)complexity all we have to do is calculate the dp which can be calculated with the help of divide and conquer the only hard part of this method was the persistent segment tree part which was difficult to understand and actually think by yourself(atleast for me it was very new idea)
In problem B1, when all the elements of the string is 1, then how Bob wins?
It is given in the input section that string $$$s$$$ contains at least one $$$0$$$
But for this, why Draw is not the correct answer?
Yes, technically it should be DRAW but to avoid confusion we omitted that case
i have implemented dp for B2, but it's giving me incorrect output, pls help me find the bug
in case of 1100 why bob will win??
Alice can reverse
then bob has to do 1011
again Alice can reverse
and bob again has to do 1111
so Alice will win..
but initially it is pallin so alice can't reverse it!
1100 is pallin??
no, 1100 is not pallin so u can's reverse it at the first place alice had to put 1
orz
Does someone know of any problem similar to C?
what is the time complexity in B2 dp approach. 1.is it O(n^2) for one test case as it depends on no of 00 pairs and no of 01 pairs? 2.also if n^2 per test case how it passes the judge in 1 sec as n^2*t=1e9 ?
We precompute the dp and use it to answer all test cases
Dp is pre-computed not run for each test case
Alternative solution to A:
Keep doing $$$n=n$$$ & $$$(n-1)$$$ while $$$n$$$ & $$$(n-1)>0$$$. Print $$$n-1$$$.
I think this will TLE in python
It does not. PyPy 3 submission: 116877296
Yes, you can do that too, but it would take too much time and result in TLE
The complexity is logn for this so it won't TLE. At each iteration, you're setting at least 1 set bit to 0.
Hey! I am not able to understand why I am getting TLE for this solution :(
This is my submission : 116759121
ok when the number of zeros are even for example
isn't this optimal here every 4 changes means DRAW and extra 1,2,3 means BOB wins
And when zeros are odd:
Alice will change s[n/2] from '0' to '1' and play with the same strategy as Bob did in the above case. This way Bob will spend 1 dollar more than Alice resulting in Alice's win.
in this case every 2 means DRAW and its repeating pattern of pay1 as
AB BA AB BA
then if cnt_of_0 is odd and cnt_of_0/2 is odd we will have 1 zero extra which will be paid by B means ALICE wins.but if cnt_of_0/2 is even we will have 1 zero extra which will be paid by A means BOB wins.
PLEASEEEEE HELPPPPPPP!!
UPD:
Understood!!How to solve this.
Thanks everyoneActually, for example $$$000000$$$ game goes-
$$$A$$$ pay $$$1$$$ $$$100000$$$
$$$B$$$ pay $$$1$$$ $$$100001$$$
$$$A$$$ pay $$$1$$$ $$$100101$$$
$$$B$$$ pay $$$1$$$ $$$101101$$$
$$$A$$$ pay $$$1$$$ $$$111101$$$
$$$B$$$ reverse $$$101111$$$
$$$A$$$ pay $$$1$$$ $$$111111$$$
$$$B$$$ wins
Now, analyse $$$010101010$$$
example 0 0 0 0 0 0
A pay1 1 0 0 0 0 0
B pay1 1 0 0 0 0 1
A pay1 1 1 0 0 0 1
B pay1 1 1 0 0 1 1
A pay1 1 1 1 0 1 1
B reverse 1 1 0 1 1 1
A pay1 1 1 1 1 1 1
This is the optimal strategy discussed in the editorial. In each step except the last one, try to make the string palindrome again and in the last reverse the string. Yours is the same strategy I used during the contest but guess I needed to think more.
After spending about 20-25 minutes I understood the logic of problem C ( yes I'm still a noob), but I was wondering how does one come up with that logic during contests ( I know practice, practice practice) but I suck at dp and I've been trying to improve it, so if anyone has dp sheets that can build my foundation it'll be of great help thanks :), I've been doing classic dp problems like knapsack, longest common subsequence type questions and even started with matrix chain multiplication recently.
The states are easier to come up during contests if you really try to, most probably you just take what the problem asks and derive subtasks as a prefix, eg: Kadane-ish (or multiple prefixes across multiple sequences, eg: LCS), suffix, subarray of the original sequence, eg: matrix chain multiplication. I'm sure after a lot of $$$practice$$$, things would become somewhat more intuitive and reflexive.
Alternative solution to E:
First steps are also coming up with the $$$dp$$$ and writing the brute-force transition formula. Then, by considering $$$last(a_{r + 1})$$$, we can prove the following property:
Therefore, $$$c$$$ satisfies Quadrilateral Inequality, where a divide-and-conquer solution works in $$$O(nk\log n)$$$ time.
Note that calculating $$$c$$$ needs a two pointers trick similar to 868F - Yet Another Minimization Problem.
I am using divide and conquer dp optimization for problem E. can you help me why i am getting TLE code
$$$k$$$ should be enumerated from $$$optr$$$ to $$$optl$$$, not $$$mid$$$ to $$$optl$$$. Otherwise, the parameter optr is unused.
How to prove complexity of two pointers trick?
Anyone please, help me to understand..
For problem B1 help me to figure out the answer for this test case 00100
ALICE — 10100 BOB — 10101 ALICE- 10111 BOB — 11101 (REVERSE) ALICE — 11111
ALICE --> 3 BOB -->1 BOB WINS
Why it is not possible?
ALICE — 10100 BOB — 00101(REVERSE) ALICE- 10101 BOB — 11101 ALICE — 10111(REVERSE) BOB — 11111
ALICE --> 2 BOB -->2 DRAW
it's not that you can't do that . you can .But you know what , the word optimal is mentioned in the question, means if i got a chance to play then i tried my best to win , so if bob put a 1 in the string instead of reversing he will land in the winning position , instead of a draw. You can't just brute force and say bob or alice win or its a draw. its not mandiatory that if i have a chance to reverse the string then i have to reverse it , so that i will be relived from that 1 dollar penalty, you can't do that .
rivalq the_nightmare I am confused in the editorial for E. Aren't the k mentioned in the dp transitions and the k mentioned in the big oh notation different?
Yes they are different. The one in dp transitions you can regard as a temp variable.
Alice can win this way:
A pays -> 1001
B pays -> 1101
A reverses -> 1011
B pays -> 1111
B = 2 A = 1, so Alice wins. Bob has no other moves.
According to you Alice wins..But according to Jyotirmaya Bob wins...So what is the exact ans...Both of you correct.
Alice wants to win right? So she would do exactly what I stated. Bob has no other move than just to lose. It is not logical to make a move that will allow your oponent to win.
In fact , some users of the Chinese online judge : Luogu said that the difficulty of these problems is not monotonically increasing and they suggested that you should have changed the order of problem B and C. the_nightmare
There is only one additional case to be dealt in B2 if you look at the editorial. That would explain why they considered B2 as easier probably..
and dp is not what most div 2 contestants used.
Basically, we have to put together B1 and B2 due to contest restrictions due to which we are not able to swap B2 and C. But we have provided the scoring according to difficulty B(750+1500) total 2250 and C only 1500.
In problem D's editorial shouldn't it be "We will always break before or on reaching root" instead of "Note that we will always break at the root as it is marked visited in the initial step."
The term "Contiguous Subarray" is much more quicker to grasp than "Subsegment".
Hope future authors see this :) Nice Contest btw
but you know what you got something to learn.
I mixed subsegment with subsquence, and it wasted me lots of time to solve this problem in a wrong way
Could someone please write a simpler edit for Problem-C, I have gone over it a lot of times but am still confused as to why the question creator went for:
value[a[i]] += (i + 1);
please help me out with the logic. I understood the task but couldn't implement it that well and now I'm even more confused.
I think
(i+1)
refers to the total number of subarrays ending ati
. Since we are using0
indexing, so+1
for the adjustment.Consider and element
i
. Now if take an element j such thata[i]==a[j]
andj < i
then subarraya[j-i]
will occur as part of all subarray's fromi = 0 to j
i.e j + 1 times. Sovalue[a[i]] += i + 1
Oh now i get it, thank you so much
Happy to help
I was confused over this part. Thanks now,I got it.
Can someone help me with my solution :
My idea:
Maintain a path and its endpoints.
Maintain a 'visited' array which denotes whether or not this node is in current path.
Consider 0 as base case and mark it visited and initialize both the endpoints to 0.
Iterate from 0 to i
In order to find if there can be a path having all nodes [0, i] we just need to check if the endpoints of path having all of [0, i-1] can be extended to i, so move from ith node to its parent till we find a node that is in the path that includes the nodes [0, i-1], that is first visited node.
If this node happens to be one of the endpoints then extend the path and update endpoints else there can be no such path that includes all of [0, i] nodes and we dont need to check this for following i's.
I am unable to figure out why this gives TLE !
https://mirror.codeforces.com/contest/1527/submission/116924323
My code is giving wrong answer. Please someone help !!
include<bits/stdc++.h>
using namespace std;
int main(){
}
This is my logic, you can use to improve your code 116814530
Nice explanation of problem B2
Can someone give a small test for those codes which fail test case 5 by printing 1 instead of 0 at 1923rd position for problem D? Submission
I got that error by incorrectly calculating in the tree "0 -- 2 -- 1" the number of pairs with mex == 2 (there are 0).
In problem A I am getting
wrong output format Expected integer, but "2.68435e+008" found
What does the pow function in c++ return? In some previous questions also the I got WA because of pow function return type, so can anyone tell
how it works, what it return and what are its constraints
??pow()
returns a double, while the expected output is an integer, hence the WA. Also as anubh4v stated,pow()
(andlog2()
too) can be imprecise at times, leading to incorrect rounding of the number.I will keep that in mind. Thanks
Can someone explain me how does the dynamic programming solution for B2 works?
From my understanding of the problem when we consider alice we add positively, when we consider bob we add negatively. But how does that happen in code? How does the code distinguish bob from alice? And how does it simulate turns?
In other words: can someone explain me how the simulation of the game occurs during the bottom up transitions of the editorial / given code?
Thanks in advance.
Because dp[i][j][k][l] is the optimal answer for a state where i is the number of 00, j is the number of 01 or 10, and k = 1 denotes if the middle position in case of odd length string is 0 and l = 1 denotes that in the last turn other person reversed the sting thus we can not reverse.
For all the states, we will assume that the current turn is of Alice and to compute the answer for that state, we will add negative of the transition states, which will denote Bob's optimal score.
can anyone pls tell why i am getting time limit exceeded on test case 7 in problem D MEX TREE i am just doing a dfs traversal once to calculate subtree sizes and then iterating from 1 to n and marking not visited nodes as visited in my current path and calculating answer for each mex value.
my submission link https://mirror.codeforces.com/contest/1527/submission/116996030
In Problem D: as mentioned in the editorial that we need to "update the subtree sizes as we move up to parent recursively", we don't need to do this. When (l!=r) we will always choose the other parent. Only when we are calculating MEX1 (the previous l was equal to r) so we have to update the size of 0 subtree only once.
Yoir solution simplified the question mqnyfolds. Thanks anadii!
I do not know if this approach has been covered for E using divide and conquer dp. To get cost of current interval, maintain global 2 pointers on the array, sum variable and array of deque. Fit the pointer for each query. Amortized complexity over per level of dp should be N*log(N). So with K layers it becomes K*N*log(N).
the_nightmare's solution for D will TLE for the following case. https://drive.google.com/file/d/1K-1sb5ls2PP0lKiGQf5dy9BVuqMBvReG/view?usp=sharing
Problem 1527C - Sequence Pair Weight could have been done greedily (and imo it's easier). Let $$$d(x, y)$$$ denote the number of segments which contain elements at indices $$$x$$$ and $$$y$$$ (indices start from 0 so $$$x,y \in {0, 1, 2, \dots, n-1}$$$). It is easy to see that if $$$y > x$$$ then $$$d(x, y) = (x+1)*(n-y)$$$. This allows obvious $$$O(n^2)$$$ solution, but it can be done faster in $$$O(n)$$$. Let's say we have a vector $$$v$$$ and we are at it's $$$i$$$-th element.
Then, we can calculate the answer as:
which is just
and this can be simplified to:
Which you can easily calculate while iterating through the vector. Code: 124839948
Shouldn't it be
?
I think more short solution for A: https://mirror.codeforces.com/contest/1527/submission/127546267
in problem C let the array be, 1 3 1 2 1 when we take subarray ,
but according to editorial the weight of second one will be 3.
anyone please reply ?
I ran the same code. Its giving correct answer : 7
can you please explain me ? how is it possible
Check input format
Only necessary for C
Can anyone clear me this thing?
In the solution of B1 by DenOMINATOR, it says there will be no draw.It also says that if the number of "0" is even,BOB will always win. If it is the thing then explain me a test case,
let's think of string of even number of zero,,
let it be "0000" now ,Alice will make the string "1000",,and she will have 1 point. then,as it is not a palindrom,bob will just reverse it and his point is 0. now,alice cannot reverse it,so she will make it "1001" and she will have 2 point; thus,in the end ,bob will also have 2 point,as from the next step bob will start the game,,
now ,my question is,why it is not DRAW!!??
explain me please,if i am missing any point
First Alice will be forced to put a 1
Like in the case of 0000 , it will become 1000 and Alice would have had paid 1 dollar Following this , it would be beneficial for Bob to play 1 at the ending that is make it 1001 and Bob would have paid 1 dollar aswell
Current String : 1001 Bob : 1 dollar Alice : 1 dollar
Now Alice will be forced to put a 1 in, therefore the new string will be 1011
Current String : 1011 Bob : 1 dollar Alice : 2 dollar
Now Bob will reverse , therefore Alice will be forced to put Again
Current String : 1111 Bob : 1 dollar Alice : 3 dollar
Therefore Bob wins since he has used up less dollars.
Thank you