contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
sequencelengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample: | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
struct edge{int to,next;}E[maxn<<1];
int head[maxn],tot;
inline void add(int u,int v)
{
E[++tot]={v,head[u]};
head[u]=tot;
}
int nd;
int n,m,dfn[maxn],dep[maxn],top[maxn],times;
bool del[maxn];
vector<int> adin;
vector<int> V;
void predfs(int u,int fa)
{
dep[u]=dep[fa]+1;
V.push_back(u);
dfn[u]=++times;
top[u]=dep[u];
int cnt=0;
for(int i=head[u];i;i=E[i].next)
{
int v=E[i].to;
if(!dfn[v]){predfs(v,u);}
else if(dep[u]-dep[v]+1>=nd)
{
puts("2");
printf("%d\n",dep[u]-dep[v]+1);
//printf("%d %d %d\n",u,dep[u],top[u]);
for(int i=dep[v]-1;i<dep[u];i++)
printf("%d ",V[i]);
putchar('\n');
exit(0);
}
}
if(!del[u])
{
adin.push_back(u);
for(int i=head[u];i;i=E[i].next)
{
int v=E[i].to;
del[v]=1;
}
}
V.pop_back();
}
int main()
{
scanf("%d%d",&n,&m);
nd=sqrt(n-1)+1;
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v);add(v,u);
}
predfs(1,0);
puts("1");
for(int i=0;i<nd;i++)
printf("%d ",adin[i]);
return 0;
}
| cpp |
1303 | G | G. Sum of Prefix Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define the sum of prefix sums of an array [s1,s2,…,sk][s1,s2,…,sk] as s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk)s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk).You are given a tree consisting of nn vertices. Each vertex ii has an integer aiai written on it. We define the value of the simple path from vertex uu to vertex vv as follows: consider all vertices appearing on the path from uu to vv, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.InputThe first line contains one integer nn (2≤n≤1500002≤n≤150000) — the number of vertices in the tree.Then n−1n−1 lines follow, representing the edges of the tree. Each line contains two integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi), denoting an edge between vertices uiui and vivi. It is guaranteed that these edges form a tree.The last line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤1061≤ai≤106).OutputPrint one integer — the maximum value over all paths in the tree.ExampleInputCopy4
4 2
3 2
4 1
1 3 3 7
OutputCopy36
NoteThe best path in the first example is from vertex 33 to vertex 11. It gives the sequence [3,3,7,1][3,3,7,1], and the sum of prefix sums is 3636. | [
"data structures",
"divide and conquer",
"geometry",
"trees"
] | #include <bits/stdc++.h>
using i64 = std::int64_t;
using namespace std;
struct dp_hull {
// dp_hull enables you to do the following two operations in amortized O(log
// n) time:
// 1. Insert a pair (a_i, b_i) into the structure
// 2. For any value of x, query the maximum value of a_i * x + b_i
// All values a_i, b_i, and x can be positive or negative.
struct point {
i64 x, y;
point() : x(0), y(0) {}
point(i64 _x, i64 _y) : x(_x), y(_y) {}
};
struct segment {
point p;
mutable point next_p;
segment(point _p = {0, 0}, point _next_p = {0, 0})
: p(_p), next_p(_next_p) {}
bool operator<(const segment &other) const {
if (p.y == std::numeric_limits<i64>::max() / 2)
return p.x * (other.next_p.x - other.p.x) <=
other.p.y - other.next_p.y;
return make_pair(p.x, p.y) < make_pair(other.p.x, other.p.y);
}
};
set<segment> segments;
int size() const { return segments.size(); }
set<segment>::iterator prev(set<segment>::iterator it) const {
return it == segments.begin() ? it : --it;
}
set<segment>::iterator next(set<segment>::iterator it) const {
return it == segments.end() ? it : ++it;
}
static i64 floor_div(i64 a, i64 b) {
return a / b - ((a ^ b) < 0 && a % b != 0);
}
static bool bad_middle(const point &a, const point &b, const point &c) {
return floor_div(a.y - b.y, b.x - a.x) >=
floor_div(b.y - c.y, c.x - b.x);
}
bool bad(set<segment>::iterator it) const {
return it != segments.begin() && next(it) != segments.end() &&
bad_middle(prev(it)->p, it->p, next(it)->p);
}
void insert(const point &p) {
set<segment>::iterator next_it = segments.lower_bound(segment(p));
if (next_it != segments.end() && p.x == next_it->p.x) return;
if (next_it != segments.begin()) {
set<segment>::iterator prev_it = prev(next_it);
if (p.x == prev_it->p.x)
segments.erase(prev_it);
else if (next_it != segments.end() &&
bad_middle(prev_it->p, p, next_it->p))
return;
}
set<segment>::iterator it = segments.insert(next_it, segment(p, p));
while (bad(prev(it))) segments.erase(prev(it));
while (bad(next(it))) segments.erase(next(it));
if (it != segments.begin()) prev(it)->next_p = it->p;
if (next(it) != segments.end()) it->next_p = next(it)->p;
}
void insert(i64 a, i64 b) { insert(point(a, b)); }
// Queries the maximum value of ax + b.
i64 query(i64 x) const {
assert(size() > 0);
set<segment>::iterator it = segments.upper_bound(
segment(point(x, std::numeric_limits<i64>::max() / 2)));
return it->p.x * x + it->p.y;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<vector<int>> adj(n);
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
x--, y--;
adj[x].emplace_back(y);
adj[y].emplace_back(x);
}
vector<i64> val(n);
for (int i = 0; i < n; i++) cin >> val[i];
vector<int> siz(n), vis(n), maxSiz(n);
dp_hull hull;
int subtSiz = n;
int root = -1;
i64 ans = 0;
auto dfs1 = [&](auto self, int u, int fa) -> void {
siz[u] = 1;
maxSiz[u] = 0;
for (auto v : adj[u]) {
if (v == fa || vis[v]) continue;
self(self, v, u);
maxSiz[u] = max(maxSiz[u], siz[v]);
siz[u] += siz[v];
}
maxSiz[u] = max(maxSiz[u], subtSiz - siz[u]);
if (root == -1) root = u;
if (maxSiz[u] < maxSiz[root]) root = u;
};
auto dfs2 = [&](auto self, int u) -> void {
vis[u] = 1;
hull.segments.clear();
auto in = [&](auto self, int u, int fa, i64 sum, i64 psum,
int dep) -> void {
dep += 1;
sum += val[u];
psum += 1LL * dep * val[u];
int sumv = 0;
for (auto v : adj[u]) {
if (vis[v] || v == fa) continue;
sumv++;
self(self, v, u, sum, psum, dep);
}
if (sumv == 0) hull.insert(sum, psum);
};
auto out = [&](auto self, int u, int fa, i64 sum, i64 psum,
int dep) -> void {
dep += 1;
sum += val[u];
psum += sum;
int sumv = 0;
for (auto v : adj[u]) {
if (vis[v] || v == fa) continue;
sumv++;
self(self, v, u, sum, psum, dep);
}
if (hull.size() != 0 && sumv == 0)
ans = max(ans, hull.query(dep) + psum);
if (hull.size() == 0 && sumv == 0) {
ans = max(ans, psum);
}
};
for (auto v : adj[u]) {
if (vis[v]) continue;
out(out, v, u, val[u], val[u], 1);
in(in, v, u, 0, 0, 0);
}
if (hull.size() != 0)
ans = max(ans, hull.query(1) + val[u]);
else
ans = max(ans, val[u]);
hull.segments.clear();
for (auto it = adj[u].rbegin(); it != adj[u].rend(); it++) {
auto v = *it;
if (vis[v]) continue;
out(out, v, u, val[u], val[u], 1);
in(in, v, u, 0, 0, 0);
}
for (auto v : adj[u]) {
if (vis[v]) continue;
root = -1;
subtSiz = siz[v];
dfs1(dfs1, v, -1);
self(self, root);
}
};
dfs1(dfs1, 0, -1);
dfs2(dfs2, root);
cout << ans << endl;
return 0;
} | cpp |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | #include<bits/stdc++.h>
using namespace std;
int n,k,t,r,u,v,b[200010],h[200010],ans[200010];
struct node
{
int to,ne;
}a[1000010];
void add(int u,int v)
{
a[++t].to=v;
a[t].ne=h[u];
h[u]=t;
}
void work(int u,int bu,int s)
{
for(int i=h[u];i>0;i=a[i].ne)
{
if(a[i].to==bu)
{
continue;
}
s++;
if(s>r)
{
s=1;
}
ans[(i+1)/2]=s;
work(a[i].to,u,s);
}
}
int main()
{
cin>>n>>k;
for(int i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
b[u]++;
b[v]++;
add(u,v);
add(v,u);
}
sort(b+1,b+n+1);
r=b[n-k];
cout<<r<<endl;
work(1,0,0);
for(int i=1;i<n;i++)
{
cout<<ans[i]<<' ';
}
return 0;
} | cpp |
1305 | G | G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105) — the ages of the people.OutputOutput exactly one integer — the maximum possible combined gainings of all nn people.ExampleInputCopy3
1 2 3
OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it. | [
"bitmasks",
"brute force",
"dp",
"dsu",
"graphs"
] | /*
author : evenbao
created : 2020 / 03 / 06
*/
#include<bits/stdc++.h>
using namespace std;
#ifndef LOCAL
#define eprintf(...) fprintf(stderr , _VA_ARGS)
#else
#define eprintf(...) 42
#endif
// define evenbao
#define PII pair<int , int>
#define FI first
#define SE second
#define MP make_pair
typedef long long LL;
const int N = 2e5 + 10;
const int mx = (1 << 18);
int n;
int cnt[mx] , p[mx] , rnk[mx];
LL ans;
template <typename T> inline void chkmax(T &x , T y) { x = max(x , y); }
template <typename T> inline void chkmin(T &x , T y) { x = min(x , y); }
template <typename T> inline void read(T &x) {
T f = 1; x = 0;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
x *= f;
}
inline int get_root(int v) {
return (p[v] == v) ? v : (p[v] = get_root(p[v]));
}
inline int join(int u , int v) {
u = get_root(u) ,
v = get_root(v);
if (u != v) {
if (rnk[u] > rnk[v])
swap(u , v);
p[u] = v;
if (rnk[u] == rnk[v])
++rnk[v];
return 1;
} else return 0;
}
int main() {
read(n);
for (int i = 0; i < n; ++i) {
int val;
read(val);
ans -= val;
++cnt[val];
}
iota(p , p + mx , 0);
++cnt[0];
for (int e = mx - 1; e >= 0; --e)
for (int i = e; true; i = ((i - 1) & e)) {
if (cnt[i] && cnt[e ^ i] && join(i , e ^ i)) {
ans += (LL)(cnt[i] + cnt[e ^ i] - 1) * e;
cnt[i] = 1;
cnt[i ^ e] = 1;
}
if (i == 0) break;
}
printf("%lld\n" , ans);
return 0;
} | cpp |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | // LUOGU_RID: 101198123
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
using namespace std;
const int N = 5e3 + 10;
const int NN = N << 2;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
#define endl '\n'
#define int long long
typedef pair<int, int> PII;
int n;
string s;
void solve() {
cin >> n;
cin >> s;
string ans_s = s;
int ans_k = 1;
for (int k = n; k >= 1; --k) {
string s1 = s.substr(0, k - 1);
if ((n - k + 1) % 2 == 1)
reverse(s1.begin(), s1.end());
string s2 = s.substr(0 + k - 1);
string ss = s2 + s1;
if (ss <= ans_s)
ans_s = ss, ans_k = k;
}
cout << ans_s << endl;
cout << ans_k << endl;
}
signed main() {
// ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T = 1;
cin >> T;
while (T--) {
solve();
}
return 0;
} | cpp |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | // Problem: C. World of Darkraft: Battle for Azathoth
// Contest: Codeforces - Codeforces Round #625 (Div. 1, based on Technocup 2020 Final Round)
// URL: https://codeforces.com/contest/1320/problem/C
// Memory Limit: 512 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("avx,avx2,sse,sse2")
#include<bits/stdc++.h>
#define all(x) begin(x), end(x)
using namespace std;
using ll = long long;
template<typename F>
void multitest(F func) {
int t;
cin >> t;
while(t--) func();
}
void report(int ok) {
cout << (ok?"YES":"NO") << '\n';
}
#define int long long
const int inf = 1ll<<31;
struct Seg {
int n;
vector<int> mx, add;
Seg(vector<array<int, 2>> armor) {
n = 1;
while(n < armor.size()) n *= 2;
mx.resize(2*n, -inf);
add.resize(2*n, 0);
for(int i = 0; i < armor.size(); i++)
mx[n + i] = -armor[i][1];
for(int i = n; i--;) {
mx[i] = max(mx[2*i], mx[2*i+1]);
}
}
void upd(int p) {
while(p /= 2)
mx[p] = max(mx[2*p], mx[2*p+1]) + add[p];
}
void update(int l, int r, int v) {
int L = l + n, R = r + n;
for(l = L, r = R; l < r; l>>=1, r>>=1) {
if(l & 1) {
mx[l] += v;
add[l] += v;
l++;
}
if(r & 1) {
--r;
mx[r] += v;
add[r] += v;
}
}
if(L < R) {
upd(L);
upd(R-1);
}
}
int getMax() { return mx[1]; }
};
signed main() {
cin.tie(0)->sync_with_stdio(0);
//multitest([&](){});
int n, m, p;
cin >> n >> m >> p;
vector<array<int, 2>> weapons(n);
for(auto &[a, c] : weapons)
cin >> a >> c;
vector<array<int, 2>> armor(m);
for(auto &[b, c] : armor)
cin >> b >> c;
vector<array<int, 3>> monsters(p);
for(auto &[x, y, z] : monsters)
cin >> x >> y >> z;
sort(all(weapons));
sort(all(armor));
sort(all(monsters));
Seg profit(armor);
int m_ptr = 0, ans = -inf;
for(auto [a, cost] : weapons) {
while(m_ptr < monsters.size() &&
monsters[m_ptr][0] < a) {
int R = lower_bound(all(armor), array{monsters[m_ptr][1], inf}) - armor.begin();
profit.update(R, armor.size(), monsters[m_ptr][2]);
// cout << "Add " << m_ptr << " " << R << " " << monsters[m_ptr][2] << endl;
m_ptr++;
}
// cout << a << " " << profit.getMax() << endl;
ans = max(ans, profit.getMax() - cost);
}
cout << ans << '\n';
}
| cpp |
1284 | E | E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213 | [
"combinatorics",
"geometry",
"math",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define X first
#define ll __int128
#define int long long
#define Y second
#define pii pair<int, int>
#define SZ(a) ((int)a.size())
#define ALL(v) v.begin(), v.end()
#define pb push_back
#define eb emplace_back
#define push emplace
#define lb(x, v) lower_bound(ALL(x), v)
#define ub(x, v) upper_bound(ALL(x), v)
#define re(x) reverse(ALL(x))
#define uni(x) x.resize(unique(ALL(x)) - x.begin())
#define inf 1000000000
#define INF 1000000000000000000
#define mod 1000000007
#define get_bit(x, y) ((x>>y)&1)
#define mkp make_pair
#define IO ios_base::sync_with_stdio(0); cin.tie(0);
#ifdef loli
void trace_() {cerr << "\n";}
template<typename T1, typename... T2> void trace_(T1 t1, T2... t2) {cerr << ' ' << t1; trace_(t2...); }
#define trace(...) cerr << "[" << #__VA_ARGS__ << "] :", trace_(__VA_ARGS__);
#else
#define trace(...) 49
#endif
#define x first
#define y second
#define point pii
point pt[2501];
point operator + (point a, point b) {
return point(a.x + b.x, a.y + b.y);
}
point operator - (point a, point b) {
return point(a.x - b.x, a.y - b.y);
}
inline int cross(point a, point b) {
return a.x * b.y - a.y * b.x;
}
int sgn(point a) {
if (a.X >= 0 and a.Y >= 0) return 1;
if (a.X <= 0 and a.Y >= 0) return 2;
if (a.X <= 0 and a.Y <= 0) return 3;
return 4;
}
point o;
bool cmp(point a, point b) {
a = a - o;
b = b - o;
if (sgn(a) == sgn(b)) return cross(a, b) >= 0;
return sgn(a) < sgn(b);
}
ll C4(ll x) {
return (x * (x - 1) * (x - 2) * (x - 3) / 24);
}
int n;
inline void solve() {
cin >> n;
for (int i = 0; i < n; i++) cin >> pt[i].x >> pt[i].y;
ll ans = 0;
for (int c = 0; c < n; c++) {
o = pt[c];
vector<point> v;
for (int i = 0; i < n; i++) if (i != c) v.eb(pt[i]);
sort(ALL(v), cmp);
for (int i = 0; i < n - 1; i++) v.eb(v[i]);
int j = -1;
ll add = 0, prv = 0, res = C4(n - 1);
for (int i = 0; i < n - 1; i++) {
j = max(j, i - 1);
while (j + add + 1 < SZ(v) and (cross(v[j + add + 1] - v[i], o - v[i]) > 0 or (j + add + 1) == i)) add++;
prv = j - i + 1;
ll sub = j - n + 2;
if (sub < 0) sub = 0;
j += add;
if (add + prv >= 4) res -= C4(add + prv);
if (prv >= 4) res += C4(prv);
if (j - n + 2 >= 4) res += C4(j - n + 2);
if (sub >= 4) res -= C4(sub);
add = 0;
}
ans += res;
}
int out = ans;
cout << out << '\n';
}
signed main() {
IO;
solve();
} | cpp |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | #include <bits/stdc++.h>
#define itn long long
#define int long long
#define double long double
//#define endl '\n'
#define p_b push_back
#define fi first
#define se second
#define pii std::pair<int, int>
#define oo LLONG_MAX
#define big INT_MAX
#define elif else if
using namespace std;
int input()
{
int x;
cin>>x;
return x;
}
void solve()
{
int x, s;
cin>>x>>s;
if(x>s)
{
cout<<-1;
return;
}
if(s==0)
{
cout<<0;
return;
}
if((s-x)%2!=0)
{
cout<<-1;
return;
}
if(s==x)
{
cout<<1<<endl<<s;
return;
}
itn p=(s-x)/2;
if((x&p)==0)
{
cout<<2<<endl<<(p|x)<<' '<<p;
return;
}
cout<<3<<endl<<p<<' '<<p<<' '<<x;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// freopen("network.in", "r", stdin);
// freopen("magic.txt", "w", stdout);
int t=1;
// cin>>t;
while(t--)
{
solve();
cout<<endl<<endl;
}
}
| cpp |
13 | D | D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7 | [
"dp",
"geometry"
] | #include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=505;
struct Point
{
int x,y;
Point(){};
Point(int _x,int _y)
{
x=_x,y=_y;
}
Point operator-(const Point &b)const
{
return Point(x-b.x,y-b.y);
}
ll operator*(const Point &b)const
{
return (ll)x*b.y-(ll)y*b.x;
}
}a[maxn],b[maxn];
int n,m,dp[maxn][maxn];
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)scanf("%d%d",&a[i].x,&a[i].y);
for(int i=1;i<=m;i++)scanf("%d%d",&b[i].x,&b[i].y);
a[0]=Point(-1e9-1,-1e9-1);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if((a[i]-a[0])*(a[j]-a[0])<=0)continue;
for(int k=1;k<=m;k++)
if((a[i]-a[0])*(b[k]-a[0])>=0&&(a[j]-a[i])*(b[k]-a[i])>=0&&(b[k]-a[0])*(a[j]-a[0])>=0)
dp[i][j]++;
dp[j][i]=-dp[i][j];
}
int ans=0;
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
for(int k=j+1;k<=n;k++)
if(dp[i][j]+dp[k][i]+dp[j][k]==0)
ans++;
printf("%d\n",ans);
return 0;
} | cpp |
1286 | C1 | C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"interactive",
"math"
] | // Problem: C1. Madhouse (Easy version)
// Contest: Codeforces - Codeforces Round #612 (Div. 1)
// URL: https://codeforces.com/contest/1286/problem/C1
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
#define rep(i, a, b) for(int i = (a); i <= (b); i ++)
#define per(i, a, b) for(int i = (a); i >= (b); i --)
#define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt)
using namespace std;
inline int read() {
int x = 0, f = 1; char c = getchar();
while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar();
while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar();
return x * f;
}
multiset<string> st;
int main() {
int n = read();
printf("? %d %d\n", 1, n);
fflush(stdout);
rep(i, 1, n * (n + 1) / 2) {
string s; cin >> s;
sort(s.begin(), s.end());
st.insert(s);
}
if(n == 1) {
printf("! "); cout << * st.begin() << endl;
fflush(stdout);
return 0;
}
printf("? %d %d\n", 2, n);
fflush(stdout);
rep(i, 1, n * (n - 1) / 2) {
string s; cin >> s;
sort(s.begin(), s.end());
st.erase(st.find(s));
}
string pre[110]; int cnt = 0;
for(string o : st) pre[++ cnt] = o;
sort(pre + 1, pre + cnt + 1, [](string x, string y) {return x.length() < y.length();});
int cnt1[30], cnt2[30];
string ans = pre[1];
rep(i, 1, n - 1) {
rep(j, 0, 25) cnt1[j] = cnt2[j] = 0;
for(auto o : pre[i]) cnt1[o - 'a'] ++;
for(auto o : pre[i + 1]) cnt2[o - 'a'] ++;
rep(j, 0, 25) if(cnt1[j] != cnt2[j]) {
ans += j + 'a';
break;
}
}
printf("! "); cout << ans << endl;
fflush(stdout);
return 0;
}
| cpp |
1304 | F1 | F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp"
] | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
//#include<boost/algorithm/string.hpp>
//pragmas
#pragma GCC optimize("O3")
//types
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define ll int
#define ull unsigned long long int
#define vec vector<long long int>
#define pall pair<long long int, long long int>
#define vecpair vector<pair<long long int,long long int>>
#define vecvec(a, i, j) vector<vector<long long int>> a (i, vec (j, 0))
#define vecvecvec(a, i, j, k) vector<vector<vector<long long int>>> dp (i + 1, vector<vector<long long int>>(j + 1, vector<long long int>(k + 1, 0)))
using namespace std;
using namespace __gnu_pbds;
//random stuff
#define all(a) a.begin(),a.end()
#define read(a) for (auto &x : a) cin >> x
#define endl "\n"
#define print(a) for(auto x : a) cout << x << " "; cout << endl
#define sp " "
// ll INF = 9223372036854775807;
typedef tree<long long int, null_type, less<long long int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
#define safe_map unordered_map<long long, int, custom_hash>
//debug
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#define reach cerr<<"reached"<<endl
#else
#define debug(x...)
#define reach
#endif
/*---------------------------------------------------------------------------------------------------------------------------*/
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3
ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b
ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}
bool revsort(ll a, ll b) {return a > b;}
void swap(int &x, int &y) {int temp = x; x = y; y = temp;}
ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}
void google(int t) {cout << "Case #" << t << ": ";}
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (ll j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
ll mod_add(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mod_mul(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll mod_sub(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mod_div(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m
ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))
void precision(int a) {cout << setprecision(a) << fixed;}
ll ceil_div(ll x, ll y){return (x + y - 1) / y;}
unsigned long long power(unsigned long long x,ll y, ll p){unsigned long long res = 1;x = x % p; while (y > 0){if (y & 1)res = (res * x) % p;y = y >> 1;x = (x * x) % p;}return res;}
unsigned long long modInverse(unsigned long long n,int p){return power(n, p - 2, p);}
ll nCr(ll n,ll r, ll p){if (n < r)return 0;if (r == 0)return 1;unsigned long long fac[n + 1];fac[0] = 1;for (int i = 1; i <= n; i++)fac[i] = (fac[i - 1] * i) % p;return (fac[n] * modInverse(fac[r], p) % p* modInverse(fac[n - r], p) % p)% p;}
ll accumulate(const vec &nums){ll sum = 0; for(auto x : nums) sum += x; return sum;}
// ll tmax(ll a, ll b, ll c = 0, ll d = -INF, ll e = -INF, ll f = -INF){return max(a, max(b, max(c, max(d, max(e, f)))));}
/*--------------------------------------------------------------------------------------------------------------------------*/
ll forest[55][20002], dp[55][20002], pref[55][20002];
//code starts
int main()
{
fastio();
ll n, m, k;
cin >> n >> m >> k;
for(ll i = 1; i <= n; i ++)
{
cin >> forest[i][1];
pref[i][1] = forest[i][1];
for(ll j = 2; j <= m; j ++)
{
cin >> forest[i][j];
pref[i][j] = pref[i][j - 1] + forest[i][j];
}
}
// dp[1][] manually
for(ll j = 1; j <= m - k + 1; j ++)
dp[1][j] = pref[1][j + k - 1] - pref[1][j - 1] + ((n - 1) ? pref[2][j + k - 1] - pref[2][j - 1] : 0);
ll lmax[m - k + 1], rmax[m - k + 1];
lmax[1] = dp[1][1];
for(ll j = 2; j <= m - k + 1; j ++) lmax[j] = max(lmax[j - 1], dp[1][j]);
rmax[m - k + 1] = dp[1][m - k + 1];
for(ll j = m - k; j >= 1; j --) rmax[j] = max(rmax[j + 1], dp[1][j]);
for(ll i = 2; i <= n; i ++)
{
for(ll j = 1; j <= m - k + 1; j ++)
{
ll cur = pref[i][j + k - 1] - pref[i][j - 1] + pref[i + 1][j + k - 1] - pref[i + 1][j - 1];
if(j - k >= 1) dp[i][j] = max(dp[i][j], cur + lmax[j - k]);
if(j + k <= m - k + 1) dp[i][j] = max(dp[i][j], cur + rmax[j + k]);
for(ll p = max(1, j - k + 1); p <= min(m - k + 1, j + k - 1); p ++)
{
ll l, r;
ll now = dp[i - 1][p] + pref[i][j + k - 1] - pref[i][j - 1] + pref[i + 1][j + k - 1] - pref[i + 1][j - 1];
l = max(j, p), r = min(j + k - 1, p + k - 1);
if(l <= r) now -= pref[i][r] - pref[i][l - 1];
dp[i][j] = max(dp[i][j], now);
}
}
lmax[1] = dp[i][1];
for(ll j = 2; j <= m - k + 1; j ++) lmax[j] = max(lmax[j - 1], dp[i][j]);
rmax[m - k + 1] = dp[i][m - k + 1];
for(ll j = m - k; j >= 1; j --) rmax[j] = max(rmax[j + 1], dp[i][j]);
}
cout << lmax[m - k + 1] << endl;
}
// There is an idea of a Patrick Bateman. Some kind of abstraction.
// But there is no real me. Only an entity. Something illusory.
// And though I can hide my cold gaze, and you can shake my hand and
// feel flesh gripping yours, and maybe you can even sense our lifestyles
// are probably comparable, I simply am not there. | cpp |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
#define ll long long
#define pb push_back
using namespace std;
const int N=2e5+20;
int t, cnt, ans;
string s;
void solve() {
cin >> s;
ans=0;
cnt=0;
for(int i=0; i < s.size(); i++) {
if(s[i]=='L') cnt++;
else cnt=0;
ans=max(ans, cnt);
}
cout << ans+1;
}
int main()
{
cin >> t;
while(t--)
{
solve();
cout << '\n';
}
}
| cpp |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | [
"math"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int32_t test; cin >> test;
int64_t x, y, a, b, d;
while (test--)
{
cin >> x >> y >> a >> b;
d = y-x;
if ((d/(a+b))*a+(d/(a+b))*b == d)
cout << d/(a+b) << '\n';
else cout << "-1\n";
}
return 0;
} | cpp |
1313 | D | D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third. | [
"bitmasks",
"dp",
"implementation"
] | // LUOGU_RID: 98031196
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
typedef long long ll;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
vector<pair<int,int> >a;
typedef pair<int,int> pii;
int f[1<<8],vis[maxn],n;
signed main()
{
int tm1,tm2;
cin>>n>>tm1>>tm2;
for(int i=1,l,r;i<=n;i++)
{
cin>>l>>r;
pii s1,s2;
s1.first=l, s1.second=i;
s2.first=r+1,s2.second=-i;
a.push_back(s1),a.push_back(s2);
}
sort(a.begin(),a.end());
for (int i = 1; i < 256; i++) f[i] = -inf;
for(int u=0;u<a.size();u++)
{
int id=a[u].second,len,k;
if(u==a.size()-1) len=0;
else len=a[u+1].first-a[u].first;
if(id>0)//左端点
{
for(int i=0;i<8;i++)
{
if(!vis[i])
{
k=i,vis[i]=id;
break;
}
}
for(int i=255;i>=0;i--)
{
if((i>>k)&1) f[i]=f[i^(1<<k)]+len*__builtin_parity(i);
else f[i]=f[i]+len*__builtin_parity(i);
}
}
else
{
for(int i=0;i<8;i++)
{
if(vis[i]==-id)
{
k=i,vis[k]=0;
break;
}
}
for(int i=0;i<256;i++)
{
if ((i>>k)&1) f[i]=-inf;
else f[i]=max(f[i],f[i^(1<<k)])+len*__builtin_parity(i);
}
}
}
cout<<f[0]<<endl;
return 0;
} | cpp |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, a, b, k;
cin >> n >> a >> b >> k;
vector<int> h(n);
for (int i = 0; i < n; ++i) {
cin >> h[i];
h[i] %= a + b;
if (h[i] == 0) h[i] += a + b;
h[i] = ((h[i] + a - 1) / a) - 1;
}
sort(h.begin(), h.end());
int ans = 0;
for (int i = 0; i < n; ++i) {
if (k - h[i] < 0) break;
++ans;
k -= h[i];
}
cout << ans << endl;
return 0;
} | cpp |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define float double
signed main(){
int t=1;
cin>>t;
while(t--){
int n;
cin>>n;
map<int,pair<int,int>> mp;
string ans="YES",line="";
for(int i=0;i<n;i++){
int a,b;cin>>a>>b;
pair<int,int> pa;
auto it=mp.find(a);
if(it==mp.end()){
pa={b,b};
mp[a]=pa;
}
else{
pa={min(mp[a].first,b),max(mp[a].second,b)};
mp[a]=pa;
}
}
int x=0,y=0;
for(auto it=mp.begin();it!=mp.end();it++){
int a=(*it).first,b_min=(*it).second.first,b_max=(*it).second.second;
if(b_min<y){ans="NO";break;}
while(a>x){x++;line+='R';}
while(b_max>y){line+='U';y++;}
}
cout<<ans<<endl;
if(ans=="NO")continue;
cout<<line<<endl;
}
return 0;
} | cpp |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | #include<bits/stdc++.h>
#define int long long
#define fa(i,a,n) for(int i=a;i<n;i++)
#define pb push_back
#define bp pop_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define vi vector<int>
#define faster ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
void solve(){
int a,b;
cin >> a >> b;
int cnt=0,ans;
map<int,int> m;
while(b>0)
{
m[b%10]++;
b/=10;
cnt++;
}
if(m[9]==cnt)
{
ans=cnt;
}
else
{
ans=cnt-1;
}
cout << (a*ans) << endl;
return;
}
signed main()
{
faster;
int t=1;
cin>>t;
while(t--)
solve();
} | cpp |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105) — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
const int maxn=2*1e5+11;
const int Maxx=5*1e5+11;
const int mod=1e9+7;
int t;
string s;
int q;
int l,r;
int pre[maxn][30];
void solve()
{
cin>>s;
for(int i=0;i<s.size();++i)
{
for(int j=1;j<=26;++j) pre[i+1][j]=pre[i][j];
++pre[i+1][int(s[i]-'a')+1];
}
cin>>q;
while(q--)
{
cin>>l>>r;
--l,--r;
if(s[l]!=s[r])
{
cout<<"Yes"<<endl;continue;
}
if(l==r) {cout<<"Yes"<<endl;continue;}
++l,++r;
int num=0;
for(int i=1;i<=26;++i)
{
if(pre[r][i]-pre[l-1][i]) ++num;
}
if(num>=3) {cout<<"Yes"<<endl;continue;}
else {cout<<"No"<<endl;continue;}
}
}
int main()
{
//scanf("%d",&t);
ios::sync_with_stdio(false);cin.tie(0);
//ios::sync_with_stdio(false);cin.tie(0);cin>>t;while(t--)
solve();
return 0;
} | cpp |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int t, a, b, x, y;
cin.tie(0), ios::sync_with_stdio(0);
cin >> t;
while (t--) {
cin >> a >> b >> x >> y;
cout << max(max(x, a-x-1)*b,max(y,b-y-1)*a) << '\n';
}
} | cpp |
1141 | A | A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272. | [
"implementation",
"math"
] | #include<iostream>
#include<iterator>
#include<ranges>
void solve_test_case();
int main()
{
unsigned t{ 1 };
do
solve_test_case();
while (--t);
}
void solve_test_case()
{
unsigned n, m;
std::cin >> n >> m;
if (m % n)
std::cout << "-1" << std::endl;
else {
m /= n;
unsigned c{};
while (!(m & 1))
++c,
m >>= 1;
while (!(m % 3))
++c,
m /= 3;
if (m == 1)
std::cout << c << std::endl;
else
std::cout << "-1" << std::endl;
}
} | cpp |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | // LUOGU_RID: 100771727
#define poj
//#define zcz
#ifdef poj
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<ctime>
#include<cstring>
#include<algorithm>
#include<queue>
#include<set>
#include<vector>
#include<map>
#include<string>
#include<stack>
#include<map>
#else
#include<bits/stdc++.h>
#endif
using namespace std;
#ifdef zcz
class fastin{
private:
#ifdef poj
static const int MAXBF=1<<20;
#else
const int MAXBF=1<<27;
#endif
FILE *inf;
char *inbuf,*inst,*ined;
inline char _getchar(){
if(inst==ined)inst=inbuf,ined=inbuf+fread(inbuf,1,MAXBF,inf);
return inst==ined?EOF:*inst++;
}
public:
fastin(FILE*_inf=stdin){
inbuf=new char[MAXBF],inf=_inf,inst=inbuf,ined=inbuf;
}
~fastin(){delete inbuf;}
template<typename Int> fastin&operator>>(Int &n){
static char c;
Int t=1;
while((c=_getchar())<'0'||c>'9')if(c=='-')t=-1;
n=(c^48);
while((c=_getchar())>='0'&&c<='9')n=(n<<3)+(n<<1)+(c^48);
n*=t;
return*this;
}
fastin&operator>>(char*s){
int t=0;
static char c;
while((c=_getchar())!=' '&&c!='\n')s[t++]=c;
s[t]='\0';
return *this;
}
}fi;
class fastout{
private:
#ifdef poj
static const int MAXBF=1<<20;
#else
const int MAXBF=1<<27;
#endif
FILE *ouf;
char *oubuf,*oust,*oued;
inline void _flush(){fwrite(oubuf,1,oued-oust,ouf);}
inline void _putchar(char c){
if(oued==oust+MAXBF)_flush(),oued=oubuf;
*oued++=c;
}
public:
fastout(FILE*_ouf=stdout){
oubuf=new char[MAXBF],ouf=_ouf,oust=oubuf,oued=oubuf;
}
~fastout(){_flush();delete oubuf;}
template<typename Int> fastout&operator<<(Int n){
if(n<0)_putchar('-'),n=-n;
static char S[20];
int t=0;
do{S[t++]='0'+n%10,n/=10;}while(n);
for(int i=0;i<t;++i)_putchar(S[t-i-1]);
return*this;
}
fastout&operator<<(char c){_putchar(c);return *this;}
fastout&operator<<(char*s){
for(int i=0;s[i];++i)_putchar(s[i]);
return *this;
}
}fo;
#define cin fi
#define cout fo
#else
#define czc ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#endif
#define mod 1000000007
#define ll long long
#define isinf 0x3f3f3f3f
#define ilinf 0x7fffffff
#define lsinf 0x3f3f3f3f3f3f3f3f
#define llinf 0x7fffffffffffffff
int n,f[1010][1010],g[1000],u,v,vis[1010];
queue<int> q;
int main(){
// #ifndef zcz
// czc;
// #endif
cin>>n;
for(int i=1;i<n;i++){
cin>>u>>v;
f[u][v]=f[v][u]=1;
++g[u];++g[v];
}
for(int i=1;i<=n;i++){
if(g[i]==1)q.push(i);
}
while(q.size()>=2){
u=q.front();q.pop();
v=q.front();q.pop();
vis[u]=vis[v]=1;
cout<<"? "<<u<<' '<<v<<'\n';
cout.flush();
int lca;
cin>>lca;
if(lca==u||lca==v){
cout<<"! "<<lca;
return 0;
}
for(int i=1;i<=n;i++){
if(f[u][i]){
g[i]--;
if(g[i]==1)q.push(i);
}
if(f[v][i]){
g[i]--;
if(g[i]==1)q.push(i);
}
}
}
for(int i=1;i<=n;i++)if(!vis[i]){
cout<<"! "<<i<<'\n';
return 0;
}
return 0;
} | cpp |
1286 | D | D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2
1 1 100
3 1 0
OutputCopy1
InputCopy3
7 10 0
9 4 86
14 5 100
OutputCopy0
InputCopy4
6 4 50
11 25 50
13 16 50
15 8 50
OutputCopy150902884
| [
"data structures",
"math",
"matrices",
"probabilities"
] | // LUOGU_RID: 101728700
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 100001
#define yu (998244353)
inline ll ksm(ll x,ll y){
ll an=1;
for(;y;y>>=1){
if(y&1)an=an*x%yu;
x=x*x%yu;
}return an;
}inline ll ni(ll x){return ksm(x,yu-2);}
ll n;
ll x[N],v[N],p[N];
ll xu[N];
struct juz{
ll a[3][3],n,m;
juz(){
memset(a,0,sizeof(a));return;
}
inline juz operator*(const juz &x){
juz t;t.n=n;t.m=x.m;
for(int i=1;i<=n;i++){
for(int j=1;j<=t.m;j++){
for(int k=1;k<=m;k++){
t.a[i][j]=(t.a[i][j]+a[i][k]*x.a[k][j])%yu;
}
}
}return t;
}
};
juz sum[N<<2],a[N];
inline void pushup(ll o){
sum[o]=sum[o<<1]*sum[o<<1|1];
return ;
}
inline void build(ll o,ll l,ll r){
if(l==r){sum[o]=a[l];return ;}
ll mid=(l+r)>>1;
build(o<<1,l,mid);build(o<<1|1,mid+1,r);
pushup(o);
return ;
}
inline void update(ll o,ll l,ll r,ll x){
if(l==r){
sum[o]=a[l];return ;
}ll mid=(l+r)>>1;
if(mid>=x)update(o<<1,l,mid,x);
else update(o<<1|1,mid+1,r,x);
pushup(o);
return ;
}
inline juz ask(ll o,ll l,ll r,ll x,ll y){
if(x<=l&&r<=y)return sum[o];
ll mid=(l+r)>>1;
if(mid>=x&&mid>=y)return ask(o<<1,l,mid,x,y);
if(mid<x&&mid<y)return ask(o<<1|1,mid+1,r,x,y);
return ask(o<<1,l,mid,x,y)*ask(o<<1|1,mid+1,r,x,y);
}
inline void add(ll &x,ll y){x+=y;if(x>=yu)x-=yu;return ;}
#define T pair<double,ll>
#define mk make_pair
#define fi first
#define se second
T t[N<<1];
ll cn=0;
int main()
{
// freopen("test1.in","r",stdin);
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>n;for(int i=1;i<n;i++)xu[i]=i;ll xs=ni(100);
for(int i=1;i<=n;i++)cin>>x[i]>>v[i]>>p[i],p[i]=p[i]*xs%yu;
for(int i=1;i<n;i++)t[++cn]=mk((double)(x[i+1]-x[i])/(double)(v[i]+v[i+1]),i);
for(int i=1;i<n;i++)if(v[i]!=v[i+1])t[++cn]=mk((double)(x[i+1]-x[i])/(double)(max(v[i],v[i+1])-min(v[i],v[i+1])),i+n);
sort(t+1,t+cn+1);
for(int i=1;i<=n;i++){
a[i].n=a[i].m=2;
a[i].a[1][1]=a[i].a[2][1]=yu+1-p[i];a[i].a[1][2]=a[i].a[2][2]=p[i];
}build(1,1,n);
ll ans=0;
for(int i=1;i<=cn;i++){
ll q=t[i].se,o=q;
if(q>n)o-=n;
juz an;an.n=1;an.m=2;an.a[1][1]=1;an.a[1][2]=0;
juz z=an,y=an;
juz tem=ask(1,1,n,1,o);
z=z*tem;
if(q<n||v[o]<v[o+1])y.a[1][1]=yu+1-p[o+1],y.a[1][2]=0;
else y.a[1][1]=0,y.a[1][2]=p[o+1];
if(o+2<=n){
y=y*ask(1,1,n,o+2,n);
}ll x1,x2=(y.a[1][1]+y.a[1][2]);
if(q<n||v[o]>v[o+1])x1=z.a[1][2];
else x1=z.a[1][1];
ll ji=x1*x2%yu;
ll val;
if(q<n)val=(x[o+1]-x[o])*ni(v[o]+v[o+1])%yu;
else val=(x[o+1]-x[o])*ni(max(v[o],v[o+1])-min(v[o],v[o+1]))%yu;
add(ans,ji*val%yu);
if(q<n)a[o+1].a[2][1]=0;
else{
if(v[o]>v[o+1])a[o+1].a[2][2]=0;
else a[o+1].a[1][1]=0;
}
update(1,1,n,o+1);
}cout<<ans;
return 0;
}
| cpp |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | #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;
template<class T> using ordset = tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>;
#define ar array
#define ll long long
#define ld long double
#define sz(x) ((int)x.size())
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define pb push_back
#define ppb pop_back
#define vll vector<long long int>
#define vi vector<int>
#define PrintArray(arr) for(int i=0;i<(int)arr.size();i++)cout<<arr[i]<<" ";cout<<"\n";
#define lowerb lower_bound
#define upperb upper_bound
#define pqi priority_queue<int>
#define pqll priority_queue<long long>
#define nl '\n';
const long long MAX_SIZE = 1000001;
const int MAX_N = 1e5 + 5;
const ll MOD1 = 1e9 + 7;
const ll MOD2 = 9882999;
const ll INF = 1e18;
const ld EPS = 1e-9;
//----------------------------------------------Code---------------------------------------------------//
void solve()
{
int n, k;
cin >> n >> k;
vll a(n);
for (int i = 0; i < n; i++) cin >> a[i];
map<ll, int> m;
int buu = 1;
for (int i = 0; i < n; i++)
{
ll cur = 0;
while (a[i] > 0)
{
m[cur] += (a[i] % k);
a[i] /= k;
cur++;
}
}
for (auto it: m)
{
if (it.second > 1)
{
cout << "NO" << nl;
return;
}
}
cout << "YES" << nl;
}
//-----------------------------------------------------------------------------------------------------//
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int tc = 1;
cin >> tc;
for (int t = 1; t <= tc; t++)
{
// cout << "Case #" << t << ": ";
solve();
}
return 0;
}
| cpp |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | [
"implementation",
"strings"
] | #include "bits/stdc++.h"
#define ll long long
#define ld long double
#define ull unsigned long long
#define pb push_back
#define sz(x) (int)x.size()
#define all(v) v.begin(), v.end()
#define F_OR(i, a, b, s) for (int i=(a); (s)>0?i<=(b):i>=(b); i+=(s))
#define F_OR1(e) F_OR(i, 1, e, 1)
#define F_OR2(i, e) F_OR(i, 1, e, 1)
#define F_OR3(i, b, e) F_OR(i, b, e, 1)
#define F_OR4(i, b, e, s) F_OR(i, b, e, s)
#define GET5(a, b, c, d, e, ...) e
#define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1)
#define forn(...) F_ORC(__VA_ARGS__)(__VA_ARGS__)
#define dbg cout << "_____________________HERE_________________________"
using namespace std;
const int N=1e5+10,LOG=17,mod=998244353;
const int inf=1e9;
const double eps = 1e-9;
const int block = 340, timer = 0;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define IOS ios_base::sync_with_stdio(false),cin.tie(0);cout.tie(0)
#define int ll
#define pii pair <int, int>
void solve(){
int n , m ; cin >> n >> m ;
string s[n + 1] , t[m + 1] ;
forn(i , 1 , n){
cin >> s[i] ;
}
forn(i , 1 , m){
cin >> t[i] ;
}
int q ; cin >> q ;
forn(i , 1 , q){
int cur ; cin >> cur ;
cur-- ;
int x = cur % n ;
int y = cur % m ;
cout << s[x + 1] << t[y + 1] << "\n" ;
}
}
signed main(){
IOS ;
int test = 1 ;
// cin >> test ;
forn(i , 1 , test){
solve() ;
}
} | cpp |
1141 | C | C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1
| [
"math"
] | // ~BhupinderJ
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define spc <<" "<<
#define pii pair<int, int>
#define vvi vector<vector<int>>
#define all(t) t.begin(), t.end()
//#define int long long
const int Mod = 1e9+7;
const int N = 2e5+1;
bool check(vector<int> &v, int n){
set<int> st;
for(int x : v) {
if(x > 0 and x <= n) st.insert(x);
}
return (st.size() == v.size());
}
void SOLVE(){
int n; cin >> n;
vector<int> q(n);
int mx = 0, mn = N;
for(int i=1 ; i<n ; i++){
cin >> q[i];
q[i] += q[i-1];
mx = max(mx, q[i]);
mn = min(mn, q[i]);
}
vector<int> p(n);
int p1;
if(mx > 0 and mn > 0) p1 = 1;
else if(mx < 0 and mn < 0) p1 = n;
else {
int t = (n+1-mx-mn);
if(t&1){
cout << -1 << endl;
return;
}
p1 = t/2;
}
p[0] = p1;
for(int i = 1 ; i < n ; i++){
p[i] = q[i] + p1;
}
if(check(p, n)){
for(int x : p) cout << x <<" ";
cout << endl;
}else cout << "-1\n";
}
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int T = 1; //cin >> T;
while(T--) SOLVE();
} | cpp |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define ss second
#define ff first
#define pb push_back // stoi() , to_string()
#define mp make_pair
#define lb lower_bound
#define nl "\n"
#define pll pair<ll, ll>
#define vll vector<ll>
#define prtvec(v) for(auto it = v.begin(); it != v.end(); ++it){cout<<*it<<" ";}cout<<nl;
const ll MOD = 1e9 + 7;
// const ll MOD = 998244353 ;
// Use LL ? yes => use everywhere.
void solve(int tt, int TT){
int n, m , p;
cin >> n >> m >> p;
vector<int> a(n), b(m);
for(int i = 0; i < n ; ++i)cin >> a[i];
for(int i = 0; i < m; ++i) cin >> b[i];
int i1 = -1;
int i2 = -1;
for(int i = 0; i < n; ++i){
if (a[i]%p != 0){
i1 = i;
break ;
}
}
for(int i = 0; i < m; ++i){
if (b[i]%p != 0){
i2 = i;
break ;
}
}
cout << i1 + i2 << nl;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int TCS = 1;
// cin >> TCS;
int tcs = 1;
while(tcs <= TCS){
solve(tcs, TCS);
tcs++;
}
return 0;
} | cpp |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"brute force",
"data structures",
"dp",
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD 1000000007
#define MOD1 998244353
#define ln "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define vi vector<int>
#define vlli vector<ll>
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
/******************************************/
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ll countDivisors(ll n){ll cnt = 0;for (ll i = 1; i <= sqrt(n); i++) {if (n % i == 0) {if (n / i == i)cnt++;else cnt = cnt + 2;}}return cnt;}
ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b
ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}
bool revsort(ll a, ll b) {return a > b;}
ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}
void google(int t) {cout << "Case #" << t << ": ";}
vector<ll> primeFactors(ll n){vector<ll>ret;while (n % 2 == 0){ret.pb(2);n = n/2;}for (ll i = 3; i <= sqrt(n); i = i + 2){while (n % i == 0){ret.pb(i);n = n/i;}}if (n > 2){ret.pb(n);}return ret;}
vector<ll> prime(ll n) {ll*arr = new ll[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (ll j = (ll(i) * ll(i)); j <= n; j += i)arr[j] = 1;} return vect;}
vector<ll>divisor(ll n){vector<ll>res;for (ll i=1; i<=sqrt(n); i++){if (n%i == 0){if (n/i == i)res.pb(i);else{res.pb(i);res.pb(n/i);} }}return res;}
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
ll countnumber(ll n){ll cnt=0;while(n>0){cnt++;n/=10;}return cnt;}
ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll getupper(ll k){ll x = 8*k+1;ll sqr = sqrt(x);if((sqr*sqr)==x){sqr--;return(sqr/2);}sqr--;return (sqr/2)+1;}
ll get2upper(ll n,ll rem){ll a = (2*n)+1;ll s = ((4*n*n)+(4*n)+1)-(8*rem);ll sqr = sqrt(s);if((sqr*sqr)==s){return ((a-sqr)/2)-1;}sqr++;return ((a-sqr)/2);}
ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m
ll modPower(ll x,ll y){ll res = 1;x = x % MOD;if (x == 0)return 0;while (y > 0) {if (y & 1)res = (res * x) % MOD;y = y / 2;x = (x * x) % MOD;}return res;}
ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))
ll modFact(ll n){ll result = 1;for (ll i = 1; i <= n; i++)result = (result * i) % MOD;return result;}
ll power(ll x,ll y){ll res=1;while(y>0){if(y&1)res = res * x;y = y >> 1;x = x * x;}return res;}
ll negMOD(ll x){x=-x;ll s = x/MOD;if(x%MOD)s++;return (MOD*s)-x;}
ll maxll(ll a,ll b) {if(a>b) return a; return b;}
ll minll(ll a,ll b) {if(a<b) return a; return b;}
void precision(ll a) {cout << setprecision(a) << fixed;}
ll msb(ll n){ ll res=0; while(n/2!=0){ n/=2; res++;} return res;}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("Error.txt", "w", stderr);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n;cin>>n;
vlli a(n);
for(int i=0;i<n;i++) cin>>a[i];
ll ind=-1,ans=0,mn;
if(is_sorted(all(a))){
for(int i=0;i<n;i++) cout<<a[i]<<" ";
}
else{
for(int i=0;i<n;i++){
ll temp=a[i];
mn=a[i];
for(int j=i+1;j<n;j++){
if(a[j]>=mn) temp+=mn;
else{
mn=a[j];
temp+=a[j];
}
}
mn=a[i];
for(int j=i-1;j>=0;j--){
if(a[j]>=mn) temp+=mn;
else{
mn=a[j];
temp+=a[j];
}
}
if(temp>ans){
ind=i;ans=temp;
}
}
mn=a[ind];
vlli b;
for(int i=ind-1;i>=0;i--){
if(a[i]>=mn) b.pb(mn);
else{
mn=a[i];
b.pb(mn);
}
}
reverse(all(b));
for(int i=0;i<ind;i++) cout<<b[i]<<" ";
mn=a[ind];
for(int i=ind;i<n;i++){
if(a[i]>=mn) cout<<mn<<" ";
else{
mn=a[i];
cout<<mn<<" ";
}
}
}
return 0;
}
| cpp |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define all(v) v.begin(), v.end()
#define F first
#define S second
#define ll long long
#define el '\n'
#define hanou2a ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
const int N = 1e5 + 3, mod = 1e9 + 7, M = 1e3 + 2;
const double E = 2.718281828459, pi = 3.14159265359;
using namespace std;
using namespace __gnu_pbds;
template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int n, p, k, s[N][8];
vector<pair<int, int>> v;
ll dp[N][1 << 8];
ll solve(int idx, int msk, int cnt) {
if (idx >= n) {
if (msk == (1 << p) - 1) return 0;
else return INT_MIN;
}
ll &ret = dp[idx][msk];
if (~ret)return ret;
ret = solve(idx + 1, msk, cnt);
for (int i = 0; i < p; i++) {
if (msk & (1 << i))continue;
ret = max(ret, solve(idx + 1, msk | (1 << i), cnt + 1) + s[v[idx].second][i]);
}
if (idx - cnt < k)
ret = max(ret, solve(idx + 1, msk, cnt) + v[idx].first);
return ret;
}
void func() {
memset(dp, -1, sizeof dp);
cin >> n >> p >> k;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
v.push_back({x, i});
}
sort(all(v), greater<>());
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++)cin >> s[i][j];
}
cout << solve(0, 0, 0);
}
int main() {
hanou2a
int tst;
tst = 1;
// cin >> tst;
for (int i = 1; i <= tst; i++) {
// cout << "Case " << i << ": ";
func();
}
return 0;
}
| cpp |
1307 | E | E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000) — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n) — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n) — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2
1 1 1 1 1
1 2
1 3
OutputCopy2 2
InputCopy5 2
1 1 1 1 1
1 2
1 4
OutputCopy1 4
InputCopy3 2
2 3 2
3 1
2 1
OutputCopy2 4
InputCopy5 1
1 1 1 1 1
2 5
OutputCopy0 1
NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side. | [
"binary search",
"combinatorics",
"dp",
"greedy",
"implementation",
"math"
] |
#pragma GCC optimize(3)
#pragma GCC target("avx")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("inline-functions")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("inline-small-functions")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("inline-functions-called-once")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#pragma GCC optimize(2)
#include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
#define rep(i, a, b) for(int i = (a); i <= (b); i ++)
#define per(i, a, b) for(int i = (a); i >= (b); i --)
#define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt)
using namespace std;
const int P = 1e9 + 7;
inline int plu(int x, int y) {return x + y >= P ? x + y - P : x + y;}
inline int del(int x, int y) {return x - y < 0 ? x - y + P : x - y;}
inline void add(int &x, int y) {x = plu(x, y);}
inline void sub(int &x, int y) {x = del(x, y);}
inline int qpow(int a, int b) {int s = 1; for(; b; b >>= 1, a = 1ll * a * a % P) if(b & 1) s = 1ll * s * a % P; return s;}
char buf[1<<22],*p1=buf,*p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
inline int read() {
int x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
while(isdigit(ch)) x=x*10+(ch^48),ch=getchar();
return x*f;
}
const int N = 5010;
int n, m, s[N], c[N];
int p[N][N], q[N][N];
int cnt, head[N];
struct node {int nxt, v;} e[N];
int main() {
n = read(), m = read();
rep(i, 1, n) s[i] = read();
rep(i, 1, n) rep(j, 1, n) p[i][j] = n + 1, q[i][j] = -1;
rep(i, 1, n) p[s[i]][++ c[s[i]]] = i;
rep(i, 1, n) c[i] = 0;
per(i, n, 1) q[s[i]][++ c[s[i]]] = i;
rep(i, 1, m) {int f = read(), h = read(); e[++ cnt] = (node) {head[f], h}, head[f] = cnt;}
vector<int> arc;
rep(i, 1, n) if(head[i]) arc.emplace_back(i);
int dat = 0, sum = 0;
rep(t, 0, n) {
int val = 0;
int num[2]; num[0] = 1, num[1] = 0;
int rec[2]; rec[0] = 1, rec[1] = 0;
bool flag = false;
for(int i : arc) {
int f[3][2]; rep(a, 0, 2) rep(b, 0, 1) f[a][b] = 0; f[0][0] = 1;
int d[3]; rep(b, 0, 2) d[b] = 0; d[0] = 1;
int cntl = 0, cntr = 0, cnto = 0;
Ede(x, i) {
int o = e[x].v;
int h[3][2];
h[0][0] = f[0][0], h[0][1] = f[0][1];
h[1][0] = f[1][0], h[1][1] = f[1][1];
h[2][0] = f[2][0], h[2][1] = f[2][1];
if(p[i][o] <= t) {
cntl ++;
add(f[1 + (p[i][o] == t)][0], h[0][0]);
add(f[1 + (p[i][o] == t)][1], h[0][1]);
}
if(q[i][o] > t) {
cntr ++;
add(f[0][1], h[0][0]);
add(f[1][1], h[1][0]);
add(f[2][1], h[2][0]);
add(d[1 + (q[i][o] == t + 1)], 1);
}
if(p[i][o] <= t && q[i][o] > t) cnto ++;
}
int cur[2]; cur[0] = cur[1] = 0;
int nxt[2]; nxt[0] = nxt[1] = 0;
val += (cntl > 0) + (cntr > 0);
rep(b, (cntr > 0), 2) add(nxt[b == 2], d[b]);
if(cnto == 1 && cntl == 1 && cntr == 1) {
val --;
add(cur[0], f[0][1]);
add(cur[0], f[1][0]);
add(cur[1], f[2][0]);
}
else {
flag |= (cntl > 0);
if(cntl == 0) {
if(cntr == 0) add(cur[0], f[0][0]); else add(cur[0], f[0][1]);
}
else {
if(cntr == 0) add(cur[0], f[1][0]), add(cur[1], f[2][0]);
else add(cur[0], f[1][1]), add(cur[1], f[2][1]);
}
}
int pre[2]; pre[0] = num[0], pre[1] = num[1]; num[0] = num[1] = 0;
int v = (1ll * (pre[0] + pre[1]) * cur[1] + 1ll * pre[1] * cur[0]) % P;
add(num[1], v);
add(num[0], 1ll * pre[0] * cur[0] % P);
pre[0] = rec[0], pre[1] = rec[1]; rec[0] = rec[1] = 0;
v = (1ll * plu(pre[0], pre[1]) * nxt[1] + 1ll * pre[1] * nxt[0]) % P;
add(rec[1], v);
add(rec[0], 1ll * pre[0] * nxt[0] % P);
}
if(! flag) add(num[1], rec[1]);
if(val > dat) dat = val, sum = num[1]; else if(val == dat) add(sum, num[1]);
}
if(dat == 0) sum = 1;
printf("%d %d\n", dat, sum);
return 0;
}
| cpp |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
bool ans = false;
cin >> n;
int dp[n+1];
dp[0] = 0;
vector<int> indexes;
for(int i = 1 ; i <= n ; i++)
cin >> dp[i];
for(int i = 1 ; i <= n && !ans; i++)
if(!(dp[i]%2)){
ans = true;
indexes.push_back(i);
indexes.push_back(i);
}
if(!ans){
for(int i = 1 ; i < n && !ans; i++){
int sum = dp[i];
for(int j = i + 1 ; j <= n && !ans ; j++){
sum += dp[j];
if(!(sum%2)){
ans = true;
indexes.push_back(i);
indexes.push_back(j);
}
}
}
}
if(ans){
cout << indexes[1] - indexes[0] + 1 << '\n';
for(int i = indexes[0] ; i <= indexes[1]; i++){
if(i == indexes[1])
cout << i << '\n';
else
cout << i << ' ';
}
}else
cout << "-1\n";
}
} | cpp |
1291 | F | F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"graphs",
"interactive"
] | // LUOGU_RID: 93829825
#include<bits/stdc++.h>
using namespace std;
#define pi pair<int,int>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define ls (rt<<1)
#define rs (rt<<1|1)
#define mid ((l+r)>>1)
#define lowbit(x) (x&-x)
const int maxn=1e4+5,M=2e5+5,mod=998244353;
inline int read(){
char ch=getchar();bool f=0;int x=0;
for(;!isdigit(ch);ch=getchar())if(ch=='-')f=1;
for(;isdigit(ch);ch=getchar())x=(x<<1)+(x<<3)+(ch^48);
if(f==1){x=-x;}return x;
}
void print(int x){
static int a[55];int top=0;
if(x<0) putchar('-'),x=-x;
do{a[top++]=x%10,x/=10;}while(x);
while(top) putchar(a[--top]+48);
}
int n,k,flag[maxn],x,ans=0,z=0;
int g[1055][1055];
char a[5];
void query(int x){
cout<<"? "<<x<<endl;
fflush(stdout);
scanf("%s",a);
if(a[0]=='Y')flag[x]=1;
}
void solve(int x,int y){
cout<<"R \n";
fflush(stdout);
for(int i=0;i<k/2;i++)
query(g[x][i]);
for(int i=0;i<k/2;i++)
query(g[y][i]);
}
void add(int x,int y){
cout<<"R \n";
fflush(stdout);
for(int i=x;i<=z;i+=y){
for(int j=0;j<k/2;j++)
query(g[i][j]);
}
}
signed main(){
n=read(),k=read();
if(n<=k){
for(int i=1;i<=n;i++){
query(i);ans+=!flag[i];
}
cout<<"! "<<ans<<endl;
fflush(stdout);
exit(0);
}
if(k==1){
for(int i=2;i<=n;i++)
for(int j=1;j<i;j++){
cout<<"R \n";
fflush(stdout);
query(j),query(i);
if(flag[i])break;
}
for(int i=1;i<=n;i++)
if(!flag[i])ans++;
cout<<"! "<<ans<<endl;
fflush(stdout);exit(0);
}z=0;
for(int i=1;i<=n;i+=k/2){++z;
for(int j=0;j<k/2;j++)
g[z][j]=i+j;
}
for(int i=1;i<=z;i++){
for(int j=1;j<=i;j++){
if(j+i<=z){
add(j,i);
}
}
}
for(int i=1;i<=n;i++)
if(!flag[i])ans++;
cout<<"! "<<ans<<endl;
fflush(stdout);
return 0;
} | cpp |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define I_am_speed() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define vec vector<ll>
#define loop(x, start, end) for(int x = start; x < end; ++x)
vector<int> primeNumbersTillN(int N)
{
bool isprime[N+1] ;
for(int i =0; i<=N ; i++) {
isprime[i] = true ;
}
for(int i = 2 ; i*i <= N ; i++) {
if(isprime[i] == true) {
for(int j = i*i ; j<= N ; j+=i) {
isprime[j] = false;
}
}
}
vector<int> ans ;
for(int i =2; i<= N ; i++) {
if(isprime[i] == true ) {
ans.push_back(i);
}
}
return ans ;
}
void print(vector<int> & v){
int n = v.size();
for(int i =0; i<v.size()-1; i++){
cout<<v[i]<<" ";
}
cout<<v[n-1]<<endl;
return ;
}
void print_2d(vector<vector<ll>> &v)
{
for (int i = 0; i < v.size(); i++)
{
for (int j = 0; j < v[i].size(); j++)
{
cout << v[i][j] <<" ";
}
cout << endl;
}
return;
}
void solve() {
int n ; cin >>n;
vector<int> b(n) ;
unordered_set<int> temp ;
loop(i,0,n) cin >>b[i] , temp.insert(b[i]) ;
set<int> st;
for(int i = 1;i <= 2*n; i++) {
if(temp.find(i) == temp.end()){
st.insert(i) ;
}
}
// for(auto it : st) cout <<it <<" " ;
// cout <<endl ;
vector<int> cp = b;
sort(cp.begin(), cp.end());
reverse(cp.begin(), cp.end()) ;
unordered_map<int ,pair<int ,int>> mp;
bool flag = false;
for(int i = 0; i<n; i++) {
int el = b[i] ;
if(lower_bound(st.begin() ,st.end() ,el) == st.end()) {
flag = true;
break ;
}
int se = *lower_bound(st.begin() , st.end(), el) ;
if(se> el) {
mp[el] ={el,se} ;
st.erase(se) ;
}
else{
flag = true;
break ;
}
}
if(flag) {
cout <<-1 <<endl ;
return ;
}
vector<int> ans ;
for(int i = 0; i<n; i++) {
ans.push_back(mp[b[i]].first) ;
ans.push_back(mp[b[i]].second) ;
}
print(ans );
}
int main(){
I_am_speed();
int t ; cin>>t;
while(t--){
solve();
}
return 0;
} | cpp |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
int64_t x0, y0, ax, ay, bx, by, xs, ys, t;
cin >> x0 >> y0 >> ax >> ay >> bx >> by;
cin >> xs >> ys >> t;
vector<int64_t> x(1, x0), y(1, y0);
int64_t LIMIT = 0x3f3f3f3f3f3f3f3f;
while ((LIMIT - bx) / ax >= x.back() && (LIMIT - by) / ay >= y.back()) {
x.push_back(ax * x.back() + bx);
y.push_back(ay * y.back() + by);
}
int n = x.size();
int ans = 0;
for (int i=0; i<n; i++) {
for (int j=i; j<n; j++) {
int64_t length = x[j] - x[i] + y[j] - y[i];
int64_t d2l = abs(xs - x[i]) + abs(ys - y[i]);
int64_t d2r = abs(xs - x[j]) + abs(ys - y[j]);
if (length <= t - min(d2l, d2r))
ans = max(ans, j-i+1);
}
}
cout << ans << endl;
}
| cpp |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102. | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | // Problem: B. Present
// Contest: Codeforces - Codeforces Round #626 (Div. 1, based on Moscow Open Olympiad in Informatics)
// URL: https://codeforces.com/contest/1322/problem/B
// Memory Limit: 512 MB
// Time Limit: 3000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("avx,avx2,sse,sse2")
#include<bits/stdc++.h>
#define all(x) begin(x), end(x)
using namespace std;
using ll = long long;
template<typename F>
void multitest(F func) {
int t;
cin >> t;
while(t--) func();
}
void report(int ok) {
cout << (ok?"YES":"NO") << '\n';
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int n;
cin >> n;
vector<int> a(n);
for(auto &i : a) cin >> i;
int ans = 0;
for(int b = 25; b >= 0; b--) {
vector<int> counts(1<<(b+1));
for(auto &i : a) {
i &= (1<<(b+1)) - 1;
counts[i]++;
}
for(int i = 1; i < 1<<(b+1); i++) counts[i] += counts[i - 1];
array<int, 4> bc;
bc.fill(0);
auto get = [&](int l, int r) {
--l, --r;
r = min(r, (1<<(b+1)) - 1);
l = min(l, (1<<(b+1)) - 1);
return (r < 0 ? 0 : counts[r]) - (l < 0 ? 0 : counts[l]);
};
for(auto i : a) {
for(int v = 0; v < 4; v++) {//[v*2^b; (v+1)*2^b)
int low = v<<b, high = (v+1)<<b;
bc[v] += get(low - i, high - i);
}
bc[(i+i)>>b] -= 1;
}
int ones = bc[1] / 2 + bc[3] / 2;
if(ones & 1) ans += 1<<b;
}
cout << ans << '\n';
}
| cpp |
1322 | F | F. Assigning Farestime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMayor of city M. decided to launch several new metro lines during 2020. Since the city has a very limited budget; it was decided not to dig new tunnels but to use the existing underground network.The tunnel system of the city M. consists of nn metro stations. The stations are connected with n−1n−1 bidirectional tunnels. Between every two stations vv and uu there is exactly one simple path. Each metro line the mayor wants to create is a simple path between stations aiai and bibi. Metro lines can intersects freely, that is, they can share common stations or even common tunnels. However, it's not yet decided which of two directions each line will go. More precisely, between the stations aiai and bibi the trains will go either from aiai to bibi, or from bibi to aiai, but not simultaneously.The city MM uses complicated faring rules. Each station is assigned with a positive integer cici — the fare zone of the station. The cost of travel from vv to uu is defined as cu−cvcu−cv roubles. Of course, such travel only allowed in case there is a metro line, the trains on which go from vv to uu. Mayor doesn't want to have any travels with a negative cost, so it was decided to assign directions of metro lines and station fare zones in such a way, that fare zones are strictly increasing during any travel on any metro line.Mayor wants firstly assign each station a fare zone and then choose a lines direction, such that all fare zones are increasing along any line. In connection with the approaching celebration of the day of the city, the mayor wants to assign fare zones so that the maximum cici will be as low as possible. Please help mayor to design a new assignment or determine if it's impossible to do. Please note that you only need to assign the fare zones optimally, you don't need to print lines' directions. This way, you solution will be considered correct if there will be a way to assign directions of every metro line, so that the fare zones will be strictly increasing along any movement of the trains.InputThe first line contains an integers nn, mm (2≤n,≤500000, 1≤m≤5000002≤n,≤500000, 1≤m≤500000) — the number of stations in the city and the number of metro lines.Each of the following n−1n−1 lines describes another metro tunnel. Each tunnel is described with integers vivi, uiui (1≤vi, ui≤n1≤vi, ui≤n, vi≠uivi≠ui). It's guaranteed, that there is exactly one simple path between any two stations.Each of the following mm lines describes another metro line. Each line is described with integers aiai, bibi (1≤ai, bi≤n1≤ai, bi≤n, ai≠biai≠bi).OutputIn the first line print integer kk — the maximum fare zone used.In the next line print integers c1,c2,…,cnc1,c2,…,cn (1≤ci≤k1≤ci≤k) — stations' fare zones. In case there are several possible answers, print any of them. In case it's impossible to assign fare zones, print "-1".ExamplesInputCopy3 1
1 2
2 3
1 3
OutputCopy3
1 2 3
InputCopy4 3
1 2
1 3
1 4
2 3
2 4
3 4
OutputCopy-1
InputCopy7 5
3 4
4 2
2 5
5 1
2 6
4 7
1 3
6 7
3 7
2 1
3 6
OutputCopy-1
NoteIn the first example; line 1→31→3 goes through the stations 1, 2, 3 in this order. In this order the fare zones of the stations are increasing. Since this line has 3 stations, at least three fare zones are needed. So the answer 1, 2, 3 is optimal.In the second example, it's impossible to assign fare zones to be consistent with a metro lines. | [
"dp",
"trees"
] | // LUOGU_RID: 98244252
#include <bits/stdc++.h>
using namespace std;
const int N=5e5+5;
int n,m,k,sz[N],d[N],so[N],tp[N],fa[N],s[N],h[N],c[N*2],b[N*2],p[N*2],f[N*2];
vector<int> e[N],g[N];
inline void cmi(int&x,int y) {if(x>y) x=y;}
inline void cmx(int&x,int y) {if(x<y) x=y;}
int getf(int x) {return f[x]==x?x:f[x]=getf(f[x]);}
void merge(int x,int y){
b[x]=b[y]=1;
x=getf(x);y=getf(y);
if(x==y) return;
f[x]=y;
}
void dfs1(int x){
sz[x]=1;
for(int y:e[x]) if(y!=fa[x]){
d[y]=d[fa[y]=x]+1;
dfs1(y);sz[x]+=sz[y];
if(sz[y]>sz[so[x]]) so[x]=y;
}
}
void dfs2(int x){
if(!tp[x]) tp[x]=x;
if(so[x]) tp[so[x]]=tp[x],dfs2(so[x]);
for(int y:e[x]) if(y!=fa[x]&&y!=so[x]) dfs2(y);
}
int lca(int x,int y){
while(tp[x]!=tp[y])
if(d[tp[x]]<d[tp[y]]) y=fa[tp[y]];
else x=fa[tp[x]];
return d[x]<d[y]?x:y;
}
int anc(int x,int y){
while(tp[x]!=tp[y]){
if(fa[tp[x]]==y) return tp[x];
x=fa[tp[x]];
}
return so[y];
}
void dfs3(int x){
for(int y:e[x]) if(y!=fa[x]) dfs3(y),s[x]+=s[y];
if(s[x]) merge(x,fa[x]),merge(x+n,fa[x]+n);
}
bool solve(int x){
int l=1,r=k,tl=1,tr=(k+1)/2;
for(int y:e[x]) if(y!=fa[x]){
if(!solve(y)) return 0;
if(!b[y]) continue;
if(f[x]==f[y]) cmx(l,h[y]+1);
else if(f[x+n]==f[y]) cmi(r,k-h[y]);
else if(f[y]<=n) cmx(p[f[y]],h[y]+1);
else cmi(p[f[y]],k-h[y]);
}
for(int y:g[x]){
if(p[y]>p[y+n]) return 0;
cmx(tl,min(p[y],k-p[y+n]+1));
cmi(tr,min(p[y+n],k-p[y]+1));
}
cmx(l,tl);cmi(r,k-tl+1);
int rr=k+1-tr;
if(l>r||(tr<l&&r<rr)) return 0;
return (h[x]=(l<=tr||l>=rr)?l:rr);
}
bool chk(){
fill_n(p+1,n,1);fill_n(p+n+1,n,k);
return solve(1);
}
void print(int x,int op){
for(int y:e[x]) if(y!=fa[x]){
if(!b[y]) {print(y,0);continue;}
if(f[x]==f[y]) print(y,op);
else if(f[x+n]==f[y]) print(y,op^1);
else if(f[y]<=n) c[f[y]]|=h[y]>=h[x];
else c[f[y]]|=h[x]>=k-h[y]+1;
}
for(int y:e[x]) if(y!=fa[x]&&b[y]&&f[x]!=f[y]&&f[x+n]!=f[y]){
int t=f[y]-(f[y]>n)*n;
print(y,op^(f[y]>n)^(c[t]||c[t+n]));
}
if(op) h[x]=k-h[x]+1;
}
int main(){
scanf("%d%d",&n,&m);
iota(f,f+n*2+1,0);
for(int i=1,u,v;i<n;i++) scanf("%d%d",&u,&v),e[u].push_back(v),e[v].push_back(u);
dfs1(1);dfs2(1);
for(int u,v;m--;){
scanf("%d%d",&u,&v);
if(d[u]>d[v]) swap(u,v);
int l=lca(u,v),fu,fv;
s[v]++;s[fv=anc(v,l)]--;
if(l!=u) s[u]++,s[fu=anc(u,l)]--,merge(fu,fv+n),merge(fu+n,fv);
else b[fv]=b[fv+n]=1;
}
dfs3(1);
for(int i=1;i<=n;i++) if(getf(i)==getf(i+n)) return puts("-1"),0;
for(int x=1;x<=n;x++){
for(int y:e[x]) if(f[x]!=f[y]&&f[x+n]!=f[y]&&f[y]<=n) g[x].push_back(f[y]);
sort(g[x].begin(),g[x].end());
g[x].erase(unique(g[x].begin(),g[x].end()),g[x].end());
}
int l=1,r=n,ans=0;
while(l<=r){
k=l+r>>1;
if(chk()) r=(ans=k)-1;
else l=k+1;
}
printf("%d\n",k=ans);
chk();print(1,0);
for(int i=1;i<=n;i++) printf("%d ",h[i]);
return 0;
} | cpp |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
#define N 100010
#define ll long long
#define fs first
#define sc second
#define ii pair<int,int>
#define pb push_back
#define iii pair<int,ii>
#define cong 1000001
#define ld long double
#define pb push_back
#define int ll
const int MAX_VAL=1e5;
int ans=0,n,ktr[N],a[N],dpt,nt[N],f[N],dp[N];
vector<int>uoc[N],uoc_nt[N];
vector<int>lis[N],pos[N];
void build(int u)
{
f[0]=1;
for(int mask=1;mask<(1<<uoc_nt[u].size());mask++)
for(int i=0;i<uoc_nt[u].size();i++)
if((mask>>i)&1)
f[mask]=f[mask-(1<<i)]*uoc_nt[u][i];
for(int mask=1;mask<(1<<uoc_nt[u].size());mask++)
if(__builtin_popcount(mask)&1)
lis[u].pb(f[mask]);
else lis[u].pb(-f[mask]);
}
void them(int u,int val)
{
for(auto v:lis[u])
dp[abs(v)]+=val;
}
int get(int u)
{
int res=0;
for(auto v:lis[u])
if(v>0)
res+=dp[v];
else res-=dp[-v];
return res;
}
void tknp(int l,int r,int gcd)
{
int mid=(l+r)/2;
for(int i=l;i<=mid;i++)
them(a[i],1);
for(auto i:pos[mid])
{
// cout<<a[i]<<" "<<mid<<" "<<get(a[i])<<endl;
if(get(a[i])<mid)
{
// cout<<a[i]<<" "<<mid<<" "<<a[mid]<<" "<<dp[35]<<endl;
ans=max(ans,a[i]*a[mid]*gcd);
if(l<mid)
pos[(l+(mid-1))/2].pb(i);
}else
{
if(mid<r)
pos[(r+(mid+1))/2].pb(i);
}
}
if(mid<r)
tknp(mid+1,r,gcd);
for(int i=l;i<=mid;i++)
them(a[i],-1);
if(l<mid)
tknp(l,mid-1,gcd);
}
void solve(int gcd)
{
//if(gcd!=7)
// return;
for(int i=1;i*2<=n;i++)
swap(a[i],a[n-i+1]);
for(int i=1;i<=n;i++)
pos[i].clear();
for(int i=1;i<=n;i++)
pos[(n+1)/2].pb(i);//,cout<<i<<endl;
for(int i=1;i<=n;i++)
for(auto v:lis[a[i]])
dp[abs(v)]=0;
tknp(1,n,gcd);
// cout<<gcd<<" "<<ans<<" "<<n<<endl;
}
int32_t main()
{
// freopen("A.inp","r",stdin);
// freopen("A.out","w",stdout);
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
cin>>n;
for(int i=1;i<=n;i++)
{
int u;
// u=i;
cin>>u;
// cout<<u<<endl;
ktr[u]=1;
}
for(int i=1;i<=MAX_VAL;i++)
for(int j=i;j<=MAX_VAL;j+=i)
uoc[j].pb(i);
for(int i=2;i*i<=MAX_VAL;i++)
if(nt[i]==0)
{
for(int j=i*i;j<=MAX_VAL;j+=i)
nt[j]=1;
}
for(int i=2;i<=MAX_VAL;i++)
if(nt[i]==0)
{
for(int j=i;j<=MAX_VAL;j+=i)
uoc_nt[j].pb(i);
}
for(int i=1;i<=MAX_VAL;i++)
build(i);
for(int gcd=1;gcd<=MAX_VAL;gcd++)
{
n=0;
for(int j=gcd;j<=MAX_VAL;j+=gcd)
if(ktr[j]==1)
a[++n]=j/gcd;
solve(gcd);
}
cout<<ans;
return 0;
}
| cpp |
1322 | E | E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5
1 2 1 2 1
OutputCopy2
1 1 1 1 1
InputCopy6
1 3 2 5 4 6
OutputCopy1
1 2 3 4 5 6
InputCopy6
1 1 2 2 1 1
OutputCopy0
1 1 2 2 1 1
NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00. | [
"data structures"
] | // Judges with GCC >= 12 only needs Ofast
// #pragma GCC optimize("O3,no-stack-protector,fast-math,unroll-loops,tree-vectorize")
// MLE optimization
// #pragma GCC optimize("conserve-stack")
// Old judges
// #pragma GCC target("sse4.2,popcnt,lzcnt,abm,mmx,fma,bmi,bmi2")
// New judges. Test with assert(__builtin_cpu_supports("avx2"));
// #pragma GCC target("avx2,popcnt,lzcnt,abm,bmi,bmi2,fma,tune=native")
// Atcoder
// #pragma GCC target("avx2,popcnt,lzcnt,abm,bmi,bmi2,fma")
#include<bits/stdc++.h>
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
uniform_real_distribution<> pp(0.0,1.0);
#define int long long
#define ld long double
#define pii pair<int,int>
#define piii pair<int,pii>
#define fi first
#define se second
const int inf=1e18;
const int mod=998244353;
const int mod2=1e9+7;
const int maxn=500005;
const int maxm=200005;
const int maxq=500005;
const int maxl=20;
const int maxa=1000005;
int power(int a,int n){
int res=1;
while(n){
if(n&1) res=res*a%mod;
a=a*a%mod;n>>=1;
}
return res;
}
map<int,vector<int>> mp;
set<int> s,rem;
int n,a[maxn],res[maxn],ans;
void update(int x){
if(x<=1 || x>n) return;
if(s.find(x)!=s.end()) s.erase(x);
else s.insert(x);
}
void cal(int val,int x){
if(x<=0 || x>n) return;
auto it=s.upper_bound(x);
int r=*it-1,l=*prev(it);
//cout << l << ' ' << r << '\n';
ans=max(ans,(r-l)/2);
if(a[l]+a[r]==0) return;
if(a[l]+a[r]==1){
if(a[l]) r-=(r-l+1)/2;
else l+=(r-l+1)/2;
}
while(true){
auto it=rem.lower_bound(l);
if(it==rem.end() || *it>r) break;
res[*it]=val;
rem.erase(it);
}
}
void solve(){
cin >> n;
for(int i=1;i<=n;i++){
int x;cin >> x;
mp[x].push_back(i);
}
for(int i=1;i<=n;i++) rem.insert(i);
for(int i=1;i<=n+1;i++) s.insert(i);
for(auto x:mp){
for(int id:x.se){a[id]=1;update(id);update(id+1);}
for(int id:x.se){cal(x.fi,id-1);cal(x.fi,id);cal(x.fi,id+1);}
}
cout << ans << '\n';
for(int i=1;i<=n;i++) cout << res[i] << ' ';
cout << '\n';
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
int test=1;//cin >> test;
while(test--) solve();
}
| cpp |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define all(c) c.begin(), c.end()
#define endl "\n"
const double PI=3.141592653589;
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define dbg(x...) cerr << "LINE(" << __LINE__ << ") -> " <<"[" << #x << "] = ["; _print(x)
#else
#define dbg(x...)
#endif
int n;
vector<int>dp,a,res,root;
vector<vector<int>>adj;
void dfs1(int u, int p){
dp[u] = a[u];
for(int v : adj[u]){
if(v==p)continue;
dfs1(v,u);
dp[u]+=max(0ll,dp[v]);
}
}
void dfs(int u, int p){
for(int v : adj[u]){
if(v==p)continue;
// find the value when the root changes from u->v
int tmp = root[u]-max(0ll,dp[v]);
root[v]+=max(0ll,tmp);
res[v] = max(res[v], root[v]);
dfs(v,u);
}
}
void solve()
{
cin >> n;
dp.resize(n+1);
a.resize(n+1);
adj.resize(n+1);
res.resize(n+1);
root.resize(n+1);
for(int i = 1;i<=n;++i){
cin >> a[i];
if(!a[i])a[i] = -1;
}
for(int i = 1;i<n;++i){
int u,v;
cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
dfs1(1,-1);
res = dp;
root = dp;
dfs(1,-1);
for(int i = 1;i<=n;++i)cout << res[i] << ' ';
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// freopen("error.txt", "w", stderr);
// #endif
int T=1;
// cin >> T;
for(int i = 1;i<=T;++i)
{
// cout << "Case #" << i << ": ";
solve();
}
} | cpp |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
| [
"constructive algorithms",
"sortings"
] | #include <bits/stdc++.h>
#define ll long long
#define endl '\n'
#define B break
#define R return
#define C continue
#define F first
#define S second
using namespace std;
ll t,n,m,i,a[1000000],ans,sum,q,x,b;
string w;
map<int,int>mm;
char cc;
stack <char>s;
int main(){
cin>>t;
while(t--){
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n,greater<int>());
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
}
| cpp |
1288 | E | E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] | [
"data structures"
] | /// What are you doing now? Just go f*cking code now dude?
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define TASK "codin"
#define int long long
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long llu;
#define IO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define is insert
#define eb emplace_back
#define FOR(x,a,b) for (ll x=a;x<=b;x++)
#define FOD(x,a,b) for (ll x=a;x>=b;x--)
#define FER(x,a,b) for (ll x=a;x<b;x++)
#define FED(x,a,b) for (ll x=a;x>b;x--)
#define EL "\n"
#define ALL(v) v.begin(),v.end()
#define vi vector<ll>
#define vii vector<pii>
#define pii pair<int,int>
///---------- TEMPLATE ABOUT BIT ----------///
ll getbit(ll val, ll num){
return ((val >> (num)) & 1LL);
}
ll offbit(ll val, ll num){
return ((val ^ (1LL << (num - 1))));
}
ll setbit(ll k, ll s) {
return (k &~ (1 << s));
}
///---------- TEMPLATE ABOUT MATH ----------///
ll lcm(ll a, ll b){
return a * b/__gcd(a, b);
}
ll bmul(ll a, ll b, ll mod){
if(b == 0){return 0;}
if(b == 1){return a;}
ll t = bmul(a, b/2, mod);t = (t + t)%mod;
if(b%2 == 1){t = (t + a) % mod;}return t;
}
ll bpow(ll n, ll m, ll mod){
ll res = 1; while (m) {
if (m & 1) res = res * n % mod; n = n * n % mod; m >>= 1;
} return res;
}
///----------------------------------------///
const int S = 5e5 + 5, M = 2e3 + 4;
const ll mod = 1e9 + 7, hashmod = 1e9 + 9, inf = 1e18;
const int base = 311, BLOCK_SIZE = 420;
const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
const int dxx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, dyy[8]={0, 1, 1, 1, 0, -1, -1, -1};
///------ The main code starts here ------///
int n, m, a[S], minpos[S], maxpos[S], st[8 * S], pos[S];
void upd(int id, int le, int ri, int pos, int c){
if(ri < pos || le > pos){
return;
}
if(le == ri){
st[id] += c;
return;
}
int mi = (le + ri) / 2;
upd(id * 2, le, mi, pos, c);
upd(id * 2 + 1, mi + 1, ri, pos, c);
st[id] = st[id * 2] + st[id * 2 + 1];
}
int query(int id, int le, int ri, int u, int v){
if(u > ri || v < le){
return 0;
}
if(le >= u && ri <= v){
return st[id];
}
int mi = (le + ri) / 2;
return query(id * 2, le, mi, u, v) + query(id * 2 + 1, mi + 1, ri, u, v);
}
void solve(){
cin >> n >> m;
FOR(i, 1, n){
minpos[i] = maxpos[i] = i;
}
FOR(i, 1, m){
cin >> a[i];
minpos[a[i]] = 1;
}
int cnt = 0;
FOD(i, n, 1){
pos[i] = ++cnt;
upd(1, 1, n + m, cnt, 1);
}
FOR(i, 1, m){
cnt++;
int tmp = query(1, 1, n + m, pos[a[i]], cnt);
maxpos[a[i]] = max(maxpos[a[i]], tmp);
upd(1, 1, n + m, pos[a[i]], -1);
upd(1, 1, n + m, cnt, 1);
pos[a[i]] = cnt;
}
FOR(i, 1, n){
int tmp = query(1, 1, n + m, pos[i], cnt);
maxpos[i] = max(maxpos[i], tmp);
}
FOR(i, 1, n){
cout << minpos[i] << " " << maxpos[i] << EL;
}
}
signed main(){
IO
if(fopen(TASK".inp","r")){
freopen(TASK".inp","r",stdin);
freopen(TASK".out","w",stdout);
}
int t = 1;
//cin >> t;
while(t--){
solve();
}
}
| cpp |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<ll>adj[2000];
bool vis[2000];
ll r=1;
ll dfs(ll x)
{
vis[x]=true;
for(auto t:adj[x])
{
if(!vis[t])
return dfs(t);
}
return x;
}
int main()
{
ll N;cin>>N;
vis[1]=false; ll u,v;
for(ll i=0;i<N-1;i++)
{
cin>>u>>v;
adj[u].push_back(v); adj[v].push_back(u);
vis[i+2]=false;
}
while(1)
{
ll x=dfs(r);
ll y=dfs(r);
if(x==r)break;
cout<<"? "<<x<<" "<<y<<endl;
cin>>r;
}
cout<<"! "<<r<<endl;
} | cpp |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<bool> primes;
void seive(int n){
primes.resize(n+1, true);
primes[0] = false; primes[1] = false;
for(int i=2; i*i<=n; i++){
if(primes[i]){
for(int j=i*i; j<=n; j+=i) primes[j] = false;
}
}
}
ll kadane(vector<ll> &vec, ll start, ll end) {
ll currSum = 0, maxSum = INT_MIN;
for(ll i = start; i < end; i++) {
currSum += vec[i];
if(currSum < 0) currSum = 0;
maxSum = max(maxSum, currSum);
}
return maxSum;
}
void solve(){
ll n; cin>>n;
ll i = 0;
vector<ll> a(n);
while(i < n) cin>>a[i++];
ll sum = 0;
for(auto i:a) sum += i;
ll x = max(kadane(a, 0, n-1), kadane(a, 1, n));
if(x >= sum) cout<<"NO\n";
else cout<<"YES\n";
}
int main(){
ll t;
cin>>t;
while(t--){
solve();
}
} | cpp |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes. | [
"brute force",
"strings"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ar array
#define vt vector
#define pq priority_queue
#define pu push
#define pub push_back
#define em emplace
#define emb emplace_back
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define allp(x, l, r) x.begin() + l, x.begin() + r
#define len(x) (int)x.size()
using namespace std;
using namespace __gnu_pbds;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
template <class T, size_t N>
void re(array <T, N>& x);
template <class T>
void re(vt <T>& x);
template <class T>
void re(T& x) {
cin >> x;
}
template <class T, class... M>
void re(T& x, M&... args) {
re(x); re(args...);
}
template <class T>
void re(vt <T>& x) {
for(auto& it : x)
re(it);
}
template <class T, size_t N>
void re(array <T, N>& x) {
for(auto& it : x)
re(it);
}
template <class T, size_t N>
void wr(array <T, N> x);
template <class T>
void wr(vt <T> x);
template <class T>
void wr(T x) {
cout << x;
}
template <class T, class ...M> void wr(T x, M... args) {
wr(x), wr(args...);
}
template <class T>
void wr(vt <T> x) {
for(auto it : x)
wr(it, ' ');
}
template <class T, size_t N>
void wr(array <T, N> x) {
for(auto it : x)
wr(it, ' ');
}
void set_fixed(int p = 0) {
cout << fixed << setprecision(p);
}
void set_scientific() {
cout << scientific;
}
inline void Open(const string Name) {
#ifndef ONLINE_JUDGE
(void)!freopen((Name + ".in").c_str(), "r", stdin);
(void)!freopen((Name + ".out").c_str(), "w", stdout);
#endif
}
void solve() {
int n; re(n);
vt <int> v(n); re(v);
map <int, int> H;
for (int i = 0; i < n; ++i) {
++H[v[i]];
if (i and H[v[i]] == 2 and v[i - 1] != v[i]) {
wr("YES\n");
return;
}
if (H[v[i]] > 2) {
wr("YES\n");
return;
}
}
wr("NO\n");
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
//Open("");
int t; re(t);
for(;t;t--) {
solve();
}
return 0;
} | cpp |
1303 | F | F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10
2 1 1
1 2 1
2 2 1
1 1 2
3 1 2
1 2 2
2 2 2
2 1 2
3 2 4
2 1 5
OutputCopy2
4
3
3
4
4
4
2
2
4
| [
"dsu",
"implementation"
] | // LUOGU_RID: 99410486
#include <bits/stdc++.h>
using namespace std;
const int N=310;
const int Q=2000010;
const int X[]={1,-1,0,0},Y[]={0,0,1,-1};
int n,m,q,lim,ans[Q],fa[N*N],nw[N][N];
struct Query {
int id,x,y;
};
vector<Query> q1[Q],q2[Q];
int f(int x,int y)
{
return (x-1)*m+y;
}
bool chk(int x,int y)
{
return x>0&&x<=n&&y>0&&y<=m;
}
void clear(int n)
{
for (int i=1;i<=n;i++)
fa[i]=i;
}
int rt(int x)
{
return x==fa[x]?x:fa[x]=rt(fa[x]);
}
bool merge(int x,int y)
{
x=rt(x);
y=rt(y);
if (x==y) return 0;
fa[x]=y;
return 1;
}
int main()
{
scanf("%d%d%d",&n,&m,&q);
for (int i=1,x,y,c;i<=q;++i)
{
scanf("%d%d%d",&x,&y,&c);
lim=c;
q2[nw[x][y]].push_back({i,x,y});
q1[nw[x][y]=c].push_back({i,x,y});
}
for (int i=1;i<=n;i++)
for (int j=1;j<=m;++j)
q2[nw[i][j]].push_back({0,i,j});
memset(nw,-1,sizeof nw);
for (int i=0,sz,id,x,y;i<=lim;i++)
{
sz=q1[i].size();
if(!sz) continue;
clear(n*m);
for (int j=0;j<sz;j++)
{
id=q1[i][j].id,x=q1[i][j].x,y=q1[i][j].y;
nw[x][y]=i;
ans[id]++;
for (int k=0,gX,gY;k<4;k++)
{
gX=x+X[k],gY=y+Y[k];
if (chk(gX,gY)&&nw[gX][gY]==i)
ans[id]-=merge(f(x,y),f(gX,gY));
}
}
}
memset(nw,-1,sizeof nw);
for (int i=0,sz,x,y,id;i<=lim;i++)
{
sz=q2[i].size();
if (!sz) continue;
clear(n*m);
for (int j=sz-1;j>=0;j--)
{
x=q2[i][j].x,y=q2[i][j].y,id=q2[i][j].id;
nw[x][y]=i;
ans[id]--;
for (int k=0,gX,gY;k<4;k++)
{
gX=x+X[k],gY=y+Y[k];
if (chk(gX,gY)&&nw[gX][gY]==i)
ans[id]+=merge(f(x,y),f(gX,gY));
}
}
}
ans[0]=1;
for(int i=1;i<=q;i++)
printf("%d\n",ans[i]+=ans[i-1]);
return 0;
} | cpp |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | #include <bits/stdc++.h>
#define int long long int
#define endl "\n"
#define pb push_back
#define pf push_front
#define ff first
#define ss second
#define fastio() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(__null);
#define cnt1(x) __builtin_popcountll(x)
using namespace std;
const int mod = 1e9 + 7;
const int N = 1e15;
signed main()
{
fastio()
int t;
cin >> t;
while (t--)
{
int n, x;
cin >> n >> x;
string s;
cin >> s;
vector<int> f0(n, 0), f1(n, 0);
s[0] == '1' ? f1[0] = 1 : f0[0] = 1;
for (int i = 1; i < n; i++) f0[i] = f0[i - 1] + (s[i] == '0' ? 1 : 0), f1[i] = f1[i - 1] + (s[i] == '1' ? 1 : 0);
int ans = (x == 0 ? 1 : 0);
for (int i = 0; i < n; i++)
{
if (x == f0[i] - f1[i] && f0[n - 1] == f1[n - 1]) ans = N;
else if (f0[n - 1] != f1[n - 1])
{
int y = (x - f0[i] + f1[i]) / (f0[n - 1] - f1[n - 1]);
if (y >= 0 && y * (f0[n - 1] - f1[n - 1]) == x - f0[i] + f1[i]) ans++;
}
}
cout << (ans >= N ? -1 : ans) << endl;
}
return 0;
} | cpp |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample: | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | //DEVENDRA KUMAR
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define vi vector<int>
#define pb push_back
#define pii pair<int,int>
#define F first
#define S second
#define rep(i,n) for(int i=0; i<n; i++)
#define nl cout<<endl
#define all(x) x.begin(),x.end()
#define yes {cout<<"YES";nl;}
#define no {cout<<"NO";nl;}
const int mod = 1000000007;
const double PI = 3.14159265358979323846;
int power(int x,int y,int p);
void read(vector<int> &a);
void read(vector<vector<int>> &a);
void print(vector<int>&a);
void print(vector<vector<int>>&a);
int inv(int x){return power(x,mod-2,mod);};
const int MAXN = 100001;
vector<int> adj[MAXN];
vector<int> label(MAXN, -1);
void solve(){
int n, u, v; cin>>n;
for(int i=1; i<n; i++){
cin>>u>>v;
adj[u].pb(i);
adj[v].pb(i);
}
int cnt = 0;
for(int i=1; i<=n; i++){
if(adj[i].size() > 2){
label[adj[i][0]] = cnt++;
label[adj[i][1]] = cnt++;
label[adj[i][2]] = cnt++;
break;
}
}
for(int i=1; i<n; i++){
if(label[i]==-1){
label[i] = cnt++;
}
}
for(int i=1; i<n; i++){
cout<<label[i]<<"\n";
}
}
signed main(){
ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
int t = 1;
// cin>>t;
while(t--) solve();
return 0;
}
void read(vector<int> &a){
rep(i,a.size()) cin>>a[i];
}
void read(vector<vector<int>> &a){
rep(i,a.size()) rep(j,a[i].size()) cin>>a[i][j];
}
void print(vector<int> &a){
for(auto x: a) cout<<x<<' '; nl;
}
void print(vector<vector<int>> &a){
for(auto x: a){
for(auto z: x) cout<<z<<" "; nl;
}
}
int power(int x,int y,int p){int res = 1; x%=p; if(!x) return 0; while(y){ if(y&1) res=(res*x)%p; y=y>>1; x=(x*x)%p; } return res;} | cpp |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb. | [
"implementation",
"strings"
] | // CF template, version 3.0
#include <bits/stdc++.h>
using namespace std;
#define improvePerformance ios_base::sync_with_stdio(false); cin.tie(0)
#define getTest int t; cin >> t
#define eachTest for (int _var=0;_var<t;_var++)
#define get(name) int (name); cin >> (name)
#define out(o) cout << (o)
#define getList(cnt, name) vector<int> (name); for (int _=0;_<(cnt);_++) { get(a); (name).push_back(a); }
#define sortl(name) sort((name).begin(), (name).end())
#define rev(name) reverse((name).begin(), (name).end())
#define forto(name, var) for (int (var) = 0; (var) < (name); (var)++)
#define decision(b) if (b){out("YES");}else{out("NO");}
#define int long long int
int gcd(int a, int b) {
if (a == b) return a;
return gcd(max(a, b), max(a, b) % min(a, b));
}
/*
Segtree:
void build(vector<int> &tree, vector<int> &array, int i, int l, int r) {
if (l == r) {
tree[i] = array[l];
} else {
int middle = (l + r) / 2;
build(tree, array, i * 2, l, middle);
build(tree, array, i * 2 + 1, middle + 1, r);
tree[i] = max(tree[i * 2], tree[i * 2 + 1]);
}
}
void set_(vector<int> &tree, int v, int l, int r, int i, int x) {
if (l == r) {
tree[v] = x;
} else {
int middle = (l + r) / 2;
if (i <= middle) {
set_(tree, v * 2, l, middle, i, x);
} else {
set_(tree, v * 2 + 1, middle + 1, r, i, x);
}
tree[v] = max(tree[v * 2], tree[v * 2 + 1]);
}
}
int query(vector<int> &tree, int v, int cl, int cr, int l, int r) {
if (l == cl && r == cr) {
return tree[v];
}
if (l > r) return 0;
int middle = (cl + cr) / 2;
return max(
query(tree, v * 2, cl, middle, l, min(r, middle)),
query(tree, v * 2 + 1, middle + 1, cr, max(l, middle + 1), r)
);
}
vector<int> tree(4 * n);
build(tree, initial, 1, 0, n-1); // replace initial with name of array
set_(tree, 1, 0, n-1, a, b);
query(tree, 1, 0, n-1, a, b); // this returns an int
data structure can be changed
*/
signed main() {
improvePerformance;
getTest;
vector<vector<vector<int>>> arrs = {{{0, 0, 1}}, {{0, 1, 1}, {0, 0, 1}}, {{0, 1, 1}}, {{0, 1, 0}, {0, 0, 1}}, {{0, 1, 0}}, {{0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{0, 1, 0}, {0, 1, 1}}, {{1, 1, 1}, {0, 0, 1}}, {{1, 1, 1}}, {{1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 1}}, {{1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 0}}, {{1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {0, 0, 1}}, {{1, 1, 0}}, {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 0}}, {{1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {0, 0, 1}}, {{1, 0, 1}}, {{1, 0, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 1}}, {{1, 0, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 0}}, {{1, 0, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {0, 0, 1}}, {{1, 0, 0}}, {{1, 0, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 1}}, {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 0}}, {{1, 0, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}};
eachTest {
string a;
string b;
string c;
cin >> a;
cin >> b;
cin >> c;
bool can = true;
forto(a.size(), i) {
if (c[i] != a[i] && c[i] != b[i]) {
can = false;
break;
}
}
decision(can);
out("\n");
}
} | cpp |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
void solve()
{
LL n, a, b;
cin >> n >> a >> b;
LL t = (n + 1) / 2;
if(t <= a)
{
cout << n << '\n';
}
else
{
LL tmp = t / a;
LL ans = tmp * (a + b);
if(t % a) ans += t % a;
else ans -= b;
if(ans < n) cout << n << '\n';
else cout << ans << '\n';
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while(T--) solve();
return 0;
} | cpp |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pi;
#define pb push_back
const int MN=78501;
int N, at=170, a,b, ans = MN; bool pvis[1001];
vector<int> prime, vals; vector<vector<int>> adj; vector<pi> dist;
unordered_map<int, int> ind; // (value, index it maps to)
void bfs1(int r){ queue<pi> q; q.push({r,-1}); dist[r]={1,r};
while(!q.empty()){ pi t = q.front(); int x=t.first, p=t.second; q.pop();
for(int nx: adj[x]) if(nx!=p && nx>r) {
if(dist[nx].second==dist[x].second) { ans=min(ans,dist[x].first+dist[nx].first-1);
if(dist[x].first>=ans/2+1) return; }
else{ dist[nx]={dist[x].first + 1,r}; q.push({nx,x}); } } } }
void bfs(int r){ queue<pi> q; q.push({r,-1}); dist[r]={1,r};
while(!q.empty()){ pi t = q.front(); int x=t.first, p=t.second; q.pop();
for(int nx: adj[x]) if(nx!=p && nx>=r && adj[nx].size()>1) {
if(dist[nx].second==dist[x].second) { ans=min(ans,dist[x].first+dist[nx].first-1);
if(dist[x].first>=ans/2+1) return; }
else { dist[nx]={dist[x].first + 1,r}; q.push({nx,x}); } } } }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
prime.reserve(170); prime.pb(0); prime.pb(1);
for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.pb(i);
for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; } adj.resize(MN);
cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x;
for (int j=2; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0;
while (x%prime[j] == 0) { x /= prime[j]; cnt++; }
if (cnt%2 == 1) vals.pb(prime[j]); }
if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; }
if(x!=1) vals.pb(x); int sz=5000;
for (int k: vals) if (ind.count(k) == 0)
{ if (k > 1e3) ind[k] = ++at;
else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin();
ind[k]=t; } } ind[1]=1;
if(vals.size()==1) adj[1].pb(ind[vals.front()]);
else { a=ind[vals.front()]; b=ind[vals.back()];
if(a==2 || a==3) adj[a].pb(b);
else adj[a].pb(b); adj[b].pb(a); }
} dist.resize(at+1);
for(int x:{1,2,3}) if(adj[x].size()>1) bfs1(x);
for (int j: prime) if(j>3 && adj[ind[j]].size()>1) bfs(ind[j]);
cout << (ans == MN ? -1 : ans) <<'\n';
} | cpp |
1307 | D | D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | #include <bits/stdc++.h>
#define SQ(a) (a)*(a)
#define all(a) (a).begin(), (a).end()
using namespace std;
using i64 = long long int;
using pi = pair<int, int>;
constexpr int INF{ numeric_limits<int>::max() / 2 };
constexpr int MOD{ 0 };
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, k;
cin >> n >> m >> k;
vector adj(n + 1, vector<int>());
vector<int> v(k);
for (auto& x : v)
cin >> x;
for (int i{ 0 }; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<int> dist_1(n + 1, -1), dist_n(n + 1, -1);
auto bfs = [&](int s, vector<int>& d) {
queue<int> q;
q.push(s);
d[s] = 0;
while (!q.empty()) {
int t{ q.front() };
q.pop();
for (auto x : adj[t])
if (d[x] == -1) {
d[x] = d[t] + 1;
q.push(x);
}
}
};
bfs(1, dist_1);
bfs(n, dist_n);
sort(all(v), [&](int& x, int& y) {
return dist_1[x] - dist_n[x] < dist_1[y] - dist_n[y];
});
int res{ 0 }, t{ -INF };
for (auto x : v) {
res = max(res, dist_n[x] + t + 1);
t = max(t, dist_1[x]);
}
cout << min(res, dist_1[n]);
return 0;
} | cpp |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void test_case(int test)
{
int n;
cin >> n;
set<int> a;
int temp;
for (int i = 0; i < n; ++i)
{
cin >> temp;
a.insert(temp);
}
cout << a.size() << "\n";
}
int main()
{
int T;
cin >> T;
for (int t = 1; t <= T; ++t) test_case(t);
return 0;
} | cpp |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | #include <cmath>
#include <iostream>
using namespace std;
int n, m, block;
int op, x, y;
int a[2000005], pre[2000005], sum[2000005];
int sec (int x) {return (x - 1) / block + 1;}
void modify (int l) {
sum[l] = 0;
int s = sec (l), tmp = l;
while (sec (tmp) == s && tmp <= n) {
tmp += a[tmp];
++ sum[l];
}
pre[l] = tmp;
}
int main () {
scanf ("%d%d", &n, &m);
block = sqrt (n);
for (int i = 1; i <= n; i ++) scanf ("%d", &a[i]);
for (int i = 1; i <= n; i ++) modify (i);
for (int i = 1; i <= m; i ++) {
scanf ("%d%d", &op, &x);
if (op == 0) {
scanf ("%d", &y);
a[x] = y;
for (int j = x; j>=(sec(x)-1)*block+1; -- j) {
if (j + a[j] > min(sec(x)*block,n) ) {
pre[j] = j + a[j];
sum[j] = 1;
}
else {
pre[j] = pre[j + a[j] ];
sum[j] = sum[j + a[j] ] + 1;
}
}
}
else {
int ans = 0;
while (pre[x] <= n) {
ans += sum[x];
x = pre[x];
}
while (x + a[x] <= n) {
++ ans;
x += a[x];
}
printf ("%d %d\n", x, ans + 1);
}
}
return 0;
}
| cpp |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,
tree_order_statistics_node_update> indexed_set;
#define endl '\n'
#define ilihg ios_base::sync_with_stdio(false);cin.tie(NULL)
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
clock_t time_req=clock();
ilihg;
int t=1;
// cin>>t;
while(t--){
int n,m;
cin>>n>>m;
int a[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>a[i][j];
}
}
int l=0;
int r=1e9;
while(l<r){
vector<int> dp(1<<m);
int x=(l+r+1)/2;
for(int i=0;i<n;i++){
int c=0;
for(int j=0;j<m;j++){
if(a[i][j]>=x){
c+=(1<<j);
}
}
dp[c]=i+1;
}
for(int i=(1<<m)-1;i>=0;i--){
if(dp[i]){
for(int j=0;j<m;j++){
if(i&(1<<j)){
dp[i^(1<<j)]=dp[i];
}
}
}
}
int z=0;
for(int i=0;i<n;i++){
int c=0;
for(int j=0;j<m;j++){
if(a[i][j]>=x){
c+=(1<<j);
}
}
if(dp[(1<<m)-1-c]){
z=1;
}
}
// cout<<x<<" "<<z<<endl;
if(z){
l=x;
}
else{
r=x-1;
}
}
vector<int> dp(1<<m);
for(int i=0;i<n;i++){
int c=0;
for(int j=0;j<m;j++){
if(a[i][j]>=l){
c+=(1<<j);
}
}
dp[c]=i+1;
}
for(int i=(1<<m)-1;i>=0;i--){
if(dp[i]){
for(int j=0;j<m;j++){
if(i&(1<<j)){
dp[i^(1<<j)]=dp[i];
}
}
}
}
for(int i=0;i<n;i++){
int c=0;
for(int j=0;j<m;j++){
if(a[i][j]>=l){
c+=(1<<j);
}
}
if(dp[(1<<m)-1-c]){
cout<<i+1<<" "<<dp[(1<<m)-1-c]<<endl;
break;
}
}
}
#ifndef ONLINE_JUDGE
cout<<"Time : "<<fixed<<setprecision(6)<<((double)(clock()-time_req))/CLOCKS_PER_SEC<<endl;
#endif
} | cpp |
1286 | E | E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
OutputCopy1
2
4
5
7
9
12
InputCopy4
a 2
y 2
z 0
y 2
OutputCopy2
2
2
2
InputCopy5
a 7
u 5
t 3
s 10
s 11
OutputCopy7
9
11
12
13
NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313. | [
"data structures",
"strings"
] | #include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 6e5 + 5;
int n, w, s[N], mn[N<<2], ne[N], fa[N][26], sum;
map<int, int> mp;char op;
__int128 ans;
void pushup(int x){
mn[x] = min(mn[x<<1], mn[x<<1|1]);
}
void update(int x, int l, int r, int pos, int k){
if(l == r){
mn[x] = k;
return;
}
int mid = (l + r) >> 1;
if(pos <= mid) update(x<<1, l, mid, pos, k);
else update(x<<1|1, mid + 1, r, pos, k);
pushup(x);
}
int query(int x, int l, int r, int l1, int r1){
if(l1 <= l && r <= r1) return mn[x];
int mid = (l + r) >> 1, res = 1e18;
if(l1 <= mid) res = min(res, query(x<<1, l, mid, l1, r1));
if(r1 > mid) res = min(res, query(x<<1|1, mid + 1, r, l1, r1));
return res;
}
void add(int x, int k){
mp[x] += k, sum += x*k;
}
int insert(int w){
int res = 0;
vector<map<int, int>::iterator> vec;
for(auto it = mp.upper_bound(w); it != mp.end(); it++){
res += it->second, sum -= it->first * it->second;
vec.push_back(it);
}
for(auto it:vec) mp.erase(it);
return res;
}
template <typename T>
void write(T x){
if(x > 9) write(x/10);
cout << (char)(x%10 + '0');
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n;
cin >> op >> w;
s[1] = op - 'a';
update(1, 1, n, 1, w);
ans = w;
write(ans);
cout << '\n';
for(int i = 2, j = 0; i <= n; i++){
cin >> op >> w;
s[i] = (op - 'a' + ans%26)%26;
w = w ^ (ans & ((1<<30) - 1));
while(j && s[j + 1] != s[i]) j = ne[j];
if(s[j + 1] == s[i]) j++;
ne[i] = j;
if(s[i] == s[1]) add(w, 1);
update(1, 1, n, i, w);
ans += query(1, 1, n, 1, i);
for(int c = 0; c < 26; c++) fa[i][c] = fa[ne[i]][c];
fa[i][s[ne[i] + 1]] = ne[i];
for(int c = 0; c < 26; c++){
if(c == s[i]) continue;
for(int k = fa[i - 1][c]; k; k = fa[k][c]) add(query(1, 1, n, i - k, i - 1), -1);
}
add(w, insert(w));
ans += sum;
write(ans);
cout << '\n';
}
return 0;
} | cpp |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
#define int long long
#define ld long double
#define pb push_back
#define vi vector <int>
#define vpi vector <pair<int,int>>
#define vvi vector<vector<int>>
#define mii map <int,int>
#define mem(a,x) memset(a,x,sizeof(a))
#define endl '\n'
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define setbits(x) __builtin_popcountll(x)
#define rep(i, a, b) for (int i = a; i < b; ++i)
#define repb(i,a,b) for(int i=a-1;i>=b;--i)
#define repn(i,a,b,n) for(int i=a;i<b;i+=n)
#define take(a,n) for(int i=0;i<n;++i) cin>>a[i];
#define printv(v) for(auto x:v) cout<<x<<" ";
#define printa(a,n) for(int i=0;i<n;++i) cout<<a[i]<<" ";
#define w(t) int t; cin>>t; while(t--)
#define fastio \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
// const int Mod=998244353;
const int Mod=1e9+7;
int binaryexp(int a,int b){
int ans=0;
if(b<0)return 0;
if(b==0)return 1;
else if(b==1)return a;
else if(b%2){
ans=(a*(binaryexp((a*a)%Mod,b/2)%Mod))%Mod;
}
else ans=binaryexp((a*a)%Mod,b/2)%Mod;
return ans%Mod;
}
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
int32_t main()
{ fastio;
int n,k;
cin>>n>>k;
vector<string> s(n);
take(s,n);
int ans=0;
rep(i,0,n)
{
set<string> check;
rep(j,i+1,n)
{
string temp;
rep(l,0,k)
{
if(s[j][l]==s[i][l]) temp.pb(s[i][l]);
else
{
if(s[i][l]=='S' && s[j][l]=='E') temp.pb('T');
else if(s[i][l]=='S' && s[j][l]=='T') temp.pb('E');
else if(s[i][l]=='E' && s[j][l]=='S') temp.pb('T');
else if(s[i][l]=='E' && s[j][l]=='T') temp.pb('S');
else if(s[i][l]=='T' && s[j][l]=='S') temp.pb('E');
else if(s[i][l]=='T' && s[j][l]=='E') temp.pb('S');
}
}
if(check.find(temp)!=check.end()) ans++;
else check.insert(s[j]);
temp.clear();
}
check.clear();
}
cout<<ans;
return 0;
} | cpp |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
constexpr int N = 100'000;
long long x0, y0, bx, by, t, xs, ys;
int ax, ay;
vector<pair<long long, long long>> p;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> x0 >> y0 >> ax >> ay >> bx >> by >> xs >> ys >> t;
while (x0 <= 5E16 && y0 <= 5E16) {
p.emplace_back(x0, y0);
x0 = ax * x0 + bx;
y0 = ay * y0 + by;
}
int ans = 0;
for (int i = 0; i < int(p.size()); ++i)
for (int j = 0; j < int(p.size()); ++j)
if (abs(xs - p[i].first) + abs(ys - p[i].second) + abs(p[i].first - p[j].first) + abs(p[i].second - p[j].second) <= t)
ans = max(ans, abs(i - j) + 1);
cout << ans << endl;
return 0;
} | cpp |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll lcm(ll a,ll b) { return a/gcd(a,b)*b; }
#define endl '\n';
void solve()
{
int n; cin>>n;
string s; cin>>s;
int c = 0;
for (int i = 0; i < n; i++)
{
if ((s[i]-'1')%2==0)
{
c++;
}
}
if (c>1)
{
int a = 2;
for (int i = 0; i < n; i++)
{
if ((s[i]-'1')%2==0 && a!=0)
{
cout<<s[i];
a--;
}
}
}
else
{
cout<<-1;
}
cout<<endl;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t;
cin >> t;
while(t--)
{
solve();
}
return 0;
} | cpp |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | #include<bits/stdc++.h>
#define ll long long
#define int long long
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rrep(i,a,b) for(int i=a;i>=b;i--)
#define repin rep(i,0,n)
#define di(a) int a;cin>>a;
#define precise(i) cout<<fixed<<setprecision(i)
#define vi vector<int>
#define si set<int>
#define mii map<int,int>
#define take(a,n) for(int j=0;j<n;j++) cin>>a[j];
#define give(a,n) for(int j=0;j<n;j++) cout<<a[j]<<' ';
#define vpii vector<pair<int,int>>
#define sis string s;
#define sin string s;cin>>s;
#define db double
#define be(x) x.begin(),x.end()
#define pii pair<int,int>
#define pb push_back
#define pob pop_back
#define ff first
#define ss second
#define lb lower_bound
#define ub upper_bound
#define bpc(x) __builtin_popcountll(x)
#define btz(x) __builtin_ctz(x)
using namespace std;
const long long INF=1e18;
const long long M=1e9+7;
const long long MM=998244353;
int power( int N, int M){
int power = N, sum = 1;
if(N == 0) sum = 0;
while(M > 0){if((M & 1) == 1){sum *= power;}
power = power * power;M = M >> 1;}
return sum;
}
struct segtree{
int size;
vector<int> operations;
vector<int> values;
int NEUTRAL_ELEMENT = LONG_MIN;
int NO_OPERATION = LLONG_MAX-1;
int modify_op(int a,int b,int len){
if(b==NO_OPERATION)return a;
if(a==NO_OPERATION)return b;
return a+b;
}
int calc_op(int a,int b){
return max(a,b);
}
void apply_mod_op(int &a,int b,int len){
a=modify_op(a,b,len);
}
void init(int n){
size=1;
while(size<n)size*=2;
operations.assign(2*size,0LL);
values.assign(2*size,LONG_MIN);
}
void propogate(int x, int lx, int rx){
if(rx-lx==1)return;
int m = (rx+lx)/2;
apply_mod_op(operations[2*x+1],operations[x],1);
apply_mod_op(values[2*x+1],operations[x],m-lx);
apply_mod_op(operations[2*x+2],operations[x],1);
apply_mod_op(values[2*x+2],operations[x],rx-m);
operations[x]=NO_OPERATION;
}
void build(vi &a,int x,int lx,int rx){
if(rx-lx==1){
if(lx<a.size()){
values[x]=a[lx];
}
return;
}
int m = (lx+rx)/2;
build(a,2*x+1,lx,m);
build(a,2*x+2,m,rx);
values[x]=(values[2*x+1]+values[2*x+2]);
}
void build(vi &a){
build(a,0,0,size);
}
void modify(int l,int r,int v,int x,int lx,int rx){
propogate(x,lx,rx);
if(lx>=r || l>=rx)return;
if(lx>=l && rx<=r){
apply_mod_op(operations[x],v,1);
apply_mod_op(values[x],v,rx-lx);
return;}
int m = (lx+rx)/2;
modify(l,r,v,2*x+1,lx,m);
modify(l,r,v,2*x+2,m,rx);
values[x]=calc_op(values[2*x+1],values[2*x+2]);
apply_mod_op(values[x],operations[x],rx-lx);
}
void modify(int l,int r,int v){
return modify(l,r,v,0,0,size);
}
int calc(int l,int r,int x,int lx,int rx){
propogate(x,lx,rx);
if(lx>=r || l>=rx)return NEUTRAL_ELEMENT;
if(lx>=l && rx<=r){return values[x];}
int m = (lx+rx)/2;
int m1=calc(l,r,2*x+1,lx,m);
int m2=calc(l,r,2*x+2,m,rx);
auto res = calc_op(m1,m2);
apply_mod_op(res,operations[x],min(r,rx)-max(l,lx));
return res;
}
int calc(int l,int r){
return calc(l,r,0,0,size);
}
};
void solve()
{
di(n) di(m) di(p)
vpii v2,v3;
repin{
di(x) di(y)
v2.pb({y,x});
}
sort(be(v2));
vpii v,v1;
rep(i,0,v2.size()){
if(v.empty()){v.pb(v2[i]);continue;}
if(v2[i].ff==(v.back()).ff){
v.pob();
v.pb(v2[i]);continue;
}
if((v.back()).ss>=v2[i].ss){
continue;
}
v.pb(v2[i]);
}
rep(i,0,m){
di(x) di(y)
v3.pb({y,x});
}
sort(be(v3));
rep(i,0,v3.size()){
if(v1.empty()){v1.pb(v3[i]);continue;}
if(v3[i].ff==(v1.back()).ff){
v1.pob();
v1.pb(v3[i]);continue;
}
if((v1.back()).ss>=v3[i].ss){
continue;
}
v1.pb(v3[i]);
}
// for(auto x : v){cout<<x.ff<<" "<<x.ss<<"\n";}cout<<"\n";
// for(auto x : v1){cout<<x.ff<<" "<<x.ss<<"\n";}cout<<"\n";
int ans = v[0].ff+v1[0].ff;
ans*=-1;
vector<pair<pii, int>> res;
rep(i,0,p){
di(x) di(y) di(z)
res.pb({{x,y},z});
}
sort(be(res));
segtree st;
st.init(1000005);
rep(i,0,v1.size()){
int dy = LONG_MAX+1LL;
// cout<<dy<<"\n";
st.modify(v1[i].ss,v1[i].ss+1,dy-v1[i].ff);
// cout<<st.calc(v1[i].ss,v1[i].ss+1)<<"\n";
}
int l = 0;
rep(i,0,v.size()){
int re = -v[i].ff;
while(l<res.size() && ((res[l].ff.ff) < v[i].ss)){
st.modify(res[l].ff.ss+1,1000005,res[l].ss);
l++;
}
re+=st.calc(0,1000001);
// cout<<re<<"\n";
ans=max(ans,re);
}
cout<<ans<<"\n";
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef NCR
init();
#endif
#ifdef SIEVE
sieve();
#endif
solve();
return 0;
} | cpp |
1292 | C | C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10. | [
"combinatorics",
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
const int N = 3005;
vector<int> G[N];
long long dp[N][N];
int par[N][N], sz[N][N], fpar[N][N];
void dfs(int rt, int v, int p) {
par[rt][v] = p;
fpar[rt][v] = (p == rt ? v : fpar[rt][p]);
sz[rt][v] = 1;
for (int u: G[v]) {
if (u == p) continue;
dfs(rt, u, v);
sz[rt][v] += sz[rt][u];
}
}
long long calc(int u, int v) {
long long &x = dp[u][v];
if (x != -1) return x;
if (u == v) return x = 0;
bool flag = (u == 4 && v == 5);
x = calc(u, par[u][v]);
if (fpar[u][v] != v) x = max(x, calc(v, fpar[u][v]));
x += sz[u][v]*(sz[u][u]-sz[u][fpar[u][v]]);
dp[v][u] = x;
return x;
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
dp[i][j] = -1;
}
}
int n;
cin >> n;
for (int i = 0; i < n-1; i++) {
int u, v;
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
for (int v = 1; v <= n; v++) {
dfs(v, v, v);
}
long long ans = 0;
for (int u = 1; u <= n; u++) {
for (int v = 1; v <= n; v++) {
ans = max(ans, calc(u, v));
}
}
cout << ans << '\n';
}
| cpp |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample: | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | #include <bits/stdc++.h>//114514
using namespace std;
const int maxn = 2e5 + 10;
int n, m;
vector<int> G[maxn];
int T;
int fa[maxn], dep[maxn];
vector<int> ans;
class Node {
public:
int u, dep;
Node() = default;
Node(int u, int dep) : u(u), dep(dep) {}
const bool operator<(const Node& d) const {
return dep < d.dep;
}
};
multiset<Node> s;
int tag[maxn];
void dfs(int u, int f) {
fa[u] = f;
dep[u] = dep[f] + 1;
for (int v : G[u]) {
if (v == f)
continue;
if (!dep[v])
dfs(v, u);
else if (dep[u] - dep[v] + 1 >= T) {
printf("2\n");
int p = u;
printf("%d\n%d ", dep[u] - dep[v] + 1, v);
do {
printf("%d ", p);
p = fa[p];
} while (p != v);
exit(0);
}
}
if(!tag[u]){
ans.emplace_back(u);
for(int v : G[u]){
tag[v] = true;
}
}
}
int main() {
scanf("%d%d", &n, &m);
T = (int)ceil(sqrt(1.0 * n));
for (int i = 1; i <= m; i++) {
int u, v;
scanf("%d%d", &u, &v);
G[u].emplace_back(v);
G[v].emplace_back(u);
}
dfs(1, 0);
for (int i = 1; i <= n; i++) {
s.emplace(i, dep[i]);
}
printf("1\n");
for (int i = 1; i <= T; i++) {
printf("%d ", ans[i - 1]);
}
}
| cpp |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = tuple<int, int>;
using vi = vector<ll>;
using vii = vector<ii>;
using vvi = vector<vi>;
using si = set<ll>;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
ll n, t;
cin >> t;
while (t--) {
cin >> n;
vi a(n), b(n);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) cin >> b[i];
sort(a.begin(), a.end());
sort(b.begin(), b.end());
for (int i = 0; i < n; i++) cout << a[i] << " \n"[i == n-1];
for (int i = 0; i < n; i++) cout << b[i] << " \n"[i == n-1];
}
} | cpp |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence. | [
"data structures",
"geometry",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
char buf[1<<23],*p1=buf,*p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
template <typename T>
inline void read(T &f)
{
f=0;T fu=1;char c=getchar();
while(c<'0'||c>'9') {if(c=='-'){fu=-1;}c=getchar();}
while(c>='0'&&c<='9') {f=(f<<3)+(f<<1)+(c&15);c=getchar();}
f*=fu;
}
template <typename T>
void print(T x,char c=0)
{
if(x<0) putchar('-'),x=-x;
if(x<10) putchar(x+48);
else print(x/10),putchar(x%10+48);
if(c) putchar(c);
}
inline void reads(string &f)
{
string str="";char ch=getchar();
while(ch<'!'||ch>'~') ch=getchar();
while((ch>='!')&&(ch<= '~')) str+=ch,ch=getchar();
f=str;
}
void prints(string s)
{
for(int i=0;s[i];++i)
putchar(s[i]);
}
typedef long long ll;
const int multicase=0,debug=0,maxn=1e6+50;
const double eps=1e-10;
int sgn(double x)
{
if(fabs(x)<eps) return 0;
else return x<0?-1:1;
}
int n,a[maxn];
double ans[maxn];
struct Point
{
double x,y;
Point(){}
Point(double x,double y):x(x),y(y){}
Point operator - (Point B){return Point(x-B.x,y-B.y);}
};
Point ch[maxn],p[maxn];
double Cross(Point A,Point B){return A.x*B.y-A.y*B.x;}
int Convex_hull(Point *p,int n,Point *ch)
{
int v=0;
for(int i=0;i<n;++i)
{
while(v>1&&sgn(Cross(ch[v-1]-ch[v-2],p[i]-ch[v-2]))<=0)
v--;
ch[v++]=p[i];
}
return v;
}
void solve()
{
read(n);
for(int i=1;i<=n;++i)
read(a[i]);
double sum=0;
p[0]={0,0};
for(int i=1;i<=n;++i)
{
sum+=a[i];
p[i]={1.0*i,1.0*sum};
}
int cnt=Convex_hull(p,n+1,ch);
for(int i=1;i<cnt;++i)
{
double val=ch[i].y-ch[i-1].y,len=ch[i].x-ch[i-1].x;
for(int j=ch[i-1].x+1;j<=ch[i].x;++j)
{
ans[j]=val/len;
}
}
for(int i=1;i<=n;++i)
printf("%.9lf\n",ans[i]);
}
int main()
{
#ifdef AC
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
clock_t program_start_clock=clock();
int _=1;
if(multicase) read(_);
while(_--) solve();
fprintf(stderr,"\nTotal Time: %lf ms",double(clock()-program_start_clock)/1000);
return 0;
} | cpp |
1290 | F | F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is: | [
"dp"
] | // LUOGU_RID: 92674887
#include<bits/stdc++.h>
#define file(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout)
#define mod 998244353
#define ll long long
using namespace std;
template<class T>void read(T&x) {
T f=1;x=0;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while('0'<=c&&c<='9'){x=x*10+c-'0';c=getchar();}
x*=f;
}
template<class T>void write(T x) {
if(x<0)putchar('-'),x=-x;int s[20],top=0;
while(s[++top]=x%10,x/=10);
while(top)putchar(s[top--]+'0');putchar(' ');
}
template<class T,class...Ts>void write(T arg,Ts...args){write(arg);write(args...);}
template<class...Ts>void print(Ts...args){write(args...);putchar('\n');}
void cer(){cerr << '\n';}
template<class T,class...Ts>void cer(T arg,Ts...args){cerr << arg << ' ';cer(args...);}
namespace SHIK {
char _st;
int n,m,x[6],y[6];
ll f[31][21][21][21][21][2][2];
ll dfs(int d,int px,int nx,int py,int ny,int p,int q) {
if(d == 30)return !px&&!nx&&!py&&!ny&&!p&&!q;
if(~f[d][px][nx][py][ny][p][q])return f[d][px][nx][py][ny][p][q];
int v = m>>d&1;ll res = 0;
for(int s=0; s<1<<n; ++s) {
int PX = px,NX = nx,PY = py,NY = ny;
for(int i=1; i<=n; ++i)if(s>>i-1&1) {
if(x[i] > 0)PX += x[i];else NX -= x[i];
if(y[i] > 0)PY += y[i];else NY -= y[i];
}
if((PX&1) == (NX&1) && (PY&1) == (NY&1))
res += dfs(d+1,PX>>1,NX>>1,PY>>1,NY>>1,(v==(PX&1))?p:!v,(v==(PY&1))?q:!v);
}return f[d][px][nx][py][ny][p][q] = res%mod;
}
char _ed;
int main() {
cerr << "Memory: " << ((&_st-&_ed)>>20) << '\n';
read(n);read(m);
for(int i=1; i<=n; ++i)read(x[i]),read(y[i]);
memset(f,-1,sizeof(f));
print((dfs(0,0,0,0,0,0,0)-1+mod)%mod);
return 0;
}
}
int main(){SHIK::main();} | cpp |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11. | [
"graphs",
"hashing",
"math",
"number theory"
] | // LUOGU_RID: 102607059
#include <bits/stdc++.h>
#define IOS std::ios::sync_with_stdio(false);std::cin.tie(0);std::cout.tie(0);
using namespace std;
#define INF 0x3f3f3f3f
#define endl '\n'
#define int long long
using pll = std::pair<int,int>;
void solv(){
int n, m;
cin >> n >> m;
vector<int>a(n + 7);
vector<set<int>>g(n + 8);
map<set<int>, int>mp;
for (int i = 1;i <= n;++i)cin >> a[i];
for (int i = 1;i <= m;++i) {
int u, v;
cin >> u >> v;
g[v].insert(u);
}
for (int i = 1;i <= n;++i) {
if (g[i].size())mp[g[i]] += a[i];
}
int ans = mp.begin()->second;
for (auto [x, y] : mp) {
ans = gcd(ans, y);
// cout << y << ' ';
}
cout << ans << '\n';
}
signed main(){
//#ifdef LOCAL
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
//#endif
IOS;
int T=1;
cin >> T;
while (T--){
solv();
}
return 0;
} | cpp |
1304 | F1 | F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp"
] | #include<bits/stdc++.h>
using namespace std;
int n,m,k;
int a[55][20200];
int f[55][200200];
int tree[55][20200];
int lowbit(int x)
{
return x&(-x);
}
int get(int x,int y,int i)
{
if (x>y) return 0;
int sum=0;
while(y>=x)
{
sum=max(sum,f[i][y]);
y--;
for (;y-lowbit(y)>=x;y-=lowbit(y)) sum=max(sum,tree[i][y]);
}
return sum;
}
void push(int x,int i,int j)
{
for (;j<=m;j+=lowbit(j)) tree[i][j]=max(tree[i][j],x);
}
int main()
{
int x;
cin>>n>>m>>k;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
cin>>x;
a[i][j]=a[i][j-1]+x;
}
for (int i=2;i<=n+1;i++)
{
for (int j=k;j<=m;j++)
{
f[i][j]=max(get(k,j-k,i-1),get(j+k,m,i-1));
for (int ii=max(j-k+1,k);ii<=j+k-1;ii++)
f[i][j]=max(f[i][j],f[i-1][ii]-(a[i-1][min(ii,j)]-a[i-1][max(j-k,ii-k)]));
f[i][j]+=a[i-1][j]-a[i-1][j-k]+a[i][j]-a[i][j-k];
push(f[i][j],i,j);
}
}
int ans=0;
for (int j=k;j<=m;j++)
ans=max(ans,f[n+1][j]);
cout<<ans<<endl;
}
| cpp |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | #include<bits/stdc++.h>
#define N 100010
#define B 350
using namespace std;
int n,q,a[N],las[N],cnt[N];
void get(int i){
if(i+a[i]>=n||i/B!=(i+a[i])/B)las[i]=i,cnt[i]=0;
else las[i]=las[i+a[i]],cnt[i]=cnt[i+a[i]]+1;
}
int main(){
scanf("%d%d",&n,&q);
for(int i=0;i<n;++i)cin>>a[i];
for(int i=n-1;i>=0;--i)get(i);
for(int o,p,v;q--;){
scanf("%d",&o);
if(o){
scanf("%d",&p);--p;
int dwn=0,s=0;
for (;p<n;dwn=las[p],p=dwn+a[dwn]) s+=cnt[p]+1;
printf("%d %d\n",dwn+1,s);
}
else{
scanf("%d%d",&p,&v);--p;a[p]=v;
for(int i=p;i>=0&&i/B==p/B;--i)get(i);
}
}
return 0;
} | cpp |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define int long long int
#define vi vector<int>
int gcd(int a,int b) {if (b==0) return a; return gcd(b, a%b);}
int lcm(int a,int b) { return a/gcd(a,b)*b; }
bool prime(int a) { if (a==1) return 0; for (int i=2;i<=round(sqrt(a));i++) if (a%i==0) return 0; return 1; }
void yes() { cout<<"Yes\n"; }
void no() { cout<<"No\n"; }
int ModExp(int x,int y){if(y==0) return 1;int p=ModExp(x,y/2);if(y&1)return (x*(p*p)%MOD)%MOD; return (p*p)%MOD;}
// *******************SOLVE START**************
void solve(){
int n;
cin>>n;
vi arr(n);
int ele=INT_MIN,maxi=0;
for(int i=0;i<n;i++){
cin>>arr[i];
}
int a=INT_MAX,b=INT_MAX;
for(int i=0;i<n;i++){
if(arr[i]<i){
a=i;
break;
}
}
for(int i=n-1;i>=0;i--){
if(arr[i]<n-i-1){
b=i;
break;
}
}
// cout<<a<<" "<<b<<endl;
if(a==INT_MAX||b==INT_MAX){
yes();
return ;
}
b++;
a--;
// cout<<a<<" "<<b<<endl;
int r1=1,r2=1;
for(int i=a+1;i<n;i++){
if(i>=arr[a]||arr[i]<n-i-1){
r1=0;
break;
}
}
for(int i=0;i<b;i++){
if(i>=arr[b]||arr[i]<i){
r2=0;
break;
}
}
if(r1||r2){
yes();
}
else{
no();
}
}
// *******************SOLVE END****************
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.out","w",stdout);
#endif
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t=1;
cin>>t;
while(t--){
solve();
}
return 0;
} | cpp |
1305 | G | G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105) — the ages of the people.OutputOutput exactly one integer — the maximum possible combined gainings of all nn people.ExampleInputCopy3
1 2 3
OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it. | [
"bitmasks",
"brute force",
"dp",
"dsu",
"graphs"
] | // LUOGU_RID: 100960512
#include <bits/stdc++.h>
#define sizen 200003
using namespace std;
const int MAXN = 1 << 18;
int a[sizen];
pair<int, int> large[sizen], best[MAXN + 3][2];
int fa[sizen];
int find(int x) {return (fa[x] == x ? x : fa[x] = find(fa[x]));}
void update(pair<int, int> A[2], pair<int, int> B[2]) {
if (A[0].first < B[0].first || (A[0].first == B[0].first && A[0].second != B[0].second)) {
if (B[0].second != A[0].second) A[1] = A[0];
A[0] = B[0];
} else if (A[1].first < B[0].first && B[0].second != A[0].second) A[1] = B[0];
if (A[0].first < B[1].first || (A[0].first == B[1].first && A[0].second != B[1].second)) {
if (B[1].second != A[0].second) A[1] = A[0];
A[0] = B[1];
} else if (A[1].first < B[1].first && B[1].second != A[0].second) A[1] = B[1];
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int n;
cin >> n;
long long ans = 0;
for (int i = 1; i <= n + 1; ++i) fa[i] = i;
for (int i = 1; i <= n; ++i) cin >> a[i];
int cnt = n + 1;
while (cnt > 1) {
for (int i = 0; i < MAXN; ++i) best[i][0] = best[i][1] = make_pair(-1, -1);
for (int i = 1; i <= n + 1; ++i) {
int id = find(i);
if (best[a[i]][0].second == -1)
best[a[i]][0] = make_pair(a[i], id);
else if (best[a[i]][1].second == -1 && id != best[a[i]][0].second)
best[a[i]][1] = make_pair(a[i], id);
// cout << id << " " << best[a[i]][0].first << " " << best[a[i]][1].first << endl;
}
for (int i = 0; i < 18; ++i)
for (int j = 0; j < MAXN; ++j)
if ((j >> i) & 1) {
int k = j ^ (1 << i);
update(best[j], best[k]);
// cout << j << " " << best[j][0].first << endl;
}
for (int i = 1; i <= n + 1; ++i)
large[i] = make_pair(-1, -1);
for (int i = 1; i <= n + 1; ++i) {
// cout << i << " ";
int id = find(i);
// cout << id << endl;
// cout << "#" << ((MAXN - 1) ^ (a[i])) << endl;
int x = (MAXN - 1) ^ (a[i]);
// cout << "@" << x << endl;
// int x = 0;
// cout << best[x][0].first << endl;
if (best[x][0].first == -1) continue;
if ((best[x][0].first ^ a[i]) > large[id].first && best[x][0].second != id) large[id] = make_pair(best[x][0].first ^ a[i], best[x][0].second);
if ((best[x][1].first ^ a[i]) > large[id].first && best[x][1].second != id) large[id] = make_pair(best[x][1].first ^ a[i], best[x][1].second);
// cout << "-------------------" << endl;
}
// cout << "@@@@" << endl;
// cout << cnt << endl;
for (int i = 1; i <= n + 1; ++i) {
if (find(i) != i) continue;
if (large[i].first == -1) continue;
int x = i, y = large[i].second;
y = find(y);
if (x == y) continue;
fa[x] = y;
--cnt;
ans += large[i].first;
}
}
for (int i = 1; i <= n; ++i) ans -= a[i];
cout << ans << endl;
return 0;
} | cpp |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000
| [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vb = vector<bool>;
using vvb = vector<vb>;
using vi = vector<int>;
using vvi = vector<vi>;
using vl = vector<ll>;
using vvl = vector<vl>;
using vc = vector<char>;
using vvc = vector<vc>;
using vs = vector<string>;
#define pb push_back
#include <bits/stdc++.h>
using namespace std;
// ll mod = 1e9 + 7 ;
// const ll maxn = 1e5+1 ;
// ll fac[maxn],invfact[maxn];
// ll power(ll x, ll y)
// {
// ll res = 1;
// x = x % mod;
// while (y > 0) {
// if (y & 1)
// res = (res * x) % mod;
// y = y >> 1;
// x = (x * x) % mod;
// }
// return res;
// }
// ll modInverse(ll n)
// {
// return power(n, mod - 2);
// }
// ll NCR(ll n, ll r, ll p=mod)
// {
// if(r < 0 || n < 0)
// assert(false);
// if( n < r ) return 0;
// if (r == 0 || r == n)
// return 1;
// return ( fac[n] * invfact[r] % mod) * invfact[n - r] % mod;
// }
// void comp()
// {
// fac[0] = 1, invfact[0] = 1;
// for (ll i = 1; i < maxn; i++){
// fac[i] = (fac[i - 1] * i) % mod;
// invfact[i] = modInverse(fac[i]);
// }
// }
void solve()
{
int n;
cin >> n;
string s;
cin >> s;
bool ok = true;
int dec = s[0] - 'a';
string ans = "0";
int mx = s[0]-'a';
set<int> one;
for (int i = 1; i < n; i++)
{
if (s[i] - 'a' >= mx)
ans.push_back('0');
else
{
for (auto j:one)
{
if(j>s[i]-'a'){
ok = false ;
break ;
}
}
one.insert(s[i]-'a') ;
ans.push_back('1');
}
mx = max(mx, s[i] - 'a');
}
if (ok)
cout << "YES\n"
<< ans << endl;
else
cout << "NO\n";
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// comp() ; -> to use ncr
int t = 1;
while (t--)
{
solve();
}
return 0;
} | cpp |
1288 | E | E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] | [
"data structures"
] | #include<bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
#define int long long
#define ld long double
#define vi vector<int>
#define vpi vector<pair<int,int>>
#define vvi vector<vector<int>>
#define ss second
#define ff first
#define inf (int)1e18
#define rz resize
#define pii pair<int,int>
#define rep(i,a,b) for(int i=a;i<b;i++)
#define pb push_back
#define all(x) x.begin(),x.end()
template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T>
using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define ook order_of_key
#define fbo find_by_order
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
#ifndef ONLINE_JUDGE
#define dbg(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define dbg(x...)
#endif
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
template <typename T1, typename T2>
istream &operator>>(istream &istream, pair<T1, T2> &p){return (istream >> p.first >> p.second);}
template <typename T>
istream &operator>>(istream &istream, vector<T> &v){for (auto &it : v)cin >> it;return istream;}
template <typename T1, typename T2>
ostream &operator<<(ostream &ostream, const pair<T1, T2> &p){return (ostream << p.first << " " << p.second);}
template <typename T>
ostream &operator<<(ostream &ostream, const vector<T> &c){for (auto &it : c)cout << it << " ";return ostream;}
template <typename T>void print(T &&t) { cout << t << "\n"; }
template <typename T, typename... Args>void print(T &&t, Args &&...args){cout << t << " ";print(forward<Args>(args)...);}
template <typename T> int32_t size_i(T &container) { return static_cast<int32_t>(container.size()); }
const ld PI = 3.141592653589793238;
const ld eps=1e-11;
const int mod_9= 998244353;
const int mod=1e9+7;
const int N=3e5+10;
const int lim=505;
void solve(){
int n,m;
cin >> n >> m;
ordered_set<pii> st;
vi minans(n+1);
vi maxans(n+1);
vi tim(n+1,0);
int cnt=0;
rep(i,1,n+1){
minans[i]=maxans[i]=i;
st.insert({0ll,i});
}
rep(i,0,m){
int e;
cin >> e;
minans[e]=1;
cnt--;
int pos=st.ook({tim[e],e})+1;
maxans[e]=max(maxans[e],pos);
st.erase({tim[e],e});
tim[e]=cnt;
st.insert({tim[e],e});
}
int c=0;
for(auto it:st){
c++;
maxans[it.ss]=max(maxans[it.ss],c);
}
rep(i,1,n+1)
cout << minans[i] << ' ' << maxans[i] << '\n';
}
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t=1;
// cin >> t;
while(t--){
solve();
}
return 0;
}
| cpp |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
#define x first
#define y second
#define all(v) v.begin(),v.end()
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
void solve()
{
int n,a,b;
cin>>n>>a>>b;
int mi = a + b - n + 1,mx = a + b - 1;
if(mi <= 0) mi = 1;
if(mi > n) mi = n;
if(mx > n) mx = n;
cout<<mi<<' '<<mx<<'\n';
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int tc = 1;
cin>>tc;
while (tc--)
{
solve();
}
return 0;
} | cpp |
1307 | F | F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n) — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105) — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi) — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below. | [
"dfs and similar",
"dsu",
"trees"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
template <typename T> inline void read(T &F) {
int R = 1; F = 0; char CH = getchar();
for(; !isdigit(CH); CH = getchar()) if(CH == '-') R = -1;
for(; isdigit(CH); CH = getchar()) F = F * 10 + CH - 48;
F *= R;
}
inline void file(string str) {
freopen((str + ".in").c_str(), "r", stdin);
freopen((str + ".out").c_str(), "w", stdout);
}
const int N = 4e5 + 10, Log = 19;
int n, m, k, co[N], anc[N], dep[N], fa[N][Log], dis[N]; vector<int> edge[N];
int getfa(int x) {
return anc[x] == x ? x : anc[x] = getfa(anc[x]);
}
int skp(int x, int d) {
while(d) x = fa[x][__builtin_ctz(d)], d -= (d & -d);
return x;
}
int getlca(int x, int y) {
if(dep[x] < dep[y]) swap(x, y);
x = skp(x, dep[x] - dep[y]);
if(x == y) return x;
for(int i = 31 - __builtin_clz(dep[x]); i >= 0; i--)
if(fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
return fa[x][0];
}
void predfs(int x) {
dep[x] = dep[fa[x][0]] + 1;
for(int i = 1; i < Log; i++)
fa[x][i] = fa[fa[x][i - 1]][i - 1];
for(int i : edge[x]) {
if(i == fa[x][0]) continue;
fa[i][0] = x; predfs(i);
}
}
void add(int x, int y) {
edge[x].emplace_back(y), edge[y].emplace_back(x);
}
void merge(int x, int y) {
x = getfa(x), y = getfa(y); anc[x] = y;
}
void bfs() {
queue<int> q; memset(dis, 0x3f, sizeof(dis));
for(int i = 1; i <= n; i++) if(co[i]) q.push(i), dis[i] = 0;
while(!q.empty()) {
int p = q.front(); q.pop(); if(dis[p] == k / 2) continue;
for(int i : edge[p]) {
if(dis[p] + 1 < dis[i])
dis[i] = dis[p] + 1, co[i] = co[p], q.push(i);
else merge(co[i], co[p]);
}
}
}
int main() {
//file("");
read(n), read(k), read(m); k *= 2;
for(int i = 1; i < n; i++) {
int x, y; read(x), read(y);
add(i + n, x), add(i + n, y);
}
for(int i = 1; i <= m; i++) {
int x; read(x); co[x] = i;
anc[i] = i;
}
n = 2 * n - 1; predfs(1); bfs();
int q; read(q);
for(int i = 1; i <= q; i++) {
int x, y; read(x), read(y);
const int z = getlca(x, y), d = dep[x] + dep[y] - 2 * dep[z];
if(d <= k) {
puts("YES"); continue;
}
if(dep[x] < dep[y]) swap(x, y);
const int a = skp(x, k / 2), b = (dep[y] - dep[z] < k / 2 ? skp(x, d - k / 2) : skp(y, k / 2));
if(co[a] && co[b] && getfa(co[a]) == getfa(co[b])) puts("YES");
else puts("NO");
}
#ifdef _MagicDuck
fprintf(stderr, "# Time: %.3lf s", (double)clock() / CLOCKS_PER_SEC);
#endif
return 0;
} | cpp |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | #include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<unordered_map>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstdlib>
#include<stack>
#include<ctime>
#define forin(i,a,n) for(int i=a;i<=n;i++)
#define forni(i,n,a) for(int i=n;i>=a;i--)
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=2e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
int T;
int n,m,k;
int w[N];
int ans;
void solve() {
n=read();
int a=read(),b=read();
if(a>=b) printf("%d\n",n);
else {
ll ans=0;
int c=n/(2*a);
ans+=(ll)c*(a+b);
int p=n%(2*a);
ll x=(ll)(b-a)*c;
if(p==0) ans-=min((ll)b,x);
else {
int q=p/2;
ans+=p;
ans-=min(x,(ll)q);
}
printf("%lld\n",ans);
}
}
int main() {
// init();
// stin();
scanf("%d",&T);
// T=1;
while(T--) solve();
return 0;
} | cpp |
13 | D | D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7 | [
"dp",
"geometry"
] | #include "bits/stdc++.h"
using namespace std;
typedef double ld;
typedef long long ll;
#define f first
#define s second
const int N=500;
int n,m;
struct pt{
int x,y;
};
pt R[N], B[N];
int cnt[N][N];
int main(){
cin.tie(0)->sync_with_stdio(0);
cin >> n >> m;
for(int i=0; i<n; i++){
cin >> R[i].x >> R[i].y;
}
for(int i=0; i<m; i++){
cin >> B[i].x >> B[i].y;
}
sort(R, R+n, [&](pt a, pt b){ return a.y<b.y; });
sort(B, B+m, [&](pt a, pt b){ return a.y<b.y; });
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
for(int k=0; k<m; k++){
if(!(R[i].y<=B[k].y && B[k].y<R[j].y)) continue;
pair<int,int> u={R[j].x-R[i].x, R[j].y-R[i].y};
pair<int,int> v={B[k].x-R[j].x, B[k].y-R[j].y};
cnt[i][j]+=ll(u.f)*v.s-ll(u.s)*v.f>0;
}
}
}
int ans=0;
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
for(int k=j+1; k<n; k++){
ans+=cnt[i][j]+cnt[j][k]==cnt[i][k];
}
}
}
cout << ans;
}
| cpp |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
for(int i = 0; i<n ; i++)
{
cin>>arr[i];
}
int e = 0, o = 0;
for(int i = 0;i<n;i++)
{
if(arr[i]%2==0)
{
e++;
}
else
{
o++;
}
}
if((n%2==0 && e == 0) || o == 0)
{
cout<<"NO"<<endl;
}
else if(o>0)
{
cout<<"YES"<<endl;
}
}
return 0;
}
| cpp |
1292 | F | F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0. After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible: b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8]) b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible: b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4]) b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9]) b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12]) b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty. | [
"bitmasks",
"combinatorics",
"dp"
] | #include<bits/stdc++.h>
#define mset(a,b) memset((a),(b),sizeof((a)))
#define rep(i,l,r) for(int i=(l);i<=(r);i++)
#define dec(i,l,r) for(int i=(r);i>=(l);i--)
#define cmax(a,b) (((a)<(b))?(a=b):(a))
#define cmin(a,b) (((a)>(b))?(a=b):(a))
#define Next(k) for(int x=head[k];x;x=li[x].next)
#define vc vector
#define ar array
#define pi pair
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define N 63
#define M 200010
using namespace std;
typedef double dd;
typedef long double ld;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
#define int long long
typedef pair<int,int> P;
typedef vector<int> vi;
const int INF=0x3f3f3f3f;
const dd eps=1e-9;
const int mod=1e9+7;
template<typename T> inline void read(T &x) {
x=0; int f=1;
char c=getchar();
for(;!isdigit(c);c=getchar()) if(c == '-') f=-f;
for(;isdigit(c);c=getchar()) x=x*10+c-'0';
x*=f;
}
int n,a[N],id[N],rd[N],ans,jie[N],invjie[N];
vi e[N],v,S,T;
int ts[N],cnt[M],f[M][N],sum;
bool vis[N];
inline int ksm(int a,int b,int mod){
int res=1;while(b){if(b&1)res=1ll*res*a%mod;a=1ll*a*a%mod;b>>=1;}return res;
}
inline int inv(int a){return ksm(a,mod-2,mod);}
inline void dfs(int k){
vis[k]=1;v.pb(k);
for(int to:e[k])if(!vis[to]){
// printf("k=%d to=%d\n",k,to);
dfs(to);
}
}
inline int DP(){
for(int x:v){
// printf("x=%d ",x);
if(!id[x]) S.pb(a[x]);else T.pb(a[x]);
}
// puts("");
if(T.empty()){
S.clear();return -1;
}
rep(i,0,(int)T.size()-1){
int nows=0;
rep(j,0,(int)S.size()-1){
// printf("T[%d]=%d S[%d]=%d\n",i,T[i],j,S[j]);
if(T[i]%S[j]==0) nows|=(1<<j);
}
cnt[nows]++;ts[i]=nows;
// printf("ts[%d]=%d\n",i,nows);
}
rep(i,0,(int)S.size()-1){
rep(j,0,(1<<((int)S.size()))-1){
if((j>>i)&1) cnt[j]+=cnt[j^(1<<i)];
}
}
// printf("cnt[1]=%d\n",cnt[1]);
rep(i,0,(int)T.size()-1){
f[ts[i]][1]++;
}
rep(i,1,(int)T.size()-1)rep(j,0,(1<<((int)S.size()))-1)if(f[j][i]){
bool op=0;
rep(k,0,(int)T.size()-1){
if((ts[k]&j)==0) continue;
if((ts[k]&j)==ts[k]){
if(op) continue;
else{
// puts("");
f[j][i+1]=(f[j][i+1]+f[j][i]*(cnt[j]-i)%mod)%mod;op=1;
}
}
else f[j|ts[k]][i+1]=(f[j|ts[k]][i+1]+f[j][i])%mod;
}
}
int ans=f[(1<<((int)S.size()))-1][T.size()];
rep(i,0,(1<<((int)S.size()))-1)rep(j,1,T.size()) f[i][j]=0,cnt[i]=0,ts[j-1]=0;
sum+=T.size()-1;ans=ans*invjie[T.size()-1]%mod;
S.clear();T.clear();
return ans;
}
signed main(){
// freopen("my.in","r",stdin);
// freopen("my.out","w",stdout);
read(n);rep(i,1,n) read(a[i]);
jie[0]=1;rep(i,1,n) jie[i]=1ll*jie[i-1]*i%mod;
invjie[n]=inv(jie[n]);dec(i,0,n-1) invjie[i]=invjie[i+1]*(i+1)%mod;
rep(i,1,n)rep(j,1,n){
if(i==j) continue;
if(a[j]%a[i]==0){
// printf("%d %d\n",i,j);
e[i].pb(j);id[j]++;rd[i]++;e[j].pb(i);
}
}
ans=1;sum=0;
// printf("ans=%d\n",ans);
rep(i,1,n)if(!vis[i]){
v.clear();dfs(i);
int nowans=DP();
if(nowans==-1) continue;
ans=ans*nowans%mod;
// printf("nowans=%d\n",nowans);
}
ans=ans*jie[sum]%mod;
printf("%d\n",ans);
return 0;
} | cpp |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"brute force",
"data structures",
"dp",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<ll>;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
int n;
cin >> n;
vi a(n);
for (int i = 0; i < n; i++) cin >> a[i];
ll best = 0, k = 0;
for (int i = 0; i < n; i++) {
ll ml = a[i], mr = a[i], sum = a[i];
for (int j = i - 1; j >= 0; j--)
ml = min(a[j], ml), sum += ml;
for (int j = i + 1; j < n; j++)
mr = min(a[j], mr), sum += mr;
if (sum > best) best = sum, k = i;
}
vi b(n);
b[k] = a[k];
ll ml = b[k], mr = b[k];
for (int j = k - 1; j >= 0; j--)
ml = min(a[j], ml), b[j] = ml;
for (int j = k + 1; j < n; j++)
mr = min(a[j], mr), b[j] = mr;
for (int i = 0; i < n; i++) cout << b[i] << " \n"[i==n-1];
}
| cpp |
1305 | G | G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105) — the ages of the people.OutputOutput exactly one integer — the maximum possible combined gainings of all nn people.ExampleInputCopy3
1 2 3
OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it. | [
"bitmasks",
"brute force",
"dp",
"dsu",
"graphs"
] | #include<bits/stdc++.h>
#define int long long
#define gmax(x,y) x=max(x,y)
#define gmin(x,y) x=min(x,y)
#define F first
#define S second
#define P pair
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,a,b) for(int i=a;i<b;i++)
#define V vector
#define RE return
#define ALL(a) a.begin(),a.end()
#define MP make_pair
#define PB emplace_back
#define PF push_front
#define FILL(a,b) memset(a,b,sizeof(a))
#define lwb lower_bound
#define upb upper_bound
#define lc (x<<1)
#define rc ((x<<1)|1)
#define sz(x) ((int)x.size())
using namespace std;
int n,a[200005];
int tot=(1<<18)-1;
struct DSU{
int fa[200005];
void init(int n){
FOR(i,1,n)fa[i]=i;
}
int get(int x){
RE (fa[x]==x)?x:(fa[x]=get(fa[x]));
}
void merge(int x,int y){
x=get(x);y=get(y);
fa[x]=y;
}
}T;
P<int,int> mx1[1<<18],mx2[1<<18];
int mx[200005],ed[200005];
void update(int x,int val,int fr){
if(a[val]>a[mx1[x].F]){
if(fr!=mx1[x].S)mx2[x]=mx1[x];
mx1[x]=MP(val,fr);
}else if(fr!=mx1[x].S&&a[val]>a[mx2[x].F]){
mx2[x]=MP(val,fr);
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n;
int ans=0;
FOR(i,1,n)cin>>a[i],ans-=a[i];
n++;
T.init(n);
a[0]=-1e18;
while(1){
rep(i,0,1<<18)mx1[i]=mx2[i]=MP(0,-1);
FOR(i,1,n)update(a[i],i,T.get(i));
rep(i,0,18)rep(mask,0,1<<18)if(!(mask&(1<<i))){
update(mask|(1<<i),mx1[mask].F,mx1[mask].S);
update(mask|(1<<i),mx2[mask].F,mx2[mask].S);
}
FOR(i,1,n)mx[i]=-1e18;
FOR(i,1,n){
int fr=T.get(i),res=tot^a[i];
int to=0,now=a[i];
if(mx1[res].S!=fr){
if(mx1[res].F>0)now+=a[mx1[res].F],to=mx1[res].S;
}else if(mx2[res].F>0)now+=a[mx2[res].F],to=mx2[res].S;
if(now>mx[fr]&&to){
mx[fr]=now;
ed[fr]=to;
}
}
V<P<int,P<int,int> > > v;
FOR(i,1,n)if(mx[i]>=0){
v.PB(MP(mx[i],MP(i,ed[i])));
}
sort(ALL(v));reverse(ALL(v));
for(auto u:v){
if(T.get(u.S.F)!=T.get(u.S.S)){
T.merge(u.S.F,u.S.S);
ans+=u.F;
}
}
int cnt=0;
FOR(i,1,n)cnt+=T.get(i)==i;
if(cnt==1)break;
}
cout<<ans;
RE 0;
}
| cpp |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define ll long long
#define endl "\n"
#define FOR(i,n) for(long long i = 0; i < n; i++)
#define FOR1(i,s,e,d) for(long long i = s; i < e; i += d)
#define FOR2(i,s,e,d) for(long long i = s; i > e; i -= d)
#define FOR3(x,v) for (auto x : v)
#define pll pair<long long, long long>
#define vi vector<int>
#define vl vector<long long>
#define vll vector<pair<long long, long long>>
#define vvl vector<vector<long long>>
#define vs vector<string>
#define vc vector<char>
#define mll map<long long, long long>
#define mlc map<long long,char>
#define mls map<long long,string>
#define mlvl map<long long, vector<long long>>
#define pql priority_queue<long long>
#define over(ans) {cout<<ans<<endl;return;}
#define all(v) (v).begin(), (v).end()
const ll INF = 1e9;
const ll mod = 998244353;
const ll mod1 = 1e9 + 7;
template<class T, class T1> bool ckmin(T& a, const T1& b) { return b < a ? a = b, 1 : 0; }
template<class T, class T1> bool ckmax(T& a, const T1& b) { return a < b ? a = b, 1 : 0; }
template<class c>
void display(c vect) {
FOR3(x, vect) cout << x << ' ';
cout << "\n";
}
void display(vll v) {
FOR3(x, v) cout << "(" << x.first << ", " << x.second << ") ";
cout << endl;
}
void display(vvl vect2d) {
FOR3(x, vect2d) display(x);
}
void display(mll m) {
FOR3(x, m) cout << x.first << ' ' << x.second << endl;
}
void display(mlvl m) {
FOR3(x, m) {
cout << x.first << " : ";
display(x.second);
}
}
vl vin(ll n) {
vl v(n);
FOR(i,n) cin >> v[i];
return v;
}
vi vin(int n) {
vi v(n);
FOR(i, n) cin >> v[i];
return v;
}
int to_int(string s) {
return stoi(s);
}
int to_int(char c) {
string s = {c};
return stoi(s);
}
char to_char(int i) {
return char('0' + i);
}
bool is_prime(ll n) {
if (n == 1) return false;
if (n == 2 || n == 3) return true;
if ( n % 6 == 1 || n % 6 == 5) {
for (ll k = 5; k*k <= n; k += 2) if (n % k == 0) return false;
return true;
}
return false;
}
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a % b);
}
ll inv(ll a, ll b){
return 1<a ? b - inv(b%a,a)*b/a : 1;
}
template<class T>
T power(T a, ll b) {
T res = 1;
for(; b; b /= 2, a *= a) if (b%2) {res *= a;}
return res;
}
template<class T>
T powermod(T a, ll b, ll P) {
a %= P; ll res = 1;
while (b > 0) {
if (b & 1) res = res * a % P;
a = a * a % P;
b >>= 1;
}
return res;
}
vl factors(ll n) {
vl factors;
ll i = 1;
while(i*i <= n) {
if (n%i == 0) {
factors.push_back(i);
if (i*i != n) factors.push_back(n/i);
}
i++;
}
sort(factors.begin(), factors.end());
return factors;
}
ll lsb(ll a) {return (a & -a);}
template < typename T>
struct Fenwick {
const ll n;
vector<T> a;
Fenwick(ll n) : n(n), a(n) {}
void add(ll x, T v) {
for (ll i = x+1; i <= n; i += i & -i) {
a[i-1] += v;
}
}
T sum(ll x) {
T ans = 0;
for (ll i = x; i > 0; i -= i & -i) {
ans += a[i-1];
}
return ans;
}
T rangeSum(ll l, ll r) {
return sum(r) - sum(l);
}
};
struct DSU {
vl f, siz;
DSU(ll n) : f(n), siz(n-1) { iota(f.begin(), f.end(), 0); }
ll leader(ll x) {
while (x != f[x]) x = f[x] = f[f[x]];
return x;
}
bool same(ll x, ll y) { return leader(x) == leader(y); }
bool merge(ll x, ll y) {
x = leader(x);
y = leader(y);
if (x == y) return false;
siz[x] += siz[y];
f[y] = x;
return true;
}
ll size(ll x) { return siz[leader(x)]; }
};
ll ncrmodP(ll n, ll r, ll P) {
ll fac[n+1];
fac[0] = 1;
FOR1(i, 1, n+1, 1) {
fac[i] = (fac[i-1] * i) % P;
}
return (fac[n] * inv(fac[r], P) % P * inv(fac[n-r], P) % P) % P;
}
vi primes_n(int n) {
vi primes;
FOR1(i, 1, n+1, 1) {
if (is_prime(i)) primes.push_back(i);
}
return primes;
}
// (condition ? value if yes : value if no)
// sort(v.begin(), v.end(), [](data_type x, data_type y) -> bool {
// return condition;
// });
// use 1.0 for decimal calculations
// cout << setprecision(12) << fixed << ans << endl;
void init() {
}
void solve() {
int n; cin >> n;
double ans = 0;
FOR1(i, 1, n+1, 1) ans += 1.0 / i;
cout << setprecision(12) << fixed << ans << endl;
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
init();
int t = 1;
// cin >> t;
FOR(i,t) {
// cout << "Case #" << i+1 << ": ";
solve();
}
} | cpp |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define uint unsigned long long
#define float long double
#define double long double
#define endl '\n'
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define f(i,a,b) for(int i = a; i <= b; i++)
#define fr(i,a,b) for(int i = a; i >= b; i--)
#define all(x) x.begin(),x.end()
#define sz(x) ((int)(x).size())
#define vec vector<int>
#define dvec vector<vector<int>>
#define pb push_back
//************Nitin1605************
vector<int> colour(200001,-1);
dvec g(200001);
vec dp(200001,-10);vector<bool> vis(200001,false);
int answer(int n,int p)
{
int ok=0;
for(auto i:g[n])
{
if(i==p)continue;
if(dp[i]==-10)answer(i,n);
if(dp[i]>0)ok=ok+dp[i];
}
if(colour[n]==1)ok++;
else ok--;
dp[n]=ok;
return ok;
}
void dfs(int p,int c)
{
if(dp[c]>0)
{
if((dp[p]-dp[c])>0 && dp[c]>0)dp[c]=dp[p];
}
else
{
if(dp[p]>0)dp[c]+=dp[p];
}
vis[c]=true;
for(auto i:g[c])if(!vis[i])dfs(c,i);
}
int32_t main()
{
ios_base::sync_with_stdio(false);cin.tie(0),cout.tie(0);
cout << fixed << setprecision(0);
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int TESTCASES=1,n;
//cin>>TESTCASES;
f(test,1,TESTCASES)
{
cin >> n;
f(i,1,n)cin >> colour[i];
f(i,1,n-1)
{
int x,y;
cin >> x >> y;
g[x].pb(y);
g[y].pb(x);
}
answer(1,0);vis[1]=true;
for(auto i:g[1])dfs(1,i);
f(i,1,n)cout << dp[i] << " ";
}
} | cpp |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pi;
#define pb push_back
const int MN=8e4;
int N, at=170, ans = MN; bool pvis[1001]; pi dist[MN];
set<int> start; vector<int> prime, vals, adj[MN]; queue<pi> q;
unordered_map<int, int> ind; // (value, index it maps to)
void bfs(int r){ q.push({r,-1}); dist[r]={1,r};
while(!q.empty()){ pi t = q.front(); int x=t.first, p=t.second; q.pop();
for(int nx: adj[x]) if(nx!=p && nx>=r && adj[nx].size()>1) {
if(dist[nx].second==dist[x].second) ans=min(ans,dist[x].first+dist[nx].first-1);
else{ dist[nx]={dist[x].first + 1,r}; q.push({nx,x}); } } } }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
prime.reserve(170); prime.pb(0); prime.pb(1);
for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.pb(i);
for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; }
cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x;
for (int j=2; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0;
while (x%prime[j] == 0) { x /= prime[j]; cnt++; }
if (cnt%2 == 1) vals.pb(prime[j]); }
if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; }
vals.pb(x); if (vals.size() == 1) vals.pb(1);
for (int k: vals) if (ind.count(k) == 0)
{ if (k > 1e3) ind[k] = at++;
else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin();
ind[k]=t; start.insert(t); } }
adj[ind[vals[0]]].pb(ind[vals[1]]);
adj[ind[vals[1]]].pb(ind[vals[0]]);
}
for (int j: start) if(j && adj[j].size()>1) bfs(j);
cout << (ans == MN ? -1 : ans) <<'\n';
} | cpp |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | // https://codeforces.com/problemset/problem/1366/E
//https://codeforces.com/problemset/problem/1312/E
// https://codeforces.com/problemset/problem/1409/F
#include <algorithm>
#include <bitset>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <stack>
#include <math.h>
#include <vector>
using namespace std;
#define what(a) cerr << (#a) << " is " << (a) << '\n';
const int N = 505;
int memo1[N][N] , memo2[N][N] , n , a[N];
int dp1(int l , int r) {
if(l == r) {
return a[l];
}
if(l > r) return -1;
int &res = memo1[l][r];
if(res != -2) return res;
res = -1;
for(int i = l + 1 ; i <= r ; i++) {
if(dp1(l , i - 1) == dp1(i , r) && dp1(l , i - 1) != -1) {
res = dp1(l , i - 1) + 1;
}
}
return res;
}
int dp2(int i , int last) {
if(i == n + 1) {
if(last == n + 1) return 0;
return 1e9;
}
int &res = memo2[i][last];
if(res != -2) return res;
res = 1e9;
res = min(res , dp2(i + 1 , last));
if(dp1(last , i) != -1)
res = min(res , 1 + dp2(i + 1 , i + 1));
return res;
}
void solve() {
cin >> n;
for(int i = 1 ; i <= n ; i++) cin >> a[i];
for(int i = 0 ; i < N ; i++) for(int j = 0 ; j < N ; j++) memo1[i][j] = memo2[i][j] = -2;
cout << dp2(1 , 1);
return;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tt = 1;
// cin >> tt;
while (tt--) {
solve();
}
return 0;
}
| cpp |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | #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;
typedef long double ld;
typedef long long ll;
#define el '\n'
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
int n, p, k;
const int N = 1e5 + 5;
vector<array<int, 2>> a(N);
int s[N][8];
ll dp[N][1 << 7];
ll solve(int i, int msk) {
if (i == n && msk == (1 << p) - 1)return 0;
if (i == n)return -1e15;
auto &ans = dp[i][msk];
if (~ans)return ans;
int cnt = i - __builtin_popcount(msk);
if (cnt < k) {
ans = solve(i + 1, msk) + a[i][0]; // pick audience
} else {
ans = solve(i + 1, msk); //leave audience
}
for (int j = 0; j < p; j++) {
if (((1 << j) & msk) == 0) {
ans = max(ans, 1ll * solve(i + 1, msk | (1 << j)) + s[a[i][1]][j]);
}
}
return ans;
}
void Tc() {
cin >> n >> p >> k;
for (int i = 0; i < n; i++) {
cin >> a[i][0];
a[i][1] = i;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < p; j++)cin >> s[i][j];
sort(a.rbegin(), a.rend());
memset(dp, -1, sizeof dp);
cout << solve(0, 0) << el;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int tc = 1;
// cin >> tc;
while (tc--)Tc();
}
| cpp |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<long long,long long>
#define F first
#define S second
#define all(x) x.begin(),x.end()
#define vi vector<int>
#define vll vector<long long>
#define ent(v) for(auto &k:v)cin>>k
#define print(v) for(auto &k:v)cout<<k<<' ';cout<<endl
#define range(n) for(int i=0;i<n;i++)
#define mp(x,y) make_pair(x,y)
///////////////////////////
ll mod=1000000007;
ll poww(ll a,ll b){
if(b<0)b=mod+b-1;
if(!b)return 1;
if(b&1)return a*poww(a*a%mod,b>>1)%mod;
return poww(a*a%mod,b>>1);
}
//ll inv6=poww(6,-1);
/////////////////////////////
/*vi tree;
vi a;
void add(int k,int n){
while(k<=n){
tree[k]++;
k+=k&-k;
}
}
int sum(int k){
int ans=0;
while(k){
ans+=tree[k];
k-=k&-k;
}
return ans;
}*/
int n;
vi v[200002];
vi dis,path;
vector<bool> vis;
void dfs(int x,int p){
for(int k:v[x]){
if(k!=p){
dis[k]=dis[x]+1;
dfs(k,x);
}
}
}
void road(int x,int p,int t){
path.pb(x);
if(x==t)return;
for(int k:v[x]){
if(k!=p){
road(k,x,t);
if(path.back()==t)return;
}
}
path.pop_back();
}
void solve()
{
cin>>n;
dis.resize(n+1);
vis.resize(n+1);
range(n-1){
int a,b;
cin>>a>>b;
v[a].pb(b);
v[b].pb(a);
}
dfs(1,0);
int a=0;
range(n){
if(dis[a]<dis[i+1]){
a=i+1;
}
}
dis.assign(n+1,0);
dfs(a,0);
int b=0;
range(n){
if(dis[b]<dis[i+1]){
b=i+1;
}
}
road(a,0,b);
dis.assign(n+1,0);
queue<int> q;
for(int k:path){
vis[k]=1;
q.push(k);
}
while(!q.empty()){
int cur=q.front();
q.pop();
for(int k:v[cur]){
if(!vis[k]){
dis[k]=dis[cur]+1;
q.push(k);
vis[k]=1;
}
}
}
int ans=path.size()-1;
int c=0;
range(n){
if(dis[c]<dis[i+1]){
c=i+1;
}
}
if(dis[c]==0){
if(a==1 || b==1){
if(a==2 || b==2){
c=3;
}
else{
c=2;
}
}
else{
c=1;
}
}
ans+=dis[c];
cout<<ans<<endl;
cout<<a<<' '<<b<<' '<<c<<endl;
}
////////////////////////////
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
//freopen("/storage/emulated/0/input.txt","r",stdin);
int t=1;
//cin>>t;
while(t--)solve();
return 0;
} | cpp |
1288 | C | C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1]. | [
"combinatorics",
"dp"
] | #include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<unordered_map>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstdlib>
#include<stack>
#include<ctime>
#define forin(i,a,n) for(int i=a;i<=n;i++)
#define forni(i,n,a) for(int i=n;i>=a;i--)
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=2e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
int T;
int n,m,k;
int f1[11][1100];
int f2[11][1100];
void init() {
for(int i=1;i<=n;i++) f1[1][i]=1;
for(int i=2;i<=m;i++) {
for(int j=1;j<=n;j++) {
for(int k=1;k<=j;k++) {
f1[i][j]=((ll)f1[i][j]+f1[i-1][k])%mod;
}
}
}
for(int i=1;i<=n;i++) f2[1][i]=1;
for(int i=2;i<=m;i++) {
for(int j=1;j<=n;j++) {
for(int k=j;k<=n;k++) {
f2[i][j]=((ll)f2[i][j]+f2[i-1][k])%mod;
}
}
}
}
void solve() {
n=read(),m=read();
init();
int ans=0;
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
ans=((ll)ans+((ll)f2[m][i]*f1[m][j])%mod)%mod;
}
}
printf("%lld\n",ans);
}
int main() {
// init();
// stin();
// scanf("%d",&T);
T=1;
while(T--) solve();
return 0;
}
| cpp |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7. | [
"brute force",
"combinatorics",
"math",
"number theory"
] | #include "bits/stdc++.h"
using namespace std;
#define int long long
//#define endl "\n"
#define inf (int)1e18
#define BeethovenBeedrilla true
#define TheEndOfPutin true
const int MOD =1000000000+7;
int binPow(int x, int p, int mod) {
int res = 1;
while (p > 0) {
if (p % 2)
res = (res * x) % mod;
x = (x * x) % mod;
p /= 2;
}
return res;
}
inline int modDiv(int a, int b, int mod = MOD) {
int p = binPow(b, mod - 2, mod);
return (a * p) % mod;
}
vector<int> facts;
int fact(int x, int mod = MOD) {
if (facts.size() <= x) {
facts.push_back(x <= 0 ? 1 : (fact(x - 1, mod) * x) % mod);
}
return facts[x];
}
inline int binom(int n, int k, int mod = MOD) {
return modDiv(fact(n), fact(n - k) * fact(k) % mod);
}
int logPow(int n, int p, int mod = MOD) {
int ans = 1;
int c = n % mod;
while (p > 0) {
if (p % 2) {
ans = (ans * c) % mod;
}
p /= 2;
c%=mod;
c = (c * c) % mod;
}
return ans;
}
//int fact(int n){
// int ans = 1;
// while(n>= 2){
// ans *=n;
// n--;
// }
// return ans;
//}
int sp_mult(int l,int r){
int ans = 1;
for(int i = l+1 ; i <=r ; i ++){
ans *= i;
}
return ans ;
}
signed main() {
cin.tie(nullptr), cout.tie(nullptr);
ios_base::sync_with_stdio(false);
cout << setprecision(15) << fixed;
int n,k,ans = 1;
cin >> n >> k;
vector<int>v(n);
for(int i = 0 ; i < n ; i ++){
cin >> v[i];
}
if(n <= k){
for(int i = 0 ; i < n-1 ; i ++){
for(int j = i+1; j <n; j ++){
ans = (ans * (max(v[i],v[j]) - min(v[i],v[j])))%k;
}
}
cout << ans << endl;
}
else{
cout << 0 << endl;
}
}
| cpp |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <bits/stdc++.h>
#define int long long
using namespace std;
int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int32_t main()
{
int t=1;
//cin>>t;
while(t--)
{
int n,q;
cin>>n>>q;
vector<vector<int>>v(2,vector<int>(n+10,0));
int wall=0;
for(int i=0;i<q;i++)
{
int a,b;
cin>>a>>b;
a--;
int p=(a+1)%2;
if(v[a][b])
{
wall-=(v[p][b+1]+v[p][b-1]+v[p][b]);
}else
{
wall+=v[p][b+1]+v[p][b-1]+v[p][b];
}
v[a][b]^=1;
if(wall==0)
cout<<"Yes\n";
else cout<<"No\n";
}
}
return 0;
} | cpp |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n) — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111. | [
"dfs and similar",
"dsu",
"graphs"
] | #include <bits/stdc++.h>
#define int long long
#define pb push_back
using namespace std;
const int INF=1e6+5;
int n,m,fa_set[INF],sz[INF],vis2[INF],ans,vis[INF];
int find_set(int x) {return x==fa_set[x]?x:fa_set[x]=find_set(fa_set[x]);}
void mer(int x,int y) {
x=find_set(x);y=find_set(y);
if (x==y) return ;
// cout<<x<<" "<<y<<" okkkkkkkqweq??????\n";
fa_set[x]=y;
sz[y]+=sz[x];sz[x]=0;
vis2[y]|=vis2[x];
}
string s1;
vector <int> v[INF];
void solve(int x,int y) {
x=find_set(x);y=find_set(y);
if (vis2[x]) ans-=sz[x];
else if (vis2[y]) ans-=sz[y];
else if (vis[x]) ans-=sz[x];
else ans-=sz[y];
vis[x]=vis[y]=0;
}
void solve2(int x,int y) {
x=find_set(x);y=find_set(y);
if (vis2[x]) ans+=sz[x];
else if (vis2[y]) ans+=sz[y];
else {
if (sz[x]<sz[y]) ans+=sz[x],vis[x]=1;
else ans+=sz[y],vis[y]=1;
}
}
signed main()
{
ios::sync_with_stdio(false);
cin>>n>>m>>s1; s1=" "+s1;
for (int i=1;i<=m;i++) {
int c=0;cin>>c;
for (int j=1;j<=c;j++) {
int y=0;cin>>y;
v[y].pb(i);
}
}
for (int i=1;i<=m;i++) fa_set[i]=i,sz[i]=1;
for (int i=1;i<=m;i++) fa_set[i+m]=i+m;
for (int i=1;i<=n;i++) {
if (v[i].size()==1) {
int id=v[i][0];
int xx=find_set(id),yy=find_set(id+m);
solve(xx,yy);
if (s1[i]=='0') vis2[xx]=1;
else vis2[yy]=1;
solve2(xx,yy);
}
else if (v[i].size()==2) {
int id=v[i][0],id2=v[i][1];
int xx=find_set(id),yy=find_set(id+m);
int aa=find_set(id2),bb=find_set(id2+m);
if (xx==aa || xx==bb) ;
else {
// cout<<i<<" "<<vis2[yy]<<" "<<vis2[bb]<<" "<<sz[yy]<<" "<<yy<<" "<<sz[aa]<<" iwjriewr\n";
// cout<<find_set(aa)<<" "<<find_set(yy)<<" this one?\n";
solve(xx,yy);solve(aa,bb);
if (s1[i]=='0') {mer(xx,bb);mer(yy,aa);}
else {mer(xx,aa);mer(yy,bb);}
xx=find_set(xx);yy=find_set(yy);
solve2(xx,yy);
}
}
cout<<ans<<"\n";
}
return 0;
} | cpp |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] |
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 2e5 + 10;
#define PII pair<int,int >
int a[200];
void solve() {
int n;
cin >> n;
string s;
cin >> s;
int r = 0, l = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'L')
l++;
else
r++;
}
cout << r + l+1;
}
int main() {
int t;
//cin >> t;
t = 1;
while (t--) {
solve();
}
return 0;
}
| cpp |
1310 | B | B. Double Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2n2n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 11 to 2n2n and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with 2n−12n−1 teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round 2k2k teams play a game with each other (teams are split into games by team numbers). 2k−12k−1 loosing teams are eliminated from the championship, 2k−12k−1 winning teams are playing 2k−12k−1 teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have 2k−12k−1 teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers a1,a2,...,aka1,a2,...,ak. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?InputFirst input line has two integers n,kn,k — 2n2n teams are competing in the championship. You are a fan of kk teams (2≤n≤17;0≤k≤2n2≤n≤17;0≤k≤2n).Second input line has kk distinct integers a1,…,aka1,…,ak — numbers of teams you're a fan of (1≤ai≤2n1≤ai≤2n).OutputOutput single integer — maximal possible number of championship games that include teams you're fan of.ExamplesInputCopy3 1
6
OutputCopy6
InputCopy3 3
1 7 8
OutputCopy11
InputCopy3 4
1 3 5 7
OutputCopy14
NoteOn the image; each game of the championship is denoted with an English letter (aa to nn). Winner of game ii is denoted as WiWi, loser is denoted as LiLi. Teams you're a fan of are highlighted with red background.In the first example, team 66 will play in 6 games if it looses the first upper bracket game (game cc) and wins all lower bracket games (games h,j,l,mh,j,l,m). In the second example, teams 77 and 88 have to play with each other in the first game of upper bracket (game dd). Team 88 can win all remaining games in upper bracket, when teams 11 and 77 will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship. | [
"dp",
"implementation"
] | #include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
using LL = long long;
const int maxn = 1e6 + 5;
bool v[maxn];
int main(){
#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
const int INF = 1e9;
int n, k;
cin >> n >> k;
if (k == 0){
cout << 0 << '\n';
return 0;
}
vector<array<int, 4> > dp(1 << n, {0, -INF, -INF, -INF});
for(int i = 1; i <= k; i++){
int x;
cin >> x;
int s = (1 << n - 1) + (x - 1) / 2;
if (dp[s][1] != -INF) dp[s][3] = 1;
else dp[s][1] = dp[s][2] = 1;
}
for(int i = (1 << n - 1) - 1; i >= 1; i--){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
dp[i][j | k] = max(dp[i][j | k], dp[2 * i][j] + dp[2 * i + 1][k] + (j | k));
}
}
}
cout << max({dp[1][1], dp[1][2], dp[1][3]}) + 1 << '\n';
} | cpp |
1290 | F | F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is: | [
"dp"
] | #include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 10;
const long long mod = 998244353;
inline long long solve(void);
int x[maxn], y[maxn], n, m;
int main() {
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) scanf("%d %d", x + i, y + i);
printf("%lld\n", solve());
return 0;
}
const int maxl = 35, maxs = 25;
long long dp[maxl][maxs][maxs][maxs][maxs][2][2];
int len;
long long dfs(const int p, const int px, const int nx, const int py, const int ny, const bool fx,
const bool fy) {
if (p == len)
return !px && !nx && !py && !ny && !fx && !fy;
if (dp[p][px][nx][py][ny][fx][fy] != -1)
return dp[p][px][nx][py][ny][fx][fy];
int lim = 1 << n;
long long ret = 0;
for (int i = 0; i < lim; i++) {
int Px = px, Nx = nx, Py = py, Ny = ny;
for (int j = 0; j < n; j++)
if ((i >> j) & 1) {
if (x[j] > 0)
Px += x[j];
else
Nx -= x[j];
if (y[j] > 0)
Py += y[j];
else
Ny -= y[j];
}
if ((Px & 1) == (Nx & 1) && (Py & 1) == (Ny & 1)) {
bool Fx = ((m >> p) & 1) != (Px & 1) ? (Px & 1) : fx;
bool Fy = ((m >> p) & 1) != (Py & 1) ? (Py & 1) : fy;
ret += dfs(p + 1, Px >> 1, Nx >> 1, Py >> 1, Ny >> 1, Fx, Fy);
}
}
return dp[p][px][nx][py][ny][fx][fy] = ret % mod;
}
inline long long solve(void) {
int M = m;
while (M) len++, M >>= 1;
memset(dp, -1, sizeof(dp));
return (dfs(0, 0, 0, 0, 0, false, false) + mod - 1) % mod;
}
| cpp |
1292 | F | F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0. After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible: b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8]) b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible: b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4]) b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9]) b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12]) b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty. | [
"bitmasks",
"combinatorics",
"dp"
] | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
int n, a[65], f[65], ind[65], nidx[65], imsk[65], pfxs[65536];
long long dp[65536][65], fac[65], ifac[65];
vector <int> wcc[65], nod;
inline int GetRoot(int v) {
if (f[v] == v) return v;
return f[v] = GetRoot(f[v]);
}
inline void Merge(int x, int y) {
int u = GetRoot(x), v = GetRoot(y);
if (u != v) f[v] = u;
}
inline void Read() {
cin >> n;
for (int i = 1;i <= n;i++) cin >> a[i];
}
inline void Prefix() {
for (int i = 1;i <= n;i++) f[i] = i;
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= n;j++) {
if (a[i] % a[j] == 0) Merge(i, j);
}
}
for (int i = 1;i <= n;i++) wcc[GetRoot(i)].push_back(a[i]);
ifac[1] = ifac[0] = fac[1] = fac[0] = 1;
for (int i = 2;i <= n;i++) ifac[i] = (mod - mod / i) * ifac[mod % i] % mod;
for (int i = 2;i <= n;i++) {
fac[i] = fac[i - 1] * i % mod;
ifac[i] = ifac[i - 1] * ifac[i] % mod;
}
}
inline pair <int, long long> Work(int idx) {
nod.clear(); nod.shrink_to_fit();
sort(wcc[idx].begin(), wcc[idx].end());
for (int i = 0;i < wcc[idx].size();i++) {
for (int j = i + 1;j < wcc[idx].size();j++) {
if (wcc[idx][j] % wcc[idx][i] == 0) ind[wcc[idx][j]]++;
}
}
for (int x : wcc[idx]) {
if (!ind[x]) {
nidx[x] = nod.size();
nod.push_back(x);
// cout << x << " no indgr\n";
}
}
memset(imsk, 0, sizeof(imsk));
//cout << nod.size() << endl;
memset(pfxs, 0, sizeof(pfxs));
for (int x : wcc[idx]) {
for (int y : nod) {
if (x % y == 0) imsk[x] |= (1 << nidx[y]);
}
if (ind[x]) pfxs[imsk[x]]++;
}
for (int i = 0;i < nod.size();i++) {
for (int j = 0;j < (1 << nod.size());j++) {
if (j & (1 << i)) pfxs[j] += pfxs[j ^ (1 << i)];
}
}
memset(dp, 0, sizeof(dp));
for (int x : wcc[idx]) {
if (ind[x]) dp[imsk[x]][1]++;
}
//cout << (1 << nod.size()) << endl;
for (int i = 1;i < (1 << nod.size());i++) {
//cout << i << " " << pfxs[i] << endl;
for (int j = 1;j <= n;j++) {
//cout << i << " " << j << " " << dp[i][j] << endl;
dp[i][j + 1] = (dp[i][j + 1] + dp[i][j] * (pfxs[i] - j)) % mod;
for (int k = 1;k <= n;k++) {
if ((imsk[a[k]] & i) != 0 && (imsk[a[k]] & i) != imsk[a[k]]) {
dp[i | imsk[a[k]]][j + 1] = (dp[i | imsk[a[k]]][j + 1] + dp[i][j]) % mod;
}
}
}
}
return make_pair(pfxs[(1 << nod.size()) - 1] - 1, dp[(1 << nod.size()) - 1][pfxs[(1 << nod.size()) - 1]]);
}
inline void Solve() {
long long ans = 1;
int fcnt = 0;
for (int i = 1;i <= 60;i++) {
if (wcc[i].size() > 1) {
// for (int x : wcc[i]) cout << x << " "; cout << endl;
pair <int, long long> res = Work(i);
//cout << res.first << " " << res.second << endl;
ans = ans * res.second % mod * ifac[res.first] % mod;
fcnt += res.first;
}
}
cout << ans * fac[fcnt] % mod << endl;
}
int main() {
std::ios::sync_with_stdio(0);
Read();
Prefix();
Solve();
return 0;
} | cpp |
1290 | E | E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th question.ExamplesInputCopy5
2 4 1 5 3
OutputCopy1
3
6
8
11
InputCopy6
1 2 4 5 6 3
OutputCopy1
3
6
8
12
17
NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11. | [
"data structures"
] | // LUOGU_RID: 97831402
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define db double
#define ldb long double
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define FR first
#define SE second
#define int long long
using namespace std;
inline int read() {
int x = 0; bool op = 0;
char c = getchar();
while(!isdigit(c))op |= (c == '-'), c = getchar();
while(isdigit(c))x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
return op ? -x : x;
}
const int N = 2e5 + 10;
const int INF = 1e14;
int n;
int a[N], ans[N], pos[N];
struct Node {
int c, sum, mn, mn2, mnc;
int tg, mtg;
}nd[N << 2];
void build(int k, int l, int r) {
nd[k].c = nd[k].mnc = nd[k].sum = nd[k].tg = nd[k].mtg = 0;
nd[k].mn = nd[k].mn2 = INF;
if(l == r)return ;
int mid = l + r >> 1;
build(k << 1, l, mid); build(k << 1 | 1, mid + 1, r);
return ;
}
void mark1(int k, int l, int r, int w) {
nd[k].sum += w * nd[k].c; nd[k].mn += w; nd[k].mn2 += w;
nd[k].tg += w;
}
void mark2(int k, int l, int r, int w) {
nd[k].sum += w * nd[k].mnc; nd[k].mn += w;
nd[k].mtg += w;
return ;
}
void pushdown(int k, int l, int r) {
int mid = l + r >> 1, ls = k << 1, rs = k << 1 | 1;
mark1(k << 1, l, mid, nd[k].tg);
mark1(k << 1 | 1, mid + 1, r, nd[k].tg);
if(nd[ls].mn <= nd[rs].mn)mark2(k << 1, l, mid, nd[k].mtg);
if(nd[ls].mn >= nd[rs].mn)mark2(k << 1 | 1, mid + 1, r, nd[k].mtg);
nd[k].tg = nd[k].mtg = 0;
return ;
}
void pushup(int k) {
int ls = k << 1, rs = k << 1 | 1;
nd[k].sum = nd[ls].sum + nd[rs].sum;
nd[k].c = nd[ls].c + nd[rs].c;
if(nd[ls].mn < nd[rs].mn) {
nd[k].mn = nd[ls].mn; nd[k].mnc = nd[ls].mnc;
nd[k].mn2 = min(nd[ls].mn2, nd[rs].mn);
}
else if(nd[ls].mn > nd[rs].mn) {
nd[k].mn = nd[rs].mn; nd[k].mnc = nd[rs].mnc;
nd[k].mn2 = min(nd[rs].mn2, nd[ls].mn);
}
else {
nd[k].mn = nd[ls].mn; nd[k].mnc = nd[ls].mnc + nd[rs].mnc;
nd[k].mn2 = min(nd[ls].mn2, nd[rs].mn2);
}
return ;
}
void add(int k, int l, int r, int qx, int qy, int w) {
if(l >= qx && r <= qy)return mark1(k, l, r, w), void();
pushdown(k, l, r);
int mid = l + r >> 1;
if(qx <= mid)add(k << 1, l, mid, qx, qy, w);
if(qy > mid)add(k << 1 | 1, mid + 1, r, qx, qy, w);
pushup(k);
// printf("add:%d %d %d %d %d\n", l, r, qx, qy, nd[k << 1 | 1].sum);
return ;
}
void chg(int k, int l, int r, int qx, int qy, int w) {
if(nd[k].mn >= w)return ;
if(l >= qx && r <= qy && nd[k].mn2 > w) {
return mark2(k, l, r, w - nd[k].mn), void();
}
pushdown(k, l, r);
int mid = l + r >> 1;
if(qx <= mid)chg(k << 1, l, mid, qx, qy, w);
if(qy > mid)chg(k << 1 | 1, mid + 1, r, qx, qy, w);
pushup(k);
return ;
}
void upd(int k, int l, int r, int x) {
if(l == r) {
nd[k].c = nd[k].mnc = 1; nd[k].mn = 0;
return ;
}
pushdown(k, l, r);
int mid = l + r >> 1;
if(x <= mid)upd(k << 1, l, mid, x);
else upd(k << 1 | 1, mid + 1, r, x);
pushup(k);
return ;
}
int qryc(int k, int l, int r, int qx, int qy) {
if(l >= qx && r <= qy)return nd[k].c;
pushdown(k, l, r);
int mid = l + r >> 1, res = 0;
if(qx <= mid)res += qryc(k << 1, l, mid, qx, qy);
if(qy > mid)res += qryc(k << 1 | 1, mid + 1, r, qx, qy);
return res;
}
void calc() {
for(int i = 1; i <= n; i++)pos[a[i]] = i;
build(1, 1, n);
for(int i = 1; i <= n; i++) {
int x = (pos[i] > 1 ? qryc(1, 1, n, 1, pos[i] - 1) : 0) + 1;
if(pos[i] < n) {
add(1, 1, n, pos[i] + 1, n, 1);
chg(1, 1, n, pos[i] + 1, n, x);
}
upd(1, 1, n, pos[i]);
ans[i] += nd[1].sum;
}
return ;
}
signed main() {
n = read();
for(int i = 1; i <= n; i++)a[i] = read();
calc();
reverse(a + 1, a + 1 + n);
calc();
for(int i = 1; i <= n; i++)printf("%lld\n", i * i - ans[i]);
return 0;
} | cpp |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define mod 1000000007
void solve()
{
ll n, k;
cin >> n >> k;
vector<ll> a(n);
for (ll i = 0; i < n; i++)
{
cin >> a[i];
}
map<ll, ll> m;
for (ll i = 0; i < n; i++)
{
ll cnt = 0;
if (a[i] == 1)
{
m[0]++;
continue;
}
while (a[i])
{
while (a[i] % k == 0)
{
a[i] /= k;
cnt++;
}
a[i]--, m[cnt]++;
}
}
for (auto it : m)
{
// cout << it.first << " " << it.second << endl;
if (it.second > 1)
{
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll test;
cin >> test;
while (test--)
{
solve();
}
return 0;
}
| cpp |
1292 | E | E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1
4
2 1 2
1 2
0
1OutputCopy
? C
? CH
? CCHO
! CCHH
InputCopy2
5
0
2 2 3
1
8
1 5
1 5
1 3
2 1 2
1OutputCopy
? O
? HHH
! CHHHH
? COO
? COOH
? HCCOO
? HH
! HHHCCOOH
NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well. | [
"constructive algorithms",
"greedy",
"interactive",
"math"
] | #include<iostream>
#include<cstdio>
#include<cassert>
#define N 50
using namespace std;
int read()
{
char c=0;
int sum=0;
while (c<'0'||c>'9') c=getchar();
while ('0'<=c&&c<='9') sum=sum*10+c-'0',c=getchar();
return sum;
}
int t,n,k,p[N+1];
string s1,s2,s3,s4,s5,s6,s7,divs,zero;
bool guess(string s)
{
cout<<'?'<<' '<<s<<endl,fflush(stdout);
k=read();
if (k==-1) exit(0);
for (int i=1;i<=k;++i) p[i]=read();
return k;
}
bool s_guess(string s,int x)
{
cout<<'?'<<' '<<s<<endl,fflush(stdout);
k=read();
if (k==-1) exit(0);
for (int i=1;i<=k;++i) p[i]=read();
for (int i=1;i<=k;++i)
if (p[i]==x)
return 1;
return 0;
}
void bfs(string s)
{
int ft=p[1];
for (int i=ft-1;i>=1;--i)
{
if (s_guess('H'+s,i)) s='H'+s;
else if (s_guess('O'+s,i)) s='O'+s;
else s='C'+s;
}
for (int i=ft+2;i<=n;++i)
{
if (s_guess(s+'H',1)) s=s+'H';
else if (s_guess(s+'O',1)) s=s+'O';
else s=s+'C';
}
cout<<'!'<<' '<<s<<endl,fflush(stdout);
return;
}
void exbfs(string s)
{
int ft=p[k];
for (int i=ft-1;i>=1;--i)
{
if (s_guess('H'+s,i)) s='H'+s;
else s='O'+s;
}
bool op=0;
for (int i=ft+2;i<=n;++i)
{
if (!op)
{
if (s_guess(s+'H',1)) s=s+'H';
else if (s_guess(s+'O',1)) s=s+'O',op=1;
else s=s+'C',op=1;
}
else
{
if (s_guess(s+'O',1)) s=s+'O';
else s=s+'C';
}
}
cout<<'!'<<' '<<s<<endl,fflush(stdout);
return;
}
void exbfs2(string s)
{
int ft=p[1];
for (int i=ft-1;i>=1;--i) s='H'+s;
for (int i=ft+3;i<=n;++i)
{
if (s_guess(s+'O',1)) s=s+'O';
else s=s+'C';
}
cout<<'!'<<' '<<s<<endl,fflush(stdout);
return;
}
void exbfs3(string s)
{
int ft=p[1];
for (int i=ft+3;i<=n;++i) s=s+'C';
for (int i=ft-1;i>=1;--i)
{
if (s_guess('H'+s,i)) s='H'+s;
else s='O'+s;
}
cout<<'!'<<' '<<s<<endl,fflush(stdout);
return;
}
void work(string s)
{
cout<<'!'<<' ';
for (int i=1;i<=p[1]-1;++i) cout<<'H';
cout<<s;
for (int i=p[1]+3;i<=n;++i) cout<<'C';
cout<<endl;
fflush(stdout);
return;
}
int main()
{
t=read();
while (t--)
{
n=read(),s1=s2=s3=s4=s5=s6=s7=divs=zero;
for (int i=1;i<=n;++i)
{
s1=s1+'H',s2=s2+'O',s3=s3+'C';
if (i==1) s4=s4+'H',s5=s5+'H',s6=s6+'O',s7=s7+'H';
else
{
s4=s4+'O',s5=s5+'C',s6=s6+'C',divs=divs+'C';
if (i==2) s7=s7+'O';
else s7=s7+'C';
}
}
if (guess("CO")) bfs("CO");
else if (guess("CH")) bfs("CH");
else if (guess("OH")) exbfs("OH");
else if (guess("HHO")) exbfs2("HHO");
else if (guess("OOC")) exbfs3("OOC");
else if (guess("HHC")) work("HHC");
else if (guess(divs))
{
if (guess(s3)) cout<<'!'<<' '<<s3<<endl,fflush(stdout);
else if (guess(s5)) cout<<'!'<<' '<<s5<<endl,fflush(stdout);
else cout<<'!'<<' '<<s6<<endl,fflush(stdout);
}
else
{
if (guess(s1)) cout<<'!'<<' '<<s1<<endl,fflush(stdout);
else if (guess(s2)) cout<<'!'<<' '<<s2<<endl,fflush(stdout);
else if (guess(s4)) cout<<'!'<<' '<<s4<<endl,fflush(stdout);
else cout<<'!'<<' '<<s7<<endl,fflush(stdout);
}
int st=read();
if (st==0) break;
}
return 0;
}
| cpp |
1316 | F | F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212. | [
"data structures",
"divide and conquer",
"probabilities"
] | #line 1 "/home/maspy/compro/library/my_template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) \
vector<vector<vector<type>>> name( \
h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name( \
a, vector<vector<vector<type>>>( \
b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
#define FOR_(n) for (ll _ = 0; (_) < (ll)(n); ++(_))
#define FOR(i, n) for (ll i = 0; (i) < (ll)(n); ++(i))
#define FOR3(i, m, n) for (ll i = (m); (i) < (ll)(n); ++(i))
#define FOR_R(i, n) for (ll i = (ll)(n)-1; (i) >= 0; --(i))
#define FOR3_R(i, m, n) for (ll i = (ll)(n)-1; (i) >= (ll)(m); --(i))
#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define stoi stoll
template <typename T>
T SUM(vector<T> &A) {
T sum = T(0);
for (auto &&a: A) sum += a;
return sum;
}
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int lowbit(u32 x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int lowbit(ll x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
int lowbit(u64 x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
template <typename T, typename U>
T ceil(T x, U y) {
return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U>
T floor(T x, U y) {
return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
T q = floor(x, y);
return {q, x - q * y};
}
ll binary_search(function<bool(ll)> check, ll ok, ll ng) {
assert(check(ok));
while (abs(ok - ng) > 1) {
auto x = (ng + ok) / 2;
if (check(x))
ok = x;
else
ng = x;
}
return ok;
}
template <class T, class S>
inline bool chmax(T &a, const S &b) {
return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
return (a > b ? a = b, 1 : 0);
}
vi s_to_vi(string S, char first_char = 'a') {
vi A(S.size());
FOR(i, S.size()) { A[i] = S[i] - first_char; }
return A;
}
template <typename T>
vector<T> cumsum(vector<T> &A, int off = 1) {
int N = A.size();
vector<T> B(N + 1);
FOR(i, N) { B[i + 1] = B[i] + A[i]; }
if (off == 0) B.erase(B.begin());
return B;
}
template <typename T, typename CNT = int>
vc<CNT> bincount(vc<T> &A, int size) {
vc<CNT> C(size);
for (auto &&x: A) { ++C[x]; }
return C;
}
template <typename T>
vector<int> argsort(vector<T> &A) {
// stable
vector<int> ids(A.size());
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
return ids;
}
#line 1 "/home/maspy/compro/library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace detail {
template <typename T, decltype(&T::is_modint) = &T::is_modint>
std::true_type check_value(int);
template <typename T>
std::false_type check_value(long);
} // namespace detail
template <typename T>
struct is_modint : decltype(detail::check_value<T>(0)) {};
template <typename T>
using is_modint_t = enable_if_t<is_modint<T>::value>;
template <typename T>
using is_not_modint_t = enable_if_t<!is_modint<T>::value>;
struct Scanner {
FILE* fp;
char line[(1 << 15) + 1];
size_t st = 0, ed = 0;
void reread() {
memmove(line, line + st, ed - st);
ed -= st;
st = 0;
ed += fread(line + ed, 1, (1 << 15) - ed, fp);
line[ed] = '\0';
}
bool succ() {
while (true) {
if (st == ed) {
reread();
if (st == ed) return false;
}
while (st != ed && isspace(line[st])) st++;
if (st != ed) break;
}
if (ed - st <= 50) {
bool sep = false;
for (size_t i = st; i < ed; i++) {
if (isspace(line[i])) {
sep = true;
break;
}
}
if (!sep) reread();
}
return true;
}
template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
while (true) {
size_t sz = 0;
while (st + sz < ed && !isspace(line[st + sz])) sz++;
ref.append(line + st, sz);
st += sz;
if (!sz || st != ed) break;
reread();
}
return true;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
bool neg = false;
if (line[st] == '-') {
neg = true;
st++;
}
ref = T(0);
while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
if (neg) ref = -ref;
return true;
}
template <class T, is_modint_t<T> * = nullptr>
bool read_single(T &ref) {
long long val = 0;
bool f = read_single(val);
ref = T(val);
return f;
}
bool read_single(double &ref) {
string s;
if (!read_single(s)) return false;
ref = std::stod(s);
return true;
}
template <class T>
bool read_single(vector<T> &ref) {
for (auto &d: ref) {
if (!read_single(d)) return false;
}
return true;
}
template <class T, class U>
bool read_single(pair<T, U> &p) {
return (read_single(p.first) && read_single(p.second));
}
template <class A, class B, class C>
bool read_single(tuple<A, B, C> &p) {
return (read_single(get<0>(p)) && read_single(get<1>(p))
&& read_single(get<2>(p)));
}
template <class A, class B, class C, class D>
bool read_single(tuple<A, B, C, D> &p) {
return (read_single(get<0>(p)) && read_single(get<1>(p))
&& read_single(get<2>(p)) && read_single(get<3>(p)));
}
void read() {}
template <class H, class... T>
void read(H &h, T &... t) {
bool f = read_single(h);
assert(f);
read(t...);
}
Scanner(FILE *fp) : fp(fp) {}
};
struct Printer {
Printer(FILE *_fp) : fp(_fp) {}
~Printer() { flush(); }
static constexpr size_t SIZE = 1 << 15;
FILE *fp;
char line[SIZE], small[50];
size_t pos = 0;
void flush() {
fwrite(line, 1, pos, fp);
pos = 0;
}
void write(const char &val) {
if (pos == SIZE) flush();
line[pos++] = val;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
void write(T val) {
if (pos > (1 << 15) - 50) flush();
if (val == 0) {
write('0');
return;
}
if (val < 0) {
write('-');
val = -val; // todo min
}
size_t len = 0;
while (val) {
small[len++] = char(0x30 | (val % 10));
val /= 10;
}
for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
pos += len;
}
void write(const string &s) {
for (char c: s) write(c);
}
void write(const char *s) {
size_t len = strlen(s);
for (size_t i = 0; i < len; i++) write(s[i]);
}
void write(const double &x) {
ostringstream oss;
oss << setprecision(12) << x;
string s = oss.str();
write(s);
}
template <class T, is_modint_t<T> * = nullptr>
void write(T &ref) {
write(ref.val);
}
template <class T>
void write(const vector<T> &val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
template <class T, class U>
void write(const pair<T, U> &val) {
write(val.first);
write(' ');
write(val.second);
}
};
Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);
void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
printer.write(head);
if (sizeof...(Tail)) printer.write(' ');
print(forward<Tail>(tail)...);
}
void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
scanner.read(head);
read(tail...);
}
#define INT(...) \
int __VA_ARGS__; \
read(__VA_ARGS__)
#define LL(...) \
ll __VA_ARGS__; \
read(__VA_ARGS__)
#define STR(...) \
string __VA_ARGS__; \
read(__VA_ARGS__)
#define DBL(...) \
double __VA_ARGS__; \
read(__VA_ARGS__)
#define VEC(type, name, size) \
vector<type> name(size); \
read(name)
#define VV(type, name, h, w) \
vector<vector<type>> name(h, vector<type>(w)); \
read(name)
void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 2 "/home/maspy/compro/library/mod/modint.hpp"
template <int mod>
struct modint {
static constexpr bool is_modint = true;
int val;
constexpr modint(const ll val = 0) noexcept
: val(val >= 0 ? val % mod : (mod - (-val) % mod) % mod) {}
bool operator<(const modint &other) const {
return val < other.val;
} // To use std::map
modint &operator+=(const modint &p) {
if ((val += p.val) >= mod) val -= mod;
return *this;
}
modint &operator-=(const modint &p) {
if ((val += mod - p.val) >= mod) val -= mod;
return *this;
}
modint &operator*=(const modint &p) {
val = (int)(1LL * val * p.val % mod);
return *this;
}
modint &operator/=(const modint &p) {
*this *= p.inverse();
return *this;
}
modint operator-() const { return modint(-val); }
modint operator+(const modint &p) const { return modint(*this) += p; }
modint operator-(const modint &p) const { return modint(*this) -= p; }
modint operator*(const modint &p) const { return modint(*this) *= p; }
modint operator/(const modint &p) const { return modint(*this) /= p; }
bool operator==(const modint &p) const { return val == p.val; }
bool operator!=(const modint &p) const { return val != p.val; }
modint inverse() const {
int a = val, b = mod, u = 1, v = 0, t;
while (b > 0) {
t = a / b;
swap(a -= t * b, b), swap(u -= t * v, v);
}
return modint(u);
}
modint pow(int64_t n) const {
modint ret(1), mul(val);
while (n > 0) {
if (n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
static constexpr int get_mod() { return mod; }
};
struct ArbitraryModInt {
static constexpr bool is_modint = true;
int val;
ArbitraryModInt() : val(0) {}
ArbitraryModInt(int64_t y)
: val(y >= 0 ? y % get_mod()
: (get_mod() - (-y) % get_mod()) % get_mod()) {}
bool operator<(const ArbitraryModInt &other) const {
return val < other.val;
} // To use std::map<ArbitraryModInt, T>
static int &get_mod() {
static int mod = 0;
return mod;
}
static void set_mod(int md) { get_mod() = md; }
ArbitraryModInt &operator+=(const ArbitraryModInt &p) {
if ((val += p.val) >= get_mod()) val -= get_mod();
return *this;
}
ArbitraryModInt &operator-=(const ArbitraryModInt &p) {
if ((val += get_mod() - p.val) >= get_mod()) val -= get_mod();
return *this;
}
ArbitraryModInt &operator*=(const ArbitraryModInt &p) {
unsigned long long a = (unsigned long long)val * p.val;
unsigned xh = (unsigned)(a >> 32), xl = (unsigned)a, d, m;
asm("divl %4; \n\t" : "=a"(d), "=d"(m) : "d"(xh), "a"(xl), "r"(get_mod()));
val = m;
return *this;
}
ArbitraryModInt &operator/=(const ArbitraryModInt &p) {
*this *= p.inverse();
return *this;
}
ArbitraryModInt operator-() const { return ArbitraryModInt(-val); }
ArbitraryModInt operator+(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) += p;
}
ArbitraryModInt operator-(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) -= p;
}
ArbitraryModInt operator*(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) *= p;
}
ArbitraryModInt operator/(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) /= p;
}
bool operator==(const ArbitraryModInt &p) const { return val == p.val; }
bool operator!=(const ArbitraryModInt &p) const { return val != p.val; }
ArbitraryModInt inverse() const {
int a = val, b = get_mod(), u = 1, v = 0, t;
while (b > 0) {
t = a / b;
swap(a -= t * b, b), swap(u -= t * v, v);
}
return ArbitraryModInt(u);
}
ArbitraryModInt pow(int64_t n) const {
ArbitraryModInt ret(1), mul(val);
while (n > 0) {
if (n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
};
template<typename mint>
tuple<mint, mint, mint> get_factorial_data(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
static vector<mint> fact = {1, 1};
static vector<mint> fact_inv = {1, 1};
static vector<mint> inv = {0, 1};
while(len(fact) <= n){
int k = len(fact);
fact.eb(fact[k - 1] * mint(k));
auto q = ceil(mod, k);
int r = k * q - mod;
inv.eb(inv[r] * mint(q));
fact_inv.eb(fact_inv[k - 1] * inv[k]);
}
return {fact[n], fact_inv[n], inv[n]};
}
template<typename mint>
mint fact(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n);
if(n >= mod) return 0;
return get<0>(get_factorial_data<mint>(n));
}
template<typename mint>
mint fact_inv(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
return get<1>(get_factorial_data<mint>(n));
}
template<typename mint>
mint inv(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
return get<2>(get_factorial_data<mint>(n));
}
template<typename mint>
mint C(ll n, ll k, bool large = false) {
assert(n >= 0);
if (k < 0 || n < k) return 0;
if (!large) return fact<mint>(n) * fact_inv<mint>(k) * fact_inv<mint>(n - k);
k = min(k, n - k);
mint x(1);
FOR(i, k) {
x *= mint(n - i);
}
x *= fact_inv<mint>(k);
return x;
}
using modint107 = modint<1000000007>;
using modint998 = modint<998244353>;
using amint = ArbitraryModInt;
#line 2 "/home/maspy/compro/library/ds/segtree.hpp"
template <class Monoid>
struct SegTree {
using X = typename Monoid::value_type;
using value_type = X;
vc<X> dat;
int n, log, size;
SegTree() : SegTree(0) {}
SegTree(int n) : SegTree(vc<X>(n, Monoid::unit)) {}
SegTree(vc<X> v) : n(len(v)) {
log = 1;
while ((1 << log) < n) ++log;
size = 1 << log;
dat.assign(size << 1, Monoid::unit);
FOR(i, n) dat[size + i] = v[i];
FOR3_R(i, 1, size) update(i);
}
X operator[](int i) { return dat[size + i]; }
void update(int i) { dat[i] = Monoid::op(dat[2 * i], dat[2 * i + 1]); }
void set(int i, X x) {
assert(i < n);
dat[i += size] = x;
while (i >>= 1) update(i);
}
X prod(int L, int R) {
assert(L <= R);
assert(R <= n);
X vl = Monoid::unit, vr = Monoid::unit;
L += size, R += size;
while (L < R) {
if (L & 1) vl = Monoid::op(vl, dat[L++]);
if (R & 1) vr = Monoid::op(dat[--R], vr);
L >>= 1, R >>= 1;
}
return Monoid::op(vl, vr);
}
X prod_all() { return dat[1];}
template <class F>
int max_right(F &check, int L) {
assert(0 <= L && L <= n && check(Monoid::unit));
if (L == n) return n;
L += size;
X sm = Monoid::unit;
do {
while (L % 2 == 0) L >>= 1;
if (!check(Monoid::op(sm, dat[L]))) {
while (L < size) {
L = 2 * L;
if (check(Monoid::op(sm, dat[L]))) {
sm = Monoid::op(sm, dat[L]);
L++;
}
}
return L - size;
}
sm = Monoid::op(sm, dat[L]);
L++;
} while ((L & -L) != L);
return n;
}
template <class F>
int min_left(F &check, int R) {
assert(0 <= R && R <= n && check(Monoid::unit));
if (R == 0) return 0;
R += size;
X sm = Monoid::unit;
do {
--R;
while (R > 1 && (R % 2)) R >>= 1;
if (!check(Monoid::op(dat[R], sm))) {
while (R < size) {
R = 2 * R + 1;
if (check(Monoid::op(dat[R], sm))) {
sm = Monoid::op(dat[R], sm);
R--;
}
}
return R + 1 - size;
}
sm = Monoid::op(dat[R], sm);
} while ((R & -R) != R);
return 0;
}
void debug() { print("segtree", dat); }
};
#line 2 "/home/maspy/compro/library/nt/primetable.hpp"
vc<ll>& primetable(int LIM) {
++LIM;
const int S = 32768;
static int done = 2;
static vc<ll> primes = {2}, sieve(S + 1);
if(done >= LIM) return primes;
done = LIM;
primes = {2}, sieve.assign(S + 1, 0);
const int R = LIM / 2;
primes.reserve(int(LIM / log(LIM) * 1.1));
vc<pi> cp;
for (int i = 3; i <= S; i += 2) {
if (!sieve[i]) {
cp.eb(i, i * i / 2);
for (int j = i * i; j <= S; j += 2 * i) sieve[j] = 1;
}
}
for (int L = 1; L <= R; L += S) {
array<bool, S> block{};
for (auto& [p, idx]: cp)
for (int i = idx; i < S + L; idx = (i += p)) block[i - L] = 1;
FOR(i, min(S, R - L)) if (!block[i]) primes.eb((L + i) * 2 + 1);
}
return primes;
}
#line 3 "/home/maspy/compro/library/mod/powertable.hpp"
template<typename mint>
vc<mint> powertable_1(mint a, ll N) {
// table of a^i
vc<mint> f(N, 1);
FOR(i, N - 1) f[i + 1] = a * f[i];
return f;
}
template<typename mint>
vc<mint> powertable_2(ll e, ll N) {
// table of i^e. N 以下の素数テーブルを利用する.
auto& primes = primetable(N);
vc<mint> f(N, 1);
f[0] = mint(0).pow(e);
for(auto&& p : primes){
if(p > N) break;
mint xp = mint(p).pow(e);
ll pp = p;
while(pp < N){
ll i = pp;
while(i < N){
f[i] *= xp;
i += pp;
}
pp *= p;
}
}
return f;
}
#line 6 "main.cpp"
using mint = modint107;
struct T {
mint cnt, ans, min_sum, max_sum;
};
struct Mono {
using value_type = T;
using X = value_type;
static X op(X x, X y) {
if (x.cnt == mint(0)) return y;
if (y.cnt == mint(0)) return x;
T z;
z.cnt = x.cnt * y.cnt;
z.ans = x.ans * y.cnt + y.ans * x.cnt + x.max_sum * y.min_sum;
z.max_sum = y.max_sum * x.cnt + x.max_sum;
z.min_sum = x.min_sum * y.cnt + y.min_sum;
return z;
}
static constexpr X unit = X{0, 0, 0, 0};
static constexpr bool commute = false;
};
void solve() {
LL(N);
VEC(ll, A, N);
LL(Q);
VEC(pi, query, Q);
vc<pi> X;
FOR(i, N) X.eb(A[i], i);
FOR(i, Q) X.eb(query[i].se, i + N);
UNIQUE(X);
vi last_time(N, -1);
SegTree<Mono> seg(N + Q);
auto upd = [&](ll time, ll i, ll x) -> void {
if (last_time[i] != -1) {
ll idx = LB(X, mp(A[i], last_time[i]));
seg.set(idx, {0, 0, 0, 0});
}
A[i] = x;
last_time[i] = time;
ll idx = LB(X, mp(x, time));
seg.set(idx, {2, 0, x, x});
};
auto out = [&]() -> void {
auto e = seg.prod_all();
// print(e.cnt, e.ans, e.max_sum, e.min_sum);
print(e.ans / e.cnt);
};
FOR(i, N) upd(i, i, A[i]);
out();
FOR(q, Q) {
auto [i, x] = query[q];
--i;
upd(N + q, i, x);
out();
}
}
signed main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << setprecision(15);
ll T = 1;
// LL(T);
FOR(_, T) solve();
return 0;
}
| cpp |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair<ll, ll> ii;
#define eps 1e-9
#define MOD 998244353
#define pi 3.141592653589793
const int INF = 1e9 + 5;
int t = 0;
vector<int> dp1, dp2;
vector<int> adjList[200005];
vector<int> A;
void dfs1(int u, int parent){
dp1[u] = A[u];
// cout << "u = " << u << " " << dp1[u] << endl;
for(int v: adjList[u]){
if(v == parent) continue;
dfs1(v, u);
dp1[u] += max(dp1[v], 0);
}
// cout << "u = " << u << " " << dp1[u] << endl;
}
void dfs2(int u, int parent){
if(u != 1){
if(dp1[u] > 0){
int x = dp2[parent] - dp1[u];
dp2[u] = dp1[u] + max(x, 0);
}
else{
dp2[u] = dp1[u] + max(dp2[parent], 0);
}
}
for(int v: adjList[u]){
if(v == parent) continue;
dfs2(v, u);
}
}
int main()
{
int n;
cin >> n;
A.resize(n + 1);
for(int i = 1; i <= n; i++) cin >> A[i];
for(int i = 1; i <= n; i++){
if(A[i] == 0) A[i] = -1;
}
// vector<vector<int>> adjList(n+1);
for(int i = 1; i < n; i++){
int u, v;
cin >> u >> v;
adjList[u].push_back(v);
adjList[v].push_back(u);
}
// for(int i = 1; i <= n; i++) cout << A[i] << " ";
// cout << endl;
dp1.resize(n + 1);
dp2.resize(n + 1);
dfs1(1, 1);
// for(int i = 1; i <= n; i++) cout << dp1[i] << " ";
// cout << endl;
dp2[1] = dp1[1];
dfs2(1, 1);
for(int i = 1; i <= n; i++) cout << dp2[i] << " ";
return 0;
}
| cpp |
1312 | F | F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
OutputCopy2
3
0
InputCopy10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
OutputCopy0
2
1
2
5
12
5
0
0
2
| [
"games",
"two pointers"
] | #include<bits/stdc++.h>
#define ll long long
#define ls u<<1
#define rs u<<1|1
#define mm(x) memset(x,0,sizeof(x))
using namespace std;
ll read()
{
ll a=0;ll f=0;char p=getchar();
while(!isdigit(p)){f|=p=='-';p=getchar();}
while(isdigit(p)){a=(a<<3)+(a<<1)+(p^48);p=getchar();}
return f?-a:a;
}
const int INF=998244353;
const int P=998244353;
const int N=1e6+5;
int T;
int n,m;
int x,y,z;
int ans;
ll val[N];
int SG[N][3];
int t[N],top;
int att[3];
int r;
int find(ll u)
{
if(u<=100) return u;
return (u-100)%r+100;
}
void solve()
{
n=read(); ans=0; t[0]=-1;
for(int i=0;i<3;++i) att[i]=read();
for(int i=1;i<=300;++i)
{
for(int j=0;j<3;++j)
{
top=0;
for(int k=0;k<3;++k)
{
if(j==1&&k==1) continue;
if(j==2&&k==2) continue;
t[++top]=SG[max(0,i-att[k])][k];
}
sort(t+1,t+top+1);
SG[i][j]=t[top]+1;
for(int k=0;k<top;++k)
if(t[k]+1<t[k+1])
{
SG[i][j]=t[k]+1;
break;
}
}
}
for(int i=1;i<=100;++i)
{
bool flag=true;
for(int j=1;j<=200;++j)
for(int k=0;k<3;++k)
if(SG[100+j][k]!=SG[100+j%i][k]) flag=false;
if(flag) {r=i;break;}
}
int sum=0;
for(int i=1;i<=n;++i) val[i]=read();
for(int i=1;i<=n;++i)
{
int now=SG[find(val[i])][0];
sum^=now;
}
for(int i=1;i<=n;++i)
{
int now=SG[find(val[i])][0];
for(int j=0;j<3;++j)
{
int ts=SG[find(max(0ll,val[i]-att[j]))][j];
if((sum^now^ts)==0) ans++;
}
}
printf("%d\n",ans);
}
int main()
{
T=read();
while(T--) solve();
return 0;
} | cpp |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
ll t;
cin >> t;
while (t--)
{
ll x, y;
cin >> x >> y;
if (x == y)
cout << x - y << endl;
else if (x < y)
{
if ((y - x) % 2 == 0)
cout << "2" << endl;
else
cout << "1" << endl;
}
else if (x > y)
{
if ((x - y) % 2 == 0)
cout << "1" << endl;
else
cout << "2" << endl;
}
}
return 0;
}
| cpp |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
#pragma optimization_level 3
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
#pragma GCC optimize("Ofast")//Comment optimisations for interactive problems (use endl)
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
using namespace std;
struct PairHash {inline std::size_t operator()(const std::pair<int, int> &v) const { return v.first * 31 + v.second; }};
// speed
#define Code ios_base::sync_with_stdio(false);
#define By ios::sync_with_stdio(0);
#define Sumfi cout.tie(NULL);
// alias
using ll = long long;
using ld = long double;
using ull = unsigned long long;
// constants
const ld PI = 3.14159265358979323846; /* pi */
const ll INF = 1e18;
const ld EPS = 1e-6;
const ll MAX_N = 202020;
const ll mod = 1e9 + 7;
// typedef
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
typedef array<ll,3> all3;
typedef array<ll,4> all4;
typedef array<ll,5> all5;
typedef vector<all3> vall3;
typedef vector<all4> vall4;
typedef vector<all5> vall5;
typedef pair<ld, ld> pld;
typedef vector<pld> vpld;
typedef vector<ld> vld;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<vll> vvll;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef deque<ll> dqll;
typedef deque<pll> dqpll;
typedef pair<string, string> pss;
typedef vector<pss> vpss;
typedef vector<string> vs;
typedef vector<vs> vvs;
typedef unordered_set<ll> usll;
typedef unordered_set<pll, PairHash> uspll;
typedef unordered_map<ll, ll> umll;
typedef unordered_map<pll, ll, PairHash> umpll;
// macros
#define rep(i,m,n) for(ll i=m;i<n;i++)
#define rrep(i,m,n) for(ll i=n;i>=m;i--)
#define all(a) begin(a), end(a)
#define rall(a) rbegin(a), rend(a)
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define INF(a) memset(a,0x3f3f3f3f3f3f3f3fLL,sizeof(a))
#define ASCEND(a) iota(all(a),0)
#define sz(x) ll((x).size())
#define BIT(a,i) (a & (1ll<<i))
#define BITSHIFT(a,i,n) (((a<<i) & ((1ll<<n) - 1)) | (a>>(n-i)))
#define pyes cout<<"YES\n";
#define pno cout<<"NO\n";
#define endl "\n"
#define pneg1 cout<<"-1\n";
#define ppossible cout<<"Possible\n";
#define pimpossible cout<<"Impossible\n";
#define TC(x) cout<<"Case #"<<x<<": ";
#define X first
#define Y second
// utility functions
template <typename T>
void print(T &&t) { cout << t << "\n"; }
template<typename T>
void printv(vector<T>v){ll n=v.size();rep(i,0,n){cout<<v[i];if(i+1!=n)cout<<' ';}cout<<endl;}
template<typename T>
void printvv(vector<vector<T>>v){ll n=v.size();rep(i,0,n)printv(v[i]);}
template<typename T>
void printvln(vector<T>v){ll n=v.size();rep(i,0,n)cout<<v[i]<<endl;}
void fileIO(string in = "input.txt", string out = "output.txt") {freopen(in.c_str(),"r",stdin); freopen(out.c_str(),"w",stdout);}
void readf() {freopen("", "rt", stdin);}
template <typename... T>
void in(T &...a) { ((cin >> a), ...); }
template<typename T>
void readv(vector<T>& v){rep(i,0,sz(v)) cin>>v[i];}
template<typename T, typename U>
void readp(pair<T,U>& A) {cin>>A.first>>A.second;}
template<typename T, typename U>
void readvp(vector<pair<T,U>>& A) {rep(i,0,sz(A)) readp(A[i]); }
void readvall3(vall3& A) {rep(i,0,sz(A)) cin>>A[i][0]>>A[i][1]>>A[i][2];}
void readvall5(vall5& A) {rep(i,0,sz(A)) cin>>A[i][0]>>A[i][1]>>A[i][2]>>A[i][3]>>A[i][4];}
void readvvll(vvll& A) {rep(i,0,sz(A)) readv(A[i]);}
struct Combination {
vll fac, inv;
ll n, MOD;
ll modpow(ll n, ll x, ll MOD = mod) { if(!x) return 1; ll res = modpow(n,x>>1,MOD); res = (res * res) % MOD; if(x&1) res = (res * n) % MOD; return res; }
Combination(ll _n, ll MOD = mod): n(_n + 1), MOD(MOD) {
inv = fac = vll(n,1);
rep(i,1,n) fac[i] = fac[i-1] * i % MOD;
inv[n - 1] = modpow(fac[n - 1], MOD - 2, MOD);
rrep(i,1,n - 2) inv[i] = inv[i + 1] * (i + 1) % MOD;
}
ll fact(ll n) {return fac[n];}
ll nCr(ll n, ll r) {
if(n < r or n < 0 or r < 0) return 0;
return fac[n] * inv[r] % MOD * inv[n-r] % MOD;
}
};
struct Matrix {
ll r,c;
vvll matrix;
Matrix(ll r, ll c, ll v = 0): r(r), c(c), matrix(vvll(r,vll(c,v))) {}
Matrix(vvll m) : r(sz(m)), c(sz(m[0])), matrix(m) {}
Matrix operator*(const Matrix& B) const {
Matrix res(r, B.c);
rep(i,0,r) rep(j,0,B.c) rep(k,0,B.r) {
res.matrix[i][j] = (res.matrix[i][j] + matrix[i][k] * B.matrix[k][j] % mod) % mod;
}
return res;
}
Matrix copy() {
Matrix copy(r,c);
copy.matrix = matrix;
return copy;
}
ll get(ll y, ll x) {
return matrix[y][x];
}
Matrix pow(ll n) {
assert(r == c);
Matrix res(r,r);
Matrix now = copy();
rep(i,0,r) res.matrix[i][i] = 1;
while(n) {
if(n & 1) res = res * now;
now = now * now;
n /= 2;
}
return res;
}
};
// geometry data structures
template <typename T>
struct Point {
T y,x;
Point(T y, T x) : y(y), x(x) {}
Point(pair<T,T> p) : y(p.first), x(p.second) {}
Point() {}
void input() {cin>>y>>x;}
friend ostream& operator<<(ostream& os, const Point<T>& p) { os<<p.y<<' '<<p.x<<'\n'; return os;}
Point<T> operator+(Point<T>& p) {return Point<T>(y + p.y, x + p.x);}
Point<T> operator-(Point<T>& p) {return Point<T>(y - p.y, x - p.x);}
Point<T> operator*(ll n) {return Point<T>(y*n,x*n); }
Point<T> operator/(ll n) {return Point<T>(y/n,x/n); }
bool operator<(const Point &other) const {if (x == other.x) return y < other.y;return x < other.x;}
Point<T> rotate(Point<T> center, ld angle) {
ld si = sin(angle * PI / 180.), co = cos(angle * PI / 180.);
ld y = this->y - center.y;
ld x = this->x - center.x;
return Point<T>(y * co - x * si + center.y, y * si + x * co + center.x);
}
ld distance(Point<T> other) {
T dy = abs(this->y - other.y);
T dx = abs(this->x - other.x);
return sqrt(dy * dy + dx * dx);
}
T norm() { return x * x + y * y; }
};
template<typename T>
struct Line {
Point<T> A, B;
Line(Point<T> A, Point<T> B) : A(A), B(B) {}
Line() {}
void input() {
A = Point<T>();
B = Point<T>();
A.input();
B.input();
}
T ccw(Point<T> &a, Point<T> &b, Point<T> &c) {
T res = a.x * b.y + b.x * c.y + c.x * a.y;
res -= (a.x * c.y + b.x * a.y + c.x * b.y);
return res;
}
bool isIntersect(Line<T> o) {
T p1p2 = ccw(A,B,o.A) * ccw(A,B,o.B);
T p3p4 = ccw(o.A,o.B,A) * ccw(o.A,o.B,B);
if (p1p2 == 0 && p3p4 == 0) {
pair<T,T> p1(A.y, A.x), p2(B.y,B.x), p3(o.A.y, o.A.x), p4(o.B.y, o.B.x);
if (p1 > p2) swap(p2, p1);
if (p3 > p4) swap(p3, p4);
return p3 <= p2 && p1 <= p4;
}
return p1p2 <= 0 && p3p4 <= 0;
}
pair<bool,Point<ld>> intersection(Line<T> o) {
if(!this->intersection(o)) return {false, {}};
ld det = 1. * (o.B.y-o.A.y)*(B.x-A.x) - 1.*(o.B.x-o.A.x)*(B.y-A.y);
ld t = ((o.B.x-o.A.x)*(A.y-o.A.y) - (o.B.y-o.A.y)*(A.x-o.A.x)) / det;
return {true, {A.y + 1. * t * (B.y - A.y), B.x + 1. * t * (B.x - A.x)}};
}
//@formula for : y = ax + fl
//@return {a,fl};
pair<ld, ld> formula() {
T y1 = A.y, y2 = B.y;
T x1 = A.x, x2 = B.x;
if(y1 == y2) return {1e9, 0};
if(x1 == x2) return {0, 1e9};
ld a = 1. * (y2 - y1) / (x2 - x1);
ld b = -x1 * a + y1;
return {a, b};
}
};
template<typename T>
struct Circle {
Point<T> center;
T radius;
Circle(T y, T x, T radius) : center(Point<T>(y,x)), radius(radius) {}
Circle(Point<T> center, T radius) : center(center), radius(radius) {}
Circle() {}
void input() {
center = Point<T>();
center.input();
cin>>radius;
}
bool circumference(Point<T> p) {
return (center.x - p.x) * (center.x - p.x) + (center.y - p.y) * (center.y - p.y) == radius * radius;
}
bool intersect(Circle<T> c) {
T d = (center.x - c.center.x) * (center.x - c.center.x) + (center.y - c.center.y) * (center.y - c.center.y);
return (radius - c.radius) * (radius - c.radius) <= d and d <= (radius + c.radius) * (radius + c.radius);
}
bool include(Circle<T> c) {
T d = (center.x - c.center.x) * (center.x - c.center.x) + (center.y - c.center.y) * (center.y - c.center.y);
return d <= radius * radius;
}
};
ll __gcd(ll x, ll y) { return !y ? x : __gcd(y, x % y); }
all3 __exgcd(ll x, ll y) { if(!y) return {x,1,0}; auto [g,x1,y1] = __exgcd(y, x % y); return {g, y1, x1 - (x/y) * y1}; }
ll __lcm(ll x, ll y) { return x / __gcd(x,y) * y; }
ll modpow(ll n, ll x, ll MOD = mod) { if(x < 0) return modpow(modpow(n,-x,MOD),MOD-2,MOD); n%=MOD; if(!x) return 1; ll res = modpow(n,x>>1,MOD); res = (res * res) % MOD; if(x&1) res = (res * n) % MOD; return res; }
vll solve(ll n, ll a, ll b) {
if(a > b) return solve(n,b,a);
ll sum = a + b, r = sum - n, f = sum - 1;
ll A = r >= 0 ? min(n,r+1) : 1;
ll B = f >= n ? n : f;
return {A,B};
}
int main() {
Code By Sumfi
cout.precision(12);
ll tc = 1;
in(tc);
rep(i,1,tc+1) {
ll n,a,b;
in(n,a,b);
printv(solve(n,a,b));
}
return 0;
} | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.