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 |
---|---|---|---|---|---|
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"
] | #define _CRT_SEstartE_NO_DEPRECATE
#pragma warning(disable : 4996)
#include <map>
#include <unordered_map>
#include <set>
#include <fstream>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <bitset>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdio>
#include <bits/stdc++.h>
#define ACcode ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
typedef long long ll;
typedef unsigned long long ull;
const ll maxn = 1e6 + 7;
const ll maxm = 1e5 + 7;
constexpr ll mod = 998244353;
const ll inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int Prime = 100007;
const double eps = 1e-14;
const double pi = acos(-1.0);
using namespace std;
int fa[maxn * 2], sz[maxn * 2][3], app[maxn * 2][3];
ll ans = 0;
int find(int x)
{
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
void merge(int x, int y)
{
x = find(x), y = find(y);
if (x != y)
{
ans -= min(sz[x][0], sz[x][1]) + min(sz[y][0], sz[y][1]);
fa[y] = x;
sz[x][0] += sz[y][0], sz[x][1] += sz[y][1];
ans += min(sz[x][0], sz[x][1]);
}
}
void solve()
{
int n, m;
string s;
cin >> n >> m >> s;
s = " " + s;
for (int i = 1; i <= m; i++)
{
int k;
cin >> k;
for (int j = 1; j <= k; j++)
{
int x;
cin >> x;
if (!app[x][0])
app[x][0] = i;
else
app[x][1] = i;
}
}
m++; //因为0也计算进并查集中,说明只出现过一次或没有
for (int i = 0; i < 2 * m; i++)
fa[i] = i, sz[i][i >= m] = 1;
for (int i = 1; i <= n; i++)
{
if (s[i] == '0')
{
merge(app[i][0], app[i][1] + m);
merge(app[i][1], app[i][0] + m);
}
else
{
merge(app[i][0], app[i][1]);
merge(app[i][0] + m, app[i][1] + m);
}
int x = find(0);
if (sz[x][0] < sz[x][1])
cout << ans / 2 - sz[x][0] + sz[x][1] << '\n';
else
cout << ans / 2 << '\n';
}
}
signed main()
{
ACcode;
//freopen("intel.in", "r", stdin);
//freopen("intel.out", "w", stdout);
int t = 1;
//cin >> t;
while (t--)
{
solve();
}
return 0;
} | 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"
] | /* #pragma GCC optimize("O3") */
/* #pragma GCC optimize("unroll-loops") */
/* #pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt") */
#include <bits/stdc++.h>
using namespace std;
// #define constexpr(...) (__VA_ARGS__)
using ll = long long;
using ld = long double;
const ld eps = 1e-8;
// for matching the kactl notes
#define sz(x) ((int)x.size())
#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define all(a) (a).begin(), (a).end()
#define print_op(...) ostream &operator<<(ostream &out, const __VA_ARGS__ &u)
// DEBUGING TEMPLETE
// ////////////////////////////////////////////////////////////////////////{{{
// What? You wanted to see how this template works? Check this out:
// https://quangloc99.github.io/2021/07/30/my-CP-debugging-template.html
#define db(val) "[" #val " = " << (val) << "] "
#define CONCAT_(x, y) x##y
#define CONCAT(x, y) CONCAT_(x, y)
#ifdef LOCAL_DEBUG
#define clog cerr << setw(__db_level * 2) << setfill(' ') << "" << setw(0)
#define DB() debug_block CONCAT(dbbl, __LINE__)
int __db_level = 0;
struct debug_block {
debug_block() {
clog << "{" << endl;
++__db_level;
}
~debug_block() {
--__db_level;
clog << "}" << endl;
}
};
#else
#define clog \
if (0) cerr
#define DB(...)
#endif
template <class U, class V> print_op(pair<U, V>) {
return out << "(" << u.first << ", " << u.second << ")";
}
template <size_t i, class T>
ostream &print_tuple_utils(ostream &out, const T &tup) {
if constexpr (i == tuple_size<T>::value) return out << ")";
else
return print_tuple_utils<i + 1, T>(
out << (i ? ", " : "(") << get<i>(tup), tup);
}
template <class... U> print_op(tuple<U...>) {
return print_tuple_utils<0, tuple<U...>>(out, u);
}
template <class Con, class = decltype(begin(declval<Con>()))>
typename enable_if<!is_same<Con, string>::value, ostream &>::type
operator<<(ostream &out, const Con &con) {
out << "{";
for (auto beg = con.begin(), it = beg; it != con.end(); ++it)
out << (it == beg ? "" : ", ") << *it;
return out << "}";
}
// ACTUAL SOLUTION START HERE
// ////////////////////////////////////////////////////////////////}}}
optional<pair<ll, ll>> pair_from_sum_and_xor(ll s, ll x) {
if ((x + s) & 1) return {};
ll a = 0, b = 0;
ll borrow = 0;
for (int bit = 63; bit--; ) {
auto xbit = (x >> bit) & 1;
auto sbit = (s >> bit) & 1;
ll t = borrow * 2 + sbit;
if (xbit) {
a |= 1ll << bit;
borrow = t - 1;
if (borrow > 1 or borrow < 0) return {};
continue;
}
borrow = t & 1;
ll new_bit = t >> 1;
a |= new_bit << bit;
b |= new_bit << bit;
clog << db(bit) << db(a) << db(b) << db(new_bit) << endl;
}
return {{a, b}};
}
int main() {
#ifdef LOCAL
freopen("main.inp", "r", stdin);
freopen("main.out", "w", stdout);
freopen(".log", "w", stderr);
#endif
cin.tie(0)->sync_with_stdio(0);
ll x, s;
cin >> x >> s;
if ((x + s) & 1) {
cout << "-1\n";
return 0;
}
if (x == 0 and s == 0) {
cout << "0\n";
return 0;
}
if (x == s) {
cout << "1\n" << x << '\n';
return 0;
}
auto t = pair_from_sum_and_xor(s, x);
if (t) {
cout << "2\n" << t->first << ' ' << t->second << '\n';
return 0;
}
if (s < x) {
cout << "-1\n";
return 0;
}
cout << "3\n" << x << ' ' << (s - x) / 2 << ' ' << (s - x) / 2 << '\n';
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"
] | // BEGIN BOILERPLATE CODE
#include <bits/stdc++.h>
using namespace std;
#ifdef KAMIRULEZ
const bool kami_loc = true;
const long long kami_seed = 69420;
#else
const bool kami_loc = false;
const long long kami_seed = chrono::steady_clock::now().time_since_epoch().count();
#endif
const string kami_fi = "kamirulez.inp";
const string kami_fo = "kamirulez.out";
mt19937_64 kami_gen(kami_seed);
long long rand_range(long long rmin, long long rmax) {
uniform_int_distribution<long long> rdist(rmin, rmax);
return rdist(kami_gen);
}
long double rand_real(long double rmin, long double rmax) {
uniform_real_distribution<long double> rdist(rmin, rmax);
return rdist(kami_gen);
}
void file_io(string fi, string fo) {
if (fi != "" && (!kami_loc || fi == kami_fi)) {
freopen(fi.c_str(), "r", stdin);
}
if (fo != "" && (!kami_loc || fo == kami_fo)) {
freopen(fo.c_str(), "w", stdout);
}
}
void set_up() {
if (kami_loc) {
file_io(kami_fi, kami_fo);
}
ios_base::sync_with_stdio(0);
cin.tie(0);
}
void just_do_it();
void just_exec_it() {
if (kami_loc) {
auto pstart = chrono::steady_clock::now();
just_do_it();
auto pend = chrono::steady_clock::now();
long long ptime = chrono::duration_cast<chrono::milliseconds>(pend - pstart).count();
string bar(50, '=');
cout << '\n' << bar << '\n';
cout << "Time: " << ptime << " ms" << '\n';
}
else {
just_do_it();
}
}
int main() {
set_up();
just_exec_it();
return 0;
}
// END BOILERPLATE CODE
// BEGIN MAIN CODE
const int ms = 5e5 + 20;
const int inf = 1e9 + 20;
int a[ms];
pair<int, int> p[ms];
int b[ms];
int res[ms];
int pos;
void fix(int <, int &rt) {
if (lt == 0) {
lt = -inf;
rt = inf;
}
else if (b[lt] == 1 && b[rt] == 1) {
lt = -inf;
rt = inf;
}
else if (b[lt] == 2 && b[rt] == 1) {
rt = (lt + rt) / 2;
}
else if (b[lt] == 1 && b[rt] == 2) {
lt = (lt + rt) / 2 + 1;
}
}
void inter(int &l1, int &r1, int l2, int r2) {
if (l1 > r1 || l2 == -inf) {
return;
}
if (l1 <= min(r1, l2 - 1)) {
r1 = min(r1, l2 - 1);
}
else if (max(l1, r2 + 1) <= r1) {
l1 = max(l1, r2 + 1);
}
else {
l1 = inf;
r1 = -inf;
}
}
void update(int l1, int r1, int l2, int r2, int l3, int r3, int val) {
fix(l1, r1);
if (l1 == -inf) {
return;
}
b[pos] = 1;
fix(l2, r2);
fix(l3, r3);
b[pos] = 2;
inter(l1, r1, l2, r2);
inter(l1, r1, l3, r3);
for (int i = l1; i <= r1; i++) {
if (res[i] != -1) {
exit(0);
}
res[i] = val;
}
}
void just_do_it() {
int n, k;
cin >> n;
k = 1;
//cin >> k;
set<int> s;
multiset<int> len;
for (int i = 1; i <= n; i++) {
cin >> a[i];
p[i] = {a[i], i};
b[i] = 1;
res[i] = -1;
s.insert(i);
len.insert(1);
}
int mx = 1;
sort(p + 1, p + n + 1, greater<>());
for (int i = 1; i <= n; i++) {
int l1 = -1;
int r1 = -1;
int l2 = -1;
int r2 = -1;
int l3 = -1;
int r3 = -1;
int val = p[i].first;
pos = p[i].second;
auto it = prev(s.upper_bound(pos));
l2 = (*it);
if (it != s.begin()) {
it--;
r1 = l2 - 1;
l1 = (*it);
it++;
}
it++;
if (it == s.end()) {
r2 = n;
}
else {
r2 = (*it) - 1;
l3 = r2 + 1;
it++;
if (it == s.end()) {
r3 = n;
}
else {
r3 = (*it) - 1;
}
}
b[pos] = 2;
if (l2 == r2 && l2 > 1 && r2 < n) {
update(l1, r3, l1, r1, l3, r3, val);
len.erase(len.find(r1 - l1 + 1));
s.erase(l2);
len.erase(len.find(r2 - l2 + 1));
s.erase(l3);
len.erase(len.find(r3 - l3 + 1));
len.insert(r3 - l1 + 1);
}
else {
len.erase(len.find(r2 - l2 + 1));
if (pos > l2) {
update(l2, pos - 1, l2, r2, 0, 0, val);
len.insert(pos - l2);
}
else {
s.erase(l2);
}
if (pos < r2) {
update(pos + 1, r2, l2, r2, 0, 0, val);
s.insert(pos + 1);
len.insert(r2 - pos);
}
if (pos == l2 && l2 > 1) {
update(l1, pos, l1, r1, 0, 0, val);
len.erase(len.find(r1 - l1 + 1));
len.insert(pos - l1 + 1);
}
else if (pos == r2 && r2 < n) {
update(pos, r3, l3, r3, 0, 0, val);
s.erase(l3);
len.erase(len.find(r3 - l3 + 1));
s.insert(pos);
len.insert(r3 - pos + 1);
}
else {
update(pos, pos, l2, r2, 0, 0, val);
s.insert(pos);
len.insert(1);
}
}
if (val != p[i + 1].first) {
mx = max(mx, *len.rbegin());
}
}
cout << (mx - 1) / 2 << '\n';
if (k == 1) {
for (int i = 1; i <= n; i++) {
cout << res[i] << " ";
}
}
}
// END MAIN CODE | cpp |
1307 | G | G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3
1 2 2
2 3 2
1 3 3
5
0
1
2
3
4
OutputCopy3.0000000000
4.0000000000
4.5000000000
5.0000000000
5.5000000000
| [
"flows",
"graphs",
"shortest paths"
] | #pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
#define int long long
#define elif else if
#define ALL(x) x.begin(),x.end()
#define lowbit(x) (x&(-x))
using namespace std;
void fileio(const string &s)
{
freopen((s+".in").c_str(),"r",stdin);
freopen((s+".out").c_str(),"w",stdout);
}
const int INF=4e18;
inline int read()
{
int x=0;
bool flag=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-')
flag=0;
c=getchar();
}
while(c>='0'&&c<='9')
{
x=(x<<1)+(x<<3)+c-'0';
c=getchar();
}
return (flag?x:~(x-1));
}
struct node{
int to,nxt,cap,val;
}edge[5001];
int n,m,s,t,q,cnt=-1,flow,cost,head[51],dis[51],vis[51],from[51];
vector<array<int,2>> v;
void add(int x,int y,int z,int w)
{
edge[++cnt]={y,head[x],z,w};
head[x]=cnt;
edge[++cnt]={x,head[y],0,-w};
head[y]=cnt;
}
void spfa()
{
fill(dis+1,dis+1+n,INF);
fill(vis+1,vis+1+n,0);
queue<int> q;
q.push(s);
vis[s]=1;
dis[s]=0;
while(!q.empty())
{
int f=q.front();
q.pop();
vis[f]=0;
for(int i=head[f];~i;i=edge[i].nxt)
if(edge[i].cap>0&&dis[edge[i].to]>dis[f]+edge[i].val)
{
dis[edge[i].to]=dis[f]+edge[i].val;
from[edge[i].to]=i;
if(!vis[edge[i].to])
{
vis[edge[i].to]=1;
q.push(edge[i].to);
}
}
}
}
void EK()
{
while(1)
{
spfa();
if(dis[t]==INF)
return ;
int x=INF;
for(int i=t;i!=s;i=edge[from[i]^1].to)
x=min(x,edge[from[i]].cap);
flow+=x;
for(int i=t;i!=s;i=edge[from[i]^1].to)
{
edge[from[i]^1].cap+=x;
edge[from[i]].cap-=x;
cost+=x*edge[from[i]].val;
}
v.push_back({flow,cost});
}
}
signed main()
{
s=1;
t=n=read();
m=read();
for(int i=1;i<=n;i++)
head[i]=-1;
while(m--)
{
int x=read(),y=read(),z=read();
add(x,y,1,z);
}
EK();
q=read();
while(q--)
{
int x=read();
double ans=INF;
for(auto i:v)
ans=min(ans,1.0*(i[1]+x)/i[0]);
printf("%.10f\n",ans);
}
return 0;
}
| cpp |
1299 | E | E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n 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 determine permutation, output !! p1p1 p2p2 ... pnpnAfter 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 formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2
| [
"interactive",
"math"
] | #include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
const int M = 805;
int read()
{
int x=0,f=1;char c;
while((c=getchar())<'0' || c>'9') {if(c=='-') f=-1;}
while(c>='0' && c<='9') {x=(x<<3)+(x<<1)+(c^48);c=getchar();}
return x*f;
}
int n,p[M],id[M],rd[M];
int ask(vector<int> v)
{
printf("? %d",v.size());
for(int x:v) printf(" %d",x);
puts("");fflush(stdout);
return read();
}
int qry(int x)
{
vector<int> v;
for(int i=1;i<=n;i++)
if(i!=x && !p[i]) v.push_back(i);
return ask(v);
}
void get(int x,int a,int y,int b)
{
for(int i=1;i<=n;i++)
{
if(!p[i] && !id[x] && rd[i]==a)
{if(qry(i)) id[x]=i;}
else if(!p[i] && !id[y] && rd[i]==b)
{if(qry(i)) id[y]=i;}
}
p[id[x]]=x;p[id[y]]=y;
}
signed main()
{
n=read();get(1,0,n,0);
for(int t=2,l=2,r=n-1;l<=r;t<<=1)
{
//calc the remainder
for(int i=1;i<=n;i++) if(!p[i])
{
vector<int> v;
for(int j=1;j<=t;j++)
if(j%t!=rd[i]) v.push_back(id[j]);
v.push_back(i);
if(ask(v)) rd[i]+=t>>1;
}
while(l<=2*t && l<=r)
get(l,l%t,r,r%t),l++,r--;
}
if(p[1]>n/2) for(int i=1;i<=n;i++)
p[i]=n-p[i]+1;
printf("!");
for(int i=1;i<=n;i++) printf(" %d",p[i]);
puts("");fflush(stdout);
} | cpp |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define ld double
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define line cout << '\n'
#define sz(v) ((int)(v).size())
const double pi = 3.1415926535897932384626433832795;
const long long mod = 998244353;
const long long inf = 9099999999999999999;
const long long nmax = 2e5 + 100;
const long double eps = 1e-9;
// random_device rd;
// mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
// int MAGIC = rnd();
vector<vector<int>> g(nmax), gr(nmax);
vector<int> d(nmax, inf);
void bfs(int s) {
queue<int> q;
vector<bool> used(nmax, false);
used[s] = true;
q.push(s);
d[s] = 0;
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto to : gr[v]) {
if (!used[to]) {
used[to] = true;
d[to] = d[v] + 1;
q.push(to);
}
}
}
}
void runtimeerror() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
gr[v].push_back(u);
}
int k;
cin >> k;
vector<int> arr(k);
for (int i = 0; i < k; i++)
cin >> arr[i];
int ansmn = 0, ansmx = 0;
bfs(arr[k - 1]);
for (int i = 0; i < k - 1; i++) {
int f = 0;
for (auto to : g[arr[i]]) {
if (to != arr[i + 1]) {
if (d[to] == d[arr[i]] - 1) {
f++;
}
}
}
if (f > 0 || d[arr[i + 1]] > d[arr[i]] - 1)
ansmx++;
if (d[arr[i + 1]] > d[arr[i]] - 1)
ansmn++;
}
cout << ansmn << ' ' << ansmx;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// freopen("C:/Users/tmazi/Downloads/27_B.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
ll t = 1;
// cin >> t;
while (t--)
runtimeerror();
// cout << "WINNER";
// i'm stupid man
} | cpp |
1322 | D | D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
OutputCopy6
InputCopy2 2
1 2
0 0
2 1 -100 -100
OutputCopy2
InputCopy5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
OutputCopy62
NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11. | [
"bitmasks",
"dp"
] | // BEGIN BOILERPLATE CODE
#include <bits/stdc++.h>
using namespace std;
#ifdef KAMIRULEZ
const bool kami_loc = true;
const long long kami_seed = 69420;
#else
const bool kami_loc = false;
const long long kami_seed = chrono::steady_clock::now().time_since_epoch().count();
#endif
const string kami_fi = "kamirulez.inp";
const string kami_fo = "kamirulez.out";
mt19937_64 kami_gen(kami_seed);
long long rand_range(long long rmin, long long rmax) {
uniform_int_distribution<long long> rdist(rmin, rmax);
return rdist(kami_gen);
}
long double rand_real(long double rmin, long double rmax) {
uniform_real_distribution<long double> rdist(rmin, rmax);
return rdist(kami_gen);
}
void file_io(string fi, string fo) {
if (fi != "" && (!kami_loc || fi == kami_fi)) {
freopen(fi.c_str(), "r", stdin);
}
if (fo != "" && (!kami_loc || fo == kami_fo)) {
freopen(fo.c_str(), "w", stdout);
}
}
void set_up() {
if (kami_loc) {
file_io(kami_fi, kami_fo);
}
ios_base::sync_with_stdio(0);
cin.tie(0);
}
void just_do_it();
void just_exec_it() {
if (kami_loc) {
auto pstart = chrono::steady_clock::now();
just_do_it();
auto pend = chrono::steady_clock::now();
long long ptime = chrono::duration_cast<chrono::milliseconds>(pend - pstart).count();
string bar(50, '=');
cout << '\n' << bar << '\n';
cout << "Time: " << ptime << " ms" << '\n';
}
else {
just_do_it();
}
}
int main() {
set_up();
just_exec_it();
return 0;
}
// END BOILERPLATE CODE
// BEGIN MAIN CODE
const int ms = 2e3 + 20;
const int inf = 1e9 + 20;
const int st = 11;
int a[ms];
int b[ms];
int c[ms * 2];
int dp[ms][1 << st];
int best1[ms];
int best2[ms];
int calc(int x, int y) {
int res = 0;
bool ok = false;
for (int i = 0; i < st; i++) {
res += c[x + i];
if (!((y >> i) & 1)) {
ok = true;
break;
}
}
assert(ok);
return res;
}
void just_do_it() {
fill_n(&dp[0][0], ms * (1 << st), -inf);
dp[0][0] = 0;
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
cin >> b[i];
}
for (int i = 1; i <= n + m; i++) {
cin >> c[i];
}
for (int i = n; i >= 1; i--) {
for (int k = a[i]; k >= max(0, a[i] - st); k--) {
for (int j = (1 << st) - 1; j >= 0; j--) {
if (dp[k][j] == -inf) {
continue;
}
int nj = j >> (a[i] - k);
dp[a[i]][nj + 1] = max(dp[a[i]][nj + 1], dp[k][j] + calc(a[i], nj) - b[i]);
}
}
dp[a[i]][1] = max(dp[a[i]][1], best2[max(0, a[i] - st)] + c[a[i]] - b[i]);
best1[a[i]] = -inf;
for (int j = 0; j < (1 << st); j++) {
best1[a[i]] = max(best1[a[i]], dp[a[i]][j]);
}
for (int i = 1; i <= m; i++) {
best2[i] = max(best2[i - 1], best1[i]);
}
}
cout << best2[m];
}
// END MAIN CODE | cpp |
1304 | F2 | F2. Animal Observation (hard 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 on 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≤m1≤k≤m) – 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",
"greedy"
] | #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++)
{
priority_queue<pair<int,int> >q,q2;
for (int j=1;j<k;j++)
q2.push(make_pair(f[i-1][j+k-1]-(a[i-1][m]-a[i-1][j-1]),j+k-1));
for (int j=k;j<=m;j++)
{
f[i][j]=max(get(k,j-k,i-1),get(j+k,m,i-1));
while(!q.empty()&&q.top().second<j-k+1) q.pop();
q.push(make_pair(f[i-1][j]-a[i-1][j],j));
f[i][j]=max(f[i][j],q.top().first+a[i-1][j-k]);
while(!q2.empty()&&q2.top().second<j) q2.pop();
q2.push(make_pair(f[i-1][j+k-1]-(a[i-1][m]-a[i-1][j-1]),j+k-1));
f[i][j]=max(f[i][j],q2.top().first+a[i-1][m]-a[i-1][j]);
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 |
1322 | D | D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
OutputCopy6
InputCopy2 2
1 2
0 0
2 1 -100 -100
OutputCopy2
InputCopy5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
OutputCopy62
NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11. | [
"bitmasks",
"dp"
] | #include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define all(a) a.begin(),a.end()
#define pii pair<int,int>
#define pb push_back
#define sz(a) ((int)a.size())
const int maxn=2005;
int n,m,a[maxn],w[maxn],c[maxn*2],dp[maxn][1<<11],maxx[maxn];
signed main(){
ios_base::sync_with_stdio(0),cin.tie(0);
cin >> n >> m;
for(int i=0; i<n; ++i) cin >> a[i],a[i]--;
for(int i=0; i<n; ++i) cin >> w[i];
for(int i=0; i<n+m; ++i) cin >> c[i];
for(int i=0; i<m; ++i){
maxx[i]=-1e9;
for(int s=0; s<(1<<11); ++s) dp[i][s]=-1e9;
}
for(int i=n-1; i>=0; --i){
int ndp[1<<11];
for(int s=0; s<(1<<11); ++s) ndp[s]=-1e9;
ndp[1]=c[a[i]]-w[i];
for(int j=0; j<=a[i]; ++j){
if(j+11<a[i]){
ndp[1]=max(ndp[1],maxx[j]+c[a[i]]-w[i]);
continue;
}
for(int s=0; s<(1<<11); ++s){
int ns=(s>>(a[i]-j))+1;
int val=dp[j][s]-w[i];
for(int k=a[i]; k<=a[i]+__builtin_ctz(ns); ++k) val+=c[k];
ndp[ns]=max(ndp[ns],val);
}
}
for(int s=0; s<(1<<11); ++s){
dp[a[i]][s]=max(dp[a[i]][s],ndp[s]);
maxx[a[i]]=max(maxx[a[i]],dp[a[i]][s]);
}
}
int res=0;
for(int i=0; i<m; ++i) for(int s=0; s<(1<<11); ++s) res=max(res,dp[i][s]);
cout << res << "\n";
} | cpp |
13 | C | C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1 | [
"dp",
"sortings"
] | #include <bits/stdc++.h>
#define int ll
#define ff first
#define ss second
#define zort sort
#define endl '\n'
#define pb push_back
#define IMAX INT64_MAX
#define N 200005
#define MOD 1000000007
#define MOD2 998244353
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define cno cout<<"NO"<<endl
#define cyes cout<<"YES"<<endl
#define cendl cout<<endl
#define rset srand(int(time(NULL)));
#define dpset memset(dp,-1,sizeof(dp))
#define isint(x) ceil(x)==floor(x)
#define acm(x) accumulate(all(v),0)
#define sumroot(i) double(1/2)*double((double)sqrt(8*i+1)-1)
#define ssum(x) x*(x+1)/2
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);cout<<setprecision(10);
#define allset fast;rset;dpset
using namespace std;
typedef long long ll;
typedef long double ldouble;
typedef string str;
typedef pair<int,int> ii;
typedef pair<ii,int> iii;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<pair<char,int>> vci;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<vi> vvi;
typedef map<int,int> mii;
typedef map<char,int> mci;
typedef map<double,int> mdi;
typedef map<string,int> msi;
typedef map<int,str> mis;
/*
g++ -Wall -g C:\Users\teoat\OneDrive\Belgeler\temp.cpp -o C:\Users\teoat\OneDrive\Belgeler\a.exe
*/
int n,res;
priority_queue<int> pq;
main()
{
cin >> n;
for(int i=1;i<=n;++i)
{
int x; cin >> x;
if(!pq.empty() && pq.top() > x)
{
res += pq.top() - x;
pq.pop();
pq.push(x);
}
pq.push(x);
}
cout << res;
return 0;
}
| cpp |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int i,a,n,r,c,f;
int main()
{
for(cin>>n;n>0;n--)cin>>a,a?c++:(f?(r=max(r,c)):(f=1,i=c),c=0);
cout<<max(r,c+i);
}
| cpp |
1310 | D | D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
OutputCopy2
InputCopy3 2
0 1 1
2 0 1
2 2 0
OutputCopy3
| [
"dp",
"graphs",
"probabilities"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef double db;
template<typename T>inline void read(T&num){
int f=1,ch=getchar();num=0;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){num=num*10+(ch^48);ch=getchar();}
num=num*f;
}
template<typename T>void print(T x){
if(x<0){putchar('-');x=-x;}
if(x>9)print(x/10);
putchar(x%10+48);
}
const int MAXN=82,MAXK=12,INF=0x3f3f3f3f;
int dis[MAXN][MAXN],n,k,dp[MAXK][MAXN],col[MAXN],ans=INF;
template<typename T>inline void Min(T&a,T b){if(a>b)a=b;}
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
void solve(){
for(int i=1;i<=n;i++)col[i]=rng()%2;
for(int i=0;i<=k;i++)for(int j=1;j<=n;j++)dp[i][j]=INF;
dp[0][1]=0;
for(int i=0;i<k;i++){
for(int j=1;j<=n;j++){
if(dp[i][j]==INF)continue;
for(int K=1;K<=n;K++){
if(col[j]==col[K])continue;
Min(dp[i+1][K],dp[i][j]+dis[j][K]);
}
}
}
Min(ans,dp[k][1]);
}
int main(){
read(n);read(k);
for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)read(dis[i][j]);
while((double)clock()/CLOCKS_PER_SEC<=2.55)solve();
cout<<ans<<'\n';
return 0;
}
| 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;
int main()
{
long long t;cin>>t;
while(t--)
{
map<long long,long long> mp;
long long n;cin>>n;
vector<long long> v(n);
long long s1=0,sum=0;
long long maxi= LONG_LONG_MIN;
long long neg=0;
for(long long i=0;i<n;i++)
{
cin>>v[i];
s1+=v[i];
sum+=v[i];
if(maxi<=sum)
{
mp[sum]++;
maxi=sum;
}
if(sum<0)
{
sum=0;
neg++;
}
else if(sum==0)
neg++;
}
// cout<<maxi<<"\n";
// cout<<mp[maxi]<<"\n";
if(s1==maxi && neg==0 && mp[maxi]==1)
cout<<"YES\n";
else if(s1>maxi)
cout<<"YES\n";
else
cout<<"NO\n";
}
} | 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>
#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 = 998244353;
// 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; }
ll solve(ll x, ll y, ll ax, ll ay, ll bx, ll by, ll xs, ll ys, ll t) {
vpll c{{x,y}};
ll sx = x, sy = y;
ll nx = sx * ax + bx, ny = sy * ay + by;
auto dist = [&](ll x1, ll y1, ll x2, ll y2) {return abs(x1-x2) + abs(y1-y2);};
ll INF = 3e16;
while(nx < INF and ny < INF) {
sx = nx, sy = ny;
c.push_back({sx,sy});
nx = sx * ax + bx, ny = sy * ay + by;
}
ll res = 0;
rep(i,0,sz(c)) {
rep(j,i,sz(c)) {
ll ext = min(dist(xs,ys,c[i].first,c[i].second), dist(xs,ys,c[j].first,c[j].second));
ll req = ext + dist(c[i].first, c[i].second, c[j].first, c[j].second);
if(req <= t) res = max(res, j - i + 1);
}
}
return res;
}
int main() {
Code By Sumfi
cout.precision(12);
ll tc = 1;
//in(tc);
rep(i,1,tc+1) {
ll x,y,ax,ay,bx,by,xs,ys,t;
in(x,y,ax,ay,bx,by,xs,ys,t);
print(solve(x,y,ax,ay,bx,by,xs,ys,t));
}
return 0;
} | cpp |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | #include <bits/stdc++.h>
#pragma GCC optimize(2)
#define N 5005
// #define mod 998244353
#define endl '\n'
// #define int long long
// #define ll long long
// #define ll __int128
// #define double long double
#define fastio \
ios_base::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
using namespace std;
int n, mp[N][N], x[N], y[N], a[N], b[N], c[N], m, dep[N];
int tot, head[N], nxt[N << 1], to[N << 1], val[N << 1];
void add(int x, int y, int z)
{
nxt[tot] = head[x], to[tot] = y, val[tot] = z, head[x] = tot++;
}
void dfs(int fa, int cur)
{
dep[cur] = dep[fa] + 1;
for (int p = head[cur]; ~p; p = nxt[p])
if (!dep[to[p]])
dfs(cur, to[p]);
}
void work(int x, int y, int z)
{
if (dep[x] < dep[y])
swap(x, y);
while (dep[x] != dep[y])
{
for (int p = head[x]; ~p; p = nxt[p])
{
if (dep[to[p]] + 1 == dep[x])
{
val[p] = val[p ^ 1] = max(val[p], z);
x = to[p];
break;
}
}
}
while (x != y)
{
for (int p = head[x]; ~p; p = nxt[p])
{
if (dep[to[p]] + 1 == dep[x])
{
val[p] = val[p ^ 1] = max(val[p], z);
x = to[p];
break;
}
}
for (int p = head[y]; ~p; p = nxt[p])
{
if (dep[to[p]] + 1 == dep[y])
{
val[p] = val[p ^ 1] = max(val[p], z);
y = to[p];
break;
}
}
}
}
bool check(int x, int y, int z)
{
int res = 2e6;
if (dep[x] < dep[y])
swap(x, y);
while (dep[x] != dep[y])
{
for (int p = head[x]; ~p; p = nxt[p])
{
if (dep[to[p]] + 1 == dep[x])
{
res = min(res, val[p]);
x = to[p];
break;
}
}
}
while (x != y)
{
for (int p = head[x]; ~p; p = nxt[p])
{
if (dep[to[p]] + 1 == dep[x])
{
res = min(res, val[p]);
x = to[p];
break;
}
}
for (int p = head[y]; ~p; p = nxt[p])
{
if (dep[to[p]] + 1 == dep[y])
{
res = min(res, val[p]);
y = to[p];
break;
}
}
}
return res == z;
}
void solve()
{
cin >> n;
memset(head, -1, sizeof(head));
for (int i = 1; i < n; i++)
{
cin >> x[i] >> y[i];
add(x[i], y[i], 1);
add(y[i], x[i], 1);
}
dfs(0, 1);
cin >> m;
for (int i = 1; i <= m; i++)
{
cin >> a[i] >> b[i] >> c[i];
work(a[i], b[i], c[i]);
}
for (int i = 1; i <= m; i++)
{
if (!check(a[i], b[i], c[i]))
{
cout << -1 << endl;
return;
}
}
for (int i = 0; i < tot; i += 2)
cout << val[i] << " ";
}
signed main()
{
fastio;
// freopen("data.in", "r", stdin);
int t = 1;
// cin >> t;
while (t--)
solve();
// fclose(stdin);
} | cpp |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5
| [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define MOD ((ll) 1e9+7)
#define INF 2e9
#define MAX_LEN (int) 2e5+1
#define pi pair<int, int>
#define f first
#define s second
void solve() {
int n;
cin >> n;
vector<vector<int>> segs(n, vector<int>(2));
for(int i=0; i<n; i++)
cin >> segs[i][0] >> segs[i][1];
sort(begin(segs), end(segs));
int gaps = 0, r = segs[0][0];
for(int i=0; i<n; i++) {
if(r < segs[i][0]) gaps++;
r = max(r, segs[i][1]);
}
gaps++;
int last = -INF, res = 0;
for(int i=0; i<n; i++) {
int j = i+1, add = last == -INF ? -1 : 0;
while(j < n && segs[j][0] <= segs[i][1]) {
if(last < segs[j][0]) add++;
last = max(segs[j][1], last);
if(last > segs[i][1]) break;
j++;
}
if(j < n && segs[j][0] > segs[i][1])
last = -INF;
if(last > segs[i][1])
last = segs[i][1];
i = j-1;
res = max(res, gaps+add);
}
cout << res << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--) solve();
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 all(x) x.begin(), x.end()
#define r_all(x) x.rbegin(), x.rend()
#define sz(x)(ll) x.size()
#define g_max(x, y) x = max(x, y)
#define g_min(x, y) x = min(x, y)
#define rsz(a, n) a.resize(n)
#define ass(a, n) a.assign(n, 0)
#define YES() cout << "YES\n"
#define Yes cout << "Yes\n"
#define NO() cout << "NO\n"
#define No() cout << "No\n"
#define endl "\n"
#define print(a) for (auto &x: a) cout << x << " "; cout << endl
#define print_pair(a)
#define FOR(i, fr, to) for (long long i = fr; i <= to; i++)
#define RFOR(i, fr, to) for (long long i = fr; i >= to; i--)
#define pb push_back
#define eb emplace_back
#define is insert
#define F first
#define S second
using namespace std;
using ll = long long;
using ld = long double;
using vll = vector<ll>;
using vvll = vector<vll>;
using vc = vector<char>;
using vvc = vector<vc>;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
using vvpll = vector<vpll>;
using stkll = stack<ll>;
using qll = queue<ll>;
using dqll = deque<ll>;
using sll = set<ll>;
using msll = multiset<ll>;
using mll = map<ll, ll>;
using vsll = vector<sll>;
using sc = set<char>;
using pcll = pair<char, ll>;
ll dr[] = {0, 1, 0, -1}, dc[] = {-1, 0, 1, 0};
const ll INF = 1e18;
ll MOD = 998244353;
ll mod_add(ll u, ll v, ll mod = MOD) {
u %= mod, v %= mod;
return (u + v) % mod;
}
ll mod_sub(ll u, ll v, ll mod = MOD) {
u %= mod, v %= mod;
return (u - v + mod) % mod;
}
ll mod_mul(ll u, ll v, ll mod = MOD) {
u %= mod, v %= mod;
return (u * v) % mod;
}
ll mod_pow(ll u, ll p, ll mod = MOD) {
u %= mod;
if (p == 0) {
return 1;
}
ll v = mod_pow(u, p / 2, mod) % mod;
v = (v * v) % mod;
return (p % 2 == 0) ? v : (u * v) % mod;
}
ll mod_inv(ll u, ll mod = MOD) {
u %= mod;
ll g = __gcd(u, mod);
if (g != 1) {
return -1;
}
return mod_pow(u, mod - 2, mod);
}
ll mod_div(ll u, ll v, ll mod = MOD) {
u %= mod, v %= mod;
return mod_mul(u, mod_inv(v), mod);
}
template<class T>
vector<T> operator+(vector<T> a, vector<T> b) {
a.insert(a.end(), b.begin(), b.end());
return a;
}
pll operator+(pll a, pll b) {
pll ans = {a.first + b.first, a.second + b.second};
return ans;
}
template<class A, class B>
ostream &operator<<(ostream &os,
const pair<A, B> &p) {
os << p.first << " " << p.second;
return os;
}
template<class A, class B>
istream &operator>>(istream &is, pair<A, B> &p) {
is >> p.first >> p.second;
return is;
}
template<class T>
ostream &operator<<(ostream &os,
const vector<T> &vec) {
for (auto &x: vec) {
os << x << " ";
}
return os;
}
template<class T>
istream &operator>>(istream &is, vector<T> &vec) {
for (auto &x: vec) {
is >> x;
}
return is;
}
template<class T>
ostream &operator<<(ostream &os,
const set<T> &vec) {
for (auto &x: vec) {
os << x << " ";
}
return os;
}
template<class A, class B>
ostream &operator<<(ostream &os,
const map<A, B> d) {
for (auto &x: d) {
os << "(" << x.first << " " << x.second << ") ";
}
return os;
}
template<class A>
void read_arr(A a[], ll from, ll to) {
for (ll i = from; i <= to; i++) {
cin >> a[i];
}
}
template<class A>
void print_arr(A a[], ll from, ll to) {
for (ll i = from; i <= to; i++) {
cout << a[i] << " ";
}
cout << "\n";
}
template<class A>
void print_arr(A a[], ll n) {
print_arr(a, 0, n - 1);
}
template<class A>
void set_arr(A a[], A val, ll from, ll to) {
for (ll i = from; i <= to; i++) {
a[i] = val;
}
}
template<class A>
void set_arr(A a[], A val, ll n) {
set_arr(a, val, 0, n - 1);
}
const ll N = 3e5 + 10;
ll n, m, k, q;
//ll a[N];
string s, s1, s2,s3;
void init() {
}
ll pref[N], vis[N];
ll get_ans() {
s = " " + s;
FOR(i, 1, n) {
ll v = (s[i] == '0') ? 1 : -1;
pref[i] =pref[i - 1] + v;
}
ll cnt_def = 0, cnt = 0;
FOR(i, 0, n) {
cnt_def += (m == pref[i]);
}
if (pref[n] == 0) {
return (cnt_def > 0) ? -1 : 0;
}
FOR(i, 0, n) {
if (i == 0) {
cnt += (m == pref[i]);
continue;
}
cnt += ((m - pref[i]) % pref[n] == 0) && ((m - pref[i]) * pref[n] >= 0);
}
// print_arr(pref, 1, n);
// print_arr(vis, 1, n);
// cout << "Ok\n";
return cnt;
}
void single(ll t_id = 0) {
cin >> n >> m >> s;
cout << get_ans() << "\n";
}
void multiple() {
ll t;
cin >> t;
for (ll i = 0; i < t; i++) {
single(i);
}
}
//#endif
#if 0
void multiple() {
while (cin >> n >> m) {
if (n == 0 && m == 0) {
break;
}
single();
}
#endif
int main(int argc, char *argv[]) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
init();
// freopen("feast.in", "r", stdin);
// freopen("feast.out", "w", stdout);
// freopen("../input.txt", "r", stdin);
multiple();
// single();
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>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//#include <bits/extc++.h>
typedef long long ll;
#define int long long
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define all(a) (a).begin(), (a).end()
#define clr(a, h) memset(a, (h), sizeof(a))
#define F first
#define S second
#define fore(i, b, e) for (int i = (int) b, o_o = e; i < (int) o_o; ++i)
#define forr(i, b, e) for (int i = (int) b, o_o = e; i < (int) o_o; ++i)
#define deb(x) cerr << "# " << (#x) << " = " << (x) << endl;
#define sz(x) (int) x.size()
#define endl '\n'
// int in(){int r=0,c;for(c=getchar();c<=32;c=getchar());if(c=='-') return -in();for(;c>32;r=(r<<1)+(r<<3)+c-'0',c=getchar());return r;}
using namespace std;
//using namespace __gnu_pbds;
//#pragma GCC target ("avx2")
//#pragma GCC optimization ("O3")
//#pragma GCC optimization ("unroll-loops")
typedef pair < int, int > ii;
typedef vector < int > vi;
typedef vector < ii > vii;
typedef vector < ll > vll;
//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
//find_by_order kth largest order_of_key <
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 1e17;
const double PI = acos(-1);
const int tam = 1e6 + 10;
int weapon[tam];
int armor[tam];
const int maxN = 2e5 + 10;
struct node {
int val, lazy;
node() {
val = lazy = 0;
}
node(int v, int l) {
val = v;
lazy = l;
}
void join(node a, node b) {
val = max(a.val, b.val);
}
};
node t[4*tam];
#define index int l = 2*nodo+1, r = l+1, mid = (b+e)/2;
void propagate(int b, int e, int nodo) {
if (t[nodo].lazy == 0) return;
t[nodo].val += t[nodo].lazy;
index;
if (b != e) {
t[l].lazy += t[nodo].lazy;
t[r].lazy += t[nodo].lazy;
}
t[nodo].lazy = 0;
}
void update(int b, int e, int nodo, int i, int j, int val) {
propagate(b, e, nodo);
if (b > j || e < i) return;
if (b >= i && e <= j) {
t[nodo].lazy += val;
propagate(b, e, nodo);
return;
}
index;
update(b, mid, l, i, j, val);
update(mid + 1, e, r, i, j, val);
t[nodo].join(t[l], t[r]);
}
node query(int b, int e, int nodo, int i, int j) {
propagate(b, e, nodo);
if (b > j || e < i) return node(-INF, 0);
if (b >= i && e <= j) return t[nodo];
index;
node a = query(b, mid, l, i, j);
node c = query(mid + 1, e, r, i, j);
node ans;
ans.join(a, c);
return ans;
}
inline void update(int l, int r, int val) {
update(0, tam-1, 0, l, r, val);
}
inline node query(int l, int r) {
return query(0, tam-1, 0, l, r);
}
signed main() {
std::ios::sync_with_stdio(false);
cin.tie(0);
//freopen("","r",stdin);
//freopen("","w",stdout);
fore(i, 0, tam) weapon[i] = armor[i] = INF;
int n, m, p;
cin >> n >> m >> p;
fore(i, 0, n) {
int a, b;
cin >> a >> b;
weapon[a] = min(weapon[a], b);
}
fore(i, 0, m) {
int a, b;
cin >> a >> b;
armor[a] = min(armor[a], b);
}
for (int i = tam-1; i >= 0; --i) {
if (i + 1 < tam) {
weapon[i] = min(weapon[i], weapon[i + 1]);
armor[i] = min(armor[i], armor[i + 1]);
}
if (i+1 < tam) update(i, i, - weapon[i+1]);
else update(i, i, -INF);
}
int ans = - weapon[0] - armor[0];
vector<pair<ii, ii>> vals;
fore(i, 0, p) {
int a, b, c;
cin >> a >> b >> c;
vals.pb({{a, b}, {c, i}});
}
sort(all(vals), [](pair<ii, ii> a, pair<ii, ii> b) {
return mp(a.F.S, a.F.F) < mp(b.F.S, b.F.F);
});
// fore(i, 0, p) vals[i].S.S = i;
// sort(all(vals), [](pair<ii, ii> a, pair<ii, ii> b) {
// return a.F < b.F;
// });
fore(i, 0, p) {
int pos = vals[i].S.S;
int val = vals[i].S.F;
int x = vals[i].F.F;
int y = vals[i].F.S;
update(x, tam-1, val);
ans = max(ans, query(0, tam-1).val - armor[y+1]);
// cerr << x << " " << y << " " << ans << endl;
}
cout << ans << endl;
return 0;
}
// Dinosaurs
| cpp |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | #include<iostream>
using namespace std;
using ll=long long int;
int main()
{
ll t;
cin>>t;
while(t--)
{
ll cnt=0,k=0,sum=0;
ll n;
string s, s1;
cin>>n;
if(n%2 and n>=3)s+='7', n-=3;
while(n>1 and n%2==0)
{
s1+='1';
n-=2;
}
//debug;
s+=s1;
cout<<s<<endl;
}
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>
using namespace std;
struct segtree {
long long mx[4000005], tg[4000005];
segtree(int n) {
for(int i = 1; i <= 4 * n; i++) {
mx[i] = tg[i] = 0;
}
}
void add_tag(int v, int z) {
mx[v] += z;
tg[v] += z;
}
void push_down(int v) {
if(tg[v] != 0) {
add_tag(v << 1, tg[v]);
add_tag(v << 1 | 1, tg[v]);
tg[v] = 0;
}
}
void push_up(int v) {
mx[v] = max(mx[v << 1], mx[v << 1 | 1]);
}
void modify(int x, int y, int z, int v, int l, int r) {
if(y < l || r < x) return;
if(x <= l && r <= y) {
add_tag(v, z);
return;
}
push_down(v);
int mid = (l + r) >> 1;
modify(x, y, z, v << 1, l, mid);
modify(x, y, z, v << 1 | 1, mid + 1, r);
push_up(v);
}
long long query(int x, int y, int v, int l, int r) {
if(y < l || r < x) return INT_MIN;
if(x <= l && r <= y) {
return mx[v];
}
push_down(v);
int mid = (l + r) >> 1;
return max(query(x, y, v << 1, l, mid), query(x, y, v << 1 | 1, mid + 1, r));
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m, p; cin >> n >> m >> p;
segtree tree = segtree(m);
vector<pair<int, int>> a, b;
for(int i = 0; i < n; i++) {
int at, ca; cin >> at >> ca;
a.push_back({at, ca});
}
for(int i = 0; i < m; i++) {
int bt, cb; cin >> bt >> cb;
b.push_back({bt, cb});
}
vector<tuple<int, int, int>> mon;
for(int i = 0; i < p; i++) {
int x, y, z; cin >> x >> y >> z;
mon.push_back({x, y, z});
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
sort(mon.begin(), mon.end());
for(int i = 0; i < m; i++) {
tree.modify(i + 1, i + 1, -b[i].second, 1, 1, m);
}
int ptr = 0;
long long ans = INT_MIN;
for(int i = 0; i < n; i++) {
vector<pair<int, int>> new_mon;
while(ptr < p && get<0>(mon[ptr]) < a[i].first) {
new_mon.push_back({get<1>(mon[ptr]), get<2>(mon[ptr])});
ptr++;
}
sort(new_mon.begin(), new_mon.end());
int j = 0;
for(auto [min_b, cost] : new_mon) {
j = upper_bound(b.begin(), b.end(), make_pair(min_b, (int) 1e9)) - b.begin();
if(j + 1 <= m) tree.modify(j + 1, m, cost, 1, 1, m);
}
ans = max(ans, tree.query(1, m, 1, 1, m) - a[i].second);
}
cout << ans << '\n';
} | 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 <cstdio>
#include <vector>
const int N = 200;
std::vector<int> adj_list[N];
bool color[N], visited[N];
char str[N];
int n;
void dfs(int v) {
visited[v] = true;
for (int u : adj_list[v]) {
if (!visited[u]) {
color[u] = !color[v];
dfs(u);
}
}
}
bool bipartite() {
for (int v = 0; v < n; v++) {
for (int u : adj_list[v]) {
if (color[v] == color[u]) {
return false;
}
}
}
return true;
}
void insert_edge(int u, int v) {
adj_list[u].push_back(v);
adj_list[v].push_back(u);
}
int main() {
scanf("%d\n", &n);
for (int i = 0; i < n; i++) {
str[i] = getchar();
for (int j = 0; j < i; j++) {
if (str[i] < str[j]) {
insert_edge(i, j);
}
}
}
for (int v = 0; v < n; v++) {
if (!visited[v]) {
dfs(v);
}
}
if (bipartite()) {
puts("YES");
for (int i = 0; i < n; i++) {
putchar(color[i] ? '1' : '0');
}
} else {
puts("NO");
}
}
| 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"
] | //MD SHARIQUE HUSSAIN 2112015
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <set>
#include<iomanip>
#include<algorithm>
#include<utility>
#include<set>
#include<unordered_set>
#include<list>
#include<iterator>
#include<deque>
#include<queue>
#include<stack>
#include<bitset>
#include<random>
#include<stdio.h>
#include<complex>
#include<cstring>
#include<chrono>
#include<string>
#include <unordered_map>
//header file ended
using namespace std;
#define INF 1e18
#define pb push_back
#define pll pair <ll,ll>
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define mod1 1000000007
#define mod2 998244353
#define PI 3.141592653589793238462
#define vch vector<char>
#define vll vector<ll>
#define vbb vector<bool>
#define vst vector<string>
#define mll map<ll,ll>
#define mcl map<char,ll>
#define mlc map<ll,char>
#define msl map<string,ll>
#define si set<int>
#define usi unordered_set<int>
#define msi multiset<int>
#define pqsmall priority_queue <ll,vll,greater<ll> >
#define pqlarge priority_queue <ll>
#define nl '\n'
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
#define all(x) (x).begin(), (x).end()
//--------------------------------------------------------------//// nCr starts ////---------------------------------------------------------------
ll powerM(ll a,ll b,ll m){ll res = 1;while(b){if(b & 1){res = (res * a) % m;}a = (a * a) % m;b >>= 1;}return res;}
ll modInverse(ll a , ll m){return powerM(a , m - 2 , m);}
ll nCrModPFermat(ll n , ll r , ll p){if(r == 0){return 1;}ll fac[n + 1];fac[0] = 1;for(ll 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;}
//--------------------------------------------------------------//// nCr ends ////-----------------------------------------------------------------
bool cmp(pair<ll,ll> a,pair<ll,ll> b){if (a.ff!=b.ff){return a.ff>b.ff;}else{return a.ss<b.ss;}}
int gcd(int a, int b){return b == 0 ? a : gcd(b, a % b);}
ll power(ll a,ll n){ll ct=0;if (!(a%n)){while (a%n==0){a/=n;ct++;}}return ct;}
int computeXOR(int n){if (n % 4 == 0)return n;if (n % 4 == 1)return 1;if (n % 4 == 2)return n + 1;return 0;}
void seive1(bool vb[],ll n) {vb[0]=vb[1]=1;for(int i=2;(i*i)<n;i++){if (vb[i]==0){for (int j = i*i; j < n; j+=i){vb[j]=1;}}}}
ll celi(ll a,ll b){return (a+b-1)/b;}
ll modulas(ll i,ll m){return ((i%m)+m)%m;}
ll flor(ll a,ll b){return (a)/b;}
ll moduler_expo(ll a,ll n,ll m){ll x=1,pow=a%m;while (n){if (n&1){x=(x*pow)%m;}pow=(pow*pow)%m;n=n>>1;}return x;}
void fact(ll n,vector<pll> &vp1){for(ll i=2;i*i<=n;i++){if(n%i==0){ll ct=0;while (n%i==0){ct++;n/=i;}vp1.pb(mp(i,ct));}}if(n>1)vp1.pb(mp(n,1));}
ll multi_inv(ll r1,ll r2){ll q,r,t1=0,t2=1,t,m=r1;while (r2 > 0){q=r1/r2;r=r1%r2;t=1-(q*t2);r1=r2;r2=r;t1=t2;t2=t;}if (t1<0){ll a=abs(t1/m);a++;a=a*m;t1=a+t1;}return t1;}
#define rsort(a) sort(a, a + n, greater<int>())
#define rvsort(a) sort(all(a), greater<int>())
#define FOR(i, a, b) for (auto i = a; i < b; i++)
#define rFOR(a, b) for (auto i = a; i >= b; i--)
#define read(a , n) for(int i = 0 ; i < n ; i ++){cin >> a[i];}
const ll N=1e7;
void sol()
{
ll n,flag=0;cin>>n;
map <ll,vll> m1;
FOR(i,0,n)
{
ll x;cin>>x;
m1[x].pb(i);
if(m1[x].size()>2)
{
flag=1;
}
}
if(flag==1)
{
cout<<"YES\n";
return;
}
if(m1.size()==n)
{
cout<<"NO\n";
return;
}
for(auto &val : m1)
{
ll sz=val.ss.size();
if(val.ss[sz-1]-val.ss[0]>1)
{
cout<<"YES\n";
return;
}
}
cout<<"NO\n";
}
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w", stdout);
#endif
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--)
{
sol();
}
return 0;
} | cpp |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
int t,m,n;
for(cin>>t;t--;){
cin>>m>>n;
cout<<(m%n==0?"YES\n":"NO\n");
}
} | 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"
] | #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 = 5e3 + 10;
const LL mod = 1e9 + 7;
int n, m, ai[N]; vector<int> pos[N], f[N]; int g[N][N];
int main() {
//file("test");
read(n), read(m);
for(int i = 1; i <= n; i++) {
int x; read(x); pos[x].emplace_back(i);
ai[i] = x;
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++)
g[i][j] = g[i - 1][j];
g[i][ai[i]]++;
}
vector<int> c;
for(int i = 1; i <= m; i++) {
int x, y; read(x), read(y);
f[x].emplace_back(y);
if(pos[x].size() >= y)
c.emplace_back(pos[x][y - 1]);
}
int ans = 0; LL res = 1;
for(int i = 1; i <= n; i++) sort(f[i].begin(), f[i].end());
for(int i = 1; i <= n; i++) {
int p = 0;
for(int j : f[i])
if(pos[i].size() >= j) p++;
if(p) ans++, res = res * p % mod;
}
for(int i : c) {
LL p = 1; int cnt = 1;
for(int j = 1; j <= n; j++) {
int a = g[i][j], b = pos[j].size() - g[i][j];
int x = upper_bound(f[j].begin(), f[j].end(), a) - f[j].begin();
int y = upper_bound(f[j].begin(), f[j].end(), b) - f[j].begin();
if(ai[i] == j) {
if(b >= a) y--;
if(y) cnt++, p = p * y % mod;
continue;
}
a = x, b = y;
if(a > b) swap(a, b);
if(!b) continue;
else if(b == 1 || a == 0) {
cnt++;
if(a) p = p * 2 % mod;
else p = p * b % mod;
}
else {
b -= a; cnt += 2;
p = p * (1LL * a * (a - 1) % mod + 1LL * a * b % mod) % mod;
}
}
if(cnt > ans) {
ans = cnt, res = p;
}
else if(cnt == ans) res = (res + p) % mod;
}
cout << ans << " " << res << '\n';
#ifdef _MagicDuck
fprintf(stderr, "# Time: %.3lf s", (double)clock() / CLOCKS_PER_SEC);
#endif
return 0;
} | cpp |
1286 | F | F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3
1 10 100
OutputCopy3
InputCopy3
5 3 -2
OutputCopy2
InputCopy1
0
OutputCopy0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed. | [
"brute force",
"constructive algorithms",
"dp",
"fft",
"implementation",
"math"
] | #pragma GCC optimize(2)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#define fi first
#define sc second
#define mkp make_pair
#define pii pair<int,int>
#include <iostream>
using namespace std;
typedef long long ll;
const int N=25,M=(1<<20)+5,K=40000,oo=1e9;
inline int read() {
int x=0;int flag=0;char ch=getchar();
while(ch<'0'||ch>'9') {flag|=(ch=='-');ch=getchar();}
while('0'<=ch&&ch<='9') {x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return flag?-x:x;
}
inline int mx(int x,int y) {return x>y?x:y;}
inline int mn(int x,int y) {return x<y?x:y;}
inline void swp(int &x,int &y) {x^=y^=x^=y;}
inline int as(int x) {return x>0?x:-x;}
int n,st[N],dp[M];
ll a[N];
inline vector<ll> getq(int L,int R) {
if(L>R) return vector<ll>{0};
vector<ll> now,now1,now2; now.clear();
now1=now2=getq(L+1,R);
for(ll &now:now1) now+=a[st[L]];
for(ll &now:now2) now-=a[st[L]];
int len=now1.size(),l=0,r=0;
now.resize(len<<1);
while(l<len&&r<len) {
if(now1[l]<now2[r]) now[l+r]=now1[l],++l;
else now[l+r]=now2[r],++r;
}
while(l<len) now[l+r]=now1[l],++l;
while(r<len) now[l+r]=now2[r],++r;
return now;
}
inline bool check(int S) {
int sum=0,sz=0;
for(int i=0;i<n;++i)
if((S>>i)&1) sum+=a[i+1],st[++sz]=i+1;
if(sz==1) return !sum;
if((sum&1)^((sz-1)&1)) return 0;
int mid=(sz+1)/2;
vector<ll> L=getq(1,mid),R=getq(mid+1,sz);
// printf("%d:\n",S);
// for(ll &now:L) printf("%d ",now); printf("\n");
// for(ll &now:R) printf("%d ",now); printf("\n");
int ccnd=1+(abs(sum)<sz)*2;
int l1=L.size(),l2=R.size(); R.push_back(1e18);
for(int i=0,vl=l2,vr=l2;i<l1;++i) {
while(vr>=0&&L[i]+R[vr]>=sz) --vr;
while(vl>=0&&L[i]+R[vl]>-sz) --vl; ++vl;
ccnd-=mn(ccnd,vr-vl+1);
}
return !ccnd;
}
int main() {
n=read();
for(int i=1;i<=n;++i) scanf("%lld",&a[i]);
for(int fuckrmj=1;fuckrmj<(1<<n);++fuckrmj) if(!dp[fuckrmj]&&check(fuckrmj)) {
int lst=((1<<n)-1)^fuckrmj;
for(int j=lst;;j=(j-1)&lst) {
dp[fuckrmj|j]=mx(dp[fuckrmj|j],dp[j]+1);
if(!j) break;
}
}
printf("%d\n",n-dp[(1<<n)-1]);
return 0;
}
| 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: 97979252
//Writer: HugeWide
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
inline ll read() {
ll x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9') {
if(ch=='-') f=-f;
ch=getchar();
}
while(ch>='0'&&ch<='9') {
x=(x<<3)+(x<<1)+ch-'0';
ch=getchar();
}
return x*f;
}
inline void write(ll x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) write(x/10);
putchar(x%10+'0');
}
#define writesp(x) write(x),putchar(' ')
#define writeln(x) write(x),putchar('\n')
#define rep(x,l,r) for(int x=l;x<=r;x++)
#define per(x,r,l) for(int x=r;x>=l;x--)
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
const int N=500500;
int n,m;
ll c[N];
set<int> s[N];
map<set<int>,ll> sum;
ll gcd(ll x,ll y) {
if(!y) return x;
return gcd(y,x%y);
}
void solve() {
n=read(),m=read(); sum.clear();
rep(i,1,n) c[i]=read(),s[i].clear();
rep(i,1,m) {
int u=read(),v=read();
s[v].insert(u);
}
rep(i,1,n) if(!s[i].empty()) sum[s[i]]+=c[i];
ll g=0; rep(i,1,n) if(!s[i].empty()) g=gcd(g,sum[s[i]]);
writeln(g);
}
int main() {
int t=read(); while(t--) solve();
return 0;
}
| cpp |
1324 | E | E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good. | [
"dp",
"implementation"
] | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
//---------------------------------------------------------------------------------
#define ll long long
#define fixed(n) cout << fixed << setprecision(n)
#define sz(x) int(x.size())
#define TC int t; cin >> t; while(t--)
#define all(s) s.begin(), s.end()
#define rall(s) s.rbegin(), s.rend()
#define dl "\n"
#define Ceil(a, b) ((a / b) + (a % b ? 1 : 0))
#define pi 3.141592
#define OO 2'000'000'000
#define MOD 1'000'000'007
#define EPS 1e-10
using namespace std;
using namespace __gnu_pbds;
//---------------------------------------------------------------------------------
template <typename K, typename V, typename Comp = std::less<K>>
using ordered_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = std::greater<K>>
using ordered_set = ordered_map<K, null_type, Comp>;
template <typename K, typename V, typename Comp = std::less_equal<K>>
using ordered_multimap = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = std::less_equal<K>>
using ordered_multiset = ordered_multimap<K, null_type, Comp>;
// order_of_key(val) count elements smaller than val
// *s.find_by_order(idx) element with index idx
template<typename T = int > istream& operator >> (istream &in , vector < T > &v){
for(auto &i : v) in >> i ;
return in ;
}
template<typename T = int > ostream& operator << (ostream &out ,vector < T > &v){
for(auto &i : v) out << i << ' ' ;
return out ;
}
//-----------------------------------------------------------------------------------------
void ZEDAN() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin) ;
freopen("output.txt", "w", stdout) ;
#endif
}
//-----------------------------------------(notes)-----------------------------------------
/*
*/
//-----------------------------------------(function)--------------------------------------
ll n , h , l , r ;
vector<ll>v ;
vector<vector<ll>>dp ;
bool valid(ll t){
return t>=l &&t<=r ;
}
ll rec(ll i=0 , ll t=0){
if(i>=n) return 0 ;
ll &ret = dp[i][t] ;
if(~ret) return ret ;
return ret = max(valid((t+v[i])%h)+rec(i+1,(t+v[i])%h),valid((t+v[i]-1)%h)+rec(i+1,(t+v[i]-1)%h)) ;
}
//-----------------------------------------(code here)-------------------------------------
void solve(){
int n , h , l , r ;
cin >> n >> h >> l >> r;
vector<int>v(n) ;
vector<vector<int>>dp(2,vector<int>(h+5)) ;
cin >> v ;
auto valid=[&](ll t)->bool{
return t>=l && t<=r ;
};
for(int i=n-1 ; i>=0 ; i--){
for(int t=0 ; t<h ; t++){
int &ret = dp[i%2][t] ;
ret = 0 ;
ret = max(ret,valid((t+v[i])%h)+dp[(i+1)%2][(t+v[i])%h]) ;
ret = max(ret,valid((t+v[i]-1)%h)+dp[(i+1)%2][(t+v[i]-1)%h]) ;
}
}
cout << dp[0][0] ;
}
//-----------------------------------------------------------------------------------------
int main()
{
ZEDAN() ;
ll t = 1 ;
// cin >> t ;
while(t--){
solve() ;
if(t) cout << dl ;
}
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;
int an[1111],m[1111],ans[1111];
int main()
{
long long mx=0,sum;
int n,i,j;
scanf("%d",&n);
for(i=1; i<=n; i++)scanf("%d",&m[i]);
for(i=1; i<=n; i++)
{
an[i]=m[i],sum=m[i];
for(j=i-1; j>=1; j--)an[j]=min(m[j],an[j+1]),sum+=an[j];
for(j=i+1; j<=n; j++)an[j]=min(m[j],an[j-1]),sum+=an[j];
if(mx<sum)
{
mx=sum;
for(j=1; j<=n; j++)ans[j]=an[j];
}
}
for(i=1; i<=n; i++)cout<<ans[i]<<" ";
cout<<endl;
}
| 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;
int main()
{
int n;
char c;
cin>>n>>c;
string s(n,c);
int x=0,y=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='L')
x++;
if(s[i]=='R')
y++;
}
cout<<(x+y+1);
return 0;
}
| cpp |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
// #include<ext/pb_ds/assoc_container.hpp>
// #include<ext/pb_ds/tree_policy.hpp>
#define ll long long
const int mod=998244353;
const int maxn=1e6;
const ll INF=9e18;
#define endl "\n"
#define pb push_back
using namespace std;
// using namespace __gnu_pbds;
// #define ordered_set tree<int, null_type, less_equal<int>, rb_tree_tag,tree_order_statistics_node_update> //(less,less_equal,greater,greater_equal)=(set,multiset,decreasing set,decreasing multiset)
//He who loves to sleep and the folding of hands , poverty will set upon you like a thief in the night.
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tc;
// cin>>tc;
tc=1;
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
while(tc--){
int m,n;
cin>>m>>n;
vector<vector<int> >arr(m,vector<int>(n));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>arr[i][j];
arr[i][j]--;
}
}
int res=0;
for(int j=0;j<n;j++){
map<int,int>mp;
for(int i=0;i<m;i++){
int real=j+i*n;
if((arr[i][j]-j)>=0 && (arr[i][j]-j)%n==0){
int row=(arr[i][j]-j)/n;
if(row>=m) continue;
if(row<=i) mp[i-row]++;
else mp[i+m-row]++;
}
}
int ans=m;
for(auto it:mp){
ans=min(ans,it.first+m-it.second);
}
// cout<<ans<<endl;
res+=ans;
}
cout<<res<<endl;
}
return 0;
} | cpp |
1310 | C | C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1
abac
OutputCopyaba
InputCopy19 5 1821
aupontrougevkoffice
OutputCopyau
NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a". | [
"binary search",
"dp",
"strings"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1010;
const ll inf = 2000000000000000000ll;
struct str {
int l,r,lg;
void L() {lg=r-l+1;}
}w[maxn*maxn];int tmp,w0;
char S[maxn];int n,m,g[maxn][maxn];ll K,f[maxn][maxn],s[maxn][maxn];
bool operator <(str x,str y) {
tmp=min(min(x.lg,y.lg),g[x.l][y.l]);
if(tmp==x.lg&&tmp==y.lg) return x.l<y.l;
if(tmp==x.lg) return 1;
if(tmp==y.lg) return 0;
return S[x.l+tmp]<S[y.l+tmp];
}
bool operator <=(str x,str y) {return x<y||(x.l==y.l&&x.r==y.r);}
ll isok(str mid) {
memset(f,0,sizeof(f)),memset(s,0,sizeof(s)),s[n+1][0]=f[n+1][0]=1;
for(int i=n;i;i--) {
int k=n;while(k>=i&&mid<(str){i,k,k-i+1}) --k;++k;
for(int j=0;j<=m;j++) {
s[i][j]+=s[i+1][j]+(j?f[i][j]=s[k+1][j-1]:0);
if(s[i][j]>inf) s[i][j]=inf;
}
}return f[1][m];
}
signed main() {
scanf("%d%d%lld%s",&n,&m,&K,S+1);
for(int i=n;i;i--)
for(int j=1;j<=n;j++) if(S[i]==S[j]) g[i][j]=g[i+1][j+1]+1;
for(int i=1;i<=n;i++)
for(int j=i;j<=n;j++) w[++w0]=(str){i,j},w[w0].L();
sort(w+1,w+1+w0);
int l=1,r=w0,mid,ans=-1;
while(l<=r)
if(isok(w[mid=l+r>>1])<K) r=(ans=mid)-1;
else l=mid+1;
assert(ans!=-1);
for(int i=w[ans].l;i<=w[ans].r;i++) cout<<S[i];
return 0;
} | 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>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pll;
typedef std::vector<ll> vll;
typedef map<ll,ll>mll;
const ll mod =1000000007,inf = 1e18;
#define in(n) ll n;cin>>n;
#define inp(a,n) vll a(n);for(ll i = 0;i<n;i++) cin>>a[i];
#define rep(i,s,e) for(__typeof(e) i = s;i<e;i++)
#define sz(a) ll(a.size())
#define nl cout<<endl;
#define pb push_back
#define vec(a) (a).begin(),(a).end()
#define len(a) ((ll)(a).size())
const int N = 5e5 + 100;
void print(ll a){cout<<a;nl;}
void print(vll a){for(auto i : a)cout<<i<<" ";nl;}
void print(string s){cout<<s<<endl;}
const long long SIZE = 1e18+10;
void solve()
{
in(n);
inp(a,n);
for(ll i=0;i<n-2;i++){
for(ll j=i+2;j<n;j++){
if(a[i]==a[j]){
cout<<"YES"<<endl;
return;
}
}
}
cout<<"NO"<<endl;
};
signed main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t = 1;
cin >> t;
// cout<<fixed<<setprecision(x)<<endl;
for(ll i = 1;i<=t;i++)
{
// cout << "Case #"<<i<<": ";
solve();
}
} | 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"
] | #include<bits/stdc++.h>
#define endl "\n"
using namespace std;
#define mod 1000000007
#define int long long
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);
#endif
int t; cin>>t;
while(t--){
int n; cin>>n;
string s;
cin>>s;
string b=s;
sort(b.begin(), b.end());
char mini=b[0];
vector<int>pos;
for(int i=0;i<n;i++){
pos.push_back(i);
}
if(b[0]==b[b.length()-1]){
cout<<s<<endl;
cout<<1<<endl;
continue;
}
vector<pair<string,int>>v;
for(int i=0;i<pos.size();i++){
string temp=s.substr(pos[i],n);
string con=s.substr(0,pos[i]);
if(temp.size()%2==0){
temp+=con;
}
else{
reverse(con.begin(), con.end());
temp+=con;
}
v.push_back({temp,pos[i]+1});
}
sort(v.begin(),v.end());
cout<<v[0].first<<endl;
cout<<v[0].second<<endl;
}
return 0;
} | cpp |
1299 | E | E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n 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 determine permutation, output !! p1p1 p2p2 ... pnpnAfter 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 formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2
| [
"interactive",
"math"
] | #include<bits/stdc++.h>
#define ll long long
#define rep(i, x, y) for(int i = (x), stOyny = (y); i <= stOyny; ++i)
#define irep(i, x, y) for(int i = (x), stOyny = (y); i >= stOyny; --i)
#define pb emplace_back
#define pii pair<int, int>
#define vint vector<int>
#define fi first
#define se second
#define let const auto
#define il inline
#define ci const int
#define all(S) S.begin(), S.end()
int read() {
int res = 0, flag = 1; char c = getchar();
while(c < '0' || c > '9') { if(c == '-') flag = -1; c = getchar(); }
while(c >= '0' && c <= '9') res = res * 10 + c - '0', c = getchar();
return res * flag;
}
using namespace std;
template<typename T>
il void tmax(T &x, const T y) { if(x < y) x = y; }
template<typename T>
il void tmin(T &x, const T y) { if(x > y) x = y; }
mt19937 rnd(time(0));
bool query(vint a) {
cout << "? " << a.size() << ' ';
for(int x : a) cout << x << ' ';
cout << endl;
bool res;
cin >> res;
return res;
}
int ans[805], n;
void print() {
if(ans[1] > n / 2) rep(i, 1, n) ans[i] = n + 1 - ans[i];
cout << "! ";
rep(i, 1, n) cout << ans[i] << ' ';
cout << endl;
exit(0);
}
void solve(vint a, int n, int dep, int va) {
if(!dep) return;
vint nxt, gg;
for(int x : a) {
vint b;
for(int y : a) if(y != x) b.pb(y);
if(query(b)) ans[x] = va, gg.pb(x);
else nxt.pb(x);
}
solve(nxt, n - 2, dep - 1, va + 1);
}
vint plac, value;
int m, mxS, sum[1024];
vint prime;
vector<pair<int, vint>> ma[4];
void init() {
rep(s, 0, mxS) rep(i, 0, m - 1) if((s >> i) & 1) sum[s] += value[i];
rep(xby, 0, 3) {
const int mod = prime[xby];
auto &nma = ma[xby];
nma.resize(mod);
rep(i, 0, mod - 1) nma[i].fi = i;
shuffle(all(nma), rnd);
rep(i, 0, mod - 2) {
rep(s, 0, mxS) if(__builtin_popcount(s) == mod - 1 && sum[s] % mod == (mod - nma[i].fi) % mod) {
rep(j, 0, m - 1) if((s >> j) & 1) nma[i].se.pb(plac[j]);
break;
}
}
}
}
int query(int x) {
vint res(4);
rep(xby, 0, 3) {
int mod = prime[xby];
let nma = ma[xby];
res[xby] = nma.back().fi;
rep(i, 0, mod - 2) {
vint cur = nma[i].se;
cur.pb(x);
if(query(cur)) { res[xby] = nma[i].fi; break; }
}
}
rep(i, 1, n) {
bool ok = true;
rep(j, 0, 3) if(i % prime[j] != res[j]) ok = false;
if(ok) return i;
}
return -1;
}
signed main() {
memset(ans, -1, sizeof(ans));
cin >> n;
vint a;
rep(i, 1, n) a.pb(i);
solve(a, n, n <= 70 ? (n >> 1) : (n > 420 ? 5 : 4), 1);
int pl = 0;
rep(i, 1, n) if(ans[i] == 1) { ans[pl = i] = n; break; }
rep(i, 1, n) if(ans[i] > 1 && ans[i] < n) {
if(query(vint({pl, i})) == (n + ans[i]) % 2) ans[i] = n + 1 - ans[i];
}
if(n <= 70) print();
rep(i, 1, n) if(~ans[i]) plac.pb(i), value.pb(ans[i]);
m = plac.size(), mxS = (1 << m) - 1;
prime = vint{3, 5, 7};
prime.pb(n <= 210 ? 2 : ((n <= 420) ? 4 : 8));
init();
rep(i, 1, n) if(ans[i] == -1) ans[i] = query(i);
print();
return 0;
}
| 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"
] | #include<bits/stdc++.h>
using namespace std;int i=1,j,n,m,a[200000];main(){for(cin>>n;i<n;i++){scanf("%d",a+i);a[i]+=a[i-1];}set<int>s(a,a+n);m=*s.begin()-1;if(s.size()<n||*s.rbegin()>m+n)cout<<-1;else for(;j<n;j++)cout<<a[j]-m<<' ';} | 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>
using namespace std;
#define FOR(i, x, y) for (int i = x; i < y; i++)
const int mx = 1e6 + 5;
int n, m, p, ans = -2e9, A[mx], B[mx]; long long seg[mx * 4], lz[mx * 4];
void push(int l, int r, int i){
seg[i] += lz[i];
if (l != r) lz[2 * i] += lz[i], lz[2 * i + 1] += lz[i];
lz[i] = {};
}
void upd(int x, int y, int v, int l = 0, int r = mx - 1, int i = 1){
push(l, r, i);
if (l > y or r < x) return;
if (l >= x and r <= y){ lz[i] += v; push(l, r, i); return; }
int mid = (l + r) / 2;
upd(x, y, v, l, mid, i * 2); upd(x, y, v, mid + 1, r, i * 2 + 1);
seg[i] = max(seg[i * 2], seg[i * 2 + 1]);
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> m >> p;
FOR(i, 0, mx) A[i] = B[i] = 2e9;
FOR(i, 0, n){ int a, c; cin >> a >> c; A[a] = min(A[a], c); }
FOR(i, 0, m){ int b, c; cin >> b >> c; B[b] = min(B[b], c); }
for (int i = mx - 2; ~i; i--) A[i] = min(A[i], A[i + 1]);
FOR(i, 0, mx) upd(i, i, -B[i]);
vector<array<int, 3>> V(p);
for (auto &[x, y, z] : V) cin >> x >> y >> z;
V.push_back({0, 0, 0}); sort(V.begin(), V.end());
for (auto [x, y, z] : V){
upd(y + 1, mx - 1, z);
ans = max(1LL*ans, seg[1] - A[x + 1]);
}
cout<<ans<<"\n";
} | cpp |
1304 | B | B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string. | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | #include<bits/stdc++.h>
using namespace std;
set<string>cy;
int main()
{
int n,m;
string s,t,ans1="",ans2="",rev="";
cin>>n>>m;
while(n--) {
cin>>s,t=s;
reverse(t.begin(),t.end());
if(s==t) ans1=t;
else if(cy.count(t)){ ans2+=t; rev=s+rev;}
cy.insert(s);
}
ans2=ans2+ans1+rev;
cout<<ans2.size()<<"\n"<<ans2<<"\n";
}
| cpp |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an 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 xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define vt vector
#define pb push_back
#define endl "\n"
#define all(x) (x).begin(), (x).end()
#define f(i, j, k) for (ll i = j; i < k; i++)
#define max_v(x) *max_element(all(x))
#define min_v(x) *min_element(all(x))
void solve()
{
int n,x; cin>>n>>x;
vt<int>v(n);
for(int i=0 ; i<n ; i++){
cin>>v[i];
}
sort(all(v));
int t=-1;
for(int i=0 ; i<n ; i++){
if(x%v[i]==0){
t=v[i];
}
}
int ans1=0,ans2=0;
if(t!=-1){
ans1=x/t;
// cout<<ans1<<endl;
}
reverse(all(v));
int mx=v[0];
//cout<<mx<<endl;
if(2*mx>x){
if(t!=-1) cout<<min(2,ans1)<<endl;
else cout<<2<<endl;
}
else{
if(t!=-1) cout<<min(x/mx+1,ans1)<<endl;
else cout<<x/mx+1<<endl;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll tt;
cin >> tt;
while (tt--)
solve();
} | 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];
void dfs(int rt, int v, int p) {
par[rt][v] = 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 = max(calc(u, par[u][v]), calc(v, par[v][u]));
x += sz[u][v]*sz[v][u];
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 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14. | [
"constructive algorithms",
"greedy",
"number theory"
] | // Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
using namespace std;
int main() {
// Write C++ code here
int t;
cin>>t;
while(t!=0){
int x;
cin>>x;
cout<<1<<" "<<x-1<<endl;
t--;
}
return 0;
} | cpp |
1301 | F | F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105) — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m) — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2); mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4); mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4); mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4). | [
"dfs and similar",
"graphs",
"implementation",
"shortest paths"
] | // LUOGU_RID: 94013092
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<cmath>
#define F(i,l,r) for(int i=(l),i##end=(r);i<=i##end;++i)
using namespace std;
const int N=1005,dir[4][2]={-1,0,1,0,0,-1,0,1};
int n,m,k,a[N][N],dis[45][N][N],x1,x2,y1,y2,ans,q,vis[45];
vector<pair<int,int> >col[45];
template<typename T>inline void readmain(T &n){T sum=0,x=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-')x=-1;ch=getchar();}while (ch>='0'&&ch<='9'){sum=sum*10+ch-'0';ch=getchar();}n=sum*x;}
template<typename T>inline T& read(T &x){readmain(x);return x;}
template<typename T,typename ...Tr>inline void read(T &x,Tr&... r){readmain(x);read(r...);}
template<typename T>inline void write(T x){if (x<0){putchar('-');x=-x;}if (x>9)write(x/10);putchar(x%10+'0');return;}
template<typename T>inline void writesc(T x){write(x);putchar(' ');}
template<typename T>inline void writeln(T x){write(x);putchar('\n');}
inline void bfs(int c)
{
F(i,1,k)vis[i]=0;
queue<pair<int,int> >q;
for (auto [i,j]:col[c])q.push({i,j}),dis[c][i][j]=0;
vis[c]=1;while (q.size())
{
int h=q.front().first;
int l=q.front().second;
int x=dis[c][h][l],cc=a[h][l];
q.pop();if (!vis[cc])
{
vis[cc]=1;
for (auto [i,j]:col[cc])if (dis[c][i][j]<0)
{
dis[c][i][j]=x+1;
q.push({i,j});
}
}
F(i,0,3)
{
int nh=h+dir[i][0];
int nl=l+dir[i][1];
if (nh&&nh<=n&&nl&&nl<=m&&dis[c][nh][nl]<0)
{
dis[c][nh][nl]=x+1;
q.push({nh,nl});
}
}
}
}
int main()
{
read(n,m,k);
F(c,1,k)F(i,1,n)F(j,1,m)dis[c][i][j]=-1;
F(i,1,n)F(j,1,m)read(a[i][j]),col[a[i][j]].push_back({i,j});
F(i,1,k)bfs(i);
/*F(c,1,k)
{
F(i,1,n)
{
F(j,1,m)writesc(dis[c][i][j]);
puts("");
}
puts("");
}*/
read(q);while (q--)
{
read(x1,y1,x2,y2);ans=abs(x1-x2)+abs(y1-y2);
F(i,1,k)ans=min(ans,dis[i][x1][y1]+dis[i][x2][y2]+1);
writeln(ans);
}
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 t,n,a[105];
int main()
{
cin >> t;
while (t--){
cin >> n;
int indeven = 0;
int numeven = 0;
for(int i=1; i<=n; ++i){
cin >> a[i];
if(a[i] % 2 == 0){
indeven = i;
++numeven;
}
}
if (indeven > 0){
cout << 1 << endl;
cout << indeven << endl;
} else if (numeven == 0 && n > 1){
cout << 2 << endl;
cout << 1 << ' ' << 2 << endl;
} else {
cout << -1 << endl;
}
}
} | cpp |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | // Akash Singh
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; //Make less_equal for multiset
// find_by_order(k) returns iterator to kth element || order_of_key(k) returns count of elements smaller than k
#define deb(x) cout << x << "\n";
#define deb2(x,y) cout << x << " " << y << "\n";
#define debv(v) for(auto e: v) cout << e << " "; cout << '\n';
#define int long long
#define ll long long
#define mod 1000000007
const int N = 0;
void solver();
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int KitniBar = 1;
// cin >> KitniBar;
for(int tc = 1; tc <= KitniBar; tc++)
{
// cout << "Case #" << tc << ": ";
solver();
}
return 0;
}
void solver()
{
int q, x, y, ans, mex = 0; cin >> q >> x;
vector<bool> arr(400001, false);
vector<int> pre(x+1, 0);
while(q--) {
cin >> y; y -= (y/x)*x;
int mul = max(0LL, mex-y)/x;
for(int i = max(mul, pre[y]); y+i*x <= 400000; i++) {
if(arr[y+i*x]) continue;
arr[y+i*x] = true;
pre[y] = i;
break;
}
while(arr[mex] && mex <= 400000) {
mex++;
}
cout << mex << endl;
}
} | cpp |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33 | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define ff first
#define ss second
#define pii pair<int, int>
#define debug(x) cout << #x << ": " << x << "\n";
const int mxN = 1e5 + 5, lg = 20;
int lift[lg][mxN], tin[mxN], tout[mxN], dep[mxN], timer = 0;
vector<int> adj[mxN];
void dfs(int u, int p) {
lift[0][u] = p;
dep[u] = dep[p] + 1;
for (int i = 1; i < lg; i++) lift[i][u] = lift[i - 1][lift[i - 1][u]];
tin[u] = ++timer;
for (auto i : adj[u]) {
if (i != p) dfs(i, u);
}
tout[u] = timer;
}
int lca(int u, int v) {
if (tin[u] <= tin[v] && tout[u] >= tout[v]) return u;
if (tin[v] <= tin[u] && tout[v] >= tout[u]) return v;
for (int i = lg - 1; i >= 0; i--) {
if (tin[lift[i][u]] > tin[v] || tout[lift[i][u]] < tout[v]) u = lift[i][u];
}
return lift[0][u];
}
int dist(int u, int v) {
return dep[u] + dep[v] - 2 * dep[lca(u, v)];
}
void solve() {
int n;
cin >> n;
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
tin[0] = timer;
dfs(1, 0);
tout[0] = timer;
int q;
cin >> q;
while (q--) {
int x, y, a, b, k;
cin >> x >> y >> a >> b >> k;
int wow = dist(a, b), bruh = min(dist(a, x) + dist(b, y), dist(a, y) + dist(b, x)) + 1;
if ((wow <= k && wow % 2 == k % 2) || (bruh <= k && bruh % 2 == k % 2)) cout << "YES\n";
else cout << "NO\n";
}
}
int32_t main() {
clock_t t1 = clock();
#ifndef ONLINE_JUDGE
freopen("wake.in", "r", stdin);
freopen("sleep.out", "w", stdout);
#endif
int t = 1;
// cin >> t;
while (t--) solve();
// cout << "Time used: " << clock() - t1 << " ms\n";
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>
#define ll long long int
#define fr(i, x, n) for (int i = x; i < n; i++)
#define fra(x, v) for (auto x : v)
using namespace std;
ll power(int a, int b)
{
if (b == 0)
return 1;
ll temp = power(a, b / 2);
if (b % 2 == 0)
return temp * temp;
else
return temp * temp * a;
}
ll fact(ll a){
ll ans = 1;
while (a > 0)
{
ans *= a;
a--;
}
return ans;
}
ll ones(ll a){
ll ans = 0;
while (a > 0)
{
ans += a%2;
a /= 2;
}
return ans;
}
ll gcd(ll a, ll b)
{
return b == 0 ? a : gcd(b, a % b);
}
int dig(ll a)
{
int ans = 0;
while (a > 0)
{
a /= 10;
ans++;
}
return ans;
}
ll sumdig(ll a)
{
ll sum = 0;
while (a > 0)
{
sum += a % 10;
a /= 10;
}
return sum;
}
ll const N = 1000;
ll a[N][N], b[N][N];
// ll ans[10][10];
// void mulM(ll a[10][10] , ll b[10][10] , ll n){
// fr(i , 0 , n){
// fr(j , 0 , n){
// fr(k , 0 , n){
// ans[i][j] += a[i][k]*b[k][j];
// }
// }
// }
// }
// const double pi = 3.1415926536;
// const int maxo = 2e5 + 5;
// bool check[maxo];
//map<char, ll> mp2;
map<char, ll> mp3;
bool isValid(ll xx, ll yy, ll n, ll m)
{
return (xx > 0 && xx <= n && yy > 0 && yy <= m);
}
bool sortbyCond(const pair<double, int> &a,
const pair<double, int> &b)
{
if (a.second != b.second)
return (a.second < b.second);
else
return (a.first < b.first);
}
// const int N = 1000006;
vector<vector<ll>> v(N);
bool vist[N];
// void dfs(ll x)
// {
// for(int i =0 ; i< v[x].size() ; i++ ){
// }
// }
void debug(){
cout << "test" << endl;
return ;
}
ll facto[15];
vector<pair<ll,ll>> comb;
void solve(ll ind , ll s , ll x){
if(ind == 15)return;
s += facto[ind];
x++;
comb.push_back({s , x});
solve(ind + 1 , 0 , 0);
solve(ind + 1 , s , x);
return;
}
map<ll, ll> mpf;
map<ll , ll> mpe;
int main()
{
ios_base::sync_with_stdio(0);
ll n , a , b , k ;cin >> n >> a >> b >> k;
ll an[n + 5] , ans = 0;
fr(i , 0 , n){
ll x;cin >> x;
if(x <= a)an[i] = 0;
else {
x -= a;
ll y = x%(a + b);
if(y > b)an[i] = 0;
else an[i] = y/a + bool(y%a);
}
}
sort(an , an+n);
fr(i , 0 , n){
// cout << an[i] << " " << k << endl;
if(k >= an[i]){
k -= an[i];
ans ++;
}else break;
}
cout << ans << endl;
return 0;
} | cpp |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define sz(x) static_cast<int>((x).size())
#define all(x) begin(x), end(x)
const int mod = 1e9 + 7;
void solve(){
string s, t;
cin >> s >> t;
array<int, 26> def;
for (int i = 0; i < 26; ++i) def[i] = (int)s.size() + 1;
vector<array<int, 26>> next((int)s.size() + 1, def);
for (int i = (int)s.size() - 1; i >= 0; --i){
for (int j = 0; j < 26; ++j){
next[i][j] = next[i + 1][j];
}
int chr = s[i] - 'a';
next[i][chr] = i + 1;
}
auto solve = [&] (string &a, string &b) -> bool{
int n = a.size(), m = b.size();
int dp[n + 1][m + 1];
for (int i = 0; i <= n; ++i)
for (int j = 0; j <= m; ++j)
dp[i][j] = (int)s.size() + 1;
dp[0][0] = 0;
for (int i = 0; i <= n; ++i){
for (int j = 0; j <= m; ++j){
if (dp[i][j] == (int)s.size() + 1) continue;
if (i + 1 <= n) {
int chr = a[i] - 'a';
dp[i + 1][j] = min (dp[i + 1][j], next[dp[i][j]][chr]);
}
if (j + 1 <= m){
int chr = b[j] - 'a';
dp[i][j + 1] = min (dp[i][j + 1], next[dp[i][j]][chr]);
}
}
}
return (dp[n][m] <= (int)s.size());
};
for (int i = 0; i < t.size(); ++i){
string a = t.substr (0, i);
string b = t.substr(i, (int)t.size() - i);
if (solve (a, b)){
cout << "YES \n";
return;
}
}
cout << "NO \n";
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t ;
cin >> t;
while(t--){
solve();
}
} | cpp |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"implementation"
] | ///******* In the name of ALLAH, Who is Most Gracious, Most Merciful *******///
///******* There is no God but ALLAH, MUHAMMAD(S.A.W) is the Messenger of ALLAH. *******///
///******* Every soul shall taste death.*******///
// AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH
// AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH
// AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH
// AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH
// AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH
/**************************************************************************************
___ _ _ _ ___ ___ ________ _ _ _ _____ _ _ ___ _ _
/ _ \| | | | | |/ _ \| \/ | _ | | | | | |_ _| | | | / _ \| | | |
/ /_\ | | ____ | |_| / /_\ | . . | | | | | | | | | | | | | | / /_\ | |_| |
| _ | | |____| | _ | _ | |\/| | | | | | | | | | | | | | | | _ | _ |
| | | | |____ | | | | | | | | | | |/ /| |_| | |____| |_| |___| |___| | | | | | |
\_| |_\_____/ \_| |_\_| |_\_| |_|___/ \___/\_____\___/\_____\_____\_| |_\_| |_/
***************************************************************************************/
// AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH
// AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH
// AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH // AL-HAMDULILLAH
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
//#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define ll long long
#define size1 1000001
#define bm 1000000007 //bigmod
#define reset(arr,n,i) fill(arr,arr+n,i) //cbrt(n) means cube root
#define rset(arr,x) memset(arr,x,sizeof(arr))
#define _ceil(x,y) ((x)/(y))+(((x)%(y))>0)
#define INF 1e18 + 10
#define mod 1e9 + 7//998244353;
#define endl "\n"
#define _cpy(c,a,n) for(int i=0;i<n;i++) c[i]=a[i];
#define _iin(a,n) int a[n]; for(int i=0;i<n;i++) cin>>a[i]
#define _lin(a,n) ll a[n]; for(int i=0;i<n;i++) cin>>a[i]
#define _in(a,n) for(int i=0;i<n;i++) cin>>a[i]
#define _out(a,n) for(int i=0;i<n;i++) cout<<a[i]; cout<<endl
#define _celi(x,y) (x+y-1)/(y) //use this version of _ceil [note: ceil is risky]
#define eps 0.0000000001
#define fopr() freopen("input.txt", "r", stdin)
#define fopw() freopen("output.txt", "w", stdout)
#define FastIO ios_base::sync_with_stdio(false), cin.tie(0)
// Math :
void mns(int *x, int *y) {if(*x>=*y) *x-=*y, *y=0; else *y-=*x, *x=0;}
int log_2(ll n) {int cnt=0; while(n/2) cnt++, n/=2; return cnt;}
// Debuging :
#define _dbg(_x,_y,_z) cout<<_x<<" "<<_y<<" "<<_z<<endl
#define _dbl cout<<"_________________ "<<endl
#define _db(_x,_y) cout<<_x<<" "<<_y<<endl
#define OK cout<<"Ok"<<endl;
using namespace std;
void solve()
{
string str;
cin>>str;
map<char,int>mp;
deque<char>dq;
mp[str[0]]=1;
dq.push_back(str[0]);
char pre=str[0];
for(int i=1;i<str.length();i++){
if(mp.find(str[i])==mp.end()){
if(dq.front()!=pre && dq.back()!=pre){
cout<<"NO"<<endl;
return;
}
if(dq.front()==pre){
dq.push_front(str[i]);
mp[str[i]]=mp[pre]+1;
}
else{
dq.push_back(str[i]);
mp[str[i]]=mp[pre]-1;
}
pre=str[i];
}
else{
if(abs(mp[pre]-mp[str[i]])>1){
cout<<"NO"<<endl;
return;
}
pre=str[i];
}
}
for(int i=0;i<26;i++){
if(mp.find('a'+i)==mp.end()){
char ch='a'+i;
dq.push_back(ch);
}
}
cout<<"YES"<<endl;
_out(dq,dq.size());
}
int main()
{
FastIO;
int n;
cin>>n;
while(n--)
{
solve();
}
return 0;
}
//written by MAMUN
/* Cautions:
1.array out of bound!!! [check array size and last accessed index]
2.signed integer overflow!!! [int*int!=ll @typecast(ll) one of them or, multiply with 1LL]
3.floating point numbers numbers are equal if the difference between them is less than 1e-9 [better way to compare floating point numbers]
4.any square number when divided by 4 must have a remainder of either 0 or 1.
*/
/********************************************************************************************************************************************************
_ _ _ _ _____ _ _ _ _ _ _ ______ _ _ _
| \ | | | | | | | ___| | | | | | | (_) (_) | | ___ \ | | | | | |
| \| | ___ _ __| |_| |__ | |__ __ _ ___| |_ | | | |_ __ ___ _____ _ __ ___ _| |_ _ _ | |_/ / __ _ _ __ __ _| | __ _ __| | ___ ___| |__
| . ` |/ _ \| '__| __| '_ \ | __|/ _` / __| __| | | | | '_ \| \ \ / / _ \ '__/ __| | __| | | | | ___ \/ _` | '_ \ / _` | |/ _` |/ _` |/ _ \/ __| '_ \
| |\ | (_) | | | |_| | | | | |__| (_| \__ \ |_ | |_| | | | | |\ V / __/ | \__ \ | |_| |_| | | |_/ / (_| | | | | (_| | | (_| | (_| | __/\__ \ | | |
\_| \_/\___/|_| \__|_| |_| \____/\__,_|___/\__| \___/|_| |_|_| \_/ \___|_| |___/_|\__|\__, | \____/ \__,_|_| |_|\__, |_|\__,_|\__,_|\___||___/_| |_|
__/ | __/ |
|___/ |___/
*********************************************************************************************************************************************************/
| cpp |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | #include<bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#define int long long
#define N (int)2e5+5
using namespace std;
typedef pair<int, int> P;
const int mod = 998244353;
int fac[N];
int fastpow(int x, int y){
int res = 1;
while(y){
if(y & 1) res = (res * x) % mod;
x = (x * x) % mod;
y >>= 1;
}
return res;
}
void init(int mx){
fac[1] = fac[0] = 1;
for(int i = 2; i <= mx; i++) fac[i] = (fac[i - 1] * i) % mod;
}
int c(int n, int m){
return fac[n] * fastpow(fac[m], mod - 2) % mod * fastpow(fac[n - m], mod - 2) % mod;
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
if(n == 2){
cout << "0\n";
exit(0);
}
init(m);
// c(m, n - 1) * c(n - 2, 1) * sigma(k = 1 ~ n - 3)(c(n - 3, k - 1))
cout << c(m, n - 1) * (n - 2) % mod * fastpow(2, n - 3) % mod << "\n";
return 0;
} | 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"
] | // LUOGU_RID: 102570644
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
const int N = 200005;
vector<int> a;
vector<int> G[N];
int d[N], f[N];
int b[N];
bool cmp(int p1, int p2) {
return d[p1] < d[p2];
}
int main() {
int n, m, g;
scanf("%d%d%d", &n, &m, &g);
while (g--) {
int x;
scanf("%d", &x);
a.push_back(x);
}
while (m--) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
queue<int> q;
memset(d, -1, sizeof d);
memset(f, -1, sizeof f);
q.push(1);
d[1] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto v : G[u]) {
if (d[v] == -1) {
d[v] = d[u] + 1;
q.push(v);
}
}
}
q.push(n);
f[n] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto v : G[u]) {
if (f[v] == -1) {
f[v] = f[u] + 1;
q.push(v);
}
}
}
sort(a.begin(), a.end(), cmp);
int ans = 0;
for (int i = 0; i < a.size() - 1; i++) {
ans = max(ans, d[a[i]] + f[a[i + 1]] + 1);
}
ans = min(d[n], ans);
cout << ans << endl;
return 0;
}
| cpp |
1311 | E | E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example: | [
"brute force",
"constructive algorithms",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
void solve(){
int n,d;cin>>n>>d;
vector<int> v(n+1,1);
int l=1,r=n-1,p=n*(n-1)/2-d;
while(l<r){
while(p<r-l||v[l]==v[l-1]*2&&l<r) ++l;
if(l<r){
++v[l];
p-=r-l;
--r;
}
}
if(p!=0) cout<<"NO\n";
else{
cout<<"YES\n";
int pre=1;
for(int i=1;i<=l;i++){
for(int j=0;j<v[i];j++)
cout<<pre+j/2<<' ';
pre+=v[i-1];
}
cout<<"\n";
}
}
int main()
{
int t;cin>>t;
while(t--)
solve();
return 0;
} | 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: 95932192
#include<bits/stdc++.h>
using namespace std;
#define int long long
int const N=5e5+10;
int c[N];
set<int>a[N];
map< set<int>,int >mp;
inline void solve(){
mp.clear();
int n,m;cin>>n>>m;
for (int i=1;i<=n;++i) cin>>c[i],a[i].clear();
while (m--){
int u,v;cin>>u>>v;
a[v].insert(u);
}
for (int i=1;i<=n;++i) if (!a[i].empty()) mp[a[i]]+=c[i];
int res=0;
for (auto i:mp) res=__gcd(res,i.second);
cout<<res<<'\n';
return;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int t;cin>>t;
while (t--) solve();
return 0;
} | cpp |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.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.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | // Problem: D. Three Integers
// Contest: Codeforces - Codeforces Round #624 (Div. 3)
// URL: https://codeforces.com/contest/1311/problem/D
// Memory Limit: 256 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
#define endl '\n'
#define Carol MyWife^=^
#define pb push_back
#define pp pop_back
#define debug1(x) cout << #x << " = " << (x) << '\n'
#define debug2(x) cout << #x << " = " << (x) << ' '
//#define x first
//#define y second
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 2e4+5, M = 1e6+5;
const int MOD = 998244353, INF = 0x3f3f3f3f;
vector<int> v[N];
int a, b, c;
int A, B, C;
void solve() {
int mn = INF;
cin >> a >> b >> c;
for(int i = 1; i <= 20000; i ++) {
LL temp = abs(c - i);
for(auto x : v[i]) {
LL cost = abs(b - x) + temp;
for(auto y : v[x]) {
if(mn > cost + abs(a - y)) {
mn = cost + abs(a - y);
A = y, B = x, C = i;
}
}
}
}
cout << mn << endl;
cout << A << ' ' << B << ' ' << C << endl;
}
int main() {
for(int j = 1; j <= 20000; j ++) {
int x = j;
for(int i = 1; i <= x / i; i ++) {
if(x % i == 0) {
v[j].pb(i);
if(x / i != i) v[j].pb(x / i);
}
}
sort(v[j].begin(), v[j].end());
}
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int t = 1;
cin >> t;
while(t --) solve();
return 0;
} | 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"
] | #include <bits/stdc++.h>
//#pragma GCC target("sse,sse2,avx2")
//#pragma GCC optimize("unroll-loops,O3")
#define rep(i,l,r) for (int i = l; i < r; i++)
#define repr(i,r,l) for (int i = r; i >= l; i--)
#define X first
#define Y second
#define all(x) (x).begin() , (x).end()
#define pb push_back
#define endl '\n'
#define debug(x) cerr << #x << " : " << x << endl;
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
constexpr int N = 1e6+10,mod = 1e9+7,maxm = 1026;
constexpr ll inf = 1e18+10;
inline int mkay(int a,int b){
if (a+b >= mod) return a+b-mod;
if (a+b < 0) return a+b+mod;
return a+b;
}
inline int poww(int a,int k){
if (k < 0) return 0;
int z = 1;
while (k){
if (k&1) z = 1ll*z*a%mod;
a = 1ll*a*a%mod;
k >>= 1;
}
return z;
}
int n,k,t;
int m;
int p[N];
bool vis[N];
vector<pll> adj[N];
bool good[N];
int lst[maxm];
vector<int> a;
void ask(int i){
lst[i] = a.size();
a.pb(i);
cout << "? " << i << endl;
}
void rst(){
cout << "R\n";
a.clear();
memset(lst,128,sizeof lst);
}
void dfs(int v){
int l = 1 + (v-1)*k,r = v*k;
rep(i,l,r+1) if (good[i]){
ask(i);
char c;
cin >> c;
if (c == 'Y') good[i] = 0;
}
while (p[v] < (int)adj[v].size()){
int u = adj[v][p[v]].X;
int i = adj[v][p[v]].Y;
p[v]++;
if (vis[i]) continue;
rst();
rep(j,l,r+1) if (good[j]){
char c;
ask(j);
cin >> c;
}
vis[i] = 1;
dfs(u);
}
}
int main(){
//ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
memset(lst,128,sizeof lst);
cin >> n >> k;
rep(i,1,n+1){
ask(i);
char c;
cin >> c;
if (c == 'N') good[i] = 1;
}
rst();
if (k == 1){
rep(i,1,n+1){
if (!good[i]) continue;
rep(j,i+1,n+1){
if (!good[j]) continue;
char s;
ask(i);
cin >> s;
ask(j);
cin >> s;
if (s == 'Y') good[j] = 0;
rst();
}
}
int ans = 0;
rep(i,1,n+1) ans += good[i];
cout << "! " << ans << endl;
return 0;
}
k /= 2;
t = n/k;
rep(i,1,t+1) rep(j,i+2,t+1){
adj[i].pb({j,m});
adj[j].pb({i,m});
m++;
}
dfs(1);
int ans = 0;
rep(i,1,n+1) ans += good[i];
cout << "! " << ans << endl;
}
| 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"
] | #include<cstdio>
#include<vector>
#include<algorithm>
#include<map>
#define mod 998244353
struct matrix
{
long long a[2][2];
matrix(){}
matrix(long long a0,long long a1,long long a2,long long a3){a[0][0]=a0,a[0][1]=a1,a[1][0]=a2,a[1][1]=a3;}
};
matrix operator *(matrix x,matrix y)
{
matrix ans;
ans.a[0][0]=(x.a[0][0]*y.a[0][0]+x.a[0][1]*y.a[1][0])%mod;
ans.a[0][1]=(x.a[0][0]*y.a[0][1]+x.a[0][1]*y.a[1][1])%mod;
ans.a[1][0]=(x.a[1][0]*y.a[0][0]+x.a[1][1]*y.a[1][0])%mod;
ans.a[1][1]=(x.a[1][0]*y.a[0][1]+x.a[1][1]*y.a[1][1])%mod;
return ans;
}
struct sgt
{
struct node
{
matrix s;
};
node a[300005];
matrix mat[100005];
void pushup(int k){a[k].s=a[k*2+1].s*a[k*2].s;}
void build(int k,int l,int r)
{
if (l==r) return a[k].s=mat[l],void();
int mid=(l+r)/2;
build(k*2,l,mid);
build(k*2+1,mid+1,r);
pushup(k);
}
void update(int k,int l,int r,int x,int pos,long long w)
{
// if (k==1) printf("Upd %d %d %lld\n",x,pos,w);
if (l==r) return /*printf("clear %d %d\n",pos>>1,pos&1),*/a[k].s.a[pos>>1][pos&1]=0,void();
int mid=(l+r)/2;
if (x<=mid) update(k*2,l,mid,x,pos,w);
if (mid<x) update(k*2+1,mid+1,r,x,pos,w);
pushup(k);
}
};
sgt t;
struct node{double t;int id,pos;node(double t=0,int id=0,int pos=0){this->t=t,this->id=id,this->pos=pos;}};
std::vector<node> vec;
int n,pos[100005],v[100005];
long long ans=0,pb[100005];
std::map<double,long long> mp;
long long fp(long long x,int y){return (y&1?x:1ll)*(y>>1?fp(x*x%mod,y>>1):1ll)%mod;}
int cmp(node x,node y){return x.t<y.t;}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d%d%lld",&pos[i],&v[i],&pb[i]),pb[i]=pb[i]*828542813%mod;
t.mat[1]=matrix((1-pb[1]+mod)%mod,(1-pb[1]+mod)%mod,pb[1],pb[1]);
for (int i=2;i<=n;i++) t.mat[i]=matrix((1-pb[i]+mod)%mod,(1-pb[i]+mod)%mod,pb[i],pb[i]);
// for (int i=1;i<=n;i++) printf("%d:(%lld %lld %lld %lld)\n",i,t.mat[i].a[0][0],t.mat[i].a[0][1],t.mat[i].a[1][0],t.mat[i].a[1][1]);
t.build(1,1,n);
for (int i=2;i<=n;i++)
{
if (v[i]>v[i-1])
{
double w=(pos[i]-pos[i-1])/(double)(v[i]-v[i-1]);
long long c=(pos[i]-pos[i-1])*fp(v[i]-v[i-1],mod-2)%mod;
mp[w]=c;
vec.push_back(node(w,i,0));
}
if (v[i]<v[i-1])
{
double w=(pos[i]-pos[i-1])/(double)(v[i-1]-v[i]);
long long c=(pos[i]-pos[i-1])*fp(v[i-1]-v[i],mod-2)%mod;
mp[w]=c;
vec.push_back(node(w,i,3));
}
double w=(pos[i]-pos[i-1])/(double)(v[i]+v[i-1]);
long long c=(pos[i]-pos[i-1])*fp((v[i-1]+v[i])%mod,mod-2)%mod;
mp[w]=c;
vec.push_back(node(w,i,1));
}
std::sort(vec.begin(),vec.end(),cmp);
int d=0;
long long np=1;
while (d<(int)vec.size())
{
double tm=vec[d].t;
// printf("tm = %lf\n",tm);
while (d<(int)vec.size()&&vec[d].t==tm) t.update(1,1,n,vec[d].id,vec[d].pos,0),++d;
matrix mat=t.a[1].s;
// printf("(%lld %lld %lld %lld)\n",t.a[1].s.a[0][0],t.a[1].s.a[0][1],t.a[1].s.a[1][0],t.a[1].s.a[1][1]);
long long pp=499122177*(mat.a[0][0]+mat.a[0][1]+mat.a[1][0]+mat.a[1][1])%mod;
// printf("%lld\n",mp[tm]);
ans=(ans+(np-pp+mod)*mp[tm])%mod;
// printf("qwq %lld %lld\n",np,pp);
np=pp;
}
printf("%lld\n",ans);
return 0;
} | cpp |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(NULL);
cin.tie(0);
cout.tie(0);
long long int n, ans = 0;
cin >> n;
vector<int>a(n + 1);
map<long long int, long long int>mp;
for(int i = 1; i <= n;i++) {
cin >> a[i];
}
for(int i = 1; i <= n;i++) {
mp[a[i] - i]+=a[i];
ans = max(ans, mp[a[i] - i]);
}
cout << ans << '\n';
} | cpp |
1301 | B | B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33. | [
"binary search",
"greedy",
"ternary search"
] | #include<bits/stdc++.h>
using namespace std;
#define endl '\n';
#define int int64_t
#define mod (int)(1e9+7)
void solve(){
int n;
cin>>n;
vector<int>arr(n);
bool flag=true;
int mini=INT_MAX,maxi=INT_MIN;
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i]==-1){
flag=false;
if(i+1<n && arr[i+1]!=-1){
mini=min(mini,arr[i+1]);
maxi=max(maxi,arr[i+1]);
}
if(i-1>=0 && arr[i-1]!=-1){
mini=min(mini,arr[i-1]);
maxi=max(maxi,arr[i-1]);
}
}
}
// cout<<maxi<<" "<<mini<<endl;
if(flag){
cout<<0<<" "<<0<<endl;
return;
}
int k=(maxi+mini)/2;
for(int i=0;i<n;i++){
if(arr[i]==-1) arr[i]=k;
}
int ans=0;
for(int i=0;i<n-1;i++) ans=max(ans,abs(arr[i]-arr[i+1]));
cout<<ans<<" "<<k<<endl;
}
signed main(){
ios_base::sync_with_stdio(false);cin.tie(NULL);
int t=1;
cin>>t;
while(t--){
solve();
}
} | cpp |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | #include <bits/stdc++.h>
using i64 = long long;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n;
std::cin >> n;
std::vector<int> x(n), y(n);
for (int i = 0; i < n; i++) {
std::cin >> x[i] >> y[i];
}
if (n % 2) {
std::cout << "NO\n";
return 0;
}
auto dis = [&](int i, int j) {
return (x[i] - x[j]) * 1LL * (x[i] - x[j]) + (y[i] - y[j]) * 1LL * (y[i] - y[j]);
};
for (int i = 1, j = n / 2 + 1; i < n / 2; i++, j++) {
if (dis(0, i) != dis(n / 2, j) || dis(n / 2, i) != dis(0, j)) {
std::cout << "NO\n";
return 0;
}
}
std::cout << "YES\n";
return 0;
}
| cpp |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
| [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | /*
*
* ^v^
*
*/
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <iomanip>
#include <map>
#include <functional>
#include <algorithm>
#include <set>
#include <queue>
#include <climits>
#include <cstdlib>
#include <chrono>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
using namespace std;
// #define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define iamtefu ios_base::sync_with_stdio(false); cin.tie(0);
#define ll long long int
#define ld long double
#define fl(i,a,n) for (ll i(a); i<n; i++)
#define rfl(i,a,n) for (ll i(n-1); i>=a; i--)
#define print(a) for (auto x:a){cout<<x<<" ";} cout<<"\n";
#define tt int tt; cin>>tt; for(;tt--;)
ll gcd(ll a, ll b){
if (b==0){
return a;
}
return gcd(b, a%b);
}
ll pw(ll a, ll b, ll m){
ll res=1;
a%=m;
while (b){
if (b&1){
res=(res*a)%m;
}
a=(a*a)%m;
b>>=1;
}
return res;
}
void scn(){
ll n; cin>>n;
vector <ll> a(n+1);
vector <vector <ll>> ed(n+1);
ll rt = 0;
fl(i,0,n){
ll x; cin>>x>>a[i+1];
// cout<<x<<' '<<a[i+1]<<'\n';
if (x==0){
rt = i+1;
} else {
ed[x].push_back(i+1);
ed[i+1].push_back(x);
}
}
ll don = 0;
vector <ll> vis(n+1);
function<vector<ll>(ll)> dfs=[&](ll i){
vis[i]++;
vector <ll> ans;
for (auto x:ed[i]){
if (!vis[x]){
vector <ll> hu = dfs(x);
ans.insert(ans.end(), hu.begin(), hu.end());
}
}
if (ans.size()<a[i]){
don++;
ans.push_back(i);
return ans;
} else {
ans.insert(ans.begin()+a[i], i);
}
return ans;
};
vector <ll> hu = dfs(rt);
if (don){
cout<<"No\n";
return;
} else {
vector <ll> an(n);
fl(i,0,n){
an[hu[i]-1]=i+1;
}
cout<<"Yes\n";
print(an)
}
}
int main(){
iamtefu;
#if defined(airths)
auto t1=chrono::high_resolution_clock::now();
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#else
//
#endif
// tt
{
scn();
}
#if defined(airths)
auto t2=chrono::high_resolution_clock::now();
ld ti=chrono::duration_cast<chrono::nanoseconds>(t2-t1).count();
ti*=1e-6;
cerr<<"Time: "<<setprecision(12)<<ti;
cerr<<"ms\n";
#endif
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"
] | #include <bits/stdc++.h>
using namespace std;
constexpr int N = 1 << 18;
int n, fa[N], sz[N];
long long ans;
int findf(int x) { return x == fa[x] ? x : fa[x] = findf(fa[x]); }
void unite(int u, int v, int w) {
if (!sz[u] || !sz[v]) return;
if ((u = findf(u)) == (v = findf(v))) return;
ans += w * (sz[u] + sz[v] - 1ll), sz[fa[u] = v] = 1;
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n, sz[0] = 1;
for (int i = 1, a; i <= n; ++i) cin >> a, ans -= a, ++sz[a];
iota(fa, fa + N, 0);
for (int i = N - 1; i; --i) {
int j = i;
do unite(j, i ^ j, i), j = (j - 1) & i;
while (j != i);
}
return cout << ans << endl, 0;
} | cpp |
1290 | D | D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 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 3n22k3n22k 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 3n22k≤15 0003n22k≤15 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 3n22k3n22k 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 3n22k≤15 0003n22k≤15 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. | [
"constructive algorithms",
"graphs",
"interactive"
] | #include <bits/stdc++.h>
using namespace std;
bool ask(int x) {
cout << '?' << ' ' << x + 1 << endl;
char c; cin >> c;
return c == 'Y' ? true : false;
}
void reset() {
cout << 'R' << endl;
}
void tell(int x) {
cout << '!' << ' ' << x << endl;
}
void solve_small(int n, int k) {
set <int> ans;
for(int i = 0; i < n; i++) ans.insert(i);
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
reset();
ask(i);
if(ask(j)) ans.erase(j);
}
}
tell(ans.size());
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int n, k;
cin >> n >> k;
if(k == 1) {
solve_small(n, k);
return 0;
}
vector<vector<int>> v;
for(int i = 0; i < n/k; i++) {
reset();
vector <int> unique;
for(int j = 0; j < k; j++) {
auto t = ask(i*k + j);
if(!t) unique.push_back(i*k + j);
}
while((int)unique.size() < k) unique.push_back(unique.front());
v.push_back(unique);
}
for(int sz = k; sz < n; sz *= 2) {
vector<vector<int>> w;
for(int i = 0; i < (int)v.size(); i += 2) {
// merge v[i] and v[i + 1]!
auto a = v[i];
auto b = v[i + 1];
map <int, bool> rema, remb;
for(int j = 0; j < sz; j += k) {
// starting block of a.
for(int t = 0; t < sz; t += k) {
// starting block of b. Remove duplicates in (5K/2) queries.
reset();
for(int x = 0; x < k/2; x++) {
ask(a[j + x]);
}
for(int x = 0; x < k/2; x++) {
if(ask(b[t + x])) remb[t + x] = true;
}
for(int x = 0; x < k/2; x++) {
if(ask(a[j + k/2 + x])) rema[j + k/2 + x] = true;
}
for(int x = 0; x < k/2; x++) {
if(ask(b[t + k/2 + x])) remb[t + k/2 + x] = true;
}
reset();
for(int x = 0; x < k/2; x++) {
ask(a[j + x]);
}
for(int x = 0; x < k/2; x++) {
if(ask(b[t + k/2 + x])) remb[t + k/2 + x] = true;
}
}
}
vector <int> temp;
for(int i = 0; i < sz; i++) {
if(!rema[i]) temp.push_back(a[i]);
}
for(int i = 0; i < sz; i++) {
if(!remb[i]) temp.push_back(b[i]);
}
while((int)temp.size() < 2*sz) temp.push_back(temp.front());
w.push_back(temp);
}
v = w;
}
set <int> s;
for(auto i : v.front()) s.insert(i);
tell((int)s.size());
return 0;
} | cpp |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"greedy"
] | // LUOGU_RID: 101967699
#include <bits/stdc++.h>
using i64 = long long;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n;
std::cin >> n;
std::vector<int> a(n);
for (int i = 0; i < n; i++) {
std::cin >> a[i];
}
std::vector<int> s(n + 1);
for (int i = 0; i < n; i++) {
s[i + 1] = s[i] + a[i];
}
std::map<int, std::vector<std::pair<int, int>>> rag;
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
rag[s[j] - s[i - 1]].emplace_back(j, i);
}
}
std::vector<std::pair<int, int>> ans;
for (auto [x, v] : rag) {
std::sort(v.begin(), v.end());
int l = 0, r = 0;
std::vector<std::pair<int, int>> res;
for (auto p : v) {
if (res.empty() || p.second > res.back().first) {
res.emplace_back(p);
}
}
if (res.size() > ans.size()) ans = res;
}
std::cout << ans.size() << "\n";
for (auto [r, l] : ans) {
std::cout << l << " " << r << "\n";
}
return 0;
} | 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>
using namespace std;
namespace vbzIO {
char ibuf[(1 << 20) + 1], *iS, *iT;
#if ONLINE_JUDGE
#define gh() (iS == iT ? iT = (iS = ibuf) + fread(ibuf, 1, (1 << 20) + 1, stdin), (iS == iT ? EOF : *iS++) : *iS++)
#else
#define gh() getchar()
#endif
#define pi pair<int, int>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define ins insert
#define era erase
inline int read () {
char ch = gh();
int x = 0;
bool t = 0;
while (ch < '0' || ch > '9') t |= ch == '-', ch = gh();
while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = gh();
return t ? ~(x - 1) : x;
}
inline void write(int x) {
if (x < 0) {
x = ~(x - 1);
putchar('-');
}
if (x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
}
using vbzIO::read;
using vbzIO::write;
const int maxn = 4e5 + 400;
int n, m, b, top, st[maxn], vis[maxn], dep[maxn];
vector<int> ans, g[maxn];
void dfs(int u, int fa) {
dep[u] = dep[fa] + 1, st[++top] = u;
for (int v : g[u]) {
if (dep[v]) {
if (dep[v] > dep[u] - b + 1) continue;
write(2), puts("");
vector<int> tp;
while (st[top] != v) {
tp.pb(st[top]);
top--;
}
write(tp.size() + 1), puts("");
for (int i : tp) write(i), putchar(' ');
write(v);
exit(0);
} else dfs(v, u);
}
if (!vis[u]) {
ans.pb(u);
for (int v : g[u]) vis[v] = 1;
}
top--;
}
int main() {
n = read(), m = read(), b = sqrt(n - 1) + 1;
for (int i = 1, u, v; i <= m; i++) {
u = read(), v = read();
g[u].pb(v), g[v].pb(u);
}
dfs(1, 0);
write(1), puts("");
for (int i = 0; i < b; i++) write(ans[i]), putchar(' ');
return 0;
} | cpp |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.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.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | //__________Includes__________________//
# include <iostream>
# include <algorithm>
# include <vector>
# include <string>
# include <map>
# include <unordered_map>
# include <set>
# include <unordered_set>
# include <bitset>
# include <queue>
# include <stack>
# include <complex>
# include <cmath>
# include <climits>
# include <cstring>
//____________Containers_Define__________//
# define vi vector<int>
# define vll vector<long long>
# define vull vector<unsigned long long>
# define vvi vector<vector<int> >
# define vvll vector<vector<long long> >
# define vvull vector<vector<unsigned long long> >
# define vs vector<string>
# define vvs vector<vector<string> >
# define vpi vector<pair<int, int> >
# define vvpi vector<vector<pair<int, int> > >
# define pii pair<int, int>
# define pis pair<int, string>
# define psi pair<string, int>
# define mpii map<int, int>
# define mpis map<int, string>
# define mpsi map<string, int>
# define mpiv map<int, vector<int> >
# define umpii unordered_map<int, int>
# define umpis unordered_map<int, string>
# define umpsi unordered_map<string, int>
# define umpiv unordered_map<int, vector<int> >
//_____________Data_type________________//
# define ll long long
# define ull unsigned long long
//_____________Methods__________________//
# define mp make_pair
# define pb push_back
# define pf push_front
# define f first
# define s second
# define srt(v) sort(v.begin(), v.end())
# define ub(v, trg) upper_bound(v.begin(), v.end(), trg)
# define lb(v, trg) lower_bound(v.begin(), v.end(), trg)
using namespace std;
//______________Functions________________//
bool isInt(double d)
{
return ((double)(int)d - d == (double)0.00);
}
ull fact(ull n)
{
ull res = 1;
while (n--) res *= (n + 1);
return (res);
}
ull C(ull n, ull k)
{
vull dpp(n + 1);
vvull dp(k + 1, dpp);
for (int i=1; i<=n; i++) dp[1][i] = i;
for (int i=2; i<=k; i++)
{
for (int j=1; j<=n; j++)
{
if (i > j)
dp[i][j] = 0;
else
dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1];
}
}
return (dp[k][n]);
}
vpi merge_intervals(vpi intervals)
{
pair<int, int> v;
vpi ans;
if (!intervals.size()) return (ans);
sort(intervals.begin(), intervals.end());
v.f = intervals[0].f;
v.s = intervals[0].s;
for (int i=1; i<intervals.size(); i++)
{
if (intervals[i].f > v.s)
{
ans.push_back(v);
v.f = intervals[i].f;
v.s = intervals[i].s;
}
else
{
v.f = min(v.f, intervals[i].f);
v.s = max(v.s, intervals[i].s);
}
}
ans.push_back(v);
return (ans);
}
# define MOD 1000000007LL
bool is_prime(ll n)
{
if (n == 1) return (false);
if (n == 2) return (true);
if (n % 2 == 0)
return (false);
for (int i=3; i<=(ll)sqrt(n); i += 2)
if (n % i == 0) return (false);
return (true);
}
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
ll get_pairs(int nm, vll& v)
{
ll ans = 0;
for (ll dv=1; dv <= sqrt(nm); dv++)
{
if (nm / dv == dv) continue ;
if (nm % dv == 0)
{
if (v[nm / dv] == -1 or v[dv] == -1) continue ;
if (v[nm / dv] + v[dv] == nm) ans++;
}
}
return (ans);
}
void solve()
{
ll n;
cin >> n;
vector<pair<ll, ll> > v;
for (ll div=2; div<=sqrt(n); div++)
{
if (n % div == 0)
{
v.pb(mp(div, 1));
n /= div;
}
while (n % div == 0)
{
v[v.size() - 1].s++;
n /= div;
}
}
if (n > 1)
v.pb(mp(n, 1));
//cout << v.size() << " " << v[0].f << " " << v[0].s << endl;
if (v.size() == 1 and v[0].s < 6)
cout << "NO" << endl;
else if (v.size() == 1)
{
cout << "YES" << endl;
cout << v[0].f << " " << (ll)pow(v[0].f, 2) << " " << (ll)pow(v[0].f, v[0].s - 3) << endl;
}
else if (v.size() == 2 and v[0].s + v[1].s <= 3)
cout << "NO" << endl;
else if (v.size() == 2)
cout << "YES\n" << v[0].f << " " << (ll)pow(v[0].f, v[0].s - 1) * (ll)pow(v[1].f, v[1].s - 1) << " " << v[1].f << endl;
else
{
cout << "YES" << endl;
ll last_div = 1;
for (int i=2; i<v.size(); i++)
last_div *= (ll)pow(v[i].f, v[i].s);
cout << (ll)pow(v[0].f, v[0].s) << " " << (ll)pow(v[1].f, v[1].s) << " " << last_div << endl;
}
}
int main()
{
int cases = 1;
cin >> cases;
while (cases--)
solve();
return (0);
}
| cpp |
1295 | E | E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
| [
"data structures",
"divide and conquer"
] | # include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
map<int,int>mp;
ll a[200000+10],n;
int pos[200000+10];
ll tree[200000*4+10],dp[200000+10],add[200000*4+10];
void build(int root,int l,int r)
{
if(l==r)
{
tree[root]=dp[l];
return ;
}
int mid=(l+r)>>1;
build(root<<1,l,mid);
build(root<<1|1,mid+1,r);
tree[root]=min(tree[root<<1],tree[root<<1|1]);
}
void pushdown(int root)
{
if(add[root])
{
add[root<<1]+=add[root];
add[root<<1|1]+=add[root];
tree[root<<1]+=add[root];
tree[root<<1|1]+=add[root];
add[root]=0;
}
}
void change(int root,int l,int r,int L,int R,ll val)
{
// cout<<l<<" "<<r<<" "<<L<<" "<<R<<endl;
if(L<=l&&r<=R)
{
tree[root]+=val;
add[root]+=val;
return ;
}
int mid=(l+r)>>1;
pushdown(root);
if(L<=mid)
change(root<<1,l,mid,L,R,val);
if(R>mid)
change(root<<1|1,mid+1,r,L,R,val);
tree[root]=min(tree[root<<1],tree[root<<1|1]);
}
int main ()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
pos[a[i]]=i;
}
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
mp[a[i]]=x;
}
ll mid=1;
ll ans=mp[a[1]];
for(int i=1;i<=n;i++)
{
if(pos[i]>mid)
{
ans+=mp[i];
dp[i]=ans;
}
else
{
ans-=mp[i];
dp[i]=ans;
}
//cout<<dp[i]<<" ";
}
//cout<<endl;
build(1,1,n);
ll ans1=tree[1];
for(mid=2;mid<n;mid++)
{
change(1,1,n,a[mid],n,-mp[a[mid]]);
if(a[mid]>1)
change(1,1,n,1,a[mid]-1,mp[a[mid]]);
ans1=min(ans1,tree[1]);
}
cout<<min(ans1,(ll)mp[a[1]]);
return 0;
}
| cpp |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.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. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
| [
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
while(n--){
long long a;
cin >> a;
long long cnt=a;
if(a<10) cout << a <<endl;
else{
while(a>=10){
long long z=a/10;
a = (a%10) + z;
cnt += z;
}
cout << cnt << endl;
}
}
return 0;
} | cpp |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | [
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
int main () {
int n; cin >> n;
vector<int> a (n);
vector<int> b (n);
for (int& i : a)
cin >> i;
for (int& i : b)
cin >> i;
int aWin = 0, bWin = 0;
for (int i = 0; i < n; i++) {
if (a[i] && !b[i])
++aWin;
if (!a[i] && b[i])
++bWin;
}
if (!aWin) {
cout << -1 << endl;
return 0;
}
++bWin;
cout << (bWin+(aWin-1))/aWin << endl;
}
| cpp |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define long long long
int dp[101][101][101][4],a[102],n;
int ok(int ind,int ev,int od,int prev) {
if(ind==n+1)
return 0;
if(dp[ind][ev][od][prev]!=-1)
return dp[ind][ev][od][prev];
int ans=1e4;
if(a[ind]!=0) {
int ex;
if(prev!=3) {
ex=(prev%2!=a[ind]%2);
} else
ex=0;
ans=min(ans,ok(ind+1,ev,od,a[ind]%2)+ex);
}
else {
int ex;
if(ev>0) {
if(prev!=3) {
ex=(prev%2!=0);
} else
ex=0;
ans=min(ans,ok(ind+1,ev-1,od,0)+ex);
}
if(od>0) {
if(prev!=3) {
ex=(prev%2!=1);
}
else
ex=0;
ans=min(ans,ok(ind+1,ev,od-1,1)+ex);
}
}
return dp[ind][ev][od][prev]=ans;
}
int main() {
cin>>n;
memset(dp,-1,sizeof dp);
int odd=0,even=0;
set<int>st;
for(int i=1;i<=n;i++){
st.insert(i);
}
for(int i=1; i<=n; i++) {
cin>>a[i];
if(a[i]>0)st.erase(st.find(a[i]));
}
for(auto t:st){
if(t%2)odd++;
else even++;
}
cout<<ok(1,even,odd,3)<<"\n";
}
| 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"
] | #pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
long long t, n, a[100001];
int main(){
cin >> t;
for(int i = 1; i <= t; i ++){
cin >> n;
int sum = 0, cnt = 0;
for(int j = 1; j <= n; j ++){
cin >> a[j];
if(a[j] % 2 == 0) sum ++;
else cnt ++;
}
if((sum * 2 + cnt) % 2 != 0) cout << "YES\n";
else{
if(sum > 0 && cnt > 0) cout << "YES\n";
else cout << "NO\n";
}
}
}
| cpp |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | #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;
cin>>n;
map<pair<int,int>,int> m;
pair<int,int> a[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j].first>>a[i][j].second;
if(a[i][j].first!=-1||a[i][j].second!=-1){
a[i][j].first--;
a[i][j].second--;
m[a[i][j]]++;
}
}
}
char ans[n][n];
int z=1;
vector<vector<int>> b(n,vector<int>(n));
for(auto u:m){
if(u.first.first==-1){
continue;
}
queue<pair<int,int>> q;
if(a[u.first.first][u.first.second]!=u.first){
z=0;
}
b[u.first.first][u.first.second]=1;
q.push({u.first.first,u.first.second});
ans[u.first.first][u.first.second]='X';
int r=0;
while(!q.empty()){
r++;
int i=q.front().first;
int j=q.front().second;
q.pop();
if(i&&(a[i-1][j]==a[i][j])&&b[i-1][j]==0){
q.push({i-1,j});
b[i-1][j]=1;
ans[i-1][j]='D';
}
if(i<n-1&&(a[i+1][j]==a[i][j])&&b[i+1][j]==0){
q.push({i+1,j});
b[i+1][j]=1;
ans[i+1][j]='U';
}
if(j&&(a[i][j-1]==a[i][j])&&b[i][j-1]==0){
q.push({i,j-1});
b[i][j-1]=1;
ans[i][j-1]='R';
}
if(j<n-1&&(a[i][j+1]==a[i][j])&&b[i][j+1]==0){
q.push({i,j+1});
b[i][j+1]=1;
ans[i][j+1]='L';
}
}
if(r!=u.second){
z=0;
}
}
for(int k=0;k<n;k++){
for(int l=0;l<n;l++){
if(b[k][l]==0){
queue<pair<int,int>> q;
b[k][l]=1;
q.push({k,l});
int r=0;
while(!q.empty()){
r++;
int i=q.front().first;
int j=q.front().second;
q.pop();
if(i&&b[i-1][j]==0){
q.push({i-1,j});
b[i-1][j]=1;
ans[i-1][j]='D';
if(k==i&&l==j){
ans[k][l]='U';
}
}
if(i<n-1&&b[i+1][j]==0){
q.push({i+1,j});
b[i+1][j]=1;
ans[i+1][j]='U';
if(k==i&&l==j){
ans[k][l]='D';
}
}
if(j&&b[i][j-1]==0){
q.push({i,j-1});
b[i][j-1]=1;
ans[i][j-1]='R';
if(k==i&&l==j){
ans[k][l]='L';
}
}
if(j<n-1&&b[i][j+1]==0){
q.push({i,j+1});
b[i][j+1]=1;
ans[i][j+1]='L';
if(k==i&&l==j){
ans[k][l]='R';
}
}
}
if(r==1){
z=0;
}
}
}
}
if(z){
cout<<"VALID"<<endl;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<ans[i][j];
}
cout<<endl;
}
}
else{
cout<<"INVALID"<<endl;
}
}
#ifndef ONLINE_JUDGE
cout<<"Time : "<<fixed<<setprecision(6)<<((double)(clock()-time_req))/CLOCKS_PER_SEC<<endl;
#endif
} | 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<bits/stdc++.h>
using namespace std;
int
main ()
{
int t=1;
//cin>>t;
while (t--)
{
int n,m;
cin>>n>>m;
if (m%n!= 0)
cout<<-1<<endl;
else if (m==n)
cout<<0<<endl;
else{
int a = m / n, ans = 0;
while (a!=1) {
if (a%2==0) {
a/=2;
ans++;
} else if (a%3==0) {
a/=3;
ans++;
} else {
ans=-1;
break;
}
}
cout<<ans<<endl;
}
}
return 0;
}
| cpp |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | /*
_/ _/ _/_/_/ _/ _/ _/ _/_/_/_/_/
_/ _/ _/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/
_/_/ _/ _/ _/ _/_/_/_/
_/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/
_/ _/ _/_/_/ _/ _/_/_/_/_/ _/_/_/_/_/
*/
#include <bits/stdc++.h>
#define ll long long
#define lc(x) ((x) << 1)
#define rc(x) ((x) << 1 | 1)
#define ru(i, l, r) for (int i = (l); i <= (r); i++)
#define rd(i, r, l) for (int i = (r); i >= (l); i--)
#define mid ((l + r) >> 1)
#define pii pair<int, int>
#define mp make_pair
#define fi first
#define se second
#define sz(s) (int)s.size()
using namespace std;
inline int read() {
int x = 0, w = 0; char ch = getchar();
while(!isdigit(ch)) {w |= ch == '-'; ch = getchar();}
while(isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}
return w ? -x : x;
}
int x[1000005], y[1000005];
int main() {
int n = read();
ru(i, 1, n) {
x[i] = read(), y[i] = read();
}
if(n & 1) {
printf("NO\n");
return 0;
}
ru(i, 1, n / 2) if(x[i] + x[i + n / 2] != x[1] + x[1 + n / 2]) {
printf("NO\n");
return 0;
}
ru(i, 1, n / 2) if(y[i] + y[i + n / 2] != y[1] + y[1 + n / 2]) {
printf("NO\n");
return 0;
}
printf("YES\n");
return 0;
}
| cpp |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define SPEED \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(0)
#define ll long long int
#define minfun(a, b) ((a) < (b) ? (a) : (b))
#define maxfun(a, b) ((a) > (b) ? (a) : (b))
#define MOD 1000000007
#define rep(i, n) for (i = 0; i < n; i++)
#define repp(i, a, n) for (i = a; i < n; i++)
#define repr(i, a, n) for (i = a; i >= n; i--)
#define pb push_back
#define all(x) x.begin(), x.end()
#define mp make_pair
#define fi first
#define se second
ll fact[15];
vector<bool> isprime(100007, true);
map<ll, ll> sfact;
long long int gcd(long long int a, long long int b)
{
while (b)
{
a %= b;
swap(a, b);
}
return a;
}
ll binpowmod(ll a, ll b, ll m)
{
a %= m;
ll res = 1;
while (b > 0)
{
if (b & 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
ll absfun(ll a)
{
if (a < 0)
return -a;
return a;
}
ll binpow(ll a, ll b)
{
ll res = 1;
while (b > 0)
{
if (b & 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
ll modInverse(ll x, ll mod)
{
return binpowmod(x, mod - 2, mod);
}
void pre()
{
fact[0] = 1;
fact[1] = 1;
ll modulo = 998244353;
for (ll i = 2; i < 2005; i++)
{
fact[i] = (fact[i - 1] * i) % modulo;
}
}
const int MAX_SIEVE = 1005;
vector<int> P(MAX_SIEVE, 1);
void sieve()
{
P[1] = 0;
for (ll i = 2; i < MAX_SIEVE; i++)
{
if (P[i] == 1)
{
P[i] = i;
for (int j = 2 * i; j < MAX_SIEVE; j += i)
{
P[j] = i;
}
}
}
}
ll nckmod(ll n, ll k, ll p)
{
return ((fact[n] * modInverse(fact[k], p) % p) * modInverse(fact[n - k], p)) % p;
}
map<ll, ll> factors_prime;
void primeFactors(ll n)
{
while (n % 2 == 0)
{
factors_prime[2]++;
n = n / 2;
}
for (int i = 3; i <= sqrt(n); i = i + 2)
{
while (n % i == 0)
{
factors_prime[i]++;
n = n / i;
}
}
if (n > 1)
factors_prime[n]++;
}
bool isvowel(char x)
{
return x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u';
}
void solve()
{
int n;
cin>>n;
string a,b;
cin>>a>>b;
map<char,vector<int>> m;
for(int i=0;i<n;i++) m[a[i]].pb(i);
vector<pair<int,int>> ans;
vector<int> h;
for(int i=0;i<n;i++)
{
if(b[i]=='?'){
h.pb(i);
continue;
}
if(m[b[i]].size()>0)
{
ans.pb({m[b[i]].back()+1,i+1});
m[b[i]].pop_back();
}
else if(m['?'].size()>0)
{
ans.pb({m['?'].back()+1,i+1});
m['?'].pop_back();
}
}
for(auto it:m)
{
while(h.size()>0&&it.se.size()>0)
{
ans.pb({it.se.back()+1,h.back()+1});
it.se.pop_back();h.pop_back();
}
}
cout<<ans.size()<<'\n';
for(auto it:ans) cout<<it.fi<<' '<<it.se<<'\n';
return;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
#endif
SPEED;
int t = 1;
//cin >> t;
while (t--)
{
solve();
}
} | cpp |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | #include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
using namespace std;
// using namespace chrono;
// using namespace __gnu_pbds;
typedef vector<long long> vi;
typedef pair<int, int> pii;
#define endl "\n"
#define sd(val) scanf("%d", &val)
#define ss(val) scanf("%s", &val)
#define sl(val) scanf("%lld", &val)
#define debug(val) printf("check%d\n", val)
#define all(v) v.begin(), v.end()
#define sai(a, n) sort(a, a + n);
#define sad(a, n) sort(a, a + n, greater<int>());
#define svi(x) sort(x.begin(), x.end());
#define svd(a) sort(a.begin(), a.end(), greater<int>());
#define fi(i, x, n) for (int i = x; i < n; i++)
#define PB push_back
#define MP make_pair
#define FF firstṇ
#define SS second
#define ull unsigned long long
#define int long long
// #define MOD 1000000007
#define MOD 998244353
#define clr(val) memset(val, 0, sizeof(val))
#define what_is(x) cerr << #x << " is " << x << endl;
#define OJ \
freopen("input.txt", "r", stdin); \
freopen("output.txt", "w", stdout);
#define FIO \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
// template <class T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// Function to find a^b % MOD. Time Complexity : O(log b).
int highPowerMod(int a, int b)
{
// a %= MOD;
int res = 1;
while (b > 0)
{
if (b & 1)
res = (res * a);
a = (a * a);
b >>= 1;
}
return res;
}
// Function to find the lcm of a and b. Time Complexity : O(log(min(a, b))).
int lcm(int a, int b)
{
return a / __gcd(a, b) * b;
}
void bfs(int start, vector<vector<int>> &g2, vector<pair<int, bool>> &dp, int m)
{
queue<int> q;
q.push(start);
int cnt = 0;
bool flag = false;
while (!q.empty())
{
cnt = q.front();
if (cnt < m)
flag = true;
q.pop();
dp[cnt].second = flag;
for (const auto &nbr : g2[cnt])
{
if (dp[nbr].first == -1)
{
dp[nbr].first = dp[cnt].first + 1;
q.push(nbr);
}
}
}
}
int compliment(int x, int n)
{
return (x ^ (n - 1));
}
void dfs(int start, vector<vi> &graph, vector<bool> &vis)
{
vis[start] = true;
for (const auto &nbr : graph[start])
{
if (!vis[nbr])
{
dfs(nbr, graph, vis);
}
}
}
pair<int, int> intersection(pair<int, int> a, pair<int, int> b)
{
if (a.first > b.second || b.first > a.second)
return {-1, -1};
return {max(a.first, b.first), min(a.second, b.second)};
}
int cntDigits(int n)
{
string t = to_string(n);
return (int)t.size();
}
int bs_sqrt(int x)
{
int left = 0, right = 2000000123;
while (right > left)
{
int mid = left + (right - left) / 2;
if (mid * mid > x)
right = mid;
else
left = mid + 1;
}
return left - 1;
}
void primeFactors(int n, vi &arr)
{
int t = 1e5 + 7;
fi(i, 1, t)
{
if (i * i > n)
break;
if (n % i == 0)
{
arr.push_back(i);
arr.push_back(n / i);
}
}
}
void SieveOfEratosthenes(int n, vi &primess)
{
bool prime[n + 1];
memset(prime, true, sizeof(prime));
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int p = 2; p <= n; p++)
if (prime[p])
primess.push_back(p);
}
// And of a Range of numbers from a to b.
int andOperator(int a, int b)
{
int shiftcount = 0;
while (a != b and a > 0)
{
shiftcount++;
a = a >> 1;
b = b >> 1;
}
return int64_t(a << shiftcount);
}
void solve(int cake)
{
int n;
cin >> n;
int k;
cin >> k;
// vi arr(n);
// fi(i, 0, n) cin >> arr[i];
vector<int> fact(n + 1, 1);
fi(i, 1, n + 1)
{
fact[i] = fact[i - 1] * i;
fact[i] %= k;
fact[i] = (fact[i] + k) % k;
}
int ans = 0, cnt = n;
fi(i, 1, n + 1)
{
int anss = 0;
anss += fact[i] * fact[n - i + 1];
anss %= k;
anss = (anss + k) % k;
anss *= cnt;
anss %= k;
anss = (anss + k) % k;
ans += anss;
ans %= k;
ans = (ans + k) % k;
cnt--;
// cout << ans << " ";
}
cout << ans << endl;
}
int32_t main()
{
// OJ;
FIO;
int t = 1;
int cake = 1;
// cin >> t;
// vi primes;
// int N = 31622;
// SieveOfEratosthenes(N, primes);
while (t--)
{
solve(cake);
cake++;
}
return 0;
} | cpp |
1304 | F2 | F2. Animal Observation (hard 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 on 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≤m1≤k≤m) – 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",
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
using ll=long long;
static const ll INF=1e14;
ll N,M,K;
ll A[55][20005];
ll dp[55][20005];
ll sum[55][20005];
ll dat[80005];
ll lazy[80005];
ll n;
ll Left(ll x){
if(1<=x-K+1)return x-K+1;else return 1;
}
ll Right(ll x){
if(x<=M-K+1)return x;else return M-K+1;
}
void eval(ll k){
dat[k]+=lazy[k];
if(k<n-1){
lazy[2*k+1]+=lazy[k];
lazy[2*k+2]+=lazy[k];
}lazy[k]=0;
}
void add(ll a,ll b,ll x,ll k,ll l,ll r){
eval(k);
if(a<=l&&r<=b){
lazy[k]+=x;
eval(k);
}else if(a<r&&l<b){
add(a,b,x,2*k+1,l,(l+r)/2);
add(a,b,x,2*k+2,(l+r)/2,r);
dat[k]=max(dat[2*k+1],dat[2*k+2]);
}
}
ll query(ll a,ll b,ll k,ll l,ll r){
eval(k);
if(a<=l&&r<=b)return dat[k];
else if(r<=a||b<=l)
return -INF;
else{
ll val=query(a,b,2*k+1,l,(l+r)/2);
ll var=query(a,b,2*k+2,(l+r)/2,r);
return max(val,var);
}
}
void solve(){
for(ll i=1;i<=N;i++)
for(ll j=1;j<=M;j++)sum[i][j]=A[i][j];
for(ll i=1;i<=N;i++){
for(ll j=2;j<=M;j++)sum[i][j]+=sum[i][j-1];
}
for(ll i=2;i<=N+1;i++){
if(i!=2){ll Sum=0;for(ll j=K;1<=j;j--){
Sum+=A[i-1][j];
if(j<=M-K+1)dp[i-1][j]-=Sum;
}
n=1;
while(n<=M-K+2)n*=2;
for(ll j=0;j<2*n-1;j++){
lazy[j]=0;
}for(ll j=0;j<n;j++)if(1<=j&&j<=M-K+1)dat[n-1+j]=dp[i-1][j];
else dat[n-1+j]=-INF;
for(ll j=n-2;0<=j;j--)dat[j]=max(dat[2*j+1],dat[2*j+2]);
for(ll j=1;j<=M-K+1;j++){
dp[i][j]=query(1,M-K+2,0,0,n)+sum[i][K+j-1]-sum[i][j-1]+sum[i-1][K+j-1]-sum[i-1][j-1];
add(Left(j),1+Right(j),A[i-1][j],0,0,n);
add(Left(j+K),1+Right(j+K),-A[i-1][j+K],0,0,n);
}
}else{
for(ll j=1;j<=M-K+1;j++)dp[i][j]=sum[i][K+j-1]-sum[i][j-1]+sum[i-1][K+j-1]-sum[i-1][j-1];
}
}
ll ans=0;
for(ll j=1;j<=M-K+1;j++)ans=max(ans,dp[N+1][j]);
cout<<ans<<endl;
}
int main(){
cin>>N>>M>>K;
for(ll i=1;i<=N;i++)
for(ll j=1;j<=M;j++)scanf("%lld",&A[i][j]);
solve();
return 0;
}
| 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"
] | #include <bits/stdc++.h>
#define ll long long
#define ld long double
using namespace std;
int main(){
ll t = 1;
cin >> t;
while (t--) {
bool flag = true;
string a, b, c;
cin >> a >> b >> c;
for (int i = 0; i < a.size(); i++) {
if (c[i] == a[i] or c[i] == b[i]) {
continue;
}
else {
flag = false;
break;
}
}
cout << (flag ? "YES\n" : "NO\n");
}
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"
] | #define _USE_MATH_DEFINES
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<utility>
#include<algorithm>
#include<climits>
#include<set>
#include<map>
#include<cmath>
#include<iomanip>
#include<iterator>
#include<queue>
#include<stack>
#include<cctype>
#include<deque>
#include<time.h>
#include<bitset>
#include<random>
#include <functional>
#include<unordered_set>
#include<unordered_map>
#include<random>
#include<numeric>
#include<chrono>
#include<sstream>
#include <valarray>
#include<list>
#include<complex>
#include<cassert>
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#pragma warning(disable : 4996)
#pragma comment(linker, "/STACK:16777216")
#define pb push_back
#define en '\n'
#define forn(i,n) for(int i = 0;i<n;i++)
#define for0(i,n) for(int i = 0;i<n;i++)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define vec vector
#define veci vector<int>
#define pii pair<int,int>
#define pll pair<ll,ll>
#define szof(x) int(x.size())
#define sqr(x) ((x)*(x))
#define debug(x) cerr<<#x<<" = "<<x<<'\n'
using namespace std;
const int INF = 1000000000 + 1e8;
const ll LINF = 2000000000000000000;
template<typename T> void print(vector<T>& a) {
for (int i = 0; i < a.size(); i++)
cout << a[i] << ' ';
cout << en;
}
template <typename T> void input(vector<T>& a) {
for (int i = 0; i < a.size(); i++)
cin >> a[i];
}
const int K = 330;
void solve() {
int n, m;
cin >> n >> m;
vec<int> a(n);
input(a);
vec<int> next(n), count(n);
for (int i = n - 1; i >= 0; i--) {
if (i + a[i] >= n) {
next[i] = n;
count[i] = 1;
}
else if (i / K != (i + a[i]) / K) {
next[i] = i + a[i];
count[i] = 1;
}
else {
next[i] = next[i + a[i]];
count[i] = count[i + a[i]] + 1;
}
}
for0(q, m) {
int type;
cin >> type;
if (type == 0) {
int idx, b;
cin >> idx >> b;
idx--;
a[idx] = b;
for (int i = idx; i / K == idx / K && i >= 0; i--) {
if (i + a[i] >= n) {
next[i] = n;
count[i] = 1;
}
else if (i / K != (i + a[i]) / K) {
next[i] = i + a[i];
count[i] = 1;
}
else {
next[i] = next[i + a[i]];
count[i] = count[i + a[i]] + 1;
}
}
}
if (type == 1) {
int i;
cin >> i;
i--;
int ans = 0;
while (next[i] != n) {
ans += count[i];
i = next[i];
}
while (i + a[i] < n) {
i += a[i];
ans++;
}
ans += count[i];
cout << (i + 1) << " " << ans << en;
}
}
}
int main() {
srand(time(0));
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
int tst = 1;
//cin >> tst;
while (tst--)
solve();
} | cpp |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.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. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | // */((((((//(((#########%%%&&&&&&%%%&&&&%%%%%%%#(/***/(#%%&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// ,//(((//***//((((///((#%%&&&&&&&&&&&&&&&&&&&&%#(////(#%&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// */((##(//*/(((##(((((##%&&&&&&&&@&&&&&%%%###(//***/#%%&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&
// (###%###(((###########%%&&&&&&&%##((####(((((//***////%&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&&%##((
// &&&&&&&%%%%%&&&&&%%%%%%%&&&%###(((((#((((((((//*/((((/***/%%&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&&&&&&&%%%%%%##((/*,,.
// @@@@&&&&&&&&&&&&&&&&&&&&%#((###((#/(#(((((##(#(/((/,//,..*//(#%@@@@@@@@@@@@@@&&&&&&&&&&&&&&&&&%%%%%%%%%%%%####(((((((////*******,,
// @@@@@&&&&&&&&&&&@&&&&&%((##/*,*####(/((((/(/,,*..,*,. ..,,/%&@@@@@@@&&&%%%%%%%%%%%##(((((((((((((((((//***,,,,,,,,,,..,**///*
// @@@@&&&&&&&&&&&&&&&&&#/(**/#(((#(//((/,,,..,. .. . . .....,/#%%%%%%%####(###%%&&%%###((((///(((((((((/*,,,............,*//(/*
// %%%%%%%%%%%%%%%%%%%%/**///*/(((//(*,.... .. .,**/*//*,.....,*,,*//((((((((////((#%&&@@@@&&&&%##(((#####%%%%%#/*,,,,,,,,**,*//(((//
// ((((((((((((((((((#*,*,,,/((,,/*,........,**//(((####(((*,.,,***,,//,/((((///*/(#&&@@@@@@@@@@&%%#####%%&&@@@&%#///****/(((((###((/
// ((((///////////////. .,,**,*,....,,,,*////((#############(/,,*/**/***,(((/////(#%&&@@@@@@@@@@&&%%%%%%&&&@@@&&%#(((((((#########(/*
// ##(((////////*****, ...,.,,,,,***//((((####################(******,,,*/((((///(#%&&@@@@@@@@@&%%%%%%%&&&&&&&%#((((##%%%%&%%%%##((/*
// %##(((((#((((///***... *****//((######%%%%%%%%%%%%%%%#####((/****,,./#%%%%%%%%%&&@@@@@@@@&&&&&&&&&&&%%###(//**/(#%&&&&&&&%%%##(/*
// %##((((####(((((((#/,. ,(//((###%%%%%%%%%%%%%%%%%%%%%%%######/**//*,,%&&&&&&&&@@@@@@@@@&&&&&&&@@@@@&%%#///**,,*/#%&@@@@@@&&%%#(//*
// %#(///////*****/((#(//(###%%%%%%%########((#########%%%%%%#####(//**,&@@@@@@@@@@@@@@@@&&&&&&@@@@@@@@&%#(////**/#%&@@@@@@@&&%%#(/*,
// #((/***,,,,,,,,*/(%(/#%%%%#/*....,**//////****,.. .,*///((#####//**&@@@@@@@@@@@@@&&&&%%%%&@@@@@@@@@&%#((((/((%&&@@@@@@@&&%%#(/*,
// ##(/*,,,,...,,,*/(##(//***,,,****,,,,,*///**,,,,,.,*.,.,,,. .....##//@@@@@@@@@@@@@&&&&&&&&&&@@@@@@@@@&%#(/////(%&&@@@@@@@&&%%#(/*,
// %%##(*,,.,,****///,..**/*....,.....,,.,,,.,,.....,*...,,,. ..,..((,,(#/*&@@@@@@@@@&&&&&&&&&&@@@@@@@@@&%#(**,,*/(#%&&&@@@@&&%%#(*,,
// &%%%#(//********/(#..,,,..,,,.........../#/.........**,......, *##((//(//&@@@@@@@&&&&&&%%%%%&&@@@@@@&%#(/*,...,*((#%%%%&&&&%%#(/**
// %%%%%%%##((/**/(##%* **,.,,. .....,**.#&%%( .....,*,,,,.,.,,, *##(/,*(((&&@@@&&&&&%%###((((##%%&&%%#((/**,,,,**//((((##%%%%%##(((
// &&&&&&%%%%###%%&&&&%*./****,,.....,.. #&&%%%#. .... .......,,.*###(/*.,/##%%%%%%%##((//*****//(###(((///(//////((###(///(#%&&&%%##
// &&%%%%%%##%%&@@@@@&&%*.*****,,,.....,%&&&&&&%%(,... . ......*#(((*//#(((((/((((///***,,...,*//((/////((###########(/****(#%&&&%%#
// %%####(((#%&@@@&&&&%&&%#/*,,,,.....(%%#####((###(,......,,//////(*///((//////////**,,,.. ..,*////*****//((((((((((/*,,.,*/(######
// %##(//*//##%%##(((((/%%#((////****/(/. ..... .*///*/********/////**//(//////////**,.... ..,*////**,....,**////////((//////((##%%
// ((/**,,,*/((/**,**/((//(#(//*****/(((//*.,,.,,*/(((/*.,*******////((((((((((((///**,,.....,,,*/////*,....,,**/////((##(((###%%%%%%
// (//**,,,,,******/((((//*((((//*. *(((///((//*******,. ,***/////(((/(/((((##(((//**,,,,,,,,,***/////******////////((///((##%%%%%%%
// /***,,,.,,,,,**///(/*,,,,/(((((*,, .(##((#(#(((////((/****/////(###((((((((((((///**,,,,,,,****/////////////****/(#######%%%%%%%%%
// ****,,,,,,.....,,***,,,*/((((((((##%%%%%%%%###((((((//////////(%%%%%##((((((((((//****,,******////**,........,,*/(#%%%%%%%%%%%%%%%
// *****,,,,......,,**///(##%%%#(((((###(/**,,,,,*///(((/////***(#%%%%%%%#((////((///**,,,,,,,***////*,. .,,*(##%%%%%%%%%%%%%%%
// ****,,,,.......,*/(##%%%&&&%%%########(///////(((((((((/*,,/(#/####%%%##((////////**,,,,,,,,**/(((/**,.. .,,*/(##%%%%%%%##%%%%%
// /******,,......,*(#%%%%&&&&&&&%##(######((((((((((((/*,.,*/(##,(&((#%%###(////////***,,,,,,,**/####(/*,,....,,*/((####%%%%####%%%%
// ////**,,,...,,*/(#%&&&&&&%%%%%#(*//////*******,,,,. .,**/((##*#&&#/(###((//////////***,,,,,*/(##%%#((//*****//(((####%%%%%%%%%%%%
// ////***,,,.,,*/#%&&&&@&&&%%#(*,..,##(*,. ..,,*//((#/(%&&&(*(//(((((((((((/////****//((######((//***//((((######%%%%%%%%%
// ,,,,,,,....,*/(%&&@@@@&&%#/***,,,.(##(/*,,... ......,,***//(/*#%&&&&&#((((((((((((((/////////((###%%&&%#(*,.,*//((#(((((((((######
// *****,,,.,**(##%&@@@&&%//(///***./%###(/*,........,,,***////*,#%%&&&%&#%&&%#####((((((((((((((((###%&@@&#(*,*/#%%%#((///////(((((#
// ,**,*****/(#%&&&&&@&#/#(/*//*,,.#&%##((//***,,,,,*******///**/%#&%%&%&&&@%%&&%%%#####(((((((((((####&@@&%(*,*/#%%%#((////(((((((((
// ,,,,,,,,,,/(%&&@@%/#((////**,,#&&%%%##((/******///****///////##%%#%&%%%%%%&&&&&&&%%%%######(((######%&&&%(/**(#%%%#((/////((((((((
// ,,,,....,#&&@&(%%%#(/(/*/**,#@@@@&#%%%%##((((((((///(((((((//%%%%%%&&&%#&%%%%&&&&&@@&&&%%#############%%#(/***/(##((/////////////(
// ,,,,,,#@@&@&@&&#(/(/////**(&@@@@@&&&&&&%%%%%%%%############(&&%%%%&&&&%#%#####%&&&%&&@@&&&&%%###########((**,*,/((((((////////////
// ,,,,/@@&&&%&&%((#(/((//*/#&@@@@@@@&&&&&&&&&&&&&%%%%%%%%%%&%%&&%%%%&%&%%###%%##&%%%%&%%&&&&&&&&&%%%###(##((*,,,,*((###((((((((((///
// ,,,#@&@&&%&%%#//#(///(/(%#@@@@@@@@@&&&&&&&&&&&&&&&&&&&&&@@&&&&%%&&&%&#%%%%&&%%%&&&&&@@@&&%%&&%&&&@&#(((#((*,,,,/(##########(((((((
// ,,(%&&@@&&%#%&/*///((((%%%@@@@@@@@@@@@@&&&&&&&&&&&&&@&&&&&(.../%%&&&&#%###&&&%%%%&%%&&&&%&&&&@&%&&&@@&(##(/***/(##################
// .(&%%%%%##(#%/*/(((##(%%#@@@@@@@@@@@@@&&&&@@@&&&&&&&&&&@%#, *%@&%%%##%&&%#%#&&%&&&&&&&%&%%&%%&&&&&%%#(/**/(#%%%%##############
// .%#&&&%%%%%&@(/#(#%#(%&#%@@@@@@@@@@@@@@@@@&&&&&@@@&&@@@%(/, ......,##%#%(%&@##%&&%&&&&&%&&%%#&%%&&%#%%%&&#***/(#%#################
// *%#%%%####%&@(/(%%%##@&#@@@@@@@@@@@@@@@@@@@@@@&&&&@@@@&(#/,.. .,,,,/%(#((%#%((#&#%%%%%#%&%&%&%%%&&%#%%&&&&&@#(####################
// /&(#%%/#%#@&%#%%%%&%&@%%@@@@@@@@@@@@@@@@@@@@&&&&@@@@@&&#(#///*/////####(%###((##(##%&%%#((##&#%&#%&%#%#%&&%(#%%###################
// *&(#%%%##@&%&%%(%&&@@@#&@@@@@@@@@@@@@@@@@@@@&@@@@@@@&&&@%###(%%&&%%%%&%%%%&%##%(/*/(##%#(((%(#%#&%%&%%%#%&&###&%%#################
// ,&&((((%&&%&&#&%@&&&@%#@@@@@@@@@@@@@@@@@@@@@@@@@@@@&@&#(&%#/((###(#(#%%#(/((((((((#%%%%#(,%((#%(###%%%&%(#&@&##%%#################
// .#%(/(#&&&%&%%#%%@@@&(&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%(*#@%##%%%%%%%%&&%##%####(((##(((//##((%((%/%%&&%&##%&&&(%%#################
// *###%%%&&&&@%&&@&&&@##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#((#&&/(((((##(##%##%%(#(#////##%#//*,/##(%(,/%%&%%&&&&&&%%%#################
// #&%%/.%&&&&&%&&&@&@&(&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%((#%&&//((((%###%%##%%%%###(#%(/#**/((%%//#&*/%#%%%&%##%&%#%%################
// @%%%(*@@&%&&%&&&@&@##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&%###&@&(/####&%%#&&%#&&#%#%#*//((#,,*/#%(###(/#%##%%%&&&&%&%%%################
// &&&&%%&&&%&&&&&&@@&#&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&%##%&@&#/((((&%#(&%##&&#%(#/*((#(#,,/#%((##((/#&##%%%%%#%%%%%&&%%%############
// %&%%&&@%%&%%&@&%@@#(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%%##%&&&&%%&&%&%%#&#(#%&#%#%(///(/#/*(#/(#&&(,/%%(/(%%%&%##%&%%&#%%############
// &&%&&&&%&&%@@&&@&&##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&%%##&@&&&(/(((&##(&%##%&%&%%%##(((#(,(((#/(**/#%%%#%%%#%%##%&&%&%%%############
// (&&%%&&&&%%@&&&@&&%#@@@@@@&@@@@@@@@@@@@@@@@@&&&&&@&%%#%&@&%&%####%#%%&%##%&&&%%&&&&%//#**(*(%##/,#/(%((#%&%&#(#%&&%&%%############
// %%%%&&%#&&&&%&@@&&%#&@@@@@@@@@@@@@@@@@@@@@@&&&&&&@&%%%%&@&%%%(#######%#//(#####(#%%%%##(##(///*.#(((%#(#%%#&%##%&&%%&#############
// %%%%%%%&&&%&%@@&%&%(&@@@@@@&@&@@@@@@@@@&&@&&&&&&@@&%%%&&@&&&#*//(&###&&%#%&&%%%%#%%&&%#/##(##/,(#((/%%##%&#%&#((%&&%%%############
// %(%%%%%%%%&&@@@&%%#(&@@@@@@@@@@@@@@@@@@@@@@&&&&&&&&%%%&&&&&&%//(#%###&%###&%########%%(*#%*/**((%(#(#&###%%%&#((#%&%&%############
// %%##%%%&%%@&&@&&%%#(&@@@@@@@&&@@@@@@@&&&&&&&&&&&&&&%%&@&&%&&&/((##(##%#((#%%###%#%&&%%/,/#%(/*//#(/##&%#(#%#%%##%&&&%%%###########
// %%#%&&&&%%&&&&&&&%#(@@@@@@&@@&@@@@@@@&&@@&&&&&&&%&&%%&&&@&&&%*/(%%%%#&%##%&%%%#&%#%%#(#.*/##.(#/*(/((%%#(#%%%%###%%%%%%%%%########
// ###%&%&%#%@@&@&%&%#(&&@&@@@@&&@&&@@@@@&&&&&&&&&&&&&%%&%&@&%&#**/%&%#/&%###&#(#(%#%%%(## ./(((/**((#%%%(//(%%%%%%&&&&%&%%#########
// #((%&%&&&&&@@@%%&%#(&&&@@@&&&&&@@@@@&&&@@&&&&&&&&&@&%&&@@&%%/#(/##(#/&%###&(/(#&%%%&&%%. ./(#(///((((#(//(%%%%###%%&&%%%%%#######
// %#*&@%&&%#%@@@%&&%##@@@@@@@@&@@&@@@@@@&&&&&&&&&&&&&@%&%&&%&(,*/((#(((#(//(#(((#%%%&%#/#... *###/**(##((%#(((%#@#(#%%#&%&%%%######(
// &%#&@&%%##%&&@&&%%#(&@@@@@@&&@@&@@@@@&@@&&&&&&&&&&&&&&%&%%&#*#%%%%##(&%#(#%%%%&&&@@@&%%. *#,,*///#(((##(((%#%%/(#&#%&&&%##((((((
// %%#@&%%%&&&&&%%%%#((&&&&&&&&&&@@@@@@&&&@&&&&&&&&&&&&&&@&&&&#*((((#(##%(**/(((((####%%%%* .*/#*,*//%((/#%#((#%#%(/(##(%#%%###(((((
// @&%@%%&&&&&%#&%@%#((&&&&@&&&&&&@@@@@@@@@&&&&&&&&&&&&&%&@&@&(,*/(#&%&%&#((#%%###%%%%#((#(/ ,*/*(/,//%#/(/&#(((%#%##(#%#%(#%%###((((
// @&&@&#&##%%##%%%##/#&&@@@@&&&@&&@&@&&&@@&&&&&&&&&&&%&&%@%&&###(/(#(#(&%((#%#(((%(#%&%%#/( .*,*,(#/**(*/(%#(((#%#(///##%###########
// %#%@%#%#&@&%%%%%##((&&&&@&&&&&&&@@@@&&&&&&&&&&&&&&&&&&&&%&&/*////%(%#&%(##%###(&((%###%(%/ *%/,,,*//#//((##(((#%%(((#(#(###%######
// (/#&%#&%&%&%%%%%#(((&&&&&&&&&&@@@&&&@@@@&&&&&&&&&&%&%%&&%&&//(((/&(#/&%##%&####&##%&%%#/(# *((,*(#(((//(((***/##(##%###(##(######
// ((%&%%&%&#%&&&%%#((#&&&@&&&&&&&&&@&&&@@&&&&&&&&&&&&%%%%&%&%#&&&%#%((/%%###&####&#%&@&%#((#/ .*/(/((/(((###(///#((*///(((%@((%%###
// (#%&##&%&%&%%%%%##(#&&&&&&&&&&&&@&&&&&&&&&&&&&&&&&&&%%%&@&#///(#(##((%%(((%%###%#%#(#####((*. .,,.,*,.*/*/,((**/((#///(%%%&&%%&&%#
// (#%%%%&%#/##%%%%%#/#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%%%%&%%//######(*##(/(#(/(/((#%##(#((##/,.,..,,////((#(%%####%&&&&&&@@&@&&%&%#
// ##%&%&%%##%#(#%%##/(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%%&%&%%%#%%%%#(#((/(/*/(#(((#(#%%#//*/((/***/((#####%%%%%&&&&&&%%%%%%%&%%&&%&&%
// ##%&%&%&%#%%/####(//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%&&&&%#%/*##(/*(/**/###%%(#(#**///(((((((,/*,**///((##%%%%%%%%&&%%%%%%%%%%&%%&%
// ##%%%&%#(/%%/(&%#(//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%##((*%%#(//(*/*##(#%###*,,*,*#*/#(((./#,**///(((((##%%&%%%%%%%%%%%%%%%%%%&
// ##&%&&##((%%//#%((*/%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%#((%#/####(%(/**%(#&((%***..(**/#((#*,*.*/((#####%%%%%%%%%####%%%#%%%%%%%%
// ##%&&%%%(%%%#####(/(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%(((((/##(//#(/((%#(%(/##,. *,,*/#(((,,*/,*/////(((##%%%&&&&&%%###((////(%%
// (#%%&&@#/%(%#####(*(%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%%#(((((*%%#(/((**,#((%#(((*,**,//##((#**,*%%*,*/*///***,***//((//*/(%######(
// (#%%&###(#(&%(%##(*/%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&######(/(/(%%#(//(((##/#%, , /(#(*/////,***///////////******,,,,,*(#####(#(
// #%%&&&%%#%#(&#%##(*(%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%##%%%%#/(##((#(((/#((##(#/,.,**/**/(/*,, *///((((((((///********(########((
// #%&&%&&##((#&####(/#%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%#(/#%%(/#///#(/((*//* ..*,,,/#*,,./(((((((((((/////*****/(####(((((((
// #&%&&%#(#((%@#(##//%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%&&%%%#(/(((((#(/,#(//##((/,.**.,/#/,,,/((((#(((((((/////*/*/(####(((((((((
// #&%@%#%%%(((@%(#(//#%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%%%%((((/(%(/(#//(#*///**..*((***(((((##(((((((//////*/((##(((((((((((
// #&&&%%(%#(/#&%(%(*/(#%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%((((/#(((#///(#(((**,*/(..,(((#####(((((((////*/(((####((((((((((
// #&%%&%(%(%#&%%((/*/##%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%&&&&&%%%%###(###/*/#(((#**** ,(***/(####(((((((/////**/#####(((((((((((((
// #%&&##(%%#%%#%(((*//(#%%&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%########(((/(((/*/%#(#(//((/((( ,. /((#####((((((////**/(#########((((((((((
// #%%%&&&&((%#(%((/**/(##%%%%&&&&&&&&&&&&@&&&&&%%%%%%##%%%%%%%%%%%%%#####(#(###(//(**,/( /#######(((((///****(#########%%%######(((
// %&%#&&%%##%##&#//**/((##%%%%%%&&&&&&&&&&&&&@@&@&@&&&&&&&&&&&&&&&&&&%%%%%(#(/(#///(.,..,(######((((((///***(#########%%%%%%%%%#####
/*----------------------------------------------------------They call him ARIF-----------------------------------------------------*/
#pragma GCC optimize ("Ofast")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
typedef vector<ll> vll;
typedef vector<pair<ll,ll>> vpll;
typedef map<pll,ll> mpll;
typedef map<ll,ll> mll;
typedef map<char,ll> mcll;
typedef map<pair<char,ll>,ll> mpcll;
typedef map<pair<char,char>,ll> mpccl;
typedef pair<char,char> pcc;
typedef pair<string,string> pss;
typedef map<string,ll> msll;
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define max4(a,b,c,d) max(d,max3(a,b,c))
#define min4(a,b,c,d) min(d,min3(a,b,c))
#define all(x) x.begin(),x.end()
#define endl "\n"
const ll M=1e9+7;
// tu hamesha ceil aur floor me 1.0* daalna bhulta hai
// ll x=max4(a,b,c,d); save value in some variables & dont
// ll y=min4(a,b,c,d); print it directly it will give an error
// if(find(nums.begin()+fp+1,nums.begin()+ep,temp)!=nums.begin()+ep)
ll gcd(ll a,ll b)
{
return b == 0 ? a : gcd(b, a % b);
}
ll power(ll a,ll n)
{
if(n==0) return 1;
ll subprob=power(a,n/2);
ll subprobq=subprob*subprob;
if(n&1) return a*subprobq;
return subprobq;
}
ll lcm3(ll x,ll y,ll z)
{
ll ans=(x*y*z)*gcd(x,gcd(y,z));
ans/=gcd(x,y);ans/=gcd(y,z);ans/=gcd(x,z);
return ans;
}
mll primefact(ll n)
{
mll f;
while(n%2==0)
{
f[2]++;
n/=2;
}
for(ll i=3;i*i<=n;i+=2)
{
while(n%i==0)
{
f[i]++;
n/=i;
}
}
if(n>2) f[n]++;
return f;
}
void addk(vll &v,ll q=0)
{
// in case of seg fault try to make n+1 size vect
if(q==0) cin>>q;
ll l,r,k;
while(q--)
{
cin>>l>>r>>k;
v[l]+=k;
// may be seg fault due to r+1.
// so make vect of n+1
v[r+1]-=k;
}
for(int i=1;i<v.size();i++)//v.size()=n+1
{
v[i]+=v[i-1];
}
}
ll sumofdigits(ll n)
{
ll ans=0;
while(n>0)
{
ans+=n%10;
n/=10;
}
return ans;
}
void solve()
{
ll a,b,c,n;cin>>a>>b>>c>>n;
ll x=a+b+c;
if((a+b+c+n)%3) cout<<"NO\n";
else
{
ll mn=min3(a,b,c);
ll mx=max3(a,b,c);
ll mid=x-mn-mx;
if(n<((mx-mn)+(mx-mid)))
{
cout<<"NO\n";
return;
}
n-=(mx-mn);n-=(mx-mid);
if(n%3==0) cout<<"YES\n";
else cout<<"NO\n";
}
}
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
ll t;
t=1;
cin>>t;
while(t--){
solve();
}
} | cpp |
1288 | F | F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB
| [
"constructive algorithms",
"flows"
] | #include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 9;
//Works for both directed, undirected and with negative cost too
//doesn't work for negative cycles
//for undirected edges just make the directed flag false
//Complexity: O(min(E^2 *V log V, E logV * flow))
using T = long long;
const T inf = 1LL << 61;
struct MCMF {
struct edge {
int u, v;
T cap, cost; int id;
edge(int _u, int _v, T _cap, T _cost, int _id){
u = _u; v = _v; cap = _cap; cost = _cost; id = _id;
}
};
int n, s, t, mxid; T flow, cost;
vector<vector<int>> g; vector<edge> e;
vector<T> d, potential, flow_through;
vector<int> par; bool neg;
MCMF() {}
MCMF(int _n) { // 0-based indexing
n = _n + 10;
g.assign(n, vector<int> ());
neg = false; mxid = 0;
}
void add_edge(int u, int v, T cap, T cost, int id = -1, bool directed = true) {
if(cost < 0) neg = true;
g[u].push_back(e.size());
e.push_back(edge(u, v, cap, cost, id));
g[v].push_back(e.size());
e.push_back(edge(v, u, 0, -cost, -1));
mxid = max(mxid, id);
if(!directed) add_edge(v, u, cap, cost, -1, true);
}
bool dijkstra() {
par.assign(n, -1);
d.assign(n, inf);
priority_queue<pair<T, T>, vector<pair<T, T>>, greater<pair<T, T>> > q;
d[s] = 0;
q.push(pair<T, T>(0, s));
while (!q.empty()) {
int u = q.top().second;
T nw = q.top().first;
q.pop();
if(nw != d[u]) continue;
for (int i = 0; i < (int)g[u].size(); i++) {
int id = g[u][i];
int v = e[id].v; T cap = e[id].cap;
T w = e[id].cost + potential[u] - potential[v];
if (d[u] + w < d[v] && cap > 0) {
d[v] = d[u] + w;
par[v] = id;
q.push(pair<T, T>(d[v], v));
}
}
}
for (int i = 0; i < n; i++) { // update potential
if(d[i] < inf) potential[i] += d[i];
}
return d[t] != inf;
}
T send_flow(int v, T cur) {
if(par[v] == -1) return cur;
int id = par[v];
int u = e[id].u; T w = e[id].cost;
T f = send_flow(u, min(cur, e[id].cap));
cost += f * w;
e[id].cap -= f;
e[id^1].cap += f;
return f;
}
//returns {maxflow, mincost}
pair<T, T> solve(int _s, int _t, T goal = inf) {
s = _s; t = _t;
flow = 0, cost = 0;
potential.assign(n, 0);
if (neg) {
// run Bellman-Ford to find starting potential
d.assign(n, inf);
for (int i = 0, relax = true; i < n && relax; i++) {
for (int u = 0; u < n; u++) {
for (int k = 0; k < (int)g[u].size(); k++) {
int id = g[u][k];
int v = e[id].v; T cap = e[id].cap, w = e[id].cost;
if (d[v] > d[u] + w && cap > 0) {
d[v] = d[u] + w;
relax = true;
}
}
}
}
for(int i = 0; i < n; i++) if(d[i] < inf) potential[i] = d[i];
}
while (flow < goal && dijkstra()) flow += send_flow(t, goal - flow);
flow_through.assign(mxid + 10, 0);
for (int u = 0; u < n; u++) {
for (auto v: g[u]) {
if (e[v].id >= 0) flow_through[e[v].id] = e[v ^ 1].cap;
}
}
return make_pair(flow, cost);
}
};
struct LR_Flow{
MCMF F;
int n, s, t;
T target;
LR_Flow() {}
LR_Flow(int _n) {
n = _n + 10; s = n - 2, t = n - 1; target = 0;
F = MCMF(n);
}
void add_edge(int u, int v, T l, T r, T cost = 0, int id = -1) {
assert(0 <= l && l <= r);
if (l != 0) {
F.add_edge(s, v, l, cost);
F.add_edge(u, t, l, 0);
target += l;
}
F.add_edge(u, v, r - l, cost, id);
}
pair<T, T> solve(int _s, int _t) {
F.add_edge(_t, _s, inf, 0);
auto ans = F.solve(s, t);
if (ans.first < target) return {-1, -1}; //not feasible
return ans;
}
};
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n1, n2, m, r, b; cin >> n1 >> n2 >> m >> r >> b;
string s1, s2; cin >> s1 >> s2;
int s = n1 + n2 + 10, t = s + 1;
LR_Flow F(t);
for (int i = 0; i < m; i++) {
int u, v; cin >> u >> v; --u; --v;
F.add_edge(u, v + n1, 0, 1, r, i);
F.add_edge(v + n1, u, 0, 1, b, i + m);
}
for (int i = 0; i < n1; i++) {
if (s1[i] == 'R') F.add_edge(s, i, 1, inf, 0);
else if (s1[i] == 'B') F.add_edge(i, t, 1, inf, 0);
else F.add_edge(s, i, 0, inf, 0), F.add_edge(i, t, 0, inf, 0);
}
for (int i = 0; i < n2; i++) {
if (s2[i] == 'B') F.add_edge(s, i + n1, 1, inf, 0);
else if (s2[i] == 'R') F.add_edge(i + n1, t, 1, inf, 0);
else F.add_edge(s, i + n1, 0, inf, 0), F.add_edge(i + n1, t, 0, inf, 0);
}
auto ans = F.solve(s, t);
if (ans.first == -1) cout << -1 << '\n';
else {
cout << ans.second << '\n';
for (int i = 0; i < m; i++) {
if (F.F.flow_through[i]) cout << "R";
else if (F.F.flow_through[i + m]) cout << "B";
else cout << "U";
}
cout << '\n';
}
return 0;
} | cpp |
1301 | B | B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33. | [
"binary search",
"greedy",
"ternary search"
] | //I'm practice
#include <bits/stdc++.h>
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define odrse tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define odrmse tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update>
using namespace __gnu_pbds;*/
using namespace std;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef pair<long long,long long> pll;
typedef pair<long long, int> pli;
typedef pair<int, long long> pil;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef vector<vector<vector<ll>>> vvvl;
typedef vector<int> vi;
typedef vector<pair<long long, long long>> vll;
typedef vector<pli> vli;
typedef vector<pil> vil;
typedef vector<string> vs;
#define prqu priority_queue
typedef priority_queue<ll> pql;
typedef priority_queue<int> pqi;
typedef priority_queue<pll> pqll;
typedef priority_queue<pli> pqli;
typedef priority_queue<pil> pqil;
typedef map<ll,int> mli;
typedef map<ll,ll> mll;
typedef map<int,int> mii;
typedef map<int,ll> mil;
typedef map<pll,ll> mlll;
#define V vector
#define ff(i,a,b) for(ll i=a;i<=b;i++)
#define rep(i,a,b) for(ll i=a;i>=b;i--)
#define ffd(i,a,b,x) for(ll i=a;i<=b;i+=x)
#define repd(i,a,b,x) for(ll i=a;i>=b;i-=x)
#define fff(i,v) for(auto i : v)
#define ffi(i,v) for(ll i = 0; i <= v.sz-1; i++)
#define repi(i,v) for(ll i = v.sz-1; i >= 0; i--)
#define ffp(x1,x2,v) for(auto [x1,x2] : v)
#define ffit(it,v) for(auto it = v.begin() ; it != v.end(); it++)
#define all(x) x.begin(),x.end()
#define en cout<<endl;
#define eren cerr<<endl;
#define pb push_back
#define pf push_front
#define ppf pop_front
#define eb emplace_back
#define ft front()
#define bk back()
#define clr clear()
#define ppb pop_back
#define sqr(x) (x)*(x)
#define gcd(a,b) __gcd(a,b)
#define sz size()
#define rsz resize
#define reset(x,val) memset((x),(val),sizeof(x))
#define mtset multiset
#define cid(x) x = " "+x;
#define sstr substr
#define ins insert
#define ers erase
#define emp empty()
#define maxelm max_element
#define minelm min_element
#define ctn continue
#define rtn return
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define yesno(c) (c? "YES":"NO")
#define outyesno(c) { cout<<yesno(c)<<endl; rtn; }
#define nortn {cout<<"NO"<<endl; rtn; }
#define yesrtn { cout<<"YES"<<endl; rtn; }
#define valrtn(x) { cout<<x<<endl; rtn; }
#define x first
#define y second
#define ffmask(mask,n) for(ll mask = 1; mask <= (1<<n)-1; mask++)
//#define ffbit1(x,mask) for(x = mask;x > 0; x -= x & (-x))
#define lastbit1(x) x & (-x)
#define getbit(n,x) (1<<x)&n
#define cntbit1(x) __builtin_popcountll(x)
#define cntbit0(x) __builtin_clzll(x)
#define lwb lower_bound
#define upb upper_bound
#define tcT template <class T
#define tcTU tcT, class U
template<typename T1, typename T2> bool maxi(T1& a, T2 b) {if (a < b) {a = b; return 1;} else return 0;}
template<typename T1, typename T2> bool mini(T1& a, T2 b) {if (a > b) {a = b; return 1;} else return 0;}
template<typename T1, typename T2> bool minswap(T1& a, T2 b) {if (a > b) {swap(a,b); return 1;} else return 0;}
template<typename T1, typename T2> bool maxswap(T1& a, T2 b) {if (a < b) {swap(a,b); return 1;} else return 0;}
template <class T> using mprqu = priority_queue<T, vector<T>, greater<T>>;
#define debug(X) {auto _X=(X); cerr << "L" << __LINE__ << ": " << #X << " = " << (_X) << endl;}
#define err(x) cerr << #x << " = " << (x) << '\n'
#define arrerr(it1, it2) for(auto it = it1; it != it2; it++) cerr << *it << " "; eren;
#define dot cerr<<".";
inline void inp(){} template<typename F, typename... R> inline void inp(F &f,R&... r){cin>>f;inp(r...);}
inline void out(){} template<typename F, typename... R> inline void out(F f,R... r){cout<<f;out(r...);}
const ll cr = 2e5 + 7;
const ll mod = 1e9 + 7;
const ll MOD = 998244353;
const ll inf = 1e18 + 7;
const ll base = 311;
const ldb pi = (ldb)3.1415926535897932384626433832795;
const string Yes = "Yes";
const string No = "No";
const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
bool mem2;
#define fastIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define FILE(s) freopen(s".INP","r",stdin);freopen(s".OUT","w",stdout);
#define GetExpert int32_t main()
#define y1 tlapluvnth
#define y2 zz16102007
#define left nthnevaluvtlap
#define right tlapstillluvnt
ll rdr(ll l, ll r) {
return l + rand() % (r - l + 1);
}
ll rdd(ll ss) {
vector<ll> digit;
ff(i, 1, ss) {
ll k = rand() % 10;
//cerr << k << endl;
digit.push_back(k);
}
ll ans = 0, power = 1;
for(ll x : digit) {
ans += x * power;
power *= 10;
}
return ans;
}
//MAIN PROGRAM----
//----------------
ll n, a[500007];
void resetsolve(){
}
void init(){
cin >> n;
ff(i, 1, n) cin >> a[i];
}
ll calc(ll x) {
ll ans = 0;
ff(i, 1, n - 1) {
ll x1 = a[i];
ll x2 = a[i + 1];
if (x1 == -1) x1 = x;
if (x2 == -1) x2 = x;
maxi(ans, abs(x1 - x2));
}
return ans;
}
void solveinsolve(){
ll liml = inf, limr = -inf;
ff(i, 1, n) {
if (a[i] == -1) {
if (i > 1 && a[i - 1] != -1) mini(liml, a[i - 1]), maxi(limr, a[i - 1]);
if (i < n && a[i + 1] != -1) mini(liml, a[i + 1]), maxi(limr, a[i + 1]);
}
}
if (liml == inf) valrtn("0 0");
ll ans1 = calc((limr + liml) / 2);
ll ans2 = calc((limr + liml + 1) / 2);
if (ans1 > ans2) cout << ans2 << " " << (limr + liml + 1) / 2 << endl;
else cout << ans1 << " " << (limr + liml) / 2 << endl;
}
void print(){
}
void solve(){
//remember reset and init
resetsolve();
init();
solveinsolve();
print();
}
void generation() {
fclose(stdin);
ofstream g;
g.open("FILE.INP");
g << rdr(1, 100) << " " << rdr(1, 100);
g.close();
freopen("FILE.INP","r",stdin);
}
void pre_process(){
}
bool mem1;
GetExpert{
pre_process();
fastIO;
srand(time(NULL));
#ifndef ONLINE_JUDGE
FILE("FILE");
#endif
ll t = 1; cin>>t; ff(____,1,t) {
//cout<<"Case "<<____<<":"<<endl;
//cerr<<"Case "<<____<<endl;
solve();
//generation();
//eren;
}
//------------
//eren;
//cerr << "Memory Cost: " << abs(&mem1-&mem2)/1024./1024. << " MB" << endl;
//cerr << "Time Cost: " << clock()*1000./CLOCKS_PER_SEC << " MS" << endl;
}
| cpp |
1295 | F | F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212. | [
"combinatorics",
"dp",
"probabilities"
] | // LUOGU_RID: 93070834
#include<bits/stdc++.h>
#define LL long long
#define mod 998244353
using namespace std;
int n,m,t=0,t1=0;
LL res,ans=1;
int l[52],r[52],id[102],val[102],len[102];
LL inv[52];
LL f[102][52];
inline LL Pow(int a,int b)
{
if(!b)return 1;
LL c=Pow(a,b>>1);
c=(c*c)%mod;
if(b&1)c=(c*a)%mod;
return c;
}
inline bool cmp(int x,int y)
{
return val[x]<val[y];
}
inline void init()
{
inv[1]=1;
for(int i=2;i<=n;++i)inv[i]=(-inv[mod%i]*(mod/i))%mod;
}
int main()
{
scanf("%d",&n),init(),f[0][0]=1;
for(int i=1;i<=n;++i)scanf("%d%d",&l[i],&r[i]),++t,val[id[t]=t]=-r[i],++t,val[id[t]=t]=-l[i]+1,(ans*=r[i]-l[i]+1)%=mod;
sort(id+1,id+t+1,cmp);
for(int i=1;i<=t;++i)
{
if(i==1 || val[id[i]]^val[id[i-1]])len[t1]=val[id[i]]-val[id[i-1]],++t1;
(id[i]&1? l[(id[i]+1)>>1]:r[id[i]>>1])=t1;
}
for(int i=1;i<t1;++i)
{
for(int j=1;j<=n;++j)
{
res=1;
for(int k=j-1;~k && l[k+1]<=i && i<r[k+1];--k)(f[i][j]+=f[i-1][k]*((((res*=(len[i]+(j-k)-1))%=mod)*=inv[j-k])%=mod))%=mod;
}
for(int j=0;j<=n;++j)(f[i][j]+=f[i-1][j])%=mod;
}
return 0&printf("%lld",(((Pow(ans,mod-2)*f[t1-1][n])%mod)+mod)%mod);
} | 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"
] | #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=1e5+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 h[N],e[M],ne[M],idx;
PII vec[N];
void add(int a,int b) {
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void solve() {
n=read();
memset(h,-1,sizeof h);
for(int i=1;i<n;i++) {
int a=read(),b=read();
vec[i]={a,b};
add(a,b),add(b,a);
}
map<int,map<int,int> > st;
int last=1;
bool flag=false;
for(int i=1;i<=n;i++) {
int cnt=0;
for(int j=h[i];j!=-1;j=ne[j]) cnt++;
if(cnt>=3) {
flag=true;
for(int j=h[i];j!=-1;j=ne[j]) {
int k=e[j];
st[i][k]=st[k][i]=last++;
}
break;
}
}
if(!flag) for(int i=0;i<=n-2;i++) printf("%d\n",i);
else {
for(int i=1;i<n;i++) {
if(st[vec[i].fi][vec[i].se]!=0) printf("%d\n",st[vec[i].fi][vec[i].se]-1);
else printf("%d\n",last-1),last++;
}
}
}
int main() {
// init();
// stin();
// scanf("%d",&T);
T=1;
while(T--) solve();
return 0;
}
| cpp |
1310 | E | E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function ff of multiset aa as the multiset of number of occurences of every number, that is present in aa.E.g., f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}.Let's define fk(a)fk(a), as applying ff to array aa kk times: fk(a)=f(fk−1(a)),f0(a)=afk(a)=f(fk−1(a)),f0(a)=a. E.g., f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}.You are given integers n,kn,k and you are asked how many different values the function fk(a)fk(a) can have, where aa is arbitrary non-empty array with numbers of size no more than nn. Print the answer modulo 998244353998244353.InputThe first and only line of input consists of two integers n,kn,k (1≤n,k≤20201≤n,k≤2020).OutputPrint one number — the number of different values of function fk(a)fk(a) on all possible non-empty arrays with no more than nn elements modulo 998244353998244353.ExamplesInputCopy3 1
OutputCopy6
InputCopy5 6
OutputCopy1
InputCopy10 1
OutputCopy138
InputCopy10 2
OutputCopy33
| [
"dp"
] | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
const int N=3000+5;
const int Mod=998244353;
int n,k,ans,f[N];
vector<int> vc,t,nw;
void solve1()
{ f[0]=1;
for(int i=1;i<=n;i++)
for(int j=i;j<=n;j++)f[j]=(f[j]+f[j-i])%Mod;
for(int i=1;i<=n;i++)ans=(ans+f[i])%Mod;
}
void solve2()
{ f[0]=1;
for(int i=1;(i*(i+1)>>1)<=n;i++)
for(int j=i*(i+1)>>1;j<=n;j++)
f[j]=(f[j]+f[j-(i*(i+1)>>1)])%Mod;
for(int i=1;i<=n;i++)ans=(ans+f[i])%Mod;
}
bool check()
{ t=vc;
for(int j=1;j<k;j++,nw.clear())
{ int s=0;
sort(t.begin(),t.end()),reverse(t.begin(),t.end());
for(int i=0;i<(int)t.size();i++)s+=t[i]*(i+1);
if(s>n)return 0;
if(j+3<k&&s>23)return 0;
for(int i=0;i<(int)t.size();i++)
for(int j=0;j<t[i];j++)nw.push_back(i+1);
t=nw;
}
return 1;
}
bool dfs(int x)
{ if(!check())return 0;
ans++;
for(int i=x;;i++)
{ vc.push_back(i);
int res=dfs(i);
vc.pop_back();
if(!res)return 1;
}
return 1;
}
int main()
{ scanf("%d%d",&n,&k);
if(k==1)solve1();
else if(k==2)solve2();
else dfs(1),ans--;
printf("%d\n",ans);
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<iostream>
# include<vector>
# include<algorithm>
# include<iomanip>
#include<cmath>
# include<map>
using namespace std;
int main() {
int t; cin >> t;
while (t--) {
int n; cin >> n;
vector<int>v(n);
map<int, int>mp;
int e = n;
for (int i = 0; i < n; i++) cin >> v[i];
sort(v.begin(), v.end());
int l = 0,ans=INT_MIN;
for (int r = 0; r < n; r++) {
mp[v[r]]++;
if (mp[v[r]] == 1) {
ans = max(ans, r - l + 1);
}
else {
l++;
}
}
cout << ans << endl;
}
} | cpp |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define MOD 1000000007
using namespace std;
using namespace __gnu_pbds;
template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
//priority_queue <int, vector<int>, greater<int>> q;
long long factorial[250005];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
long long n, m, sol = 0;
cin >> n >> m;
factorial[0] = 1;
factorial[1] = 1;
for(int i = 2; i <= n; i++){
factorial[i] = (factorial[i - 1] * i) % m;
}
for(int i = 1; i <= n; i++){
long long nr = ((n - i + 1) * (n - i + 1)) % m;
nr = (nr * factorial[i]) % m;
nr = (nr * factorial[n - i] % m);
sol = (sol + nr) % m;
}
cout << sol;
return 0;
}
| cpp |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define se second
const int N = 2e5 + 10;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<vector<int>> a(n, vector<int> (m));
vector<int> r(N, -1), c(N, -1);
for(int i = 0; i < n; i++ ){
for(int j = 0; j < m; j++ ){
cin >> a[i][j];
a[i][j]--;
r[i * m + j] = i;
c[i * m + j] = j;
}
}
ll ans = 0;
for(int i = 0; i < m; i++ ){
vector<int> cnt(n);
for(int j = 0; j < n; j++ ){
if(c[a[j][i]] == i){
cnt[(j - r[a[j][i]] + n) % n]++;
}
}
int res = n;
for(int j = 0; j < n; j++ ){
res = min(res, j + (n - cnt[j]));
}
ans += res;
}
cout << ans << "\n";
return 0;
} | 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: 101258509
#include<bits/stdc++.h>
#include<unordered_map>
#include<algorithm>
using namespace std;
#define ll long long
#define pii pair<ll,ll>
//struct Edge {
// int from, to, nex;
//}edge[400010];
//int tot, head[200010];
//void add(int u, int v) {
// edge[++tot] = { u,v,head[u] };
// head[u] = tot;
//}
const ll mod = 998244353;
ll qpow(ll x, ll y) {
ll res = 1;
while (y) {
if (y & 1) res = (x * res) % mod;
x = x * x % mod;
y >>= 1;
}
return res;
}
ll n,m;
ll gcd(ll a, ll b) {
return b ? gcd(b, a % b) : a;
}
void solve()
{
cin >> n >> m;
vector<ll> a(n + 1);
vector<set<int>> s(n + 1);
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
s[v].insert(u);
}
map<set<int>, ll> mp;
for (int i = 1; i <= n; i++) {
if(!s[i].empty()) mp[s[i]] += a[i];
}
ll ans = 0;
for (auto i : mp) {
if (ans) ans = gcd(ans, i.second);
else ans = i.second;
}
cout << ans << '\n';
}
signed main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int tt = 1;
cin >> tt;
while (tt--) solve();
return 0;
}
/*
*/ | cpp |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | #include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
signed main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
for(int i=1;i<=t;i++)
{
int n,m;
cin>>n>>m;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
int mini=min(sum,m);
cout<<mini<<endl;
}
} | 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>
#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 = 1010101;
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; }
pair<bool, vll> solve(ll u, ll v) {
if(u > v) return {false, {}};
if(u == 0 and v == 0) return {true, {}};
if(u == v) return {true, {u}};
ll d = v - u;
if(d & 1) return {false, {}};
ll h = d / 2;
if(h & u) return {true, {u,d/2,d/2}};
return {true, {h | u, h}};
}
int main() {
Code By Sumfi
cout.precision(12);
ll tc = 1;
//in(tc);
rep(i,1,tc+1) {
ll u,v;
in(u,v);
auto [ok, res] = solve(u,v);
if(ok) {
print(sz(res));
printv(res);
} else pneg1
}
return 0;
} | 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>
using namespace std;
#pragma optimization_level 3
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
// Datatypes Begin
#define int long long int
#define double long double
#define longlong long long
#define __int64 int
// Datatypes End
// Constants Begin
#define PI 3.14159265358979323846264338327950288419716939937510l
const string PI_string = "314159265358979323846264338327950288419716939937510";
const int MAX_N = 1e5 + 5, MOD = 1e9 + 7, INF = 1e9, EPS = 1e-9;
// Constants End
// Definitions Begin
void fast_io() {
ios::sync_with_stdio(false);
ios_base::sync_with_stdio(0);
cin.tie(0);
cin.tie(NULL);
cout.tie(0);
cout.tie(NULL);
}
#define all(a) a.begin(), a.end()
void fix_prec(int prec) {
cout << fixed << setprecision(prec);
}
// Definitions End
// Custom Structs and Classes Begin
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
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);
}
};
// Custom Structs and Classes End
// Functions Begin
void open_file(string input, string output) {
freopen(input.c_str(), "r", stdin);
freopen(output.c_str(), "w", stdout);
}
void usaco(string filename) {
freopen((filename + ".in").c_str(), "r", stdin);
freopen((filename + ".out").c_str(), "w", stdout);
}
template <typename T> T gcd(T a, T b) {
return (b ? __gcd(a, b) : a);
}
template <typename T> T lcm(T a, T b) {
return (a * (b / gcd(a, b)));
}
unordered_map<int, int, custom_hash> factorials;
int factorial(int n) {
if (n < 0)
return 0;
if (n <= 1)
return 1;
if (factorials.find(n) != factorials.end())
return factorials[n];
return factorials[n] = (n * factorial(n - 1));
}
int nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
int nPr(int n, int r) {
return factorial(n) / factorial(n - r);
}
template<typename T> T power(T a, T n, T mod) {
T power = a, result = 1;
while (n) {
if (n & 1) {
result = (result * power) % mod;
}
power = (power * power) % mod;
n >>= 1;
}
return result;
}
template<typename T> bool witness(T a, T n) {
int t, u, i;
std::int64_t prev, curr;
u = n / 2;
t = 1;
while (!(u & 1)) {
u /= 2;
++t;
}
prev = power(a, u, n);
for (i = 1; i <= t; ++i) {
curr = (prev * prev) % n;
if ((curr == 1) && (prev != 1) && (prev != n - 1)) {
return true;
}
prev = curr;
}
if (curr != 1) {
return true;
}
return false;
}
template<typename T> bool is_prime(T number) {
if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3))
return false;
if (number < 1373653) {
for (int k = 1; 36 * k * k - 12 * k < number; ++k)
if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0))
return false;
return true;
}
if (number < 9080191) {
if (witness(std::int64_t(31), number))
return false;
if (witness(std::int64_t(73), number))
return false;
return true;
}
if (witness(std::int64_t(2), number))
return false;
if (witness(std::int64_t(7), number))
return false;
if (witness(std::int64_t(61), number))
return false;
return true;
}
// GEO
template <typename T>
inline T PointDistanceHorVer(T x1, T y1, T x2, T y2) {
return abs(x1 - x2) + abs(y1 - y2);
}
template <typename T > inline T PointDistanceDiagonally(T x1, T y1, T x2, T y2) {
return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
template <typename T > inline T PointDistanceMinimum(T x1, T y1, T x2, T y2) {
T tmp1 = abs(x1 - x2), tmp2 = abs(y1 - y2), tmp3 = abs(tmp1 - tmp2), tmp4 = min(tmp1, tmp2);
return tmp3 + tmp4;
}
template <typename T> inline T PointDistance3D(T x1, T y1, T z1, T x2, T y2, T z2) {
return sqrt(square(x2 - x1) + square(y2 - y1) + square(z2 - z1));
}
template <typename T> inline T Cube(T a) {
return a * a * a;
}
template <typename T> inline T RectengularPrism(T a, T b, T c) {
return a * b * c;
}
template <typename T> inline T Pyramid(T base, T height) {
return (1 / 3) * base * height;
}
template <typename T> inline T Ellipsoid(T r1, T r2, T r3) {
return (4 / 3) * PI * r1 * r2 * r3;
}
template <typename T> inline T IrregualarPrism(T base, T height) {
return base * height;
}
template <typename T> inline T Sphere(T radius) {
return (4 / 3) * PI * radius * radius * radius;
}
template <typename T> inline T CylinderB(T base, T height) {
return base * height;
}
template <typename T> inline T CylinderR(T radius, T height) {
return PI * radius * radius * height;
}
template <typename T> inline T Cone(T radius, T base, T height) {
return (1 / 3) * PI * radius * radius * height;
}
// Functions End
void solve(int tt = 0) {
int n;
cin >> n;
vector<int> a(n);
for (int &i : a)
cin >> i;
auto isGood = [](vector<int> &b) -> bool
{
map<int, int> mp;
for (int i = 0, n = b.size(); i < n; i++)
{
if (mp.count(i - b[i]))
return false;
mp[i - b[i]]++;
}
return true;
};
// while (!isGood(a)) {
// random_shuffle(all(a));
// }
sort(all(a), greater<int>());
if (!isGood(a))
swap(a[0], a[1]);
for (int i : a)
cout << i << " ";
cout << endl;
// cout << isGood(a) << endl;
}
#define test_cases
int32_t main(void) {
fast_io();
#ifdef test_cases
int tc = 1;
cin >> tc;
for (int t = 1; t <= tc; t++)
solve(t);
#else
solve();
#endif
}
/*
By Thamognya Kodi
▓▓▓▓▓▓ ▓▓▓▓▓▓
▓▓ ░░▓▓▓▓ ▓▓▓▓▓▓
▓▓▓▓▓▓▓▓░░ ░░▓▓░░░░▓▓▓▓ ▓▓
▒▒▓▓░░ ▓▓░░░░░░░░░░░░▓▓░░░░▓▓
▒▒░░ ░░░░░░░░░░░░░░░░▓▓▓▓▒▒
▓▓░░░░░░░░░░░░░░░░░░░░▓▓░░▓▓
██████████ ▒▒▓▓░░░░▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░▓▓
██████ ██████ ▓▓▓▓▓▓▓▓▓▓▓▓▒▒ ▒▒▒▒▒▒▓▓▓▓
████ ████████▓▓▓▓▓▓▓▓▓▓▒▒ ▒▒ ▒▒▓▓
████ ██████░░ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
██████████░░ ░░░░░░██░░░░░░████
██████████ ██░░░░░░░░░░▒▒░░░░░░▒▒██
██████████ ██░░░░░░░░░░░░░░░░░░░░██
██████████ ████░░░░░░░░░░░░░░░░██
██████ ████░░░░░░▒▒▒▒░░██
████ ██▓▓██░░░░░░░░██
████ ████████▓▓▓▓████████
██ ████▓▓▓▓▓▓████████▓▓██████
██ ████▓▓▓▓▓▓▓▓▓▓██████▓▓██▓▓▓▓██
▓▓████▓▓▓▓██▓▓▓▓▓▓▓▓██▓▓██▓▓██▓▓▓▓
████████▓▓▓▓██▓▓▓▓▓▓▓▓██▓▓██▓▓██▓▓██
██▓▓▓▓▓▓▓▓████████████████▓▓██████▓▓██
██▓▓██▓▓▓▓████▒▒░░░░ ░░░░▓▓██▒▒██▓▓██
██▓▓▓▓██████████▒▒ ░░░░ ▓▓██▒▒██▓▓████
██▓▓▓▓▓▓████ ██▒▒░░ ░░░░▓▓██▒▒▒▒██████
██▓▓▓▓▓▓▓▓██ ██▒▒░░░░ ▓▓██▒▒▒▒██▓▓██
██▓▓▓▓▓▓▓▓██ ██▒▒░░░░░░░░░░░░▓▓██▒▒██▓▓██
██▓▓▓▓████▓▓██ ████▒▒░░ ░░░░▓▓██▒▒██▓▓▓▓██
██▓▓██░░░░██ ████████▓▓▓▓▓▓▓▓████████▓▓▓▓████
██░░░░████ ████████████████████████▓▓████░░████
██░░░░░░░░██ ██▒▒░░░░░░░░░░░░░░░░████▓▓██░░░░░░░░██
██░░░░░░░░░░██ ██░░ ░░░░░░░░░░░░░░░░████░░░░░░░░██
██░░░░░░░░░░██ ██▒▒░░░░ ░░░░██░░░░░░████░░░░░░██
██░░░░░░░░██ ██▒▒ ▒▒▒▒▒▒░░░░░░██░░░░░░░░████████
████████ ██████ ▒▒▒▒████░░████░░░░██
██ ████▒▒██ ████▒▒▒▒▒▒▒▒░░██
██░░░░░░ ▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░░░██
██░░░░░░▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██
██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██
██░░░░░░░░▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██
██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██
██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒░░░░██
██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██
██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██
██░░▒▒▒▒▒▒██ ████████████
████████████ ████████
██▓▓▓▓████ ██▓▓▓▓██
████████████ ██▓▓██████████
██▓▓▓▓▓▓▓▓██ ██▓▓▓▓▓▓▓▓▓▓▓▓████
██▓▓▓▓▓▓▓▓▓▓██ ██████▓▓▓▓▓▓░░░░░░██
██▓▓░░░░░░░░████ ██████████████
██████████████
*/ | 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>
using namespace std;
int BLK_SIZE;
bool check(int i, int j) {
return (i / BLK_SIZE) == (j / BLK_SIZE);
}
int main() {
// freopen("input.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin>>n>>m;
int a[n];
for(int i=0; i<n; i++) cin>>a[i];
int jumps[n], next[n], last[n];
int begin_block[n]; // beginning of the block in which i belongs
BLK_SIZE = sqrt(n);
for(int i=n-1; i>=0; i--) {
if((i + a[i]) >= n) {
jumps[i] = 1;
next[i] = -1;
last[i] = i;
} else if(check(i, i+a[i])) {
jumps[i] = jumps[i+a[i]] + 1;
next[i] = next[i+a[i]];
last[i] = last[i+a[i]];
} else {
jumps[i] = 1;
next[i] = i + a[i];
last[i] = i;
}
}
begin_block[0] = 0;
for(int i=1; i<n; i++) {
if(check(i, i-1)) {
begin_block[i] = begin_block[i-1];
} else {
begin_block[i] = i;
}
}
while(m--) {
int type;
cin>>type;
if(type == 0) {
//update
int idx, val;
cin>>idx>>val;
idx-=1;
int beg = begin_block[idx];
a[idx] = val;
while(idx >= beg) {
if((idx + a[idx]) >= n) {
jumps[idx] = 1;
next[idx] = -1;
last[idx] = idx;
} else if(check(idx, idx+a[idx])) {
jumps[idx] = jumps[idx+a[idx]] + 1;
next[idx] = next[idx+a[idx]];
last[idx] = last[idx+a[idx]];
} else {
jumps[idx] = 1;
next[idx] = idx + a[idx];
last[idx] = idx;
}
idx--;
}
} else {
// query
int idx;
cin>>idx;
idx-=1;
int numJumps = 0;
int lastVisited = idx;
while(idx != -1) {
numJumps += jumps[idx];
lastVisited = last[idx];
idx = next[idx];
}
cout<<lastVisited+1<<" "<<numJumps<<"\n";
}
}
return 0;
}
| cpp |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | #include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define int ll
#define fr first
#define se second
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define For(i,a,b) for(int i = a; i <= b; ++i)
#define Rep(i,a,b) for(int i = a; i >= b; --i)
using namespace std;
typedef pair<int,int> pii;
#ifdef OVAL
const ll N = 2e3+10;
#else
const ll N = 2e5+10;
#endif
#define db ll
#define EPS 0
#define PI acos(-1)
// 判断a的符号 返回值为 -1,0,1
inline int sign(db a) { return a < -EPS ? -1 : a > EPS; }
// 比较 a 和 b 的大小(带eps) a<b -1; a==b 0; a>b 1
inline int cmp(db a, db b) { return sign(a - b); }
// 点/向量
struct P{
db x, y;
int id;
P(db _x = 0, db _y = 0) : x(_x), y(_y) {}
P operator+(P p) const{ return P(x + p.x, y + p.y); }
P operator-(P p) const{ return P(x - p.x, y - p.y); }
P operator*(db a) { return P(x * a, y * a); }
P operator/(db a) { return P(x / a, y / a); }
// 两点重叠(带eps)
bool operator==(P p) const { return cmp(x, p.x) == 0 && cmp(y, p.y) == 0; }
bool operator!=(P p)const{return !((*this)==p);}
db abs2() { return x * x + y * y; }
double abs() { return sqrt(abs2()); }
double disTo(P p) { return (*this - p).abs(); }
double disTo2(P p) { return (*this - p).abs2(); }
void read(){cin >> x >> y;}
};
db dotmul(P p1, P p2, P p3) {
return (p2.x - p1.x) * (p3.x - p1.x) + (p2.y - p1.y) * (p3.y - p1.y);
}
db xmul(P p1, P p2, P p3) {
return (p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y);
}
int xmulOP(P p1, P p2, P p3) { return sign(xmul(p1, p2, p3)); }
bool isInside(db a, db b, db m){
if (a > b) swap(a, b);
return cmp(a, m) <= 0 && cmp(m, b) <= 0;
}
bool isInside(P a, P b, P m){
return isInside(a.x, b.x, m.x) && isInside(a.y, b.y, m.y);
}
bool isonSeg(P a, P b, P m){
return xmulOP(a, b, m) == 0 && isInside(a, b, m);
}
struct Line{
P a, b;
void read(){a.read(), b.read();}
double len(){return a.disTo(b);}
};
bool isonSeg(Line l, P m){
return xmulOP(l.a, l.b, m) == 0 && isInside(l.a, l.b, m);
}
Line ls[10];
bool chk(Line x, P p)
{
ll d1 = p.disTo2(x.a), d2 = p.disTo2(x.b);
if(d1>d2)swap(d1, d2);
if(16*d1 >= d2)return true;
return false;
}
bool check(Line l1, Line l2, Line l3)
{
if(l1.a!=l2.a){
if(l1.a==l2.b)swap(l2.a, l2.b);
else if(l1.b==l2.a)swap(l1.a, l1.b);
else if(l1.b==l2.b){
swap(l1.a, l1.b);
swap(l2.a, l2.b);
}
else return false;
}
double angle = 1.0*dotmul(l1.a, l1.b, l2.b);
if(angle<0)return false;
if(isonSeg(l1, l3.b) && isonSeg(l2, l3.a))swap(l3.a, l3.b);
if(!(isonSeg(l1, l3.a) && isonSeg(l2, l3.b)))return false;
return chk(l1, l3.a)&&chk(l2, l3.b);
}
void solve()
{
vector<int> v;
For(i,1,3){
ls[i].read();
v.push_back(i);
}
do{
if(check(ls[v[0]], ls[v[1]], ls[v[2]])){
// for(auto c:v)cout << c << " ";
cout << "YES\n";
return ;
}
}while(next_permutation(v.begin(), v.end()));
cout << "NO\n";
}
signed main()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
int tt = 1;
cin >> tt;
For(tc,1,tt){
solve();
}
return 0;
}
/*
3 53 25
100 25
20 5
40 10
*/
| 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<iostream>
#include <bits/stdc++.h>
#include <ext/numeric>
using namespace std;
//using L = __int128;
#include<ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define nd "\n"
#define all(x) (x).begin(), (x).end()
#define lol cout <<"i am here"<<nd;
#define py cout <<"YES"<<nd;
#define pp cout <<"ppppppppppppppppp"<<nd;
#define pn cout <<"NO"<<nd;
#define popcount(x) __builtin_popcount(x)
#define clz(n) __builtin_clz(n)//31 -x
const double PI = acos(-1.0);
double EPS = 1e-9;
#define print2(x , y) cout <<x<<' '<<y<<nd;
#define print3(x , y , z) cout <<x<<' '<<y<<' '<<z<<nd;
#define watch(x) cout << (#x) << " = " << x << nd;
const ll N = 2e5+500 , LOG = 22 , inf = 1e8 , SQ= 550 , mod= 1e9+7;//998244353;
template<class container> void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;}
//template <class Type1 , class Type2>
ll fp(ll a , ll p){ if(!p) return 1; ll v = fp(a , p/2); v*=v;return p & 1 ? v*a : v; }
template <typename T> using ordered_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;
ll mul (ll a, ll b){
return ( ( a % mod ) * ( b % mod ) ) % mod;
}
ll add (ll a , ll b) {
return (a + b + mod) % mod;
}
template< typename T > using min_heap = priority_queue <T , vector <T > , greater < T > > ;
vector < vector <pair <int , int > > > g;
vector <int > ans(N);
ll dfs(int node , int par , int mx , int prv){
ll ret = 0;
ret+= ((int)g[node].size() > mx);
ll c = 1;
for (auto &ch : g[node]){
if (par == ch.first) continue;
c+=(prv == c); if (c > mx) c = 1;
ans[ch.second] = c;
ret+= dfs(ch.first , node , mx , c);
c++; if (c > mx) c = 1;
}
return ret;
}
void hi(int tc) {
ll n , k; cin >>n >> k;
g = vector < vector <pair <int , int > > > (n+5);
for (int u , v ,i = 1; i < n; ++i){
cin >> u >> v;
g[u].emplace_back(v , i);
g[v].emplace_back(u , i);
}
ll st = 1 , end = n-1;
while(st <= end){
ll mid = st + end >> 1;
ll ret = dfs(1 , 1 , mid ,-1);
if (ret <= k) end = mid-1;
else st = mid +1;
}
dfs(1 , 1 , st , -1);
cout << st <<nd;
for (int i = 1; i < n; ++i)
cout << ans[i] <<" ";
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
int tt = 1 , tc = 0;
//cin >> tt;
while(tt--) hi(++tc);
return 0;
}
/*
* greedy
* if k == 0 thw answer is equal to the maximum degree of a vertex
* cuz if it was less/ then there at least two edges out of me with the same color
*/
| cpp |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | #include<bits/stdc++.h>
#define ll long long
#define endl "\n"
#define fast ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
ll q,n,x,d,y,z,r;
int main()
{
fast
cin>>q;
while(q--)
{
cin>>n>>d;
if(n>=d)
{
cout<<"YES"<<endl;
}
else
{
ll mi=1e13;
x=1e7;
while(x>0)
{
ll ans=x+ceil(((double )d)/(x+1));
mi=min(mi,ans);
x--;
}
if(mi<=n)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}}
}
return 0;
}
| cpp |
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day. | [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
bool dfs(int x, vector<vector<int>> &roads, vector<bool> &visited, int parent)
{
if (visited[x]) return true;
visited[x] = true;
bool v = false;
for (int child : roads[x])
{
if (child == parent) continue;
if (dfs(child, roads, visited, x)) v = true;
}
return v;
}
// long loooooooooooooooong;
void solve(ll kkkk, ll tttt)
{
int n; cin >> n; int w; cin >> w;
vector<int> arr(n); for (int i = 0; i < n; i++) cin >> arr[i];
for (int i = 1; i < n; i++)
{
if (arr[i] == 0) continue;
int c = min(arr[i] * i, w) / i;
arr[0] += c;
w-=c * i;
}
cout << arr[0] << endl;
}
void fast() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); }
int main()
{
fast();
// int t = 0, i = 0;
int t; cin >> t;
for (int i = 1; i <= t; i++)
solve(t, i);
return 0;
}
| cpp |
1284 | D | D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist. | [
"binary search",
"data structures",
"hashing",
"sortings"
] | #include <bits/stdc++.h>
#include "stdio.h"
using namespace std;
#define SZ(s) ((int)s.size())
#define all(x) (x).begin(), (x).end()
#define lla(x) (x).rbegin(), (x).rend()
#define bpc(x) __builtin_popcount(x)
#define bpcll(x) __builtin_popcountll(x)
#define MP make_pair
#define endl '\n'
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
typedef long long ll;
const int MOD = 1e9 + 7;
const int N = 1e6 + 3e2;
#define pll pair<ll, ll>
vector<pll> get_hash(vector<int> a, vector<int> b){
int n = (int)a.size();
vector<int> pl(n), pr(n);
iota(all(pl), 0);
iota(all(pr), 0);
sort(all(pl), [&](int i, int j){
return a[i] > a[j];
});
sort(all(pr), [&](int i, int j){
return b[i] < b[j];
});
vector<ll> val{100003, 1000000007};
vector<ll> mod{998244353, 1000678447};
vector<vector<ll>> pw(2, vector<ll>(n));
pw[0][0] = pw[1][0] = 1;
for (int i = 1; i < n; i++){
pw[0][i] = pw[0][i - 1] * val[0] % mod[0];
pw[1][i] = pw[1][i - 1] * val[1] % mod[1];
}
function<void(pll&, pll)> add = [&](pll &x, pll y){
(x.first += y.first) %= mod[0];
(x.second += y.second) %= mod[1];
};
vector<pll> lf(n), rg(n);
for (int i = 0; i < n; i++){
int j = pl[i];
lf[i] = MP(pw[0][j], pw[1][j]);
if (i > 0) add(lf[i], lf[i - 1]);
}
for (int i = 0; i < n; i++){
int j = pr[i];
rg[i] = MP(pw[0][j], pw[1][j]);
if (i > 0) add(rg[i], rg[i - 1]);
}
vector<pll> res(n);
for (int i = 0; i < n; i++){
int l, r;
l = 0, r = n - 1;
int ind1 = -1;
while (l <= r){
int m = (l + r) >> 1;
if (a[pl[m]] > b[i]){
ind1 = m;
l = m + 1;
} else {
r = m - 1;
}
}
if (ind1 != -1) add(res[i], lf[ind1]);
l = 0, r = n - 1;
int ind2 = -1;
while (l <= r){
int m = (l + r) >> 1;
if (b[pr[m]] < a[i]){
ind2 = m;
l = m + 1;
} else {
r = m - 1;
}
}
if (ind2 != -1) add(res[i], rg[ind2]);
}
return res;
}
void solve(){
int n;
cin >> n;
vector<int> a(n), b(n), c(n), d(n);
for (int i = 0; i < n; i++){
cin >> a[i] >> b[i] >> c[i] >> d[i];
}
vector<pll> h1 = get_hash(a, b);
vector<pll> h2 = get_hash(c, d);
// for (int i = 0; i < n; i++){
// cout << h1[i].first << ' ' << h1[i].second << ' ';
// cout << h2[i].first << ' ' << h2[i].second << ' ';
// cout << endl;
// }
cout << (h1 == h2 ? "YES" : "NO") << endl;
}
int main(){
clock_t startTime = clock();
ios_base::sync_with_stdio(false);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
#endif
int test_cases = 1;
// cin >> test_cases;
for (int test = 1; test <= test_cases; test++){
solve();
}
cerr << "Time: " << int((double) (clock() - startTime) / CLOCKS_PER_SEC * 1000) << " ms" << endl;
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"
] | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
typedef long long ll;
using namespace std;
template<typename T>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<<3)+(x<<1)+(c-'0');
x*=f;
}
template<typename T>void write(T x){
if(x<0)putchar('-'),x=-x;
if(x/10)write(x/10),x%=10;
putchar(x+'0');
}
const ll mod=1000000007;
ll mo(ll a){
return a>=mod?a-mod:a;
}
const int maxn=5005;
int num[maxn][maxn],slm[maxn],srm[maxn],s[maxn];
int main(){
int n,m;
read(n),read(m);
for(int i=1;i<=n;++i) read(s[i]),++srm[s[i]];
for(int i=1;i<=m;++i){
int f,h; read(f),read(h);
++num[f][h];
}
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
num[i][j]+=num[i][j-1];
ll anssum=1,ansnum=0;
for(int i=0;i<=n;++i){
if(i)++slm[s[i]],--srm[s[i]];
ll testsum=1,testnum=0;int sl,sr;
if(i){
sl=slm[s[i]],sr=srm[s[i]];
sr=num[s[i]][sr]-(sr>=sl);
sl=num[s[i]][sl]-num[s[i]][sl-1];
if(!sl)continue;
if(sr)testsum=testsum*sl*sr%mod,testnum+=2;
else testsum=testsum*sl%mod,testnum++;
}
for(int j=1;j<=n;++j){
if(j==s[i])continue;
sl=slm[j],sr=srm[j];
sr=num[j][sr],sl=num[j][sl];
if(!sl&&!sr)continue;
if(!sl||!sr)testsum=testsum*(sl+sr)%mod,testnum++;
else if(sr==1&&sl==1) testsum=testsum*2%mod,testnum++;
else testsum=testsum*(sl*sr-min(sl,sr))%mod,testnum+=2;
}
if(testnum>ansnum) ansnum=testnum,anssum=testsum;
else if(testnum==ansnum) anssum=mo(anssum+testsum)%mod;
}
write(ansnum),putchar(' ');
if(ansnum)write(anssum),putchar('\n'); else puts("1");
return 0;
} | cpp |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | /***********
MK-1311
***********/
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define nl '\n'
#ifdef LOCAL
#include "debug.h"
#else
#define debug(...)
#endif
/*
*/
#define int long long
void solve() {
int n, it;
cin >> n >> it;
vector<tuple<int, int, int>> a(n);
for(int i = 0; i < n; i++) {
auto &[t, l, h] = a[i];
cin >> t >> l >> h;
}
vector<vector<int>> b(n, vector<int>(2, false));
b[0][0] = max(get<1>(a[0]), it - get<0>(a[0]));
b[0][1] = min(get<2>(a[0]), it + get<0>(a[0]));
for(int i = 1; i < n; i++) {
auto [t1, l1, h1] = a[i - 1];
auto [t2, l2, h2] = a[i];
int timeBetween = t2 - t1;
b[i][0] = max(b[i - 1][0], l1) - timeBetween;
b[i][1] = min(b[i - 1][1], h1) + timeBetween;
}
bool ok = true;
for(int i = 0; i < n; i++) {
auto [t, l, h] = a[i];
if(l > b[i][1] || h < b[i][0]) {
ok = false;
}
}
cout << (ok ? "YES" : "NO") << endl;
}
int32_t main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int tt = 1;
cin >> tt;
for(int i = 0; i < tt; i++) {
solve();
}
cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;
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"
] | // going to keep 1000th special
// only one doubt -> how the total edges are being calculated
#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
struct dsu {
public:
dsu() : _n(0) {}
dsu(int n) : _n(n), parent_or_size(n, -1) {}
int merge(int a, int b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
int x = leader(a), y = leader(b);
if (x == y) return x;
if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y);
parent_or_size[x] += parent_or_size[y];
parent_or_size[y] = x;
return x;
}
bool same(int a, int b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
return leader(a) == leader(b);
}
int leader(int a) {
assert(0 <= a && a < _n);
if (parent_or_size[a] < 0) return a;
return parent_or_size[a] = leader(parent_or_size[a]);
}
int size(int a) {
assert(0 <= a && a < _n);
return -parent_or_size[leader(a)];
}
std::vector<std::vector<int>> groups() {
std::vector<int> leader_buf(_n), group_size(_n);
for (int i = 0; i < _n; i++) {
leader_buf[i] = leader(i);
group_size[leader_buf[i]]++;
}
std::vector<std::vector<int>> result(_n);
for (int i = 0; i < _n; i++) {
result[i].reserve(group_size[i]);
}
for (int i = 0; i < _n; i++) {
result[leader_buf[i]].push_back(i);
}
result.erase(
std::remove_if(result.begin(), result.end(),
[&](const std::vector<int>& v) { return v.empty(); }),
result.end());
return result;
}
private:
int _n;
// root node: -1 * component size
// otherwise: parent
std::vector<int> parent_or_size;
};
void solve(){
ll n;cin>>n;
ll N = (1<<18);
vector <ll> cnt(N,0);
vector <bool> done(N,false);
ll ans = 0;
for(ll i=0;i<n;i++){
ll t;cin>>t;
cnt[t]++;
ans -= t;
}
cnt[0]++;
dsu D(N);
for(ll mask=N-1;mask>=0;mask--){
for(ll subMask = mask;subMask > 0;subMask = (subMask - 1) & mask){
ll u = subMask;
ll v = (subMask ^ mask);
if(cnt[u] > 0 && cnt[v] > 0){
if(D.leader(u) != D.leader(v)){
D.merge(u,v);
ll mul = cnt[u];
if(done[u]){
mul = 1;
}
if(done[v] == false){
mul += cnt[v] - 1;
}
ans += mask * mul;
done[u] = true;
done[v] = true;
}
}
}
}
cout << ans << "\n" ;
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(NULL);
ll t = 1;
// cin>>t;
while(t--){
solve();
}
return 0;
} | 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"
] | #include <bits/stdc++.h>
//#pragma GCC target("sse,sse2,avx2")
//#pragma GCC optimize("unroll-loops,O3")
#define rep(i,l,r) for (int i = l; i < r; i++)
#define repr(i,r,l) for (int i = r; i >= l; i--)
#define X first
#define Y second
#define all(x) (x).begin() , (x).end()
#define pb push_back
#define endl '\n'
#define debug(x) cerr << #x << " : " << x << endl;
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
constexpr int N = 1e6+10,mod = 1e9+7,maxm = 1026;
constexpr ll inf = 1e18+10;
inline int mkay(int a,int b){
if (a+b >= mod) return a+b-mod;
if (a+b < 0) return a+b+mod;
return a+b;
}
inline int poww(int a,int k){
if (k < 0) return 0;
int z = 1;
while (k){
if (k&1) z = 1ll*z*a%mod;
a = 1ll*a*a%mod;
k >>= 1;
}
return z;
}
int n,k,t;
int m;
int p[N];
bool vis[N];
vector<pll> adj[N];
bool good[N];
int lst[maxm];
vector<int> a;
char ask(int i){
lst[i] = a.size();
char c;
a.pb(i);
cout << "? " << i << endl;
cin >> c;
return c;
}
void rst(){
cout << "R\n";
a.clear();
memset(lst,128,sizeof lst);
}
void dfs(int v){
int l = 1 + (v-1)*k,r = v*k;
rep(i,l,r+1){
char c = ask(i);
if (c == 'Y') good[i] = 0;
}
while (p[v] < (int)adj[v].size()){
int u = adj[v][p[v]].X;
int i = adj[v][p[v]].Y;
p[v]++;
if (vis[i]) continue;
rst();
rep(j,l,r+1){
if (good[j])
ask(j);
}
vis[i] = 1;
dfs(u);
}
}
int main(){
//ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
memset(lst,128,sizeof lst);
cin >> n >> k;
rep(i,1,n+1){
char c = ask(i);
if (c == 'N') good[i] = 1;
}
rst();
if (k == 1){
rep(i,1,n+1){
if (!good[i]) continue;
rep(j,i+1,n+1){
if (!good[j]) continue;
char s = ask(i);
s = ask(j);
if (s == 'Y') good[j] = 0;
rst();
}
}
int ans = 0;
rep(i,1,n+1) ans += good[i];
cout << "! " << ans << endl;
return 0;
}
k /= 2;
t = n/k;
rep(i,1,t+1) rep(j,i+2,t+1){
adj[i].pb({j,m});
adj[j].pb({i,m});
m++;
}
dfs(1);
int ans = 0;
rep(i,1,n+1) ans += good[i];
cout << "! " << ans << endl;
}
| 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;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define fi first
#define se second
#define n_l '\n'
using ll = long long;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
using ld = long double;
using ull = uint64_t;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
using vvl = vector<vector<ll>>;
#define gg(...) [](const auto&...x){ char c='='; cerr<<#__VA_ARGS__<<" "; ((cerr<<exchange(c,',')<<" "<<x),...); cerr<<endl; }(__VA_ARGS__);
int nxt() { int x; cin >> x; return x; }
// const uint64_t mod = (1ULL << 61) - 1;
// const uint64_t seed = chrono::system_clock::now().time_since_epoch().count();
// const uint64_t base = mt19937_64(seed)() % (mod / 3) + (mod / 3);
// #include <atcoder/dsu>
// #include <atcoder/lazysegtree>
// #include <atcoder/segtree>
// #include <atcoder/modint>
// using namespace atcoder;
// using mint = modint998244353;
const ll INF = 1e18;
ll tests;
ll n, m, p;
// mint fac[333333];
void solve() {
cin >> n >> m >> p;
ll av, bv;
rep(i, 0, n) {
ll x = nxt();
if (x % p != 0) {
av = i;
}
}
rep(i, 0, m) {
ll x = nxt();
if (x % p != 0) {
bv = i;
}
}
cout << av+bv << endl;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
// cin >> tests;
// while(tests--) {
solve();
// }
}
| cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.