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 |
---|---|---|---|---|---|
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000
| [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | /*████████████████████████████████████████████████████████████████████████████████████
██████████████████████████████████████████████████████████████████████████████████████
███████████████████████████▓▓▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓▓╬╬╬╬╬╬▓███████████████████████
███████████████████████████▓███████▓▓╬╬╬╬╬╬╬╬╬╬╬╬▓███▓▓▓▓█▓╬╬╬▓███████████████████████
███████████████████████████████▓█████▓▓╬╬╬╬╬╬╬╬▓███▓╬╬╬╬╬╬╬▓╬╬▓███████████████████████
████████████████████████████▓▓▓▓╬╬▓█████╬╬╬╬╬╬███▓╬╬╬╬╬╬╬╬╬╬╬╬╬███████████████████████
███████████████████████████▓▓▓▓╬╬╬╬╬╬▓██╬╬╬╬╬╬▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████
████████████████████████████▓▓▓╬╬╬╬╬╬╬▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████
███████████████████████████▓█▓███████▓▓███▓╬╬╬╬╬╬▓███████▓╬╬╬╬▓███████████████████████
████████████████████████████████████████▓█▓╬╬╬╬╬▓▓▓▓▓▓▓▓╬╬╬╬╬╬╬███████████████████████
███████████████████████████▓▓▓▓▓▓▓╬╬▓▓▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████
████████████████████████████▓▓▓╬╬╬╬▓▓▓▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████
███████████████████████████▓█▓▓▓▓▓▓▓▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████
█████████████████████████████▓▓▓▓▓▓▓▓█▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████
█████████████████████████████▓▓▓▓▓▓▓██▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████████████████████
█████████████████████████████▓▓▓▓▓████▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████████████████████
████████████████████████████▓█▓▓▓▓██▓▓▓▓██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████████████████████
████████████████████████████▓▓███▓▓▓▓▓▓▓██▓╬╬╬╬╬╬╬╬╬╬╬╬█▓╬▓╬╬▓████████████████████████
█████████████████████████████▓███▓▓▓▓▓▓▓▓████▓▓╬╬╬╬╬╬╬█▓╬╬╬╬╬▓████████████████████████
█████████████████████████████▓▓█▓███▓▓▓████╬▓█▓▓╬╬╬▓▓█▓╬╬╬╬╬╬█████████████████████████
██████████████████████████████▓██▓███████▓╬╬╬▓▓╬▓▓██▓╬╬╬╬╬╬╬▓█████████████████████████
███████████████████████████████▓██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬██████████████████████████
███████████████████████████████▓▓██▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓██████████████████████████
████████████████████████████████▓▓▓█████▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████████
█████████████████████████████████▓▓▓█▓▓▓▓▓███▓╬╬╬╬╬╬╬╬╬╬╬▓████████████████████████████
██████████████████████████████████▓▓▓█▓▓▓╬▓██╬╬╬╬╬╬╬╬╬╬╬▓█████████████████████████████
███████████████████████████████████▓▓█▓▓▓▓███▓╬╬╬╬╬╬╬╬╬▓██████████████████████████████
██████████████████████████████████████▓▓▓███▓▓╬╬╬╬╬╬╬╬████████████████████████████████
███████████████████████████████████████▓▓▓██▓▓╬╬╬╬╬╬▓█████████████████████████████████
██████████████████████████████████████████████████████████████████████████████████████
*/
/*
______ __ __ __ __ ________ _______ __ __ ______ ______ ______ ______ __ __
/ \| \ | \ \ / \ \ \ | \ | \/ \ / \ / \ / \| \ | \
| ▓▓▓▓▓▓\ ▓▓ | ▓▓ ▓▓\ / ▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓\ | ▓▓ | ▓▓ ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓\ | ▓▓
| ▓▓__| ▓▓ ▓▓__| ▓▓ ▓▓▓\ / ▓▓▓ ▓▓__ | ▓▓ | ▓▓ | ▓▓__| ▓▓ ▓▓__| ▓▓ ▓▓___\▓▓ ▓▓___\▓▓ ▓▓__| ▓▓ ▓▓▓\| ▓▓
| ▓▓ ▓▓ ▓▓ ▓▓ ▓▓▓▓\ ▓▓▓▓ ▓▓ \ | ▓▓ | ▓▓ | ▓▓ ▓▓ ▓▓ ▓▓\▓▓ \ \▓▓ \| ▓▓ ▓▓ ▓▓▓▓\ ▓▓
| ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓\▓▓ ▓▓ ▓▓ ▓▓▓▓▓ | ▓▓ | ▓▓ | ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓_\▓▓▓▓▓▓\_\▓▓▓▓▓▓\ ▓▓▓▓▓▓▓▓ ▓▓\▓▓ ▓▓
| ▓▓ | ▓▓ ▓▓ | ▓▓ ▓▓ \▓▓▓| ▓▓ ▓▓_____| ▓▓__/ ▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓ \__| ▓▓ \__| ▓▓ ▓▓ | ▓▓ ▓▓ \▓▓▓▓
| ▓▓ | ▓▓ ▓▓ | ▓▓ ▓▓ \▓ | ▓▓ ▓▓ \ ▓▓ ▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓\▓▓ ▓▓\▓▓ ▓▓ ▓▓ | ▓▓ ▓▓ \▓▓▓
\▓▓ \▓▓\▓▓ \▓▓\▓▓ \▓▓\▓▓▓▓▓▓▓▓\▓▓▓▓▓▓▓ \▓▓ \▓▓\▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓▓▓▓▓ \▓▓ \▓▓\▓▓ \▓▓
__ __ __ __ __ ______ ______ _______ ______ __
| \ | \ | \ \ | \ / \ / \| \ / \ | \
| ▓▓ | ▓▓ ______ ______ ____| ▓▓\▓▓_______ ______ _| ▓▓_ ______ | ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓▓▓▓▓▓\ ▓▓▓▓▓▓\ \▓▓ _______ ______
| ▓▓__| ▓▓/ \ | \ / ▓▓ \ \ / \ | ▓▓ \ / \ | ▓▓__| ▓▓ ▓▓ \▓▓ ▓▓__/ ▓▓ ▓▓ \▓▓ | \/ \| \
| ▓▓ ▓▓ ▓▓▓▓▓▓\ \▓▓▓▓▓▓\ ▓▓▓▓▓▓▓ ▓▓ ▓▓▓▓▓▓▓\ ▓▓▓▓▓▓\ \▓▓▓▓▓▓ | ▓▓▓▓▓▓\ | ▓▓ ▓▓ ▓▓ | ▓▓ ▓▓ ▓▓ | ▓▓ ▓▓▓▓▓▓▓ \▓▓▓▓▓▓\
| ▓▓▓▓▓▓▓▓ ▓▓ ▓▓/ ▓▓ ▓▓ | ▓▓ ▓▓ ▓▓ | ▓▓ ▓▓ | ▓▓ | ▓▓ __| ▓▓ | ▓▓ | ▓▓▓▓▓▓▓▓ ▓▓ __| ▓▓▓▓▓▓▓| ▓▓ __ | ▓▓\▓▓ \ / ▓▓
| ▓▓ | ▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓ ▓▓__| ▓▓ ▓▓ ▓▓ | ▓▓ ▓▓__| ▓▓ | ▓▓| \ ▓▓__/ ▓▓ | ▓▓ | ▓▓ ▓▓__/ \ ▓▓ | ▓▓__/ \ | ▓▓_\▓▓▓▓▓▓\ ▓▓▓▓▓▓▓
| ▓▓ | ▓▓\▓▓ \\▓▓ ▓▓\▓▓ ▓▓ ▓▓ ▓▓ | ▓▓\▓▓ ▓▓ \▓▓ ▓▓\▓▓ ▓▓ | ▓▓ | ▓▓\▓▓ ▓▓ ▓▓ \▓▓ ▓▓ | ▓▓ ▓▓\▓▓ ▓▓
\▓▓ \▓▓ \▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓\▓▓\▓▓ \▓▓_\▓▓▓▓▓▓▓ \▓▓▓▓ \▓▓▓▓▓▓ \▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓\▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓
| \__| ▓▓
\▓▓ ▓▓
\▓▓▓▓▓▓
*/
#include<bits/stdc++.h>
using namespace std;
// todo defines
#define ll long long
#define int long long
#define double long double
#define ld long double
#define f(i,n) for(ll i=0;i<(n);i++)
#define f1(i,n) for(ll i=1;i<=(n);i++)
#define el '\n'
#define sq(a) (a)*(a)
#define pb emplace_back
#define sz(x) (int)((x).size())
#define all(x) (x).begin(), (x).end()
#define asort(a,n) sort(a,a+n)
#define dsort(a,n) sort(a,a+n,greater<>())
#define vasort(v) sort(v.begin(), v.end());
#define vdsort(v) sort(v.begin(), v.end(),greater<>());
#define cina(arr) f(i,n) cin >> arr[i];
#define YES cout << "YES\n"
#define Yes cout << "Yes"<<el
#define yes cout << "yes"<<el
#define NO cout << "NO\n"
#define No cout << "No"<<el
#define no cout << "no"<<el
#define covid19 ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define TC int t; cin >> t; while(t--)
// todo typedefs
typedef pair<int,int> pii;
typedef map<int,int>mii;
typedef vector<int>vi;
typedef vector<pii>vii;
typedef set<int> si;
typedef set<char> sc;
bool as_second(const pair<ll,ll> &a, const pair<ll,ll> &b) {return (a.second < b.second); }//sort the vector pair in assending order according to second element
bool ds_first(const pair<ll,ll> &a, const pair<ll,ll> &b){ return (a.first > b.first);}//sort the vector pair in decending order according to first element
bool ds_second(const pair<ll,ll> &a, const pair<ll,ll> &b) {return a.second>b.second;}//sort the vector pair in decending order according to second element
bool isPrime(ll n) {
if (n <= 1)
return false;
for (int i = 2; i * i <= (n); i++)
if (n % i == 0)
return false;
return true;
}
ll factorial(ll n) {
int fact = 1;
for (int i = 1; i <= n; i++)fact *= i;
return fact;
}
bool primeFactors(int n, int l, int r, bool notFound)
{
for (int i = l; i <= r; i++)
{
if (i == 1)
i++;
if (n % i == 0)
{
cout << i << " ";
notFound = false;
}
while (n % i == 0)
{
n = n / i;
}
}
return notFound;
}
bool IsInBinarySequence(ll number) {
ll numberToCheck = 1;
do {
if (number == numberToCheck) return true;
numberToCheck *= 2;
} while (numberToCheck <= number);
return false;
}
ll nextPowerOf2(ll n)
{
if (n && !(n & (n - 1)))
return n;
ll cnt = 0;
while (n != 0)
{
n >>= 1;
cnt++;
}
ll x = 1;
x = x << cnt;
return x;
}
ll highestPowerof2(ll n)
{
ll res = 0;
for (ll i = n; i >= 1; i--)
{
// If i is a power of 2
if ((i & (i - 1)) == 0)
{
res = i;
break;
}
}
return res;
}
vector<ll> first50fib1_1_2()
{
vector<ll>v = { 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155, 165580141 ,267914296 ,433494437 ,701408733 ,1134903170 ,1836311903 ,2971215073 ,4807526976 ,7778742049,12586269025,20365011074 };
return v;
}
void first50fib0_0_1()
{
ll arr[51]={0, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368,75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049};
}
ll fib(ll n) {
if (n == 1)
return 0;
if (n == 2)
return 1;
return fib(n - 1) + fib(n - 2);
}
ll binets_formula(ll n) {
double sqrt5 = sqrt(5);
int F_n = (pow((1 + sqrt5), n) - pow((1 - sqrt5), n)) / (pow(2, n) * sqrt5);
return F_n;
}
/*const int N = 1e7;
bool prime[N+3];
void Sieve() {
memset(prime, true, sizeof(prime));
for (int p = 2; p * p <= N; p++) {
if (prime[p]) {
for (int i = p * p; i <= N; i += p)
prime[i] = false;
}
}
}
*/
/*
void Sieve(int n) {
memset(prime, true, sizeof(prime));
prime[0] = prime[1] = false;
for (int i = 2; i <= n; i++) {
if (prime[i]) {
for (int j = 2 * i; j <= n; j += i) {
prime[j] = false;
}
}
}
}
*/
void luckyGenerator() {
vector<ll> lucky;
lucky.pb(0);
int idx = 0;
while (lucky.back() < 1e10) {
lucky.push_back(((lucky[idx] * 10) + 4));
lucky.push_back((lucky[idx] * 10) + 7);
idx++;
}
}
int binarySearch(int a[], int first, int last, int search_num) {
int middle;
if (last >= first) {
middle = (first + last) / 2;
//Checking if the element is present at middle loc
if (a[middle] == search_num)
return middle + 1;
//Checking if the search element is present in greater half
else if (a[middle] < search_num)
return binarySearch(a, middle + 1, last, search_num);
//Checking if the search element is present in lower half
else
return binarySearch(a, first, middle - 1, search_num);
}
return -1;
}
void factorize(long long n) {
int count = 0;
while (!(n % 2)) {
n /= 2;
count++;
}
if (count)
cout << 2 << " " << count << endl;
for (long long i = 3; i <= sqrt(n); i += 2) {
count = 0;
while (n % i == 0) {
count++;
n = n / i;
}
if (count)
cout << i << " " << count << endl;
}
if (n > 2)
cout << n << " " << 1 << endl;
}
vector<pair<int,int>> primeFactors(ll num) {
ll fac = 2;
vector<pair<int,int>>v;
while (num > 1) {
if (num % fac == 0) {
num /= fac;
ll pow = 1;
while (num % fac == 0) {
num /= fac;
pow++;
}
v.pb(fac, pow);
}
else {
fac++;
}
}
return v;
}
bool onePrimeFactor(ll num) {
ll fac = 2;
int cnt = 0;
while (num > 1) {
if (num % fac == 0) {
cnt++;
while (num % fac == 0)
num /= fac;
} else
fac++;
if (cnt >= 2)
return false;
}
return true;
}
bool isPerfect(ll d)
{
double temp = d;
d = sqrt(d);
temp = sqrt(temp);
if (temp == d)
return true;
return false;
}
void sort(string s[], int n)//sort string according to length
{
for (int i = 1; i < n; i++)
{
string temp = s[i];
int j = i - 1;
while (j >= 0 && temp.length() < s[j].length())
{
s[j + 1] = s[j];
j--;
}
s[j + 1] = temp;
}
}
bool IsPowerOfTwo(ll x)
{
return !(x & (x - 1));
}
int binarySearchCount(ll arr[], int n, ll key)
{
int left = 0, right = n;
int mid;
while (left < right) {
mid = (right + left) >> 1;
if (arr[mid] == key) {
while (mid + 1 < n && arr[mid + 1] == key)
mid++;
break;
}
else if (arr[mid] > key)
right = mid;
else
left = mid + 1;
}
while (mid > -1 && arr[mid] > key)
mid--;
return mid + 1;
}
int countOnesInBin(ll n) {
int cnt = 0;
while (n) {
cnt += n & 1;
n >>= 1;
}
return cnt;
}
string convertToBinary(ll x) {
string s;
while (x > 0) {
if (x % 2)
s += '1';
else
s += '0';
x /= 2;
}
reverse(s.begin(), s.end());
return s;
}
ll convertToDecimal(string s) {
reverse(s.begin(), s.end());
ll ans = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '1')
ans += (1 << i);
}
return ans;
}
long long lcm(int a, int b)
{
return (a / __gcd(a, b)) * b;
}
bool palindrome(string s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s[i] != s[s.length() - i - 1])
return false;
}
return true;
}
int sumOfDigits(ll n) {
int sum = 0;
string s = to_string(n);
f(i, s.length())sum += s[i] - '0';
return sum;
}
bool isUnique(ll x) {
int size = log10(x) + 1;
set<int> s;
while (x > 0) {
s.insert(x % 10);
x /= 10;
}
if (s.size() == size)
return true;
else
return false;
}
void subString(string s, int n) {
for (int i = 0; i < n; i++)
for (int len = 1; len <= n - i; len++)
cout << s.substr(i, len) << el;
}
bool sortByVal(const pair<string, int> &a,
const pair<string, int> &b)
{
return (a.second > b.second);
}
ll Round(double n) {
ll y = n;
if (y == n)
return y;
else
return y + 1;
}
bool isLetter(char x) {
if (x >= 'A' && x <= 'Z')
return true;
else if (x >= 'a' && x <= 'z')
return true;
else
return false;
}
int findLastIndex(string s, char x)
{
int index = -1;
for (int i = 0; i < s.length(); i++)
if (s[i] == x)
index = i;
return index;
}
bool isVowel(char c) {
c = tolower(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'u' || c == 'o')
return true;
else
return false;
}
bool isOdd(char c) {
if (c == '1' || c == '3' || c == '5' || c == '7' || c == '9')
return true;
else
return false;
}
ll sum(ll n) {
ll sum = (n * (n + 1)) / 2;
return sum;
}
ll sumInRange(ll l , ll r) {
ll ans = sum(r) - sum(l - 1);
return ans;
}
bool sortedAsc(ll arr[],ll n) {
for (int i = 1; i < n; i++) {
if (arr[i] < arr[i-1])
return false;
}
return true;
}
bool sortedDesc(ll arr[],ll n) {
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1])
return false;
}
return true;
}
ll decimalDigitRoot(ll n) {
return ((n - 1) % 9) + 1;
}
bool equal(char x , char y) {
if (x == '.')
return true;
return x == y;
}
string add(string s , int n) {
string temp = "";
while (n--)
temp += s;
return temp;
}
bool regularBracketSequence(string s) {
stack<char> s1;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(')
s1.push('(');
else {
if (s1.empty())
return false;
else
s1.pop();
}
}
return s1.empty();
}
bool sumDigits(int n) {
int rem = 0;
while (n) {
rem += n % 10;
n /= 10;
}
return rem == 10;
}
bool sortedA(int arr[],int n) {
for (int i = 1; i < n; i++)
if (arr[i] < arr[i - 1])
return false;
return true;
}
bool sortedD(int arr[],int n) {
for (int i = 1; i < n; i++)
if (arr[i] > arr[i - 1])
return false;
return true;
}
//int ans[N];
/*
vector<int>adjList[N];
int dfs(int node,int parent) {
visited[node] = true;
for (auto adjNode : adjList[node]) {
if (!visited[adjNode]) {
group.pb(adjNode);
dfs(adjNode, node);
}
else if (visited[adjNode] && adjNode != parent)
return 1;
}
return 0;
}
*/
/*
void bfs(int node) {
queue<int> q;
q.push(node);
visited[node] = 1;
while (!q.empty()) {
group.pb(q.front());
for (auto adjNode : adjList[q.front()])
if (!visited[adjNode])
q.push(adjNode), visited[adjNode] = 1;
q.pop();
}
}
void dijkstra(int source, vector<vector<pair<int,int>>>&graph) {
int n = graph.size();
vector<int> dist(n, inf), pre(n, -1);
// cost , node
priority_queue<pair<int, int>> nextToVisit;
dist[source] = 0;
pre[source] = source;
nextToVisit.push({0, source});
while (!nextToVisit.empty()) {
int u = nextToVisit.top().second;
nextToVisit.pop();
if (visited[u])continue;
visited[u] = 1;
for (auto e : graph[u]) {
int v = e.first;
int c = e.second;
if (dist[u] + c < dist[v]) {
dist[v] = dist[u] + c;
pre[v] = u;
nextToVisit.push({-dist[v], v});
}
}
}
}
*/
string onlyAlphaString(string s) {
string temp = "";
for (int i = 0; i < s.size(); i++)
if (isalpha(s[i]))temp += tolower(s[i]);
return temp;
}
int computeXOR(ll a) {
if (a % 4 == 0) return a;
else if (a % 4 == 1) return 1;
else if (a % 4 == 2) return a + 1;
else return 0;
}
void sort3(int& a, int& b, int& c) {
if (a > b)swap(a, b);
if (b > c)swap(b, c);
if (a > b)swap(a, b);
}
int lis(vector<int>&a) {
int n = a.size();
vector<int> dp(n, 1);
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
if (a[j] < a[i])dp[i] = max(dp[i], dp[j] + 1);
int ans = dp[0];
for (int i = 1; i < n; i++)ans = max(ans, dp[i]);
return ans;
}
bool oneCharacterString(string s) {
vasort(s)
return s[0] == s[s.size() - 1];
}
ll nPr(ll n , ll r) {
ll fact = 1;
while (r--) {
fact *= n;
n--;
}
return fact;
}
//todo consts
//const int inf = 1e9 + 10;
const double pi=acos(-1);
bool containEven(string s) {
for (int i = 0; i < s.size(); i++)
if (s[i] == '2' || s[i] == '4' || s[i] == '6' || s[i] == '8')return true;
return false;
}void printNcR(int n, int r) {
long long p = 1, k = 1;
if (n - r < r)
r = n - r;
if (r != 0) {
while (r) {
p *= n;
k *= r;
long long m = __gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
} else
p = 1;
cout << p << endl;
}
string convertToTernary(int n) {
string ans = "";
while (n > 0) {
ans += (char) ((n % 3) + '0');
n /= 3;
}
reverse(ans.begin(), ans.end());
return ans;
}
string sumOfTernaries(string s1,string s2) {
string ans = "";
for (int i = 0; i < s1.size(); i++) {
int x = (s1[i] - '0') + (s2[i] - '0');
x %= 3;
ans += (char) (x + '0');
}
return ans;
}
string unique_string(string s) {
string t = "";
for (int i = 0; i < s.size(); i++) {
if (s[i] == t.back())continue;
t += s[i];
}
return t;
}
int countOdd(int L, int R) {
int N = (R - L) / 2;
// if either R or L is odd
if (R % 2 != 0 || L % 2 != 0)
N += 1;
return N;
}
/*
void dfs(int node) {
group.pb(node);
visited[node] = true;
for (auto adjNode: adjList[node])
if (!visited[adjNode])
dfs(adjNode);
}
*/
bool isPowerof10(int n) {
while (n >= 10 && n % 10 == 0)n /= 10;
return n == 1;
}
int sumDigitsString(string s) {
int sum = 0;
for (int i = 0; i < s.size(); i++)sum += s[i] - '0';
return sum;
}
long long nCr(int n, int r) {
if(r > n - r) r = n - r; // because C(n, r) == C(n, n - r)
long long ans = 1;
int i;
for(i = 1; i <= r; i++) {
ans *= n - r + i;
ans /= i;
}
return ans;
}
int log_a_base_b(int a, int b) {
return log2(a) / log2(b);
}
/*
int dx[] = {1, 1, 1, -1, -1, -1, 0, 0};
int dy[] = {0, -1, 1, -1, 0, 1, -1, 1};
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*void dfs(int node,int depth) {
mx = max(mx, depth);
vis[node] = 1;
for (auto adjNode: adjList[node])
dfs(adjNode, depth + 1);
}
*/
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimize("Ofast")
string converToPigLatin(string s) {
if (s.size() == 1) {
s += "ay";
return s;
}
string ans = "";
for (int i = 1; i < s.size(); i++) {
if (i == 1)ans += (char) toupper(s[i]);
else ans += (char) tolower(s[i]);
}
ans += tolower(s[0]);
ans += "ay";
return ans;
}
string cfRate(int n) {
if (n < 1200)return "Newbie";
else if (n <= 1399)return "Pupil";
else if (n <= 1599)return "Specialist";
else if (n <= 1899)return "Expert";
else if (n <= 2099)return "Candidate master";
else if (n <= 2299)return "Master";
else if (n <= 2399)return "International master";
else if (n <= 2599)return "Grandmaster";
else if (n <= 2999)return "International grandmaster";
return "Legendary grandmaster";
}
int maxDigit(int n) {
int mx = 0;
while (n > 0) {
mx = max(mx, n % 10);
n /= 10;
}
return mx;
}
int minDigit(int n) {
int mn = 1e18;
while (n > 0) {
mn = min(mn, n % 10);
n /= 10;
}
return mn;
}
string convert_from_decimal_to_X(int n, int x) {
string ans = "";
while (n > 0) {
int rem = n % x;
if (rem >= 10) {
rem -= 10;
ans += ('A' + rem);
} else ans += (rem + '0');
n /= x;
}
reverse(ans.begin(), ans.end());
return ans;
}
int convert_from_X_to_Decimal(string s,int x) {
reverse(s.begin(), s.end());
int st = 1, ans = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] != '0') {
if (isalpha(s[i])) {
int dig = (s[i] - 'A') + 10;
ans += dig * st;
} else ans += (s[i] - '0') * st;
}
st *= x;
}
return ans;
}
int mod9 = 998244353;
int fast_power(int a, int n) {
if (n == 0)
return 1;
// putting a check to avoid unnecessary recursive calls
if (a == 0)
return 0;
int tmp = fast_power(a, n / 2);
if (n % 2 == 0) // b is even
return (tmp * tmp );
else
return (a * tmp * tmp );
}
bool checkSemiPrime(int num) {
int cnt = 0;
for (int i = 2; i * i <= num && cnt < 2; i++) {
while (num % i == 0) {
num /= i;
cnt++;
if (cnt > 2)break;
}
}
if (num > 1)cnt++;
return cnt == 2;
}
string binaryAdd(string a, string b) {
string result = "";
int temp = 0;
int size_a = a.size() - 1;
int size_b = b.size() - 1;
while (size_a >= 0 || size_b >= 0 || temp == 1) {
temp += ((size_a >= 0) ? a[size_a] - '0' : 0);
temp += ((size_b >= 0) ? b[size_b] - '0' : 0);
result = char(temp % 2 + '0') + result;
temp /= 2;
size_a--;
size_b--;
}
return result;
}
int cmp(string a,string b) {
int cnt = 0;
for (int i = 0; i < a.size(); i++)cnt += (a[i] != b[i]);
return cnt;
}
int sumOfDivisors(int n) {
int sum = 0;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
if (n / i == i)sum += i;
else sum += (n / i) + i;
}
}
return sum;
}
int cntDistinctLetters(string s) {
int cnt = 0;
map<char, bool> vis;
for (auto c: s)if (!vis[c] && c != ' ')cnt++, vis[c] = 1;
return cnt;
}
int numOfOnes(int x) {
return __builtin_popcount(x);
}
bool checkPalindromeTime(string s1,string s2) {
if (s1[0] == s2[1] && s1[1] == s2[0])return true;
return false;
}
int cntVowels(string s) {
int cnt = 0;
f(i, s.size())if (isVowel(s[i]))cnt++;
return cnt;
}
int largest_divisor(int x) {
int mx = -1;
for (int i = 1; i * i <= x; i++) {
if (x % i == 0) {
mx = max(mx, i);
mx = max(mx, x / i);
}
}
return mx;
}
char shift(char c , int x) {
int y = x + (c - 'a');
y %= 26;
return y + 'a';
}
int max_Area_Given_Perimeter(double p) {
return (int) ceil(p / 4.0) * floor(p / 4.0);
}
/*
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
*/
bool checkRBS(string t) {
stack<char> st;
for (auto c: t) {
if (c == '(')st.push(c);
else {
if (st.empty())return 0;
else st.pop();
}
}
return st.empty();
}
int cntTrailingZeroes(int x) {
return __builtin_clz(x);
}
int cntLeadingZeroes(int x) {
return __builtin_ctz(x);
}
double DecimalMod(double a, double b) {
if (a < b) {
return a;
}
return DecimalMod(a - b, b);
}
/*
long long longPower (long long a, long long n) {
if (n == 0)
return 1;
if (n % 2 == 1)
return (longPower (a, n-1) * a) % mod;
else {
long long b = (longPower (a, n/2)) % mod;
return (b * b) % mod;
}
}
// sort vector descending by first , ascending by second
auto comp = [](auto p1, auto p2) {
if(p1.first < p2.first) return true;
if(p1.first > p2.first) return false;
return p1.second >= p2.second;
}
const int N = 5e5 + 5;
ll fact[N];
ll mod = 1e9 + 7;
ll fastP(ll b, ll e) {
if (!e)
return 1;
if (e & 1)
return b * 1ll * fastP(b * 1ll * b % mod, e >> 1) % mod;
return fastP(b * 1ll * b % mod, e >> 1) % mod;
}
ll mod_inverse(ll x) {
return fastP(x, mod - 2);
}
ll ncr(ll n, ll r) {
if (r > n)
return 0;
return (1LL * fact[n] %mod* mod_inverse(fact[n - r])%mod * mod_inverse(fact[r])%mod) % mod;
}
void fac()
{
fact[0] = 1;
for (int i = 1; i < N; i++)
{
fact[i] = (1LL * i * fact[i - 1]) % mod;
}
}
*/
const int N = 2e5 + 5 , mod = 1e9 + 7;
ll fastP(ll b, ll e) {
if (!e)
return 1;
if (e & 1)
return b * 1ll * fastP(b * 1ll * b % mod, e >> 1) % mod;
return fastP(b * 1ll * b % mod, e >> 1) % mod;
}
int32_t main() {
covid19
int n;
string s, ans = "";
cin >> n >> s;
char c1 = 'a', c2 = 'a';
f(i, n) {
if (s[i] >= c1) {
ans += '0';
c1 = s[i];
} else if (s[i] >= c2) {
ans += '1';
c2 = s[i];
} else return NO, 0;
}
YES;
cout << ans << el;
}
/* NOTESSS
decimal digit root ::
d(n)=1+((n−1)mod9)
*/ | cpp |
1304 | F1 | F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, k;
cin >> n >> m >> k;
vector<vector<int>> a(n, vector<int>(m));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> a[i][j];
vector<vector<int>> p(n, vector<int>(m + 1));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
p[i][j + 1] = p[i][j] + a[i][j];
vector<int> dp(m - k + 1);
for (int i = 0; i + k <= m; i++)
dp[i] = p[0][i + k] - p[0][i];
for (int x = 1; x < n; x++) {
vector<int> new_dp(m - k + 1);
for (int y = 0; y + k <= m; y++) {
for (int z = max(0, y - k + 1); z <= y; z++)
new_dp[z] = max(new_dp[z], dp[y] + p[x][y + k] - p[x][z]);
for (int z = y + 1; z < y + k && z + k <= m; z++)
new_dp[z] = max(new_dp[z], dp[y] + p[x][z + k] - p[x][y]);
}
multiset<int> s;
for (int y = k - 1; y < m - k + 1; y++)
s.insert(dp[y] + p[x][y + k] - p[x][y]);
for (int y = 0; y + k <= m; y++) {
if (y + 2 * k - 1 <= m)
s.erase(s.find(dp[y + k - 1] + p[x][y + 2 * k - 1] - p[x][y + k - 1]));
if (y >= k)
s.insert(dp[y - k] + p[x][y] - p[x][y - k]);
if (!s.empty())
new_dp[y] = max(new_dp[y], *s.rbegin() + p[x][y + k] - p[x][y]);
}
dp = new_dp;
}
cout << *max_element(dp.begin(), dp.end()) << "\n";
} | cpp |
1312 | G | G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier. | [
"data structures",
"dfs and similar",
"dp"
] | #line 1 "/home/maspy/compro/library/my_template.hpp"
#if defined(LOCAL)
#include <my_template_compiled.hpp>
#else
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) \
vector<vector<vector<type>>> name( \
h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name( \
a, vector<vector<vector<type>>>( \
b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c))
#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)
#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) \
overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)
#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define stoi stoll
template <typename T, typename U>
T SUM(const vector<U> &A) {
T sum = 0;
for (auto &&a: A) sum += a;
return sum;
}
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) \
sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
template <typename T>
T pick(deque<T> &que) {
T a = que.front();
que.pop_front();
return a;
}
template <typename T>
T pick(pq<T> &que) {
T a = que.top();
que.pop();
return a;
}
template <typename T>
T pick(pqg<T> &que) {
assert(que.size());
T a = que.top();
que.pop();
return a;
}
template <typename T>
T pick(vc<T> &que) {
assert(que.size());
T a = que.back();
que.pop_back();
return a;
}
template <typename T, typename U>
T ceil(T x, U y) {
return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U>
T floor(T x, U y) {
return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
T q = floor(x, y);
return {q, x - q * y};
}
template <typename F>
ll binary_search(F check, ll ok, ll ng) {
assert(check(ok));
while (abs(ok - ng) > 1) {
auto x = (ng + ok) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return ok;
}
template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
FOR(iter) {
double x = (ok + ng) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return (ok + ng) / 2;
}
template <class T, class S>
inline bool chmax(T &a, const S &b) {
return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
return (a > b ? a = b, 1 : 0);
}
vc<int> s_to_vi(const string &S, char first_char) {
vc<int> A(S.size());
FOR(i, S.size()) { A[i] = S[i] - first_char; }
return A;
}
template <typename T, typename U>
vector<T> cumsum(vector<U> &A, int off = 1) {
int N = A.size();
vector<T> B(N + 1);
FOR(i, N) { B[i + 1] = B[i] + A[i]; }
if (off == 0) B.erase(B.begin());
return B;
}
template <typename CNT, typename T>
vc<CNT> bincount(const vc<T> &A, int size) {
vc<CNT> C(size);
for (auto &&x: A) { ++C[x]; }
return C;
}
// stable
template <typename T>
vector<int> argsort(const vector<T> &A) {
vector<int> ids(A.size());
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
return ids;
}
// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
int n = len(I);
vc<T> B(n);
FOR(i, n) B[i] = A[I[i]];
return B;
}
#endif
#line 1 "/home/maspy/compro/library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace fastio {
// クラスが read(), print() を持っているかを判定するメタ関数
struct has_write_impl {
template <class T>
static auto check(T &&x) -> decltype(x.write(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_write : public decltype(has_write_impl::check<T>(std::declval<T>())) {
};
struct has_read_impl {
template <class T>
static auto check(T &&x) -> decltype(x.read(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_read : public decltype(has_read_impl::check<T>(std::declval<T>())) {};
struct Scanner {
FILE *fp;
char line[(1 << 15) + 1];
size_t st = 0, ed = 0;
void reread() {
memmove(line, line + st, ed - st);
ed -= st;
st = 0;
ed += fread(line + ed, 1, (1 << 15) - ed, fp);
line[ed] = '\0';
}
bool succ() {
while (true) {
if (st == ed) {
reread();
if (st == ed) return false;
}
while (st != ed && isspace(line[st])) st++;
if (st != ed) break;
}
if (ed - st <= 50) {
bool sep = false;
for (size_t i = st; i < ed; i++) {
if (isspace(line[i])) {
sep = true;
break;
}
}
if (!sep) reread();
}
return true;
}
template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
while (true) {
size_t sz = 0;
while (st + sz < ed && !isspace(line[st + sz])) sz++;
ref.append(line + st, sz);
st += sz;
if (!sz || st != ed) break;
reread();
}
return true;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
bool neg = false;
if (line[st] == '-') {
neg = true;
st++;
}
ref = T(0);
while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
if (neg) ref = -ref;
return true;
}
template <typename T,
typename enable_if<has_read<T>::value>::type * = nullptr>
inline bool read_single(T &x) {
x.read();
return true;
}
bool read_single(double &ref) {
string s;
if (!read_single(s)) return false;
ref = std::stod(s);
return true;
}
bool read_single(char &ref) {
string s;
if (!read_single(s) || s.size() != 1) return false;
ref = s[0];
return true;
}
template <class T>
bool read_single(vector<T> &ref) {
for (auto &d: ref) {
if (!read_single(d)) return false;
}
return true;
}
template <class T, class U>
bool read_single(pair<T, U> &p) {
return (read_single(p.first) && read_single(p.second));
}
template <size_t N = 0, typename T>
void read_single_tuple(T &t) {
if constexpr (N < std::tuple_size<T>::value) {
auto &x = std::get<N>(t);
read_single(x);
read_single_tuple<N + 1>(t);
}
}
template <class... T>
bool read_single(tuple<T...> &tpl) {
read_single_tuple(tpl);
return true;
}
void read() {}
template <class H, class... T>
void read(H &h, T &... t) {
bool f = read_single(h);
assert(f);
read(t...);
}
Scanner(FILE *fp) : fp(fp) {}
};
struct Printer {
Printer(FILE *_fp) : fp(_fp) {}
~Printer() { flush(); }
static constexpr size_t SIZE = 1 << 15;
FILE *fp;
char line[SIZE], small[50];
size_t pos = 0;
void flush() {
fwrite(line, 1, pos, fp);
pos = 0;
}
void write(const char val) {
if (pos == SIZE) flush();
line[pos++] = val;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
void write(T val) {
if (pos > (1 << 15) - 50) flush();
if (val == 0) {
write('0');
return;
}
if (val < 0) {
write('-');
val = -val; // todo min
}
size_t len = 0;
while (val) {
small[len++] = char(0x30 | (val % 10));
val /= 10;
}
for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
pos += len;
}
void write(const string s) {
for (char c: s) write(c);
}
void write(const char *s) {
size_t len = strlen(s);
for (size_t i = 0; i < len; i++) write(s[i]);
}
void write(const double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
void write(const long double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
template <typename T,
typename enable_if<has_write<T>::value>::type * = nullptr>
inline void write(T x) {
x.write();
}
template <class T>
void write(const vector<T> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
template <class T, class U>
void write(const pair<T, U> val) {
write(val.first);
write(' ');
write(val.second);
}
template <size_t N = 0, typename T>
void write_tuple(const T t) {
if constexpr (N < std::tuple_size<T>::value) {
if constexpr (N > 0) { write(' '); }
const auto x = std::get<N>(t);
write(x);
write_tuple<N + 1>(t);
}
}
template <class... T>
bool write(tuple<T...> tpl) {
write_tuple(tpl);
return true;
}
template <class T, size_t S>
void write(const array<T, S> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
void write(i128 val) {
string s;
bool negative = 0;
if (val < 0) {
negative = 1;
val = -val;
}
while (val) {
s += '0' + int(val % 10);
val /= 10;
}
if (negative) s += "-";
reverse(all(s));
if (len(s) == 0) s = "0";
write(s);
}
};
Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);
void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
printer.write(head);
if (sizeof...(Tail)) printer.write(' ');
print(forward<Tail>(tail)...);
}
void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
scanner.read(head);
read(tail...);
}
} // namespace fastio
using fastio::print;
using fastio::flush;
using fastio::read;
#define INT(...) \
int __VA_ARGS__; \
read(__VA_ARGS__)
#define LL(...) \
ll __VA_ARGS__; \
read(__VA_ARGS__)
#define STR(...) \
string __VA_ARGS__; \
read(__VA_ARGS__)
#define CHAR(...) \
char __VA_ARGS__; \
read(__VA_ARGS__)
#define DBL(...) \
double __VA_ARGS__; \
read(__VA_ARGS__)
#define VEC(type, name, size) \
vector<type> name(size); \
read(name)
#define VV(type, name, h, w) \
vector<vector<type>> name(h, vector<type>(w)); \
read(name)
void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 2 "/home/maspy/compro/library/alg/monoid/add.hpp"
template <typename X>
struct Monoid_Add {
using value_type = X;
static constexpr X op(const X &x, const X &y) noexcept { return x + y; }
static constexpr X inverse(const X &x) noexcept { return -x; }
static constexpr X power(const X &x, ll n) noexcept { return X(n) * x; }
static constexpr X unit() { return X(0); }
static constexpr bool commute = true;
};
#line 2 "/home/maspy/compro/library/string/trie.hpp"
template <int sigma>
struct Trie {
using ARR = array<int, sigma>;
int n_node;
vc<ARR> TO;
vc<int> parent;
vc<int> suffix_link;
vc<int> words;
vc<int> V; // BFS 順
Trie() {
n_node = 0;
new_node();
}
template <typename STRING>
int add(STRING S, int off) {
int v = 0;
for (auto&& ss: S) {
int s = ss - off;
assert(0 <= s && s < sigma);
if (TO[v][s] == -1) {
TO[v][s] = new_node();
parent.back() = v;
}
v = TO[v][s];
}
words.eb(v);
return v;
}
int add_char(int v, int c, int off) {
c -= off;
if (TO[v][c] != -1) return TO[v][c];
TO[v][c] = new_node();
parent.back() = v;
return TO[v][c];
}
void calc_suffix_link(bool upd_TO) {
suffix_link.assign(n_node, -1);
V.resize(n_node);
int p = 0, q = 0;
V[q++] = 0;
while (p < q) {
int v = V[p++];
FOR(s, sigma) {
int w = TO[v][s];
if (w == -1) continue;
V[q++] = w;
int f = suffix_link[v];
while (f != -1 && TO[f][s] == -1) f = suffix_link[f];
suffix_link[w] = (f == -1 ? 0 : TO[f][s]);
}
}
if (!upd_TO) return;
for (auto&& v: V) {
FOR(s, sigma) if (TO[v][s] == -1) {
int f = suffix_link[v];
TO[v][s] = (f == -1 ? 0 : TO[f][s]);
}
}
}
vc<int> calc_count() {
assert(!suffix_link.empty());
vc<int> count(n_node);
for (auto&& x: words) count[x]++;
for (auto&& v: V)
if (v) { count[v] += count[suffix_link[v]]; }
return count;
}
private:
int new_node() {
parent.eb(-1);
TO.eb(ARR{});
fill(all(TO.back()), -1);
return n_node++;
}
};
#line 2 "/home/maspy/compro/library/ds/segtree/dual_segtree.hpp"
template <typename Monoid>
struct Dual_SegTree {
using MA = Monoid;
using A = typename MA::value_type;
int n, log, size;
vc<A> laz;
Dual_SegTree() : Dual_SegTree(0) {}
Dual_SegTree(int n) { build(n); }
void build(int m) {
n = m;
log = 1;
while ((1 << log) < n) ++log;
size = 1 << log;
laz.assign(size << 1, MA::unit());
}
A get(int p) {
assert(0 <= p && p < n);
p += size;
for (int i = log; i >= 1; i--) push(p >> i);
return laz[p];
}
vc<A> get_all() {
FOR(i, size) push(i);
return {laz.begin() + size, laz.begin() + size + n};
}
void apply(int l, int r, const A& a) {
assert(0 <= l && l <= r && r <= n);
if (l == r) return;
l += size, r += size;
if (!MA::commute) {
for (int i = log; i >= 1; i--) {
if (((l >> i) << i) != l) push(l >> i);
if (((r >> i) << i) != r) push((r - 1) >> i);
}
}
while (l < r) {
if (l & 1) all_apply(l++, a);
if (r & 1) all_apply(--r, a);
l >>= 1, r >>= 1;
}
}
private:
void push(int k) {
if (laz[k] == MA::unit()) return;
all_apply(2 * k, laz[k]), all_apply(2 * k + 1, laz[k]);
laz[k] = MA::unit();
}
void all_apply(int k, A a) { laz[k] = MA::op(laz[k], a); }
};
#line 2 "/home/maspy/compro/library/alg/monoid/min.hpp"
template <class X>
struct Monoid_Min {
using value_type = X;
static constexpr X op(const X &x, const X &y) noexcept { return min(x, y); }
static constexpr X unit() { return numeric_limits<X>::max(); }
static constexpr bool commute = true;
};
#line 6 "main.cpp"
void solve() {
LL(N);
Trie<26> X;
FOR(N) {
LL(i);
CHAR(c);
X.add_char(i, c, 'a');
}
++N;
vc<int> V;
vc<int> LID(N), RID(N);
auto dfs = [&](auto& dfs, int v) -> void {
LID[v] = len(V);
V.eb(v);
FOR(k, 26) {
int t = X.TO[v][k];
if (t == -1) continue;
dfs(dfs, X.TO[v][k]);
}
RID[v] = len(V);
};
dfs(dfs, 0);
LL(Q);
VEC(int, S, Q);
// euler id -> int
vc<int> IN(N);
for (auto&& s: S) IN[LID[s]] = 1;
vc<int> RK = cumsum<int>(IN, 0); // [0, i]
const ll INF = 1LL << 60;
vi dp(N, INF);
Dual_SegTree<Monoid_Min<ll>> seg(N);
seg.apply(0, N, INF);
dp[0] = 0;
FOR(i, N) {
if (IN[i]) { chmin(dp[i], seg.get(i) + RK[i]); }
ll off = (IN[i] ? 1 - RK[i] : -RK[i]);
int v = V[i];
int L = LID[v], R = RID[v];
/*
FOR(k, L, R) if (IN[k]) chmin(dp[k], RK[k] + dp[i] + off);
*/
seg.apply(L, R, dp[i] + off);
FOR(k, 26) {
int to = X.TO[v][k];
if (to == -1) continue;
chmin(dp[LID[to]], dp[i] + 1);
}
}
vi ANS(Q);
FOR(q, Q) ANS[q] = dp[LID[S[q]]];
print(ANS);
}
signed main() {
int T = 1;
// INT(T);
FOR(T) solve();
return 0;
}
| cpp |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000
| [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve(){
int n;cin>>n;
string s;cin>>s;
int ok=1;
for(int i = 0; i < n;i++){
int small = 0,big = 0;
for(int j = 0; j< i;j++)
if(s[j] > s[i]) small=1;
for(int j = i+1;j < n;j++)
if(s[j] < s[i]) big=1;
if(small && big) ok = 0;
}
if(!ok) {cout<<"NO\n";return;}
cout<<"YES\n";
string ans(n,'0');
for(int i = 0;i < n;i++){
int cur = 1;
for(int j = 0; j<i;j++)
if(s[j]>s[i]) cur=0;
if(!cur)ans[i]='1';
}
cout<<ans;
}
int main(){
ios_base::sync_with_stdio(0),cin.tie(0);
int t=1;//cin>>t;
while(t--) solve();
}
/*
its impossible if there exists a character that has to
be swapped left itself, and another that has to be swapped
even more left than it
e.g. if for some character c_i at index i, there exists
character c_j, such that c_i < c_j and j < i and also
theres a c_k, such that c_i > c_k and k > i
abacbecfd
001010100
i think its fine if we mark any character that doesnt have to move
0 and the rest 1
e.g. if for prefix i, all character on 1..i-1 <= to c_i
*/ | cpp |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
long long n, m, k, c, x, a, resn=0, resm=0, ans=0, cnt;
vector<int>an;
vector<int>am;
vector<int>v;
int main(){
cin >> n >> m >> k;
for(long long i=0; i<n; i++){
cin >> a;
an.push_back(a);
}
for(long long i=0; i<m; i++){
cin >> a;
am.push_back(a);
}
for(long long i=1; i*i<=k; i++){
if(k%i == 0){
x=k/i;
if(x == i){
v.push_back(i);
}
else{
v.push_back(i);
v.push_back(x);
}
}
}
for(long long i=0; i<v.size(); i++){
cnt=0;
resn=0;
for(long long j=0; j<n; j++){
if(an[j]==1){
cnt++;
}
else{
if(cnt>=v[i]){
resn+=cnt-v[i]+1;
}
cnt=0;
}
}
if(cnt>=v[i]){
resn+=cnt-v[i]+1;
}
c=k/v[i];
cnt=0;
resm=0;
for(long long j=0; j<m; j++){
if(am[j]==1){
cnt++;
}
else{
if(cnt>=c){
resm+=cnt-c+1;
}
cnt=0;
}
}
if(cnt>=c){
resm+=cnt-c+1;
}
ans+=resn*resm;
}
cout << ans << 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>
#define int long long
using namespace std;
typedef pair<int,int>PII;
const int N = 2e5+10;
int p[600][600];
int n;
int sum=0;
int s[N];
void solve()
{
int a,b;
cin>>a>>b;
if(a==b)
{
if(a==0){
puts("0");
return ;
}
cout<<"1\n"<<a<<"\n";
return ;
}
if(b<a){
puts("-1");
return;
}
int sum=b-a,t=(b-a)/2,t1=sum-t;
if(((a+t) xor t1)==a)
{
cout<<"2\n";
cout<<a+t<<" "<<t1<<"\n";
return ;
}
else if(t==t1)
{
cout<<"3\n";
cout<<a<<" "<<t<<" "<<t1<<"\n";
return ;
}
puts("-1");
}
signed main()
{
int t=1;
//cin>>t;
while(t--)solve();
return 0;
} | cpp |
1286 | C1 | C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"interactive",
"math"
] | #include <bits/stdc++.h>
using namespace std;
string s;
int vis1[101][26]={},vis2[101][26]={},cur1[26]={},cur2[26]={};
int ans[100];
int main(int argc, char** argv) {
// ios::sync_with_stdio(false),cin.tie(0);
int n,i,j;
cin>>n;
if(n==1)
{
cout<<"? 1 1\n";
cin>>s;
cout<<"! "<<s<<'\n';
}
else
{
cout<<"? 1 "<<n<<'\n';
for(i=0;i<n*(n+1)/2;i++)
{
cin>>s;
for(j=0;j<s.length();j++)
{
vis1[s.length()][s[j]-'a']++;
}
}
cout<<"? 2 "<<n<<'\n';
for(i=0;i<n*(n-1)/2;i++)
{
cin>>s;
for(j=0;j<s.length();j++)
{
vis2[s.length()][s[j]-'a']++;
}
}
cout<<"? 1 1\n";
cin>>s;
ans[0]=s[0]-'a';
for(i=1;i<n;i++)
{
if(i%2==0)
{
for(j=0;j<26;j++)
{
vis2[i/2][j]+=vis2[n-1][j];
if(vis2[i/2][j]-vis2[i/2+1][j]-cur2[j]==2||vis2[i/2][j]-vis2[i/2+1][j]-cur2[j]==1&&ans[n-i/2]!=j)ans[i/2]=j;
cur2[j]=vis2[i/2][j]-vis2[i/2+1][j];
}
}
else
{
for(j=0;j<26;j++)
{
vis1[i/2+1][j]+=vis1[n][j];
if(vis1[i/2+1][j]-vis1[i/2+2][j]-cur1[j]==2||vis1[i/2+1][j]-vis1[i/2+2][j]-cur1[j]==1&&ans[i/2]!=j)ans[n-i/2-1]=j;
cur1[j]=vis1[i/2+1][j]-vis1[i/2+2][j];
}
}
}
cout<<"! ";
for(i=0;i<n;i++)cout<<(char)(ans[i]+'a');
cout<<'\n';
}
return 0;
} | 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 f(i,a,b) for(int i=a;i<b;i++)
int n,dp[103][103][2],a[103],z;
int main(){
cin>>n;
f(i,1,n+1) cin>>a[i];
f(i,0,103){f(j,0,103) dp[i][j][0]=dp[i][j][1]=1e9;}dp[0][0][0]=0;dp[0][0][1]=0;
f(i,1,n+1){
f(j,0,i+1){
if(a[i]%2==0) dp[i][j][0]=min(dp[i-1][j-1][0],dp[i-1][j-1][1]+1);
if(a[i]%2==1 || a[i]==0) dp[i][j][1]=min(dp[i-1][j][0]+1,dp[i-1][j][1]);
}
}
cout<<min(dp[n][n/2][0],dp[n][n/2][1]);
} | 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 <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <string>
#include <bits/stdc++.h>
#include <math.h>
#include <climits>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <utility>
#define ll long long
#define ull unsigned long long int
#define int int64_t
#define vi vector<int>
#define vii vector<pair<int, int>>
#define vs vector<string>
#define vc vector<char>
#define vb vector<bool>
#define pb push_back
#define vvi vector<vector<int>>
#define pii pair<int, int>
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define vin(x, v) \
for (auto &x : v) \
cin >> x;
#define vout(x, v) \
for (auto x : v) \
cout << x << " ";
#define MEM(a, b) memset(a, (b), sizeof(a))
#define forl for (int i = 0; i < n; i++)
#define loop(i, j, k) for (int i = j; i < k; i += 1)
#define rloop(i, j, k) for (int i = j; i >= k; i -= 1)
#define rep(i, j) loop(i, 0, j)
#define rrep(i, j) rloop(i, j, 0)
#define MP make_pair
#define endl "\n"
#define INF (int)1e18
#define EPS 1e-18
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define MODD 998244353
#define isortarr(arr, n) sort(arr, arr + n)
#define dsortarr(arr, n) sort(arr, arr + n, greater<int>())
#define isortvect(v) sort(v.begin(), v.end())
#define dsortvect(v) sort(v.begin(), v.end(), greater<>());
#define isortstrng(str) sort(str.begin(), str.end())
#define dsortstrng(str) sort(str.begin(), str.end(), greater<char>())
#define ltransfr(str) transform(str.begin(), str.end(), str.begin(), ::tolower)
#define utransfr(str) transform(str.begin(), str.end(), str.begin(), ::toupper)
#define ct(x) cout << x
#define cn(x) cin >> x
#define deb(x) cout << #x << "=" << x << endl
#define debb(x, y) cout << #x << "=" << x << " , " << #y << "=" << y << endl
#define cp(t) \
int t; \
cin >> t; \
while (t--)
// srand(time(0));
// x = rand()%XYZ
// cout<<fixed<<setprecision(15)<<
using namespace std;
int zero = 0;
// int gcd(int a, int b)
//{
// if (b == 0)
// return a;
// return gcd(b, a % b);
// }
// int lcm(int a, int b) { return a * b / gcd(a, b); }
//
// ll GA[10000001];
// void prime()
//{
// memset(GA, 0, 10000001);
// GA[0] = GA[1] = 1;
// for (ll i = 2; i < 10000001; i++)
// {
// if (GA[i] == 0)
// {
// for (ll j = i * i; j < 10000001; j = j + i)
// GA[j] = 1;
// }
// }
// }
//
//
// bool check_ps(ll n)
//{
// int sq = sqrt(n);
// if (n == (sq*sq)
// {
// return true;
// }
// else
// {
// return false;
// }
// }
//
map<int, int> mpp;
void dijkstra(vector<vector<pair<int, int>>> graph, int s, vi ar)
{
int k = ar.size();
priority_queue<pair<int, int>> ppr;
int v = graph.size();
int key[v + 2];
loop(i, 0, v + 1)
{
key[i] = 1e9;
}
key[s] = 0;
ppr.push({key[s], s});
while (!(ppr.empty()))
{
int u = ppr.top().second;
// cout << u << " -> ";
ppr.pop();
for (auto x : graph[u])
{
int v = x.first;
int w = x.second;
// cout << v << " ";
if (key[v] > (key[u] + w))
{
mpp[v] = 1;
key[v] = key[u] + w;
ppr.push({((-1) * key[v]), v});
}
else if (key[v] == (key[u] + w))
{
mpp[v]++;
}
}
// cout << endl;
}
// cout << endl;
// loop(i, 1, v + 1)
// {
// cout << i << " -> " << key[i] << " " << mpp[i] << endl;
// }
int mn = 0, mx = 0;
loop(i, 0, k - 1)
{
if (mpp[ar[i]] == 1)
{
if (!((key[ar[i]]) == (key[ar[i + 1]] + 1)))
{
mn += 1;
mx += 1;
}
}
else
{
if (!((key[ar[i]]) == (key[ar[i + 1]] + 1)))
{
mn += 1;
mx += 1;
}
else
{
mx += 1;
}
}
}
cout << mn << " " << mx << endl;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int v, e;
cin >> v >> e;
vector<vector<pair<int, int>>> adj(v + 2);
loop(i, 0, e)
{
int u, v, w;
cin >> u >> v;
adj[v].pb({u, 1});
// adj[v].pb({u, w});
}
int k;
cin >> k;
vi ar(k);
loop(i, 0, k)
{
cin >> ar[i];
}
int s = ar[k - 1];
dijkstra(adj, s, ar);
return 0;
} | cpp |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds. | [
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<bool> primes;
void seive(int n){
primes.resize(n+1, true);
primes[0] = false; primes[1] = false;
for(int i=2; i*i<=n; i++){
if(primes[i]){
for(int j=i*i; j<=n; j+=i) primes[j] = false;
}
}
}
ll kadane(vector<ll> &vec, ll start, ll end) { //largest sum of contiguous subarray
ll currSum = 0, maxSum = INT_MIN;
for(ll i = start; i < end; i++) {
currSum += vec[i];
if(currSum < 0) currSum = 0;
maxSum = max(maxSum, currSum);
}
return maxSum;
}
void solve(){
ll n; cin>>n;
string s; cin>>s;
ll i, c = 0;
for(i=0; i<n; i++) {
if(s[i] == '(') ++c;
else --c;
}
if(c != 0) {cout<<-1; return;}
ll l = 0, ans = 0;
for(i=0; i<n; i++) {
if(s[i] == '(') ++c;
else --c;
if(c==0 && s[l]!='(' && s[i]!=')') {
ans += i-l+1;
}
if(c==0) l = i+1;
}
cout<<ans;
}
int main(){
solve();
} | 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"
] | #import<bits/stdc++.h>
using namespace std;
const int N=5000;
int n,m,a[N],b[N],c[N],f[N][N];
main()
{
cin>>n>>m,m+=n;
for(int i=n;i;i--)
cin>>a[i];
for(int i=n;i;i--)
cin>>b[i];
memset(f,0xaf,sizeof(f));
for(int i=1;i<=m;i++)
cin>>c[i],f[i][0]=0;
for(int i=1;i<=n;i++)
{
for(int j=n;j;j--)
f[a[i]][j]=max(f[a[i]][j],f[a[i]][j-1]+c[a[i]]-b[i]);
for(int j=a[i];j<=m;j++)
for(int k=0;k<=n>>(j-a[i]);k++)
f[j+1][k/2]=max(f[j+1][k/2],f[j][k]+k/2*c[j+1]);
}
cout<<f[m][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>
#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 n, ll x, string s) {
ll mi = 0, ma = 0, now = 0;
umll freq;
rep(i,0,n) {
if(s[i] == '0') now += 1;
else now -= 1;
freq[now] += 1;
mi = min(mi,now);
ma = max(ma, now);
}
if(now == 0) return mi <= x and x <= ma ? -1 : 0;
ll res = x == 0;
if(x > ma and now < 0) return 0;
if(x < mi and now > 0) return 0;
if(x > ma) {
ll diff = (abs(x - ma) + abs(now) - 1) / abs(now);
x -= now * diff;
} else if(x < mi) {
ll diff = (abs((mi - x)) + abs(now) - 1) / abs(now);
x -= now * diff;
}
while(mi <= x and x <= ma) {
if(freq.count(x)) res += freq[x];
x -= now;
}
return res;
}
int main() {
Code By Sumfi
cout.precision(12);
ll tc = 1;
in(tc);
rep(i,1,tc+1) {
ll n,x;
string s;
in(n,x,s);
print(solve(n,x,s));
}
return 0;
} | cpp |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | /* بسم الله الرحمن الرحيم */
#include <bits/stdc++.h>
using namespace std;
#define Ma3rof ios_base::sync_with_stdio(false);cin.tie(NULL);
#define int long long
void solve() {
int n, l, r;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int c = 0;
for (int i = 0; i < n; ++i) {
if (a[i] >= c) {
l = i;
c++;
} else {
break;
}
}
c = 0;
for (int i = n - 1; i >= 0; --i) {
if (a[i] >= c) {
r = i;
c++;
} else {
break;
}
}
if (l >= r) {
cout << "YES\n";
} else {
cout << "NO\n";
}
}
signed main() {
Ma3rof
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t = 1;
cin >> t;
while (t--) {
/* وما تدري نفس ماذا تکسب غدا وما تدري نفس باي ارض تموت */
solve();
}
return 0;
}
| cpp |
1286 | C2 | C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"hashing",
"interactive",
"math"
] | #include <bits/stdc++.h>
#define ll long long
#define pb push_back
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n;
cin >> n;
int l, r;
switch(n%4)
{
case 0:
l = n/2+1;
r = n/2-1;
break;
case 1:
l = n/2+1;
r = n/2;
break;
case 2:
l = n/2+2;
r = n/2-2;
break;
case 3:
l = n/2;
r = n/2+1;
}
if(n==2)
{
l = 1;
r = 1;
}
vector<vector<int>> L(l+1, vector<int>(26, 0)), R(r+1, vector<int>(26, 0)), N(n+1, vector<int>(26, 0));
vector<string> left, right, all;
if(l>1)
{
cout << "? 1 " << l << "\n";
cout.flush();
string x;
for(int i=0; i<l*(l+1)/2; i++)
{
cin >> x;
for(char c: x)
{
L[x.size()][c-97]++;
}
}
vector<int> prev(26, 0);
for(int s=1; s<=(l+1)/2; s++)
{
string S;
vector<int> temp(26, 0);
for(int i=0; i<26; i++)
{
temp[i] += L[1][i] + L[s][i] - L[s+1][i] - prev[i];
prev[i] += temp[i];
while(temp[i]-->0) S += (char) 97+i;
}
//cout << "! " << S << "\n";
left.pb(S);
}
}
else if(l==1)
{
cout << "? 1 " << l << "\n";
cout.flush();
string x;
cin >> x;
left.pb(x+x);
}
if(r>1)
{
cout << "? " << l + 1 << " " << n << "\n";
cout.flush();
string x;
for(int i=0; i<r*(r+1)/2; i++)
{
cin >> x;
for(char c: x)
{
R[x.size()][c-97]++;
}
}
vector<int> prev(26, 0);
for(int s=1; s<=(r+1)/2; s++)
{
string S;
vector<int> temp(26, 0);
for(int i=0; i<26; i++)
{
temp[i] += R[1][i] + R[s][i] - R[s+1][i] - prev[i];
prev[i] += temp[i];
while(temp[i]-->0) S += (char) 97+i;
}
//cout << "! " << S << "\n";
right.pb(S);
}
}
else if(r==1)
{
cout << "? " << l + 1 << " " << n << "\n";
cout.flush();
string x;
cin >> x;
right.pb(x+x);
}
if(n>1)
{
cout << "? 1 " << n << "\n";
cout.flush();
string x;
for(int i=0; i<n*(n+1)/2; i++)
{
cin >> x;
for(char c: x)
{
N[x.size()][c-97]++;
}
}
vector<int> prev(26, 0);
for(int s=1; s<=(n+1)/2; s++)
{
string S;
vector<int> temp(26, 0);
for(int i=0; i<26; i++)
{
temp[i] += N[1][i] + N[s][i] - N[s+1][i] - prev[i];
prev[i] += temp[i];
while(temp[i]-->0) S += (char) 97+i;
}
//cout << "! " << S << "\n";
all.pb(S);
}
}
else if(n==1)
{
cout << "? 1 " << n << "\n";
cout.flush();
string x;
cin >> x;
all.pb(x+x);
}
int now = (l+1)/2;
string ans(n, ' ');
ans[now-1] = left[now-1][0];
for(int i=0; i<n; i++)
{
//cout << now << " " << ans[now-1] << "\n";
if(i%2==0)
{
now = n + 1 - now;
if(all[min(now, n+1-now)-1][0]==ans[n-now]) ans[now-1] = all[min(now, n+1-now)-1][1];
else ans[now-1] = all[min(now, n+1-now)-1][0];
}
else if(now<=l)
{
now = l + 1 - now;
if(left[min(now, l+1-now)-1][0]==ans[l-now]) ans[now-1] = left[min(now, l+1-now)-1][1];
else ans[now-1] = left[min(now, l+1-now)-1][0];
}
else
{
now = n + l + 1 - now;
if(right[min(now, n+l+1-now)-l-1][0]==ans[n+l-now]) ans[now-1] = right[min(now, n+l+1-now)-l-1][1];
else ans[now-1] = right[min(now, n+l+1-now)-l-1][0];
}
}
cout << "! " << ans << "\n";
cout.flush();
}
/*
5
a
as
ask
s
sk
k
b
y
by
askby
askb
skby
ask
skb
kby
as
sk
kb
by
a
s
y
k
b
*/
| cpp |
1307 | F | F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n) — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105) — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi) — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below. | [
"dfs and similar",
"dsu",
"trees"
] | #include <cstdio>
#include <vector>
#include <iostream>
#include <queue>
using namespace std;
const int M = 400005;
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,m,k,q,p[M],d[M],dep[M],fa[M][20];
vector<int> g[M];
void dfs(int u,int p)
{
fa[u][0]=p;
dep[u]=dep[p]+1;
for(int i=1;i<20;i++)
fa[u][i]=fa[fa[u][i-1]][i-1];
for(auto v:g[u]) if(v^p) dfs(v,u);
}
int lca(int u,int v)
{
if(dep[u]<dep[v]) swap(u,v);
for(int i=19;i>=0;i--)
if(dep[fa[u][i]]>=dep[v])
u=fa[u][i];
if(u==v) return u;
for(int i=19;i>=0;i--)
if(fa[u][i]^fa[v][i])
u=fa[u][i],v=fa[v][i];
return fa[u][0];
}
int jump(int x,int y)
{
for(int i=19;i>=0;i--)
if(y&(1<<i)) x=fa[x][i];
return x;
}
int find(int x)
{
if(x!=p[x]) p[x]=find(p[x]);
return p[x];
}
void bfs()
{
queue<int> q;
for(int i=1;i<2*n;i++)
p[i]=i,d[i]=-1;
for(int i=1;i<=k;i++)
{
int u=read();
d[u]=0;q.push(u);
}
while(!q.empty())
{
int u=q.front();q.pop();
if(d[u]==m) break;
for(int v:g[u])
{
p[find(v)]=find(u);
if(d[v]==-1)
{
d[v]=d[u]+1;
q.push(v);
}
}
}
}
signed main()
{
n=read();m=read();k=read();
for(int i=1;i<n;i++)
{
int u=read(),v=read();
g[u].push_back(n+i);g[n+i].push_back(u);
g[v].push_back(n+i);g[n+i].push_back(v);
}
dfs(1,0);bfs();
q=read();
while(q--)
{
int u=read(),v=read(),x=lca(u,v);
int d=dep[u]+dep[v]-2*dep[x];
if(d<=2*m) {puts("YES");continue;}
int A=dep[u]-dep[x]>=m?find(jump(u,m)):find(jump(v,d-m));
int B=dep[v]-dep[x]>=m?find(jump(v,m)):find(jump(u,d-m));
if(A==B) puts("YES");
else puts("NO");
}
} | 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"
] | // practice with Dukkha
#include <algorithm>
#include <iostream>
using namespace std;
const int N = 1000;
const int di[] = { -1, 1, 0, 0 };
const int dj[] = { 0, 0, -1, 1 };
const char dd[] = { 'D', 'U', 'R', 'L' };
int ii[N][N], jj[N][N];
char cc[N][N + 1];
int n;
void dfs(int i, int j) {
for (int h = 0; h < 4; h++) {
int i_ = i + di[h];
int j_ = j + dj[h];
if (0 <= i_ && i_ < n
&& 0 <= j_ && j_ < n
&& !cc[i_][j_]
&& ii[i][j] == ii[i_][j_]
&& jj[i][j] == jj[i_][j_]) {
cc[i_][j_] = dd[h];
dfs(i_, j_);
}
}
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
int i_, j_; cin >> i_ >> j_, i_--, j_--;
ii[i][j] = i_;
jj[i][j] = j_;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if (cc[i][j])
continue;
int i_ = ii[i][j];
int j_ = jj[i][j];
if (i_ == i && j_ == j) {
cc[i][j] = 'X';
dfs(i, j);
} else if (i_ == -2) {
int h = 0;
while (h < 4) {
i_ = i + di[h];
j_ = j + dj[h];
if (0 <= i_ && i_ < n && 0 <= j_ && j_ < n && ii[i_][j_] == -2)
break;
h++;
}
if (h == 4) {
cout << "INVALID\n";
return 0;
}
cc[i][j] = dd[h ^ 1];
cc[i_][j_] = dd[h];
dfs(i, j);
dfs(i_, j_);
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (!cc[i][j]) {
cout << "INVALID\n";
return 0;
}
cout << "VALID\n";
for (int i = 0; i < n; i++) {
cc[i][n] = '\0';
cout << cc[i] << '\n';
}
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>
#include <iostream>
#include <algorithm>
#define ll long long int
#define pb push_back
using namespace std;
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
bool check_prime(int n) {
bool is_prime = true;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
is_prime = false;
}
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
is_prime = false;
break;
}
}
return is_prime;
}
int main(){
int n,k;
cin >> n;
int aux = 0, diff = 0;
vector<int> l, suporte;
while(n--){
int a,b;
cin >> a >> b;
if(a%b==0){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
}
return 0;
} | cpp |
13 | D | D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7 | [
"dp",
"geometry"
] | // 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
struct point {
long long x = 0;
long long y = 0;
point() {
}
point(long long _x, long long _y) {
x = _x;
y = _y;
}
point operator-(point p2) {
return point(x - p2.x, y - p2.y);
}
long long operator^(point p2) {
return x * p2.y - y * p2.x;
}
};
ostream& operator<<(ostream &out, point p) {
out << "(" << p.x << ", " << p.y << ")";
return out;
}
bool cmpx(point p1, point p2) {
return p1.x < p2.x;
}
const int ms = 5e2 + 20;
point a[ms];
point b[ms];
int low1[ms];
int low2[ms][ms];
void just_do_it() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i].x >> a[i].y;
}
for (int i = 1; i <= m; i++) {
cin >> b[i].x >> b[i].y;
}
sort(a + 1, a + n + 1, cmpx);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
low1[i] += (a[i].x == b[j].x) && (b[j].y < a[i].y);
}
}
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
int s = 0;
for (int k = 1; k <= m; k++) {
s += (a[i].x <= b[k].x) && (b[k].x <= a[j].x) && (((b[k] - a[i]) ^ (a[j] - a[i])) > 0);
}
low2[i][j] = low2[j][i] = s;
}
}
int res = 0;
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
for (int k = j + 1; k <= n; k++) {
if (low2[i][j] + low2[j][k] - low1[j] == low2[i][k]) {
res++;
}
}
}
}
cout << res;
}
// END MAIN CODE | 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>
typedef long long ll;
typedef unsigned long long ull;
#define rep(i, a, b) for(int i = (a); i <= (b); i ++)
#define per(i, a, b) for(int i = (a); i >= (b); i --)
#define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt)
using namespace std;
typedef pair<int, int> pii;
#define mp make_pair
#define fi first
#define se second
#define eb emplace_back
inline int read() {
int x = 0, f = 1; char c = getchar();
while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar();
while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar();
return x * f;
}
const int N = 3010;
int n, dis[N][N], siz[N][N], par[N][N];
vector<int> g[N];
int t; pii arc[N * N]; ll f[N][N];
void dfs(int u, int fa, int tp) {
par[tp][u] = fa, siz[tp][u] = 1, dis[tp][u] = dis[tp][fa] + 1;
for(int v : g[u]) if(v != fa) dfs(v, u, tp), siz[tp][u] += siz[tp][v];
}
void push(int x, int y, ll v) {if(x > y) swap(x, y); f[x][y] = f[x][y] > v ? f[x][y] : v;}
int main() {
n = read();
rep(i, 2, n) {int u = read(), v = read(); g[u].eb(v), g[v].eb(u);}
rep(i, 1, n) dfs(i, 0, i);
rep(i, 1, n) rep(j, i + 1, n) arc[++ t] = mp(i, j), f[i][j] = 1;
sort(arc + 1, arc + t + 1, [](pii x, pii y) {return dis[x.fi][x.se] > dis[y.fi][y.se];});
ll ans = 0;
rep(i, 1, t) {
int x = arc[i].fi;
int y = arc[i].se;
ans = max(ans, f[x][y]);
if(dis[x][y] == 1) continue;
int nx = par[y][x];
push(nx, y, f[x][y] + siz[nx][y] * siz[y][nx]);
int ny = par[x][y];
push(x, ny, f[x][y] + siz[x][ny] * siz[ny][x]);
}
printf("%lld\n", ans);
return 0;
}
| 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>
using namespace std;
#ifdef DEBUG
#include "debug.h"
#else
#define debug(x) void(37)
#endif
#define lsb(x) ((x)&(-x))
#define all(x) x.begin(),x.end()
#define setprec(n) cout << fixed << showpoint;cout << setprecision(n);
typedef long long ll;
typedef long double ld;
const ld eps = 1e-10;
const ll MOD1 = 1e9+7;//1000000007
const ll MOD2 = 998244353ll;
const ll LINF = (ll)1e18;
const int IINF = (int)1e9;
#define int ll
int v[] = {1, 0, 0, -1};
int h[] = {0, 1, -1, 0};
// {i + v[k], j + h[k]}
char chr[] = {'D', 'R', 'L', 'U'};
char rev[] = {'U', 'L', 'R', 'D'};
void solve(){
int n;
cin >> n;
vector<vector<pair<int,int>>> arr(n+2, vector<pair<int,int>>(n+2, {-2, -2}));
for(int i = 1;i <= n;i++) for(int j = 1;j <= n;j++)
cin >> arr[i][j].first >> arr[i][j].second;
set<pair<int,int>> xses;
vector<vector<char>> ans(n+2, vector<char>(n+2, '.'));
for(int i = 1;i <= n;i++) for(int j = 1;j <= n;j++) if(arr[i][j].first != -1){
ans[arr[i][j].first][arr[i][j].second] = 'X';
xses.insert(arr[i][j]);
}
for(int i = 1;i <= n;i++) for(int j = 1;j <= n;j++) if(ans[i][j] == 'X' && (arr[i][j].first != i || arr[i][j].second != j)){
cout << "INVALID" << "\n";
return;
}
for(int i = 1;i <= n;i++) for(int j = 1;j <= n;j++) if(arr[i][j].first == -1){
for(int k = 0;k < 4;k++){
int ti = i + v[k];
int tj = j + h[k];
if(arr[ti][tj].first == -1){
ans[i][j] = chr[k];
}
}
}
queue<pair<int,int>> q;
for(auto it:xses) q.push(it);
while(q.size()){
pair<int,int> cur = q.front();
q.pop();
for(int k = 0;k < 4;k++){
int ti = cur.first + v[k];
int tj = cur.second + h[k];
if(ans[ti][tj] == '.' && (arr[ti][tj].first == arr[cur.first][cur.second].first && arr[ti][tj].second == arr[cur.first][cur.second].second)){
ans[ti][tj] = rev[k];
q.push({ti, tj});
}
}
}
for(int i = 1;i <= n;i++) for(int j = 1;j <= n;j++) if(ans[i][j] == '.'){
cout << "INVALID" << "\n";
return;
}
cout << "VALID" << "\n";
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
cout << ans[i][j];
}cout << "\n";
}
}
signed main(){
ios_base::sync_with_stdio(false); cin.tie(NULL);
mt19937 mt(time(NULL));
//setprec(10);
//freopen("sleepy.in", "r", stdin);
//freopen("in.txt", "w", stdout);
int t = 1;
//cin >> t;
for(int i = 1;i <= t;i++)
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: 97154482
#include <bits/stdc++.h>
#define int long long
#define se second
using namespace std;
const int INF=5e5+5;
int t,n,m,a[INF];
map <set<int>,int> M;
set <int> s[INF];
void solve() {
M.clear();
cin>>n>>m;
for (int i=1;i<=n;i++) cin>>a[i],s[i].clear();
for (int i=1;i<=m;i++) {
int x=0,y=0;
cin>>x>>y;
s[y].insert(x);
}
for (int i=1;i<=n;i++)
if (s[i].size()) M[s[i]]+=a[i];
int ans=0;
for (map <set<int>,int>::iterator it=M.begin();it!=M.end();it++)
ans=__gcd(ans,it->se);
cout<<ans<<"\n";
}
signed main()
{
ios::sync_with_stdio(false);
cin>>t;
while (t--) solve();
return 0;
} | 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"
] | //#pragma GCC optimize("Ofast,unroll-loops")
//#pragma GCC target("avx,fma,sse4.2")
#include<bits/stdc++.h>
using namespace std;
#define f first
#define s second
typedef long long ll;
typedef long double ld;
typedef pair<int, pair<int, int>> ft;
const ld PI = acos(-1);
const int maxn = 2e3+20;
const ll inf = 1e18;
const int mod = 998244353;
int n, m;
ll dp[maxn][maxn], dp2[maxn*2][maxn], dp3[maxn];
ll C[2*maxn], cost[maxn], A[maxn];
ll eval(int mask, int pos){
ll re = 0;
for(int i = 0; i < 11; i++){
if(mask&(1<<i))re+=C[pos+i];
}
return re;
}
signed main(){
ll ans = 0;
cin >> n >> m;
//assert(n <= 200 && m <= 200);
for(int i = 1; i <= n; i++)cin >> A[i];
for(int i = 1; i <= n; i++)cin >> cost[i];
for(int i = 1; i <= n+m; i++){
for(int k = 1; k <= n; k++){
dp2[i][k] = -inf;
}
cin >> C[i];
}
for(int i = n; i > 0; i--){
for(int k = 1; k <= n; k++)dp[i][k] = -inf;
dp[i][1] = C[A[i]] - cost[i];
for(int j = i+1; j <= n; j++){
if(A[i] - A[j] >= 11)dp[i][1] = max(dp[i][1], dp3[j] + C[A[i]] - cost[i]);
}
for(int j = A[i]; j > max(0LL, A[i]-11); j--){
for(int k = 1; k <= n; k++){
int nmask = k>>(A[i] - j);
dp[i][nmask+1] = max(dp[i][nmask+1], dp2[j][k] + eval(nmask^(nmask+1), A[i]) - cost[i]);
}
}
dp3[i] = -inf;
for(int k = 1; k <= n; k++){
dp2[A[i]][k] = max(dp2[A[i]][k], dp[i][k]);
dp3[i] = max(dp3[i], dp[i][k]);
ans = max(ans, dp[i][k]);
}
}
cout << ans;
}
| cpp |
1310 | F | F. Bad Cryptographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: Let's fix a finite field and two it's elements aa and bb. One need to fun such xx that ax=bax=b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 22k−122k−1 for some positive integer kk . Bitwise exclusive or (⊕⊕) operation is used as addition. One of ways to define multiplication operation (⊙⊙) is following properties: 0⊙a=a⊙0=00⊙a=a⊙0=0 1⊙a=a⊙1=a1⊙a=a⊙1=a a⊙b=b⊙aa⊙b=b⊙a a⊙(b⊙c)=(a⊙b)⊙ca⊙(b⊙c)=(a⊙b)⊙c a⊙(b⊕c)=(a⊙b)⊕(a⊙c)a⊙(b⊕c)=(a⊙b)⊕(a⊙c) If a=22na=22n for some integer n>0n>0, and b<ab<a, then a⊙b=a⋅ba⊙b=a⋅b. If a=22na=22n for some integer n>0n>0, then a⊙a=32⋅aa⊙a=32⋅a. For example: 4⊙4=64⊙4=6 8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13.8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13. 32⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=14132⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=141 5⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=85⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans;}multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a⊙k=a⊙a⊙⋯⊙ak timesa⊙k=a⊙a⊙⋯⊙a⏟k times.You need to analyze the proposed scheme strength. For pairs of numbers aa and bb you need to find such xx, that a⊙x=ba⊙x=b, or determine that it doesn't exist. InputIn the first line of input there is single integer tt (1≤t≤1001≤t≤100) — number of pairs, for which you need to find the discrete logarithm.In each of next tt line there is a pair of integers aa bb (1≤a,b<2641≤a,b<264). OutputFor each pair you should print one integer xx (0≤x<2640≤x<264), such that a⊙x=ba⊙x=b, or -1 if no such x exists. It can be shown, that if any such xx exists, there is one inside given bounds. If there are several good values, you can output any of them. ExampleInputCopy7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
OutputCopy1
1
2
4
-1
6148914691236517205
68943624821423112
| [
"math",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const ull l = 0xFFFFFFFFFFFFFFFF;
const int p[] = {3, 5, 17, 257, 641, 65537, 6700417}, m[] = {1, 2, 6, 16, 25, 256, 2588}, I[] = {2, 2, 1, 32, 590, 16384, 3883315};
ull F[65][65], T[65][257][257], a, b, ans; int t, r[7];
namespace HT {
const int C = 65537;
int nd, head[C], nxt[C], val[C], top, stk[C]; ull key[C];
void ins(ull x, int id) { ull y = x & C - 2; if (! head[y]) stk[++top] = y; nxt[++nd] = head[y], head[y] = nd, key[nd] = x, val[nd] = id; }
int get(ull x) { for (int e=head[x&C-2]; e; e=nxt[e]) if (key[e] == x) return val[e]; return - 1; }
void clear() { nd = 0; while (top) head[stk[top--]] = 0; }
}
ull mul(ull, ull) ;
ull mul2(ull a, ull b) {
if (a == 1 || b == 1) return a * b;
if (a < b) swap(a, b);
int x = __builtin_ctzll(a), y = __builtin_ctzll(b), z = 1 << 63 - __builtin_clz(x);
if (y & z) return mul((1ull << z >> 1) * 3, mul2(a >> z, b >> z));
return mul2(a >> z, b) << z;
}
ull mul(ull a, ull b) {
ull x, y, c = 0;
for (ull i=a; i; i^=x) {
x = 1ull << __builtin_ctzll(i);
for (ull j=b; j; j^=y)
y = 1ull << __builtin_ctzll(j), c ^= mul2(x, y);
} return c;
}
ull prod(ull a, ull b) {
ull c = 0;
for (int i=0; i<8; i++)
for (int j=0; j<8; j++)
c ^= T[i<<3|j][a>>(i<<3)&255][b>>(j<<3)&255];
return c;
}
ull qpow(ull x, ull y) {
ull t = 1;
for (; y; y>>=1) {
if (y & 1) t = prod(t, x);
x = prod(x, x);
} return t;
}
int main() {
for (int x=0; x<64; x++)
for (int y=0; y<64; y++)
F[x][y] = mul2(1ull << x, 1ull << y);
for (int i=0; i<8; i++)
for (int j=0; j<8; j++) {
for (int x=0; x<8; x++)
for (int y=0; y<8; y++)
T[i<<3|j][1<<x][1<<y] = F[i<<3|x][j<<3|y];
for (int a=1; a<256; a++)
for (int b=1; b<256; b++)
if (a^a&-a) T[i<<3|j][a][b] = T[i<<3|j][a&-a][b] ^ T[i<<3|j][a^a&-a][b];
else if (b^b&-b) T[i<<3|j][a][b] = T[i<<3|j][a][b&-b] ^ T[i<<3|j][a][b^b&-b];
}
cin >> t;
while (t --) {
scanf ("%llu%llu", &a, &b), ans = 0;
for (int i=0; i<7; i++) {
ull A = qpow(a, l / p[i]), B = qpow(b, l / p[i]), Am = qpow(A, m[i]), P = 1; int res = -1;
for (int j=0; j<m[i]; j++)
HT :: ins(B, j), B = prod(B, A);
for (int j=0, u=(p[i]-1)/m[i]; j<=u; j++) {
int k = HT :: get(P);
if (~ k) { res = (j * m[i] - k + p[i]) % p[i]; break; }
P = prod(P, Am);
} HT :: clear();
if (~ res) r[i] = res;
else { puts ("-1"); goto E; }
}
for (int i=0; i<7; i++) {
ull d = (1ull * r[i] * I[i]) % p[i] * (l / p[i]);
ans >= l - d ? ans -= l - d : ans += d;
} assert (qpow(a, ans) == b);
printf ("%llu\n", ans); E : ;
}
} | 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"
] | #include <bits/stdc++.h>
using namespace std;
int n,c[2048],father,child[2048],a[2048];
vector<int> v[2048];
void dfs1(int now, int fa, int tmp)
{
if(now != fa) a[now] += tmp;
if(a[now] >= c[fa] + 1 && now != fa) a[now] ++;
for(int i = 0 ; i < v[now].size() ; i ++)
{
dfs1(v[now][i],fa,tmp);
if(now == fa) tmp += child[v[now][i]] + 1;
}
}
int dfs(int idx)
{
for(int i = 0 ; i < v[idx].size() ; i ++)
{
int tmp = dfs(v[idx][i]);
child[idx] += tmp;
}
dfs1(idx,idx,0);
a[idx] = c[idx] + 1;
return child[idx] + 1;
}
int main()
{
cin >> n;
for (int i = 1 ; i <= n ; i ++)
{
int f;
cin >> f >> c[i];
if (f == 0) father = i;
v[f].push_back(i);
}
dfs(father);
int flag = 0;
for(int i = 1 ; i <= n ; i ++) if(c[i] > child[i]) flag = 1;
if(flag == 0)
{
cout << "YES" << endl;
for(int i = 1 ; i <= n ; i ++) cout << a[i] << " ";
}
else cout << "NO";
return 0;
}
| cpp |
1307 | F | F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n) — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105) — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi) — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below. | [
"dfs and similar",
"dsu",
"trees"
] | #include<bits/stdc++.h>
using namespace std;
const int N=4e5+10;
const int M=N*2;
int n,m,k;
int tot;
int head[N],ver[M],ne[M];
void add(int x,int y)
{
ver[++tot]=y;
ne[tot]=head[x];
head[x]=tot;
}
int d[N];
int f[N][25];
void dfs(int x,int fath)
{
d[x]=d[fath]+1;
for(int i=1;i<=20;i++) f[x][i]=f[f[x][i-1]][i-1];
for(int i=head[x];i;i=ne[i])
{
int y=ver[i];
if(y==fath) continue;
f[y][0]=x;
dfs(y,x);
}
}
int lca(int x,int y)
{
if(d[x]<d[y]) swap(x,y);
for(int i=20;i>=0;i--)
{
if(d[f[x][i]]>=d[y])
x=f[x][i];
}
if(x==y) return x;
for(int i=20;i>=0;i--)
{
if(f[x][i]!=f[y][i])
x=f[x][i],y=f[y][i];
}
return f[x][0];
}
int dis[N];
int fa[N];
int get(int x)
{
if(x==fa[x])return x;
return fa[x]=get(fa[x]);
}
void vacation()
{
queue<int>q;
memset(dis,-1,sizeof(dis));
for(int i=1;i<=k;i++)
{
int x;
scanf("%d",&x);
dis[x]=0;
q.push(x);
}
while(q.size())
{
int x=q.front();q.pop();
if(dis[x]==m) break;
for(int i=head[x];i;i=ne[i])
{
int y=ver[i];
fa[get(y)]=get(x);
if(dis[y]==-1)
{
dis[y]=dis[x]+1;
q.push(y);
}
}
}
}
int move(int x,int len)
{
for(int i=20;i>=0;i--)
{
if((1<<i)<=len)
{
len-=(1<<i);
x=f[x][i];
}
}
return x;
}
int main(){
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=n*2;i++) fa[i]=i;
for(int i=1;i<n;i++)
{
int x,y;
cin>>x>>y;
add(x,n+i);
add(y,n+i);
add(n+i,x);
add(n+i,y);
}
dfs(1,0);
vacation();
int q;
cin>>q;
while(q--)
{
int x,y;
scanf("%d%d",&x,&y);
int z=lca(x,y);
int len=d[x]+d[y]-2*d[z];
if(len<=2*m) printf("YES\n");
else
{
int ans1=(m<=(d[x]-d[z]))?get(move(x,m)):get(move(y,len-m));
int ans2=(m<=(d[y]-d[z]))?get(move(y,m)):get(move(x,len-m));
if(ans1==ans2) printf("YES\n");
else printf("NO\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"
] | #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int MOD = 1e9+7;
int bm(int b, int p) {
if(p==0) return 1;
int r=bm(b,p>>1);
if(p&1) return (((r*r)%MOD)*b)%MOD;
return (r*r)%MOD;
}
mt19937_64 rng((int)std::chrono::steady_clock::now().time_since_epoch().count());
int rnd(int x, int y) {
return uniform_int_distribution<int>(x,y)(rng);
}
const int MAXN = 5e5+10;
int a[MAXN];
int dsu[MAXN];
int set_of(int u) {
if(dsu[u]==u) return u;
return dsu[u]=set_of(dsu[u]);
}
void union_(int u,int v) {
dsu[set_of(u)]=set_of(v);
}
void solve() {
int n, m;
scanf("%lld %lld", &n, &m);
for(int i=1; i<=n; i++)dsu[i]=i;
int c[n+1];
for(int i=1; i<=n; i++) scanf("%lld", &c[i]);
int h[n+1]; for(int i=1; i<=n; i++)h[i]=0;
int deg[n+1];
for(int i=1;i<=n;i++)deg[i]=0;
for(int i=1; i<=m; i++) {
int32_t u,v; scanf("%d %d", &u, &v);
h[v]^=a[u];
deg[v]++;
}
map<int,int32_t>ok;
for(int i=1; i<=n; i++) {
if(ok.count(h[i])) {
union_(ok[h[i]],i);
}
else ok[h[i]]=i;
}
int sum[n+1];
for(int i=1;i<=n; i++)sum[i]=0;
for(int i=1; i<=n; i++) {
sum[set_of(i)] += c[i];
}
int g = 0;
for(int i=1; i<=n; i++) {
if(deg[i]==0)continue;
if(sum[i]>0) {
g = (g==0 ? sum[i] : gcd(g, sum[i]));
}
}
cout<<g<<"\n";
}
int32_t main() {
for(int i=1; i<MAXN; i++) a[i] = rnd(0, LLONG_MAX);
int32_t t;
scanf("%d", &t);
while(t--)solve();
} | cpp |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | #include<bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// #define pbds \
// tree<pair<int, int>, null_type, less<pair<int, int> >, \
// rb_tree_tag, tree_order_statistics_node_update>
// using namespace __gnu_pbds;
// using namespace __gnu_cxx;
using namespace std;
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD 1000000007
#define MOD1 998244353
#define INF LLONG_MAX
#define nline "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
// typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update > pbds; // find_by_order, order_of_key
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
/****************************************************************************************************************************/
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3
ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b
ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}
bool revsort(ll a, ll b) {return a > b;}
ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}
void google(int t) {cout << "Case #" << t << ": ";}
vector<ll> primeFactors(ll n){vector<ll>ret;while (n % 2 == 0){ret.pb(2);n = n/2;}for (ll i = 3; i <= sqrt(n); i = i + 2){while (n % i == 0){ret.pb(i);n = n/i;}}if (n > 2){ret.pb(n);}return ret;}
vector<ll> prime(ll n) {ll*arr = new ll[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (ll j = (ll(i) * ll(i)); j <= n; j += i)arr[j] = 1;} return vect;}
vector<ll>divisor(ll n){vector<ll>res;for (ll i=1; i<=sqrt(n); i++){if (n%i == 0){if (n/i == i)res.pb(i);else{res.pb(i);res.pb(n/i);} }}return res;}
vector<ll>sieve(){ll MAXN=1e7;vector<ll>spf(MAXN);spf[1] = 1;for (ll i=2; i<MAXN; i++)spf[i] = i;for (ll i=4; i<MAXN; i+=2)spf[i] = 2;for (ll i=3; i*i<MAXN; i++){if (spf[i] == i){for (ll j=i*i; j<MAXN; j+=i)if (spf[j]==j)spf[j] = i;}}return spf;}
vector<ll> Divisors(ll n){vector<ll>res; for(ll i=1;i<=sqrt(n);i++){if (n%i == 0){if (n/i == i)res.pb(i);else{res.pb(i);res.pb(n/i);}}}return res;}
// vector<ll>countSmallerRight(vector<ll>arr){pbds s;ll n = arr.size();vector<ll> ans;for (ll i = n - 1; i >= 0; i--) {if (i == n - 1) { ans.push_back(0);}else {ans.push_back(s.order_of_key({ arr[i], i }));}s.insert({ arr[i], i });}reverse(ans.begin(), ans.end());return ans;}
ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m
ll modPower(ll x,ll y){ll res = 1;x = x % MOD;if (x == 0)return 0;while (y > 0) {if (y & 1)res = (res * x) % MOD;y = y / 2;x = (x * x) % MOD;}return res;}
ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))
ll modFact(ll n){if (n >= MOD)return 0;ll result = 1;for (ll i = 1; i <= n; i++)result = (result * i) % MOD;return result;}
ll power(ll x,ll y){ll res = 1;while (y > 0) {if (y & 1)res = res * x;y = y >> 1;x = x * x;}return res;}
void precision(ll a) {cout << setprecision(a) << fixed;}
/*prime-O(n*log(log(n)));
smallest prime factor-O(log(n));
a%(b+c)=0 <=> a%c = b%c */
/*--------------------------------------------------------------------------------------------------------------------------*/
const int N = 1e5+1;
vector<ll>vec(11ll);
void se()
{
for(ll i=1;i<11ll;i++)
{
vec[i]=power(10,i)-1;
}
debug(vec);
}
void solve()
{
ll a,b; cin>>a>>b;
ll lb = lower_bound(all(vec),b)-vec.begin();
if(vec[lb]!=b)lb--;
cout<<a*lb<<endl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("Error.txt", "w", stderr);
#endif
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
fastio();
se();
ll test; cin>>test; while(test--) {solve();}
// solve();
return 0;
} | cpp |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | //#pragma GCC optimize("unroll-loops")
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,abm,mmx,popcnt")
#define _CRT_SECURE_NO_WARNINGS
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,sse4.1,sse4.2,abm,mmx,avx,avx2,popcnt,tune=native")
//#pragma comment(linker,"/STACK:256777216")
/*
MMMMMMMMNNNNNNNNNNNNNNNNNNmNNNNNNNNNNNmmmmmmmmNNMMMMNMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMNNMMMNMMMMMMMMMMMMMMMMMMMMMMNNMMNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMNNNNNNNNNNNmNNNMMMMMMMMMMMMNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMNNNNNNNNNNNNNNNNmmNNNNNNNNMMMMMMMMNmNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMNNNNNMMNNNNNNNNNNNNNNNNNNNNNMMMMMMMMNmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMNNNNNMMNNNNNNmNNNNNNNMMMMMMMMMMMMMMMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMNNNNNNNNNNNNNmNNNNNNNNNNMMMMMMMMMMMMMMmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMNNNNNNNNNNNNNmNNNmNMMMMmMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMNNNNNNNNNNmmmmmNNNNMMNMMNNMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNNNNNmmmmdddddmNNNNMNNMMNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMNNMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNNNmmmddddhhhdNNNmmMMMMNmmNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMNMMMMMMMMMNMMMMMMMMMMMMMMMNMMNMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNNmmddddhhhhhdmNNmNmNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMNMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMNMMMMMMMMMMMMMMMNMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNmmddddhhhhhhhdNNmNNNNNNNNmmNNNNNNNNNNMMMMMMMMMMMMNMMNMMMMNMMMMMNMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMNMMMMMMMMMMMMMMNMNMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNmddhhhhhhhyyyhmmNmmmNNMMMMNmNNNNNNNNNMMMMMMMMMMMNMMMNMMMMNMMMMNNMMMMNMMMNMMMMMMMMMMMMMMMMNMMNMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMNNMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNmdhhhhhhyyysssshmdmNMMNNNNNNNmmmmmmmmMMMMMMMMMMMMNMMMNMMMMMMMMMNNMMMMNMMMNMMMMMMMMMMMMMMMMNMMNMMMNMMMNMMMNMMMMMMMMNMMMMMMMMMMMMMMNMMMMMMNNNNNNNNNMMNNNNNNNNNNNNNNNMM
MNNNNmdhyyyyyyysssssssdNNNNNNNNNNNNNNNNNNNmMMMMMMMMMMMMNMMMNMMMNMMMMMNNMMMMNMMMMMMMMMMMMMMMMMMMMNMMNMMMNMMMNMMMMNMMMMMMMNNNNMMMMMMMMMMMNMMMMMMMmmmmmNNNNmmmmmmmmmmmmmmmNNN
MMNNmmdhsoooooooooooooohmNNNNNNNNNNNNNNNdNNMMMMMMMMMMMMNMMMNMMMNNMMMMNMNMMMNMMMMNMMMMMMMMMMMMMMMNMMNMMMNMMMNMMMMMNMMMMMMNNNMNNNMMMMMMMNmMMMMMMMmdddmmmdddddddddddddddddmmN
MNNmmmdhsooooooooooo++ooshmNNNNNNNNNNmhysNNMMMMMMMMMMMNNMMMNMMMNNMMMMNMNMMMNMMMMNMMMMMMMMMMMMMMNMMNMMMNMMMMNNNMMMNMMMMMMNNNMMMMNNMMNNNMdMMMMNMMNmddddddddddddhhhhhhhhddmmN
NmmddddhhhhhhhhhhhhyyyyyyyyhdddmmdddhsoosdNMMMMMMMMMMMNNMMMNMMMNNMMNNmNNMMMNNMMMNMMMMMMMMMMMMMMNMMNMMMNMNNmNMMMMMMNMMMMMMNNNMMmNNNNMMMMmNMMMNNMNmNNNNNNNNNNNmmmmmmmmmNNNMM
mmdddddddddddddddddddhhyyyyyyyhhhyyyoooosdNMMMMMMMMMMMNNMMMNMMMNNMMMMNMNmNNMNMMMNMMMMMMMMMMMMMNNMNNMMNNNNNNMMMMMMMMNMMMMMNMMNMMmNNMmmMmNNMMMMNMMNNNNNNNNNNNNNNNNNNNNNNMMMM
mmddddhdddddddddddddddhhhyyyhhhysssoooosshNMMMMMMMMMMMNNMMMNMMMNNMMMMNMMNMMNNmNNNmMMMMMMMMMMMMNMNmNNNNMMMNMMMMMMMMMMNMMMMNMMMNNMMMMNMNNMNMMMMNNMNNNNNNNNNNNNmmmNNNNNNMMMMM
dddddhhhdddddddddddddddhhhhhhysosyoooosmsyNMMMMMMMMMMMNNMMMNMMMMNNMMMdMNNNMMMNNMMmNMMMMMMMMMMNMMNNMMNMMMNNNMNMMMMMMMMNMMMNMMNNNNNMMMmNMMNMMMMMNNNNNNNNNNNNNNmmNNNNNNMMMMMM
dddddhhhddddddddddddddddhhhsoosyhooooodNssNMMMMMMMMMMMNNNMMNNMNmdhhysshmNNNNNMNNMNmMMMMMMMMMNNMNNMMNNNNmNNNmyhddmmNMMMNMMNMNmMNdNMMmNmNMNMMMMMNmMmNNNNNNMMNNNNNNNMMMMMMMMM
dddddhhhddddddddddddddddysoooyhho++o+sNmosNMMMMMMMMMMMNNNMNdyhhhho////oyssydmmMNNMNNMMMMMMMMNMMNMMMNNNmdhyso++oosssyddNNNNMmMMNMNmNNmMmNmMMMMMMmmNmNNNNNNNNNNNNMMMMMMMMMMM
hdddhhhhhhhddddddddddddsoooyhhho++ssodNmosMMMMMMMMMMMMmNmhddmNMNNy/////+mmy/hNMMMMMMMMMMMMMMMMMMMMMMNmsohdo:::::+mNNdhhmNNNNMMNmNNmNMMNmmMMMMMMNdNmmNNNNNNNNNNMMMMMMMMMMMM
hhhhhyyyhhhhhdddddddddh++shhhho++shooNMdoyMMMMMMMMMMMMmMNdMMMMN+yy+sss++oMMdsmMMMMMMMMMMMMMMMMMMMMMMmyhNhmh+oo++:+MMMMNdNmmNNNNNMMNNmNMdmNMMMMMMNdNmNNNNNNNNMMMMMMMMMMMMMM
hhhhhyyyyhhhhhddddddddy++hhhhs+/+ys+hNNyoyNMMMMMMMMMMMNMMNNMMMh-oshdddyy+NMMNhMMMMMMMMMMMMMMMMMMMMMMdNMM+/yyddhss:NMMMMNMmNMMMMMMMMMNmmdNNNMMMMMNmmNmmNNNMMMMMMMMMMMMMMMMM
hhhhyyyyyyyhhhhddddddhs++hhhy+/:+o+smNNoodMMMMMMMMMMMMNMMMmMMMh-yydhddhhoNMMMNMMMMMMMMMMMMMMMMMMMMMMMMMM/oyddddydoNMMMmNMNMMMMMMMMMMMNNmNNNNNNNNNNdmmmNNNMMMMMMMMMMMMMMMMM
hhhhyyyyyyyhhhhddddddhs++yyo+++///ohNNs+dmNNNNNNNMMMMNNMMMNmMMN/+dhdmmhmhMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMs+hhddhdmmMMMNNMMNNNNNNNNNNNNNNNNNNNNNNNNNmmNmNNMMMMMMMMMMMMMMMMMM
hhhyyyyyyyyhhhhhhhhdhhy//o+/+s////yhNy+yNmNNNNNNNNNNNNNMMMMNNMMNoodNNNdsmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNohNNNmdyNMMNNMMMNNNNNNNNNNNNNNNNNNNNNNNNNmmmNmMMMMMMMMMMMMMMMMMMM
hhhyyyyyyyyyhhhhhhhhhhh+//+sho/::/hhs+yNNmNNNNNNNNNNNNNMMMMMNNNNNmhdmddMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMmdmmmmNNNNNNNNNmNNNNNNNNNNNNNNNNNNNNNNNNNmNmmNMMMMMMMMMMMMMMMMMM
hhhyyyyyhyyhhhhhhhhhhhhhhhhhh+/://+/+hNNNmNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNmNNNNNNNNNNNNNNNmNNNNNNNNNmNNmmMMMMMMMMMMMMMMNMMM
hhyyyyyyhhhhhhhhhhhhhhhhhhhho:/os//smNNNNmNNNNNNNNNNNNmNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMNNMMMMMMMMMMMMMMMMMMMNNNNNNNNNNMNNmNNNNNNNNNNNNNNNmNNNNNNNNNNmNmmmMMMMMMMMMMNNMMMMM
hyyyyyyyhhhhhhhhhhhhhhhhhhho://hhyyNNNNNNmNNNNNNNNNNNNmNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMNmMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNdNNNNNNNNNNNNNNNmNNNNNNNNNNmMMmmNMMMMMMMMNNNMMMMM
yyyyyyyhhhhhhhhhhhhhhhhhhho/:/+hhhhNNNNNmmNNNNNNNNNNNNmNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMNNNNNNNNNNNmmmdNNNNNNNNNNNNNNmmNNNNNNNNNNmNMMmmNMMMMMMMMMMMMMMM
yysyyyyhhhhhhhhhhhhhhhhhho::::ohhhdNNNNNmmNNNNNNNNNNNNmNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNmdNNNNNNNNNNNNNNmmNNmNNNNNNNNmMMNmmNMMMMMMMMMMMMMM
yssyyyyhhyyyyyhhhhhhhhhyo:/o::shhhdNNNNmNmNNNNNNNNNNNNyNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNmsNNNNNNNNNNNNNNmmNNmNNNNNNNNmNNNmmmNNMMMMMMMMMMMN
ssssssyyysssyyyyyyyyyyy+:/so::syyymNNNmmNdNNNNNNNNNNNNhdNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNhsNNNNNNNNNNNNNNmNNNdNNNNNNNNmddddhmdNNNNNMNNNNNNN
oo++++oooooossssssssso/:/os/::+oosNNNNdNNdNNNNNNNNNNNNhymNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNmyyNNNNNNNNNNNNNNmNNNdNNNNNNNNmyyyhhhmdmmmNNmmmmddd
++////++oosssssssssso::/sss:::+++yNNNdNNNdNNNNNNNNNNNNhhyNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNyyyNNNNNNNNNNNNNNdNNNmmmmmmmmmmhdhddddmdddddddhhhhh
////////+ossyysysss+::/ssss::+ssshmNmmNNNdNNNNNNNNNNNNhhhhNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNhhhymNNNNNNNNNNNmmdmmmmdmmmmmmmmdddddmddhddhhhhhhhhh
//:::--:/+ssyyyyys/--+ssssy:-+sssmmmdmmNmdNNNNNNNNNNNNyyhyyNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNhyhhymNNNmmmmmmmmmmymmmmdmmmmmmmmdhhddddhdyhhhhhhhhhh
///::---/+osssyys/--+ssyysy--+sssmmdmmmmmdmmmmmNmNNNmmhssyyymNNNNNNNNNNNNNNNNNNNNNmmmNmmNNmmmmmNNNNNNNNNNNNNNNNNNNNNhssyssmmmmmmmmmmmmmmydmmmhmmmmmmmmdhdddddhhdyyyyhhhhhh
///::--:/+osssss:-:osssssys--+ssymdmmmmdmhmmmmmmmmmmmmhyyyyyohmNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNdyssssssmmmmmmmmmmmmmmshmmmhmmmmmmmddhddddhhyhhyyyyhhhhh
///::--:/osssso--:ssssssyys--+ssyddmmmdmmhmmmmmmmmmmmmhsssssosshmNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNdyssssssssmmmmmmmmmmmmmmsymmmhdddddddddyddhhhhhhhyyyyhhhhh
///::--:/osss+--:sssssssyss--+soydmmmhmmmhmmmmmmmmmmmmhsssssossssydNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNmhsssssosssssmmmmmmmmmmmmddosdddhdddddddddyhhhhhhyyyhsyyhhhhh
////:--:+oss/--/sssssssyyss--+sohdddhddddddmmmmmmmmmmmysssssosssssoshNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNdyosossssosssssddmddddddddddhoodddhhddddddddydhhhyyyyyysyyhhhhh
////:::/+os/../ssssssssysss--/osddddhdddddhdddddddddmdyssssoosssssoossydNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNmysosssoossooooooodddddddddddddsoohdddyddddddhhyhhhhhyyyhsyshddddd
////:::/+o/../sssssssssssss--:sddddyddddddhdddddddddddyooooooooooooooo+syhmmmmmmmmmmmmmmmmmmmmmmmmmmmmhyy+oooooooooo+ooooodddddddddddddooohddhshhhhhhhhhyhhhhhhhhhssdmmmmm
++//:::/+/../sssssssssyssss--:hhddyhhdddddydddddddddddyoooooooooooo+oo+yyysydmmmmmmmmmmmmmmmmmmmmmmdyyyys+oooooo+ooo+oooosdddddddddddhhoo+yhhhshhhhhhhhhshhhhhyyyysyyddddd
++//::://../ssyyyyyysyyssss:.-hhhhyyhhdddyyhddddddddddyoooo+ooooooo+oo+sssysssyhdmmmmmmmmmmmmmmdhysssssso+oooooo+ooo+ooooshdddhhhhhhhhy+++yhhyohhhhhhhhhsyyyyysssysosyyhhh
+++/:://..:ssyyyyyyyyyyyyss/.-hhhsyyhhhhhyhyhhhhhhhddhyoooo+ooooooyhhyosssssssssssyhdmmmmmmdhyssssssssssoooo+ooo+o+++++++shhhhhhhhhhhhs+++shhsshhhhyyyyyossssssssyyosoyyhh
+++////..-ossyyyyyyyhyyyyyy+..shyyshhhhhhyhshhhhhhhhhhy++++++++ooddddddhssssssssssssssyhhysssssssssssoyhdddhyo++/++++++++shhhhhhhhhhhy++++syysoyyyyyyyyyosssssssssysooyyhh
+++///-..+ossyyyyyyyhhhhyyss..oyssyhhhhhhyhshhhhhhhhhhy++++/++++++/:/oyddyossssssssssssossssssssssssoydho+++sy++/++/+++++yhhhhhhhhhyys/+//syyooyyyyyyyyyosssssssssysossyhh
+++//-../ooossyyyyyyyhyyysyy-.:oysyyyyyyyyysyhhhhhhhhhy++++/++++--+oo/-+hdyssyyyyssoooooooooooossssshds--///::://++/++++/yyyyyyyyyyyy+////oyyooyyyyyyyysosssssssssyysooyyh
++++/...+ooossyyyyyyyyyyssyy/..ooyyyyyyysyyysyyyyyyyyyy+++//++++:yhddhs-:yhhhhhhhddhooooooooyhhhhhhhho-+hhhhhy://///////+yyyyyyyyyyys/////oyssoyssssssss+ssssssssssyy+osyy
////.``/+++ossyyyyyyyyyyosss+..+oyyyyyyyoyyysyyyyyyyyyy//////////yhhhhhy--:---:://shh+oooo+yhhs/:::::-+hhhhhh+//////////+yyyyyyyyyyyo/////osoyosssssssss+ssssssssyyyyoooyy
/::-``-///++oossssssyyyosssso..-ssssyyyyoyyyssyyyyyyyyy//////////ohhhhhhyssoooo+:..+hy+oo+yhy:.:oyhhyshhhhhyo://////////+yyyyyyyysss/////:osohosssssssss+yyyyyyyyyhhhhoohh
:::.``::://+++o++o++oo+osssss-.-ssssssssossssossssyyyyy+o+////////hhhhhhhhhhhhhhhs-.sy++++hs-.ohhhhhhhhhhyo+/:/:/://////osssssssssso::::::ssshossssssooooyyyyyyhhhhdmmo+hh
//:--:////+++oo+++///++osssss:.-ooosssssossssosssosssysossyyssossossyyyyyyyyyyyyyyo-/so+/ss:-oyyyyysyyyyy++/-:::////++o+osossssssss///////ooos+ooooooooo+syyyyyyyyyyddo+yh
*/
#include <set>
#include <map>
#include <deque>
#include <string>
#include <cstdint>
#include <cmath>
#include <queue>
#include <cassert>
#include <random>
#include <bitset>
#include <iomanip>
#include <cstring>
#include <numeric>
#include <time.h>//////////////
#include <ctime>
#include <climits>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <complex>
#include <chrono>
#include <unordered_set>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define all(a) (a).begin(), (a).end()
#define pbc push_back
#define pob pop_back()
#define vin(a) for (auto& i : a) cin >> i
#define sp system("pause")
#define mp make_pair
// mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
template<typename T1, typename T2>
inline void chkmin(T1& x, const T2& y)
{
if (y < x) x = y;
}
template<typename T1, typename T2>
inline void chkmax(T1& x, const T2& y)
{
if (x < y) x = y;
}
mt19937_64 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
ld asdasdcl = 0;
double getTime() { return (clock() - asdasdcl) / (double)CLOCKS_PER_SEC; }
pair<int, int> operator-(pair<int, int> a, pair<int, int> b)
{
return { a.first - b.first, a.second - b.second };
}
pair<int, int> operator+(pair<int, int> a, pair<int, int> b)
{
return { a.first + b.first, a.second + b.second };
}
/*
#define getchar_unlocked _getchar_nolock
inline int readInt()
{
char x;
while (x = getchar_unlocked())
{
if (x >= '0' && x <= '9')
{
int ans = x - '0';
while (x = getchar_unlocked())
{
if (!(x >= '0' && x <= '9')) return ans;
ans = ans * 10 + x - '0';
}
}
}
}*/
/*using namespace __gnu_pbds;
using ordered_set = tree<
pair<int, int>,
null_type,
less<pair<int, int>>,
rb_tree_tag,
tree_order_statistics_node_update>;*/
const int inf = 1e9 + 228;
const ld EPS = 1e-12;
const ld PI = acos(-1.0);
const ld INF = 1e18;
int ask(int a, int b)
{
cout << "? " << a << ' ' << b << endl;
int x;
cin >> x;
return x;
}
signed main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cout.precision(20), cout.setf(ios::fixed);
int n;
cin >> n;
vector<set<int>> g(n + 1);
for (int i = 0; i < n - 1; ++i)
{
int a, b;
cin >> a >> b;
g[a].insert(b);
g[b].insert(a);
}
set<int> lft;
int sz = n;
for (int i = 1; i <= n; ++i) lft.insert(i);
while (sz > 1)
{
if (sz == 2)
{
int y = ask(*lft.begin(), *lft.rbegin());
cout << "! " << y << endl;
return 0;
}
else
{
bool fnd = 0;
for (int i : lft)
{
if (g[i].size() == 1)
{
int u = *g[i].begin();
int lv = -1;
for (int x : g[u])
{
if (g[x].size() == 1 && x!= i)
{
lv = x;
break;
}
}
if (lv != -1)
{
int val = ask(i, lv);
if (val == i || val == lv)
{
cout << "! " << val << endl;
return 0;
}
g[lv].erase(u);
g[u].erase(lv);
g[i].erase(u);
lft.erase(i);
lft.erase(lv);
g[u].erase(i);
fnd = 1;
break;
}
else
{
if (g[u].size() == 2)
{
g[u].erase(i);
int lv = *g[u].begin();
int y = ask(lv, i);
if (y == u || y == i)
{
cout << "! " << y << endl;
return 0;
}
g[u].erase(lv);
g[lv].erase(u);
g[i].erase(u);
lft.erase(i);
lft.erase(u);
fnd = 1;
break;
}
}
}
}
sz -= 2;
}
}
cout << "! " << *lft.begin() << endl;
//sp;
}
//stop investigating combinatoric problems
//tle/mle - think?? wrong asympthotics??
//don't distract
//look at different ideas, don't get stuck | 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"
] | #include <bits/stdc++.h>
#define ms(x, v) memset(x, v, sizeof(x))
#define il __attribute__((always_inline))
#define U(i,l,r) for(int i(l),END##i(r);i<=END##i;++i)
#define D(i,r,l) for(int i(r),END##i(l);i>=END##i;--i)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
template <typename T> using BS = basic_string<T>;
//const int SZ(1 << 23);
//unsigned char buf[SZ], *S, *Q;
//#define getchar() ((S==Q)&&(Q=buf+fread(S=buf,1,SZ,stdin)),S==Q?EOF:*S++)
template <typename T>
void rd(T& s) {
int c = getchar();
T f = 1; s = 0;
while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
while (isdigit(c)) { s = s * 10 + (c ^ 48); c = getchar(); }
s *= f;
}
template <typename T, typename... Y>
void rd(T& x, Y&... y) { rd(x), rd(y...); }
template <typename T>
void pr(T s, bool f = 1) {
if (s < 0) { printf("-"); s = -s; }
if (!s) return void(f ? printf("0") : 0);
pr(s / 10, 0);
printf("%d", (signed)(s % 10));
}
#define meow(...) fprintf(stderr, __VA_ARGS__)
// 将区间离散化为 [)
// 枚举相等段长进行转移
const ll P = 998244353;
const int N = 505;
ll fac[N], ifac[N], inv[N];
ll qpow(ll x, ll t) { ll v = 1; while (t) { if (t & 1) (v *= x) %= P; (x *= x) %= P; t >>= 1; } return v; }
void genFac() {
fac[0] = ifac[0] = inv[0] = 1;
U (i, 1, N - 1) fac[i] = fac[i - 1] * i % P;
ifac[N - 1] = qpow(fac[N - 1], P - 2);
D (i, N - 2, 1) ifac[i] = ifac[i + 1] * (i + 1) % P;
U (i, 1, N - 1) inv[i] = fac[i - 1] * ifac[i] % P;
}
ll C(ll n, ll m) {
if (n < 0 || m < 0 || m > n) return 0;
ll v = ifac[m];
D (i, n, n - m + 1) (v *= i) %= P;
return v;
}
#define A(n, m) (C(n, m) * fac[m] % P)
#define IA(n, m) (IC(n, m) * ifac[m] % P)
#define Inv(x) qpow(x, P - 2)
int n, m;
int v[N * 2];
int l[N], r[N];
ll prod[N];
// pair<ll, ll> approx(ll q, ll A) {
// ll x = q, y = P, a = 1, b = 0;
// while (x > A) {
// swap(x, y); swap(a, b);
// a -= x / y * b;
// x %= y;
// }
// return {x, a};
// }
// void print(ll x, ll A = 80000) {
// auto f = approx(x, A);
// meow("%lld/%lld\n", f.first, f.second);
// }
int main() {
genFac();
rd(n);
prod[0] = 1;
U (i, 1, n) {
rd(l[i], r[i]); ++r[i];
v[i * 2 - 1] = l[i];
v[i * 2] = r[i];
prod[i] = prod[i - 1] * (r[i] - l[i]) % P;
}
sort(v + 1, v + 2 * n + 1);
m = unique(v + 1, v + 2 * n + 1) - v - 1;
// 离散化为 [l, r) 的区间
U (i, 1, n) {
l[i] = lower_bound(v + 1, v + m + 1, l[i]) - v;
r[i] = lower_bound(v + 1, v + m + 1, r[i]) - v;
// clog << l[i] << ' ' << r[i] << endl;
}
// 段数同理左闭右开
static ll f[N * 2][N * 2];
U (i, 1, m + 1) f[0][i] = 1;
// clog << "m" << ' ' << m << endl;
U (i, 1, n) {
D (k, r[i] - 1, l[i]) { // 同区间,要求不增
// 插板,共有 v[k+1]-v[k] 个球,截成 i-j+1 段
D (j, i, 1) // 要求从 [j..i] 在同一区间
if (k >= l[j] && k < r[j]) {
ll iv = Inv(prod[i] * Inv(prod[j - 1]) % P);
ll c = iv * C(v[k + 1] - v[k] + i - j, i - j + 1) % P * f[j - 1][k + 1] % P;
(f[i][k] += c) %= P;
} else break;
// meow("f[%d][%d]=%lld :: ", i, k, f[i][k]); print(f[i][k]);
}
D (k, m, 1)
(f[i][k] += f[i][k + 1]) %= P;
}
ll ans = f[n][1];
printf("%lld", ans);
// print(ans);
} | 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"
] | // LUOGU_RID: 91372592
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=4000;
int siz[maxn],dfn[maxn],idn=0;
int tot=0,pre[maxn<<1],son[maxn<<1],now[maxn];
int n,u,v;
short dis[maxn][maxn];
int f[maxn][maxn],g[maxn][maxn];
queue<pair<int,int> > q;
void put(int x,int y)
{
pre[++tot]=now[x];
now[x]=tot;
son[tot]=y;
}
void dfs(int x,int fa)
{
siz[x]=1;dfn[x]=++idn;
for(int p=now[x];p;p=pre[p])
{
int t=son[p];
if(t==fa)
continue;
dfs(t,x);
siz[x]+=siz[t];
}
}
int calc(int x,int y)
{
if(x==y)
return 0;
if(g[x][y])
return g[x][y];
if(dfn[x]<dfn[y])
swap(x,y);
if(dfn[x]<=dfn[y]+siz[y]-1)
{
for(int p=now[y];p;p=pre[p])
{
int t=son[p];
if(dis[x][t]+1==dis[x][y])
return g[x][y]=g[y][x]=siz[x]*(n-siz[t]);
}
}
return g[x][y]=g[y][x]=siz[x]*siz[y];
}
void bfs()
{
memset(dis,-1,sizeof(dis));
for(int i=1;i<=n;i++)
dis[i][i]=0,q.emplace(i,i);
int ans=0;
while(!q.empty())
{
auto [x,y]=q.front();
f[x][y]+=calc(x,y);
ans=max(ans,f[x][y]);
q.pop();
for(int p=now[x];p;p=pre[p])
{
int t=son[p];
if(dis[t][y]==-1||dis[t][y]==dis[x][y]+1)
{
if(dis[t][y]==-1)
q.emplace(t,y);
dis[t][y]=dis[x][y]+1;
f[t][y]=max(f[t][y],f[x][y]);
}
}
for(int p=now[y];p;p=pre[p])
{
int t=son[p];
if(dis[x][t]==-1||dis[x][t]==dis[x][y]+1)
{
if(dis[x][t]==-1)
q.emplace(x,t);
dis[x][t]=dis[x][y]+1;
f[x][t]=max(f[x][t],f[x][y]);
}
}
}
printf("%lld\n",ans);
}
signed main()
{
scanf("%lld",&n);
for(int i=1;i<n;i++)
scanf("%lld%lld",&u,&v),put(u,v),put(v,u);
dfs(1,0);
bfs();
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"
] | #include<bits/stdc++.h>
#define ll long long
#define flot(n) cout << setprecision(n) << setiosflags(ios::fixed) << setiosflags(ios::showpoint)
#define all(a) (a).begin() , (a).end()
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define piii pair<pii,int>
#define plll pair<pll,ll>
#define R return
#define B break
#define C continue
#define SET(n , i) memset(n , i , sizeof(n))
#define SD ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define rep(i , n) for(int i = 0 ; i < n ; i++)
#define repn(i , j , n) for(int i = j ; i < n ; i++)
#define repr(i,n,j) for(int i=n;i>=j;i--)
#define positive(x) ((x%mod+mod)%mod)
#define YES(f)cout<<((f)?"YES":"NO")<<endl
#define F first
#define S second
#define endl '\n'
#define vi vector<int>
//#define int ll
using namespace std;
void readFromFile(string input = "input.txt",string output="output.txt") {
#ifndef ONLINE_JUDGE
freopen(input.c_str(),"r",stdin);
freopen(output.c_str(),"w",stdout);
#endif
}
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll rnd(ll x, ll y) {
return uniform_int_distribution<ll>(x, y)(rng);
}
template <typename T> void Max(T& x,T y){x=max(x,y);}
template <typename T> void Min(T& x,T y){x=min(x,y);}
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3f;
const long double EPS = 1e-3;
const long double pi = acos(-1.0);
const int mod = 1e9+9;
const int N =2e5+3;
ll Mul(ll x,ll y,ll mod=mod){R((x%mod)*(y%mod))%mod;}
ll Add(ll x,ll y,ll mod=mod){R((x%mod)+(y%mod)+2ll*mod)%mod;}
int n,m,k,a[N];
vector<vector<int>> gr;
int dist[2][N],ans;
vector<int> v;
void bfs(int src,int en) {
queue<int> q;
q.push(src);
rep(i,n+1)dist[en][i]=INF;
dist[en][src]=0;
while(!q.empty()) {
int top = q.front();
q.pop();
for(auto it:gr[top]) {
if(dist[en][top]+1 < dist[en][it]) {
dist[en][it] = dist[en][top]+1;
q.push(it);
}
}
}
rep(i,n) if(a[i+1] && en) v.pb(dist[en][i+1]);
}
void solve() {
cin >> n >> m >> k;
rep(i,k) {
int x;cin>>x;
a[x]=1;
}
gr.resize(n+1);
rep(i,m) {
int x,y;
cin>>x>>y;
gr[x].pb(y);
gr[y].pb(x);
}
bfs(n,1);
sort(all(v));
bfs(1,0);
int ans=0;
repn(i,1,n+1) {
if(!a[i])C;
int it = dist[1][i];
int z = lower_bound(all(v),it)-v.begin();
if(v[z] > it)z--;
if(z>=0 && v[z]==it) {
if(z+1<v.size() && v[z+1] == it)
Max(ans,min(dist[0][n],dist[0][i]+1+v[z]));
else {
z--;
if(z>=0)
Max(ans,min(dist[0][n],dist[0][i]+1+v[z]));
}
}else if(z >= 0) {
Max(ans,min(dist[0][n],dist[0][i]+1+v[z]));
}
}
cout << ans << endl;
}
int32_t main() {
readFromFile();
SD;
int t = 1;
// cin >> t;
// scanf("%d",&t);
rep(i,t) {
solve();
}
}
| cpp |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | #define RAGHAV_PATEL ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
#define int long long int
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
int printNcR(int n, int r)
{
int p = 1, k = 1;
if (n - r < r)
r = n - r;
if (r != 0)
{
while (r)
{
p *= n;
k *= r;
int m = gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
}
else
p = 1;
return p;
}
void solve()
{
int n;
cin>>n;
vector<int>a(n);
vector<int>b(n);
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
cin>>b[i];
vector<int> diff(n);
int p=0,ng=0,z=0;
for(int i=0;i<n;i++){
diff[i]=a[i]-b[i];
if(diff[i]==0)
z++;
else if(diff[i]>0)
p++;
else
ng++;
}
int ans=0;
if(p>=2)
ans += (printNcR(p, 2));
if(p>0&&z>0)
ans+=(printNcR(p,1) * printNcR(z,1));
// cout<<"ans 1 : "<<ans<<"\n";
sort(diff.begin(), diff.end());
for(int i=0;i<n;i++){
if(diff[i]<0)
{
int x = n-(upper_bound(diff.begin(), diff.end(),abs(diff[i]))-diff.begin());
ans+=x;
}
else{
break;
}
}
cout<<ans<<"\n";
}
signed main()
{
RAGHAV_PATEL
int t, i;
//cin >> t;
t = 1;
while (t)
{
solve();
t--;
}
}
/*
int l = ans.size();
while(l>=0&&ans[l]==0)
l--;
*/ | 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>
clock_t cl=clock();
#define ll long long
#define Il inline
#define mem(u,v) memset(u,v,sizeof(u))
#define rep(i,a,b) for(ll i=(a),KKK##i=(b);i<=KKK##i;i++)
#define drep(i,a,b) for(ll i=(a),KKK##i=(b);i>=KKK##i;i--)
#define go(u) for(ll i=head[u],v=e[i].to;i;i=e[i].nxt,v=e[i].to)
#define writesp(x) write(x),putchar(' ')
#define writeln(x) write(x),puts("")
//#define getchar nc
using namespace std;
inline char nc(){static char buf[1000000],*p1=buf,*p2=buf;return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;}
Il ll read(){ll sum=0,f=0;char ch=getchar();for(;!isdigit(ch);ch=getchar())f|=(ch=='-');for(;isdigit(ch);ch=getchar())sum=((sum<<1)+(sum<<3)+(ch^48));return f?-sum:sum;}
void write(const ll x){if(x<0){putchar('-');write(-x);return;}if(x>9)write(x/10);putchar(x%10+'0');}
char getc(){char c=getchar();while(!isalpha(c))c=getchar();return c;}
#define N 1100
#define pii pair<ll,ll>
#define MP make_pair
#define fi first
#define se second
ll n,m,k,m2[N],s[N],B,f[N][N],sum[N][N],lcp[N][N],tot;
pii b[N*N];
const ll M=1e9+7;char a[N];
ll gh(ll x,ll y){
return (s[y]-s[x-1]*m2[y-x+1]%M+M)%M;
}
ll gl(ll x,ll y,ll k){
ll l=0,r=k;
while(l<r){
ll mid=(l+r+1)>>1;
if(gh(x,x+mid-1)==gh(y,y+mid-1))l=mid;
else r=mid-1;
}
return l;
}
bool cmp(pii x,pii y){
ll t=lcp[x.fi][y.fi],l1=x.se-x.fi+1,l2=y.se-y.fi+1;
// cout<<lcp[1][4]<<endl;
// cout<<t<<endl;
if(t>=min(l1,l2))return l1<=l2;
return a[x.fi+t]<a[y.fi+t];
}
ll solve(pii tmp){
ll x=tmp.fi,len=tmp.se-tmp.fi+1;
mem(f,0);mem(sum,0);
f[n+1][0]=1;sum[n+1][0]=1;
drep(i,n,1){
ll p=lcp[x][i],t=n+2;
if(p>=min(len,n-i+1)){
if(len>n-i+1)t=n+2;
else t=i+len-1;
}
else{
if(a[tmp.fi+p]>a[i+p])t=n+2;
else if(a[tmp.fi+p]==a[i+p])t=i+p-1;
else t=i+p;
}
// cout<<"DE"<<i<<' '<<t<<endl;
rep(j,1,m)f[i][j]=sum[t+1][j-1];
rep(j,0,m)sum[i][j]=min(sum[i+1][j]+f[i][j],k);
}
// rep(i,1,n+1){
// rep(j,0,m)cout<<f[i][j]<<" ";puts("");
// }
// rep(i,1,n+1){
// rep(j,0,m)cout<<sum[i][j]<<" ";puts("");
// }
return f[1][m];
}
int main(){
srand(time(0));
n=read();m=read();k=read();
rep(i,1,n)a[i]=getc();
B=13+rand()%20;
m2[0]=1;rep(i,1,n)m2[i]=m2[i-1]*B%M;
rep(i,1,n)s[i]=(s[i-1]*B+(a[i]-'a'+1))%M;
rep(i,1,n)rep(j,1,n)lcp[i][j]=gl(i,j,min(n-i+1,n-j+1));
rep(i,1,n)rep(j,i,n)b[++tot]=MP(i,j);
sort(b+1,b+tot+1,cmp);
// rep(i,1,tot){
// rep(j,b[i].fi,b[i].se)cout<<(char)a[j];puts("");
// }
// cout<<solve(MP(1,3))<<endl;
// cout<<solve(MP(1,3))<<endl;
ll l=1,r=tot;
while(l<r){
ll mid=(l+r+1)>>1;
if(solve(b[mid])>=k)l=mid;
else r=mid-1;
}
rep(i,b[l].fi,b[l].se)putchar(a[i]);
}
| cpp |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences. | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | //
// Created by ahmed-kashkoush on 2/4/23.
//
//والله يابني مانا عارف ادينا بنهبد
//كود بلا هدف, تكبييييير
// Problem Link -->
/**symbols
@! --> important and and write it down
*/
#include<bits/stdc++.h>
#define el '\n'
#define ll long long
#define reset(v, d) memset(v, d , sizeof(v))
#define all(s) s.begin(), s.end()
#define cin(v) for(auto &i:v)cin>>i
#define cout(v) for(auto i:v)cout<<i<<" "
using namespace std;
void judge();void tc();
const ll OO=INT_MAX;
void solve() {
int n; cin>>n;
vector<pair<int, int>> pr;// pair of[min, max]
for(int i=0;i<n;i++){
int m; cin>>m;
vector<int> v(m);
cin(v);
reverse(all(v));
if(is_sorted(all(v)))
pr.emplace_back(v[0], v[m-1]);
// he stored what can't form
}
sort(all(pr));
ll ans=(ll)n*n;
// he removed what can't fomr
for(auto [mn, mx]:pr){
ans-=pr.end()-lower_bound(all(pr), make_pair(mx,-1));
// means to remove only the vectors that have min greater than my mx
}
cout<<ans;
}
int main() {
judge();
// tc();
solve();
return 0;
}
void tc(){
int t = 1;
cin>>t;
for (int tc = 1; tc <= t; tc++) {
cout<<"#tc"<< tc<<": ";
solve();
// cout<<endl;
cout<<el;
}
}
void judge() {
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
#endif
}
| cpp |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 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≤15001≤n≤1500) — 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
| [
"data structures",
"greedy"
] | #include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define x first
#define y second
using namespace std;
typedef pair<int, int> pii;
const int N = 1510;
unordered_map<int, vector<pii>> mp;
int n, s[N];
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++ )
{
int a;
cin >> a;
s[i] += s[i - 1] + a;
}
for (int i = 1; i <= n; i ++ )
for (int j = i; j <= n; j ++ )
mp[s[j] - s[i - 1]].push_back({i, j});
int k = 0;
vector<pii> res;
for (auto& t : mp)
{
vector<pii> path, tmp = t.y;
sort(tmp.begin(), tmp.end(), [&](pii& a, pii& b){
return a.y < b.y;
});
int st = -2e9, ed = -2e9, cnt = 0;
for (auto& range : tmp)
{
int l = range.x, r = range.y;
if (ed < l) {
if (ed != -2e9) path.push_back({st, ed});
st = l;
ed = r;
cnt ++;
}
}
path.push_back({st, ed});
if (k < cnt) k = cnt, res = path;
}
printf("%d\n", k);
for (auto& t : res)
printf("%d %d\n", t.x, t.y);
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: 95416964
#include <bits/stdc++.h>
#define fo(i,a,b) for(int i=a;i<=b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
using namespace std;
#define LL unsigned long long
mt19937_64 rd(time(0));
LL read()
{
LL X=0,w=0;char ch=0;
while(!isdigit(ch))w|=ch=='-',ch=getchar();
while(isdigit(ch))X=(X<<3)+(X<<1)+(ch^48),ch=getchar();
return w?-X:X;
}
LL nu[500005];
pair<LL,LL> zt[500005];
LL gcd(LL x,LL y)
{
if(!y)return x;
return gcd(y,x%y);
}
void solve()
{
int n=read(),m=read();
fo(i,1,n)nu[i]=rd(),zt[i]={0,read()};
fo(i,1,m)
{
int x=read(),y=read();
zt[y].first+=nu[x];
}
sort(zt+1,zt+n+1);
LL ans=0;
fo(i,1,n)
{
int j=i;
LL su=0;
while(zt[j].first==zt[i].first)su+=zt[j++].second;
i=j-1;
if(zt[i].first)ans=gcd(ans,su);
}
printf("%llu\n",ans);
}
int main()
{
int T=read();
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>
using namespace std;
typedef long long ll;
typedef double db;
typedef long double ldb;
typedef complex<double> cd;
const ll INF64 = 9'000'000'000'000'000'000, INF32 = 2'000'000'000, MOD = 1'000'000'007;
const db PI = acos(-1);
const bool IS_FILE = false, IS_TEST_CASES = false;
random_device rd;
mt19937 rnd32(rd());
mt19937_64 rnd64(rd());
template<typename T>
bool assign_max(T& a, T b) {
if (b > a) {
a = b;
return true;
}
return false;
}
template<typename T>
bool assign_min(T& a, T b) {
if (b < a) {
a = b;
return true;
}
return false;
}
template<typename T>
T square(T a) {
return a * a;
}
template<>
struct std::hash<pair<ll, ll>> {
ll operator() (pair<ll, ll> p) {
return ((__int128)p.first * MOD + p.second) % INF64;
}
};
void solve() {
ll n, k;
cin >> n >> k;
vector<bool> be(n, true);
if (k == 1) {
for (ll i = 0; i < n; i++) {
for (ll j = i + 1; j < n; j++) {
cout << "? " << i + 1 << endl;
cout << "? " << j + 1 << endl;
char c;
cin >> c >> c;
if (c == 'Y') {
be[j] = false;
}
}
}
} else {
k >>= 1;
for (ll i = 0; i < n / k; i++) {
bool b = true;
for (ll j = i + 1; j < n / k; j++) {
for (ll f = 0; f < k; f++) {
cout << "? " << i * k + f + 1 << endl;
char c;
cin >> c;
if (b && c == 'Y') {
be[i * k + f] = false;
}
}
b = false;
for (ll f = 0; f < k; f++) {
cout << "? " << j * k + f + 1 << endl;
char c;
cin >> c;
if (c == 'Y') {
be[j * k + f] = false;
}
}
}
cout << 'R' << endl;
}
}
ll ans = 0;
for (auto i : be) {
ans += i;
}
cout << "! " << ans << endl;
}
int main() {
if (IS_FILE) {
freopen("", "r", stdin);
freopen("", "w", stdout);
}
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll t = 1;
if (IS_TEST_CASES) {
cin >> t;
}
for (ll i = 0; i < t; i++) {
solve();
}
}
| 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;
#define ll long long
int tt, tc;
void solve() {
int n, d;
cin >> n >> d;
vector<int> a(n);
for (auto& u : a) cin >> u;
int ans = a[0];
for (int i = 1; i < n; i++) {
// k * i <= min(d, a[i
int k = d/i;
k = min(k, a[i]);
d -= k * i;
ans += k;
}
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
tt = 1, tc = 1; cin >> tt;
while (tt--) solve(), tc++;
}
| cpp |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement. | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | // CF template, version 3.0
#include <bits/stdc++.h>
using namespace std;
#define improvePerformance ios_base::sync_with_stdio(false); cin.tie(0)
#define getTest int t; cin >> t
#define eachTest for (int _var=0;_var<t;_var++)
#define get(name) int (name); cin >> (name)
#define out(o) cout << (o)
#define getList(cnt, name) vector<int> (name); for (int _=0;_<(cnt);_++) { get(a); (name).push_back(a); }
#define sortl(name) sort((name).begin(), (name).end())
#define rev(name) reverse((name).begin(), (name).end())
#define forto(name, var) for (int (var) = 0; (var) < (name); (var)++)
#define decision(b) if (b){out("YES");}else{out("NO");}
#define int long long int
int gcd(int a, int b) {
if (a == b) return a;
return gcd(max(a, b), max(a, b) % min(a, b));
}
/*
Segtree:
void build(vector<int> &tree, vector<int> &array, int i, int l, int r) {
if (l == r) {
tree[i] = array[l];
} else {
int middle = (l + r) / 2;
build(tree, array, i * 2, l, middle);
build(tree, array, i * 2 + 1, middle + 1, r);
tree[i] = max(tree[i * 2], tree[i * 2 + 1]);
}
}
void set_(vector<int> &tree, int v, int l, int r, int i, int x) {
if (l == r) {
tree[v] = x;
} else {
int middle = (l + r) / 2;
if (i <= middle) {
set_(tree, v * 2, l, middle, i, x);
} else {
set_(tree, v * 2 + 1, middle + 1, r, i, x);
}
tree[v] = max(tree[v * 2], tree[v * 2 + 1]);
}
}
int query(vector<int> &tree, int v, int cl, int cr, int l, int r) {
if (l == cl && r == cr) {
return tree[v];
}
if (l > r) return 0;
int middle = (cl + cr) / 2;
return max(
query(tree, v * 2, cl, middle, l, min(r, middle)),
query(tree, v * 2 + 1, middle + 1, cr, max(l, middle + 1), r)
);
}
vector<int> tree(4 * n);
build(tree, initial, 1, 0, n-1); // replace initial with name of array
set_(tree, 1, 0, n-1, a, b);
query(tree, 1, 0, n-1, a, b); // this returns an int
data structure can be changed
*/
signed main() {
improvePerformance;
getTest;
eachTest {
get(n);
get(m);
if (m >= n / 2) {
out(n * (n + 1) / 2 - (n - m));
} else {
int streaks = m + 1;
int zeroes = n - m;
int minimalLength = zeroes / streaks;
int extra = zeroes % streaks;
out(n * (n + 1) / 2 - (minimalLength * (minimalLength + 1) / 2) * streaks - (minimalLength + 1) * extra);
}
out("\n");
}
} | cpp |
1141 | A | A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272. | [
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m, div, count = 0;
cin >> n >> m;
if(n == m)
cout << 0;
else if(m%n)
cout << -1;
else
{
div = m/n;
while(div % 2 == 0)
{
div = div/2;
count++;
}
while(div % 3 == 0)
{
div = div/3;
count++;
}
if(div == 1)
cout << count;
else
cout << -1;
}
}
| 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>
using namespace std;
#define fio ios_base::sync_with_stdio(0); cin.tie(0);
#define int long long
#define vt vector
#define pb push_back
#define eb emplace_back
#define INF 0x3f3f3f3f3f3f3f3f
#define PI pair<int, int>
#define rep(i, from, to) for (int i = from; i <= to; ++i)
#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")
#pragma GCC target("avx,avx2,fma")
const int mxn = 2e5 + 5, MOD = 998244353;
//枚舉最大的數
//最大的數為i 有Ci - 1取n - 2
//每種會有n - 2種
//1 1 2 3 => 1231 1321 n - 2?
//1 2 2 3 4 => 12342 12432 24321 13421
int n, m, fac[mxn];
int fast_power(int a, int b, int MOD = MOD){
int res = 1;
while (b){
if (b & 1) res = res * a % MOD;
a = a * a % MOD;
b >>= 1;
}
return res;
}
void init() {
fac[0] = 1;
rep(i, 1, 2e5) fac[i] = fac[i - 1] * i % MOD;
}
int C(int n, int r) {
if (n < r) return 0;
return fac[n] * fast_power(fac[r], MOD - 2) % MOD * fast_power(fac[n - r], MOD - 2) % MOD;
}
signed main(void){
#ifndef ONLINE_JUDGE
freopen("C:\\Code\\C\\input.txt","r",stdin);
freopen("C:\\Code\\C\\output.txt","w",stdout);
#endif
fio
cin >> n >> m;
init();
int ans = 0;
rep(i, 1, m) {
ans = (ans + C(i - 1, n - 2) * fast_power(2, n - 2) % MOD * (n - 2) % MOD) % MOD;
}
cout << ans * fast_power(2, MOD - 2) % MOD << '\n';
} | cpp |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS. | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] |
using namespace std;
const long double PI = 3.14159265;
#include <iostream>
#include <string>
#include <fstream>
#include <set>
#include <vector>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <queue>
#include <unordered_set>
#include <random>
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
const ll INF = 1e15;
const ll MOD = 1e9 + 7;
const pii ADJ4[4] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
const pii ADJ8[8] = {{-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,1}, {1,-1}, {1,0}, {1,1}};
const int MAX_N = 1e5 + 5;
void solve() {
int n;
cin >> n;
int ans[n];
string s;
cin >> s;
int cur = n;
int last = 0;
for(int i=0; i < n; i++){
if(i == n-1 || s[i] == '>'){
for(int j=i; j >= last; j--){
ans[j] = cur;
cur--;
}
last = i+1;
}
}
for(int i=0; i < n; i++) cout << ans[i] << " ";
cout << "\n";
cur = 1;
last = 0;
for(int i=0; i < n; i++){
if(i == n-1 || s[i] == '<'){
for(int j=i; j >= last; j--){
ans[j] = cur;
cur++;
}
last = i+1;
}
}
for(int i=0; i < n; i++) cout << ans[i] << " ";
cout << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t;
cin >> t;
while(t--) solve();
}
| cpp |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using lui = long unsigned int ;
#define pass (void)0
int main()
{
ll t ;
cin >> t ;
while (t--)
{
ll n ;
cin >> n ;
set<int> num ;
for (int i = 0 ; i < n ; i++)
{
ll a ;
cin >> a ;
num.insert(a) ;
}
cout << num.size() << endl ;
}
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>
#define ll long long
#define sz(x) (x).size()
#define all(x) (x).begin(), (x).end()
#define tv ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
ll n,m,t;
void x(){
int a,b;
cin>>a>>b;
if(a<b)swap(a,b);
cout<< (a%b==0 ? "YES\n" : "NO\n");
}
int main(){tv cin>>t;
while(t--){
x();
}
return 0;
}
| cpp |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] | #include<bits/stdc++.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<math.h>
#include<map>
#include<algorithm>
#include<set>
#include<unordered_map>
#include <unordered_set>
#define fast ios_base::sync_with_stdio(false),cin.tie(NULL)
#define popcount __builtin_popcount
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define int long long int
typedef long double lld;
#define FOR(i,n) for(int i=0;i<n;i++)
#define yes cout<<"YES"<<endl;
#define no cout<<"NO"<<endl;
#define p0(a) cout << a << " "
#define p1(a) cout << a << endl
#define p2(a, b) cout << a << " " << b << endl
#define p3(a, b, c) cout << a << " " << b << " " << c << endl
#define p4(a, b, c, d) cout << a << " " << b << " " << c << " " << d << endl
#define MOD 1000000007
#define vi vector<int>
#define pii pair<int, int>
#define vii vector<pii>
#define fr front()
#define bk back()
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define max_heap priority_queue <int>
#define min_heap priority_queue <int, vector <int> , greater <int> >
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pair<int, int> > vpii;
typedef unordered_set<int> us;
typedef map<int,int> mp;
//debugging
#ifndef ONLINE_JUDGE
#define debug1(a) cerr <<#a<<" " <<a << endl
#define debug2(a, b) cerr <<#a<<" "<< a << " "<<#b<<" " << b << endl
#define debug3(a, b, c) cerr <<#a<<" "<<a << " "<<#b<<" " << b << " "<<#c<<" " << c << endl
#define debug4(a, b, c, d) cerr << #a<<" "<<a << " " <<#b<<" "<< b << " "<<#c<<" " << c << " "<<#d<<" "<< d << endl
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#define debug2(x,y)
#define debug3(x,y,z)
#define debug4(x,y,z,a)
#endif
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(multimap <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
//Constants
const long double pi= 3.141592653589793238;
const int INF= 1e18;
const int mod=1e9+7;
//MATHEMATICAL FUNCTIONS
int gcd(int a, int b){if (b == 0)return a;return gcd(b, a % b);} //gcd
int lcm(int a, int b){return (a/gcd(a,b)*b);} //lcm
//sieve
vector<int> sieve(int n) {int*arr = new int[n + 1](); vector<int> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
//binary exponentation
int expo(int a, int b, int mod) {int res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
//CHECK
bool isprime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
bool ispoweroftwo(int n){if(n==0)return false;return (ceil(log2(n)) == floor(log2(n)));}
bool isperfectsquare(int x){if (x >= 0) {int sr = sqrt(x);return (sr * sr == x);}return false;}
int ceils(int x, int y) {return x / y + (x % y > 0);}
// Operator overloads
template<typename T1, typename T2> // cin >> pair<T1, T2>
istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.first >> p.second); }
template<typename T> // cin >> vector<T>
istream& operator>>(istream &istream, vector<T> &v){for (auto &it : v)cin >> it;return istream;}
template<typename T1, typename T2> // cout << pair<T1, T2>
ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.first << " " << p.second); }
template<typename T> // cout << vector<T>
ostream& operator<<(ostream &ostream, const vector<T> &c) { for (auto &it : c) cout << it << " "; return ostream; }
//USEFUL
void printarr(vi arr, int n){FOR(i,n) cout << arr[i] << " ";cout << "\n";}
string s;
int a,b,k;
int get_c(int ind){
if(s[ind]=='A') return a;
return b;
}
void solve(){
int n,m,i,j;
cin>>a>>b>>k;
cin>>s;
n=s.length();
vi cost(n);
cost[n-2]=get_c(n-2);
for(int i=n-3;i>=0;i--){
if(s[i]!=s[i+1]){
cost[i]=cost[i+1]+get_c(i);
}
else{
cost[i]=cost[i+1];
}
}
// debug(cost);
for(int i=0;i<n;i++){
if(cost[i]<=k){
cout<<i+1<<endl;
return;
}
}
cout<<n<<endl;
}
int32_t main()
{
fast;
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t;
t=1;
cin>>t;
while(t--){
// cout<<t;
solve();
}
return 0;
}
| cpp |
1292 | C | C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10. | [
"combinatorics",
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("O2")
using ll = long long;
#define int long long
#define forn(i,n) for(int i=0; i<n; ++i)
#define pb push_back
#define pi pair<int,int>
#define f first
#define s second
#define vii(a,n) vector<int> a(n); forn(i,n) cin>>a[i];
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//const int inf = 1e18;
const int mod = 1e9+7;//998244353;
const int maxn=3e3;
vector<int> adj[maxn];
int sz[maxn][maxn]; //sz[v][par_v];
int dp[maxn][maxn];
int pu[maxn][maxn];
int pv[maxn][maxn];
int vis[maxn][maxn];
int getsz(int u, int p) {
int r=1;
for(auto&v:adj[u]) {
if (v==p) continue;
r+=getsz(v,u);
}
return r;
}
void solve() {
int n; cin>>n;
forn(i,n-1) {
int u,v; cin>>u>>v; --u, --v;
adj[u].pb(v);
adj[v].pb(u);
}
forn(i,n) forn(j,n) dp[i][j]=sz[i][j]=pu[i][j]=pv[i][j]=vis[i][j]=0;
forn(u,n) {
for(auto&v:adj[u]) {
sz[u][v]=getsz(u,v);
}
}
queue<pi> q;
forn(u,n) {
for(auto&v:adj[u]) {
dp[u][v]=sz[u][v]*sz[v][u];
pu[u][v]=v, pv[u][v]=u;
q.push({u,v});
}
}
while (q.size()) {
auto it = q.front();
int u=it.f, v=it.s;
q.pop();
for(auto&u1:adj[v]) {
if (u1==pv[u][v]) continue;
if (!vis[u][u1]) q.push({u,u1});
vis[u][u1]=1;
int x=sz[u][pu[u][v]]*sz[u1][v]+dp[u][v];
if (x>dp[u][u1]) {
dp[u][u1]=x;
pu[u][u1]=pu[u][v];
pv[u][u1]=v;
}
}
for(auto&v1:adj[u]) {
if (v1==pu[u][v]) continue;
if (!vis[v1][v]) q.push({v1,v});
vis[v1][v]=1;
int x=sz[v1][u]*sz[v][pv[u][v]]+dp[u][v];
if (x>dp[v1][v]) {
dp[v1][v]=x;
pu[v1][v]=u;
pv[v1][v]=pv[u][v];
}
}
}
int ans=0;
forn(i,n) forn(j,n) ans=max(ans,dp[i][j]);
cout<<ans;
}
int32_t main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t=1;
//cin>>t;
while (t--) solve();
return 0;
} | cpp |
1320 | F | F. Blocks and Sensorstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size 1×1×11×1×1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1×1×11×1×1; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates (x,y,z)(x,y,z) (the cell with these coordinates is a cube with opposite corners in (x,y,z)(x,y,z) and (x+1,y+1,z+1)(x+1,y+1,z+1)) and its contents ax,y,zax,y,z; if the cell is empty, then ax,y,z=0ax,y,z=0, otherwise ax,y,zax,y,z is equal to the type of the block placed in it (the types are integers from 11 to 2⋅1052⋅105).Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size n×m×kn×m×k, containing all cells (x,y,z)(x,y,z) such that x∈[1,n]x∈[1,n], y∈[1,m]y∈[1,m], and z∈[1,k]z∈[1,k]. After that, Polycarp has installed 2nm+2nk+2mk2nm+2nk+2mk sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into 66 types: there are mkmk sensors of the first type; each such sensor is installed in (0,y,z)(0,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the same direction; there are mkmk sensors of the second type; each such sensor is installed in (n+1,y,z)(n+1,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the opposite direction; there are nknk sensors of the third type; each such sensor is installed in (x,0,z)(x,0,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the same direction; there are nknk sensors of the fourth type; each such sensor is installed in (x,m+1,z)(x,m+1,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the opposite direction; there are nmnm sensors of the fifth type; each such sensor is installed in (x,y,0)(x,y,0), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the same direction; finally, there are nmnm sensors of the sixth type; each such sensor is installed in (x,y,k+1)(x,y,k+1), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the opposite direction. Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?InputThe first line contains three integers nn, mm and kk (1≤n,m,k≤2⋅1051≤n,m,k≤2⋅105, nmk≤2⋅105nmk≤2⋅105) — the dimensions of the parallelepiped.Then the sensor data follows. For each sensor, its data is either 00, if the ray emitted from it reaches the opposite sensor (there are no blocks in between), or an integer from 11 to 2⋅1052⋅105 denoting the type of the first block hit by the ray. The data is divided into 66 sections (one for each type of sensors), each consecutive pair of sections is separated by a blank line, and the first section is separated by a blank line from the first line of the input.The first section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (0,i,j)(0,i,j).The second section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (n+1,i,j)(n+1,i,j).The third section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,0,j)(i,0,j).The fourth section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,m+1,j)(i,m+1,j).The fifth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,0)(i,j,0).Finally, the sixth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,k+1)(i,j,k+1).OutputIf the information from the input is inconsistent, print one integer −1−1.Otherwise, print the figure inside the parallelepiped as follows. The output should consist of nmknmk integers: a1,1,1a1,1,1, a1,1,2a1,1,2, ..., a1,1,ka1,1,k, a1,2,1a1,2,1, ..., a1,2,ka1,2,k, ..., a1,m,ka1,m,k, a2,1,1a2,1,1, ..., an,m,kan,m,k, where ai,j,kai,j,k is the type of the block in (i,j,k)(i,j,k), or 00 if there is no block there. If there are multiple figures consistent with sensor data, describe any of them.For your convenience, the sample output is formatted as follows: there are nn separate sections for blocks having x=1x=1, x=2x=2, ..., x=nx=n; each section consists of mm lines containing kk integers each. Note that this type of output is acceptable, but you may print the integers with any other formatting instead (even all integers on the same line), only their order matters.ExamplesInputCopy4 3 2
1 4
3 2
6 5
1 4
3 2
6 7
1 4
1 4
0 0
0 7
6 5
6 5
0 0
0 7
1 3 6
1 3 6
0 0 0
0 0 7
4 3 5
4 2 5
0 0 0
0 0 7
OutputCopy1 4
3 0
6 5
1 4
3 2
6 5
0 0
0 0
0 0
0 0
0 0
0 7
InputCopy1 1 1
0
0
0
0
0
0
OutputCopy0
InputCopy1 1 1
0
0
1337
0
0
0
OutputCopy-1
InputCopy1 1 1
1337
1337
1337
1337
1337
1337
OutputCopy1337
| [
"brute force"
] | #include<stdio.h>
#include<bits/stdc++.h>
#define fir first
#define sec second
#define all(x) begin(x),end(x)
using namespace std;
typedef long long ll;
typedef unsigned uint;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef __int128 int128;
typedef __uint128_t uint128;
typedef pair<int,int> pii;
template<typename type>
inline void chmin(type &x,const type &y)
{
if(x>y)
x=y;
}
template<typename type>
inline void chmax(type &x,const type &y)
{
if(x<y)
x=y;
}
constexpr int Max=2e5+100;
constexpr int dx[6]={1,-1,0,0,0,0},dy[6]={0,0,1,-1,0,0},dz[6]={0,0,0,0,1,-1};
int n,m,o,ans[Max];
vector<int>p[Max];
inline int ask_id(const int &x,const int &y,const int &z)
{
return (x-1)*m*o+(y-1)*o+z;
}
void del(int x,int y,int z);
void dfs(int x,int y,int z,int d,int k)
{
bool in=x>=1&&x<=n&&y>=1&&y<=m&&z>=1&&z<=o;
if(!in&&k)
cout<<"-1\n",exit(0);
if(!in)
return;
int i=ask_id(x,y,z);
if(!k)
{
if(ans[i]>0)
del(x,y,z);
ans[i]=0;
dfs(x+dx[d],y+dy[d],z+dz[d],d,0);
return;
}
if(!~ans[i])
{
ans[i]=k;
p[i].push_back(d);
return;
}
if(!ans[i])
dfs(x+dx[d],y+dy[d],z+dz[d],d,k);
else
if(ans[i]!=k)
{
del(x,y,z),ans[i]=0;
dfs(x+dx[d],y+dy[d],z+dz[d],d,k);
}
else
p[i].push_back(d);
}
void del(int x,int y,int z)
{
int i=ask_id(x,y,z);
while(!p[i].empty())
{
int d=p[i].back();
p[i].pop_back();
dfs(x+dx[d],y+dy[d],z+dz[d],d,ans[i]);
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
cin>>n>>m>>o;
memset(ans,-1,sizeof(ans));
int x;
for(int i=1;i<=m;++i)
for(int j=1;j<=o;++j)
cin>>x,dfs(1,i,j,0,x);
for(int i=1;i<=m;++i)
for(int j=1;j<=o;++j)
cin>>x,dfs(n,i,j,1,x);
for(int i=1;i<=n;++i)
for(int j=1;j<=o;++j)
cin>>x,dfs(i,1,j,2,x);
for(int i=1;i<=n;++i)
for(int j=1;j<=o;++j)
cin>>x,dfs(i,m,j,3,x);
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j)
cin>>x,dfs(i,j,1,4,x);
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j)
cin>>x,dfs(i,j,o,5,x);
for(int i=1;i<=n;cout<<"\n",++i)
for(int j=1;j<=m;cout<<"\n",++j)
for(int k=1,x;k<=o;++k)
cout<<(~(x=ans[ask_id(i,j,k)])?x:0)<<" ";
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;
#define ll long long
#define mod 1000000007
int main(){
ios_base::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr);
int T=1; cin>>T;
while(T--) {
int n,mx=0; cin>>n;
vector<int>v(n);
vector<vector<int>>freq(5003);
for(int i=0;i<n;i++){
cin>>v[i];
freq[v[i]].push_back(i+1);
mx=max(mx,v[i]);
}
bool f=1;
for(int i=1;i<=mx;i++){
if(freq[i].size()>=3){f=0; break;}
else if(freq[i].size()<=1)continue;
else{
if(freq[i][1]-freq[i][0]>1){f=0; break;}
}
}
if(!f)cout<<"YES\n";
else cout<<"NO\n";
}
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<iostream>
#include<iterator>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
#include "local_dbg.cpp"
#else
#define debug(...) 101;
#endif
typedef long long int ll;
typedef long double ld;
typedef std::vector<int> vi;
typedef std::vector<ll> vll;
typedef std::vector<ld> vld;
typedef std::vector<std::vector<ll> > vvll;
typedef std::vector<std::vector<ld> > vvld;
typedef std::vector<std::vector<std::vector<ll> > > vvvll;
typedef std::vector<string> vstr;
typedef std::vector<std::pair<ll,ll> > vpll;
typedef std::pair<ll,ll> pll;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb push_back
#define nl "\n"
#define all(c) (c).begin(),(c).end()
#define iotam1 cout<<-1<<nl
#define cty cout<<"YES"<<nl
#define ctn cout<<"NO"<<nl
#define lmax LLONG_MAX
#define lmin LLONG_MIN
#define sz(v) (v).size()
#define deci(n) fixed<<setprecision(n)
#define c(x) cout<<(x)
#define csp(x) cout<<(x)<<" "
#define c1(x) cout<<(x)<<nl
#define c2(x,y) cout<<(x)<<" "<<(y)<<nl
#define c3(x,y,z) cout<<(x)<<" "<<(y)<<" "<<(z)<<nl
#define c4(a,b,c,d) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<nl
#define c5(a,b,c,d,e) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<" "<<(e)<<nl
#define c6(a,b,c,d,e,f) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<" "<<(e)<<" "<<(f)<<nl
#define f(i_itr,a,n) for(ll i_itr=a; i_itr<n; i_itr++)
#define rev_f(i_itr,n,a) for(ll i_itr=n; i_itr>a; i_itr--)
#define arri(n, arr) for(ll i_itr=0; i_itr<n; i_itr++) cin>>arr[i_itr]
#define a_arri(n, m, arr) for(ll i_itr=0; i_itr<n; i_itr++) for (ll j_itr=0; j_itr<m; j_itr++) cin>>arr[i_itr][j_itr]
#define pb push_back
#define fi first
#define se second
#define print(vec,a,b) for(ll i_itr=a;i_itr<b;i_itr++) cout<<vec[i_itr]<<" ";cout<<"\n";
#define input(vec,a,b) for(ll i_itr = a;i_itr<b;i_itr++) cin>>vec[i_itr];
#define ms(a,val) memset(a,val,sizeof(a))
const ll mod = 1000000007;
const long double pi=3.14159265358979323846264338327950288419716939937510582097494459230;
ll pct(ll x) { return __builtin_popcount(x); } // #of set bits
ll poww(ll a, ll b) { ll res=1; while(b) { if(b&1) res=(res*a); a=(a*a); b>>=1; } return res; }
ll modI(ll a, ll m=mod) { ll m0=m,y=0,x=1; if(m==1) return 0; while(a>1) { ll q=a/m; ll t=m; m=a%m; a=t; t=y; y=x-q*y; x=t; } if(x<0) x+=m0; return x;}
ll powm(ll a, ll b,ll m=mod) {ll res=1; while(b) { if(b&1) res=(res*a)%m; a=(a*a)%m; b>>=1; } return res;}
void ipgraph(ll,ll);
void ipgraph(ll); ///for tree
void dfs(ll node,ll par);
//******************************************************************************************************************************************* /
const ll N=2e5+5;
// ll inp[N];
// vll adj[N]; ///for graph(or tree) use this !!-><-!!
void ok_boss()
{
ll n;
//cin >> n;
string a,b,c;
cin>>a>>b>>c;
n=sz(a);
f(i,0,n)
{
if(a[i]!=c[i] && b[i]!=c[i])
{
c1("No");
return;
}
}
c1("Yes");
return;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
#endif
fast;
/// std::cout << fixed<<setprecision(15); ///activate it if the answers are in decimal.
ll qq_itr = 1;
cin >> qq_itr;
while (qq_itr--)
ok_boss();
return 0;
}
/*
void ipgraph(ll nodes_ipg,ll edgs_ipg)
{
f(i,0,nodes_ipg)
adj[i].clear();
ll fir,sec;
while(edgs_ipg--)
{
cin>>fir>>sec;
fir--,sec--; ///turn it off if it is 0-indexed
adj[fir].pb(sec);
adj[sec].pb(fir); ///remove this if directed !!!
}
return;
}
void ipgraph(ll nodes_ipg)
{
ipgraph(nodes_ipg,nodes_ipg-1);
}
void dfs(ll node,ll par=-1)
{
for(ll chd : adj[node])
{
if(chd==par)
continue;
dfs(chd,node);
}
return;
}
*/ | 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>
using namespace std;
using point_t=long long; //全局数据类型,可修改为 long long 等
constexpr point_t eps=0;
constexpr long double PI=3.1415926535897932384l;
// 点与向量
template<typename T> struct point
{
T x,y;
// int id=-1;
bool operator==(const point &a) const {return (abs(x-a.x)<=eps && abs(y-a.y)<=eps);}
bool operator<(const point &a) const {if (abs(x-a.x)<=eps) return y<a.y-eps; return x<a.x-eps;}
bool operator>(const point &a) const {return !(*this<a || *this==a);}
point operator+(const point &a) const {return {x+a.x,y+a.y};}
point operator-(const point &a) const {return {x-a.x,y-a.y};}
point operator-() const {return {-x,-y};}
point operator*(const T k) const {return {k*x,k*y};}
point operator/(const T k) const {return {x/k,y/k};}
T operator*(const point &a) const {return x*a.x+y*a.y;} // 点积
T operator^(const point &a) const {return x*a.y-y*a.x;} // 叉积,注意优先级
int toleft(const point &a) const {const auto t=(*this)^a; return (t>eps)-(t<-eps);} // to-left 测试
T len2() const {return (*this)*(*this);} // 向量长度的平方
T dis2(const point &a) const {return (a-(*this)).len2();} // 两点距离的平方
// 涉及浮点数
long double len() const {return sqrtl(len2());} // 向量长度
long double dis(const point &a) const {return sqrtl(dis2(a));} // 两点距离
long double ang(const point &a) const {return acosl(max(-1.0l,min(1.0l,((*this)*a)/(len()*a.len()))));} // 向量夹角
point rot(const long double rad) const {return {x*cos(rad)-y*sin(rad),x*sin(rad)+y*cos(rad)};} // 逆时针旋转(给定角度)
point rot(const long double cosr,const long double sinr) const {return {x*cosr-y*sinr,x*sinr+y*cosr};} // 逆时针旋转(给定角度的正弦与余弦)
};
using Point=point<point_t>;
// 极角排序
struct argcmp
{
bool operator()(const Point &a,const Point &b) const
{
const auto quad=[](const Point &a)
{
if (a.y<-eps) return 1;
if (a.y>eps) return 4;
if (a.x<-eps) return 5;
if (a.x>eps) return 3;
return 2;
};
const int qa=quad(a),qb=quad(b);
if (qa!=qb) return qa<qb;
const auto t=a^b;
// if (abs(t)<=eps) return a*a<b*b-eps; // 不同长度的向量需要分开
return t>eps;
}
};
// 直线
template<typename T> struct line
{
point<T> p,v; // p 为直线上一点,v 为方向向量
bool operator==(const line &a) const {return v.toleft(a.v)==0 && v.toleft(p-a.p)==0;}
int toleft(const point<T> &a) const {return v.toleft(a-p);} // to-left 测试
bool operator<(const line &a) const // 半平面交算法定义的排序
{
if (abs(v^a.v)<=eps && v*a.v>=-eps) return toleft(a.p)==-1;
return argcmp()(v,a.v);
}
// 涉及浮点数
point<T> inter(const line &a) const {return p+v*((a.v^(p-a.p))/(v^a.v));} // 直线交点
long double dis(const point<T> &a) const {return abs(v^(a-p))/v.len();} // 点到直线距离
point<T> proj(const point<T> &a) const {return p+v*((v*(a-p))/(v*v));} // 点在直线上的投影
};
using Line=line<point_t>;
//线段
template<typename T> struct segment
{
point<T> a,b;
bool operator<(const segment &s) const {return make_pair(a,b)<make_pair(s.a,s.b);}
// 判定性函数建议在整数域使用
// 判断点是否在线段上
// -1 点在线段端点 | 0 点不在线段上 | 1 点严格在线段上
int is_on(const point<T> &p) const
{
if (p==a || p==b) return -1;
return (p-a).toleft(p-b)==0 && (p-a)*(p-b)<-eps;
}
// 判断线段直线是否相交
// -1 直线经过线段端点 | 0 线段和直线不相交 | 1 线段和直线严格相交
int is_inter(const line<T> &l) const
{
if (l.toleft(a)==0 || l.toleft(b)==0) return -1;
return l.toleft(a)!=l.toleft(b);
}
// 判断两线段是否相交
// -1 在某一线段端点处相交 | 0 两线段不相交 | 1 两线段严格相交
int is_inter(const segment<T> &s) const
{
if (is_on(s.a) || is_on(s.b) || s.is_on(a) || s.is_on(b)) return -1;
const line<T> l{a,b-a},ls{s.a,s.b-s.a};
return l.toleft(s.a)*l.toleft(s.b)==-1 && ls.toleft(a)*ls.toleft(b)==-1;
}
// 点到线段距离
long double dis(const point<T> &p) const
{
if ((p-a)*(b-a)<-eps || (p-b)*(a-b)<-eps) return min(p.dis(a),p.dis(b));
const line<T> l{a,b-a};
return l.dis(p);
}
// 两线段间距离
long double dis(const segment<T> &s) const
{
if (is_inter(s)) return 0;
return min({dis(s.a),dis(s.b),s.dis(a),s.dis(b)});
}
};
using Segment=segment<point_t>;
bool check(vector<Segment> &vec)
{
for(int i=0;i<3;++i)
for(int j=i+1;j<3;++j)
if(vec[i].is_inter(vec[j])==0)return 1;
for(int i=0;i<3;++i)
for(int j=0;j<3;++j)
if(i!=j)
if((vec[i].a.y-vec[i].b.y)*(vec[j].a.x-vec[j].b.x)
==(vec[j].a.y-vec[j].b.y)*(vec[i].a.x-vec[i].b.x))
return 1;
if((vec[1].is_on(vec[0].a))
&&vec[2].is_on(vec[0].b))
{
swap(vec[0],vec[2]);
return 0;
}
if((vec[1].is_on(vec[0].b))
&&vec[2].is_on(vec[0].a))
{
swap(vec[0],vec[2]);
return 0;
}
if((vec[0].is_on(vec[1].a))
&&vec[2].is_on(vec[1].b))
{
swap(vec[1],vec[2]);
return 0;
}
if((vec[0].is_on(vec[1].b))
&&vec[2].is_on(vec[1].a))
{
swap(vec[1],vec[2]);
return 0;
}
if((vec[1].is_on(vec[2].a))
&&vec[0].is_on(vec[2].b))
return 0;
if((vec[1].is_on(vec[2].b))
&&vec[0].is_on(vec[2].a))return 0;
return 1;
}
vector<Point> dot;
void print(Segment a)
{
cout<<"Seg-->"<<a.a.x<<" "<<a.a.y<<" "<<a.b.x<<" "<<a.b.y<<endl;
}
bool check_vec(vector<Line> vec)
{
if(vec[0].toleft(vec[1].v)==0)return true;
if(vec[0].toleft(vec[2].v)==0)return true;
if(vec[1].toleft(vec[2].v)==0)return true;
return false;
}
bool check2(vector<Segment> vec)
{
if(vec[0].a==vec[1].a)
{
dot.push_back(vec[0].a);dot.push_back(vec[0].b);
dot.push_back(vec[1].a);dot.push_back(vec[1].b);
return 0;
}
if(vec[0].b==vec[1].b)
{
dot.push_back(vec[0].b);dot.push_back(vec[0].a);
dot.push_back(vec[1].b);dot.push_back(vec[1].a);
return 0;
}
if(vec[1].b==vec[0].a)
{dot.push_back(vec[1].b);dot.push_back(vec[1].a);
dot.push_back(vec[0].a);dot.push_back(vec[0].b);
return 0;}
if(vec[0].b==vec[1].a)
{dot.push_back(vec[1].a);dot.push_back(vec[1].b);
dot.push_back(vec[0].b);dot.push_back(vec[0].a);
return 0;}
return 1;
}
bool ccheck(vector<Point> vec)
{
Segment s1={vec[0],vec[1]};
if(s1.is_on(vec[4])==0)swap(vec[4],vec[5]);
point_t l1=vec[0].dis2(vec[4]),l2=vec[2].dis2(vec[5]),
l3=vec[1].dis2(vec[4]),l4=vec[0].dis2(vec[4]),
l6=vec[2].dis2(vec[5]),l7=vec[3].dis2(vec[5]),
l5=vec[4].dis2(vec[5]);
if(l1+l2-l5<0)return false;
if(max(l4,l3)>(__int128)min(l4,l3)*16)return false;
if(max(l6,l7)>(__int128)min(l6,l7)*16)return false;
return true;
}
bool is_right_triangle(vector<Point> &vec)
{
point_t a=vec[0].dis2(vec[1]),b=vec[2].dis2(vec[3]),
c=vec[4].dis2(vec[5]);
if(a+b==c||a+c==b||b+c==a)return true;
return false;
}
void solve()
{
dot.clear();
vector<Point> vec(6);
for(point_t i=0,x,y;i<6;++i)
{
scanf("%lld%lld",&x,&y);
vec[i]={x,y};
}
vector<Line>vecl(3);
for(int i=0;i<3;++i)
{
vecl[i]={vec[i*2],vec[(i*2)^1]-vec[i*2]};
}
vector<Segment>vecs(3);
for(int i=0;i<3;++i)
vecs[i]={vec[i*2],vec[(i*2)^1]};
// for(int i=0;i<3;++i)
if(check(vecs)){printf("NO\n");return ;}
if(check2(vecs)){printf("NO\n");return ;}
if(is_right_triangle(vec)) {printf("NO\n");return ;}
dot.push_back(vecs[2].a);
dot.push_back(vecs[2].b);
for(int i=0;i<3;++i)
vec[i*2]=vecs[i].a,vec[(i*2)^1]=vecs[i].b;
if(check_vec(vecl)){printf("NO\n");return ;}
if(ccheck(dot)) {printf("YES\n");return ;}
printf("NO\n");
}
int main()
{
int T;scanf("%d",&T);
while(T--)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"
] | // RADHASOAMI , WITH THE GRACE OF HUZUR I PROMISE TO FIGHT TILL THE LAST SECOND OF EVERY CONTEST AND CODE TO MY FULL POTENTIAL ......
#include <iostream>
#include <vector>
#include <unordered_map>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
#define ll long long int
#define mod 1000000007
using namespace std;
// ==================== FUNCTIONS FOR INPUT AND OUTPUT OF VECTORS =======================================================
void input(vector < ll > &arr)
{
for(int i = 0;i < arr.size();i++)
cin >> arr[i];
}
void output(vector < ll > &arr)
{
for(int i = 0;i < arr.size();i++)
cout << arr[i] << " ";
cout << "\n";
}
// ============================== FOR MATHEMATICAL FUNCTIONS =============================================================
ll gcd(ll a,ll b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
ll power(ll a,ll b)
{
if(b==0)
return 1;
if(b==1)
return a;
ll smallans=power(a,b/2);
ll myans=(smallans*smallans)%mod;
if((b&1))
myans=(myans*a)%mod;
return myans;
}
ll multiply(ll a,ll b)
{
ll ans=((a%mod)*(b%mod))%mod;
return ans;
}
ll divide(ll a,ll b)
{
return multiply(a,power(b,mod-2));
}
// ============================ SEGMENT TREE FOR DEFAULT MINIMUM QUERY ==================================================
void manageLazy(vector <ll> &tree,vector <ll> &lazy,ll idx)
{
tree[2*idx + 1] += lazy[idx];
lazy[2*idx + 1] += lazy[idx];
tree[2*idx + 2] += lazy[idx];
lazy[2*idx + 2] += lazy[idx];
lazy[idx] = 0;
}
void build(vector <ll> &tree,vector <ll> &arr,ll left,ll right,ll idx)
{
if(left == right)
{
tree[idx] = arr[left];
return;
}
ll mid = (left + right) / 2;
build(tree , arr , left , mid , 2*idx + 1);
build(tree , arr , mid + 1 , right , 2*idx + 2);
tree[idx] = min(tree[2*idx + 1],tree[2*idx + 2]);
}
void update(vector <ll> &tree,vector <ll> &lazy,ll tl,ll tr,ll l,ll r,ll idx,ll val)
{
if(l > r)
return;
if(l == tl && tr == r)
{
tree[idx] += val;
lazy[idx] += val;
return;
}
manageLazy(tree,lazy,idx);
ll mid = (tl + tr) / 2;
update(tree,lazy,tl,mid,l,min(r,mid),2*idx + 1,val);
update(tree,lazy,mid + 1,tr,max(l,mid + 1),r,2*idx + 2,val);
tree[idx] = min(tree[2*idx + 1],tree[2*idx + 2]);
}
ll query(vector <ll> &tree,vector<ll> & lazy,ll tl,ll tr,ll l,ll r,ll idx)
{
if(l > r)
return 1e18;
if(l <= tl && tr <= r)
return tree[idx];
manageLazy(tree,lazy,idx);
ll mid = (tl + tr) / 2;
ll a = query(tree,lazy,tl,mid,l,min(r,mid),2*idx + 1);
ll b = query(tree,lazy,mid + 1,tr,max(l,mid + 1),r,2*idx + 2);
return min(a,b);
}
// ================================== SPARSE TABLE FOR DEFAULT MINIMUM QUERY ==================================================
void precompute_min(vector < vector < ll > > &sparsetable , vector < ll > &a)
{
int n = sparsetable.size();
int p = sparsetable[0].size();
for(int i = 0;i < n;i++)
sparsetable[i][0] = a[i];
for(int j = 1;j < p;j++)
{
for(int i = 0;i + (1 << j) <= n;i++)
sparsetable[i][j] = min(sparsetable[i][j - 1] , sparsetable[i + (1 << (j - 1))][j - 1]);
}
}
ll minquery(vector < vector < ll > > &sparsetable , vector < ll > &log , ll l , ll r)
{
ll range = r - l + 1;
if(range == 0) return sparsetable[l][0];
ll j = log[range];
return min(sparsetable[l][j] , sparsetable[r - (1 << j) + 1][j]);
}
//========================== BINARY INDEX TREE =========================================================================
void update(vector<ll> &tree,ll index,ll val)
{
index++;
while(index < tree.size())
{
tree[index]=(tree[index] + val) %mod;
index+=index&(-index);
}
}
ll calculate(vector<ll> &tree,ll index)
{
ll sum=0;
index++;
while(index > 0)
{
sum=(sum + tree[index])%mod;
index-=index&(-index);
}
return sum;
}
//=========================== FOR DISJOINT SET UNION ====================================================================
ll findpar(ll p,vector<ll> &parent)
{
if(parent[p]==p)
return p;
parent[p]=findpar(parent[p],parent);
return parent[p];
}
void merge(ll a, ll b,vector<ll> &parent,vector<ll> &size_)
{
a = findpar(a,parent);
b = findpar(b,parent);
if (a != b)
{
if (size_[a] < size_[b])
swap(a, b);
parent[b] = a;
size_[a] += size_[b];
}
}
// ====================================== FOR STORING AND COUNTING THE PRIMES USING SIEVE ============================
void sieve(vector<bool> &primes,vector<ll> &count)
{
for(int i=2;i<primes.size();i++)
{
if(primes[i])
{
count.push_back(i);
for(int j=i*i;j<primes.size();j+=i)
primes[j]=false;
}
}
}
// =====================================================================================================================
void solve()
{
ll n;
cin >> n;
string s;
cin >> s;
string ans = s;
ll k = 1;
for(int i = 1;i < n;i++) {
string curr = "";
for(int j = i;j < n;j++) curr += s[j];
ll left = n - i;
if(left % 2) {
for(int j = i - 1;j >= 0;j--) curr += s[j];
}
else {
for(int j = 0;j < i;j++) curr += s[j];
}
if(curr < ans) {
ans = curr;
k = i + 1;
}
}
cout << ans << "\n";
cout << k << "\n";
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input2.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
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"
] | // LUOGU_RID: 99403697
#include<bits/stdc++.h>
using namespace std;
#define N 1050
int n,k,a[N],ans;
bool flag[N];
int read(){
char ch[2];
scanf("%s",ch);
return ch[0]=='Y';
}
int main(){
scanf("%d%d",&n,&k);
int x,b;
if(k==1){
ans=1;
for(int i=2;i<=n;i++){
bool f=1;
for(int j=1;j<i;j++){
cout<<"? "<<j<<endl;
x=read();
cout<<"? "<<i<<endl;
x=read();
if(x){
f=0;
break;
}
}
ans+=f;
}
printf("! %d",ans);
return 0;
}
k>>=1,b=n/k,ans=0;
for(int i=1;i<=k;i++){
cout<<"? "<<i<<endl;
x=read();
if(!x)ans++;
}
cout<<"R"<<endl;
for(int i=2;i<=b;i++){
memset(flag,0,sizeof(flag));
for(int j=1;j<i;j++){
for(int l=(j-1)*k+1;l<=j*k;l++){
cout<<"? "<<l<<endl;
x=read();
}
for(int l=(i-1)*k+1;l<=i*k;l++){
cout<<"? "<<l<<endl;
x=read();
if(x)flag[l-(i-1)*k]=1;
}
cout<<"R"<<endl;
}
for(int j=1;j<=k;j++)
if(!flag[j])ans++;
}
cout<<"! "<<ans<<endl;
return 0;
} | 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;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
const ll MAXN = 1e6 + 20;
const ll MOD = 1e9 + 7;
const ll INF = 1e18;
#define pb push_back
#define Mp make_pair
#define F first
#define S second
#define Sz(x) int((x).size())
#define endll '\n'
ll a[MAXN], b[MAXN];
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
ll n, m, p, x = 0, y = 0;
cin >> n >> m >> p;
for(int i = 0; i < n; i ++){
cin >> a[i];
if(a[i] % p) x = i;
}
for(int i = 0; i < m; i ++){
cin >> b[i];
if(b[i] % p) y = i;
}
cout << x + y << endl;
return 0;
} | 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>
//My codes-------------->>>>
#define vi vector<int>
#define vl vector<ll>
#define vc vector<char>
#define vii vector<vi>
#define vcc vector<vc>
#define ll long long
#define ld long double
#define sortx(X) sort(X.begin(),X.end());
using namespace std;
void FP()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
}
ll samm(ll n) {
return (n * (n + 1)) / 2;
}
ll mod2(ll t) {
ll summ = 0;
while (t % 2 == 0)
{
t /= 2;
summ++;
}
return summ;
}
void solve() {
ll n, m ,a=0,b=0;
cin >> n >> m;
if (m % n != 0)
{
cout << -1;
return;
}
m /= n;
while (m%2==0)
{
a++;
m /= 2;
}
while (m%3==0)
{
b++;
m /= 3;
}
if (m!= 1)
{
cout << -1;
}else cout << a + b;
}
int main()
{
FP();
int size = 1;
//cin >> size;
while (size--)
{
solve();
}
}
/*
███████╗██╗ ██╗ █████╗ ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗██╗ ██╗
╚════██║╚██╗ ██╔╝██╔══██╗██╔══██╗ ██║ ██║██╔══██╗████╗ ██║╚██╗ ██╔╝
███╔═╝ ╚████╔╝ ███████║██║ ██║ ███████║███████║██╔██╗██║ ╚████╔╝
██╔══╝ ╚██╔╝ ██╔══██║██║ ██║ ██╔══██║██╔══██║██║╚████║ ╚██╔╝
███████╗ ██║ ██║ ██║██████╔╝ ██║ ██║██║ ██║██║ ╚███║ ██║
╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚══╝ ╚═╝
*/
| cpp |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n) — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111. | [
"dfs and similar",
"dsu",
"graphs"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
const int inf = 1e9;
const int maxn = 3e5 + 10;
typedef pair<int,int> ii;
#define ff first
#define ss second
int n,m,k;
vector <int> adj[maxn],b[maxn];
int a[maxn];
ii e[maxn];
int ans=0;
ii p[maxn],num[maxn];
int s[maxn];
ii get(int x)
{
if (p[x].ff!=x)
{
ii temp = get(p[x].ff);
p[x].ff=temp.ff;
p[x].ss^=temp.ss;
}
return p[x];
}
void hop(int x, int y, int w)
{
ii xx = get(x); ii yy = get(y);
x=xx.ff; y=yy.ff;
// cout<<x<<' '<<y<<' '<<w<<"!!\n";;
if (x==y) return;
if (s[x]>s[y])
{
swap(x,y);
swap(xx,yy);
}
ans -= min(num[x].ff,num[x].ss);
ans -= min(num[y].ff,num[y].ss);
int val = (xx.ss^yy.ss^w);
if (val==0)
{
num[y].ff+=num[x].ff; num[y].ss+=num[x].ss;
}
else
{
num[y].ff+=num[x].ss; num[y].ss+=num[x].ff;
}
p[x]={y,val};
s[y]+=s[x];
ans+=min(num[y].ff,num[y].ss);
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
cin>>n>>k;
for (int i=1; i<=n; i++)
{
char c; cin>>c;
a[i]=(c=='1');
}
for (int i=1; i<=k; i++)
{
int m; cin>>m;
while (m--)
{
int x; cin>>x;
b[x].push_back(i);
}
}
for (int i=1; i<=k; i++)
{
p[i]={i,0};
s[i]=1;
num[i]={1,0};
}
for (int i=1; i<=n; i++)
{
if (b[i].size()==2)
{
int u=b[i][0]; int v=b[i][1];
hop(u,v,a[i]^1);
}
else if (b[i].size()==1)
{
int u=b[i][0];
ii uu=get(u);
u=uu.ff;
ans-=min(num[u].ff,num[u].ss);
if (uu.ss==(a[i]^1)) num[u].ff+=inf;
else num[u].ss+=inf;
ans+=min(num[u].ff,num[u].ss);
}
cout<<ans<<'\n';
}
}
| cpp |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | #include <bits/stdc++.h>
#define ios ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)
#define all(a) a.begin() , a.end()
#define F first
#define S second
using namespace std;
using ll = long long;
const ll N = 3e5+5 , M = 10 ,inf = 2e9 + 7;
const ll INF = 1e18 , mod = 1e9+7 , P = 6547;
ll a[N][M] , n , m , pos[1024];
pair<ll,ll> check(ll md){
for(int mask = 0; mask < (1ll << m); mask++) pos[mask] = 0;
for(int i = 1; i <= n; i++){
ll num = 0 , kk = 0;
for(int j = 0; j < m; j++) {
if(a[i][j] >= md) num += (1ll << j);
else kk += (1ll << j);
}
if(pos[kk] > 0) return {pos[kk],i};
if(kk == 0) return {i,i};
for(int sb = num; sb > 0; sb = ((sb-1) & num)) pos[sb] = i;
}
return {0,0};
}
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 0; j < m; j++) cin >> a[i][j];
}
pair<ll,ll> res = {1,1};
for(ll l = 0 , r = 1e9; l <= r;){
ll md = (l+r) >> 1;
pair<ll,ll> r1 = check(md);
if(r1.F != 0) {
res = r1 , l = md+1;
}
else r = md-1;
}
cout << res.F <<" " << res.S <<"\n";
}
signed main(){
ios;
solve();
return 0;
} | cpp |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,k;
cin>>n>>k;
int move=0;
if(n==k){
cout<<0<<"\n";
}
else if(n<k){
if((k-n)%2!=0) cout<<1<<"\n";
else cout<<2<<"\n";
}
else{
if((n-k)%2==0) cout<<1<<"\n";
else cout<<(2)<<"\n";
}
}
return 0;
} | cpp |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | #pragma GCC optimize("O3,unroll-loops")
#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;
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD 1000000007
#define MOD1 998244353
#define INF 1e18
#define nline "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#ifdef tushar23
#define debug(x) cerr << #x<<" "; _print(x); cerr << endl;
#else
#define debug(x);
#endif
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
typedef __int128 ell;
typedef tree<pair<ll, ll>, null_type, less<pair<ll, ll>>, rb_tree_tag, tree_order_statistics_node_update > pbds; // find_by_order, order_of_key
void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
void _print(pbds v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
/*---------------------------------------------------------------------------------------------------------------------------*/
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3
ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b
ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}
bool revsort(ll a, ll b) {return a > b;}
ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}
void google(int t) {cout << "Case #" << t << ": ";}
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m
ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))
ll getRandomNumber(ll l, ll r) {return uniform_int_distribution<ll>(l, r)(rng);}
/*--------------------------------------------------------------------------------------------------------------------------*/
void solve() {
ll n;
cin>>n;
vector<ll> v(n);
for(int i=0; i<n; i++){
cin>>v[i];
}
ll left = n-1;
ll right = 0;
ll prev = -1;
for(int i=0; i<n; i++){
if(v[i] > prev)
prev++;
else{
left = i-1;
break;
}
}
prev = -1;
for(int i=n-1; i>=0; i--){
if(v[i] > prev)
prev++;
else{
right = i+1;
break;
}
}
if(left >= right){
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}
}
int main() {
#ifdef tushar23
freopen("Error.txt", "w", stderr);
#endif
fastio();
auto start1 = high_resolution_clock::now();
int t;
cin>>t;
while(t--){
solve();
}
auto stop1 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop1 - start1);
#ifdef tushar23
cerr << "Time: " << duration . count() / 1000 << endl;
#endif
} | 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;
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("O2")
using ll = long long;
#define int long long
#define forn(i,n) for(int i=0; i<n; ++i)
#define pb push_back
#define pi pair<int,int>
#define f first
#define s second
#define vii(a,n) vector<int> a(n); forn(i,n) cin>>a[i];
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//const int inf = 1e18;
const int mod = 1e9+7;//998244353;
const int maxn=3e3;
vector<int> adj[maxn];
int sz[maxn][maxn]; //sz[v][par_v];
int dp[maxn][maxn];
int pu[maxn][maxn];
int pv[maxn][maxn];
int vis[maxn][maxn];
int getsz(int u, int p) {
int r=1;
for(auto&v:adj[u]) {
if (v==p) continue;
r+=getsz(v,u);
}
return r;
}
void solve() {
int n; cin>>n;
forn(i,n-1) {
int u,v; cin>>u>>v; --u, --v;
adj[u].pb(v);
adj[v].pb(u);
}
forn(i,n) forn(j,n) dp[i][j]=sz[i][j]=pu[i][j]=pv[i][j]=vis[i][j]=0;
forn(u,n) {
for(auto&v:adj[u]) {
sz[u][v]=getsz(u,v);
}
}
queue<pi> q;
forn(u,n) {
for(auto&v:adj[u]) {
dp[u][v]=sz[u][v]*sz[v][u];
pu[u][v]=v, pv[u][v]=u;
q.push({u,v});
}
}
while (q.size()) {
auto it = q.front();
int u=it.f, v=it.s;
q.pop();
for(auto&u1:adj[v]) {
if (u1==pv[u][v]) continue;
if (!vis[u][u1]) q.push({u,u1});
vis[u][u1]=1;
int x=sz[u][pu[u][v]]*sz[u1][v]+dp[u][v];
if (x>dp[u][u1]) {
dp[u][u1]=x;
pu[u][u1]=pu[u][v];
pv[u][u1]=v;
}
}
for(auto&v1:adj[u]) {
if (v1==pu[u][v]) continue;
if (!vis[v1][v]) q.push({v1,v});
vis[v1][v]=1;
int x=sz[v1][u]*sz[v][pv[u][v]]+dp[u][v];
if (x>dp[v1][v]) {
dp[v1][v]=x;
pu[v1][v]=u;
pv[v1][v]=pv[u][v];
}
}
}
int ans=0;
forn(i,n) forn(j,n) ans=max(ans,dp[i][j]);
cout<<ans;
}
int32_t main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t=1;
//cin>>t;
while (t--) solve();
return 0;
} | cpp |
1307 | F | F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n) — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105) — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi) — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below. | [
"dfs and similar",
"dsu",
"trees"
] | // LUOGU_RID: 90198724
#include<bits/stdc++.h>
using namespace std;
const int N=4e5+10;
const int M=N*2;
int n,m,k;
int tot;
int head[N],ver[M],ne[M];
void add(int x,int y)
{
ver[++tot]=y;
ne[tot]=head[x];
head[x]=tot;
}
int d[N];
int f[N][25];
void dfs(int x,int fath)
{
d[x]=d[fath]+1;
for(int i=1;i<=20;i++) f[x][i]=f[f[x][i-1]][i-1];
for(int i=head[x];i;i=ne[i])
{
int y=ver[i];
if(y==fath) continue;
f[y][0]=x;
dfs(y,x);
}
}
int lca(int x,int y)
{
if(d[x]<d[y]) swap(x,y);
for(int i=20;i>=0;i--)
{
if(d[f[x][i]]>=d[y])
x=f[x][i];
}
if(x==y) return x;
for(int i=20;i>=0;i--)
{
if(f[x][i]!=f[y][i])
x=f[x][i],y=f[y][i];
}
return f[x][0];
}
int dis[N];
int fa[N];
int get(int x)
{
if(x==fa[x])return x;
return fa[x]=get(fa[x]);
}
void vacation()
{
queue<int>q;
memset(dis,-1,sizeof(dis));
for(int i=1;i<=k;i++)
{
int x;
scanf("%d",&x);
dis[x]=0;
q.push(x);
}
while(q.size())
{
int x=q.front();q.pop();
if(dis[x]==m) break;
for(int i=head[x];i;i=ne[i])
{
int y=ver[i];
fa[get(y)]=get(x);
if(dis[y]==-1)
{
dis[y]=dis[x]+1;
q.push(y);
}
}
}
}
int move(int x,int len)
{
for(int i=20;i>=0;i--)
{
if((1<<i)<=len)
{
len-=(1<<i);
x=f[x][i];
}
}
return x;
}
int main(){
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=n*2;i++) fa[i]=i;
for(int i=1;i<n;i++)
{
int x,y;
cin>>x>>y;
add(x,n+i);
add(y,n+i);
add(n+i,x);
add(n+i,y);
}
dfs(1,0);
vacation();
int q;
cin>>q;
while(q--)
{
int x,y;
scanf("%d%d",&x,&y);
int z=lca(x,y);
int len=d[x]+d[y]-2*d[z];
if(len<=2*m) printf("YES\n");
else
{
int ans1=(m<=(d[x]-d[z]))?get(move(x,m)):get(move(y,len-m));
int ans2=(m<=(d[y]-d[z]))?get(move(y,m)):get(move(x,len-m));
if(ans1==ans2) printf("YES\n");
else printf("NO\n");
}
}
return 0;
} | 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()
{
double a, b, c = 0;cin>>a>>b;
double ans = b/a;
if(static_cast<long long>(pow(2, 0)*pow(3, 0)==ans)) c = 0;
else{
for(int i = 0; i < 31;i++){
for(int j = 0; j < 31;j++){
if(pow(2, i) * pow(3, j)==ans){
c = i+j;
cout<<c<<endl;
return 0;
}
if(pow(2, i) * pow(3, j) > b){
c = -1;
break;
}
}
}
}
cout<<c<<endl;
} | 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 rep(i, n) for (int i = 0; i < n; i++)
vector< vector< int > > lista_ad;
vector < vector< int >> lista_ad2;
vector< int > distancias;
vector<bool> visitados;
void bfs(int inicio){
queue <int> cola;
visitados[inicio] = true;
cola.push(inicio);
distancias[inicio] = 0;
while(!cola.empty()){
int actual = cola.front();
cola.pop();
for(int i = 0; i < lista_ad[actual].size(); i++){
if(visitados[lista_ad[actual][i]] == false){
visitados[lista_ad[actual][i]] = true;
cola.push(lista_ad[actual][i]);
distancias[lista_ad[actual][i]] = distancias[actual] + 1;
}
}
}
}
void addEdge(int a, int b){
lista_ad[b].push_back(a);
lista_ad2[a].push_back(b);
}
int main(){
ios::sync_with_stdio(0); cin.tie(0);
int n, m;
cin >> n >> m;
lista_ad.assign(n, vector<int>(0));
lista_ad2.assign(n, vector<int>(0));
visitados.assign(n, 0);
distancias.assign(n, -1);
rep(i, m){
int a, b;
cin >> a >> b;
a--;
b--;
addEdge(a, b);
}
int k, rbmin = 0, rbmax=0;
cin >> k;
vector<int> camino(k);
rep(i, k) cin >> camino[i];
rep(i, k) camino[i]--;
bfs(camino[k-1]);
//rep(i, n) cerr << distancias[i] << endl;
rep(i, k-1){
int p = camino[i], l = camino[i+1];
if(distancias[l] >= distancias[p]){
rbmin++; rbmax++;
} else {
int cnt=0;
rep(j, lista_ad2[p].size()){
if(distancias[lista_ad2[p][j]] == distancias[l]) cnt++;
//cerr << cnt << ' ' << lista_ad2[p][j] << ' ' << p << endl;
if(cnt == 2){
rbmax++;
break;
}
}
}
}
cout << rbmin << ' ' << rbmax << endl;
return 0;
}
| 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"
] | //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,m,one_time=0,single=0;cin>>n>>m;
map <string,bool > m1;
string s1="",s2="",s3="",s4="";
FOR(i,0,n)
{
string s;cin>>s;
m1[s]=1;
}
for(auto &val : m1)
{
if(val.ss==1)
{
string temp=val.first;
val.second=0;
reverse(all(temp));
if(m1.find(temp)!=m1.end() && m1[temp]==1)
{
s1+=val.first;
s2+=val.first;
m1[temp]=0;
}
else if(one_time==0)
{
ll ct=0;
FOR(i,0,m/2)
{
if(val.ff[i]==val.ff[m-i-1])
{
ct++;
}
}
if((ct*2)==m || (ct*2)==m-1)
{
s3+=val.first;
one_time++;
}
}
}
}
s1+=s3;
reverse(all(s2));
s1+=s2;
cout<<s1.size()<<'\n';
cout<<s1<<'\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 |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define sz(s) (int)s.size()
#define F .first
#define S .second
#define all(v) ((v).begin()),((v).end())
#define allr(v) ((v).rbegin()),((v).rend())
const int mod = 1e9 + 7;
const int N = 2e5+5;
int dx[] { 1, -1, 0, 0, 1, 1, -1, -1 };
int dy[] { 0, 0, 1, -1, 1, -1, 1, -1 };
int main()
{
std::ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
//freopen("endure.in", "r", stdin);
//freopen("", "w", stdout);
int n;
double ans=0;
cin>>n;
for(int i=1;i<=n;i++){
ans+=(1./i);
}
cout<<fixed<<setprecision(12)<<ans;
}
| cpp |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105) — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | #include<bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define int long long
#define vi vector<int>
#define pii pair<int, int>
#define m_p make_pair
#define pyes cout << "Yes\n"
#define pno cout << "No\n"
using namespace std;
#define fastIO() \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
template<typename T> istream& operator>>(istream& in, vector<T>& a) {for (auto &x : a) in >> x; return in;};
template<typename T> ostream& operator<<(ostream& out, vector<T>& a) {for (auto &x : a) out << x << ' '; return out;};
void print(vector<int> a) {
for(auto it : a) {
cout << it << " ";
}
cout << '\n';
}
void print(vector<vi> a) {
for(auto it : a) {
for(auto kt : it) {
cout << kt << ' ';
}
cout << "\n";
}
}
void print(pii a) {
cout << a.first << "_" << a.second << '\n';
}
void print(vector<pii> a) {
for(auto it : a) {
cout << it.first << "_" << it.second << " ";
}
cout << '\n';
}
void print(vector<vector<pii>> a) {
for(auto it : a) {
for(auto kt : it) {
cout << kt.first << "_" << kt.second << " ";
}
cout << '\n';
}
}
vector<vector<int>> prefx;
int query(int l, int r) {
int ans = 0;
for(int j=0; j<26; j++) {
int x = prefx[j][r] - (l-1<0?0:prefx[j][l-1]);
if(x) ans++;
}
return ans;
}
void solve() {
string s;
cin >> s;
int n = s.size();
prefx = vector<vector<int>> (26, vector<int> (n, 0));
for(int i=0; i<(int)s.size(); i++) {
prefx[s[i]-'a'][i]++;
for(int j=0; j<26; j++) {
if(i)
prefx[j][i] += prefx[j][i-1];
}
}
int q;
cin >> q;
while(q--) {
int a, b;
cin >> a >> b;
--a; --b;
if(a == b) {
pyes;
continue;
}
if(s[a] != s[b]) {
pyes;
continue;
}
else if(query(a, b) >= 3) {
pyes;
continue;
} else {
pno;
}
}
}
signed main() {
fastIO();
int t = 1;
for(int i=0; i<t; i++) solve();
return 0;
}
| cpp |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define multiordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>
#define lop(i,n) for(ll i=0;i<n;i++)
#define lop1(i,n) for(ll i=1;i<=n;i++)
#define lopr(i,n) for(ll i=n-1;i>=0;i--)
#define ll long long int
#define pb push_back
#define all(v) v.begin(),v.end()
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define endl '\n'
#define ff first
#define ss second
#define mem(arr,val) memset(arr,val,sizeof(arr))
#define pii pair<int,int>
#define pll pair<ll,ll>
#define LCM(a,b) (a/__gcd(a,b))*b
#define mii map<int,int>
#define mll map<ll,ll>
#define ub upper_bound
#define lb lower_bound
#define sz(x) (ll)x.size()
#define ld long double
#define pcnt(x) __builtin_popcountll(x)
#define yes cout<<"YES"<<endl
#define no cout<<"NO"<<endl
const long long I1=1e9;
const long long I2=1e18;
const int32_t M1=1e9+7;
const int32_t M2=998244353;
ll binpow(ll a, ll b)
{
ll res=1;
while(b>0)
{
if(b%2==1) res=res*a;
a=a*a;
b=b/2;
}
return res;
}
ll binexp(ll a, ll b, ll mod)
{
ll res=1;
while(b>0)
{
if(b%2==1) res=((res%mod)*(a%mod))%mod;
a=((a%mod)*(a%mod))%mod;
b=b/2;
}
return res;
}
ll fact(ll n,ll mod)
{
ll ans=1;
for(ll i=2;i<=n;i++)
ans=((ans%mod)*(i%mod)+mod)%mod;
ans%=mod;
return ans;
}
ll nCr(ll n,ll r,ll mod)
{
ll ri=binexp(fact(r,mod),mod-2,mod);
ll nri=binexp(fact(n-r,mod),mod-2,mod);
ll ans=(((fact(n,mod)%mod)*(ri%mod))%mod);
ans=(((ans%mod)*(nri%mod))%mod);
ans%=mod;
ans=(ans+mod)%mod;
return ans;
}
void solve()
{
ll xo,yo,ax,ay,bx,by;
cin>>xo>>yo>>ax>>ay>>bx>>by;
ll xs,ys,t;
cin>>xs>>ys>>t;
ll mx=(1ll<<62)-1;
vector<pll> v;
ll x=xo,y=yo;
v.pb({x,y});
while(1)
{
ll temp=(mx-bx)/ax;
if(x<=temp) x=ax*x+bx;
else break;
temp=(mx-by)/ay;
if(y<=temp) y=ay*y+by;
else break;
v.pb({x,y});
}
//lop(i,sz(v)) cout<<v[i].ff<<" "<<v[i].ss<<endl;
ll ans=0;
for(ll i=0;i<sz(v);i++)
{
for(ll j=i;j<sz(v);j++)
{
ll d=abs(xs-v[i].ff)+abs(ys-v[i].ss);
if(d>t) break;
ll a=abs(v[j].ff-v[i].ff)+abs(v[j].ss-v[i].ss);
if(d<=t-a) ans=max(ans,j-i+1);
else break;
}
for(ll j=i;j>=0;j--)
{
ll d=abs(xs-v[i].ff)+abs(ys-v[i].ss);
if(d>t) break;
ll a=abs(v[j].ff-v[i].ff)+abs(v[j].ss-v[i].ss);
if(d<=t-a) ans=max(ans,i-j+1);
else break;
}
}
cout<<ans;
}
int main()
{
IOS;
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
ll t;
t=1;
//cin>>t;
while(t--)
{
solve();
}
} | cpp |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | //DEEPANSHU SONKAR
//2113092
#include<bits/stdc++.h>
#define turbo() \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
#define ll long long
const ll mod=1000000007;
const ll INF= 1e9+7;
#define pb push_back
#define pp pop_back
#define mp make_pair
#define pf push_front
#define vll vector<ll>
#define get(a,n) vll a(n); for(int i=0;i<n;i++) cin>>a[i];
#define print(a,n) for(int i=0;i<n;i++) cout<<a[i]<<" "; cout<<endl;
#define all(x) ((x).begin(),(x).end())
#define vsort(vec) sort(vec.begin(),vec.end());
#define rvsort(vec) sort(vec.begin(),vec.end(),greater<int>());
#define tc() long long int t;cin>>t;while(t--)
#define rep(var,start,to) for(ll var=start;var<to;var++)
#define rep1(a, b, c) for (ll a = b; a >= c; a--)
#define yes cout<<"YES"<<endl;
#define no cout<<"NO"<<endl;
#define google cout<<"Case #"<<i+1<<": ";
using namespace std;
bool isprime(int n) {
bool f = true;
if (n == 0 || n == 1) {
f = false;
}
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
f = false;
break;
}
}
return f;
}
void codingkarlo_BC(){
ll n;cin>>n;
get(a,n);
get(b,n);
vsort(a);
vsort(b);
print(a,n);
print(b,n);
}
signed main()
{
turbo()
//codingkarlo_BC();
tc(){ codingkarlo_BC(); /*google*/ }
return 0;
} | cpp |
1286 | D | D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2
1 1 100
3 1 0
OutputCopy1
InputCopy3
7 10 0
9 4 86
14 5 100
OutputCopy0
InputCopy4
6 4 50
11 25 50
13 16 50
15 8 50
OutputCopy150902884
| [
"data structures",
"math",
"matrices",
"probabilities"
] | #include <bits/stdc++.h>
#define maxn 100005
#define ll long long
const int mod = 998244353;
int n, p[2][maxn], x[maxn], v[maxn], tl;
struct mat
{
int a[2][2];
} M[maxn];
mat mt(int a, int b, int c, int d)
{
mat m;
m.a[0][0] = a;
m.a[0][1] = b;
m.a[1][0] = c;
m.a[1][1] = d;
return m;
}
mat mul(mat a, mat b)
{
mat c = mt(0, 0, 0, 0);
for (int k = 0; k < 2; ++k)
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
c.a[i][j] = (c.a[i][j] + (ll)a.a[i][k] * b.a[k][j] % mod) % mod;
return c;
}
struct query
{
int s, v, p, i, j;
} q[maxn << 2];
int cmp(query a, query b)
{
return (ll)a.s * b.v < (ll)b.s * a.v;
}
int get_speed(int i, int k1, int k2)
{
if (k1 == 0 && k2 == 1)
return -1;
if (k1 == 1 && k2 == 0)
return v[i] + v[i + 1];
if (k1 == 1 && k2 == 1)
return v[i] - v[i + 1];
if (k1 == 0 && k2 == 0)
return v[i + 1] - v[i];
}
int qpow(int a, int b)
{
if (b == 0)
return 1;
ll d = qpow(a, b >> 1);
d = d * d % mod;
if (b & 1)
d = d * a % mod;
return d;
}
int inv(int x) { return qpow(x, mod - 2); }
struct
{
mat sum[maxn << 2];
void update(int rt)
{
sum[rt] = mul(sum[rt << 1], sum[rt << 1 | 1]);
}
void build(int l, int r, int rt)
{
if (l == r)
{
sum[rt] = M[l];
return;
}
build(l, (l + r) >> 1, rt << 1);
build(((l + r) >> 1) + 1, r, rt << 1 | 1);
update(rt);
}
void modify(int l, int r, int p, int rt)
{
if (l == r)
{
sum[rt] = M[l];
return;
}
int mid = (l + r) >> 1;
if (p <= mid)
modify(l, mid, p, rt << 1);
else
modify(mid + 1, r, p, rt << 1 | 1);
update(rt);
}
} sgt;
int main()
{
ll ans = 0;
scanf("%d", &n);
if (n == 1)
{
printf("0");
return 0;
}
for (int i = 1; i <= n; ++i)
{
scanf("%d%d%d", &x[i], &v[i], &p[1][i]);
p[1][i] = (ll)p[1][i] * qpow(100, mod - 2) % mod;
p[0][i] = (1 - p[1][i] + mod) % mod;
}
for (int i = 1; i < n; ++i)
{
for (int j = 0; j < 2; ++j)
for (int k = 0; k < 2; ++k)
{
if (get_speed(i, j, k) < 0)
continue;
q[++tl].s = x[i + 1] - x[i];
q[tl].v = get_speed(i, j, k);
q[tl].p = i;
q[tl].i = j;
q[tl].j = k;
}
}
for (int i = 0; i < n; ++i)
M[i] = mt(p[0][i + 1], p[1][i + 1], p[0][i + 1], p[1][i + 1]);
sgt.build(1, n - 1, 1);
mat m1 = mul(M[0], sgt.sum[1]);
std::sort(q + 1, q + tl + 1, cmp);
for (int i = 1; i <= tl; ++i)
{
mat m1 = M[q[i].p], m2 = mt(0, 0, 0, 0);
m2.a[q[i].i][q[i].j] = p[q[i].j][q[i].p + 1];
M[q[i].p] = m2;
sgt.modify(1, n - 1, q[i].p, 1);
mat m3 = mul(M[0], sgt.sum[1]);
int P = (m3.a[0][0] + m3.a[0][1]) % mod;
ans = ((ans + (ll)q[i].s % mod * inv(q[i].v) % mod * P % mod) % mod + mod % mod);
m1.a[q[i].i][q[i].j] = 0;
M[q[i].p] = m1;
sgt.modify(1, n - 1, q[i].p, 1);
}
printf("%d", ans);
return 0;
}
| cpp |
13 | D | D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7 | [
"dp",
"geometry"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define name "Untitled1"
const int maxn=501;
int n,m,dp[maxn][maxn]={};
vector<int> f(maxn,0);
vector<pair<int,int>> a(maxn),b(maxn);
inline int area(pair<int,int> a1, pair<int,int> a2, pair<int,int> a3) {
int s=(a1.second+a2.second)*(a1.first-a2.first)+(a2.second+a3.second)*(a2.first-a3.first)+(a3.second+a1.second)*(a3.first-a1.first);
return ((s<0) ? (-s) : (s));
}
inline bool in(pair<int,int> point, pair<int,int> a1, pair<int,int> a2, pair<int,int> a3, pair<int,int> a4) {
return (area(point,a1,a2)+area(point,a2,a3)+area(point,a3,a4)+area(point,a4,a1)==area(a1,a2,a3)+area(a3,a4,a1));
}
inline void solve() {
cin>>n>>m;
for (int i=0; i<n; i++) {
int x,y;
cin>>x>>y;
a[i]={x,y};
}
for (int i=0; i<m; i++) {
int x,y;
cin>>x>>y;
b[i]={x,y};
}
sort(a.begin(),a.begin()+n);
for (int i=0; i<n; i++) {
for (int j=i+1; j<n; j++) {
pair<int,int> a1={a[i].first,-1e9-1},a2={a[j].first,-1e9-1};
for (int k=0; k<m; k++) {
dp[i][j]+=in(b[k],a[i],a[j],a2,a1);
}
}
}
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
f[i]+=(b[j].first==a[i].first && b[j].second<=a[i].second);
}
}
int res=0;
for (int i=0; i<n; i++) {
for (int j=i+1; j<n; j++) {
for (int k=j+1; k<n; k++) {
pair<int,int> a1={a[i].first,-1e9-1},a2={a[j].first,-1e9-1},a3={a[k].first,-1e9-1};
int d;
if (area(a[i],a[j],a2)+area(a2,a1,a[i])+area(a[j],a[k],a3)+area(a3,a2,a[j])>=area(a[i],a[k],a3)+area(a3,a1,a[i])) {
d=dp[i][j]+dp[j][k]-dp[i][k]-f[j];
}
else {
d=dp[i][k]-dp[i][j]-dp[j][k]+f[j];
}
res+=(d==0);
}
}
}
cout<<res;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
if (fopen(name".INP", "r")) {
freopen(name".INP","r",stdin);
//freopen(name".OUT", "w", stdout);
}
int t=1;
if (0) cin>>t;
while (t--) solve();
}
| cpp |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?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 a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define ll long long
#define endl "\n"
#define FOR(i,n) for(long long i = 0; i < n; i++)
#define FOR1(i,s,e,d) for(long long i = s; i < e; i += d)
#define FOR2(i,s,e,d) for(long long i = s; i > e; i -= d)
#define FOR3(x,v) for (auto x : v)
#define pll pair<long long, long long>
#define vi vector<int>
#define vl vector<long long>
#define vll vector<pair<long long, long long>>
#define vvl vector<vector<long long>>
#define vs vector<string>
#define vc vector<char>
#define mll map<long long, long long>
#define mlc map<long long,char>
#define mls map<long long,string>
#define mlvl map<long long, vector<long long>>
#define pql priority_queue<long long>
#define over(ans) {cout<<ans<<endl;return;}
#define all(v) (v).begin(), (v).end()
const ll INF = 1e9;
const ll mod = 998244353;
const ll mod1 = 1e9 + 7;
template<class T, class T1> bool ckmin(T& a, const T1& b) { return b < a ? a = b, 1 : 0; }
template<class T, class T1> bool ckmax(T& a, const T1& b) { return a < b ? a = b, 1 : 0; }
template<class c>
void display(c vect) {
FOR3(x, vect) cout << x << ' ';
cout << "\n";
}
void display(vll v) {
FOR3(x, v) cout << "(" << x.first << ", " << x.second << ") ";
cout << endl;
}
void display(vvl vect2d) {
FOR3(x, vect2d) display(x);
}
void display(mll m) {
FOR3(x, m) cout << x.first << ' ' << x.second << endl;
}
void display(mlvl m) {
FOR3(x, m) {
cout << x.first << " : ";
display(x.second);
}
}
vl vin(ll n) {
vl v(n);
FOR(i,n) cin >> v[i];
return v;
}
vi vin(int n) {
vi v(n);
FOR(i, n) cin >> v[i];
return v;
}
int to_int(string s) {
return stoi(s);
}
int to_int(char c) {
string s = {c};
return stoi(s);
}
char to_char(int i) {
return char('0' + i);
}
bool is_prime(ll n) {
if (n == 1) return false;
if (n == 2 || n == 3) return true;
if ( n % 6 == 1 || n % 6 == 5) {
for (ll k = 5; k*k <= n; k += 2) if (n % k == 0) return false;
return true;
}
return false;
}
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a % b);
}
ll inv(ll a, ll b){
return 1<a ? b - inv(b%a,a)*b/a : 1;
}
template<class T>
T power(T a, ll b) {
T res = 1;
for(; b; b /= 2, a *= a) if (b%2) {res *= a;}
return res;
}
template<class T>
T powermod(T a, ll b, ll P) {
a %= P; ll res = 1;
while (b > 0) {
if (b & 1) res = res * a % P;
a = a * a % P;
b >>= 1;
}
return res;
}
vl factors(ll n) {
vl factors;
ll i = 1;
while(i*i <= n) {
if (n%i == 0) {
factors.push_back(i);
if (i*i != n) factors.push_back(n/i);
}
i++;
}
sort(factors.begin(), factors.end());
return factors;
}
ll lsb(ll a) {return (a & -a);}
template < typename T>
struct Fenwick {
const ll n;
vector<T> a;
Fenwick(ll n) : n(n), a(n) {}
void add(ll x, T v) {
for (ll i = x+1; i <= n; i += i & -i) {
a[i-1] += v;
}
}
T sum(ll x) {
T ans = 0;
for (ll i = x; i > 0; i -= i & -i) {
ans += a[i-1];
}
return ans;
}
T rangeSum(ll l, ll r) {
return sum(r) - sum(l);
}
};
struct DSU {
vl f, siz;
DSU(ll n) : f(n), siz(n-1) { iota(f.begin(), f.end(), 0); }
ll leader(ll x) {
while (x != f[x]) x = f[x] = f[f[x]];
return x;
}
bool same(ll x, ll y) { return leader(x) == leader(y); }
bool merge(ll x, ll y) {
x = leader(x);
y = leader(y);
if (x == y) return false;
siz[x] += siz[y];
f[y] = x;
return true;
}
ll size(ll x) { return siz[leader(x)]; }
};
ll ncrmodP(ll n, ll r, ll P) {
ll fac[n+1];
fac[0] = 1;
FOR1(i, 1, n+1, 1) {
fac[i] = (fac[i-1] * i) % P;
}
return (fac[n] * inv(fac[r], P) % P * inv(fac[n-r], P) % P) % P;
}
vi primes_n(int n) {
vi primes;
FOR1(i, 1, n+1, 1) {
if (is_prime(i)) primes.push_back(i);
}
return primes;
}
// (condition ? value if yes : value if no)
// sort(v.begin(), v.end(), [](data_type x, data_type y) -> bool {
// return condition;
// });
void init() {
}
void solve() {
int n; cin >> n;
vi a = vin(2*n);
sort(all(a));
over(a[n] - a[n-1]);
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
init();
int t = 1;
cin >> t;
FOR(i,t) {
// cout << "Case #" << i+1 << ": ";
solve();
}
} | cpp |
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<iostream>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int x;
cin>>x;
cout<<x+(x-1)/9<<endl;
}
} | cpp |
1305 | E | E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5) | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
#define fi first
#define se second
#define mod 1000000007
#define ll long long
#define ull unsigned long long
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
void IO(string name)
{
ios_base::sync_with_stdio(0);
cin.tie(0);
if(name.size())
{
freopen((name+".in").c_str(), "r", stdin);
freopen((name+".out").c_str(), "w", stdout);
}
}
void solve()
{
int n, m;
cin >> n >> m;
vector<int> ans;
for (int i = 1; i <= n && m; i++) {
if (m - (i - 1) / 2 >= 0) {
ans.pb(i);
m -= (i - 1) / 2;
}
else {
ans.pb(ans.end()[-1] + ans.end()[- 2 * m]);
m = 0;
}
}
int nn = (ans.size() ? ans.back() : 1);
if (m) {
cout << "-1\n";
return;
}
int lim = n - ans.size();
for (int i = 0; i < lim; i++) {
ans.pb(1e8 + i * (nn + 1));
}
for (auto &i : ans) cout << i << ' ';
cout << '\n';
}
int main()
{
IO("");
int t = 1;
// cin >> t;
while(t--)
{
solve();
}
}
| cpp |
1312 | F | F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
OutputCopy2
3
0
InputCopy10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
OutputCopy0
2
1
2
5
12
5
0
0
2
| [
"games",
"two pointers"
] | #include<bits/stdc++.h>
#define ll long long
#define ls u<<1
#define rs u<<1|1
#define mm(x) memset(x,0,sizeof(x))
using namespace std;
ll read()
{
ll a=0;ll f=0;char p=getchar();
while(!isdigit(p)){f|=p=='-';p=getchar();}
while(isdigit(p)){a=(a<<3)+(a<<1)+(p^48);p=getchar();}
return f?-a:a;
}
const int INF=998244353;
const int P=998244353;
const int N=1e6+5;
int T;
int n,m;
int x,y,z;
int ans;
ll val[N];
int SG[N][3];
int t[N],top;
int att[3];
int r;
int find(ll u)
{
if(u<=100) return u;
return (u-100)%r+100;
}
void solve()
{
n=read(); ans=0; t[0]=-1;
for(int i=0;i<3;++i) att[i]=read();
for(int i=1;i<=300;++i)
{
for(int j=0;j<3;++j)
{
top=0;
for(int k=0;k<3;++k)
{
if(j==1&&k==1) continue;
if(j==2&&k==2) continue;
t[++top]=SG[max(0,i-att[k])][k];
}
sort(t+1,t+top+1);
SG[i][j]=t[top]+1;
for(int k=0;k<top;++k)
if(t[k]+1<t[k+1])
{
SG[i][j]=t[k]+1;
break;
}
}
}
for(int i=1;i<=100;++i)
{
bool flag=true;
for(int j=1;j<=200;++j)
for(int k=0;k<3;++k)
if(SG[100+j][k]!=SG[100+j%i][k]) flag=false;
if(flag) {r=i;break;}
}
int sum=0;
for(int i=1;i<=n;++i) val[i]=read();
for(int i=1;i<=n;++i)
{
int now=SG[find(val[i])][0];
sum^=now;
}
for(int i=1;i<=n;++i)
{
int now=SG[find(val[i])][0];
for(int j=0;j<3;++j)
{
int ts=SG[find(max(0ll,val[i]-att[j]))][j];
if((sum^now^ts)==0) ans++;
}
}
printf("%d\n",ans);
}
int main()
{
T=read();
while(T--) solve();
return 0;
} | cpp |
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>
#define int long long
#define fa(i,a,n) for(int i=a;i<n;i++)
#define pb push_back
#define bp pop_back
// #define mp make_pair
#define all(v) v.begin(),v.end()
#define vi vector<int>
#define faster ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
int ispali(string str)
{
int s=0,p=str.length()-1;
while(s<=p)
{
if(str[s]!=str[p])
return 0;
s++,p--;
}
return 1;
}
void solve(){
int n,m;
cin >> n >> m;
map<string,int> mp;
vector<string> a(n);
string s1="",s2="",s3="";
for(int i=0;i<n;i++)
{
cin >> a[i];
mp[a[i]]++;
}
for(int i=0;i<n;i++)
{
if(mp[a[i]])
{
string t=a[i];
mp[a[i]]--;
reverse(t.begin(),t.end());
if(mp[t])
{
s1.append(a[i]);
s2.append(t);
mp[t]--;
}
else if(s3.length()==0 && ispali(a[i]))
{
s3.append(a[i]);
}
}
}
s2=s1;
reverse(s2.begin(),s2.end());
cout << s1.length()+s3.length()+s2.length() << endl;
cout << s1<<s3<<s2 << endl;
return;
}
signed main()
{
faster;
int t=1;
//cin>>t;
while(t--)
solve();
} | cpp |
1290 | F | F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is: | [
"dp"
] | // LUOGU_RID: 92701667
//No More Time, No More Chance.
#include <cstdio>
#include <cstring>
namespace KamiyamaShiki{
const int mod = 998244353;
int abs(int x){return x<0?-x:x;}
int n,m,x[6],y[6],nxs[32],nys[32],pxs[32],pys[32];
int dp[31][26][26][26][26][2][2];
int DP(int dig,int nx,int ny,int px,int py,int bdx,int bdy){
if(dig == 30)return (!nx&&!ny&&!px&&!py&&!bdx&&!bdy);
int &r = dp[dig][nx][ny][px][py][bdx][bdy];if(~r)return r;
r = 0;int md = (m>>dig)&1;
for(int i=0;i<(1<<n);++i){
int now[] = {(nx+nxs[i])&1,(ny+nys[i])&1,(px+pxs[i])&1,(py+pys[i])&1};
int nxt[] = {(nx+nxs[i])/2,(ny+nys[i])/2,(px+pxs[i])/2,(py+pys[i])/2};
if(now[0] == now[2] && now[1] == now[3])
r = (r+DP(dig+1,nxt[0],nxt[1],nxt[2],nxt[3],(now[0]==md?bdx:now[0]>md),(now[1]==md?bdy:now[1]>md)))%mod;
}
return r;
}
int main(){
scanf("%d %d",&n,&m);
for(int i=1;i<=n;++i)scanf("%d %d",&x[i],&y[i]);
for(int s=0;s<(1<<n);++s)
for(int i=1;i<=n;++i)
(x[i]<0?nxs:pxs)[s] += ((s>>i-1)&1)*abs(x[i]),
(y[i]<0?nys:pys)[s] += ((s>>i-1)&1)*abs(y[i]);
memset(dp,-1,sizeof(dp));
return printf("%d\n",(DP(0,0,0,0,0,0,0)-1+mod)%mod),0;//È¥µô¿Õ¡£
}
}
int main(){return KamiyamaShiki::main();}
| 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;
void Void() {
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 {
cout << "NO\n";
return;
}
}
cout << "YES\n";
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
ll t = 1;
cin >> t;
while (t--) Void();
return 0;
}
| cpp |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t; cin>>t;
while(t--)
{
int n; cin>>n;
int a[n],b[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n;i++)
{
cin>>b[i];
}
sort(a,a+n);
sort(b,b+n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
for(int i=0;i<n;i++)
{
cout<<b[i]<<" ";
}
cout<<endl;
}
} | cpp |
1304 | F1 | F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp"
] | // LUOGU_RID: 101683611
//This code is written by Hmz(Hmz is cute!!!)
#include<bits/stdc++.h>
using namespace std;
#define TY int
#define mod (TY)(1e9+7)
#define MAXN 55
#define MAXM 20005
#define MAXK 27
#define For(i,a,b) for(TY i=(a);i<=(b);++i)
#define FOR(i,a,b) for(TY i=(a);i<(b);++i)
#define Rof(i,a,b) for(TY i=(a);i>=(b);--i)
#define ROF(i,a,b) for(TY i=(a);i>(b);--i)
inline TY qr(){
TY x=0,f=1;char op=getchar();
for(;op<'0'||op>'9';op=getchar())if(op=='-')f=-1;
for(;op>='0'&&op<='9';op=getchar())x=x*10+(op^48);
return x*f;
}inline char getc(){
char op=getchar();
while(op==' '||op=='\n'||op=='\r')op=getchar();
return op;
}inline string qs(){
string op="";char u=getchar();
while(u=='\n'||u=='\r'||u==' ')u=getchar();
while(u!='\n'&&u!='\r'&&u!=' ')op+=u,u=getchar();
return op;
}inline void qw(TY x){
if(!x){putchar('0');return;}
if(x<0)putchar('-'),x=-x;
if(x>=10)qw(x/10);putchar(x%10+'0');
}inline void qw(TY x,char op){qw(x),putchar(op);}
inline void ws(string s){FOR(i,0,s.size())putchar(s[i]);}
inline TY Ceil(TY a,TY b){return a/b+(a%b!=0);}
inline TY Mod(TY a){return (a>=mod?a-mod:a);}
inline TY Pow(TY a,TY b){
TY ans=1,base=a;
while(b){
if(b&1)ans=ans*base%mod;
base=base*base%mod;b>>=1;
}return ans;
}TY n,m,k,ans,val[MAXN][MAXM],tree[MAXM<<2],tag[MAXM<<2],dp[MAXN][MAXM];
inline void push_down(TY now){
tree[now<<1]+=tag[now],tree[now<<1|1]+=tag[now];
tag[now<<1]+=tag[now],tag[now<<1|1]+=tag[now];
tag[now]=0;
}void build(TY deep,TY now,TY l,TY r){
tag[now]=0;
if(l==r){tree[now]=dp[deep][l];return;}
TY mid=(l+r)>>1;
build(deep,now<<1,l,mid);build(deep,now<<1|1,mid+1,r);
tree[now]=max(tree[now<<1],tree[now<<1|1]);
}void update(TY now,TY l,TY r,TY x,TY y,TY w){
if(l>y||r<x)return;
if(x<=l&&r<=y){tree[now]+=w;tag[now]+=w;return;}
push_down(now);TY mid=(l+r)>>1;
update(now<<1,l,mid,x,y,w);update(now<<1|1,mid+1,r,x,y,w);
tree[now]=max(tree[now<<1],tree[now<<1|1]);
}int main(){
n=qr();m=qr();k=qr();
For(i,1,n)For(j,1,m)val[i][j]=qr();
For(i,2,n+1){
build(i-1,1,1,m);
TY l=1,r=0,sum=0;while(r<=m){
if(r-l+1<k){
++r;sum+=val[i][r]+val[i-1][r];
if(i!=2)update(1,1,m,max(1,r-k+1),r,-val[i-1][r]);
}else{
dp[i][l]=sum+tree[1];if(i==n+1)ans=max(ans,dp[i][l]);
if(i==n+1)ans=max(ans,dp[i][l]);
sum-=val[i][l]+val[i-1][l];
if(i!=2)update(1,1,m,max(1,l-k+1),l,val[i-1][l]);++l;
++r;sum+=val[i][r]+val[i-1][r];
if(i!=2)update(1,1,m,max(1,r-k+1),r,-val[i-1][r]);
}
}
}qw(ans);
return 0;
}//zhushi | cpp |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | /// endless ?
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
#define ll long long
#define F first
#define S second
#define pii pair<int, int>
#define all(x) x.begin(), x.end()
#define vi vector<int>
#define vii vector<pii>
#define pb push_back
#define pf push_front
#define wall cout <<'\n'<< "-------------------------------------" <<'\n';
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define int ll
const ll MAXN = 1e5 + 43;
const ll MOD = 1e9 + 7; ///998244353;
const ll INF = 1e18 + 19763;
const ll LG = 19;
ll pw(ll a, ll b){return b == 0 ? 1LL : (pw(a * a , b / 2) * (b % 2 == 0 ? 1LL : a));}
void solve()
{
fast
int n, k; cin >> n >> k;
int cnt = 0;
while (cnt <= 10 && pw(10, cnt) - 1 <= k)
{
cnt ++;
}
cout << n * (cnt - 1) << '\n';
}
int32_t main ()
{
fast
int t = 1; cin >> t;
while (t --)
{
solve();
}
}
/// Thanks GOD :)
| cpp |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | #include <bits/stdc++.h>
using namespace std;
const int MN=8e4;
int N, at=170, dist[MN], ans = MN; bool pvis[1001], vis[MN];
set<int> start; vector<int> prime, vals, adj[MN];
unordered_map<int, int> ind; // (value, index it maps to)
queue<pair<int, pair<int, int> > > next1; // (distance, (node, parent))
void bfs(int j){ memset(vis, 0, sizeof(vis)); next1.push({0, {j, j}});
while (!next1.empty()) { int d = next1.front().first;
int x = next1.front().second.first; int p = next1.front().second.second;
next1.pop(); if(vis[x]) continue; vis[x]=1; dist[x] = d; bool skip=0;
for (int i: adj[x]) if(adj[i].size()>1) {
if (i != p || skip)
{ if (vis[i]) ans = min(ans, dist[i] + dist[x] + 1);
else next1.push({d + 1, {i, x}}); }
else skip = 1;
}
}
adj[j].clear();
}
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
prime.reserve(170); prime.push_back(1);
for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.push_back(i);
for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; }
cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x;
for (int j=1; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0;
while (x%prime[j] == 0) { x /= prime[j]; cnt++; }
if (cnt%2 == 1) vals.push_back(prime[j]); }
if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; }
vals.push_back(x); if (vals.size() == 1) vals.push_back(1);
for (int k: vals) if (ind.count(k) == 0)
{ if (k > 1e3) ind[k] = at++;
else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin();
ind[k]=t; start.insert(t); } }
adj[ind[vals[0]]].push_back(ind[vals[1]]);
adj[ind[vals[1]]].push_back(ind[vals[0]]);
}
for (int j: start) if(adj[j].size()>1) bfs(j);
cout << (ans == MN ? -1 : ans) <<'\n';
} | cpp |
1286 | C2 | C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"hashing",
"interactive",
"math"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 101
#define bas (133)
#define yu (998244353)
ll n;
inline void ask(ll x,ll y){
cout<<"? "<<x<<' '<<y<<'\n';
cout.flush();
return ;
}
string s1[N*N/2],s2[N*N/2];
char ans[N];
ll hs1[N*N/2],hs2[N*N/2];
bool vis[N*N/2];
ll p[N],len[N*N/2],cn=0;
inline bool cmp(ll x,ll y){return len[x]<len[y];}
inline void solve(ll x){
if(x==1){
ask(1,1);
cin>>s1[0];ans[1]=s1[0][0];
return ;
}
ask(1,x);
ll cnt[N];
for(int i=1;i<=x*(x+1)/2;i++){
cin>>s1[i];memset(cnt,0,sizeof(cnt));
for(int j=0;j<s1[i].size();j++)cnt[s1[i][j]-'a']++;
for(int j=0;j<26;j++)hs1[i]=(hs1[i]*bas+cnt[j])%yu;
}ask(1,x-1);
for(int i=1;i<=(x-1)*x/2;i++){
cin>>s2[i];memset(cnt,0,sizeof(cnt));
for(int j=0;j<s2[i].size();j++)cnt[s2[i][j]-'a']++;
for(int j=0;j<26;j++)hs2[i]=(hs2[i]*bas+cnt[j])%yu;
}
for(int i=1;i<=(x-1)*x/2;i++){
for(int j=1;j<=x*(x+1)/2;j++){
if(vis[j])continue;
if(hs2[i]==hs1[j]){
vis[j]=1;break;
}
}
}for(int i=1;i<=x*(x+1)/2;i++){
if(vis[i])continue;p[++cn]=i;len[i]=s1[i].length();
}sort(p+1,p+cn+1,cmp);
for(int j=1;j<=cn;j++){
memset(cnt,0,sizeof(cnt));
ll o=p[j];for(int g=0;g<s1[o].length();g++)cnt[s1[p[j]][g]-'a']++;
if(j>1)for(int g=0;g<s1[p[j-1]].length();g++)cnt[s1[p[j-1]][g]-'a']--;
for(int g=0;g<26;g++)if(cnt[g])ans[cn-j+1]=g+'a';
}
return ;
}
ll cnt[N*N][26];
bool vv[N*N];
ll tmp[26];
inline void del(){
for(int i=1;i<=(n+1)*n/2;i++){
bool kz=1;if(vv[i])continue;
for(int j=0;j<26;j++)if(cnt[i][j]!=tmp[j])kz=0;
if(kz){
vv[i]=1;break;
}
}
return ;
}
int main()
{
// freopen("test1.in","r",stdin);
//freopen(".in","r",stdin);
//freopen("test1.out","w",stdout);
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>n;ll o=(n+1)/2,p=n-o;solve(o);
ask(1,n);
for(int i=1;i<=n*(n+1)/2;i++){
string s;cin>>s;
for(int j=0;j<s.length();j++)cnt[i][s[j]-'a']++;
}
for(int i=1;i<=n;i++){
if(i>o){
ll p=n-i,an[26];memset(an,0,sizeof(an));
for(int j=1;j<=n*(n+1)/2;j++){
if(vv[j])continue;
ll tot=0;
for(int k=0;k<26;k++)tot+=cnt[j][k];
if(tot==p+1)for(int k=0;k<26;k++)an[k]+=cnt[j][k];
if(tot==p)for(int k=0;k<26;k++)an[k]-=cnt[j][k];
}for(int j=i-1;j>=i-p;j--)an[ans[j]-'a']--;
for(int j=0;j<26;j++)if(an[j])ans[i]=j+'a';
}
memset(tmp,0,sizeof(tmp));
for(int j=i;j>=1;j--){
tmp[ans[j]-'a']++;
del();
}
}
cout<<"! ";for(int i=1;i<=n;i++)cout<<ans[i];
return 0;
}
| cpp |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".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 next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
const i64 mod = 1E9 + 7;
//
void solve() {
i64 n;
cin >> n;
string s;
cin >> s;
map<i64, int> used;
int l = 0, r = 2E9 + 10;
int x = 0, y = 0;
for (int i = 0; i < n; i ++) {
i64 now = x * mod + y;
if (used[now]) {
if (i - used[now] < r - l) {
r = i;
l = used[now];
}
}
if (s[i] == 'L') x --;
else if (s[i] == 'R') x ++;
else if (s[i] == 'U') y ++;
else y --;
used[now] = i + 1;
}
i64 now = x * mod + y;
if (used[now]) {
if (n - used[now] < r - l) {
r = n;
l = used[now];
}
}
if (r - l > 100000000) cout << -1 << "\n";
else cout << l << " " << r << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int _ = 1;
cin >> _;
while (_ --) {
solve();
}
return 0;
} | cpp |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | #include<bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long i64;
typedef int i32;
typedef long double ld;
void like(void)
{
int n,m;
cin>>n>>m;
int a[n+2];
map<int,int> mp;
int i,j;
for(i=1;i<=n;i++)
cin>>a[i];
while(m--)
{
int x;
cin>>x;
mp[x]++;
}
for(i=1;i<=n;i++)
for(j=n;j>1;j--)
if(a[j]<a[j-1]&&mp[j-1]==0)
{
cout<<"NO"<<endl;
return ;
}
else if(a[j]<a[j-1])swap(a[j],a[j-1]);
cout<<"YES"<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t;
cin>>t;
while(t--)
like();
return 0;
}
| cpp |
1301 | E | E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105) — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray. | [
"binary search",
"data structures",
"dp",
"implementation"
] | #include <bits/stdc++.h>
#define endl '\n'
#define fi first
#define se second
#define MOD(n,k) ( ( ((n) % (k)) + (k) ) % (k))
#define forn(i,n) for (int i = 0; i < n; i++)
#define forr(i,a,b) for (int i = a; i <= b; i++)
#define all(v) v.begin(), v.end()
#define pb push_back
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<ll> vl;
typedef vector<ii> vii;
const int MX = 505, MA = 300005, LG = 10;
int n, m, q, acu[4][MX][MX], mx[MX][MX], st[MX][MX][LG][LG];;
char a[MX][MX];
void build () {
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
st[i][j][0][0] = mx[i][j];
for (int i = 1; i <= n; i++)
for (int l = 1; l < LG; l++)
for (int j = 1; j + (1 << l) - 1 <= m; j++)
st[i][j][0][l] = max(st[i][j][0][l - 1], st[i][j + (1 << (l - 1))][0][l - 1]);
for (int k = 1; k < LG; k++)
for (int i = 1; i + (1 << k) - 1 <= n; i++)
for (int l = 0; l < LG; l++)
for (int j = 1; j + (1 << l) - 1 <= m; j++)
st[i][j][k][l] = max(st[i][j][k - 1][l], st[i + (1 << (k - 1))][j][k - 1][l]);
}
int query (int x1, int y1, int x2, int y2) {
if (x1 > x2 || y1 > y2) return 0;
int lx = log2(x2 - x1 + 1), ly = log2(y2 - y1 + 1);
return max({
st[x1][y1][lx][ly],
st[x2 - (1 << lx) + 1][y1][lx][ly],
st[x1][y2 - (1 << ly) + 1][lx][ly],
st[x2 - (1 << lx) + 1][y2 -(1 << ly) + 1][lx][ly]
});
}
void pre (char c, int acu[MX][MX]) {
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
acu[i][j] = a[i][j] == c;
acu[i][j] += acu[i-1][j];
acu[i][j] += acu[i][j-1];
acu[i][j] -= acu[i-1][j-1];
}
}
int query (int ind, int a, int b, int c, int d) {
return acu[ind][c][d] - acu[ind][c][b - 1] - acu[ind][a - 1][d] + acu[ind][a - 1][b - 1];
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> m >> q;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
pre('R', acu[0]);
pre('G', acu[1]);
pre('Y', acu[2]);
pre('B', acu[3]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
for (int k = 1; min(i, j) - k + 1 > 0 && i + k <= n && j + k <= m; k++) {
if (query(0, i - k + 1, j - k + 1, i, j) != k * k) break;
if (query(1, i - k + 1, j + 1, i, j + k) != k * k) break;
if (query(2, i + 1, j - k + 1, i + k, j) != k * k) break;
if (query(3, i + 1, j + 1, i + k, j + k) != k * k) break;
mx[i][j] = k;
}
build();
while (q--) {
int r1, c1, r2, c2;
cin >> r1 >> c1 >> r2 >> c2;
int i = 0, j = n, rep = 10;
while (rep--) {
int m = (i + j + 1) / 2;
if (query(r1 + m - 1, c1 + m - 1, r2 - m, c2 - m) >= m) i = m;
else j = m;
}
cout << 4 * i * i << endl;
}
return 0;
} | cpp |
1286 | E | E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
OutputCopy1
2
4
5
7
9
12
InputCopy4
a 2
y 2
z 0
y 2
OutputCopy2
2
2
2
InputCopy5
a 7
u 5
t 3
s 10
s 11
OutputCopy7
9
11
12
13
NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313. | [
"data structures",
"strings"
] | // LUOGU_RID: 101240345
// 贺的但是根据理解写了注释并加了改动
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#pragma GCC optimize ("Ofast","unroll-loops")
#pragma GCC target ("avx2,popcnt,lzcnt,fma,sse4.1,sse4.2,bmi,bmi2,abm,sse2,sse3,sse4,mmx,arch=cannonlake,tune=cannonlake")
#define query(pos) (a[*lower_bound(stk + 1, stk + 1 + r, (pos))])
#define endl '\n'
using std::cin;
using std::cout;
using std::lower_bound;
using std::map;
using std::string;
using std::upper_bound;
constexpr long long N = 6e5 + 514;
constexpr long long mask = (1 << 30) - 1;
long long nxt[N], anc[N];
string s;
long long a[N]; // 串和 w 数组
long long stk[N]; // 单调栈
long long r; // 栈顶
__int128 ans, sum;
long long tmp1, tmp2; // tmp for output
long long n;
char c;
map<long long, long long> cnt;
long long v, ncnt;
void output(__int128 out) {
std::ios::sync_with_stdio(false);
cout.tie(nullptr);
constexpr long long P = 1e18;
if (out < P) {
cout << (long long)out << endl;
} else {
tmp1 = out / P, tmp2 = out % P;
cout << tmp1 << std::setw(18) << std::setfill('0') << tmp2 << endl;
}
}
int main() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n;
s.reserve(n+1);
cin >> c >> a[0];
s += c; // 第一次加字符不需要加密
ans = a[0]; // 第一次加数字同理
stk[++r] = 0;
cout << a[0] << endl; // 因此直接输出就行了
for (long long i = 1, j = 0; i < n; ++i) {
cin >> c >> a[i];
c = (c - 'a' + ans % 26) % 26 + 'a';
s += c; // 字符加密
a[i] = a[i] ^ (ans & mask); // 数字加密
/*
KMP
求最长 border 肯定得 KMP 来
*/
while (j && c != s[j]) {
j = nxt[j];
}
if (s[j] == c) {
++j;
}
nxt[i + 1] = j;
/*
个人认为比较难理解的地方
对于当前位置 i,因为前面的所有部分都已经考虑过了,保证正确,所以只需要处理新添加 s[i] 字符后出现的 border。
为了保证效率,我们实际上维护了一个集合,存放的是合法的以 i 为结尾的 border,而到第二个字符 i+1 时,跳 border (i = nxt[i],即枚举 border 的 border) 寻找是否有 border 在添加字符 s[j] 之后不再合法并删除。
由于最多加入 n 个 border,所以每次操作删除的 border 个数是均摊 O(1) 的。
显然朴素方法删除 border 也很慢,所以这里我们维护了另一个列表 anc。
anc[i] 表示 i-1 的合法 border 中,第一个(最长的)后一位字符与 s[i] 不相同的 border 的后一位字符。(有点绕,不理解建议多读几遍)
换种说法,就是 kmp 暴力枚举 border 时的失败的失配指针,或者原题解说的“对每一个节点记录其第一个后继字符不一样的祖先”。
总之,这样我们就能 O(1) 时间内找到需要删除的 border。
*/
if (c == s[nxt[i]]) {
anc[i] = anc[nxt[i]];
} else {
anc[i] = nxt[i];
}
for (long long k = i; k > 0;) {
if (s[k] == c) {
k = anc[k];
} else {
v = query(i - k);
--cnt[v];
sum -= v;
if (cnt[v] == 0) {
cnt.erase(v);
}
k = nxt[k];
}
}
if (s[0] == c) {
++cnt[a[i]];
sum += a[i];
}
/*
单调栈
此处单调栈维护的是权值,即 w[i]
作用是寻找要删除的 border 区间最小 w[i](单调栈 + 二分)
*/
while (r && a[i] <= a[stk[r]]) {
--r;
}
stk[++r] = i;
/*
此处 map 中元素 <a,b> 代表权值为 a 的 border 有 b 个,用来暴力找到所有大于 w[i] 的权值
*/
ncnt = 0; // 当前节点 border 的数量
for (auto it = cnt.upper_bound(a[i]);;) {
if (it == cnt.end()) break;
sum -= (it->first - a[i]) * it->second;
ncnt += it->second;
auto j = std::next(it);
cnt.erase(it);
it = j;
}
cnt[a[i]] += ncnt; // 记录每一个节点的 border 数量
ans += (a[stk[1]] + sum); // a[stk[1]] 实际上是整个串自身的最小权值,因为前面维护的是单调栈,栈底就是目前的最小权值
output(ans);
}
return 0;
} | cpp |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | //Then
#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define faster ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair <int, int>;
mt19937_64 Rand(chrono::steady_clock::now().time_since_epoch().count());
const int maxN = 1e5 + 1;
//const int Mod = 1e9 + 7;
//const int inf =
int n;
int a[maxN];
int cnt[maxN];
int phi[maxN];
vector <int> divs[maxN];
bool on[maxN];
int get(int x){
int res = 0;
for (int i: divs[x]){
res += phi[i] * cnt[i];
}
return res;
}
void del(int x){
for (int i: divs[x]){
--cnt[i];
}
}
void add(int x){
for (int i: divs[x]){
++cnt[i];
}
}
void Init(){
cin >> n;
for (int i = 1; i <= n; ++i){
cin >> a[i];
on[a[i]] = 1;
}
for (int i = 1; i <= 1e5; ++i){
for (int j = i; j <= 1e5; j += i){
divs[j].pb(i);
if (i == 1) phi[i] = 1;
else if ((i / divs[i][1]) % divs[i][1] == 0) phi[i] = 0;
else phi[i] = -phi[i / divs[i][1]];
}
}
ll ans = *max_element(a + 1, a + n + 1);
for (int i = 1; i <= 1e5; ++i){
vector <int> S;
for (int j = 1e5 / i; j >= 1; --j){
if (!on[j * i]) continue;
int tem = get(j);
while (tem){
int u = S.back(); S.pop_back();
if (__gcd(u, j) == 1){
ans = max(ans, 1LL * u * j * i);
--tem;
}
del(u);
}
add(j);
S.pb(j);
}
for (auto i: S) del(i);
}
cout << ans;
}
#define debug
#define taskname "test"
signed main(){
faster
if (fopen(taskname".inp", "r")){
freopen(taskname".inp", "r", stdin);
freopen(taskname".out", "w", stdout);
}
int tt = 1;
//cin >> tt;
while (tt--){
Init();
}
if (fopen("timeout.txt", "r")){
ofstream timeout("timeout.txt");
timeout << signed(double(clock()) / CLOCKS_PER_SEC * 1000);
timeout.close();
#ifndef debug
cerr << "Time elapsed: " << signed(double(clock()) / CLOCKS_PER_SEC * 1000) << "ms\n";
#endif // debug
}
}
| cpp |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
#define eps 1e-9
#define emailam ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define MAX 200010
#define pb push_back
#define all(a) a.begin(),a.end()
#define pf push_front
#define fi first
#define se second
#define pii pair<int,int>
const long long INF = LLONG_MAX;
using namespace std;
const int N=3e5+10,M=10;
const int mod=998244353;
#define int long long
/*----------------------------------------------------------------*/
int dx[] = {+0, +0, -1, +1, +1, +1, -1, -1};
int dy[] = {-1, +1, +0, +0, +1, -1, +1, -1};
/*----------------------------------------------------------------*/
void READ(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif
}
void solve(){
int n;
cin>>n;
string s;
cin>>s;
int ans=0;
for(int i=0;i<n;i++){
if(s[i]=='P'){
for(int j=i-1;j>=0;j--){
if(s[j]=='A'){
ans=max(ans,i-j);
break;
}
}
}
}
cout<<ans<<endl;
}
signed main() {
emailam
//READ();
int t=1;
cin>>t;
while(t--){
solve();
}
} | cpp |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] | #ifdef LOCAL
#define _GLIBCXX_DEBUG
#endif
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
#define sz(s) ((int)s.size())
#define all(v) begin(v), end(v)
typedef long double ld;
const int MOD = 1000000007;
#define ff first
#define ss second
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
// *-> KISS*
int solve() {
int n, q; cin >> n >> q;
set<pair<pair<int, int>, pair<int, int>>> st;
vector<vector<int>> v(2, vector<int>(n, 0));
vector<vector<bool>> vis(2, vector<bool>(n, false));
auto update = [&](int x, int y, int add) {
const int dx[] = {-1, -1, -1, 1, 1, 1};
const int dy[] = {-1, 0, 1, -1, 0, 1};
for(int k = 0; k < 6; ++k) {
int nx = x + dx[k], ny = y + dy[k];
if(0 <= nx && nx < 2 && 0 <= ny && ny < n) {
if((nx == 0 && ny == 0) || (nx == 1 && ny == n - 1)) continue;
if(add == 1) {
if(vis[nx][ny]) {
pair<int, int> p1 = {x, y}, p2 = {nx, ny};
if(p1 > p2) {
swap(p1, p2);
}
st.insert({p1, p2});
}
}
else {
if(!vis[nx][ny]) continue;
pair<int, int> p1 = {x, y}, p2 = {nx, ny};
if(p1 > p2) {
swap(p1, p2);
}
st.erase({p1, p2});
}
}
}
};
while(q--) {
int r, c; cin >> r >> c;
--r; --c;
if(!vis[r][c]) {
vis[r][c] = true;
update(r, c, 1);
}
else {
vis[r][c] = false;
update(r, c, -1);
}
cout << (sz(st) ? ("No\n") : ("Yes\n"));
}
return 0;
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
int TET = 1;
//cin >> TET;
cout << fixed << setprecision(6);
for (int i = 1; i <= TET; i++) {
#ifdef LOCAL
cout << "##################" << '\n';
#endif
if (solve()) {
break;
}
cout << '\n';
}
#ifdef LOCAL
cout << endl << "finished in " << clock() * 1.0 / CLOCKS_PER_SEC << " sec" << endl;
#endif
return 0;
}
// -> Keep It Simple Stupid! | 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"
] | // LUOGU_RID: 95225327
#include <bits/stdc++.h>
using namespace std;
int n, k;
const int maxn = 88 ;
int dis[maxn][maxn] ;
int dp[11][maxn] ;
int main()
{
ios::sync_with_stdio(false);
cin>>n>>k;
for(int i = 1 ; i <= n ; i ++)
{
for(int j = 1 ; j <= n ; j ++)
{
cin>>dis[i][j];
}
}
int seed = 0 ;
for(char c : "sooketxdy")
seed = seed * 233 + c ;
srand(seed) ;
int times = 5000 ;
vector < int > col(n + 1 , 0);
int ans = 1e9 ;
while(times --)
{
for(int i = 1 ; i <= n ; i ++)
col[i] = rand() & 1 ;
memset(dp , 0x3f , sizeof(dp)) ;
dp[0][1] = 0;
for(int kk = 0 ; kk < k ; kk ++)
{
for(int i = 1 ; i <= n ; i ++)
{
for(int j = 1 ; j <= n ; j ++)
{
if(col[i] ^ col[j])
{
dp[kk + 1][j] = min(dp[kk + 1][j] , dp[kk][i] + dis[i][j]) ;
}
}
}
}
ans = min(ans , dp[k][1]) ;
}
cout<<ans<<endl;
return 0 ;
} | cpp |
1299 | D | D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept. | [
"bitmasks",
"combinatorics",
"dfs and similar",
"dp",
"graphs",
"graphs",
"math",
"trees"
] | #include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
#define rep(i, a, b) for(int i = (a); i <= (b); i ++)
#define per(i, a, b) for(int i = (a); i >= (b); i --)
#define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt)
using namespace std;
#define eb emplace_back
typedef pair<int, int> pii;
#define mp make_pair
#define fi first
#define se second
const int P = 1e9 + 7;
inline int plu(int x, int y) {return x + y >= P ? x + y - P : x + y;}
inline int del(int x, int y) {return x - y < 0 ? x - y + P : x - y;}
inline void add(int &x, int y) {x = plu(x, y);}
inline void sub(int &x, int y) {x = del(x, y);}
inline int qpow(int a, int b) {int s = 1; for(; b; b >>= 1, a = 1ll * a * a % P) if(b & 1) s = 1ll * s * a % P; return s;}
inline int read() {
int x = 0, f = 1; char c = getchar();
while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar();
while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar();
return x * f;
}
const int N = 1e5 + 10;
const int M = 500;
int n, m; vector<pii> g[N];
struct node {
int a[5];
node() {memset(a, 0, sizeof(a));}
void init(int x) {
a[0] = x & 1;
a[1] = x >> 1 & 3;
a[2] = x >> 3 & 7;
a[3] = x >> 6 & 15;
a[4] = x >> 10 & 31;
}
int hash() {return a[0] | a[1] << 1 | a[2] << 3 | a[3] << 6 | a[4] << 10;}
bool insert(int x) {
per(i, 4, 0) if(x >> i & 1) {
if(a[i]) x ^= a[i];
else {
a[i] = x;
per(j, i - 1, 0) if(a[i] >> j & 1) a[i] ^= a[j];
rep(j, i + 1, 4) if(a[j] >> i & 1) a[j] ^= a[i];
return true;
}
}
return false;
}
} mask[N];
int cnt, idx[N], rex[N], trans[M][M];
void find(node p) {
int x = p.hash();
if(! idx[x]) rex[idx[x] = ++ cnt] = x; else return;
rep(i, 1, 31) {node q = p; if(q.insert(i)) find(q);}
}
void prework() {
node sta; find(sta);
rep(i, 1, cnt) {
node u; u.init(rex[i]);
rep(j, 1, cnt) {
node v; v.init(rex[j]);
bool valid = true;
rep(k, 0, 4) if(u.a[k] && ! v.insert(u.a[k])) {valid = false; break;}
if(valid) trans[i][j] = idx[v.hash()];
}
}
}
int tot, bel[N], root[N], len[N]; bool cir[N], invalid[N];
int tim, val[N], dfn[N];
void dfs(int u, int fa, int tp) {
// cerr << "edge " << u << ' ' << fa << endl;
bel[u] = tp;
dfn[u] = ++ tim;
for(auto e : g[u]) {
int v = e.fi, w = e.se;
if(v == 1 || v == fa) continue;
if(! bel[v]) val[v] = val[u] ^ w, dfs(v, u, tp);
else {
// cerr << u << ' ' << v << ' ' << (val[u] ^ val[v] ^ w) << endl;
if(dfn[v] < dfn[u] && ! mask[tp].insert(val[u] ^ val[v] ^ w)) invalid[tp] = true;
}
}
}
int f[M], h[M];
int main() {
prework(), n = read(), m = read();
rep(i, 1, m) {
int u = read(), v = read(), w = read();
g[u].eb(mp(v, w));
g[v].eb(mp(u, w));
}
for(auto e : g[1]) {
int u = e.fi, w = e.se;
if(! bel[u]) root[++ tot] = u, len[tot] = w, dfs(u, 1, tot);
else {
int p = bel[u], v = root[p];
len[p] ^= w, cir[p] = true;
for(auto e : g[u]) if(e.fi == v) {len[p] ^= e.se; break;}
}
}
f[1] = 1;
rep(i, 1, tot) if(! invalid[i]) {
// cerr << i << ' ' << cir[i] << ' ' << len[i] << endl;
rep(j, 1, cnt) h[j] = f[j];
if(! cir[i]) {
int k = idx[mask[i].hash()];
rep(j, 1, cnt) if(trans[j][k]) add(f[trans[j][k]], h[j]);
}
else {
int k = idx[mask[i].hash()];
node tmp = mask[i]; bool valid = tmp.insert(len[i]);
int l = idx[tmp.hash()];
rep(j, 1, cnt) {
if(trans[j][k]) add(f[trans[j][k]], 2ll * h[j] % P);
if(valid && trans[j][l]) add(f[trans[j][l]], h[j]);
}
}
}
int ans = 0;
rep(i, 1, cnt) add(ans, f[i]);
printf("%d\n", ans);
return 0;
}
| cpp |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence. | [
"data structures",
"geometry",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
const int INF = 1e18, MOD = 1e9+7, N = 1e6+5;
int n, arr[N], x;
void solve(){
cin >> n;
vector<pair<double, int>> st;
for(int i = 0; i < n; i++){
cin >> x;
st.emplace_back(x, 1);
while(st.size() >= 2){
if(st[st.size()-2] >= st[st.size()-1]){
st[st.size()-2].first = (st[st.size()-2].first*st[st.size()-2].second + st[st.size()-1].first*st[st.size()-1].second) / (st[st.size()-1].second+st[st.size()-2].second);
st[st.size()-2].second = st[st.size()-1].second+st[st.size()-2].second;
st.pop_back();
} else {
break;
}
}
}
for(pair<double, int> u : st){
for(int i = 0; i < u.second; i++){
cout << fixed << setprecision(12) << u.first << "\n";
}
}
}
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int t = 1;
// cin >> t;
while(t--) solve();
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;
const int maxn=2e5+10;
struct edge{int to,next;}E[maxn<<1];
int head[maxn],tot;
inline void add(int u,int v)
{
E[++tot]={v,head[u]};
head[u]=tot;
}
int nd;
int n,m,dfn[maxn],dep[maxn],top[maxn],times;
bool del[maxn];
vector<int> adin;
vector<int> V;
void predfs(int u,int fa)
{
dep[u]=dep[fa]+1;
V.push_back(u);
dfn[u]=++times;
top[u]=dep[u];
int cnt=0;
for(int i=head[u];i;i=E[i].next)
{
int v=E[i].to;
if(!dfn[v]){predfs(v,u);}
else if(dep[u]-dep[v]+1>=nd)
{
puts("2");
printf("%d\n",dep[u]-dep[v]+1);
//printf("%d %d %d\n",u,dep[u],top[u]);
for(int i=dep[v]-1;i<dep[u];i++)
printf("%d ",V[i]);
putchar('\n');
exit(0);
}
}
if(!del[u])
{
adin.push_back(u);
for(int i=head[u];i;i=E[i].next)
{
int v=E[i].to;
del[v]=1;
}
}
V.pop_back();
}
int main()
{
scanf("%d%d",&n,&m);
nd=sqrt(n-1)+1;
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v);add(v,u);
}
predfs(1,0);
puts("1");
for(int i=0;i<nd;i++)
printf("%d ",adin[i]);
return 0;
} | cpp |
1311 | C | C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11. | [
"brute force"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
string s;
cin>>s;
int p[m];
for(int i=0;i<m;i++){
cin>>p[i];
}
vector<vector<int>>prefix(n+1,vector<int>(26,0));
for(int i=1;i<=n;i++){
prefix[i]=prefix[i-1];
prefix[i][s[i-1]-'a']++;
}
vector<int>ans(26,0);
for(int i=0;i<m;i++){
for(int j=0;j<26;j++){
ans[j]+=prefix[p[i]][j];
}
}
for(int i=0;i<26;i++){
cout<<1ll*ans[i]+prefix[n][i]<<" ";
}
cout<<'\n';
}
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>
#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<math.h>
#include<map>
#include<algorithm>
#include<set>
#include<unordered_map>
#include <unordered_set>
#define fast ios_base::sync_with_stdio(false),cin.tie(NULL)
#define popcount __builtin_popcount
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define int long long int
typedef long double lld;
#define FOR(i,n) for(int i=0;i<n;i++)
#define yes cout<<"YES"<<endl;
#define no cout<<"NO"<<endl;
#define p0(a) cout << a << " "
#define p1(a) cout << a << endl
#define p2(a, b) cout << a << " " << b << endl
#define p3(a, b, c) cout << a << " " << b << " " << c << endl
#define p4(a, b, c, d) cout << a << " " << b << " " << c << " " << d << endl
#define MOD 1000000007
#define vi vector<int>
#define pii pair<int, int>
#define vii vector<pii>
#define fr front()
#define bk back()
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define max_heap priority_queue <int>
#define min_heap priority_queue <int, vector <int> , greater <int> >
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pair<int, int> > vpii;
typedef unordered_set<int> us;
typedef map<int,int> mp;
//debugging
#ifndef ONLINE_JUDGE
#define debug1(a) cerr <<#a<<" " <<a << endl
#define debug2(a, b) cerr <<#a<<" "<< a << " "<<#b<<" " << b << endl
#define debug3(a, b, c) cerr <<#a<<" "<<a << " "<<#b<<" " << b << " "<<#c<<" " << c << endl
#define debug4(a, b, c, d) cerr << #a<<" "<<a << " " <<#b<<" "<< b << " "<<#c<<" " << c << " "<<#d<<" "<< d << endl
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#define debug2(x,y)
#define debug3(x,y,z)
#define debug4(x,y,z,a)
#endif
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(multimap <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
//Constants
const long double pi= 3.141592653589793238;
const int INF= 1e18;
const int mod=1e9+7;
//MATHEMATICAL FUNCTIONS
int gcd(int a, int b){if (b == 0)return a;return gcd(b, a % b);} //gcd
int lcm(int a, int b){return (a/gcd(a,b)*b);} //lcm
//sieve
vector<int> sieve(int n) {int*arr = new int[n + 1](); vector<int> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
//binary exponentation
int expo(int a, int b, int mod) {int res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
//CHECK
bool isprime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
bool ispoweroftwo(int n){if(n==0)return false;return (ceil(log2(n)) == floor(log2(n)));}
bool isperfectsquare(int x){if (x >= 0) {int sr = sqrt(x);return (sr * sr == x);}return false;}
int ceils(int x, int y) {return x / y + (x % y > 0);}
// Operator overloads
template<typename T1, typename T2> // cin >> pair<T1, T2>
istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.first >> p.second); }
template<typename T> // cin >> vector<T>
istream& operator>>(istream &istream, vector<T> &v){for (auto &it : v)cin >> it;return istream;}
template<typename T1, typename T2> // cout << pair<T1, T2>
ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.first << " " << p.second); }
template<typename T> // cout << vector<T>
ostream& operator<<(ostream &ostream, const vector<T> &c) { for (auto &it : c) cout << it << " "; return ostream; }
//USEFUL
void printarr(vi arr, int n){FOR(i,n) cout << arr[i] << " ";cout << "\n";}
void solve(){
int n,m,i,j;
cin>>n;
map<int,int>mpp;
for(int i=0;i<n;i++){
int a;
cin>>a;
mpp[a-i]+=a;
}
int ans=0;
for(auto val:mpp){
ans=max(ans,val.second);
}
cout<<ans<<endl;
}
int32_t main()
{
fast;
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t;
t=1;
//cin>>t;
while(t--){
// cout<<t;
solve();
}
return 0;
}
| cpp |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102. | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | // LUOGU_RID: 102594414
#include <bits/stdc++.h>
#define IOS std::ios::sync_with_stdio(false);std::cin.tie(0);std::cout.tie(0);
#define endl '\n'
using ll = long long;
#define int long long
using pll = std::pair<int, int>;
using namespace std;
signed main()
{
//#ifdef LOCAL
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
//#endif
IOS;
int n;
cin >> n;
vector<int>a(n + 7), b(n + 7);
for (int i = 1;i <= n;++i)cin >> a[i];
auto calc = [&](int L, int R) ->bool {
if (L > R) return 0;
ll ret = 0;
for (int i = n, l = 1, r = 1; i; i--) {
while (l <= n && b[i] + b[l] < L) ++l;
while (r <= n && b[i] + b[r] <= R) ++r;
ret += r - l - (l <= i && i < r);
}
return (ret >> 1) & 1;
};
int ans = 0;
for (int k = 0;k <= 26;++k) {
for (int i = 1;i <= n;++i) {
b[i] = a[i] & ((1 << (k + 1) ) - 1);
}
sort(&b[1], &b[1 + n]);
int g = (calc(1 << k, (1 << (k + 1)) - 1) ^ calc(3 << k, (1 << (k + 2)) - 2));
ans |= (g << k);
}
cout << ans << '\n';
return 0;
} | cpp |
1307 | F | F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n) — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105) — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi) — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below. | [
"dfs and similar",
"dsu",
"trees"
] | /* Author: izhang
* Time: 03-17-2022 02:04:59
**/
#include <bits/stdc++.h>
using namespace std;
#if defined LOCAL || defined DEBUG
#include <debug.h>
#else
struct dbg {
template<class c>
dbg &operator<<(const c &) { return *this; }
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#endif
//#define DEBUG
void setIO(const string &name) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin.exceptions(istream::failbit);
#ifdef LOCAL
freopen(("in" + name + ".txt").c_str(), "r", stdin);
freopen("out.txt", "w", stdout);
freopen("out.txt", "w", stderr);
#endif
}
const int inf = 0x3f3f3f3f, mod = 1e9 + 7, maxn = 4e5 + 5, maxs = 20;
const long long INFL = 0x3f3f3f3f3f3f3f3f;
vector<int> tmp_adj[maxn], adj[maxn];
int dist[maxn];
int par[maxn], owner[maxn], dsu_depth[maxn];
int get(int x) {
return par[x] == x ? x : par[x] = get(par[x]);
}
bool merge(int x, int y) {
int xroot = get(x), yroot = get(y);
if (dsu_depth[xroot] > dsu_depth[yroot]) {
swap(xroot, yroot);
}
if (xroot != yroot) {
par[xroot] = yroot;
dsu_depth[yroot] = max(dsu_depth[yroot], dsu_depth[xroot] + 1);
return true;
}
return false;
}
bool same(int x, int y) {
return get(x) == get(y);
}
int up[maxn][maxs], depth[maxn], n;
int jmp(int x, int d) {
for (int i = 0; i < maxs; i++) {
if ((d >> i) & 1) {
x = up[x][i];
}
}
return x;
}
int lca(int x, int y) {
if (depth[x] < depth[y]) {
swap(x, y);
}
x = jmp(x, depth[x] - depth[y]);
if (x == y) {
return x;
}
for (int i = maxs - 1; i >= 0; --i) {
int new_x = up[x][i], new_y = up[y][i];
if (new_x != new_y) {
x = new_x, y = new_y;
}
}
return up[x][0];
}
int get_dist(int x, int y) {
int l = lca(x, y);
return depth[x] - depth[l] + depth[y] - depth[l];
}
void dfs(int c = 0, int p = -1, int d = 0) {
up[c][0] = p;
depth[c] = d;
for (auto &i : adj[c]) {
if (i != p) {
dfs(i, c, d + 1);
}
}
}
void build() {
for (int i = 1; i < maxs; ++i) {
for (int j = 0; j < n; ++j) {
if (up[j][i - 1] == -1) {
up[j][i] = -1;
} else {
up[j][i] = up[up[j][i - 1]][i - 1];
}
}
}
}
void test_case() {
int k, r;
cin >> n >> k >> r;
for (int i = 0; i < n - 1; ++i) {
int node1, node2;
cin >> node1 >> node2;
--node1, --node2;
tmp_adj[node1].push_back(node2);
tmp_adj[node2].push_back(node1);
}
int cur_node = n;
for (int i = 0; i < n; ++i) {
for (auto &j : tmp_adj[i]) {
if (j > i) {
adj[i].push_back(cur_node);
adj[cur_node].push_back(i);
adj[cur_node].push_back(j);
adj[j].push_back(cur_node);
++cur_node;
}
}
}
n = cur_node;
dbg() << n;
for (int i = 0; i < n; ++i) {
par[i] = i;
}
vector<int> stops(r);
for (int i = 0; i < r; ++i) {
cin >> stops[i];
--stops[i];
}
memset(dist, 0x3f, sizeof(dist));
memset(owner, -1, sizeof(owner));
for (auto &i : stops) {
queue<int> q;
q.push(i);
if (owner[i] != -1) {
merge(i, owner[i]);
}
dist[i] = 0;
owner[i] = i;
while (!q.empty()) {
int cur = q.front();
q.pop();
for (auto &j : adj[cur]) {
if (owner[j] != -1 && owner[j] != i) {
merge(owner[j], cur);
}
if (dist[j] > dist[cur] + 1) {
dist[j] = dist[cur] + 1;
owner[j] = i;
merge(cur, j);
if (dist[j] < k) {
q.push(j);
}
}
}
}
}
for (int i = 0; i < n; ++i) {
dbg() << i << " " << get(i);
}
dfs();
build();
int que;
cin >> que;
while (que--) {
int a, b;
cin >> a >> b;
--a, --b;
if (get_dist(a, b) <= 2 * k) {
cout << "YES"
<< "\n";
continue;
}
int l = lca(a, b);
if (depth[a] > depth[b]) {
swap(a, b);
}
if (get_dist(a, l) < k) {
int cur = k - (depth[a] - depth[l]);
a = l;
a = jmp(b, (depth[b] - depth[l]) - cur);
} else {
a = jmp(a, k);
}
b = jmp(b, k);
cout << (get(a) == get(b) ? "YES" : "NO") << "\n";
}
}
int main() {
setIO("1");
int test_case_number = 1;
while (test_case_number--) {
test_case();
}
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"
] | #include<bits/stdc++.h>
using namespace std;
const int N=2e5+10,M=N*2;
struct E {
int v,next;
} e[M];
int n,m,k,u,v,p[N],len,h[N],d1[N],d2[N];
void add(int u,int v) {
e[++len].v=v;
e[len].next=h[u];
h[u]=len;
}
void bfs(int d[],int u) {
queue<int>q;
q.push(u);
memset(d,-1,sizeof(d1));
d[u]=0;
while(!q.empty()) {
u=q.front();
q.pop();
for(int j=h[u]; j; j=e[j].next) {
int v=e[j].v;
if(d[v]==-1)d[v]=d[u]+1,q.push(v);
}
}
}
bool cmp(int u,int v){
return (d1[u]-d2[u])<(d1[v]-d2[v]);
}
int main() {
cin>>n>>m>>k;
for(int i=1;i<=k;i++)cin>>p[i];
for(int i=1;i<=m;i++){
cin>>u>>v;
add(u,v);
add(v,u);
}
bfs(d1,1);
bfs(d2,n);
sort(p+1,p+1+k,cmp);
int ans=0,mx=-1e9;
for(int i=1;i<=k;i++){
v=p[i];
ans=max(ans,mx+d2[v]);
mx=max(mx,d1[v]);
}
cout<<min(ans+1,d1[n]);
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>
#define fi first
#define se second
#define mod 1000000007
#define ll long long
#define ull unsigned long long
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
void IO(string name)
{
ios_base::sync_with_stdio(0);
cin.tie(0);
if(name.size())
{
freopen((name+".in").c_str(), "r", stdin);
freopen((name+".out").c_str(), "w", stdout);
}
}
void solve()
{
int n, d;
cin >> n >> d;
vector<int> par(n + 1, -1);
vector<int> depth(n + 1, 0);
vector<int> cnum(n + 1, 0);
par[0] = 0;
int curr = 0;
for (int i = 1; i <= n; i++) {
int a = 2 * i;
int b = 2 * i + 1;
if (a <= n) {
par[a] = i;
depth[a] = depth[i] + 1;
cnum[i]++;
curr += depth[a];
}
if (b <= n) {
par[b] = i;
depth[b] = depth[i] + 1;
cnum[i]++;
curr += depth[b];
}
}
if (d < curr || d > n * (n - 1) / 2) {
cout << "NO\n";
return;
}
vector<set<int>> available(n + 1);
for (int i = 1; i <= n; i++) {
if (cnum[i] < 2) {
available[depth[i]].insert(i);
}
}
while(curr < d) {
for (int i = 2; i <= n; i++) {
if (cnum[i] == 0 && available[depth[i]].size() > 1) {
int dd = depth[i];
available[dd].erase(i);
int x = *available[dd].begin();
cnum[par[i]]--;
available[depth[par[i]]].insert(par[i]);
par[i] = x;
cnum[x]++;
if (cnum[x] == 2) available[dd].erase(x);
depth[i]++;
available[dd + 1].insert(i);
curr++;
break;
}
}
}
cout << "YES\n";
for (int i = 2; i <= n; i++) cout << par[i] << " \n"[i == n];
}
int main()
{
IO("");
int t = 1;
cin >> t;
while(t--)
{
solve();
}
}
| cpp |
1292 | D | D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3
2 1 4
OutputCopy5
InputCopy4
3 1 4 4
OutputCopy6
InputCopy4
3 1 4 1
OutputCopy6
InputCopy5
3 1 4 1 5
OutputCopy11
NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66. | [
"dp",
"graphs",
"greedy",
"math",
"number theory",
"trees"
] | #include<bits/stdc++.h>
#define ull unsigned long long
using namespace std;
int const m=5000,M=10010;bool vis[M];vector<int> g[M],h[M];map<ull,int> mp;long long dp[M];
int i,j,n,x,v,tp,num,sum,Ans,Index,pri[670],cnt[M],c[M],d[M],head[M];queue<int> q;
struct node{
int dep=0,num,x[670];ull Hash;
node(){memset(x,0,sizeof(x));}
}stk[M<<1];
int read(){
int x=0;char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
return x;
}
void Addedge(int u,int v,int w){g[u].push_back(v);h[u].push_back(w);d[u]++;}
void addedge(int u,int v,int w){Addedge(u,v,w);Addedge(v,u,w);}
node lca(node a,node b){ node c;
for (int i=669;i>0;i--)
if (a.x[i]!=b.x[i]){
for (int j=i+1;j<670;j++)
c.x[j]=a.x[j];
c.x[i]=min(a.x[i],b.x[i]);
for (int j=1;j<670;j++)
c.dep+=c.x[j];
return c;
}
}
int dist(node a,node b){
for (int i=669;i>0;i--)
if (a.x[i]!=b.x[i]){
int res=abs(a.x[i]-b.x[i]);
for (int j=1;j<i;j++) res+=a.x[j]+b.x[j];
return res;
}
}
ull Hash(node a){int hsh=0;
for (int i=1;i<670;i++)
hsh=hsh*2333333+a.x[i];
if (!mp[hsh]) mp[hsh]=++Index;
return mp[hsh];
}
bool Cmp(node a,node b){
for (int i=1;i<670;i++)
if (a.x[i]!=b.x[i])
return 1;
return 0;
}
void ins(int x,int val){ node s;
for (int i=1;i<670;i++){
for (int j=x/pri[i];j;j/=pri[i])
s.x[i]+=j;
s.dep+=s.x[i];
} s.num=Hash(s);c[s.num]=val;
if (!tp) {stk[tp=1]=s;return ;}
node ance=lca(stk[tp],s);ance.num=Hash(ance);
if (!Cmp(ance,s)) ance.num=s.num;
while (tp>1&&ance.dep<stk[tp-1].dep)
addedge(stk[tp-1].num,stk[tp].num,dist(stk[tp-1],stk[tp])),tp--;
if (ance.dep<stk[tp].dep) addedge(ance.num,stk[tp].num,dist(ance,stk[tp])),tp--;
if (!tp||Cmp(stk[tp],ance)) stk[++tp]=ance; stk[++tp]=s;
}
int main(){
sum=n=read();
for (i=2;i<=m;i++){
if (!vis[i]) pri[++num]=i;
for (j=i<<1;j<=m;j+=i) vis[j]=1;
}
for (i=1;i<=n;i++) cnt[read()]++; cnt[1]+=cnt[0];
for (i=1;i<=m;i++) if (i==1||cnt[i]) ins(i,cnt[i]);
while (tp>1) addedge(stk[tp-1].num,stk[tp].num,dist(stk[tp-1],stk[tp])),tp--;
for (n=Index,i=1;i<=n;i++) vis[i]=0;
for (i=1;i<=n;i++)
if (d[i]==1)
q.push(i),vis[i]=1;
for (i=1;i<=n;i++)
while (!q.empty()){
x=q.front();q.pop();
if (c[x]>sum/2) {Ans=x;continue;}
for (i=0;i<g[x].size();i++){
c[v=g[x][i]]+=c[x];dp[v]+=dp[x]+1ll*c[x]*h[x][i];
if (!vis[v]&&--d[v]==1) q.push(v),vis[v]=1;
}
}
printf("%lld\n",dp[Ans]);
return 0;
} | 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>
#define N 4010
using namespace std;
int n, m, l[N], s[N], c[N], f[N][N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for(int i = n; i >= 1; i--)
cin >> l[i];
for(int i = n; i >= 1; i--)
cin>> s[i];
m += n;
for(int i = 1; i <= m; i++)
cin >> c[i];
memset(f, 0xcf, sizeof f);
for(int i = 0; i <= m; i++)
f[i][0] = 0;
for(int i = 1; i <= n; i++) {
for(int j = n; j >= 1; j--)
f[l[i]][j] = max(f[l[i]][j], f[l[i]][j - 1] - s[i] + c[l[i]]);
for(int j = 0; j <= m - l[i]; j++) {
for(int k = 0; k <= n >> j; k++)
f[l[i] + j + 1][k >> 1] = max(f[l[i] + j + 1][k >> 1], f[l[i] + j][k] + (k >> 1) * c[l[i] + j + 1]);
}
}
cout << f[m][0] << endl;
}
| cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.